From 229b636f740d5a048e67e15df84e01cebea28920 Mon Sep 17 00:00:00 2001 From: luotao21 Date: Mon, 16 Nov 2026 21:28:53 +0800 Subject: [PATCH 01/14] =?UTF-8?q?feat:=20=E4=B8=BA=E8=B4=A6=E5=8F=B7?= =?UTF-8?q?=E8=AF=B7=E6=B1=82=E5=88=86=E6=95=A3=E4=BB=A3=E7=90=86=E5=B9=B6?= =?UTF-8?q?=E7=BA=A6=E6=9D=9F=E6=8E=88=E6=9D=83=E7=BB=B4=E6=8A=A4=E5=87=BA?= =?UTF-8?q?=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../admin/account_bps_proxy_data_test.go | 280 ++++++++++++ .../admin/account_codex_import_test.go | 34 ++ .../internal/handler/admin/account_data.go | 150 +++++- .../admin/account_openai_proxy_data_test.go | 98 ++++ .../handler/admin/openai_oauth_handler.go | 26 +- .../admin/openai_oauth_request_proxy_test.go | 214 +++++++++ ...openai_bps_request_proxy_admission_test.go | 154 +++++++ backend/internal/mihomo/bps_request.go | 204 +++++++++ .../mihomo/bps_request_integration.go | 14 + backend/internal/mihomo/bps_request_test.go | 209 +++++++++ backend/internal/mihomo/bps_warm_pool.go | 1 + backend/internal/mihomo/manager.go | 1 + backend/internal/pkg/openai/oauth.go | 1 + .../internal/repository/account_bps_warm.go | 6 +- .../account_bps_warm_integration_test.go | 6 + .../repository/astra_routing_upstream.go | 9 + backend/internal/repository/http_upstream.go | 10 + ...equest_proxy_transport_integration_test.go | 137 ++++++ backend/internal/repository/proxy_repo.go | 62 ++- .../repository/proxy_repo_integration_test.go | 148 ++++++ .../internal/repository/scheduler_cache.go | 7 +- .../scheduler_cache_bps_proxy_unit_test.go | 72 +++ backend/internal/service/admin_account.go | 42 +- ...count_request_proxy_upstream_merge_test.go | 95 ++++ ...min_account_upstream_billing_probe_test.go | 22 +- .../service/openai_auth_connection_oauth.go | 23 + .../openai_codex_models_request_proxy_test.go | 136 ++++++ .../service/openai_codex_models_service.go | 16 +- backend/internal/service/openai_excel_bps.go | 5 +- .../service/openai_excel_bps_images.go | 3 + .../service/openai_excel_bps_model_access.go | 2 +- .../service/openai_excel_bps_proxy_config.go | 179 ++++++++ .../openai_excel_bps_proxy_config_test.go | 187 ++++++++ .../service/openai_excel_bps_recovery.go | 2 +- ...xcel_bps_request_proxy_integration_test.go | 370 +++++++++++++++ .../openai_excel_bps_request_proxy_test.go | 35 ++ .../service/openai_excel_bps_transport.go | 56 ++- .../internal/service/openai_excel_bps_warm.go | 34 +- .../service/openai_excel_bps_warm_test.go | 17 + .../internal/service/openai_excel_oauth.go | 7 +- .../openai_gateway_chat_completions.go | 6 + .../service/openai_gateway_count_tokens.go | 12 + .../service/openai_gateway_forward.go | 14 +- .../service/openai_gateway_messages.go | 6 + .../service/openai_images_responses.go | 10 +- .../service/openai_maintenance_proxy.go | 64 +++ ...openai_maintenance_remaining_proxy_test.go | 220 +++++++++ ...nai_maintenance_task_request_proxy_test.go | 160 +++++++ .../service/openai_oauth_create_proxy.go | 101 +++++ .../openai_oauth_create_request_proxy_test.go | 118 +++++ .../internal/service/openai_oauth_reauth.go | 28 +- .../openai_oauth_reauth_request_proxy_test.go | 181 ++++++++ .../openai_oauth_request_proxy_test.go | 125 +++++ .../internal/service/openai_oauth_service.go | 33 +- .../service/openai_plugin_transport.go | 55 ++- .../internal/service/openai_proxy_routing.go | 141 ++++++ .../service/openai_proxy_routing_test.go | 214 +++++++++ .../service/openai_proxy_runtime_fallback.go | 4 +- .../openai_quota_request_proxy_test.go | 271 +++++++++++ .../internal/service/openai_quota_service.go | 12 +- .../internal/service/openai_request_proxy.go | 158 +++++++ .../openai_request_proxy_integration_test.go | 335 ++++++++++++++ .../service/openai_request_proxy_test.go | 125 +++++ .../internal/service/openai_session_export.go | 14 +- backend/internal/service/openai_siwc.go | 27 +- .../internal/service/openai_siwc_gateway.go | 9 +- ...nai_siwc_request_proxy_integration_test.go | 429 ++++++++++++++++++ .../internal/service/openai_totp_rotation.go | 9 +- .../service/openai_ws_forwarder_ingress.go | 3 + 69 files changed, 5886 insertions(+), 72 deletions(-) create mode 100644 backend/internal/handler/admin/account_bps_proxy_data_test.go create mode 100644 backend/internal/handler/admin/account_openai_proxy_data_test.go create mode 100644 backend/internal/handler/admin/openai_oauth_request_proxy_test.go create mode 100644 backend/internal/handler/openai_bps_request_proxy_admission_test.go create mode 100644 backend/internal/mihomo/bps_request.go create mode 100644 backend/internal/mihomo/bps_request_integration.go create mode 100644 backend/internal/mihomo/bps_request_test.go create mode 100644 backend/internal/repository/openai_request_proxy_transport_integration_test.go create mode 100644 backend/internal/repository/scheduler_cache_bps_proxy_unit_test.go create mode 100644 backend/internal/service/admin_account_request_proxy_upstream_merge_test.go create mode 100644 backend/internal/service/openai_codex_models_request_proxy_test.go create mode 100644 backend/internal/service/openai_excel_bps_proxy_config.go create mode 100644 backend/internal/service/openai_excel_bps_proxy_config_test.go create mode 100644 backend/internal/service/openai_excel_bps_request_proxy_integration_test.go create mode 100644 backend/internal/service/openai_excel_bps_request_proxy_test.go create mode 100644 backend/internal/service/openai_maintenance_proxy.go create mode 100644 backend/internal/service/openai_maintenance_remaining_proxy_test.go create mode 100644 backend/internal/service/openai_maintenance_task_request_proxy_test.go create mode 100644 backend/internal/service/openai_oauth_create_proxy.go create mode 100644 backend/internal/service/openai_oauth_create_request_proxy_test.go create mode 100644 backend/internal/service/openai_oauth_reauth_request_proxy_test.go create mode 100644 backend/internal/service/openai_oauth_request_proxy_test.go create mode 100644 backend/internal/service/openai_proxy_routing.go create mode 100644 backend/internal/service/openai_proxy_routing_test.go create mode 100644 backend/internal/service/openai_quota_request_proxy_test.go create mode 100644 backend/internal/service/openai_request_proxy.go create mode 100644 backend/internal/service/openai_request_proxy_integration_test.go create mode 100644 backend/internal/service/openai_request_proxy_test.go create mode 100644 backend/internal/service/openai_siwc_request_proxy_integration_test.go diff --git a/backend/internal/handler/admin/account_bps_proxy_data_test.go b/backend/internal/handler/admin/account_bps_proxy_data_test.go new file mode 100644 index 000000000000..1ecfafc79628 --- /dev/null +++ b/backend/internal/handler/admin/account_bps_proxy_data_test.go @@ -0,0 +1,280 @@ +package admin + +import ( + "bytes" + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/stretchr/testify/require" +) + +func TestAccountDataBPSRequestProxyPortableRoundTrip(t *testing.T) { + router, svc := setupAccountDataRouter() + svc.proxies = []service.Proxy{ + {ID: 11, Name: "exit-one", Protocol: "http", Host: "192.0.2.11", Port: 8080, Status: service.StatusActive}, + {ID: 22, Name: "exit-two", Protocol: "http", Host: "192.0.2.22", Port: 8080, Status: service.StatusActive}, + } + svc.accounts = []service.Account{{ID: 1, Name: "bps", Platform: service.PlatformOpenAI, Type: service.AccountTypeOAuth, Credentials: map[string]any{"access_token": "fixture"}, Extra: map[string]any{"openai_excel_bps": true, "openai_excel_bps_proxy_mode": "request", "openai_excel_bps_proxy_ids": []int64{11, 22}}}} + rec := httptest.NewRecorder() + router.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/api/v1/admin/accounts/data", nil)) + require.Equal(t, http.StatusOK, rec.Code) + var envelope struct { + Data map[string]any `json:"data"` + } + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &envelope)) + proxies := envelope.Data["proxies"].([]any) + require.Len(t, proxies, 2) + account := envelope.Data["accounts"].([]any)[0].(map[string]any) + require.NotContains(t, account["extra"], "openai_excel_bps_proxy_ids") + require.Equal(t, []any{buildBPSProxyKey("http", "192.0.2.11", 8080, "", ""), buildBPSProxyKey("http", "192.0.2.22", 8080, "", "")}, account["bps_proxy_keys"]) + // The same exits have different IDs in the destination database. + svc.proxies[0].ID = 101 + svc.proxies[1].ID = 202 + body, err := json.Marshal(map[string]any{"data": envelope.Data, "skip_default_group_bind": true}) + require.NoError(t, err) + rec = httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, "/api/v1/admin/accounts/data", bytes.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + router.ServeHTTP(rec, req) + require.Equal(t, http.StatusOK, rec.Code) + require.Len(t, svc.createdAccounts, 1) + restored := &service.Account{Extra: svc.createdAccounts[0].Extra} + require.Equal(t, []int64{101, 202}, restored.ExcelBPSRequestProxyIDs()) +} + +func TestAccountDataBPSRequestProxyRoundTripPreservesExactCredentialIdentity(t *testing.T) { + for _, tc := range []struct { + name, firstUsername, firstPassword, secondUsername, secondPassword string + }{ + {name: "delimiter", firstUsername: "a|b", firstPassword: "c", secondUsername: "a", secondPassword: "b|c"}, + {name: "username whitespace", firstUsername: " user ", firstPassword: "pass", secondUsername: "user", secondPassword: "pass"}, + {name: "password whitespace", firstUsername: "user", firstPassword: " pass ", secondUsername: "user", secondPassword: "pass"}, + } { + t.Run(tc.name, func(t *testing.T) { + router, svc := setupAccountDataRouter() + svc.proxies = []service.Proxy{ + {ID: 11, Name: "first", Protocol: "http", Host: "192.0.2.11", Port: 8080, Username: tc.firstUsername, Password: tc.firstPassword, Status: service.StatusActive}, + {ID: 22, Name: "second", Protocol: "http", Host: "192.0.2.11", Port: 8080, Username: tc.secondUsername, Password: tc.secondPassword, Status: service.StatusActive}, + } + for i, id := range []int64{11, 22} { + svc.accounts = append(svc.accounts, service.Account{ID: int64(i + 1), Name: svc.proxies[i].Name, Platform: service.PlatformOpenAI, Type: service.AccountTypeOAuth, Credentials: map[string]any{"access_token": "fixture"}, Extra: map[string]any{"openai_excel_bps": true, service.ExcelBPSProxyModeKey: service.ExcelBPSProxyModeRequest, service.ExcelBPSProxyIDsKey: []int64{id}}}) + } + rec := httptest.NewRecorder() + router.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/api/v1/admin/accounts/data", nil)) + require.Equal(t, http.StatusOK, rec.Code) + var exported struct { + Data DataPayload `json:"data"` + } + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &exported)) + svc.proxies[0].ID = 101 + svc.proxies[1].ID = 202 + body, err := json.Marshal(DataImportRequest{Data: exported.Data}) + require.NoError(t, err) + rec = httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, "/api/v1/admin/accounts/data", bytes.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + router.ServeHTTP(rec, req) + require.Equal(t, http.StatusOK, rec.Code) + require.Len(t, svc.createdAccounts, 2) + first := &service.Account{Extra: svc.createdAccounts[0].Extra} + second := &service.Account{Extra: svc.createdAccounts[1].Extra} + require.Equal(t, []int64{101}, first.ExcelBPSRequestProxyIDs(), "first credential identity must survive actual export/import") + require.Equal(t, []int64{202}, second.ExcelBPSRequestProxyIDs()) + require.NotEqual(t, exported.Data.Accounts[0].BPSProxyKeys, exported.Data.Accounts[1].BPSProxyKeys) + }) + } +} + +func TestAccountDataBPSRequestProxyRejectsSourceNumericIDs(t *testing.T) { + router, svc := setupAccountDataRouter() + svc.proxies = []service.Proxy{{ID: 11, Protocol: "http", Host: "192.0.2.99", Port: 8080}} + body := []byte(`{"data":{"proxies":[],"accounts":[{"name":"bps","platform":"openai","type":"oauth","credentials":{"access_token":"fixture"},"extra":{"openai_excel_bps_proxy_mode":"request","openai_excel_bps_proxy_ids":[11]}}]},"skip_default_group_bind":true}`) + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, "/api/v1/admin/accounts/data", bytes.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + router.ServeHTTP(rec, req) + require.Equal(t, http.StatusOK, rec.Code) + require.Empty(t, svc.createdAccounts) + var envelope struct { + Data DataImportResult `json:"data"` + } + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &envelope)) + require.Equal(t, 1, envelope.Data.AccountFailed) + require.Contains(t, envelope.Data.Errors[0].Message, "bps_proxy_keys") +} + +func TestAccountDataBPSRequestProxyRejectsLegacyCollisionAndPayloadAlias(t *testing.T) { + wanted := service.Proxy{ID: 11, Name: "wanted", Protocol: "http", Host: "192.0.2.11", Port: 8080, Username: "a|b", Password: "c", Status: service.StatusActive} + other := wanted + other.ID, other.Name, other.Username, other.Password = 202, "other", "a", "b|c" + identity := buildBPSProxyKey(wanted.Protocol, wanted.Host, wanted.Port, wanted.Username, wanted.Password) + legacy := buildProxyKey(wanted.Protocol, wanted.Host, wanted.Port, wanted.Username, wanted.Password) + for _, tc := range []struct { + name string + key string + proxyKey string + }{ + {name: "colliding destination only", key: identity, proxyKey: legacy}, + {name: "payload alias matching BPS identity", key: identity, proxyKey: identity}, + {name: "legacy ambiguous BPS identity", key: legacy, proxyKey: legacy}, + } { + t.Run(tc.name, func(t *testing.T) { + router, svc := setupAccountDataRouter() + svc.proxies = []service.Proxy{other} + payloadProxy := wanted + if tc.proxyKey == identity { + payloadProxy = other + } + data := DataPayload{ + Proxies: []DataProxy{{ProxyKey: tc.proxyKey, Name: payloadProxy.Name, Protocol: payloadProxy.Protocol, Host: payloadProxy.Host, Port: payloadProxy.Port, Username: payloadProxy.Username, Password: payloadProxy.Password, Status: payloadProxy.Status}}, + Accounts: []DataAccount{{Name: "bps", Platform: service.PlatformOpenAI, Type: service.AccountTypeOAuth, Credentials: map[string]any{"access_token": "fixture"}, Extra: map[string]any{service.ExcelBPSProxyModeKey: service.ExcelBPSProxyModeRequest}, BPSProxyKeys: []string{tc.key}}}, + } + body, err := json.Marshal(DataImportRequest{Data: data}) + require.NoError(t, err) + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, "/api/v1/admin/accounts/data", bytes.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + router.ServeHTTP(rec, req) + require.Equal(t, http.StatusOK, rec.Code) + require.Empty(t, svc.createdAccounts, "BPS import must not trust a legacy collision or payload alias") + var imported struct { + Data DataImportResult `json:"data"` + } + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &imported)) + require.Equal(t, 1, imported.Data.AccountFailed) + require.Contains(t, imported.Data.Errors[len(imported.Data.Errors)-1].Message, "not found") + }) + } +} + +// Return the actual created endpoint, rather than the generic stub's ID/name-only +// response, so this seam also exercises newly persisted destination identities. +type bpsProxyDataCreateService struct { + *stubAdminService +} + +func (s *bpsProxyDataCreateService) CreateProxy(_ context.Context, input *service.CreateProxyInput) (*service.Proxy, error) { + id := int64(400 + len(s.createdProxies)) + s.createdProxies = append(s.createdProxies, input) + p := service.Proxy{ID: id, Name: input.Name, Protocol: input.Protocol, Host: input.Host, Port: input.Port, Username: input.Username, Password: input.Password, Status: service.StatusActive} + s.proxies = append(s.proxies, p) + return &p, nil +} + +func TestAccountDataBPSRequestProxyBatchCollisionRejectsUncreatedIdentity(t *testing.T) { + _, stub := setupAccountDataRouter() + svc := &bpsProxyDataCreateService{stubAdminService: stub} + h := &AccountHandler{adminService: svc} + first := DataProxy{Name: "first", Protocol: "http", Host: "192.0.2.11", Port: 8080, Username: "a|b", Password: "c", Status: service.StatusActive} + second := first + second.Name, second.Username, second.Password = "second", "a", "b|c" + data := DataPayload{Proxies: []DataProxy{first, second}} + for _, p := range data.Proxies { + data.Accounts = append(data.Accounts, DataAccount{Name: p.Name, Platform: service.PlatformOpenAI, Type: service.AccountTypeOAuth, Credentials: map[string]any{"access_token": "fixture"}, Extra: map[string]any{service.ExcelBPSProxyModeKey: service.ExcelBPSProxyModeRequest}, BPSProxyKeys: []string{buildBPSProxyKey(p.Protocol, p.Host, p.Port, p.Username, p.Password)}}) + } + result, err := h.importData(context.Background(), DataImportRequest{Data: data}) + require.NoError(t, err) + require.Equal(t, 1, result.ProxyCreated) + require.Equal(t, 1, result.ProxyReused, "ordinary legacy proxy import semantics stay unchanged") + require.Equal(t, 1, result.AccountCreated) + require.Equal(t, 1, result.AccountFailed) + require.Len(t, svc.createdAccounts, 1) + restored := &service.Account{Extra: svc.createdAccounts[0].Extra} + require.Equal(t, []int64{400}, restored.ExcelBPSRequestProxyIDs()) + require.Equal(t, "second", result.Errors[0].Name) + require.Contains(t, result.Errors[0].Message, "not found") +} + +func TestAccountDataBPSRequestProxyExportWithoutProxiesCannotImportAsDirect(t *testing.T) { + router, svc := setupAccountDataRouter() + svc.accounts = []service.Account{{ID: 1, Name: "bps", Platform: service.PlatformOpenAI, Type: service.AccountTypeOAuth, Credentials: map[string]any{"access_token": "fixture"}, Extra: map[string]any{"openai_excel_bps": true, service.ExcelBPSProxyModeKey: service.ExcelBPSProxyModeRequest, service.ExcelBPSProxyIDsKey: []int64{11}}}} + rec := httptest.NewRecorder() + router.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/api/v1/admin/accounts/data?include_proxies=false", nil)) + require.Equal(t, http.StatusOK, rec.Code) + var exported struct { + Data DataPayload `json:"data"` + } + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &exported)) + require.Empty(t, exported.Data.Proxies) + require.Empty(t, exported.Data.Accounts[0].BPSProxyKeys) + require.NotContains(t, exported.Data.Accounts[0].Extra, service.ExcelBPSProxyIDsKey) + require.Equal(t, service.ExcelBPSProxyModeRequest, exported.Data.Accounts[0].Extra[service.ExcelBPSProxyModeKey]) + body, err := json.Marshal(DataImportRequest{Data: exported.Data}) + require.NoError(t, err) + rec = httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, "/api/v1/admin/accounts/data", bytes.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + router.ServeHTTP(rec, req) + require.Equal(t, http.StatusOK, rec.Code) + require.Empty(t, svc.createdAccounts) + var imported struct { + Data DataImportResult `json:"data"` + } + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &imported)) + require.Equal(t, 1, imported.Data.AccountFailed) + require.Contains(t, imported.Data.Errors[0].Message, "bps_proxy_keys") +} + +func TestAccountDataBPSRequestProxyRejectsMissingKey(t *testing.T) { + router, svc := setupAccountDataRouter() + svc.proxies = []service.Proxy{{ID: 11, Protocol: "http", Host: "192.0.2.11", Port: 8080}} + body := []byte(`{"data":{"proxies":[],"accounts":[{"name":"bps","platform":"openai","type":"oauth","credentials":{"access_token":"fixture"},"bps_proxy_keys":["http|192.0.2.11|8080||","http|192.0.2.22|8080||"],"extra":{"openai_excel_bps_proxy_mode":"request"}}]}}`) + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, "/api/v1/admin/accounts/data", bytes.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + router.ServeHTTP(rec, req) + require.Equal(t, http.StatusOK, rec.Code) + require.Empty(t, svc.createdAccounts) + var envelope struct { + Data DataImportResult `json:"data"` + } + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &envelope)) + require.Equal(t, 1, envelope.Data.AccountFailed) + require.Contains(t, envelope.Data.Errors[0].Message, "not found") +} + +func TestAccountDataBPSRequestProxyObserverCannotImportProxyKeys(t *testing.T) { + router, svc := setupAccountDataRouter() + body := []byte(`{"group_ids":[1],"data":{"proxies":[],"accounts":[{"name":"bps","platform":"openai","type":"oauth","credentials":{"access_token":"fixture"},"bps_proxy_keys":["http|192.0.2.11|8080||"],"extra":{"openai_excel_bps_proxy_mode":"request"}}]}}`) + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, "/api/v1/admin/accounts/data", bytes.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + req = req.WithContext(service.WithObserverScope(req.Context(), []int64{1})) + router.ServeHTTP(rec, req) + require.Equal(t, http.StatusForbidden, rec.Code) + require.Empty(t, svc.createdAccounts) +} + +func TestAccountDataBPSRequestProxyRejectsNonPortableMihomoExit(t *testing.T) { + t.Run("export source node", func(t *testing.T) { + router, svc := setupAccountDataRouter() + svc.proxies = []service.Proxy{{ID: 11, Name: "node-source", Protocol: "http", Host: "127.0.0.1", Port: 32000, MihomoNodeID: "source-node"}} + svc.accounts = []service.Account{{ID: 1, Name: "bps", Platform: service.PlatformOpenAI, Type: service.AccountTypeOAuth, Credentials: map[string]any{"access_token": "fixture"}, Extra: map[string]any{service.ExcelBPSProxyModeKey: service.ExcelBPSProxyModeRequest, service.ExcelBPSProxyIDsKey: []int64{11}}}} + rec := httptest.NewRecorder() + router.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/api/v1/admin/accounts/data", nil)) + require.Equal(t, http.StatusBadRequest, rec.Code) + require.Contains(t, rec.Body.String(), "Mihomo") + }) + t.Run("same port different destination node", func(t *testing.T) { + router, svc := setupAccountDataRouter() + svc.proxies = []service.Proxy{{ID: 101, Name: "node-destination", Protocol: "http", Host: "127.0.0.1", Port: 32000, MihomoNodeID: "different-destination-node"}} + body, err := json.Marshal(DataImportRequest{Data: DataPayload{Proxies: []DataProxy{}, Accounts: []DataAccount{{Name: "bps", Platform: service.PlatformOpenAI, Type: service.AccountTypeOAuth, Credentials: map[string]any{"access_token": "fixture"}, BPSProxyKeys: []string{buildBPSProxyKey("http", "127.0.0.1", 32000, "", "")}, Extra: map[string]any{service.ExcelBPSProxyModeKey: service.ExcelBPSProxyModeRequest}}}}}) + require.NoError(t, err) + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, "/api/v1/admin/accounts/data", bytes.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + router.ServeHTTP(rec, req) + require.Equal(t, http.StatusOK, rec.Code) + require.Empty(t, svc.createdAccounts) + var envelope struct { + Data DataImportResult `json:"data"` + } + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &envelope)) + require.Equal(t, 1, envelope.Data.AccountFailed) + require.Contains(t, envelope.Data.Errors[0].Message, "Mihomo") + }) +} diff --git a/backend/internal/handler/admin/account_codex_import_test.go b/backend/internal/handler/admin/account_codex_import_test.go index 777ec20a14ea..97c681a32b0d 100644 --- a/backend/internal/handler/admin/account_codex_import_test.go +++ b/backend/internal/handler/admin/account_codex_import_test.go @@ -5,6 +5,7 @@ import ( "encoding/base64" "encoding/json" "fmt" + "reflect" "strings" "testing" "time" @@ -1167,3 +1168,36 @@ func TestImportCodexSessionsAdmissionSourceOnlyInitializesNewAccounts(t *testing } } } + +func TestImportCodexSessionsPreservesOpenAIProxyConfiguration(t *testing.T) { + for _, twoFA := range []bool{false, true} { + svc := newCodexImportMemoryAdminService(nil) + h := NewAccountHandler(svc, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) + proxyID := int64(31) + req := CodexSessionImportRequest{ProxyID: &proxyID, InitializeOpenAITwoFA: twoFA, SkipDefaultGroupBind: boolPtr(true), Extra: map[string]any{service.OpenAIProxyModeKey: service.OpenAIProxyModeRequest, service.OpenAIProxyIDsKey: []int64{11, 22}}} + entries := []codexImportEntry{{Index: 1, Value: buildCodexRefreshImportValue(t, "proxy-workspace", "proxy-user", "fixture-refresh")}} + result, err := h.importCodexSessions(context.Background(), req, entries) + if err != nil || result.Created != 1 || result.Failed != 0 { + t.Fatalf("create import = %#v, %v", result, err) + } + created := svc.createdAccounts[0] + if created.ProxyID == nil || *created.ProxyID != proxyID { + t.Fatal("create lost original single proxy") + } + if created.Extra[service.OpenAIProxyModeKey] != service.OpenAIProxyModeRequest { + t.Fatal("create lost request mode") + } + account := &service.Account{Extra: created.Extra} + if !reflect.DeepEqual(account.OpenAIRequestProxyIDs(), []int64{11, 22}) { + t.Fatal("create lost selected group") + } + result, err = h.importCodexSessions(context.Background(), req, entries) + if err != nil || result.Updated != 1 || result.Failed != 0 { + t.Fatalf("update import = %#v, %v", result, err) + } + updated := svc.updatedAccounts[0].input + if updated.ProxyID == nil || *updated.ProxyID != proxyID || updated.Extra[service.OpenAIProxyModeKey] != service.OpenAIProxyModeRequest { + t.Fatal("update lost proxy configuration") + } + } +} diff --git a/backend/internal/handler/admin/account_data.go b/backend/internal/handler/admin/account_data.go index db3eebd8f9b7..84161ab27039 100644 --- a/backend/internal/handler/admin/account_data.go +++ b/backend/internal/handler/admin/account_data.go @@ -2,8 +2,11 @@ package admin import ( "context" + "crypto/sha256" + "encoding/json" "errors" "fmt" + "maps" "strconv" "strings" "time" @@ -65,6 +68,8 @@ type DataAccount struct { Credentials map[string]any `json:"credentials"` Extra map[string]any `json:"extra,omitempty"` ProxyKey *string `json:"proxy_key,omitempty"` + BPSProxyKeys []string `json:"bps_proxy_keys,omitempty"` + OpenAIProxyKeys []string `json:"openai_proxy_keys,omitempty"` Concurrency int `json:"concurrency"` Priority int `json:"priority"` RateMultiplier *float64 `json:"rate_multiplier,omitempty"` @@ -99,6 +104,13 @@ func buildProxyKey(protocol, host string, port int, username, password string) s return fmt.Sprintf("%s|%s|%d|%s|%s", strings.TrimSpace(protocol), strings.TrimSpace(host), port, strings.TrimSpace(username), strings.TrimSpace(password)) } +// BPS groups use an exact, unambiguous identity independent of legacy proxy_key +// aliases. Credentials are significant byte-for-byte, including whitespace. +func buildBPSProxyKey(protocol, host string, port int, username, password string) string { + tuple, _ := json.Marshal([5]string{protocol, host, strconv.Itoa(port), username, password}) + return fmt.Sprintf("bps-proxy-v1:%x", sha256.Sum256(tuple)) +} + func (h *AccountHandler) ExportData(c *gin.Context) { ctx := c.Request.Context() @@ -159,11 +171,17 @@ func (h *AccountHandler) ExportData(c *gin.Context) { } proxyKeyByID := make(map[int64]string, len(proxies)) + bpsProxyKeyByID := make(map[int64]string, len(proxies)) + nonPortableBPSProxyIDs := make(map[int64]bool) dataProxies := make([]DataProxy, 0, len(proxies)) for i := range proxies { p := proxies[i] key := buildProxyKey(p.Protocol, p.Host, p.Port, p.Username, p.Password) proxyKeyByID[p.ID] = key + bpsProxyKeyByID[p.ID] = buildBPSProxyKey(p.Protocol, p.Host, p.Port, p.Username, p.Password) + if strings.TrimSpace(p.MihomoNodeID) != "" { + nonPortableBPSProxyIDs[p.ID] = true + } var expiresAt *int64 if p.ExpiresAt != nil { @@ -193,6 +211,26 @@ func (h *AccountHandler) ExportData(c *gin.Context) { dataAccounts := make([]DataAccount, 0, len(accounts)) for i := range accounts { acc := accounts[i] + extra := maps.Clone(service.RedactOpenAICodexTicketExtra(acc.Extra)) + // Database IDs are local to an instance. Backups carry stable proxy keys + // so restoring into another database cannot silently select other exits. + delete(extra, service.ExcelBPSProxyIDsKey) + delete(extra, service.OpenAIProxyIDsKey) + var bpsProxyKeys []string + if includeProxies { + for _, id := range acc.ExcelBPSRequestProxyIDs() { + if nonPortableBPSProxyIDs[id] { + response.ErrorFrom(c, infraerrors.BadRequest("BPS_PROXY_NOT_PORTABLE", "BPS proxy groups containing Mihomo nodes require manual reconfiguration after restore; export without proxies")) + return + } + key, ok := bpsProxyKeyByID[id] + if !ok { + response.ErrorFrom(c, infraerrors.BadRequest("BPS_PROXY_NOT_FOUND", fmt.Sprintf("account %d selected BPS proxy %d not found", acc.ID, id))) + return + } + bpsProxyKeys = append(bpsProxyKeys, key) + } + } var proxyKey *string if acc.ProxyID != nil { if key, ok := proxyKeyByID[*acc.ProxyID]; ok { @@ -210,8 +248,9 @@ func (h *AccountHandler) ExportData(c *gin.Context) { Platform: acc.Platform, Type: acc.Type, Credentials: acc.Credentials, - Extra: service.RedactOpenAICodexTicketExtra(acc.Extra), + Extra: extra, ProxyKey: proxyKey, + BPSProxyKeys: bpsProxyKeys, Concurrency: acc.Concurrency, Priority: acc.Priority, RateMultiplier: acc.RateMultiplier, @@ -219,6 +258,10 @@ func (h *AccountHandler) ExportData(c *gin.Context) { ExpiresAt: expiresAt, AutoPauseOnExpired: &acc.AutoPauseOnExpired, }) + if _, explicit := acc.Extra[service.OpenAIProxyModeKey]; explicit { + dataAccounts[len(dataAccounts)-1].OpenAIProxyKeys = bpsProxyKeys + dataAccounts[len(dataAccounts)-1].BPSProxyKeys = nil + } } payload := DataPayload{ @@ -248,7 +291,7 @@ func (h *AccountHandler) ImportData(c *gin.Context) { return } for _, account := range req.Data.Accounts { - if account.ProxyKey != nil && *account.ProxyKey != "" { + if (account.ProxyKey != nil && *account.ProxyKey != "") || len(account.BPSProxyKeys) > 0 || len(account.OpenAIProxyKeys) > 0 { response.Forbidden(c, "Observers cannot import proxy credentials") return } @@ -280,12 +323,25 @@ func (h *AccountHandler) importData(ctx context.Context, req DataImportRequest) } proxyKeyToID := make(map[string]int64, len(existingProxies)) + bpsProxyKeyToID := make(map[string]int64, len(existingProxies)) + nonPortableBPSProxyKeys := make(map[string]bool) + // Populate BPS identities only from actual destination records. The legacy + // import may reuse a colliding/aliased proxy_key; it must not authorize a + // different credential identity for a BPS account. + registerBPSProxy := func(p service.Proxy) { + key := buildBPSProxyKey(p.Protocol, p.Host, p.Port, p.Username, p.Password) + bpsProxyKeyToID[key] = p.ID + if strings.TrimSpace(p.MihomoNodeID) != "" { + nonPortableBPSProxyKeys[key] = true + } + } // proxyNameToID 用于 backup_proxy_name 反查:DB 已有 + 本批次新建均会写入 proxyNameToID := make(map[string]int64, len(existingProxies)) for i := range existingProxies { p := existingProxies[i] key := buildProxyKey(p.Protocol, p.Host, p.Port, p.Username, p.Password) proxyKeyToID[key] = p.ID + registerBPSProxy(p) if p.Name != "" { proxyNameToID[p.Name] = p.ID } @@ -397,6 +453,7 @@ func (h *AccountHandler) importData(ctx context.Context, req DataImportRequest) continue } proxyKeyToID[key] = created.ID + registerBPSProxy(*created) // 把新建代理的 name 也加入反查表,供后续批内代理引用 if created.Name != "" { proxyNameToID[created.Name] = created.ID @@ -428,6 +485,11 @@ func (h *AccountHandler) importData(ctx context.Context, req DataImportRequest) for i := range dataPayload.Accounts { item := dataPayload.Accounts[i] + if err := remapDataAccountBPSProxies(&item, bpsProxyKeyToID, nonPortableBPSProxyKeys); err != nil { + result.AccountFailed++ + result.Errors = append(result.Errors, DataImportError{Kind: "account", Name: item.Name, Message: err.Error()}) + continue + } if err := validateDataAccount(item); err != nil { result.AccountFailed++ result.Errors = append(result.Errors, DataImportError{ @@ -599,18 +661,20 @@ func (h *AccountHandler) resolveExportProxies(ctx context.Context, accounts []se seen := make(map[int64]struct{}) ids := make([]int64, 0) for i := range accounts { - if accounts[i].ProxyID == nil { - continue + accountIDs := accounts[i].ExcelBPSRequestProxyIDs() + if accounts[i].ProxyID != nil { + accountIDs = append(accountIDs, *accounts[i].ProxyID) } - id := *accounts[i].ProxyID - if id <= 0 { - continue - } - if _, ok := seen[id]; ok { - continue + for _, id := range accountIDs { + if id <= 0 { + continue + } + if _, ok := seen[id]; ok { + continue + } + seen[id] = struct{}{} + ids = append(ids, id) } - seen[id] = struct{}{} - ids = append(ids, id) } if len(ids) == 0 { return []service.Proxy{}, nil @@ -619,6 +683,68 @@ func (h *AccountHandler) resolveExportProxies(ctx context.Context, accounts []se return h.adminService.GetProxiesByIDs(ctx, ids) } +func remapDataAccountBPSProxies(item *DataAccount, proxyKeyToID map[string]int64, nonPortableKeys map[string]bool) error { + if _, explicit := item.Extra[service.OpenAIProxyModeKey]; explicit { + item.Extra = maps.Clone(item.Extra) + delete(item.Extra, service.ExcelBPSProxyIDsKey) + _, sourceIDs := item.Extra[service.OpenAIProxyIDsKey] + if sourceIDs { + return errors.New("openai_proxy_keys is required instead of source numeric proxy IDs") + } + if len(item.OpenAIProxyKeys) == 0 { + if item.Extra[service.OpenAIProxyModeKey] == service.OpenAIProxyModeRequest { + return errors.New("openai_proxy_keys is required for OpenAI request proxy configuration") + } + return nil + } + ids, err := remapDataProxyGroupKeys(item.OpenAIProxyKeys, proxyKeyToID, nonPortableKeys, "openai_proxy_keys") + if err != nil { + return err + } + item.Extra[service.OpenAIProxyIDsKey] = ids + return nil + } + if _, sourceIDs := item.Extra[service.OpenAIProxyIDsKey]; sourceIDs || len(item.OpenAIProxyKeys) > 0 { + return errors.New("openai_proxy_keys requires an explicit OpenAI proxy mode") + } + _, hasSourceIDs := item.Extra[service.ExcelBPSProxyIDsKey] + if len(item.BPSProxyKeys) == 0 { + if hasSourceIDs || item.Extra[service.ExcelBPSProxyModeKey] == service.ExcelBPSProxyModeRequest { + return errors.New("bps_proxy_keys is required for BPS request proxy configuration") + } + return nil + } + ids, err := remapDataProxyGroupKeys(item.BPSProxyKeys, proxyKeyToID, nonPortableKeys, "bps_proxy_keys") + if err != nil { + return err + } + item.Extra = maps.Clone(item.Extra) + if item.Extra == nil { + item.Extra = make(map[string]any) + } + item.Extra[service.ExcelBPSProxyIDsKey] = ids + return nil +} + +func remapDataProxyGroupKeys(keys []string, proxyKeyToID map[string]int64, nonPortableKeys map[string]bool, field string) ([]int64, error) { + ids := make([]int64, 0, len(keys)) + seen := make(map[int64]bool, len(keys)) + for _, key := range keys { + if nonPortableKeys[key] { + return nil, errors.New("proxy group maps to a local Mihomo node; manually reconfigure its exits") + } + id, ok := proxyKeyToID[key] + if !ok { + return nil, fmt.Errorf("%s contains a proxy that was not found", field) + } + if !seen[id] { + ids = append(ids, id) + seen[id] = true + } + } + return ids, nil +} + func parseAccountIDs(c *gin.Context) ([]int64, error) { values := c.QueryArray("ids") if len(values) == 0 { diff --git a/backend/internal/handler/admin/account_openai_proxy_data_test.go b/backend/internal/handler/admin/account_openai_proxy_data_test.go new file mode 100644 index 000000000000..8084c52378bc --- /dev/null +++ b/backend/internal/handler/admin/account_openai_proxy_data_test.go @@ -0,0 +1,98 @@ +package admin + +import ( + "bytes" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/stretchr/testify/require" +) + +func TestAccountDataOpenAIProxyPortableRoundTrip(t *testing.T) { + for _, mode := range []string{service.OpenAIProxyModeRequest, service.OpenAIProxyModeSingle} { + t.Run(mode, func(t *testing.T) { + router, svc := setupAccountDataRouter() + svc.proxies = []service.Proxy{{ID: 11, Name: "first", Protocol: "http", Host: "192.0.2.11", Port: 8080, Status: service.StatusActive}, {ID: 22, Name: "second", Protocol: "http", Host: "192.0.2.22", Port: 8080, Status: service.StatusActive}} + svc.accounts = []service.Account{{ID: 1, Name: "ordinary", Platform: service.PlatformOpenAI, Type: service.AccountTypeOAuth, Credentials: map[string]any{"access_token": "fixture"}, Extra: map[string]any{service.OpenAIProxyModeKey: mode, service.OpenAIProxyIDsKey: []int64{11, 22}, service.ExcelBPSProxyModeKey: service.ExcelBPSProxyModeRequest, service.ExcelBPSProxyIDsKey: []int64{99}}}} + rec := httptest.NewRecorder() + router.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/api/v1/admin/accounts/data", nil)) + require.Equal(t, http.StatusOK, rec.Code) + var exported struct { + Data DataPayload `json:"data"` + } + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &exported)) + require.NotContains(t, exported.Data.Accounts[0].Extra, service.OpenAIProxyIDsKey) + require.NotContains(t, exported.Data.Accounts[0].Extra, service.ExcelBPSProxyIDsKey) + require.Contains(t, rec.Body.String(), "openai_proxy_keys") + svc.proxies[0].ID, svc.proxies[1].ID = 101, 202 + body, err := json.Marshal(DataImportRequest{Data: exported.Data}) + require.NoError(t, err) + rec = httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, "/api/v1/admin/accounts/data", bytes.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + router.ServeHTTP(rec, req) + require.Equal(t, http.StatusOK, rec.Code) + require.Len(t, svc.createdAccounts, 1) + restored := &service.Account{Platform: service.PlatformOpenAI, Type: service.AccountTypeOAuth, Extra: svc.createdAccounts[0].Extra} + require.Equal(t, []int64{101, 202}, restored.OpenAIRequestProxyIDs()) + require.Equal(t, mode == service.OpenAIProxyModeRequest, restored.OpenAIRequestProxyEnabled()) + }) + } +} + +func TestAccountDataOpenAIProxyRejectsNumericIDsAndMissingKeys(t *testing.T) { + for _, extra := range []map[string]any{ + {service.OpenAIProxyModeKey: service.OpenAIProxyModeRequest, service.OpenAIProxyIDsKey: []int64{11}}, + {service.OpenAIProxyModeKey: service.OpenAIProxyModeRequest}, + {service.OpenAIProxyModeKey: service.OpenAIProxyModeSingle, service.OpenAIProxyIDsKey: []int64{11}}, + } { + router, svc := setupAccountDataRouter() + body, err := json.Marshal(DataImportRequest{Data: DataPayload{Proxies: []DataProxy{}, Accounts: []DataAccount{{Name: "ordinary", Platform: service.PlatformOpenAI, Type: service.AccountTypeOAuth, Credentials: map[string]any{"access_token": "fixture"}, Extra: extra}}}}) + require.NoError(t, err) + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, "/api/v1/admin/accounts/data", bytes.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + router.ServeHTTP(rec, req) + require.Equal(t, http.StatusOK, rec.Code) + require.Empty(t, svc.createdAccounts) + require.Contains(t, rec.Body.String(), "openai_proxy_keys") + } +} + +func TestAccountDataOpenAIProxyExportWithoutProxiesCannotImportAsDirect(t *testing.T) { + router, svc := setupAccountDataRouter() + svc.accounts = []service.Account{{ID: 1, Name: "ordinary", Platform: service.PlatformOpenAI, Type: service.AccountTypeOAuth, Credentials: map[string]any{"access_token": "fixture"}, Extra: map[string]any{service.OpenAIProxyModeKey: service.OpenAIProxyModeRequest, service.OpenAIProxyIDsKey: []int64{11}}}} + rec := httptest.NewRecorder() + router.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/api/v1/admin/accounts/data?include_proxies=false", nil)) + require.Equal(t, http.StatusOK, rec.Code) + var exported struct { + Data DataPayload `json:"data"` + } + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &exported)) + require.NotContains(t, exported.Data.Accounts[0].Extra, service.OpenAIProxyIDsKey) + require.Empty(t, exported.Data.Accounts[0].OpenAIProxyKeys) + body, err := json.Marshal(DataImportRequest{Data: exported.Data}) + require.NoError(t, err) + rec = httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, "/api/v1/admin/accounts/data", bytes.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + router.ServeHTTP(rec, req) + require.Equal(t, http.StatusOK, rec.Code) + require.Empty(t, svc.createdAccounts) + require.Contains(t, rec.Body.String(), "openai_proxy_keys") +} + +func TestAccountDataOpenAIProxyObserverCannotImportProxyKeys(t *testing.T) { + router, svc := setupAccountDataRouter() + body := []byte(`{"group_ids":[1],"data":{"proxies":[],"accounts":[{"name":"ordinary","platform":"openai","type":"oauth","credentials":{"access_token":"fixture"},"openai_proxy_keys":["fixture"],"extra":{"openai_proxy_mode":"request"}}]}}`) + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, "/api/v1/admin/accounts/data", bytes.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + req = req.WithContext(service.WithObserverScope(req.Context(), []int64{1})) + router.ServeHTTP(rec, req) + require.Equal(t, http.StatusForbidden, rec.Code) + require.Empty(t, svc.createdAccounts) +} diff --git a/backend/internal/handler/admin/openai_oauth_handler.go b/backend/internal/handler/admin/openai_oauth_handler.go index 1b40b04b8f8d..9812e9c1e1f0 100644 --- a/backend/internal/handler/admin/openai_oauth_handler.go +++ b/backend/internal/handler/admin/openai_oauth_handler.go @@ -107,9 +107,11 @@ func NewOpenAIOAuthHandler( // OpenAIGenerateAuthURLRequest represents the request for generating OpenAI auth URL type OpenAIGenerateAuthURLRequest struct { - ProxyID *int64 `json:"proxy_id"` - RedirectURI string `json:"redirect_uri"` - OAuthClient string `json:"oauth_client"` + ProxyID *int64 `json:"proxy_id"` + ProxyMode string `json:"proxy_mode"` + ProxyIDs []int64 `json:"proxy_ids"` + RedirectURI string `json:"redirect_uri"` + OAuthClient string `json:"oauth_client"` } // GenerateAuthURL generates OpenAI OAuth authorization URL @@ -123,9 +125,11 @@ func (h *OpenAIOAuthHandler) GenerateAuthURL(c *gin.Context) { } } - result, err := h.openaiOAuthService.GenerateAuthURL( + result, err := h.openaiOAuthService.GenerateAuthURLWithProxySettings( c.Request.Context(), req.ProxyID, + req.ProxyMode, + req.ProxyIDs, req.RedirectURI, oauthPlatformFromPath(c), req.OAuthClient, @@ -140,11 +144,13 @@ func (h *OpenAIOAuthHandler) GenerateAuthURL(c *gin.Context) { // OpenAIExchangeCodeRequest represents the request for exchanging OpenAI auth code type OpenAIExchangeCodeRequest struct { - SessionID string `json:"session_id" binding:"required"` - Code string `json:"code" binding:"required"` - State string `json:"state" binding:"required"` - RedirectURI string `json:"redirect_uri"` - ProxyID *int64 `json:"proxy_id"` + SessionID string `json:"session_id" binding:"required"` + Code string `json:"code" binding:"required"` + State string `json:"state" binding:"required"` + RedirectURI string `json:"redirect_uri"` + ProxyID *int64 `json:"proxy_id"` + ProxyMode string `json:"proxy_mode"` + ProxyIDs []int64 `json:"proxy_ids"` } // ExchangeCode exchanges OpenAI authorization code for tokens @@ -162,6 +168,8 @@ func (h *OpenAIOAuthHandler) ExchangeCode(c *gin.Context) { State: req.State, RedirectURI: req.RedirectURI, ProxyID: req.ProxyID, + ProxyMode: req.ProxyMode, + ProxyIDs: req.ProxyIDs, }) if err != nil { response.ErrorFrom(c, err) diff --git a/backend/internal/handler/admin/openai_oauth_request_proxy_test.go b/backend/internal/handler/admin/openai_oauth_request_proxy_test.go new file mode 100644 index 000000000000..e2361d55d605 --- /dev/null +++ b/backend/internal/handler/admin/openai_oauth_request_proxy_test.go @@ -0,0 +1,214 @@ +package admin + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/pkg/openai" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +type oauthHandlerRequestProxyRepo struct { + service.ProxyRepository + proxies map[int64]*service.Proxy +} + +func (r *oauthHandlerRequestProxyRepo) GetByID(_ context.Context, id int64) (*service.Proxy, error) { + if proxy := r.proxies[id]; proxy != nil { + return proxy, nil + } + return nil, errors.New("synthetic private proxy address") +} + +type oauthHandlerRequestProxyClient struct { + service.OpenAIOAuthClient + proxies []string +} + +func (c *oauthHandlerRequestProxyClient) ExchangeCode(_ context.Context, _, _, _, proxyURL, _ string) (*openai.TokenResponse, error) { + c.proxies = append(c.proxies, proxyURL) + return &openai.TokenResponse{AccessToken: "synthetic", ExpiresIn: 3600}, nil +} + +func TestOpenAIAdminRequestProxyAuthorizationKeepsExit(t *testing.T) { + for _, profile := range []string{"codex", "excel"} { + t.Run(profile, func(t *testing.T) { + repo := &oauthHandlerRequestProxyRepo{proxies: map[int64]*service.Proxy{ + 11: {ID: 11, Protocol: "http", Host: "192.0.2.11", Port: 8080, Status: service.StatusActive}, + 22: {ID: 22, Protocol: "http", Host: "192.0.2.22", Port: 8080, Status: service.StatusActive}, + }} + client := &oauthHandlerRequestProxyClient{} + svc := service.NewOpenAIOAuthService(repo, client) + defer svc.Stop() + handler := &OpenAIOAuthHandler{openaiOAuthService: svc} + router := gin.New() + router.POST("/generate-auth-url", handler.GenerateAuthURL) + router.POST("/exchange-code", handler.ExchangeCode) + post := func(path, body string) *httptest.ResponseRecorder { + w := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + router.ServeHTTP(w, req) + return w + } + w := post("/generate-auth-url", `{"oauth_client":"`+profile+`","proxy_mode":"request","proxy_ids":[99,11,22]}`) + require.Equal(t, http.StatusOK, w.Code) + var generated struct { + Data service.OpenAIAuthURLResult `json:"data"` + } + require.NoError(t, json.Unmarshal(w.Body.Bytes(), &generated)) + require.Equal(t, "request", generated.Data.ProxyMode) + require.Equal(t, int64(11), generated.Data.ProxyID) + authURL, err := url.Parse(generated.Data.AuthURL) + require.NoError(t, err) + body, err := json.Marshal(map[string]any{"session_id": generated.Data.SessionID, "code": "synthetic-code", "state": authURL.Query().Get("state"), "proxy_mode": "request", "proxy_ids": []int64{22, 11}, "proxy_id": 22}) + require.NoError(t, err) + w = post("/exchange-code", string(body)) + require.Equal(t, http.StatusOK, w.Code) + require.Equal(t, []string{repo.proxies[11].URL()}, client.proxies) + }) + } +} + +func TestOpenAIAdminRequestProxyAuthorizationRejectsInvalidSettings(t *testing.T) { + svc := service.NewOpenAIOAuthService(&oauthHandlerRequestProxyRepo{proxies: map[int64]*service.Proxy{}}, nil) + defer svc.Stop() + handler := &OpenAIOAuthHandler{openaiOAuthService: svc} + for _, body := range []string{`{"proxy_mode":"request","proxy_ids":[]}`, `{"proxy_mode":"request","proxy_ids":[99]}`, `{"proxy_mode":"request","proxy_ids":[-1]}`, `{"proxy_mode":"unknown","proxy_ids":[11]}`, `{"proxy_ids":[11]}`} { + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + c.Request = httptest.NewRequest(http.MethodPost, "/generate-auth-url", strings.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + handler.GenerateAuthURL(c) + require.GreaterOrEqual(t, w.Code, http.StatusBadRequest, body) + require.NotContains(t, w.Body.String(), "synthetic private proxy address") + } +} + +type oauthHandlerProxyFixture struct { + repo *oauthHandlerRequestProxyRepo + client *oauthHandlerRequestProxyClient + router *gin.Engine +} + +func newOAuthHandlerProxyFixture(t *testing.T) *oauthHandlerProxyFixture { + t.Helper() + f := &oauthHandlerProxyFixture{ + repo: &oauthHandlerRequestProxyRepo{proxies: map[int64]*service.Proxy{ + 11: {ID: 11, Protocol: "http", Host: "192.0.2.11", Port: 8080, Status: service.StatusActive}, + 22: {ID: 22, Protocol: "http", Host: "192.0.2.22", Port: 8080, Status: service.StatusActive}, + }}, + client: &oauthHandlerRequestProxyClient{}, + router: gin.New(), + } + svc := service.NewOpenAIOAuthService(f.repo, f.client) + t.Cleanup(svc.Stop) + handler := &OpenAIOAuthHandler{openaiOAuthService: svc} + f.router.POST("/generate-auth-url", handler.GenerateAuthURL) + f.router.POST("/exchange-code", handler.ExchangeCode) + return f +} + +func (f *oauthHandlerProxyFixture) post(t *testing.T, path string, body map[string]any) *httptest.ResponseRecorder { + t.Helper() + encoded, err := json.Marshal(body) + require.NoError(t, err) + w := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(string(encoded))) + req.Header.Set("Content-Type", "application/json") + f.router.ServeHTTP(w, req) + return w +} + +func (f *oauthHandlerProxyFixture) generate(t *testing.T, body map[string]any) (service.OpenAIAuthURLResult, map[string]any) { + t.Helper() + w := f.post(t, "/generate-auth-url", body) + require.Equal(t, http.StatusOK, w.Code, w.Body.String()) + var generated struct { + Data service.OpenAIAuthURLResult `json:"data"` + } + require.NoError(t, json.Unmarshal(w.Body.Bytes(), &generated)) + authURL, err := url.Parse(generated.Data.AuthURL) + require.NoError(t, err) + return generated.Data, map[string]any{"session_id": generated.Data.SessionID, "code": "synthetic-code", "state": authURL.Query().Get("state")} +} + +func TestOpenAIAdminSingleProxyAuthorizationKeepsCompatibility(t *testing.T) { + for _, mode := range []string{"", "single"} { + t.Run("mode="+mode, func(t *testing.T) { + f := newOAuthHandlerProxyFixture(t) + settings := map[string]any{"proxy_id": 11} + if mode != "" { + settings["proxy_mode"] = mode + } + generated, exchange := f.generate(t, settings) + require.Empty(t, generated.ProxyMode) + exchange["proxy_id"] = 22 + if mode != "" { + exchange["proxy_mode"] = mode + } + w := f.post(t, "/exchange-code", exchange) + require.Equal(t, http.StatusOK, w.Code, w.Body.String()) + require.Equal(t, []string{"http://192.0.2.22:8080"}, f.client.proxies) + }) + } +} + +func TestOpenAIAdminRequestProxyAuthorizationRejectsChangedSession(t *testing.T) { + for _, change := range []string{"request to single", "single to request", "URL changed"} { + t.Run(change, func(t *testing.T) { + f := newOAuthHandlerProxyFixture(t) + settings := map[string]any{"proxy_mode": "request", "proxy_ids": []int64{11, 22}} + if change == "single to request" { + settings = map[string]any{"proxy_mode": "single", "proxy_id": 11} + } + _, exchange := f.generate(t, settings) + exchange["proxy_mode"] = "request" + exchange["proxy_ids"] = []int64{11, 22} + if change == "request to single" { + exchange["proxy_mode"] = "single" + delete(exchange, "proxy_ids") + } + if change == "URL changed" { + f.repo.proxies[11].Host = "192.0.2.99" + } + w := f.post(t, "/exchange-code", exchange) + require.GreaterOrEqual(t, w.Code, http.StatusBadRequest) + require.Empty(t, f.client.proxies) + require.NotContains(t, w.Body.String(), "192.0.2") + if change == "single to request" { + exchange["proxy_mode"] = "single" + delete(exchange, "proxy_ids") + } else { + exchange["proxy_mode"] = "request" + exchange["proxy_ids"] = []int64{22, 11} + } + f.repo.proxies[11].Host = "192.0.2.11" + w = f.post(t, "/exchange-code", exchange) + require.Equal(t, http.StatusOK, w.Code, "rejected callbacks must preserve the authorization session: %s", w.Body.String()) + require.Equal(t, []string{"http://192.0.2.11:8080"}, f.client.proxies) + }) + } +} + +func TestOpenAIAdminRequestProxyAuthorizationSkipsExpiredMember(t *testing.T) { + f := newOAuthHandlerProxyFixture(t) + expired := time.Now().Add(-time.Minute) + f.repo.proxies[11].ExpiresAt = &expired + generated, exchange := f.generate(t, map[string]any{"proxy_mode": "request", "proxy_ids": []int64{11, 22}}) + require.Equal(t, int64(22), generated.ProxyID) + exchange["proxy_mode"] = "request" + exchange["proxy_ids"] = []int64{11, 22} + w := f.post(t, "/exchange-code", exchange) + require.Equal(t, http.StatusOK, w.Code, w.Body.String()) + require.Equal(t, []string{"http://192.0.2.22:8080"}, f.client.proxies) +} diff --git a/backend/internal/handler/openai_bps_request_proxy_admission_test.go b/backend/internal/handler/openai_bps_request_proxy_admission_test.go new file mode 100644 index 000000000000..893b0e6dc83d --- /dev/null +++ b/backend/internal/handler/openai_bps_request_proxy_admission_test.go @@ -0,0 +1,154 @@ +//go:build unit + +package handler + +import ( + "context" + "net" + "net/http" + "net/http/httptest" + "os" + "strings" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/repository" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/alicebob/miniredis/v2" + "github.com/gin-gonic/gin" + "github.com/redis/go-redis/v9" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" + "go.uber.org/zap" +) + +// Both handlers have independent ConcurrencyService/cache/Redis clients. The +// shared account occupancy is the production cache's Lua authority, never a +// test counter or a per-proxy limit. This stops at handler admission; forwarding +// and actual proxy distribution are covered by the transport acceptance tests. +func TestBPSRequestProxyAdmissionRetainsAccountConcurrency(t *testing.T) { + gin.SetMode(gin.TestMode) + t.Run("production_cache_with_miniredis", func(t *testing.T) { + server := miniredis.RunT(t) + testBPSRequestProxyAccountAdmission(t, server.Addr(), false) + }) + t.Run("production_cache_with_real_redis", func(t *testing.T) { + addr := os.Getenv("BPS_REQUEST_PROXY_REDIS_ADDR") + if addr == "" { + t.Skip("set BPS_REQUEST_PROXY_REDIS_ADDR to an explicitly disposable loopback Redis for real-server evidence") + } + host, _, err := net.SplitHostPort(addr) + require.NoError(t, err) + require.Contains(t, []string{"127.0.0.1", "::1", "localhost"}, host, "the integration fixture must never address a non-loopback Redis") + testBPSRequestProxyAccountAdmission(t, addr, true) + }) +} + +func testBPSRequestProxyAccountAdmission(t *testing.T, addr string, realRedis bool) { + t.Helper() + var caches [2]service.ConcurrencyCache + var handlers [2]*OpenAIGatewayHandler + var connectionIDs [2]int64 + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + for node := range handlers { + // No application configuration, credentials, or FlushDB is used. Each + // case has a fresh positive account ID and releases only its own slots. + client := redis.NewClient(&redis.Options{Addr: addr, DB: 15, PoolSize: 1, MaxRetries: -1, ContextTimeoutEnabled: true}) + t.Cleanup(func() { require.NoError(t, client.Close()) }) + require.NoError(t, client.Ping(ctx).Err()) + if realRedis { + info, err := client.Info(ctx, "server").Result() + require.NoError(t, err) + require.True(t, strings.Contains(info, "redis_version:"), "the real-server case must not silently use miniredis") + connectionIDs[node], err = client.ClientID(ctx).Result() + require.NoError(t, err) + } + caches[node] = repository.NewConcurrencyCache(client, 1, 60) + handlers[node] = &OpenAIGatewayHandler{ + gatewayService: &service.OpenAIGatewayService{}, + concurrencyHelper: NewConcurrencyHelper(service.NewConcurrencyService(caches[node]), SSEPingFormatNone, 0), + } + } + if realRedis { + require.NotEqual(t, connectionIDs[0], connectionIDs[1], "the shared authority must be reached over independent Redis connections") + } + + account := &service.Account{ + ID: time.Now().UnixNano(), Platform: service.PlatformOpenAI, Type: service.AccountTypeOAuth, + Status: service.StatusActive, Schedulable: true, Concurrency: 6, + Extra: map[string]any{ + "openai_excel_bps": true, + service.ExcelBPSProxyModeKey: service.ExcelBPSProxyModeRequest, + service.ExcelBPSProxyIDsKey: []int64{11, 22, 33}, + }, + } + require.True(t, account.ExcelBPSRequestProxyEnabled(), "the admitted account must have request distribution enabled") + + assertOccupancy := func(want int) { + t.Helper() + for node, cache := range caches { + count, err := cache.GetAccountConcurrency(ctx, account.ID) + require.NoError(t, err) + require.Equal(t, want, count, "handler %d must observe the same account-wide occupancy", node) + } + } + acquire := func(node int, responses bool) (func(), openAISlotAcquireResult, *httptest.ResponseRecorder) { + t.Helper() + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil) + selection := &service.AccountSelectionResult{ + Account: account, + WaitPlan: &service.AccountWaitPlan{ + AccountID: account.ID, MaxConcurrency: account.Concurrency, + Timeout: 10 * time.Millisecond, MaxWaiting: 0, + }, + } + streamStarted := false + if responses { + release, result := handlers[node].acquireResponsesAccountSlot(c, nil, "", selection, false, &streamStarted, zap.NewNop()) + return release, result, recorder + } + release, result := handlers[node].acquireOpenAIAccountSlot(c, nil, "", selection, false, &streamStarted, zap.NewNop(), nil) + return release, result, recorder + } + + var releases []func() + t.Cleanup(func() { + for _, release := range releases { + if release != nil { + release() + } + } + }) + for request := 0; request < 6; request++ { + release, result, recorder := acquire(request%2, request%2 == 0) + require.Equal(t, openAISlotAcquireOK, result, "request %d must be admitted: %s", request+1, recorder.Body.String()) + require.NotNil(t, release) + releases = append(releases, release) + assertOccupancy(request + 1) + } + + for _, responses := range []bool{true, false} { + release, result, recorder := acquire(1, responses) + require.Equal(t, openAISlotAcquireFailed, result, "a seventh logical request must not gain capacity from the three configured proxies") + require.Nil(t, release) + require.Equal(t, http.StatusTooManyRequests, recorder.Code, recorder.Body.String()) + require.Equal(t, gatewayQueueFullCode, gjson.Get(recorder.Body.String(), "error.code").String()) + assertOccupancy(6) + } + + releases[0]() + releases[0]() // Handler release is idempotent. + assertOccupancy(5) + replacement, result, recorder := acquire(1, true) + require.Equal(t, openAISlotAcquireOK, result, recorder.Body.String()) + require.NotNil(t, replacement, "the other handler must observe capacity released by the first") + releases = append(releases, replacement) + assertOccupancy(6) + for _, release := range releases { + release() + } + assertOccupancy(0) +} diff --git a/backend/internal/mihomo/bps_request.go b/backend/internal/mihomo/bps_request.go new file mode 100644 index 000000000000..18ed9db822a8 --- /dev/null +++ b/backend/internal/mihomo/bps_request.go @@ -0,0 +1,204 @@ +package mihomo + +import ( + "context" + "sort" + "strings" + "sync" + "time" +) + +// Background membership refresh runs every 15 seconds. Allow one refresh +// window plus bounded account lookup/probe work, then fail closed on DB errors. +const BPSStaticRequestMembershipMaxAge = 30 * time.Second + +// BPSStaticProxy is a credential-bearing background snapshot. It must never be +// logged. Expiry is checked again on every acquisition, not just on refresh. +type BPSStaticProxy struct { + ID int64 + URL string + ExpiresAt *time.Time +} +type bpsRequestAccount struct { + active map[string]int + last string +} +type bpsRequestPool struct { + refreshedAt time.Time + records map[int64]BPSStaticProxy + groups map[int64][]int64 + accounts map[int64]*bpsRequestAccount + warmCursor int +} + +// SetBPSStaticProxyRecords refreshes the shared active membership once; account +// allowlists are applied during acquisition and cannot replace this pool. +func SetBPSStaticProxyRecords(records []BPSStaticProxy) { + next := make(map[int64]BPSStaticProxy, len(records)) + urls := make(map[string]string, len(records)) + for _, p := range records { + p.URL = strings.TrimSpace(p.URL) + if p.ID <= 0 || p.URL == "" { + continue + } + if p.ExpiresAt != nil { + expiry := *p.ExpiresAt + p.ExpiresAt = &expiry + } + next[p.ID] = p + urls[bpsStaticNodeKey(p.URL)] = p.URL + } + m := bpsStaticManager + m.bpsMu.Lock() + defer m.bpsMu.Unlock() + m.bpsRequests.records = next + m.bpsRequests.refreshedAt = time.Now() + m.bpsStatic = urls +} + +// SetBPSStaticRequestGroups registers background warming requirements before +// any user traffic. A removed configuration cannot alter an in-flight lease. +func SetBPSStaticRequestGroups(groups map[int64][]int64) { + next := make(map[int64][]int64, len(groups)) + for id, ids := range groups { + if id > 0 { + next[id] = append([]int64(nil), ids...) + } + } + m := bpsStaticManager + m.bpsMu.Lock() + defer m.bpsMu.Unlock() + m.bpsRequests.groups = next + for id, a := range m.bpsRequests.accounts { + if _, ok := next[id]; !ok && len(a.active) == 0 { + delete(m.bpsRequests.accounts, id) + } + } +} + +// AcquireBPSStaticRequestLease atomically chooses and reserves the least busy +// healthy selected exit for this account. Equal loads rotate fairly. It never +// binds a conversation, probes on the request path, or uses an unselected exit. +func AcquireBPSStaticRequestLease(ctx context.Context, accountID int64, proxyIDs []int64, excludedProxyURLs ...string) (*BPSLease, error) { + if err := ctx.Err(); err != nil { + return nil, err + } + m := bpsStaticManager + m.bpsMu.Lock() + defer m.bpsMu.Unlock() + excluded := make(map[string]bool, len(excludedProxyURLs)) + for _, raw := range excludedProxyURLs { + excluded[bpsStaticNodeKey(raw)] = true + } + now := time.Now() + if m.bpsRequests.refreshedAt.IsZero() || !now.Before(m.bpsRequests.refreshedAt.Add(BPSStaticRequestMembershipMaxAge)) { + return nil, bpsAcquisitionError(bpsSelectionError("selected_pool_stale", "selected BPS proxy membership requires a successful refresh"), 0) + } + nodes := make([]string, 0, len(proxyIDs)) + seen := map[string]bool{} + for _, id := range proxyIDs { + p, ok := m.bpsRequests.records[id] + if !ok || id <= 0 || (p.ExpiresAt != nil && !p.ExpiresAt.After(now)) { + continue + } + node := bpsStaticNodeKey(p.URL) + h := m.bpsHealthAtLocked(node, now) + if excluded[node] || seen[node] || m.bpsStatic[node] != p.URL || !now.Before(h.verifiedUntil) || m.bpsCoolingLocked(node, now) { + continue + } + seen[node] = true + nodes = append(nodes, node) + } + if accountID <= 0 || len(nodes) == 0 { + return nil, bpsAcquisitionError(bpsSelectionError("selected_pool_unavailable", "selected BPS proxies have no healthy exit"), 0) + } + sort.Strings(nodes) + if m.bpsRequests.accounts == nil { + m.bpsRequests.accounts = make(map[int64]*bpsRequestAccount) + } + a := m.bpsRequests.accounts[accountID] + if a == nil { + a = &bpsRequestAccount{active: make(map[string]int)} + m.bpsRequests.accounts[accountID] = a + } + start := sort.SearchStrings(nodes, a.last) + if start < len(nodes) && nodes[start] == a.last { + start++ + } + best := "" + load := int(^uint(0) >> 1) + for i := 0; i < len(nodes); i++ { + node := nodes[(start+i)%len(nodes)] + if a.active[node] < load { + best = node + load = a.active[node] + } + } + a.last = best + a.active[best]++ + var once sync.Once + release := func() { + once.Do(func() { + m.bpsMu.Lock() + defer m.bpsMu.Unlock() + a.active[best]-- + if a.active[best] == 0 { + delete(a.active, best) + } + // Keep the rotation cursor until the next background projection. A + // newly enabled account may send before that projection includes it. + // SetBPSStaticRequestGroups removes unconfigured idle accounts. + }) + } + return &BPSLease{ProxyURL: m.bpsStatic[best], manager: m, node: best, generation: m.bpsHealthAtLocked(best, now).generation, release: release}, nil +} + +// Warming selected subsets is independent of the old global warm target. A +// rotating cursor prevents large or unhealthy groups from starving other groups. +func (m *Manager) warmBPSRequestGroups(ctx context.Context) { + m.bpsWarmMu.Lock() + defer m.bpsWarmMu.Unlock() + m.bpsMu.Lock() + now := time.Now() + nodes := make([]string, 0) + seen := map[string]bool{} + for _, ids := range m.bpsRequests.groups { + for _, id := range ids { + p, ok := m.bpsRequests.records[id] + if !ok || (p.ExpiresAt != nil && !p.ExpiresAt.After(now)) { + continue + } + node := bpsStaticNodeKey(p.URL) + h := m.bpsHealthAtLocked(node, now) + if seen[node] || m.bpsCoolingLocked(node, now) || now.Add(30*time.Second).Before(h.verifiedUntil) { + continue + } + seen[node] = true + nodes = append(nodes, node) + } + } + sort.Strings(nodes) + start := 0 + if len(nodes) > 0 { + start = m.bpsRequests.warmCursor % len(nodes) + } + m.bpsMu.Unlock() + warmCtx, cancel := context.WithTimeout(context.WithValue(ctx, bpsWarmContextKey{}, true), 8*time.Second) + defer cancel() + for i := 0; i < len(nodes) && warmCtx.Err() == nil; i += bpsProbeParallelism { + var wg sync.WaitGroup + for j := i; j < min(i+bpsProbeParallelism, len(nodes)); j++ { + node := nodes[(start+j)%len(nodes)] + m.bpsMu.Lock() + proxy := m.bpsStatic[node] + m.bpsRequests.warmCursor = start + j + 1 + m.bpsMu.Unlock() + if proxy == "" { + continue + } + wg.Add(1) + go func() { defer wg.Done(); _ = m.checkBPSHealth(warmCtx, node, proxy, true) }() + } + wg.Wait() + } +} diff --git a/backend/internal/mihomo/bps_request_integration.go b/backend/internal/mihomo/bps_request_integration.go new file mode 100644 index 000000000000..302777afb5c5 --- /dev/null +++ b/backend/internal/mihomo/bps_request_integration.go @@ -0,0 +1,14 @@ +//go:build bps_request_integration + +package mihomo + +import "context" + +// InstallBPSRequestIntegrationProbe replaces only the external reachability +// probe in explicitly tagged local integration tests. The production build has +// no symbol or configuration that can bypass its verified HTTPS probe. +func InstallBPSRequestIntegrationProbe(probe func(context.Context, string) error) func() { + previous := bpsStaticManager + bpsStaticManager = &Manager{bpsStaticMode: true, bpsProbe: probe} + return func() { bpsStaticManager = previous } +} diff --git a/backend/internal/mihomo/bps_request_test.go b/backend/internal/mihomo/bps_request_test.go new file mode 100644 index 000000000000..f010cc2d5437 --- /dev/null +++ b/backend/internal/mihomo/bps_request_test.go @@ -0,0 +1,209 @@ +package mihomo + +import ( + "context" + "fmt" + "io" + "net/http" + "net/http/httptest" + "net/url" + "sync" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +// Real HTTP proxy endpoints observe the selected physical egress. The sole +// injected boundary is the external HTTPS health probe, never selection. +func TestBPSRequestPoolDistributesConcurrentRequestsThroughSelectedProxies(t *testing.T) { + bpsStaticTestPool(t, func(context.Context, string) error { return nil }) + var mu sync.Mutex + hits := map[int]int{} + records := make([]BPSStaticProxy, 0, 4) + for i := 1; i <= 4; i++ { + id := i + proxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + hits[id]++ + mu.Unlock() + _, _ = io.WriteString(w, "proxied") + })) + t.Cleanup(proxy.Close) + records = append(records, BPSStaticProxy{ID: int64(i), URL: proxy.URL}) + } + SetBPSStaticProxyRecords(records) + SetBPSStaticRequestGroups(map[int64][]int64{300: {1, 2, 3}}) + WarmBPSPools(t.Context(), 0, 1) + leases := make(chan *BPSLease, 6) + errs := make(chan error, 6) + var wg sync.WaitGroup + for i := 0; i < 6; i++ { + wg.Add(1) + go func() { + defer wg.Done() + lease, err := AcquireBPSStaticRequestLease(t.Context(), 300, []int64{1, 2, 3}) + if err != nil { + errs <- err + return + } + leases <- lease + u, _ := url.Parse(lease.ProxyURL) + tr := &http.Transport{Proxy: http.ProxyURL(u)} + defer tr.CloseIdleConnections() + resp, err := (&http.Client{Transport: tr}).Get("http://local-upstream.invalid/responses") + if err != nil { + errs <- err + return + } + defer resp.Body.Close() + _, err = io.ReadAll(resp.Body) + if err != nil { + errs <- err + } + }() + } + wg.Wait() + close(errs) + close(leases) + for err := range errs { + require.NoError(t, err) + } + for lease := range leases { + defer lease.Release() + } + mu.Lock() + defer mu.Unlock() + require.Equal(t, map[int]int{1: 2, 2: 2, 3: 2}, hits, fmt.Sprint(hits)) +} + +func TestBPSRequestPoolAccountsKeepIndependentSelectedGroupsAndLoads(t *testing.T) { + bpsStaticTestPool(t, func(context.Context, string) error { return nil }) + SetBPSStaticProxyRecords([]BPSStaticProxy{{ID: 1, URL: "http://one.invalid:8080"}, {ID: 2, URL: "http://two.invalid:8080"}, {ID: 3, URL: "http://three.invalid:8080"}}) + SetBPSStaticRequestGroups(map[int64][]int64{300: {1, 2}, 301: {2, 3}}) + WarmBPSPools(t.Context(), 0, 1) + a := make([]*BPSLease, 0, 4) + for i := 0; i < 4; i++ { + l, err := AcquireBPSStaticRequestLease(t.Context(), 300, []int64{1, 2}) + require.NoError(t, err) + t.Cleanup(l.Release) + a = append(a, l) + } + require.ElementsMatch(t, []string{"http://one.invalid:8080", "http://one.invalid:8080", "http://two.invalid:8080", "http://two.invalid:8080"}, []string{a[0].ProxyURL, a[1].ProxyURL, a[2].ProxyURL, a[3].ProxyURL}) + b1, err := AcquireBPSStaticRequestLease(t.Context(), 301, []int64{2, 3}) + require.NoError(t, err) + t.Cleanup(b1.Release) + b2, err := AcquireBPSStaticRequestLease(t.Context(), 301, []int64{2, 3}) + require.NoError(t, err) + t.Cleanup(b2.Release) + require.ElementsMatch(t, []string{"http://two.invalid:8080", "http://three.invalid:8080"}, []string{b1.ProxyURL, b2.ProxyURL}, "another account's load cannot suppress this account's idle selected exit") +} + +func TestBPSRequestPoolReleasedRequestsRotateAndReleaseOnlyOnce(t *testing.T) { + bpsStaticTestPool(t, func(context.Context, string) error { return nil }) + SetBPSStaticProxyRecords([]BPSStaticProxy{{ID: 1, URL: "http://one.invalid:8080"}, {ID: 2, URL: "http://two.invalid:8080"}, {ID: 3, URL: "http://three.invalid:8080"}}) + SetBPSStaticRequestGroups(map[int64][]int64{300: {1, 2, 3}}) + WarmBPSPools(t.Context(), 0, 1) + hits := map[string]int{} + for i := 0; i < 6; i++ { + l, err := AcquireBPSStaticRequestLease(t.Context(), 300, []int64{1, 2, 3}) + require.NoError(t, err) + hits[l.ProxyURL]++ + l.ReportSuccess() + l.Release() + l.Release() + } + require.Equal(t, map[string]int{"http://one.invalid:8080": 2, "http://two.invalid:8080": 2, "http://three.invalid:8080": 2}, hits) + // A double release must not make an exit appear to have negative load. + first, err := AcquireBPSStaticRequestLease(t.Context(), 300, []int64{1, 2, 3}) + require.NoError(t, err) + t.Cleanup(first.Release) + second, err := AcquireBPSStaticRequestLease(t.Context(), 300, []int64{1, 2, 3}) + require.NoError(t, err) + t.Cleanup(second.Release) + require.NotEqual(t, first.ProxyURL, second.ProxyURL) +} + +func TestBPSRequestPoolRotatesBeforeNextBackgroundAccountRefresh(t *testing.T) { + bpsStaticTestPool(t, func(context.Context, string) error { return nil }) + SetBPSStaticProxyRecords([]BPSStaticProxy{{ID: 1, URL: "http://one.invalid:8080"}, {ID: 2, URL: "http://two.invalid:8080"}}) + // These exits may already be healthy before a newly enabled account appears + // in the next background account projection. Its requests still rotate. + WarmBPSPools(t.Context(), 0, 2) + hits := map[string]int{} + for i := 0; i < 4; i++ { + l, err := AcquireBPSStaticRequestLease(t.Context(), 300, []int64{1, 2}) + require.NoError(t, err) + hits[l.ProxyURL]++ + l.Release() + } + require.Equal(t, map[string]int{"http://one.invalid:8080": 2, "http://two.invalid:8080": 2}, hits) +} + +func TestBPSRequestPoolFailsClosedWhenSelectedExitExpiresFailsOrIsRemoved(t *testing.T) { + for _, scenario := range []string{"expired", "removed", "failed", "excluded"} { + t.Run(scenario, func(t *testing.T) { + bpsStaticTestPool(t, func(context.Context, string) error { return nil }) + expires := time.Now().Add(time.Hour) + records := []BPSStaticProxy{{ID: 1, URL: "http://selected.invalid:8080", ExpiresAt: &expires}, {ID: 2, URL: "http://unselected.invalid:8080"}} + SetBPSStaticProxyRecords(records) + SetBPSStaticRequestGroups(map[int64][]int64{300: {1}}) + WarmBPSPools(t.Context(), 0, 2) + l, err := AcquireBPSStaticRequestLease(t.Context(), 300, []int64{1}) + require.NoError(t, err) + excluded := []string{} + switch scenario { + case "expired": + past := time.Now().Add(-time.Second) + records[0].ExpiresAt = &past + SetBPSStaticProxyRecords(records) + case "removed": + SetBPSStaticProxyRecords(records[1:]) + case "failed": + l.ReportStreamFailure() + case "excluded": + excluded = []string{l.ProxyURL} + } + l.Release() + _, err = AcquireBPSStaticRequestLease(t.Context(), 300, []int64{1}, excluded...) + require.Error(t, err, "an unselected healthy exit must never replace an unavailable selected group") + }) + } +} + +func TestBPSRequestPoolSelectedColdSubsetWarmsAfterGlobalTargetAlreadyMet(t *testing.T) { + bpsStaticTestPool(t, func(context.Context, string) error { return nil }) + SetBPSStaticProxyRecords([]BPSStaticProxy{{ID: 1, URL: "http://global-ready.invalid:8080"}}) + WarmBPSPools(t.Context(), 0, 1) + SetBPSStaticProxyRecords([]BPSStaticProxy{{ID: 1, URL: "http://global-ready.invalid:8080"}, {ID: 2, URL: "http://selected-cold.invalid:8080"}}) + SetBPSStaticRequestGroups(map[int64][]int64{300: {2}}) + _, err := AcquireBPSStaticRequestLease(t.Context(), 300, []int64{2}) + require.Error(t, err, "request must not qualify a cold selected exit") + WarmBPSPools(t.Context(), 0, 1) + l, err := AcquireBPSStaticRequestLease(t.Context(), 300, []int64{2}) + require.NoError(t, err, "selected subset must warm independently of an already full global target") + require.Equal(t, "http://selected-cold.invalid:8080", l.ProxyURL) + l.Release() +} + +func TestBPSRequestPoolRejectsStaleMembershipEvenWhenHealthIsStillVerified(t *testing.T) { + bpsStaticTestPool(t, func(context.Context, string) error { return nil }) + SetBPSStaticProxyRecords([]BPSStaticProxy{{ID: 1, URL: "http://selected.invalid:8080"}}) + SetBPSStaticRequestGroups(map[int64][]int64{300: {1}}) + WarmBPSPools(t.Context(), 0, 1) + // Shift time at the snapshot boundary, not the health/proxy choice, to + // model repeated ListActive failures without sleeping in a request test. + bpsStaticManager.bpsMu.Lock() + bpsStaticManager.bpsRequests.refreshedAt = time.Now().Add(-BPSStaticRequestMembershipMaxAge - time.Second) + bpsStaticManager.bpsMu.Unlock() + _, err := AcquireBPSStaticRequestLease(t.Context(), 300, []int64{1}) + require.Error(t, err, "reachability cannot prove stale database membership remains authorized") + // The old session mode retains its pre-existing snapshot behavior. + legacy, err := AcquireBPSStaticLease(t.Context(), "legacy/session") + require.NoError(t, err) + legacy.Release() + SetBPSStaticProxyRecords([]BPSStaticProxy{{ID: 1, URL: "http://selected.invalid:8080"}}) + recovered, err := AcquireBPSStaticRequestLease(t.Context(), 300, []int64{1}) + require.NoError(t, err) + recovered.Release() +} diff --git a/backend/internal/mihomo/bps_warm_pool.go b/backend/internal/mihomo/bps_warm_pool.go index 6eb25fd7dd41..755aeac22270 100644 --- a/backend/internal/mihomo/bps_warm_pool.go +++ b/backend/internal/mihomo/bps_warm_pool.go @@ -100,6 +100,7 @@ func (m *Manager) BPSWarmStatus() BPSWarmStatus { // A single service-owned worker refills both sources, never a request goroutine. func WarmBPSPools(ctx context.Context, managedTarget, staticTarget int) { + bpsStaticManager.warmBPSRequestGroups(ctx) if m := managedManager(); m != nil { m.warmBPSPool(ctx, managedTarget) } diff --git a/backend/internal/mihomo/manager.go b/backend/internal/mihomo/manager.go index 4f29843fe2d5..a54bcd26e650 100644 --- a/backend/internal/mihomo/manager.go +++ b/backend/internal/mihomo/manager.go @@ -108,6 +108,7 @@ type Manager struct { bpsProbe func(context.Context, string) error // isolated tests only bpsStaticMode bool // dedicated static (IP 管理) pool: no kernel, no listeners bpsStatic map[string]string // static node key -> upstream proxy URL; protected by bpsMu + bpsRequests bpsRequestPool // account request leases; protected by bpsMu astraGate sync.RWMutex astraLanes chan int diff --git a/backend/internal/pkg/openai/oauth.go b/backend/internal/pkg/openai/oauth.go index dc5371ba872b..aedafc7445fd 100644 --- a/backend/internal/pkg/openai/oauth.go +++ b/backend/internal/pkg/openai/oauth.go @@ -56,6 +56,7 @@ type OAuthSession struct { SIWCHostID string SIWCPreviousGrant string SIWCExpectedCredentials map[string]any + RequestProxy bool `json:"request_proxy,omitempty"` State string `json:"state"` CodeVerifier string `json:"code_verifier"` diff --git a/backend/internal/repository/account_bps_warm.go b/backend/internal/repository/account_bps_warm.go index 6a3aa04d34b8..f8ee6884134a 100644 --- a/backend/internal/repository/account_bps_warm.go +++ b/backend/internal/repository/account_bps_warm.go @@ -25,12 +25,16 @@ SELECT id, platform, type, status, schedulable, concurrency, parent_account_id, 'openai_excel_bps', extra->'openai_excel_bps', 'openai_excel_bps_mihomo', extra->'openai_excel_bps_mihomo', 'openai_excel_bps_proxy_source', extra->'openai_excel_bps_proxy_source', + 'openai_excel_bps_proxy_mode', extra->'openai_excel_bps_proxy_mode', + 'openai_excel_bps_proxy_ids', extra->'openai_excel_bps_proxy_ids', 'openai_excel_bps_authorization_pending', extra->'openai_excel_bps_authorization_pending', 'openai_excel_bps_auto_recover_on_403', extra->'openai_excel_bps_auto_recover_on_403', 'openai_excel_bps_auto_disable_on_403', extra->'openai_excel_bps_auto_disable_on_403', 'openai_excel_bps_403_disabled_at', extra->'openai_excel_bps_403_disabled_at', 'openai_siwc', extra->'openai_siwc' - ) + ) || CASE WHEN extra ? 'openai_proxy_mode' + THEN jsonb_build_object('openai_proxy_mode', extra->'openai_proxy_mode', 'openai_proxy_ids', extra->'openai_proxy_ids') + ELSE '{}'::jsonb END FROM accounts WHERE deleted_at IS NULL AND platform = $1 AND status = $2 ORDER BY priority, id` diff --git a/backend/internal/repository/account_bps_warm_integration_test.go b/backend/internal/repository/account_bps_warm_integration_test.go index bf12cc6d75a5..dcb8183b3fa9 100644 --- a/backend/internal/repository/account_bps_warm_integration_test.go +++ b/backend/internal/repository/account_bps_warm_integration_test.go @@ -23,6 +23,10 @@ func TestBPSWarmProjectionPreservesEligibilityWithoutLargePayloads(t *testing.T) }{ {name: "managed"}, {name: "static", change: func(a *service.Account) { a.Extra[service.ExcelBPSProxySourceKey] = service.ExcelBPSProxySourceIPPool }}, + {name: "request group", change: func(a *service.Account) { + a.Extra[service.ExcelBPSProxyModeKey] = service.ExcelBPSProxyModeRequest + a.Extra[service.ExcelBPSProxyIDsKey] = []int64{11, 22} + }}, {name: "free", change: func(a *service.Account) { a.Credentials["plan_type"] = " Free " }}, {name: "agent", change: func(a *service.Account) { a.Credentials["auth_mode"] = service.OpenAIAuthModeAgentIdentity }}, {name: "legacy_pat", change: func(a *service.Account) { a.Credentials["openai_auth_mode"] = "personal_access_token" }}, @@ -100,6 +104,8 @@ func TestBPSWarmProjectionPreservesEligibilityWithoutLargePayloads(t *testing.T) require.Equal(t, full.IsExcelBPS403RecoveryPending(), got.IsExcelBPS403RecoveryPending()) require.Equal(t, full.IsExcelBPSMihomoEnabled(), got.IsExcelBPSMihomoEnabled()) require.Equal(t, full.ExcelBPSProxySource(), got.ExcelBPSProxySource()) + require.Equal(t, full.ExcelBPSRequestProxyEnabled(), got.ExcelBPSRequestProxyEnabled()) + require.Equal(t, full.ExcelBPSRequestProxyIDs(), got.ExcelBPSRequestProxyIDs()) require.Equal(t, full.IsShadow(), got.IsShadow()) if full.IsShadow() { require.True(t, got.IsShadow()) diff --git a/backend/internal/repository/astra_routing_upstream.go b/backend/internal/repository/astra_routing_upstream.go index c99c978c0ff2..4aba297bfe57 100644 --- a/backend/internal/repository/astra_routing_upstream.go +++ b/backend/internal/repository/astra_routing_upstream.go @@ -78,6 +78,15 @@ func (s *astraRoutingUpstream) Do(r *http.Request, p string, a int64, n int) (*h return s.DoWithTLS(r, p, a, n, nil) } func (s *astraRoutingUpstream) DoWithTLS(r *http.Request, p string, a int64, n int, f *tlsfingerprint.Profile) (*http.Response, error) { + if r != nil { + leased, err := service.ValidateOpenAIRequestProxyEgress(r.Context(), a, p) + if err != nil { + return nil, err + } + if leased { + return s.delegate.DoWithTLS(r, p, a, n, f) + } + } if r != nil && service.IsBoundAstraTicketRequest(r.Context()) { return s.delegate.DoWithTLS(r, p, a, n, f) } diff --git a/backend/internal/repository/http_upstream.go b/backend/internal/repository/http_upstream.go index e6c33139331f..ea0d856d2672 100644 --- a/backend/internal/repository/http_upstream.go +++ b/backend/internal/repository/http_upstream.go @@ -245,6 +245,11 @@ func newHTTPUpstream(cfg *config.Config, provider OpenAIResponseHeaderTimeoutPro // - 调用方必须关闭 resp.Body,否则会导致 inFlight 计数泄漏 // - inFlight > 0 的客户端不会被淘汰,确保活跃请求不被中断 func (s *httpUpstreamService) Do(req *http.Request, proxyURL string, accountID int64, accountConcurrency int) (*http.Response, error) { + if req != nil { + if _, err := service.ValidateOpenAIRequestProxyEgress(req.Context(), accountID, proxyURL); err != nil { + return nil, err + } + } if req != nil { requestcapture.FromContext(req.Context()).BindAccount(accountID) req = req.WithContext(requestcapture.WithAccount(req.Context(), accountID)) @@ -317,6 +322,11 @@ func (s *httpUpstreamService) Do(req *http.Request, proxyURL string, accountID i // profile 为 nil 时不启用 TLS 指纹,行为与 Do 方法相同。 // profile 非 nil 时使用指定的 Profile 进行 TLS 指纹伪装。 func (s *httpUpstreamService) DoWithTLS(req *http.Request, proxyURL string, accountID int64, accountConcurrency int, profile *tlsfingerprint.Profile) (*http.Response, error) { + if req != nil { + if _, err := service.ValidateOpenAIRequestProxyEgress(req.Context(), accountID, proxyURL); err != nil { + return nil, err + } + } if profile == nil { return s.Do(req, proxyURL, accountID, accountConcurrency) } diff --git a/backend/internal/repository/openai_request_proxy_transport_integration_test.go b/backend/internal/repository/openai_request_proxy_transport_integration_test.go new file mode 100644 index 000000000000..ebff7073ae6b --- /dev/null +++ b/backend/internal/repository/openai_request_proxy_transport_integration_test.go @@ -0,0 +1,137 @@ +//go:build bps_request_integration + +package repository + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "net/url" + "sync/atomic" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/mihomo" + "github.com/Wei-Shaw/sub2api/internal/pkg/tlsfingerprint" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +type requestProxyTransportRepo struct { + service.AccountRepository + account *service.Account +} + +func (r *requestProxyTransportRepo) GetByID(context.Context, int64) (*service.Account, error) { + return r.account, nil +} +func (*requestProxyTransportRepo) UpdateExtra(context.Context, int64, map[string]any) error { + return nil +} + +type requestProxyTransportTickets struct { + service.AstraTicketLifecycle + proxy string + calls atomic.Int32 +} + +func (*requestProxyTransportTickets) UnifiedAstraTicketsEnabled(context.Context) bool { return true } +func (p *requestProxyTransportTickets) ApplyStoredAstraTarget(_ context.Context, h http.Header, _ int64, _ string) (string, func(), error) { + p.calls.Add(1) + h.Set("Cookie", "__oailb=outside-route") + return p.proxy, func() {}, nil +} + +func requestProxyTransportFixture(t *testing.T) (*service.Account, string, string, *atomic.Int32, *atomic.Int32) { + t.Helper() + selectedHits, outsideHits := &atomic.Int32{}, &atomic.Int32{} + makeProxy := func(hits *atomic.Int32) *httptest.Server { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + hits.Add(1) + _, _ = io.Copy(io.Discard, r.Body) + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, "data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_proxy\",\"status\":\"completed\",\"output\":[],\"usage\":{\"input_tokens\":1,\"output_tokens\":1}}}\n\n") + })) + t.Cleanup(server.Close) + return server + } + selected, outside := makeProxy(selectedHits), makeProxy(outsideHits) + restore := mihomo.InstallBPSRequestIntegrationProbe(func(context.Context, string) error { return nil }) + t.Cleanup(restore) + mihomo.SetBPSStaticProxyRecords([]mihomo.BPSStaticProxy{{ID: 1, URL: outside.URL}, {ID: 2, URL: selected.URL}}) + mihomo.SetBPSStaticRequestGroups(map[int64][]int64{300: {2}}) + mihomo.WarmBPSPools(t.Context(), 0, 1) + account := &service.Account{ID: 300, Platform: service.PlatformOpenAI, Type: service.AccountTypeOAuth, Concurrency: 6, Credentials: map[string]any{"access_token": "fixture-token"}, Extra: map[string]any{"openai_proxy_mode": "request", "openai_proxy_ids": []int64{2}}} + return account, selected.URL, outside.URL, selectedHits, outsideHits +} + +// The HTTPS boundary is translated only after Astra routing. Actual socket +// selection still runs through the native HTTP transport and local proxies. +func requestProxyNativeHTTPBoundary(t *testing.T, upstream service.HTTPUpstream, mutate func(string) string) (service.HTTPUpstream, *atomic.Int32) { + t.Helper() + originHits := &atomic.Int32{} + origin := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { originHits.Add(1); w.WriteHeader(http.StatusBadGateway) })) + t.Cleanup(origin.Close) + originURL, err := url.Parse(origin.URL) + require.NoError(t, err) + return gatewayPinDelegate{call: func(r *http.Request, proxy string, accountID int64, concurrency int, _ *tlsfingerprint.Profile) (*http.Response, error) { + local := r.Clone(r.Context()) + u := *r.URL + u.Scheme = "http" + u.Host = originURL.Host + local.URL = &u + local.RequestURI = "" + if mutate != nil { + proxy = mutate(proxy) + } + return upstream.Do(local, proxy, accountID, concurrency) + }}, originHits +} + +func runRequestProxyTransportAccountTest(t *testing.T, account *service.Account, upstream service.HTTPUpstream) (string, error) { + t.Helper() + svc := service.NewAccountTestService(&requestProxyTransportRepo{account: account}, nil, nil, nil, nil, upstream, nil, nil) + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + c.Request = httptest.NewRequest(http.MethodPost, "/admin/accounts/300/test", nil) + err := svc.TestAccountConnection(c, account.ID, "gpt-6-astra", "", "") + return recorder.Body.String(), err +} + +func TestOpenAIRequestProxyLateAstraAdapterKeepsSelectedExit(t *testing.T) { + account, _, outside, selectedHits, outsideHits := requestProxyTransportFixture(t) + cfg := &config.Config{} + cfg.Gateway.CodexGatewayPin = pinConfig() + tickets := &requestProxyTransportTickets{proxy: outside} + boundary, originHits := requestProxyNativeHTTPBoundary(t, NewHTTPUpstream(nil), nil) + upstream := &astraRoutingUpstream{cfg: cfg, tickets: tickets, delegate: boundary} + body, err := runRequestProxyTransportAccountTest(t, account, upstream) + require.NoError(t, err) + require.Contains(t, body, "test_complete") + require.EqualValues(t, 1, selectedHits.Load()) + require.Zero(t, outsideHits.Load()) + require.Zero(t, originHits.Load()) + require.Zero(t, tickets.calls.Load(), "late adapter must not borrow a ticket or replace the selected route") +} + +func TestOpenAIRequestProxyNativeTransportRejectsChangedExit(t *testing.T) { + for _, changed := range []string{"outside", "direct"} { + t.Run(changed, func(t *testing.T) { + account, _, outside, selectedHits, outsideHits := requestProxyTransportFixture(t) + upstream, originHits := requestProxyNativeHTTPBoundary(t, NewHTTPUpstream(nil), func(string) string { + if changed == "direct" { + return "" + } + return outside + }) + body, err := runRequestProxyTransportAccountTest(t, account, upstream) + require.Error(t, err) + require.Contains(t, body, "selected OpenAI request proxies are unavailable") + require.Zero(t, selectedHits.Load()) + require.Zero(t, outsideHits.Load()) + require.Zero(t, originHits.Load()) + }) + } +} diff --git a/backend/internal/repository/proxy_repo.go b/backend/internal/repository/proxy_repo.go index 5f37b78270c5..9004745ebb08 100644 --- a/backend/internal/repository/proxy_repo.go +++ b/backend/internal/repository/proxy_repo.go @@ -488,21 +488,67 @@ func (r *proxyRepository) ExistsByHostPortAuth(ctx context.Context, host string, return count > 0, err } -// CountAccountsByProxyID returns the number of accounts using a specific proxy +// configuredAccountProxyReferencesSQL describes saved configuration, not live +// traffic. Retained request-mode groups count while BPS is temporarily off. +// UNION deduplicates both repeated group entries and the legacy proxy_id field. +const configuredAccountProxyReferencesSQL = ` +WITH configured_account_proxy_refs AS ( + SELECT id AS account_id, proxy_id + FROM accounts + WHERE deleted_at IS NULL AND proxy_id IS NOT NULL + UNION + SELECT id AS account_id, proxy_id + FROM ( + SELECT a.id, CASE + WHEN selected_id BETWEEN 1 AND 9223372036854775807 + AND selected_id = trunc(selected_id) THEN selected_id::bigint + END AS proxy_id + FROM accounts a + CROSS JOIN LATERAL (SELECT CASE + WHEN a.extra ? 'openai_proxy_mode' THEN a.extra -> 'openai_proxy_ids' + ELSE a.extra -> 'openai_excel_bps_proxy_ids' END AS ids, CASE + WHEN a.extra ? 'openai_proxy_mode' THEN a.extra ->> 'openai_proxy_mode' + ELSE a.extra ->> 'openai_excel_bps_proxy_mode' END AS mode + ) routing + CROSS JOIN LATERAL jsonb_array_elements(CASE + WHEN jsonb_typeof(routing.ids) = 'array' + THEN routing.ids ELSE '[]'::jsonb END) selected(value) + CROSS JOIN LATERAL (SELECT CASE + WHEN jsonb_typeof(selected.value) = 'number' + THEN selected.value::text::numeric END AS selected_id) parsed + -- Match strings.TrimSpace in the account auth-mode helpers. + CROSS JOIN (VALUES (U&'\0009\000A\000B\000C\000D\0020\0085\00A0\1680\2000\2001\2002\2003\2004\2005\2006\2007\2008\2009\200A\2028\2029\202F\205F\3000')) AS whitespace(chars) + CROSS JOIN LATERAL (SELECT + lower(btrim(COALESCE(a.credentials ->> 'auth_mode', ''), whitespace.chars)) AS auth_mode, + lower(btrim(COALESCE(a.credentials ->> 'openai_auth_mode', ''), whitespace.chars)) AS legacy_auth_mode + ) auth + WHERE a.deleted_at IS NULL + AND a.platform = 'openai' AND a.type = 'oauth' + AND a.parent_account_id IS NULL + AND auth.auth_mode NOT IN ('agentidentity', 'personalaccesstoken', 'personal_access_token') + AND auth.legacy_auth_mode NOT IN ('personalaccesstoken', 'personal_access_token') + AND routing.mode = 'request' + ) selected_refs + WHERE proxy_id IS NOT NULL +) +` + +// CountAccountsByProxyID returns the number of accounts configured for a proxy. func (r *proxyRepository) CountAccountsByProxyID(ctx context.Context, proxyID int64) (int64, error) { var count int64 - if err := scanSingleRow(ctx, r.sql, "SELECT COUNT(*) FROM accounts WHERE proxy_id = $1 AND deleted_at IS NULL", []any{proxyID}, &count); err != nil { + if err := scanSingleRow(ctx, r.sql, configuredAccountProxyReferencesSQL+"SELECT COUNT(*) FROM configured_account_proxy_refs WHERE proxy_id = $1", []any{proxyID}, &count); err != nil { return 0, err } return count, nil } func (r *proxyRepository) ListAccountSummariesByProxyID(ctx context.Context, proxyID int64) ([]service.ProxyAccountSummary, error) { - rows, err := r.sql.QueryContext(ctx, ` - SELECT id, name, platform, type, notes - FROM accounts - WHERE proxy_id = $1 AND deleted_at IS NULL - ORDER BY id DESC + rows, err := r.sql.QueryContext(ctx, configuredAccountProxyReferencesSQL+` + SELECT a.id, a.name, a.platform, a.type, a.notes + FROM accounts a + JOIN configured_account_proxy_refs refs ON refs.account_id = a.id + WHERE refs.proxy_id = $1 + ORDER BY a.id DESC `, proxyID) if err != nil { return nil, err @@ -541,7 +587,7 @@ func (r *proxyRepository) ListAccountSummariesByProxyID(ctx context.Context, pro // GetAccountCountsForProxies returns a map of proxy ID to account count for all proxies func (r *proxyRepository) GetAccountCountsForProxies(ctx context.Context) (counts map[int64]int64, err error) { - rows, err := r.sql.QueryContext(ctx, "SELECT proxy_id, COUNT(*) AS count FROM accounts WHERE proxy_id IS NOT NULL AND deleted_at IS NULL GROUP BY proxy_id") + rows, err := r.sql.QueryContext(ctx, configuredAccountProxyReferencesSQL+"SELECT proxy_id, COUNT(*) AS count FROM configured_account_proxy_refs GROUP BY proxy_id") if err != nil { return nil, err } diff --git a/backend/internal/repository/proxy_repo_integration_test.go b/backend/internal/repository/proxy_repo_integration_test.go index bc9a88f7cd06..6db884995485 100644 --- a/backend/internal/repository/proxy_repo_integration_test.go +++ b/backend/internal/repository/proxy_repo_integration_test.go @@ -4,6 +4,8 @@ package repository import ( "context" + "encoding/json" + "fmt" "testing" "time" @@ -255,6 +257,152 @@ func (s *ProxyRepoSuite) TestGetAccountCountsForProxies_Empty() { s.Require().Empty(counts) } +func (s *ProxyRepoSuite) TestConfiguredAccountReferencesIncludeBPSGroupsOnce() { + p1 := s.mustCreateProxy(&service.Proxy{Name: "configured-one", Protocol: "http", Host: "192.0.2.11", Port: 8080, Status: service.StatusActive}) + p2 := s.mustCreateProxy(&service.Proxy{Name: "configured-two", Protocol: "http", Host: "192.0.2.22", Port: 8080, Status: service.StatusActive}) + s.mustInsertAccount("traditional", &p1.ID) + insert := func(name, platform, accountType string, proxyID *int64, extra map[string]any, deleted bool) { + data, err := json.Marshal(extra) + s.Require().NoError(err) + var deletedAt any + if deleted { + deletedAt = time.Now() + } + _, err = s.tx.ExecContext(s.ctx, `INSERT INTO accounts (name, platform, type, proxy_id, extra, deleted_at) VALUES ($1,$2,$3,$4,$5,$6)`, name, platform, accountType, proxyID, string(data), deletedAt) + s.Require().NoError(err) + } + group := func(enabled bool, ids ...int64) map[string]any { + return map[string]any{"openai_excel_bps": enabled, service.ExcelBPSProxyModeKey: service.ExcelBPSProxyModeRequest, service.ExcelBPSProxyIDsKey: ids} + } + insert("both-fields", service.PlatformOpenAI, service.AccountTypeOAuth, &p1.ID, group(true, p1.ID, p1.ID, p2.ID), false) + insert("saved-disabled-bps", service.PlatformOpenAI, service.AccountTypeOAuth, nil, group(false, p1.ID), false) + insert("removed-account", service.PlatformOpenAI, service.AccountTypeOAuth, &p1.ID, group(true, p1.ID), true) + insert("other-platform-extra", service.PlatformAnthropic, service.AccountTypeOAuth, nil, group(true, p1.ID), false) + insert("other-type-extra", service.PlatformOpenAI, service.AccountTypeAPIKey, nil, group(true, p1.ID), false) + insert("session-mode", service.PlatformOpenAI, service.AccountTypeOAuth, nil, map[string]any{service.ExcelBPSProxyModeKey: service.ExcelBPSProxyModeSession, service.ExcelBPSProxyIDsKey: []int64{p1.ID}}, false) + insert("invalid-scalar", service.PlatformOpenAI, service.AccountTypeOAuth, nil, map[string]any{service.ExcelBPSProxyModeKey: service.ExcelBPSProxyModeRequest, service.ExcelBPSProxyIDsKey: "invalid"}, false) + insert("invalid-elements", service.PlatformOpenAI, service.AccountTypeOAuth, nil, map[string]any{service.ExcelBPSProxyModeKey: service.ExcelBPSProxyModeRequest, service.ExcelBPSProxyIDsKey: []any{nil, "not-an-id", -1, 0, 1.5, json.Number("9223372036854775808")}}, false) + + accounts, err := s.repo.ListAccountSummariesByProxyID(s.ctx, p1.ID) + s.Require().NoError(err) + names := make([]string, 0, len(accounts)) + for _, account := range accounts { + names = append(names, account.Name) + } + s.Require().ElementsMatch([]string{"traditional", "both-fields", "saved-disabled-bps"}, names) + count, err := s.repo.CountAccountsByProxyID(s.ctx, p1.ID) + s.Require().NoError(err) + s.Require().Equal(int64(3), count) + counts, err := s.repo.GetAccountCountsForProxies(s.ctx) + s.Require().NoError(err) + s.Require().Equal(int64(3), counts[p1.ID]) + s.Require().Equal(int64(1), counts[p2.ID]) + rows, _, err := s.repo.ListWithFiltersAndAccountCount(s.ctx, pagination.PaginationParams{Page: 1, PageSize: 10, SortBy: "account_count", SortOrder: "desc"}, "", "", "configured-") + s.Require().NoError(err) + s.Require().Len(rows, 2) + s.Require().Equal(p1.ID, rows[0].ID) + s.Require().Equal(int64(3), rows[0].AccountCount) + s.Require().Equal(int64(1), rows[1].AccountCount) +} + +func (s *ProxyRepoSuite) TestBPSConfiguredReferenceProtectsSingleAndBatchDeletion() { + p := s.mustCreateProxy(&service.Proxy{Name: "saved-bps-group", Protocol: "http", Host: "192.0.2.31", Port: 8080, Status: service.StatusActive}) + extra, err := json.Marshal(map[string]any{"openai_excel_bps": false, service.ExcelBPSProxyModeKey: service.ExcelBPSProxyModeRequest, service.ExcelBPSProxyIDsKey: []int64{p.ID}}) + s.Require().NoError(err) + _, err = s.tx.ExecContext(s.ctx, `INSERT INTO accounts (name, platform, type, extra) VALUES ($1,$2,$3,$4)`, "saved-group-only", service.PlatformOpenAI, service.AccountTypeOAuth, string(extra)) + s.Require().NoError(err) + admin := service.NewAdminService( + nil, nil, nil, nil, s.repo, nil, nil, nil, nil, nil, nil, nil, + nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, + ) + s.Require().ErrorIs(admin.DeleteProxy(s.ctx, p.ID), service.ErrProxyInUse) + batch, err := admin.BatchDeleteProxies(s.ctx, []int64{p.ID}) + s.Require().NoError(err) + s.Require().Empty(batch.DeletedIDs) + s.Require().Len(batch.Skipped, 1) + s.Require().Equal(p.ID, batch.Skipped[0].ID) + s.Require().Equal(service.ErrProxyInUse.Error(), batch.Skipped[0].Reason) + _, err = s.repo.GetByID(s.ctx, p.ID) + s.Require().NoError(err, "a saved group keeps its proxy configuration intact") + _, err = s.tx.ExecContext(s.ctx, `UPDATE accounts SET extra = '{"openai_excel_bps_proxy_mode":"session","openai_excel_bps_proxy_ids":[]}'::jsonb WHERE name = $1`, "saved-group-only") + s.Require().NoError(err) + s.Require().NoError(admin.DeleteProxy(s.ctx, p.ID), "removing the saved group releases deletion protection") +} + +func (s *ProxyRepoSuite) TestOpenAIConfiguredReferencesPreferExplicitMode() { + newGroup := s.mustCreateProxy(&service.Proxy{Name: "new-group", Protocol: "http", Host: "192.0.2.61", Port: 8080, Status: service.StatusActive}) + legacyGroup := s.mustCreateProxy(&service.Proxy{Name: "legacy-group", Protocol: "http", Host: "192.0.2.62", Port: 8080, Status: service.StatusActive}) + for _, mode := range []string{service.OpenAIProxyModeSingle, service.OpenAIProxyModeRequest} { + extra, err := json.Marshal(map[string]any{service.OpenAIProxyModeKey: mode, service.OpenAIProxyIDsKey: []int64{newGroup.ID, newGroup.ID}, service.ExcelBPSProxyModeKey: service.ExcelBPSProxyModeRequest, service.ExcelBPSProxyIDsKey: []int64{legacyGroup.ID}}) + s.Require().NoError(err) + _, err = s.tx.ExecContext(s.ctx, `INSERT INTO accounts (name, platform, type, extra) VALUES ($1,$2,$3,$4)`, "explicit-"+mode, service.PlatformOpenAI, service.AccountTypeOAuth, string(extra)) + s.Require().NoError(err) + } + count, err := s.repo.CountAccountsByProxyID(s.ctx, newGroup.ID) + s.Require().NoError(err) + s.Require().Equal(int64(1), count) + count, err = s.repo.CountAccountsByProxyID(s.ctx, legacyGroup.ID) + s.Require().NoError(err) + s.Require().Zero(count, "explicit single/request both override retained legacy group") + accounts, err := s.repo.ListAccountSummariesByProxyID(s.ctx, newGroup.ID) + s.Require().NoError(err) + s.Require().Len(accounts, 1) + s.Require().Equal("explicit-request", accounts[0].Name) + counts, err := s.repo.GetAccountCountsForProxies(s.ctx) + s.Require().NoError(err) + s.Require().Equal(int64(1), counts[newGroup.ID]) + s.Require().Zero(counts[legacyGroup.ID]) +} + +func (s *ProxyRepoSuite) TestNonBPSCredentialsIgnoreRetainedGroupsButKeepLegacyProxy() { + groupOnly := s.mustCreateProxy(&service.Proxy{Name: "non-bps-group-only", Protocol: "http", Host: "192.0.2.41", Port: 8080, Status: service.StatusActive}) + batchOnly := s.mustCreateProxy(&service.Proxy{Name: "non-bps-batch-only", Protocol: "http", Host: "192.0.2.42", Port: 8080, Status: service.StatusActive}) + legacy := s.mustCreateProxy(&service.Proxy{Name: "non-bps-legacy", Protocol: "http", Host: "192.0.2.43", Port: 8080, Status: service.StatusActive}) + extra, err := json.Marshal(map[string]any{"openai_excel_bps": true, service.ExcelBPSProxyModeKey: service.ExcelBPSProxyModeRequest, service.ExcelBPSProxyIDsKey: []int64{groupOnly.ID, batchOnly.ID, legacy.ID, legacy.ID}}) + s.Require().NoError(err) + credentials := []map[string]any{ + {"auth_mode": " \tAGENTidentity\n"}, + {"auth_mode": "\tPersonalAccessToken \r"}, + {"auth_mode": " PERSONAL_ACCESS_TOKEN "}, + {"auth_mode": "oauth", "openai_auth_mode": " PeRsOnAlAcCeSsToKeN "}, + {"openai_auth_mode": "\u00a0personal_access_token\u3000"}, + } + for i, credential := range credentials { + data, marshalErr := json.Marshal(credential) + s.Require().NoError(marshalErr) + _, err = s.tx.ExecContext(s.ctx, `INSERT INTO accounts (name, platform, type, proxy_id, credentials, extra) VALUES ($1,$2,$3,$4,$5,$6)`, fmt.Sprintf("non-bps-credentials-%d", i), service.PlatformOpenAI, service.AccountTypeOAuth, legacy.ID, string(data), string(extra)) + s.Require().NoError(err) + } + for _, id := range []int64{groupOnly.ID, batchOnly.ID} { + accounts, listErr := s.repo.ListAccountSummariesByProxyID(s.ctx, id) + s.Require().NoError(listErr) + s.Require().Empty(accounts, "non-BPS retained groups must not be configured references") + count, countErr := s.repo.CountAccountsByProxyID(s.ctx, id) + s.Require().NoError(countErr) + s.Require().Zero(count) + } + accounts, err := s.repo.ListAccountSummariesByProxyID(s.ctx, legacy.ID) + s.Require().NoError(err) + s.Require().Len(accounts, 5, "the traditional field remains one reference per account") + counts, err := s.repo.GetAccountCountsForProxies(s.ctx) + s.Require().NoError(err) + s.Require().Zero(counts[groupOnly.ID]) + s.Require().Zero(counts[batchOnly.ID]) + s.Require().Equal(int64(5), counts[legacy.ID]) + admin := service.NewAdminService( + nil, nil, nil, nil, s.repo, nil, nil, nil, nil, nil, nil, nil, + nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, + ) + s.Require().NoError(admin.DeleteProxy(s.ctx, groupOnly.ID)) + batch, err := admin.BatchDeleteProxies(s.ctx, []int64{batchOnly.ID, legacy.ID}) + s.Require().NoError(err) + s.Require().Equal([]int64{batchOnly.ID}, batch.DeletedIDs) + s.Require().Len(batch.Skipped, 1) + s.Require().Equal(legacy.ID, batch.Skipped[0].ID) + s.Require().Equal(service.ErrProxyInUse.Error(), batch.Skipped[0].Reason) + s.Require().ErrorIs(admin.DeleteProxy(s.ctx, legacy.ID), service.ErrProxyInUse) +} + // --- ListActiveWithAccountCount --- func (s *ProxyRepoSuite) TestListActiveWithAccountCount() { diff --git a/backend/internal/repository/scheduler_cache.go b/backend/internal/repository/scheduler_cache.go index d746a8d908c9..3359fd8b4a45 100644 --- a/backend/internal/repository/scheduler_cache.go +++ b/backend/internal/repository/scheduler_cache.go @@ -1470,6 +1470,11 @@ func filterSchedulerExtra(extra map[string]any) map[string]any { "openai_passthrough", "openai_oauth_passthrough", "openai_excel_bps", + service.ExcelBPSProxyModeKey, + service.ExcelBPSProxyIDsKey, + service.OpenAIProxyModeKey, + service.OpenAIProxyIDsKey, + "openai_excel_bps_proxy_source", "openai_excel_bps_auto_disable_on_403", service.ExcelBPSAutoRecoverOn403Key, service.ExcelBPS403RecoveryIntervalMinutesKey, @@ -1506,7 +1511,7 @@ func filterSchedulerExtra(extra map[string]any) map[string]any { } filtered := make(map[string]any) for _, key := range keys { - if value, ok := extra[key]; ok && (value != nil || key == "openai_excel_bps_models") { + if value, ok := extra[key]; ok && (value != nil || key == "openai_excel_bps_models" || key == service.OpenAIProxyModeKey) { if key == service.UpstreamBillingProbeExtraKey { filteredProbe := filterSchedulerUpstreamBillingProbe(value) if filteredProbe == nil { diff --git a/backend/internal/repository/scheduler_cache_bps_proxy_unit_test.go b/backend/internal/repository/scheduler_cache_bps_proxy_unit_test.go new file mode 100644 index 000000000000..a589ef545034 --- /dev/null +++ b/backend/internal/repository/scheduler_cache_bps_proxy_unit_test.go @@ -0,0 +1,72 @@ +//go:build unit + +package repository + +import ( + "context" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/stretchr/testify/require" +) + +func TestSchedulerCacheBPSRequestProxyRoundTrip(t *testing.T) { + ctx := context.Background() + cache := newSchedulerCacheUnit(t) + account := service.Account{ID: 601, Platform: service.PlatformOpenAI, Type: service.AccountTypeOAuth, Status: service.StatusActive, Schedulable: true, Concurrency: 6, Extra: map[string]any{"openai_excel_bps": true, "openai_excel_bps_proxy_mode": "request", "openai_excel_bps_proxy_ids": []int64{11, 22}, "openai_excel_bps_proxy_source": "ip_pool"}} + bucket := service.SchedulerBucket{GroupID: 1, Platform: service.PlatformOpenAI, Mode: service.SchedulerModeSingle} + token, err := cache.CaptureBucketWriteToken(ctx, bucket) + require.NoError(t, err) + require.NoError(t, cache.SetSnapshot(ctx, bucket, token, []service.Account{account})) + candidates, hit, err := cache.GetSnapshot(ctx, bucket) + require.NoError(t, err) + require.True(t, hit) + require.Len(t, candidates, 1) + full, err := cache.GetAccount(ctx, account.ID) + require.NoError(t, err) + for _, saved := range []*service.Account{candidates[0], full} { + require.True(t, saved.ExcelBPSRequestProxyEnabled()) + require.Equal(t, []int64{11, 22}, saved.ExcelBPSRequestProxyIDs()) + require.Equal(t, "ip_pool", saved.Extra["openai_excel_bps_proxy_source"]) + } +} + +func TestSchedulerCacheOpenAIRequestProxyRoundTrip(t *testing.T) { + ctx := context.Background() + cache := newSchedulerCacheUnit(t) + account := service.Account{ID: 602, Platform: service.PlatformOpenAI, Type: service.AccountTypeOAuth, Status: service.StatusActive, Schedulable: true, Extra: map[string]any{service.OpenAIProxyModeKey: service.OpenAIProxyModeRequest, service.OpenAIProxyIDsKey: []int64{11, 22}}} + bucket := service.SchedulerBucket{GroupID: 1, Platform: service.PlatformOpenAI, Mode: service.SchedulerModeSingle} + token, err := cache.CaptureBucketWriteToken(ctx, bucket) + require.NoError(t, err) + require.NoError(t, cache.SetSnapshot(ctx, bucket, token, []service.Account{account})) + candidates, hit, err := cache.GetSnapshot(ctx, bucket) + require.NoError(t, err) + require.True(t, hit) + require.Len(t, candidates, 1) + full, err := cache.GetAccount(ctx, account.ID) + require.NoError(t, err) + for _, saved := range []*service.Account{candidates[0], full} { + require.True(t, saved.OpenAIRequestProxyEnabled()) + require.Equal(t, []int64{11, 22}, saved.OpenAIRequestProxyIDs()) + } +} + +func TestSchedulerCacheOpenAIProxyPreservesExplicitNullMode(t *testing.T) { + ctx := context.Background() + cache := newSchedulerCacheUnit(t) + account := service.Account{ID: 603, Platform: service.PlatformOpenAI, Type: service.AccountTypeOAuth, Status: service.StatusActive, Schedulable: true, Extra: map[string]any{service.OpenAIProxyModeKey: nil, service.OpenAIProxyIDsKey: []int64{11}}} + bucket := service.SchedulerBucket{GroupID: 1, Platform: service.PlatformOpenAI, Mode: service.SchedulerModeSingle} + token, err := cache.CaptureBucketWriteToken(ctx, bucket) + require.NoError(t, err) + require.NoError(t, cache.SetSnapshot(ctx, bucket, token, []service.Account{account})) + candidates, hit, err := cache.GetSnapshot(ctx, bucket) + require.NoError(t, err) + require.True(t, hit) + require.Len(t, candidates, 1) + full, err := cache.GetAccount(ctx, account.ID) + require.NoError(t, err) + for _, saved := range []*service.Account{candidates[0], full} { + require.True(t, saved.OpenAIRequestProxyEnabled(), "malformed stored mode must not turn into direct fallback") + require.Empty(t, saved.OpenAIRequestProxyIDs()) + } +} diff --git a/backend/internal/service/admin_account.go b/backend/internal/service/admin_account.go index fe3a1aaf3ec8..bd4e4f58414b 100644 --- a/backend/internal/service/admin_account.go +++ b/backend/internal/service/admin_account.go @@ -585,6 +585,9 @@ func (s *adminServiceImpl) CreateAccount(ctx context.Context, input *CreateAccou return nil, err } account.GroupIDs = append([]int64(nil), groupIDs...) + if err := s.validateExcelBPSProxySettings(ctx, account); err != nil { + return nil, err + } if err := s.validateExcelBPS403GroupSettings(ctx, account); err != nil { return nil, err } @@ -664,6 +667,8 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U if (account.Platform == PlatformTypeSafe || account.Platform == PlatformMistral || account.Platform == PlatformQwen) && input.Type != "" && input.Type != AccountTypeAPIKey { return nil, fmt.Errorf("%s accounts only support apikey credentials", account.Platform) } + previousBPSProxySettings := *account + previousBPSProxySettings.Extra = maps.Clone(account.Extra) var normalizedExtra map[string]any if input.Extra != nil { normalizedExtra, err = normalizeOpenAILongContextBillingUpdateExtra(account, input) @@ -819,6 +824,7 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U normalizedExtra[key] = value } } + normalizedExtra = preserveExcelBPSProxyExtra(account.Extra, normalizedExtra) normalizedExtra = MergeOpenAICodexTicketExtra(normalizedExtra, account.Extra) normalizedExtra = prepareCodexFingerprintExtraForUpdate(account, normalizedExtra) account.Extra = normalizedExtra @@ -981,6 +987,9 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U } } + if err := s.validateExcelBPSProxySettingsChange(ctx, &previousBPSProxySettings, account); err != nil { + return nil, err + } if err := s.validateExcelBPS403GroupSettings(ctx, account); err != nil { return nil, err } @@ -1064,6 +1073,15 @@ func (s *adminServiceImpl) UpdateAccountExtra(ctx context.Context, id int64, upd if err := ValidateAccountCostMultiplierExtra(updates); err != nil { return err } + if hasExcelBPSProxyUpdates(updates) { + account, err := s.accountRepo.GetByID(ctx, id) + if err != nil { + return err + } + if err := s.validateExcelBPSProxyUpdates(ctx, account, updates); err != nil { + return err + } + } _, moveChanged := updates[ExcelBPSAutoMoveOn403Key] _, targetChanged := updates[ExcelBPS403TargetGroupIDKey] _, bpsChanged := updates["openai_excel_bps"] @@ -1193,7 +1211,7 @@ func (s *adminServiceImpl) BulkUpdateAccounts(ctx context.Context, input *BulkUp // 预取所有目标账号,供凭据守卫/代理守卫/混合渠道检查共用,避免多次 DB 查询。 var cachedTargets []*Account - if len(input.Credentials) > 0 || input.ProxyID != nil || needMixedChannelCheck || openAISettings.any() || input.ProbeEnabled != nil || input.RateMultiplier != nil { + if len(input.Credentials) > 0 || input.ProxyID != nil || needMixedChannelCheck || openAISettings.any() || input.ProbeEnabled != nil || input.RateMultiplier != nil || hasExcelBPSProxyUpdates(input.Extra) { loaded, err := s.accountRepo.GetByIDs(ctx, input.AccountIDs) if err != nil { return nil, err @@ -1213,6 +1231,28 @@ func (s *adminServiceImpl) BulkUpdateAccounts(ctx context.Context, input *BulkUp } result.LongContextInheritedCount = inheritedCount } + if hasExcelBPSProxyUpdates(input.Extra) || len(input.Credentials) > 0 { + for _, accountID := range input.AccountIDs { + account := targetsByID[accountID] + if account == nil { + return nil, ErrAccountNotFound + } + merged := *account + merged.Credentials = maps.Clone(account.Credentials) + if merged.Credentials == nil { + merged.Credentials = make(map[string]any) + } + maps.Copy(merged.Credentials, input.Credentials) + merged.Extra = maps.Clone(account.Extra) + if merged.Extra == nil { + merged.Extra = make(map[string]any) + } + maps.Copy(merged.Extra, input.Extra) + if err := s.validateExcelBPSProxySettingsChange(ctx, account, &merged); err != nil { + return nil, err + } + } + } _, moveChanged := input.Extra[ExcelBPSAutoMoveOn403Key] _, targetChanged := input.Extra[ExcelBPS403TargetGroupIDKey] _, bpsChanged := input.Extra["openai_excel_bps"] diff --git a/backend/internal/service/admin_account_request_proxy_upstream_merge_test.go b/backend/internal/service/admin_account_request_proxy_upstream_merge_test.go new file mode 100644 index 000000000000..3940beca83e2 --- /dev/null +++ b/backend/internal/service/admin_account_request_proxy_upstream_merge_test.go @@ -0,0 +1,95 @@ +//go:build unit + +package service + +import ( + "context" + "encoding/json" + "net/http" + "testing" + + infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" + "github.com/stretchr/testify/require" +) + +type requestProxyUpstreamMergeRepo struct { + *upstreamBillingProbeAccountRepo + atomicCreates int + ordinaryCreates int + bindCalls int + initialGroupIDs []int64 + initialPolicy *OAuthAPIKeyDispositionConfig + atomicGroups []AccountGroup +} + +func (r *requestProxyUpstreamMergeRepo) Create(ctx context.Context, account *Account) error { + r.ordinaryCreates++ + return r.upstreamBillingProbeAccountRepo.Create(ctx, account) +} + +func (r *requestProxyUpstreamMergeRepo) BindGroups(_ context.Context, _ int64, _ []int64) error { + r.bindCalls++ + return nil +} + +func (r *requestProxyUpstreamMergeRepo) CreateWithAccountGroups(ctx context.Context, account *Account, groups []AccountGroup) error { + r.atomicCreates++ + r.initialGroupIDs = append([]int64(nil), account.GroupIDs...) + r.initialPolicy = account.InitialAPIKeyDisposition + r.atomicGroups = append([]AccountGroup(nil), groups...) + return r.upstreamBillingProbeAccountRepo.Create(ctx, account) +} + +func TestAdminCreateRequestProxyPreservesAtomicAPIKeyDisposition(t *testing.T) { + for _, tc := range []struct { + name string + proxyID int64 + valid bool + }{ + {name: "valid proxy preserves initial groups and policy", proxyID: 11, valid: true}, + {name: "missing proxy rejects before any write", proxyID: 99}, + } { + t.Run(tc.name, func(t *testing.T) { + cfg := DefaultOAuthAutoConfig() + cfg.Enabled = true + cfg.GroupIDs = []int64{5} + cfg.APIKeyDisposition.Enabled = true + cfg.APIKeyDisposition.AccountIDs = []int64{7} + raw, err := json.Marshal(cfg) + require.NoError(t, err) + repo := &requestProxyUpstreamMergeRepo{upstreamBillingProbeAccountRepo: &upstreamBillingProbeAccountRepo{}} + svc := &adminServiceImpl{ + accountRepo: repo, + accountDuplicateRepo: repo, + settingService: NewSettingService(&accountOpsSettingsStub{raw: string(raw)}, nil), + groupRepo: autoConfigGroups{group: &Group{ID: 5, Platform: PlatformOpenAI, Status: StatusActive}}, + proxyRepo: &bpsProxyConfigProxies{proxies: []Proxy{{ID: 11, Status: StatusActive}}}, + } + + created, err := svc.CreateAccount(t.Context(), &CreateAccountInput{ + Name: "request proxy account", Platform: PlatformOpenAI, Type: AccountTypeOAuth, + SkipDefaultGroupBind: true, SkipMixedChannelCheck: true, + Extra: map[string]any{OpenAIProxyModeKey: OpenAIProxyModeRequest, OpenAIProxyIDsKey: []int64{tc.proxyID}}, + }) + + if !tc.valid { + require.Equal(t, http.StatusBadRequest, infraerrors.Code(err)) + require.Zero(t, repo.atomicCreates) + require.Zero(t, repo.ordinaryCreates) + require.Zero(t, repo.bindCalls) + return + } + require.NoError(t, err) + require.True(t, created.OpenAIRequestProxyEnabled()) + require.Equal(t, []int64{5}, created.GroupIDs) + require.Equal(t, 1, repo.atomicCreates) + require.Zero(t, repo.ordinaryCreates) + require.Zero(t, repo.bindCalls) + require.Equal(t, []int64{5}, repo.initialGroupIDs, "initial account groups must be available at the atomic create boundary") + require.NotNil(t, repo.initialPolicy) + require.Equal(t, []int64{7}, repo.initialPolicy.AccountIDs) + require.Equal(t, 180, repo.initialPolicy.PauseMinutes) + require.Equal(t, []AccountGroup{{GroupID: 5, Priority: 50}}, repo.atomicGroups) + }) + } +} diff --git a/backend/internal/service/admin_account_upstream_billing_probe_test.go b/backend/internal/service/admin_account_upstream_billing_probe_test.go index 42988062c3c3..092742552f27 100644 --- a/backend/internal/service/admin_account_upstream_billing_probe_test.go +++ b/backend/internal/service/admin_account_upstream_billing_probe_test.go @@ -705,7 +705,16 @@ func TestBulkUpdateAccountsRejectsProbeSettingWhenTargetIsMissing(t *testing.T) } func TestBulkUpdateAccountsInvalidatesProbeSnapshotForIdentityCredentials(t *testing.T) { - repo := &upstreamBillingProbeAccountRepo{} + repo := &upstreamBillingProbeAccountRepo{accounts: map[int64]*Account{ + 1: { + ID: 1, + Platform: PlatformOpenAI, + Type: AccountTypeAPIKey, + Status: StatusActive, + Credentials: map[string]any{"api_key": "sk-existing"}, + Extra: map[string]any{UpstreamBillingProbeExtraKey: map[string]any{"status": "ok"}}, + }, + }} input := &BulkUpdateAccountsInput{ AccountIDs: []int64{1}, Credentials: map[string]any{"api_key": "sk-new"}, @@ -738,7 +747,16 @@ func TestBulkUpdateAccountsInvalidatesProbeSnapshotForProxyUpdate(t *testing.T) } func TestBulkUpdateAccountsKeepsProbeSnapshotForUnrelatedCredentials(t *testing.T) { - repo := &upstreamBillingProbeAccountRepo{} + repo := &upstreamBillingProbeAccountRepo{accounts: map[int64]*Account{ + 1: { + ID: 1, + Platform: PlatformOpenAI, + Type: AccountTypeAPIKey, + Status: StatusActive, + Credentials: map[string]any{"api_key": "sk-existing"}, + Extra: map[string]any{UpstreamBillingProbeExtraKey: map[string]any{"status": "ok"}}, + }, + }} input := &BulkUpdateAccountsInput{ AccountIDs: []int64{1}, Credentials: map[string]any{"model_mapping": map[string]any{"gpt-old": "gpt-new"}}, diff --git a/backend/internal/service/openai_auth_connection_oauth.go b/backend/internal/service/openai_auth_connection_oauth.go index 7e729cc89630..d5b476c542a8 100644 --- a/backend/internal/service/openai_auth_connection_oauth.go +++ b/backend/internal/service/openai_auth_connection_oauth.go @@ -21,6 +21,17 @@ type openAIConnectionTokenClient interface { RevokeConnectionToken(context.Context, string, string, string) error } +func (s *OpenAIOAuthReauthService) validateConnectionMaintenanceProxyMode(ctx context.Context, accountID int64) error { + account, err := s.connectionAccount(ctx, accountID) + if err != nil { + return err + } + if account.OpenAIRequestProxyEnabled() { + return infraerrors.BadRequest("OPENAI_PROXY_CONNECTION_UNSUPPORTED", "Switch to single proxy mode before managing a fixed authorization connection") + } + return nil +} + func (s *OpenAIOAuthReauthService) readConnectionCredentials(c *OpenAIAuthConnection) (map[string]any, error) { if c.CredentialsCiphertext == "" { return map[string]any{}, nil @@ -63,6 +74,9 @@ func (s *OpenAIOAuthReauthService) BeginConnectionAuthorization(ctx context.Cont if _, err := s.managementConnectionAccount(ctx, accountID); err != nil { return nil, err } + if err := s.validateConnectionMaintenanceProxyMode(ctx, accountID); err != nil { + return nil, err + } c, err := s.authConnection(ctx, accountID, id) if err != nil { return nil, err @@ -149,6 +163,9 @@ func (s *OpenAIOAuthReauthService) CompleteConnectionAuthorization(ctx context.C if _, err := s.managementConnectionAccount(ctx, accountID); err != nil { return err } + if err := s.validateConnectionMaintenanceProxyMode(ctx, accountID); err != nil { + return err + } c, err := s.authConnection(ctx, accountID, id) if err != nil { return err @@ -295,6 +312,9 @@ func connectionCapabilities(kind, scope string) []string { } func (s *OpenAIOAuthReauthService) ConnectionAccessToken(ctx context.Context, accountID int64, id string) (string, error) { + if err := s.validateConnectionMaintenanceProxyMode(ctx, accountID); err != nil { + return "", err + } c, err := s.authConnection(ctx, accountID, id) if err != nil { return "", err @@ -448,6 +468,9 @@ func (s *OpenAIOAuthReauthService) RevokeAuthConnection(ctx context.Context, acc if _, err := s.managementConnectionAccount(ctx, accountID); err != nil { return false, err } + if err := s.validateConnectionMaintenanceProxyMode(ctx, accountID); err != nil { + return false, err + } lease, err := s.lockAuthConnection(ctx, accountID, id) if err != nil { return false, err diff --git a/backend/internal/service/openai_codex_models_request_proxy_test.go b/backend/internal/service/openai_codex_models_request_proxy_test.go new file mode 100644 index 000000000000..5263d7c37ccd --- /dev/null +++ b/backend/internal/service/openai_codex_models_request_proxy_test.go @@ -0,0 +1,136 @@ +package service + +import ( + "context" + "net" + "net/http" + "net/http/httptest" + "net/url" + "strconv" + "sync/atomic" + "testing" + + "github.com/stretchr/testify/require" +) + +type codexModelsRequestProxyRepo struct { + ProxyRepository + proxies map[int64]*Proxy +} + +func (r *codexModelsRequestProxyRepo) GetByID(_ context.Context, id int64) (*Proxy, error) { + return r.proxies[id], nil +} + +func codexModelsProxyRecord(t *testing.T, id int64, raw string) *Proxy { + t.Helper() + u, err := url.Parse(raw) + require.NoError(t, err) + host, port, err := net.SplitHostPort(u.Host) + require.NoError(t, err) + number, err := strconv.Atoi(port) + require.NoError(t, err) + return &Proxy{ID: id, Protocol: u.Scheme, Host: host, Port: number, Status: StatusActive} +} + +func TestFetchCodexModelsManifestRequestProxyReplacesSingleAndIsolatesCache(t *testing.T) { + var directCalls, singleCalls, selectedCalls, replacementCalls atomic.Int32 + server := func(name string, calls *atomic.Int32) *httptest.Server { + return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + calls.Add(1) + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"models":[{"slug":"` + name + `"}]}`)) + })) + } + origin := server("direct", &directCalls) + defer origin.Close() + single := server("single", &singleCalls) + defer single.Close() + selected := server("selected", &selectedCalls) + defer selected.Close() + replacement := server("replacement", &replacementCalls) + defer replacement.Close() + originalURL := chatgptCodexModelsURL + chatgptCodexModelsURL = origin.URL + t.Cleanup(func() { chatgptCodexModelsURL = originalURL }) + + singleProxy := codexModelsProxyRecord(t, 10, single.URL) + selectedProxy := codexModelsProxyRecord(t, 20, selected.URL) + replacementProxy := codexModelsProxyRecord(t, 30, replacement.URL) + repo := &codexModelsRequestProxyRepo{proxies: map[int64]*Proxy{10: singleProxy, 20: selectedProxy, 30: replacementProxy}} + svc := &OpenAIGatewayService{proxyRepo: repo} + account := newCodexModelsTestAccount() + account.ProxyID, account.Proxy = &singleProxy.ID, singleProxy + fetch := func(want string) { + t.Helper() + manifest, err := svc.FetchCodexModelsManifest(context.Background(), account, "0.137.0", "") + require.NoError(t, err) + require.JSONEq(t, `{"models":[{"slug":"`+want+`"}]}`, string(manifest.Body)) + } + fetch("single") + account.Extra = map[string]any{"openai_proxy_mode": "request", "openai_proxy_ids": []int64{20}} + fetch("selected") + fetch("selected") + account.Extra["openai_proxy_ids"] = []int64{30} + fetch("replacement") + require.Equal(t, int32(0), directCalls.Load()) + require.Equal(t, int32(1), singleCalls.Load()) + require.Equal(t, int32(1), selectedCalls.Load()) + require.Equal(t, int32(1), replacementCalls.Load()) + require.Equal(t, int64(10), *account.ProxyID) + + // A previously cached success cannot hide a now-unavailable saved group. + replacementProxy.Status = StatusDisabled + _, err := svc.FetchCodexModelsManifest(context.Background(), account, "0.137.0", "") + require.ErrorContains(t, err, "direct fallback is disabled") + require.Equal(t, int32(0), directCalls.Load()) + require.Equal(t, int32(1), singleCalls.Load()) + require.Equal(t, int32(1), replacementCalls.Load()) +} + +func TestFetchCodexModelsManifestRequestProxyUnavailableDoesNotSend(t *testing.T) { + var directCalls atomic.Int32 + origin := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + directCalls.Add(1) + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"models":[]}`)) + })) + defer origin.Close() + originalURL := chatgptCodexModelsURL + chatgptCodexModelsURL = origin.URL + t.Cleanup(func() { chatgptCodexModelsURL = originalURL }) + account := newCodexModelsTestAccount() + account.Extra = map[string]any{"openai_proxy_mode": "request", "openai_proxy_ids": []int64{404}} + svc := &OpenAIGatewayService{proxyRepo: &codexModelsRequestProxyRepo{}} + _, err := svc.FetchCodexModelsManifest(context.Background(), account, "0.137.0", "") + require.ErrorContains(t, err, "direct fallback is disabled") + require.Zero(t, directCalls.Load()) +} + +func TestFetchCodexModelsManifestRequestProxyOwnsTransportAndCachePolicy(t *testing.T) { + var calls atomic.Int32 + proxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + calls.Add(1) + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"models":[]}`)) + })) + defer proxy.Close() + originalURL := chatgptCodexModelsURL + chatgptCodexModelsURL = "http://models.fixture.invalid/backend-api/codex/models" + t.Cleanup(func() { chatgptCodexModelsURL = originalURL }) + record := codexModelsProxyRecord(t, 20, proxy.URL) + svc := &OpenAIGatewayService{proxyRepo: &codexModelsRequestProxyRepo{proxies: map[int64]*Proxy{20: record}}} + account := newCodexModelsTestAccount() + account.ProxyID, account.Proxy = &record.ID, record + _, err := svc.FetchCodexModelsManifest(context.Background(), account, "0.137.0", "") + require.NoError(t, err) + require.Equal(t, int32(1), calls.Load()) + + manager := &PluginManager{} + manager.route.Store(&pluginRoute{rolloutPercent: 100, unavailable: "fixture plugin unavailable"}) + svc.pluginManager = manager + account.Extra = map[string]any{"openai_proxy_mode": "request", "openai_proxy_ids": []int64{20}} + _, err = svc.FetchCodexModelsManifest(context.Background(), account, "0.137.0", "") + require.NoError(t, err, "request proxies keep the selected native transport") + require.Equal(t, int32(2), calls.Load(), "the old single-mode cache cannot conceal a different transport policy") +} diff --git a/backend/internal/service/openai_codex_models_service.go b/backend/internal/service/openai_codex_models_service.go index 6c6c44f2b094..8028c8cda9d4 100644 --- a/backend/internal/service/openai_codex_models_service.go +++ b/backend/internal/service/openai_codex_models_service.go @@ -1642,6 +1642,7 @@ type openAIModelsRequest struct { credentialAccount *Account accountConcurrency int useAPIKeyUpstream bool + requestProxy bool // Cached bodies have already been converted to their requested format. standardModelsList bool } @@ -1825,7 +1826,13 @@ func (s *OpenAIGatewayService) fetchNativeCodexModelsManifest(ctx context.Contex headers.Set("Version", headerVersion) proxyURL := "" - if account.ProxyID != nil && account.Proxy != nil { + requestProxy := account.OpenAIRequestProxyEnabled() + if requestProxy { + proxyURL, err = resolveOpenAIMaintenanceProxy(ctx, account, s.proxyRepo) + if err != nil { + return nil, err + } + } else if account.ProxyID != nil && account.Proxy != nil { proxyURL = account.Proxy.URL() } @@ -1838,6 +1845,7 @@ func (s *OpenAIGatewayService) fetchNativeCodexModelsManifest(ctx context.Contex credentialAccount: credAccount, accountConcurrency: account.Concurrency, useAPIKeyUpstream: useAPIKeyUpstream, + requestProxy: requestProxy, } if !useCache { request.headers.Del("If-None-Match") @@ -2030,7 +2038,9 @@ func (s *OpenAIGatewayService) fetchOpenAIModelsUpstream(ctx context.Context, re resp, err = s.httpUpstream.Do(req, request.proxyURL, request.accountID, request.accountConcurrency) } else { handled := false - if s.pluginManager != nil { + // Account-selected proxies own this egress; external plugins can supply + // their own transport and cannot enforce membership in the saved group. + if s.pluginManager != nil && !request.requestProxy { resp, handled, err = s.pluginManager.RoundTripOpenAIOAuth(reqCtx, req, request.proxyURL, request.credentialAccount) } if !handled { @@ -2669,7 +2679,7 @@ func validateCodexModelsManifestEnvelope(body []byte) error { func buildOpenAIModelsCacheKey(request openAIModelsRequest) string { hasher := sha256.New() - _, _ = fmt.Fprintf(hasher, "%d\n%d\n%t\n%s\n%s\n", request.accountID, request.credentialAccountID, request.standardModelsList, request.proxyURL, request.url) + _, _ = fmt.Fprintf(hasher, "%d\n%d\n%t\n%t\n%s\n%s\n", request.accountID, request.credentialAccountID, request.standardModelsList, request.requestProxy, request.proxyURL, request.url) headerNames := make([]string, 0, len(request.headers)) for name := range request.headers { headerNames = append(headerNames, name) diff --git a/backend/internal/service/openai_excel_bps.go b/backend/internal/service/openai_excel_bps.go index b26a943ead07..d3377da7fcad 100644 --- a/backend/internal/service/openai_excel_bps.go +++ b/backend/internal/service/openai_excel_bps.go @@ -467,7 +467,7 @@ func (s *OpenAIGatewayService) forwardExcelBPS(ctx context.Context, c *gin.Conte if account.Proxy != nil { attachmentProxy = account.Proxy.URL() } - if images != nil && images.HasImages() && account.IsExcelBPSMihomoEnabled() { + if images != nil && images.HasImages() && (account.IsExcelBPSMihomoEnabled() || account.ExcelBPSRequestProxyEnabled()) { var lease excelBPSLease // Pin the attachment upload and the Responses request to the same exit, // whichever pool the account chose. @@ -858,6 +858,9 @@ func (s *OpenAIGatewayService) forwardExcelBPS(ctx context.Context, c *gin.Conte if len(compactOutput) > 0 { converted = basispoints.WithCompactedWindow(requestCtx, converted, compactOutput, compactUsageWire) } + if account.ExcelBPSRequestProxyEnabled() { + converted = ownExcelBPSRequestBody(ctx, converted, lease) + } defer func() { _ = converted.Close() }() // The bridge sees the body after group policy mapping. Keep the original // client effort for usage display, and the BPS-normalized effort for billing. diff --git a/backend/internal/service/openai_excel_bps_images.go b/backend/internal/service/openai_excel_bps_images.go index 90574a03aeb6..aab9eb8ece49 100644 --- a/backend/internal/service/openai_excel_bps_images.go +++ b/backend/internal/service/openai_excel_bps_images.go @@ -274,6 +274,9 @@ func (s *OpenAIGatewayService) forwardExcelBPSImages(ctx context.Context, c *gin if lease != nil { defer lease.Release() } + if account.ExcelBPSRequestProxyEnabled() { + resp.Body = ownExcelBPSRequestBody(ctx, resp.Body, lease) + } defer func() { _ = resp.Body.Close() }() if resp.StatusCode < 200 || resp.StatusCode >= 300 { diff --git a/backend/internal/service/openai_excel_bps_model_access.go b/backend/internal/service/openai_excel_bps_model_access.go index 98c19d283a3c..1ceb7eeb37a9 100644 --- a/backend/internal/service/openai_excel_bps_model_access.go +++ b/backend/internal/service/openai_excel_bps_model_access.go @@ -127,7 +127,7 @@ func (s *OpenAIGatewayService) FetchExcelBPSModelsList(ctx context.Context, acco fetchCtx, cancel := context.WithTimeout(fetchCtx, 5*time.Second) defer cancel() var lease excelBPSLease - if account.IsExcelBPSMihomoEnabled() { + if account.IsExcelBPSMihomoEnabled() || account.ExcelBPSRequestProxyEnabled() { proxy, lease, err = s.excelBPSAcquireFor(account)(fetchCtx, fmt.Sprintf("transient:bps-models:%d", account.ID)) if err != nil { return nil, fmt.Errorf("excel BPS discovery proxy is unavailable") diff --git a/backend/internal/service/openai_excel_bps_proxy_config.go b/backend/internal/service/openai_excel_bps_proxy_config.go new file mode 100644 index 000000000000..7d80e377ec1c --- /dev/null +++ b/backend/internal/service/openai_excel_bps_proxy_config.go @@ -0,0 +1,179 @@ +package service + +import ( + "context" + "encoding/json" + "maps" + "math" + "slices" + "time" + + infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" +) + +const ( + ExcelBPSProxyModeKey = "openai_excel_bps_proxy_mode" + ExcelBPSProxyIDsKey = "openai_excel_bps_proxy_ids" + ExcelBPSProxyModeSession = "session" + ExcelBPSProxyModeRequest = "request" +) + +// ExcelBPSRequestProxyEnabled selects an explicit account-owned IP group. An +// invalid/empty stored group still selects this mode so runtime can fail closed. +func (a *Account) ExcelBPSRequestProxyEnabled() bool { + return a != nil && a.IsExcelBPSEnabled() && a.OpenAIRequestProxyEnabled() +} + +func (a *Account) ExcelBPSRequestProxyIDs() []int64 { + return a.OpenAIRequestProxyIDs() +} + +func parseExcelBPSProxyIDs(raw any) ([]int64, bool) { + var values []any + switch v := raw.(type) { + case nil: + return nil, true + case []int64: + for _, id := range v { + values = append(values, id) + } + case []int: + for _, id := range v { + values = append(values, id) + } + case []any: + values = v + default: + return nil, false + } + ids := make([]int64, 0, len(values)) + seen := make(map[int64]bool, len(values)) + for _, rawID := range values { + var id int64 + switch value := rawID.(type) { + case int: + id = int64(value) + case int64: + id = value + case float64: + if math.IsNaN(value) || math.IsInf(value, 0) || value != math.Trunc(value) || value > 9007199254740991 { + return nil, false + } + id = int64(value) + case json.Number: + var err error + id, err = value.Int64() + if err != nil { + return nil, false + } + default: + return nil, false + } + if id <= 0 { + return nil, false + } + if !seen[id] { + ids = append(ids, id) + seen[id] = true + } + } + return ids, true +} + +func hasExcelBPSProxyUpdates(extra map[string]any) bool { + _, mode := extra[ExcelBPSProxyModeKey] + _, ids := extra[ExcelBPSProxyIDsKey] + _, enabled := extra["openai_excel_bps"] + _, openAIMode := extra[OpenAIProxyModeKey] + _, openAIIDs := extra[OpenAIProxyIDsKey] + return mode || ids || enabled || openAIMode || openAIIDs +} + +func preserveExcelBPSProxyExtra(existing, incoming map[string]any) map[string]any { + for _, key := range []string{ExcelBPSProxyModeKey, ExcelBPSProxyIDsKey, OpenAIProxyModeKey, OpenAIProxyIDsKey} { + if _, supplied := incoming[key]; !supplied { + if value, ok := existing[key]; ok { + if incoming == nil { + incoming = make(map[string]any) + } + incoming[key] = value + } + } + } + return incoming +} + +func (s *adminServiceImpl) validateExcelBPSProxySettings(ctx context.Context, account *Account) error { + return s.validateExcelBPSProxySettingsChange(ctx, nil, account) +} + +func (s *adminServiceImpl) validateExcelBPSProxySettingsChange(ctx context.Context, previous, account *Account) error { + if err := s.validateOpenAIProxySettingsChange(ctx, previous, account); err != nil { + return err + } + if _, explicit := account.Extra[OpenAIProxyModeKey]; explicit { + return nil + } + mode, supplied := account.Extra[ExcelBPSProxyModeKey] + if supplied && mode != ExcelBPSProxyModeSession && mode != ExcelBPSProxyModeRequest { + return infraerrors.BadRequest("INVALID_BPS_PROXY_MODE", "BPS proxy mode must be session or request") + } + ids, valid := parseExcelBPSProxyIDs(account.Extra[ExcelBPSProxyIDsKey]) + if !valid { + return infraerrors.BadRequest("INVALID_BPS_PROXY_IDS", "BPS proxy IDs must be positive integers") + } + if !supplied && len(ids) == 0 { + return nil + } + if account.Platform != PlatformOpenAI || account.Type != AccountTypeOAuth || account.IsShadow() || account.IsOpenAIAgentIdentity() || account.IsOpenAIPersonalAccessToken() { + return infraerrors.BadRequest("INVALID_BPS_PROXY_ACCOUNT", "BPS request proxies require an OpenAI OAuth account") + } + if mode == ExcelBPSProxyModeRequest { + if err := s.validateOpenAIRequestProxyConnection(ctx, previous, account); err != nil { + return err + } + } + if mode == ExcelBPSProxyModeRequest && len(ids) == 0 { + return infraerrors.BadRequest("BPS_PROXY_GROUP_REQUIRED", "select at least one BPS proxy") + } + if len(ids) == 0 || mode != ExcelBPSProxyModeRequest { + return nil + } + // Removing an exit must not prevent unrelated edits or turning the feature + // off. Existing request groups remain explicit so forwarding still fails + // closed; a changed group or newly activated feature must resolve every ID. + if previous != nil && previous.Extra[ExcelBPSProxyModeKey] == mode && + slices.Equal(previous.ExcelBPSRequestProxyIDs(), ids) && + (previous.ExcelBPSRequestProxyEnabled() || !account.ExcelBPSRequestProxyEnabled()) { + return nil + } + if s.proxyRepo == nil { + return infraerrors.BadRequest("BPS_PROXY_NOT_FOUND", "selected BPS proxy not found") + } + proxies, err := s.proxyRepo.ListByIDs(ctx, ids) + if err != nil { + return err + } + now := time.Now() + found := make(map[int64]bool, len(proxies)) + for _, proxy := range proxies { + found[proxy.ID] = proxy.IsActive() && !proxy.IsExpired(now) + } + for _, id := range ids { + if !found[id] { + return infraerrors.BadRequest("BPS_PROXY_NOT_FOUND", "selected BPS proxy not found") + } + } + account.Extra[ExcelBPSProxyIDsKey] = ids + return nil +} + +func (s *adminServiceImpl) validateExcelBPSProxyUpdates(ctx context.Context, account *Account, updates map[string]any) error { + merged := *account + merged.Extra = maps.Clone(account.Extra) + if merged.Extra == nil { + merged.Extra = make(map[string]any) + } + maps.Copy(merged.Extra, updates) + return s.validateExcelBPSProxySettingsChange(ctx, account, &merged) +} diff --git a/backend/internal/service/openai_excel_bps_proxy_config_test.go b/backend/internal/service/openai_excel_bps_proxy_config_test.go new file mode 100644 index 000000000000..50858d1c10b2 --- /dev/null +++ b/backend/internal/service/openai_excel_bps_proxy_config_test.go @@ -0,0 +1,187 @@ +//go:build unit + +package service + +import ( + "context" + "net/http" + "testing" + "time" + + infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" + "github.com/stretchr/testify/require" +) + +func TestAdminCreateBPSRequestProxyRejectsEmptyGroup(t *testing.T) { + svc := &adminServiceImpl{accountRepo: &longContextBillingRepoStub{}} + _, err := svc.CreateAccount(context.Background(), &CreateAccountInput{ + Platform: PlatformOpenAI, Type: AccountTypeOAuth, SkipDefaultGroupBind: true, + Extra: map[string]any{"openai_excel_bps": true, "openai_excel_bps_proxy_mode": "request"}, + }) + require.Equal(t, http.StatusBadRequest, infraerrors.Code(err)) +} + +type bpsProxyConfigRepo struct { + longContextBillingRepoStub +} + +func (r *bpsProxyConfigRepo) UpdateExtra(_ context.Context, _ int64, updates map[string]any) error { + for key, value := range updates { + r.account.Extra[key] = value + } + return nil +} + +type bpsProxyConfigProxies struct { + ProxyRepository + proxies []Proxy +} + +func (r *bpsProxyConfigProxies) ListByIDs(_ context.Context, ids []int64) ([]Proxy, error) { + var proxies []Proxy + for _, proxy := range r.proxies { + for _, id := range ids { + if proxy.ID == id { + proxies = append(proxies, proxy) + break + } + } + } + return proxies, nil +} + +func newBPSProxyConfigService() (*adminServiceImpl, *bpsProxyConfigRepo) { + repo := &bpsProxyConfigRepo{} + return &adminServiceImpl{accountRepo: repo, proxyRepo: &bpsProxyConfigProxies{proxies: []Proxy{{ID: 11, Status: StatusActive}, {ID: 22, Status: StatusActive}}}}, repo +} + +func TestAdminBPSRequestProxyConfigurationRoundTrip(t *testing.T) { + svc, _ := newBPSProxyConfigService() + account, err := svc.CreateAccount(context.Background(), &CreateAccountInput{ + Name: "bps account", Platform: PlatformOpenAI, Type: AccountTypeOAuth, SkipDefaultGroupBind: true, Concurrency: 6, + Extra: map[string]any{"openai_excel_bps": true, ExcelBPSProxyModeKey: "request", ExcelBPSProxyIDsKey: []any{float64(11), float64(22), float64(11)}}, + }) + require.NoError(t, err) + saved, err := svc.GetAccount(context.Background(), account.ID) + require.NoError(t, err) + require.True(t, saved.ExcelBPSRequestProxyEnabled()) + require.Equal(t, []int64{11, 22}, saved.ExcelBPSRequestProxyIDs()) + require.Equal(t, 6, saved.Concurrency) + + // An older form does not own the newly introduced keys. + _, err = svc.UpdateAccount(context.Background(), account.ID, &UpdateAccountInput{Extra: map[string]any{"openai_excel_bps": true}}) + require.NoError(t, err) + saved, err = svc.GetAccount(context.Background(), account.ID) + require.NoError(t, err) + require.True(t, saved.ExcelBPSRequestProxyEnabled()) + require.Equal(t, []int64{11, 22}, saved.ExcelBPSRequestProxyIDs()) + + err = svc.UpdateAccountExtra(context.Background(), account.ID, map[string]any{ExcelBPSProxyIDsKey: []any{float64(22)}}) + require.NoError(t, err) + saved, err = svc.GetAccount(context.Background(), account.ID) + require.NoError(t, err) + require.Equal(t, []int64{22}, saved.ExcelBPSRequestProxyIDs()) +} + +func TestAdminBPSRequestProxyRejectsInvalidConfiguration(t *testing.T) { + for _, tc := range []struct { + name string + mode any + ids any + platform string + accountType string + }{ + {"unknown mode", "round-robin", []any{float64(11)}, PlatformOpenAI, AccountTypeOAuth}, + {"null mode", nil, []any{float64(11)}, PlatformOpenAI, AccountTypeOAuth}, + {"fractional ID", "request", []any{11.5}, PlatformOpenAI, AccountTypeOAuth}, + {"string ID", "request", []any{"11"}, PlatformOpenAI, AccountTypeOAuth}, + {"missing ID", "request", []any{float64(99)}, PlatformOpenAI, AccountTypeOAuth}, + {"negative ID", "request", []any{float64(-1)}, PlatformOpenAI, AccountTypeOAuth}, + {"non OAuth", "request", []any{float64(11)}, PlatformOpenAI, AccountTypeAPIKey}, + {"other platform", "request", []any{float64(11)}, PlatformGrok, AccountTypeOAuth}, + } { + t.Run(tc.name, func(t *testing.T) { + svc, _ := newBPSProxyConfigService() + _, err := svc.CreateAccount(context.Background(), &CreateAccountInput{Platform: tc.platform, Type: tc.accountType, SkipDefaultGroupBind: true, Extra: map[string]any{ExcelBPSProxyModeKey: tc.mode, ExcelBPSProxyIDsKey: tc.ids}}) + require.Equal(t, http.StatusBadRequest, infraerrors.Code(err)) + }) + } +} + +func TestAdminBPSRequestProxyPartialAndBulkValidateMergedConfiguration(t *testing.T) { + for _, bulk := range []bool{false, true} { + svc, repo := newBPSProxyConfigService() + repo.account = &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Extra: map[string]any{ExcelBPSProxyModeKey: "request", ExcelBPSProxyIDsKey: []int64{11}}} + var err error + if bulk { + _, err = svc.BulkUpdateAccounts(context.Background(), &BulkUpdateAccountsInput{AccountIDs: []int64{1}, Extra: map[string]any{ExcelBPSProxyIDsKey: []any{}}}) + } else { + err = svc.UpdateAccountExtra(context.Background(), 1, map[string]any{ExcelBPSProxyIDsKey: []any{}}) + } + require.Equal(t, http.StatusBadRequest, infraerrors.Code(err)) + saved, err := svc.GetAccount(context.Background(), 1) + require.NoError(t, err) + require.Equal(t, []int64{11}, saved.ExcelBPSRequestProxyIDs()) + } +} + +func TestAdminBPSRequestProxyRejectsNewInactiveOrExpiredExit(t *testing.T) { + expired := time.Now().Add(-time.Minute) + for _, proxy := range []Proxy{{ID: 11, Status: StatusDisabled}, {ID: 11, Status: StatusActive, ExpiresAt: &expired}} { + svc, _ := newBPSProxyConfigService() + svc.proxyRepo = &bpsProxyConfigProxies{proxies: []Proxy{proxy}} + _, err := svc.CreateAccount(context.Background(), &CreateAccountInput{Platform: PlatformOpenAI, Type: AccountTypeOAuth, SkipDefaultGroupBind: true, Extra: map[string]any{"openai_excel_bps": true, ExcelBPSProxyModeKey: ExcelBPSProxyModeRequest, ExcelBPSProxyIDsKey: []int64{11}}}) + require.Equal(t, http.StatusBadRequest, infraerrors.Code(err)) + } +} + +func TestAdminBPSRequestProxyMissingExitCanBeEditedOrDisabled(t *testing.T) { + for _, tc := range []struct { + name string + input *UpdateAccountInput + }{ + {"unrelated edit", &UpdateAccountInput{Name: "renamed"}}, + {"older form", &UpdateAccountInput{Extra: map[string]any{"openai_excel_bps": true}}}, + {"disable BPS", &UpdateAccountInput{Extra: map[string]any{"openai_excel_bps": false}}}, + {"switch to session", &UpdateAccountInput{Extra: map[string]any{"openai_excel_bps": true, ExcelBPSProxyModeKey: ExcelBPSProxyModeSession}}}, + } { + t.Run(tc.name, func(t *testing.T) { + svc, repo := newBPSProxyConfigService() + repo.account = &Account{ID: 1, Name: "bps", Platform: PlatformOpenAI, Type: AccountTypeOAuth, Extra: map[string]any{"openai_excel_bps": true, ExcelBPSProxyModeKey: ExcelBPSProxyModeRequest, ExcelBPSProxyIDsKey: []int64{99}}} + _, err := svc.UpdateAccount(context.Background(), 1, tc.input) + require.NoError(t, err) + saved, err := svc.GetAccount(context.Background(), 1) + require.NoError(t, err) + require.Equal(t, []int64{99}, saved.ExcelBPSRequestProxyIDs()) + if tc.name == "unrelated edit" || tc.name == "older form" { + require.True(t, saved.ExcelBPSRequestProxyEnabled(), "stale groups must still fail closed at runtime") + } else { + require.False(t, saved.ExcelBPSRequestProxyEnabled()) + } + }) + } +} + +func TestAdminBPSRequestProxyCannotActivateMissingExit(t *testing.T) { + svc, repo := newBPSProxyConfigService() + repo.account = &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Extra: map[string]any{"openai_excel_bps": false, ExcelBPSProxyModeKey: ExcelBPSProxyModeRequest, ExcelBPSProxyIDsKey: []int64{99}}} + _, err := svc.UpdateAccount(context.Background(), 1, &UpdateAccountInput{Extra: map[string]any{"openai_excel_bps": true}}) + require.Equal(t, http.StatusBadRequest, infraerrors.Code(err)) +} + +func TestAdminBPSRequestProxyPartialAndBulkCannotActivateMissingExit(t *testing.T) { + for _, bulk := range []bool{false, true} { + svc, repo := newBPSProxyConfigService() + repo.account = &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Extra: map[string]any{"openai_excel_bps": false, ExcelBPSProxyModeKey: ExcelBPSProxyModeRequest, ExcelBPSProxyIDsKey: []int64{99}}} + var err error + if bulk { + _, err = svc.BulkUpdateAccounts(context.Background(), &BulkUpdateAccountsInput{AccountIDs: []int64{1}, Extra: map[string]any{"openai_excel_bps": true}}) + } else { + err = svc.UpdateAccountExtra(context.Background(), 1, map[string]any{"openai_excel_bps": true}) + } + require.Equal(t, http.StatusBadRequest, infraerrors.Code(err)) + saved, err := svc.GetAccount(context.Background(), 1) + require.NoError(t, err) + require.False(t, saved.ExcelBPSRequestProxyEnabled()) + } +} diff --git a/backend/internal/service/openai_excel_bps_recovery.go b/backend/internal/service/openai_excel_bps_recovery.go index 8ffa683eca4b..dd1879b1846b 100644 --- a/backend/internal/service/openai_excel_bps_recovery.go +++ b/backend/internal/service/openai_excel_bps_recovery.go @@ -256,7 +256,7 @@ func (s *OpenAIGatewayService) probeExcelBPS403Recovery(ctx context.Context, acc proxy = account.Proxy.URL() } var lease excelBPSLease - if probe.IsExcelBPSMihomoEnabled() { + if probe.IsExcelBPSMihomoEnabled() || probe.ExcelBPSRequestProxyEnabled() { proxy, lease, err = s.excelBPSAcquireFor(&probe)(ctx, "transient:bps-403-recovery:"+nonce) if err != nil { return err diff --git a/backend/internal/service/openai_excel_bps_request_proxy_integration_test.go b/backend/internal/service/openai_excel_bps_request_proxy_integration_test.go new file mode 100644 index 000000000000..9e69d4cc3b8a --- /dev/null +++ b/backend/internal/service/openai_excel_bps_request_proxy_integration_test.go @@ -0,0 +1,370 @@ +//go:build bps_request_integration + +package service + +import ( + "bytes" + "context" + "fmt" + "io" + "net/http" + "net/http/httptest" + "net/url" + "strconv" + "sync" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/mihomo" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +const bpsRequestCompletedWire = "data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_local\",\"status\":\"completed\",\"output\":[],\"usage\":{\"input_tokens\":1,\"output_tokens\":1}}}\n\n" + +type requestProxyObservation struct { + id int + path string + body []byte +} + +// This adapter replaces the external HTTPS boundary with controlled local HTTP +// proxies. Selection, leases, request construction and bridge consumption stay +// on the public Forward path; no external host is resolved or contacted. +func localBPSRequestProxyFixture(t *testing.T, count int, handler func(int, http.ResponseWriter, *http.Request)) (*OpenAIGatewayService, *Account) { + t.Helper() + restore := mihomo.InstallBPSRequestIntegrationProbe(func(context.Context, string) error { return nil }) + t.Cleanup(restore) + clients := make(map[string]*http.Client, count) + proxies := make(map[int64]*Proxy, count) + records := make([]mihomo.BPSStaticProxy, 0, count) + ids := make([]int64, 0, count) + for i := 1; i <= count; i++ { + id := i + proxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { handler(id, w, r) })) + t.Cleanup(proxy.Close) + u, err := url.Parse(proxy.URL) + require.NoError(t, err) + port, err := strconv.Atoi(u.Port()) + require.NoError(t, err) + proxies[int64(i)] = &Proxy{ID: int64(i), Protocol: "http", Host: u.Hostname(), Port: port, Status: StatusActive} + tr := &http.Transport{Proxy: http.ProxyURL(u)} + t.Cleanup(tr.CloseIdleConnections) + clients[proxy.URL] = &http.Client{Transport: tr, Timeout: 10 * time.Second} + ids = append(ids, int64(i)) + records = append(records, mihomo.BPSStaticProxy{ID: int64(i), URL: proxy.URL}) + } + mihomo.SetBPSStaticProxyRecords(records) + mihomo.SetBPSStaticRequestGroups(map[int64][]int64{300: ids}) + mihomo.WarmBPSPools(t.Context(), 0, 1) + svc := openAIClientToolsTestService(nil) + svc.proxyRepo = &openAIMaintenanceProxyRepo{proxies: proxies} + svc.httpUpstream = &nativeAttachmentUpstream{do: func(r *http.Request, proxy string, _ int64, _ int) (*http.Response, error) { + client := clients[proxy] + if client == nil { + return nil, fmt.Errorf("unexpected proxy outside selected fixture") + } + local := r.Clone(r.Context()) + u := *r.URL + u.Scheme = "http" + local.URL = &u + local.RequestURI = "" + return client.Do(local) + }} + account := excelAccount() + account.Concurrency = 6 + account.Extra["openai_excel_bps_proxy_mode"] = "request" + account.Extra["openai_excel_bps_proxy_ids"] = ids + account.Extra["openai_excel_bps_mihomo"] = false + return svc, account +} + +func forwardLocalBPSRequest(ctx context.Context, svc *OpenAIGatewayService, account *Account, body []byte) (int, string, error) { + // Scheduler hydration gives each request its own Account model caches. Keep + // that contract here while sharing the account ID for actual pool load. + requestAccount := *account + requestAccount.Extra = cloneExcelBPSRecoveryExtra(account.Extra) + requestAccount.Credentials = cloneExcelBPSRecoveryExtra(account.Credentials) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewReader(body)).WithContext(ctx) + _, err := svc.Forward(ctx, c, &requestAccount, body) + return rec.Code, rec.Body.String(), err +} + +func TestExcelBPSRequestProxyForwardSameSessionDistributesSixThroughThree(t *testing.T) { + arrived := make(chan int, 6) + release := make(chan struct{}) + var releaseOnce sync.Once + t.Cleanup(func() { releaseOnce.Do(func() { close(release) }) }) + svc, account := localBPSRequestProxyFixture(t, 4, func(id int, w http.ResponseWriter, r *http.Request) { + _, _ = io.Copy(io.Discard, r.Body) + arrived <- id + select { + case <-release: + case <-r.Context().Done(): + return + } + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, bpsRequestCompletedWire) + }) + account.Extra["openai_excel_bps_proxy_ids"] = []int64{1, 2, 3} + ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second) + defer cancel() + results := make(chan error, 6) + for i := 0; i < 6; i++ { + go func() { + code, response, err := forwardLocalBPSRequest(ctx, svc, account, []byte(`{"model":"gpt-6-astra","input":"test","stream":true,"prompt_cache_key":"same-session"}`)) + if err == nil && (code != 200 || !bytes.Contains([]byte(response), []byte("response.completed"))) { + err = fmt.Errorf("incomplete local response: status %d", code) + } + results <- err + }() + } + hits := map[int]int{} + for i := 0; i < 6; i++ { + select { + case id := <-arrived: + hits[id]++ + case <-ctx.Done(): + t.Fatal("six requests did not reach local proxies") + } + } + releaseOnce.Do(func() { close(release) }) + for i := 0; i < 6; i++ { + require.NoError(t, <-results) + } + require.Equal(t, map[int]int{1: 2, 2: 2, 3: 2}, hits) +} + +func TestExcelBPSRequestProxyForwardAttachmentAndGenerationKeepOneExit(t *testing.T) { + observed := make(chan requestProxyObservation, 4) + svc, account := localBPSRequestProxyFixture(t, 3, func(id int, w http.ResponseWriter, r *http.Request) { + raw, _ := io.ReadAll(r.Body) + observed <- requestProxyObservation{id: id, path: r.URL.Path, body: raw} + if r.URL.Path == "/basispoints/api/attachments" { + _, _ = io.WriteString(w, `{"openai_file_id":"file-local"}`) + return + } + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, bpsRequestCompletedWire) + }) + enableNativeAttachments(svc) + body, _ := nativeGatewayBody(t) + code, _, err := forwardLocalBPSRequest(t.Context(), svc, account, body) + require.NoError(t, err) + require.Equal(t, 200, code) + upload, generated := <-observed, <-observed + require.Equal(t, "/basispoints/api/attachments", upload.path) + require.Equal(t, "/basispoints/api/responses", generated.path) + require.Equal(t, upload.id, generated.id) + require.Contains(t, string(generated.body), `"file_id":"file-local"`) + require.Empty(t, observed, "a logical request uploads once and generates once") +} + +func TestExcelBPSRequestProxyForwardCancellationReleasesExitWhileOtherStreamsStayBusy(t *testing.T) { + arrived := make(chan int, 4) + svc, account := localBPSRequestProxyFixture(t, 3, func(id int, w http.ResponseWriter, r *http.Request) { + _, _ = io.Copy(io.Discard, r.Body) + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, "data: {\"type\":\"response.created\",\"response\":{\"id\":\"resp_busy\",\"status\":\"in_progress\"}}\n\n") + w.(http.Flusher).Flush() + arrived <- id + <-r.Context().Done() + }) + ctx, cancel := context.WithTimeout(t.Context(), 8*time.Second) + defer cancel() + type request struct { + cancel context.CancelFunc + done chan error + proxy int + } + start := func() request { + child, stop := context.WithCancel(ctx) + done := make(chan error, 1) + go func() { + _, _, err := forwardLocalBPSRequest(child, svc, account, []byte(`{"model":"gpt-6-astra","input":"hold","stream":true,"prompt_cache_key":"same-busy-session"}`)) + done <- err + }() + select { + case id := <-arrived: + return request{cancel: stop, done: done, proxy: id} + case <-ctx.Done(): + stop() + t.Fatal("local stream did not start") + return request{} + } + } + first, second, third := start(), start(), start() + t.Cleanup(first.cancel) + t.Cleanup(second.cancel) + t.Cleanup(third.cancel) + require.ElementsMatch(t, []int{1, 2, 3}, []int{first.proxy, second.proxy, third.proxy}) + first.cancel() + select { + case <-first.done: + case <-ctx.Done(): + t.Fatal("canceled stream did not finish") + } + fourth := start() + t.Cleanup(fourth.cancel) + require.Equal(t, first.proxy, fourth.proxy, "canceled request releases its load; other selected exits remain in flight") + second.cancel() + third.cancel() + fourth.cancel() + for _, r := range []request{second, third, fourth} { + select { + case <-r.done: + case <-ctx.Done(): + t.Fatal("remaining stream did not finish") + } + } +} + +func TestExcelBPSRequestProxyForwardCompletionReleasesExitWhileOtherStreamsStayBusy(t *testing.T) { + arrived := make(chan int, 4) + upstreamClosed := make(chan struct{}, 2) + var mu sync.Mutex + calls := 0 + svc, account := localBPSRequestProxyFixture(t, 3, func(id int, w http.ResponseWriter, r *http.Request) { + _, _ = io.Copy(io.Discard, r.Body) + mu.Lock() + calls++ + order := calls + mu.Unlock() + w.Header().Set("Content-Type", "text/event-stream") + arrived <- id + if order <= 2 { + _, _ = io.WriteString(w, "data: {\"type\":\"response.created\",\"response\":{\"id\":\"resp_held\",\"status\":\"in_progress\"}}\n\n") + w.(http.Flusher).Flush() + <-r.Context().Done() + return + } + _, _ = io.WriteString(w, bpsRequestCompletedWire) + w.(http.Flusher).Flush() + <-r.Context().Done() + upstreamClosed <- struct{}{} + }) + ctx, cancel := context.WithTimeout(t.Context(), 8*time.Second) + defer cancel() + body := []byte(`{"model":"gpt-6-astra","input":"hold","stream":true}`) + done := make(chan error, 2) + for i := 0; i < 2; i++ { + go func() { _, _, err := forwardLocalBPSRequest(ctx, svc, account, body); done <- err }() + select { + case <-arrived: + case <-ctx.Done(): + t.Fatal("held request did not start") + } + } + code, _, err := forwardLocalBPSRequest(ctx, svc, account, body) + require.NoError(t, err) + require.Equal(t, 200, code) + completed := <-arrived + code, _, err = forwardLocalBPSRequest(ctx, svc, account, body) + require.NoError(t, err) + require.Equal(t, 200, code) + require.Equal(t, completed, <-arrived, "normal EOF/Close releases the completed stream, leaving the other two exits busy") + for i := 0; i < 2; i++ { + select { + case <-upstreamClosed: + case <-time.After(time.Second): + t.Fatal("completed bridge must close upstream without waiting for upstream EOF") + } + } + cancel() + for i := 0; i < 2; i++ { + select { + case <-done: + case <-time.After(time.Second): + t.Fatal("held request did not finish") + } + } +} + +func TestExcelBPSRequestProxyForwardRejectedRequestReleasesExit(t *testing.T) { + arrived := make(chan int, 4) + var mu sync.Mutex + calls := 0 + svc, account := localBPSRequestProxyFixture(t, 3, func(id int, w http.ResponseWriter, r *http.Request) { + _, _ = io.Copy(io.Discard, r.Body) + mu.Lock() + calls++ + order := calls + mu.Unlock() + arrived <- id + if order <= 2 { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, "data: {\"type\":\"response.created\",\"response\":{\"id\":\"resp_held\",\"status\":\"in_progress\"}}\n\n") + w.(http.Flusher).Flush() + <-r.Context().Done() + return + } + if order == 3 { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusBadRequest) + _, _ = io.WriteString(w, `{"error":{"code":"bad_request","message":"local fixture rejected"}}`) + return + } + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, bpsRequestCompletedWire) + }) + ctx, cancel := context.WithTimeout(t.Context(), 8*time.Second) + defer cancel() + body := []byte(`{"model":"gpt-6-astra","input":"hold","stream":true}`) + done := make(chan error, 2) + for i := 0; i < 2; i++ { + go func() { _, _, err := forwardLocalBPSRequest(ctx, svc, account, body); done <- err }() + select { + case <-arrived: + case <-ctx.Done(): + t.Fatal("held request did not start") + } + } + code, _, err := forwardLocalBPSRequest(ctx, svc, account, body) + require.Error(t, err) + require.Equal(t, http.StatusBadRequest, code) + rejected := <-arrived + code, _, err = forwardLocalBPSRequest(ctx, svc, account, body) + require.NoError(t, err) + require.Equal(t, 200, code) + require.Equal(t, rejected, <-arrived, "error-body consumption and Close release the rejected request's exit") + cancel() + for i := 0; i < 2; i++ { + select { + case <-done: + case <-time.After(time.Second): + t.Fatal("held request did not finish") + } + } +} + +func TestExcelBPSRequestProxyForwardSupportedRepairKeepsOriginalExit(t *testing.T) { + observed := make(chan requestProxyObservation, 3) + var mu sync.Mutex + calls := 0 + svc, account := localBPSRequestProxyFixture(t, 3, func(id int, w http.ResponseWriter, r *http.Request) { + raw, _ := io.ReadAll(r.Body) + observed <- requestProxyObservation{id: id, path: r.URL.Path, body: raw} + mu.Lock() + calls++ + first := calls == 1 + mu.Unlock() + if first { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(400) + _, _ = io.WriteString(w, excelBPSInvalidCiphertext) + return + } + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, bpsRequestCompletedWire) + }) + code, _, err := forwardLocalBPSRequest(t.Context(), svc, account, excelBPSEncryptedHistoryRequest(true)) + require.NoError(t, err) + require.Equal(t, 200, code) + first, repaired := <-observed, <-observed + require.Equal(t, first.id, repaired.id) + require.Contains(t, string(first.body), "private-ciphertext") + require.NotContains(t, string(repaired.body), "private-ciphertext") + require.Empty(t, observed, "only the existing bounded application repair is submitted") +} diff --git a/backend/internal/service/openai_excel_bps_request_proxy_test.go b/backend/internal/service/openai_excel_bps_request_proxy_test.go new file mode 100644 index 000000000000..e6b9eddd74a1 --- /dev/null +++ b/backend/internal/service/openai_excel_bps_request_proxy_test.go @@ -0,0 +1,35 @@ +package service + +import ( + "bytes" + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +// A configured request pool must take precedence even when the old session +// pool switch is off. Observing the forwarding boundary catches direct leaks. +func TestExcelBPSRequestProxyNeverSendsOutsideSelectedPool(t *testing.T) { + upstream := &httpUpstreamRecorder{resp: &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": {"text/event-stream"}}, Body: io.NopCloser(strings.NewReader("data: {\"type\":\"response.completed\",\"response\":{\"id\":\"r\",\"status\":\"completed\",\"output\":[]}}\n\n"))}} + svc := openAIClientToolsTestService(upstream) + account := excelAccount() + account.Extra["openai_excel_bps_proxy_mode"] = "request" + account.Extra["openai_excel_bps_proxy_ids"] = []int64{987654321} + account.Extra["openai_excel_bps_mihomo"] = false + account.Proxy = &Proxy{Protocol: "http", Host: "unused.example", Port: 8080} + body := []byte(`{"model":"gpt-5.6-sol","input":"test","stream":true}`) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewReader(body)) + _, err := svc.Forward(context.Background(), c, account, body) + require.Error(t, err) + require.Equal(t, http.StatusServiceUnavailable, rec.Code) + require.Contains(t, rec.Body.String(), "basispoints_proxy_unavailable") + require.Nil(t, upstream.lastReq, "an unavailable selected pool must send neither directly nor through the old account proxy") +} diff --git a/backend/internal/service/openai_excel_bps_transport.go b/backend/internal/service/openai_excel_bps_transport.go index 467d4a8655e4..fcf2c6c9d16f 100644 --- a/backend/internal/service/openai_excel_bps_transport.go +++ b/backend/internal/service/openai_excel_bps_transport.go @@ -12,6 +12,7 @@ import ( "net/url" "strconv" "strings" + "sync" "time" "github.com/Wei-Shaw/sub2api/internal/mihomo" @@ -70,6 +71,16 @@ func acquireExcelBPSProxy(ctx context.Context, scope string, excluded ...string) // excelBPSAcquireFor routes the managed session to the pool the account chose. // Both pools share binding/scoring semantics, so callers keep one acquire shape. func (s *OpenAIGatewayService) excelBPSAcquireFor(account *Account) excelBPSAcquire { + if account.ExcelBPSRequestProxyEnabled() { + ids := account.ExcelBPSRequestProxyIDs() + return func(ctx context.Context, _ string, excluded ...string) (string, excelBPSLease, error) { + lease, err := mihomo.AcquireBPSStaticRequestLease(ctx, account.ID, ids, excluded...) + if err != nil { + return "", nil, err + } + return lease.ProxyURL, lease, nil + } + } if account.ExcelBPSProxySource() == ExcelBPSProxySourceIPPool { return s.acquireExcelBPSIPPoolProxy } @@ -113,14 +124,51 @@ func (s *OpenAIGatewayService) refreshExcelBPSIPPool(ctx context.Context) { logger.FromContext(ctx).Warn("excel_bps.ip_pool_refresh_failed", zap.Error(err)) return } - urls := make([]string, 0, len(proxies)) + records := make([]mihomo.BPSStaticProxy, 0, len(proxies)) for i := range proxies { if proxies[i].IsExpired(now) { continue } - urls = append(urls, proxies[i].URL()) + records = append(records, mihomo.BPSStaticProxy{ID: proxies[i].ID, URL: proxies[i].URL(), ExpiresAt: proxies[i].ExpiresAt}) } - mihomo.SetBPSStaticProxies(urls) + mihomo.SetBPSStaticProxyRecords(records) +} + +// Wrap the final logical response, not individual upstream attempts: repairs, +// search continuations and attachments must retain their original exit. +func ownExcelBPSRequestBody(ctx context.Context, body io.ReadCloser, lease excelBPSLease) io.ReadCloser { + if body == nil || lease == nil { + return body + } + b := &excelBPSRequestBody{ReadCloser: body, lease: lease} + b.stop = context.AfterFunc(ctx, func() { b.closeBody(); b.finish() }) + return b +} + +type excelBPSRequestBody struct { + io.ReadCloser + lease excelBPSLease + done sync.Once + closed sync.Once + closeErr error + stop func() bool +} + +func (b *excelBPSRequestBody) finish() { b.done.Do(b.lease.Release) } +func (b *excelBPSRequestBody) closeBody() { b.closed.Do(func() { b.closeErr = b.ReadCloser.Close() }) } +func (b *excelBPSRequestBody) Read(p []byte) (int, error) { + n, err := b.ReadCloser.Read(p) + if err != nil { + b.stop() + b.finish() + } + return n, err +} +func (b *excelBPSRequestBody) Close() error { + b.stop() + b.closeBody() + b.finish() + return b.closeErr } // Missing trace is not evidence of safety. Standard net/http emits GetConn @@ -175,7 +223,7 @@ func (s *OpenAIGatewayService) doExcelBPSRequest(ctx context.Context, c *gin.Con // doExcelBPSRequestTo applies the same exit and no-replay rules to another BPS // endpoint; build must return a fresh request for each attempt. func (s *OpenAIGatewayService) doExcelBPSRequestTo(ctx context.Context, c *gin.Context, account *Account, scope, upstreamURL string, build func(context.Context) (*http.Request, error), acquire excelBPSAcquire) (*http.Response, excelBPSLease, string, error) { - managed := account.IsExcelBPSMihomoEnabled() + managed := account.IsExcelBPSMihomoEnabled() || account.ExcelBPSRequestProxyEnabled() var excluded []string proxy := "" if account.Proxy != nil { diff --git a/backend/internal/service/openai_excel_bps_warm.go b/backend/internal/service/openai_excel_bps_warm.go index 75f136cd86b9..a86fc32268e8 100644 --- a/backend/internal/service/openai_excel_bps_warm.go +++ b/backend/internal/service/openai_excel_bps_warm.go @@ -18,23 +18,31 @@ type BPSWarmAccountRepository interface { ListBPSWarmAccounts(context.Context) ([]Account, error) } +// Recovery probes remain eligible for warming without mutating the repository +// account or re-enabling it for normal scheduling. +func effectiveExcelBPSWarmAccount(account *Account) (*Account, bool) { + if !account.IsExcelBPS403RecoveryPending() { + return account, false + } + probe := *account + probe.Extra = cloneExcelBPSRecoveryExtra(account.Extra) + probe.Extra["openai_excel_bps"] = true + return &probe, true +} + func excelBPSWarmTargets(accounts []Account) (managed, static int) { for i := range accounts { - a := &accounts[i] + a, recovery := effectiveExcelBPSWarmAccount(&accounts[i]) // Keep one healthy exit available for opted-in disabled accounts, even // when no production account still uses their proxy pool. - if a.IsExcelBPS403RecoveryPending() { - probe := *a - probe.Extra = cloneExcelBPSRecoveryExtra(a.Extra) - probe.Extra["openai_excel_bps"] = true - probe.Concurrency = 1 - a = &probe + if recovery { + a.Concurrency = 1 } - if !a.IsActive() || !a.Schedulable || !a.IsExcelBPSMihomoEnabled() { + if !a.IsActive() || !a.Schedulable || (!a.IsExcelBPSMihomoEnabled() && !a.OpenAIRequestProxyEnabled()) { continue } target := max(1, min(a.Concurrency, excelBPSWarmMaxTarget)) - if a.ExcelBPSProxySource() == ExcelBPSProxySourceIPPool { + if a.OpenAIRequestProxyEnabled() || a.ExcelBPSProxySource() == ExcelBPSProxySourceIPPool { static = min(excelBPSWarmMaxTarget, static+target) } else { managed = min(excelBPSWarmMaxTarget, managed+target) @@ -107,6 +115,14 @@ func (s *OpenAIGatewayService) syncBPSWarmPool(ctx context.Context) { return } managed, static := excelBPSWarmTargets(accounts) + groups := make(map[int64][]int64) + for i := range accounts { + a, _ := effectiveExcelBPSWarmAccount(&accounts[i]) + if a.IsActive() && a.Schedulable && a.OpenAIRequestProxyEnabled() { + groups[a.ID] = a.OpenAIRequestProxyIDs() + } + } + mihomo.SetBPSStaticRequestGroups(groups) if static > 0 { proxyCtx, stop := context.WithTimeout(ctx, 5*time.Second) s.refreshExcelBPSIPPool(proxyCtx) diff --git a/backend/internal/service/openai_excel_bps_warm_test.go b/backend/internal/service/openai_excel_bps_warm_test.go index 9dc2054fd0ab..615d23255868 100644 --- a/backend/internal/service/openai_excel_bps_warm_test.go +++ b/backend/internal/service/openai_excel_bps_warm_test.go @@ -39,6 +39,23 @@ func TestExcelBPSWarmTargetsUseConfiguredConcurrency(t *testing.T) { require.Equal(t, excelBPSWarmMaxTarget, m) } +func TestExcelBPSWarmRequestRecoveryDoesNotMutateAccount(t *testing.T) { + account := recoveryTestAccount(time.Now()) + account.Concurrency = 6 + account.Extra[ExcelBPSProxyModeKey] = ExcelBPSProxyModeRequest + account.Extra[ExcelBPSProxyIDsKey] = []int64{11, 22} + projection, recovery := effectiveExcelBPSWarmAccount(account) + require.True(t, recovery) + require.True(t, projection.ExcelBPSRequestProxyEnabled()) + require.Equal(t, []int64{11, 22}, projection.ExcelBPSRequestProxyIDs()) + require.Equal(t, 6, projection.Concurrency, "group projection must retain account settings") + managed, static := excelBPSWarmTargets([]Account{*account}) + require.Zero(t, managed) + require.Equal(t, 1, static, "recovery target only needs one healthy exit") + require.False(t, account.IsExcelBPSEnabled(), "warming cannot re-enable the stored account") + require.Equal(t, 6, account.Concurrency) +} + type warmProjectionRepo struct { AccountRepository projectionCalls int diff --git a/backend/internal/service/openai_excel_oauth.go b/backend/internal/service/openai_excel_oauth.go index 92eef6931054..ce62b68479f1 100644 --- a/backend/internal/service/openai_excel_oauth.go +++ b/backend/internal/service/openai_excel_oauth.go @@ -252,7 +252,12 @@ func (s *OpenAIOAuthReauthService) ExcelAccessToken(ctx context.Context, account if err != nil { return "", errors.New("saved Excel identity does not match the account") } - proxyURL, err := s.reauthProxyURL(ctx, fresh.ProxyID) + var proxyURL string + if fresh.OpenAIRequestProxyEnabled() { + proxyURL, err = resolveOpenAIMaintenanceProxy(ctx, fresh, s.oauth.proxyRepo) + } else { + proxyURL, err = s.reauthProxyURL(ctx, fresh.ProxyID) + } if err != nil { return "", err } diff --git a/backend/internal/service/openai_gateway_chat_completions.go b/backend/internal/service/openai_gateway_chat_completions.go index 12bd3542bc89..d4794dd4a4dc 100644 --- a/backend/internal/service/openai_gateway_chat_completions.go +++ b/backend/internal/service/openai_gateway_chat_completions.go @@ -109,6 +109,12 @@ func (s *OpenAIGatewayService) forwardAsChatCompletions( return nil, admissionErr } account = latest + proxyCtx, releaseProxy, proxyErr := s.beginOpenAIRequestProxy(ctx, c, account) + if proxyErr != nil { + return nil, proxyErr + } + defer releaseProxy() + ctx = proxyCtx if err := CheckUpstreamModeration(ctx, c, account); err != nil { return nil, err } diff --git a/backend/internal/service/openai_gateway_count_tokens.go b/backend/internal/service/openai_gateway_count_tokens.go index f9de5e85afe5..7d388dd8c1fb 100644 --- a/backend/internal/service/openai_gateway_count_tokens.go +++ b/backend/internal/service/openai_gateway_count_tokens.go @@ -65,6 +65,12 @@ func (s *OpenAIGatewayService) ForwardResponsesInputTokens( writeOpenAIResponsesInputTokensFallback(c, account, prepared, 0, "custom_relay") return nil } + proxyCtx, releaseProxy, proxyErr := s.beginOpenAIRequestProxy(ctx, c, account) + if proxyErr != nil { + return proxyErr + } + defer releaseProxy() + ctx = proxyCtx token, _, err := s.GetAccessToken(ctx, account) if err != nil { @@ -295,6 +301,12 @@ func (s *OpenAIGatewayService) ForwardCountTokensAsAnthropic( writeAnthropicCountTokensError(c, http.StatusBadRequest, "invalid_request_error", "Failed to parse request body") return err } + proxyCtx, releaseProxy, proxyErr := s.beginOpenAIRequestProxy(ctx, c, account) + if proxyErr != nil { + return proxyErr + } + defer releaseProxy() + ctx = proxyCtx upstreamBody, err := marshalOpenAIUpstreamJSON(prepared.Request) if err != nil { diff --git a/backend/internal/service/openai_gateway_forward.go b/backend/internal/service/openai_gateway_forward.go index 28b3a6868d77..19ca05b6c261 100644 --- a/backend/internal/service/openai_gateway_forward.go +++ b/backend/internal/service/openai_gateway_forward.go @@ -234,6 +234,9 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco return s.forwardSIWC(ctx, c, account, body, startTime) } if !account.IsExcelOAuth() && account.IsPrismBrowserEnabledForModel(modelForBPS) && s.prismBrowserGloballyEnabled(ctx) { + if account.OpenAIRequestProxyEnabled() { + return nil, writeOpenAIRequestProxyError(c, "openai_proxy_route_unsupported", "Request proxy routing is unavailable for Prism") + } return s.forwardPrismBrowser(withOpenAITransportMode(ctx, "prism_browser"), c, account, body, startTime) } if c.GetBool(bpsAccountProbeRequiredContextKey) && @@ -243,6 +246,12 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco if account.IsExcelBPSEnabledForModel(modelForBPS) && s.excelBPSGloballyEnabled(ctx) { return s.forwardExcelBPS(withOpenAITransportMode(ctx, "bps"), c, account, body, startTime) } + proxyCtx, releaseProxy, proxyErr := s.beginOpenAIRequestProxy(ctx, c, account) + if proxyErr != nil { + return nil, proxyErr + } + defer releaseProxy() + ctx = proxyCtx if account.IsOpenAIOAuthLike() { stripped, changed, stripErr := stripOpenAICodexUnsupportedWebSearchFields(body) @@ -316,6 +325,9 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco wsDecision := s.getOpenAIWSProtocolResolver().Resolve(account) // HTTP SSE may opt into the native WS pool on ordinary OAuth accounts. wsDecision = s.resolveOpenAIHTTPWSSSEDecision(c, account, body, wsDecision) + if account.OpenAIRequestProxyEnabled() { + wsDecision = openAIWSHTTPDecision("request_proxy_requires_http") + } if openAIAgentRecoveryBound(ctx) { // The observation was made at an actual HTTP send. Preserve that wire // instead of letting a later WS preference change its continuation. @@ -323,7 +335,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco } accelerateHTTPSSE := wsDecision.Reason == openAIOAuthWSSSEAccelerationReason var anchorFinish func(*OpenAIForwardResult, error) - if !openAIAgentRecoveryBound(ctx) { + if !openAIAgentRecoveryBound(ctx) && !account.OpenAIRequestProxyEnabled() { anchorCtx, finish, anchorErr := s.prepareCodexWSAnchor(ctx, c, account, body) if anchorErr != nil { return nil, anchorErr diff --git a/backend/internal/service/openai_gateway_messages.go b/backend/internal/service/openai_gateway_messages.go index faf8a5d35d19..a9c7cb534859 100644 --- a/backend/internal/service/openai_gateway_messages.go +++ b/backend/internal/service/openai_gateway_messages.go @@ -67,6 +67,12 @@ func (s *OpenAIGatewayService) forwardAsAnthropic( return nil, admissionErr } account = latest + proxyCtx, releaseProxy, proxyErr := s.beginOpenAIRequestProxy(ctx, c, account) + if proxyErr != nil { + return nil, proxyErr + } + defer releaseProxy() + ctx = proxyCtx if err := CheckUpstreamModeration(ctx, c, account); err != nil { return nil, err } diff --git a/backend/internal/service/openai_images_responses.go b/backend/internal/service/openai_images_responses.go index 7bafab840838..751bdaad190e 100644 --- a/backend/internal/service/openai_images_responses.go +++ b/backend/internal/service/openai_images_responses.go @@ -1832,6 +1832,14 @@ func (s *OpenAIGatewayService) forwardOpenAIImagesOAuth( } } } + // Image generation already survives client disconnects so completed work + // can be accounted for. Its proxy scope follows that upstream lifecycle. + proxyCtx, releaseProxy, proxyErr := s.beginOpenAIRequestProxy(upstreamCtx, c, account) + if proxyErr != nil { + return nil, proxyErr + } + defer releaseProxy() + upstreamCtx = proxyCtx credentialAccount, err := resolveCredentialAccount(ctx, s.accountRepo, account) if err != nil { @@ -1908,7 +1916,7 @@ func (s *OpenAIGatewayService) forwardOpenAIImagesOAuth( _ = resp.Body.Close() respBody = s.redactAgentIdentitySensitiveBody(upstreamCtx, account, respBody) if direct && (resp.StatusCode == http.StatusNotFound || resp.StatusCode == http.StatusMethodNotAllowed) { - return s.forwardOpenAIImagesOAuth(withOpenAIImagesForceResponses(ctx), c, account, parsed, channelMappedModel) + return s.forwardOpenAIImagesOAuth(withOpenAIImagesForceResponses(upstreamCtx), c, account, parsed, channelMappedModel) } if !agentIdentityTaskRecoveryWasTried(ctx) && s.isAgentIdentityAccount(ctx, account) && isAgentIdentityTaskInvalidHTTPResponse(resp.StatusCode, respBody) { expectedTaskID := account.GetCredential("task_id") diff --git a/backend/internal/service/openai_maintenance_proxy.go b/backend/internal/service/openai_maintenance_proxy.go new file mode 100644 index 000000000000..d379f8a45f0c --- /dev/null +++ b/backend/internal/service/openai_maintenance_proxy.go @@ -0,0 +1,64 @@ +package service + +import ( + "context" + "net/http" + "net/url" + "strings" + "time" + + infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" +) + +// Maintenance uses a saved member without changing the account's single proxy. +// Inference owns its independent least-in-flight lease for the logical request. +func resolveOpenAIMaintenanceProxy(ctx context.Context, account *Account, repo ProxyRepository, expectedURL ...string) (string, error) { + if account == nil || !account.OpenAIRequestProxyEnabled() { + return "", nil + } + if account.AuthConnectionID != "" || account.HasManagedOpenAIConnections() { + return "", infraerrors.New(http.StatusServiceUnavailable, "OPENAI_PROXY_CONNECTION_CONFLICT", "Request proxies require an ordinary OAuth account without a fixed authorization connection") + } + unavailable := func() (string, error) { + return "", infraerrors.New(http.StatusServiceUnavailable, "OPENAI_PROXY_UNAVAILABLE", "No selected OpenAI proxy is available; direct fallback is disabled") + } + if repo == nil { + return unavailable() + } + if route, ok := openAIRequestProxyFromContext(ctx, account.ID); ok { + if len(expectedURL) > 0 && expectedURL[0] != route.proxy { + return unavailable() + } + expectedURL = []string{route.proxy} + } + now := time.Now() + for _, id := range account.OpenAIRequestProxyIDs() { + if err := ctx.Err(); err != nil { + return "", err + } + proxy, err := repo.GetByID(ctx, id) + if err != nil || proxy == nil || !proxy.IsActive() || proxy.IsExpired(now) { + continue + } + if strings.TrimSpace(proxy.Host) == "" || proxy.Port <= 0 || proxy.Port > 65535 { + continue + } + switch strings.ToLower(proxy.Protocol) { + case "http", "https", "socks5", "socks5h": + default: + continue + } + raw := proxy.URL() + if len(expectedURL) > 0 && raw != expectedURL[0] { + continue + } + parsed, err := url.Parse(raw) + if err == nil && parsed.Hostname() != "" { + return raw, nil + } + } + if err := ctx.Err(); err != nil { + return "", err + } + return unavailable() +} diff --git a/backend/internal/service/openai_maintenance_remaining_proxy_test.go b/backend/internal/service/openai_maintenance_remaining_proxy_test.go new file mode 100644 index 000000000000..0be598f085a5 --- /dev/null +++ b/backend/internal/service/openai_maintenance_remaining_proxy_test.go @@ -0,0 +1,220 @@ +package service + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "net/url" + "testing" + "time" + + infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" + "github.com/Wei-Shaw/sub2api/internal/pkg/openai" + "github.com/stretchr/testify/require" +) + +type remainingMaintenanceClient struct { + *reauthTestOAuthClient + credentials map[string]any + proxies []string + connectionCalls int +} + +func (c *remainingMaintenanceClient) RefreshTokenWithClientID(_ context.Context, _, proxy, _ string) (*openai.TokenResponse, error) { + c.proxies = append(c.proxies, proxy) + return &openai.TokenResponse{AccessToken: reauthMapString(c.credentials, "access_token"), RefreshToken: reauthMapString(c.credentials, "refresh_token"), IDToken: reauthMapString(c.credentials, "id_token"), ExpiresIn: 3600}, nil +} + +func (c *remainingMaintenanceClient) SIWCToken(_ context.Context, _ url.Values, proxy, _ string) (*openai.TokenResponse, *openai.SIWCIdentity, error) { + c.proxies = append(c.proxies, proxy) + identity := &openai.SIWCIdentity{Email: "user@example.com"} + identity.Subject = "subscriber" + return &openai.TokenResponse{AccessToken: "fresh-siwc-access", RefreshToken: "fresh-siwc-refresh", ExpiresIn: 3600, Scope: openai.SIWCDirectScope}, identity, nil +} + +func (c *remainingMaintenanceClient) ConnectionToken(context.Context, url.Values, string, string, string) (*openai.TokenResponse, *openai.SIWCIdentity, error) { + c.connectionCalls++ + identity := &openai.SIWCIdentity{} + identity.Subject = "subscriber" + return &openai.TokenResponse{AccessToken: "connection-access", RefreshToken: "connection-refresh", ExpiresIn: 3600}, identity, nil +} +func (c *remainingMaintenanceClient) RevokeConnectionToken(context.Context, string, string, string) error { + c.connectionCalls++ + return nil +} + +func remainingMaintenanceSelection(reader *reauthTestAccountReader, svc *OpenAIOAuthReauthService) *openAIMaintenanceProxyRepo { + legacy := &Proxy{ID: 90, Protocol: "http", Host: "old.invalid", Port: 8080, Status: StatusActive} + reader.proxy = legacy + reader.account.ProxyID = &legacy.ID + reader.account.Extra = map[string]any{OpenAIProxyModeKey: OpenAIProxyModeRequest, OpenAIProxyIDsKey: []int64{33}} + repo := &openAIMaintenanceProxyRepo{proxies: map[int64]*Proxy{33: {ID: 33, Protocol: "http", Host: "selected.invalid", Port: 8080, Status: StatusActive}}} + svc.oauth.proxyRepo = repo + return repo +} + +type remainingMaintenanceConnectionRepo struct { + *connectionTypeRepo +} + +func (r *remainingMaintenanceConnectionRepo) BeginAuthConnectionRefresh(context.Context, *OpenAIAuthConnection, string) (bool, error) { + r.writes++ + return false, errors.New("unexpected refresh intent") +} + +func TestRemainingMaintenanceExcelRefreshUsesRequestGroup(t *testing.T) { + svc, reader, repo, _, _ := newExcelReauthTestService(t) + defer svc.oauth.Stop() + remainingMaintenanceSelection(reader, svc) + storeExcelTestCredentials(t, svc, repo, excelTestCredentials("expired", time.Now().Add(-time.Hour))) + client := &remainingMaintenanceClient{credentials: excelTestCredentials("fresh", time.Now().Add(time.Hour))} + svc.oauth.oauthClient = client + token, err := svc.ExcelAccessToken(context.Background(), reader.account, nil) + require.NoError(t, err) + require.Equal(t, client.credentials["access_token"], token) + require.Equal(t, []string{"http://selected.invalid:8080"}, client.proxies) + require.EqualValues(t, 90, *reader.account.ProxyID) +} + +func TestRemainingMaintenanceSIWCUsesRequestGroup(t *testing.T) { + svc, reader, base, _, oldClient, _ := newReauthTestService("acct-1") + defer svc.oauth.Stop() + store := &siwcTestRepo{reauthTestRepo: base} + svc.repo = store + remainingMaintenanceSelection(reader, svc) + client := &remainingMaintenanceClient{reauthTestOAuthClient: oldClient} + svc.oauth.oauthClient = client + auth, err := svc.BeginSIWCAuthorization(context.Background(), reader.account.ID) + require.NoError(t, err) + session, ok := svc.readSIWCSession(context.Background(), auth.SessionID, false) + require.True(t, ok) + require.Equal(t, "http://selected.invalid:8080", session.ProxyURL) + callback := openai.SIWCRedirectURI + "?code=test-code&state=" + url.QueryEscape(session.State) + "&client_id=issued" + require.NoError(t, svc.CompleteSIWCAuthorization(context.Background(), reader.account.ID, auth.SessionID, callback, nil)) + require.Equal(t, []string{"http://selected.invalid:8080"}, client.proxies) + plain, err := svc.encryptor.Decrypt(store.ciphertext) + require.NoError(t, err) + var grant siwcGrant + require.NoError(t, json.Unmarshal([]byte(plain), &grant)) + grant.ExpiresAt = time.Now().Add(-time.Hour).Unix() + raw, err := json.Marshal(grant) + require.NoError(t, err) + store.ciphertext, err = svc.encryptor.Encrypt(string(raw)) + require.NoError(t, err) + _, err = svc.SIWCAccessToken(context.Background(), reader.account, nil) + require.NoError(t, err) + require.Equal(t, []string{"http://selected.invalid:8080", "http://selected.invalid:8080"}, client.proxies) +} + +func TestRemainingMaintenanceConnectionRequestModeRejectsBeforeSideEffects(t *testing.T) { + for _, operation := range []string{"begin", "complete", "token", "revoke"} { + t.Run(operation, func(t *testing.T) { + const id = "c910c45b-79a0-4367-a1dc-60e12210e199" + svc, connections := connectionTypeService(AccountTypeOAuth) + base, _, _, _, oldClient, _ := newReauthTestService("acct-1") + defer base.oauth.Stop() + svc.oauth = base.oauth + reader := svc.accounts.(*reauthTestAccountReader) + remainingMaintenanceSelection(reader, svc) + client := &remainingMaintenanceClient{reauthTestOAuthClient: oldClient} + svc.oauth.oauthClient = client + c := &OpenAIAuthConnection{ID: id, AccountID: 42, Kind: "siwc", Status: "active", Revision: 1, ClientID: "issued", Subject: "subscriber", IdentityVerified: true, RefreshState: "idle", Capabilities: []string{"responses"}} + require.NoError(t, svc.encryptConnectionCredentials(c, map[string]any{"client_id": "issued", "access_token": "old", "refresh_token": "old-refresh", "expires_at": "0"})) + connections.rows = []*OpenAIAuthConnection{c} + svc.repo = &remainingMaintenanceConnectionRepo{connectionTypeRepo: connections} + session := &openai.OAuthSession{SIWCAccountID: 42, ConnectionID: id, ConnectionKind: c.Kind, ConnectionRevision: 1, State: "state", ClientID: "issued", RedirectURI: openai.SIWCRedirectURI, ProxyURL: "http://old.invalid:8080", CreatedAt: time.Now()} + require.NoError(t, svc.setSIWCSession(context.Background(), "test-session", session)) + var err error + switch operation { + case "begin": + _, err = svc.BeginConnectionAuthorization(context.Background(), 42, id) + case "complete": + err = svc.CompleteConnectionAuthorization(context.Background(), 42, id, "test-session", openai.SIWCRedirectURI+"?code=code&state=state&client_id=issued") + case "token": + _, err = svc.ConnectionAccessToken(context.Background(), 42, id) + case "revoke": + _, err = svc.RevokeAuthConnection(context.Background(), 42, id, 1) + } + require.Equal(t, http.StatusBadRequest, infraerrors.Code(err)) + require.Equal(t, "OPENAI_PROXY_CONNECTION_UNSUPPORTED", infraerrors.Reason(err)) + require.Zero(t, client.connectionCalls) + require.Zero(t, connections.writes) + require.EqualValues(t, 0, connections.rows[0].LeaseEpoch, "reject before taking a lifecycle lease") + _, retained := svc.readSIWCSession(context.Background(), "test-session", false) + require.True(t, retained, "reject before consuming the fixed-exit session") + }) + } +} + +func TestRemainingMaintenanceRequestRefreshUnavailableRetainsGrants(t *testing.T) { + t.Run("excel", func(t *testing.T) { + svc, reader, repo, _, _ := newExcelReauthTestService(t) + defer svc.oauth.Stop() + selection := remainingMaintenanceSelection(reader, svc) + selection.err = errors.New("http://private:secret@private.invalid:8080") + storeExcelTestCredentials(t, svc, repo, excelTestCredentials("expired", time.Now().Add(-time.Hour))) + before := repo.ciphertext + client := &remainingMaintenanceClient{credentials: excelTestCredentials("fresh", time.Now().Add(time.Hour))} + svc.oauth.oauthClient = client + _, err := svc.ExcelAccessToken(context.Background(), reader.account, nil) + require.Equal(t, http.StatusServiceUnavailable, infraerrors.Code(err)) + require.Equal(t, "OPENAI_PROXY_UNAVAILABLE", infraerrors.Reason(err)) + require.NotContains(t, err.Error(), "secret") + require.Empty(t, client.proxies) + require.Equal(t, before, repo.ciphertext) + }) + t.Run("siwc", func(t *testing.T) { + svc, reader, base, _, oldClient, _ := newReauthTestService("acct-1") + defer svc.oauth.Stop() + store := &siwcTestRepo{reauthTestRepo: base} + svc.repo = store + selection := remainingMaintenanceSelection(reader, svc) + delete(selection.proxies, 33) + raw, err := json.Marshal(siwcGrant{AccessToken: "expired", RefreshToken: "saved-refresh", ClientID: "issued", Subject: "subscriber", Email: "user@example.com", Workspace: "acct-1", Scope: openai.SIWCDirectScope, ExpiresAt: time.Now().Add(-time.Hour).Unix()}) + require.NoError(t, err) + store.ciphertext, err = svc.encryptor.Encrypt(string(raw)) + require.NoError(t, err) + before := store.ciphertext + client := &remainingMaintenanceClient{reauthTestOAuthClient: oldClient} + svc.oauth.oauthClient = client + _, err = svc.SIWCAccessToken(context.Background(), reader.account, nil) + require.Equal(t, http.StatusServiceUnavailable, infraerrors.Code(err)) + require.Equal(t, "OPENAI_PROXY_UNAVAILABLE", infraerrors.Reason(err)) + require.Empty(t, client.proxies) + require.Equal(t, before, store.ciphertext) + require.Zero(t, store.writes) + }) +} + +func TestRemainingMaintenanceSIWCCallbackRejectsStaleSessionExit(t *testing.T) { + for _, beganSingle := range []bool{false, true} { + t.Run(map[bool]string{false: "group changed", true: "single switched to request"}[beganSingle], func(t *testing.T) { + svc, reader, base, _, oldClient, _ := newReauthTestService("acct-1") + defer svc.oauth.Stop() + store := &siwcTestRepo{reauthTestRepo: base} + svc.repo = store + selection := remainingMaintenanceSelection(reader, svc) + if beganSingle { + reader.account.Extra[OpenAIProxyModeKey] = OpenAIProxyModeSingle + } + client := &remainingMaintenanceClient{reauthTestOAuthClient: oldClient} + svc.oauth.oauthClient = client + auth, err := svc.BeginSIWCAuthorization(context.Background(), reader.account.ID) + require.NoError(t, err) + session, ok := svc.readSIWCSession(context.Background(), auth.SessionID, false) + require.True(t, ok) + reader.account.Extra[OpenAIProxyModeKey] = OpenAIProxyModeRequest + reader.account.Extra[OpenAIProxyIDsKey] = []int64{44} + selection.proxies[44] = &Proxy{ID: 44, Protocol: "http", Host: "replacement.invalid", Port: 8080, Status: StatusActive} + callback := openai.SIWCRedirectURI + "?code=test-code&state=" + url.QueryEscape(session.State) + "&client_id=issued" + err = svc.CompleteSIWCAuthorization(context.Background(), reader.account.ID, auth.SessionID, callback, nil) + require.Equal(t, http.StatusServiceUnavailable, infraerrors.Code(err)) + require.Equal(t, "OPENAI_PROXY_UNAVAILABLE", infraerrors.Reason(err)) + require.Empty(t, client.proxies) + require.Zero(t, store.writes) + _, retained := svc.readSIWCSession(context.Background(), auth.SessionID, false) + require.True(t, retained, "reject stale egress before consuming OAuth code/session") + }) + } +} diff --git a/backend/internal/service/openai_maintenance_task_request_proxy_test.go b/backend/internal/service/openai_maintenance_task_request_proxy_test.go new file mode 100644 index 000000000000..b6c6f4f14946 --- /dev/null +++ b/backend/internal/service/openai_maintenance_task_request_proxy_test.go @@ -0,0 +1,160 @@ +package service + +import ( + "context" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +type maintenanceTaskProxyRepo struct { + ProxyRepository + proxies map[int64]*Proxy +} + +func (r *maintenanceTaskProxyRepo) GetByID(_ context.Context, id int64) (*Proxy, error) { + return r.proxies[id], nil +} + +type maintenanceTaskRotationRepo struct { + *rotationTestRepo + finished bool + code string +} + +func (r *maintenanceTaskRotationRepo) FinishTOTPRotation(_ context.Context, _ int64, _ string, _ bool, code string) error { + r.finished = true + r.code = code + return nil +} + +type maintenanceTaskSessionRepo struct { + OpenAISessionExportRepository + record *OpenAISessionExportTaskRecord +} + +func (r *maintenanceTaskSessionRepo) ExpireActiveSessionExportTasks(context.Context) error { + return nil +} +func (r *maintenanceTaskSessionRepo) ClaimSessionExportTask(_ context.Context, worker string, _ time.Duration) (*OpenAISessionExportTaskRecord, error) { + r.record.WorkerID = worker + return r.record, nil +} +func (r *maintenanceTaskSessionRepo) FinishSessionExportTask(_ context.Context, _ int64, _ string, status, code string) error { + r.record.Status = status + r.record.ErrorCode = code + return nil +} + +func newMaintenanceTaskProxyService(t *testing.T) (*OpenAIOAuthReauthService, *reauthTestAccountReader, *maintenanceTaskRotationRepo, *maintenanceTaskSessionRepo, *maintenanceTaskProxyRepo) { + t.Helper() + svc, base := newRotationService(t) + t.Cleanup(svc.oauth.Stop) + reader := svc.accounts.(*reauthTestAccountReader) + legacyID := int64(90) + reader.account.ProxyID = &legacyID + reader.account.Extra = map[string]any{ + "openai_proxy_mode": "request", + "openai_proxy_ids": []any{float64(1), float64(2)}, + } + reader.proxy = &Proxy{ID: 90, Status: StatusActive, Protocol: "http", Host: "outside.example.test", Port: 8080} + proxies := &maintenanceTaskProxyRepo{proxies: map[int64]*Proxy{ + 1: {ID: 1, Status: StatusActive, Protocol: "http", Host: "expired.example.test", Port: 8080, ExpiresAt: func() *time.Time { expired := time.Now().Add(-time.Hour); return &expired }()}, + 2: {ID: 2, Status: StatusActive, Protocol: "http", Host: "selected.example.test", Port: 8080}, + }} + svc.oauth.proxyRepo = proxies + rotation := &maintenanceTaskRotationRepo{rotationTestRepo: base} + svc.repo = rotation + session := &maintenanceTaskSessionRepo{record: &OpenAISessionExportTaskRecord{ + OpenAISessionExportTask: OpenAISessionExportTask{ID: 8, AccountID: 42, Status: OpenAISessionExportStatusRunning}, + }} + svc.SetSessionExportRepository(session) + return svc, reader, rotation, session, proxies +} + +func TestOpenAIMaintenanceTaskRequestProxyUsesSelectedGroup(t *testing.T) { + for _, operation := range []string{"totp", "session"} { + t.Run(operation, func(t *testing.T) { + svc, reader, _, _, _ := newMaintenanceTaskProxyService(t) + if operation == "totp" { + claim, err := svc.ClaimTOTPRotation(t.Context(), "worker") + require.NoError(t, err) + require.NotNil(t, claim) + require.Equal(t, "http://selected.example.test:8080", claim.ProxyURL) + } else { + claim, err := svc.ClaimSessionExportTask(t.Context(), "worker", []string{OpenAISessionExportOperation}) + require.NoError(t, err) + require.NotNil(t, claim) + require.Equal(t, "http://selected.example.test:8080", claim.ProxyURL) + } + require.EqualValues(t, 90, *reader.account.ProxyID) + }) + } +} + +func TestOpenAIMaintenanceTaskRequestProxyRejectsUnavailableOrOutsideSources(t *testing.T) { + for _, operation := range []string{"totp", "session"} { + for _, condition := range []string{"unavailable", "unavailable-direct", "fixed_connection", "managed_proxy", "mihomo"} { + t.Run(operation+"/"+condition, func(t *testing.T) { + svc, reader, rotation, session, proxies := newMaintenanceTaskProxyService(t) + if condition == "unavailable" || condition == "unavailable-direct" { + proxies.proxies = nil + if condition == "unavailable-direct" { + reader.account.ProxyID = nil + } + } else if condition == "fixed_connection" { + reader.account.AuthConnectionID = "outside-fixed-connection" + } else { + rotation.config.ProxySource = condition + if condition == "managed_proxy" { + id := int64(90) + rotation.config.ProxyID = &id + } + } + mihomoCalls := 0 + svc.acquireMihomoProxy = func(context.Context, string) (string, func(), error) { + mihomoCalls++ + return "http://outside-mihomo.example.test:8080", func() {}, nil + } + if operation == "totp" { + claim, err := svc.ClaimTOTPRotation(t.Context(), "worker") + require.Error(t, err) + require.Nil(t, claim) + require.True(t, rotation.finished) + require.Equal(t, "configuration_unavailable", rotation.code) + } else { + claim, err := svc.ClaimSessionExportTask(t.Context(), "worker", []string{OpenAISessionExportOperation}) + require.NoError(t, err) + require.Nil(t, claim) + require.Equal(t, OpenAISessionExportStatusFailed, session.record.Status) + require.Equal(t, "proxy_unavailable", session.record.ErrorCode) + } + require.Zero(t, mihomoCalls) + }) + } + } +} + +func TestOpenAIMaintenanceTaskRequestProxyPreservesExplicitSingle(t *testing.T) { + for _, operation := range []string{"totp", "session"} { + t.Run(operation, func(t *testing.T) { + svc, reader, _, _, _ := newMaintenanceTaskProxyService(t) + reader.account.Extra["openai_proxy_mode"] = "single" + reader.account.Extra["openai_excel_bps"] = true + reader.account.Extra["openai_excel_bps_proxy_mode"] = "request" + reader.account.Extra["openai_excel_bps_proxy_ids"] = []any{float64(2)} + if operation == "totp" { + claim, err := svc.ClaimTOTPRotation(t.Context(), "worker") + require.NoError(t, err) + require.NotNil(t, claim) + require.Equal(t, "http://outside.example.test:8080", claim.ProxyURL) + } else { + claim, err := svc.ClaimSessionExportTask(t.Context(), "worker", []string{OpenAISessionExportOperation}) + require.NoError(t, err) + require.NotNil(t, claim) + require.Equal(t, "http://outside.example.test:8080", claim.ProxyURL) + } + }) + } +} diff --git a/backend/internal/service/openai_oauth_create_proxy.go b/backend/internal/service/openai_oauth_create_proxy.go new file mode 100644 index 000000000000..e0799039e91a --- /dev/null +++ b/backend/internal/service/openai_oauth_create_proxy.go @@ -0,0 +1,101 @@ +package service + +import ( + "context" + "net/url" + "strings" + "time" + + infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" +) + +// GenerateAuthURLWithProxySettings pins a request-mode authorization session to +// one currently available member. Single-proxy callers keep the existing flow. +func (s *OpenAIOAuthService) GenerateAuthURLWithProxySettings(ctx context.Context, proxyID *int64, proxyMode string, proxyIDs []int64, redirectURI, platform string, oauthClient ...string) (*OpenAIAuthURLResult, error) { + requestProxy, err := openAIOAuthRequestProxySettings(proxyMode, proxyIDs) + if err != nil { + return nil, err + } + if !requestProxy { + return s.GenerateAuthURL(ctx, proxyID, redirectURI, platform, oauthClient...) + } + selectedID, proxyURL, err := s.resolveOAuthRequestProxy(ctx, proxyIDs) + if err != nil { + return nil, err + } + result, err := s.generateAuthURLWithProxyURL(ctx, proxyURL, true, redirectURI, platform, oauthClient...) + if err != nil { + return nil, err + } + result.ProxyMode = OpenAIProxyModeRequest + result.ProxyID = selectedID + return result, nil +} + +func openAIOAuthRequestProxySettings(mode string, ids []int64) (bool, error) { + switch mode { + case "", OpenAIProxyModeSingle: + if len(ids) != 0 { + return false, infraerrors.BadRequest("INVALID_OPENAI_PROXY_MODE", "OpenAI proxy IDs require request proxy mode") + } + return false, nil + case OpenAIProxyModeRequest: + if len(ids) == 0 { + return false, infraerrors.BadRequest("OPENAI_PROXY_GROUP_REQUIRED", "Select at least one OpenAI proxy") + } + for _, id := range ids { + if id <= 0 { + return false, infraerrors.BadRequest("INVALID_OPENAI_PROXY_IDS", "OpenAI proxy IDs must be positive integers") + } + } + return true, nil + default: + return false, infraerrors.BadRequest("INVALID_OPENAI_PROXY_MODE", "OpenAI proxy mode must be single or request") + } +} + +// expectedURL makes callback validation fail closed if the original exit is no +// longer an available member of the current group; it never selects a new exit. +func (s *OpenAIOAuthService) resolveOAuthRequestProxy(ctx context.Context, ids []int64, expectedURL ...string) (int64, string, error) { + unavailable := func() (int64, string, error) { + return 0, "", infraerrors.ServiceUnavailable("OPENAI_OAUTH_PROXY_UNAVAILABLE", "The authorization proxy is unavailable; generate a new authorization URL after checking the selected proxies") + } + if s.proxyRepo == nil { + return unavailable() + } + now := time.Now() + seen := make(map[int64]bool, len(ids)) + for _, id := range ids { + if err := ctx.Err(); err != nil { + return 0, "", err + } + if seen[id] { + continue + } + seen[id] = true + proxy, err := s.proxyRepo.GetByID(ctx, id) + if err != nil || proxy == nil || !proxy.IsActive() || proxy.IsExpired(now) { + continue + } + if strings.TrimSpace(proxy.Host) == "" || proxy.Port <= 0 || proxy.Port > 65535 { + continue + } + switch strings.ToLower(proxy.Protocol) { + case "http", "https", "socks5", "socks5h": + default: + continue + } + raw := proxy.URL() + if len(expectedURL) > 0 && raw != expectedURL[0] { + continue + } + parsed, err := url.Parse(raw) + if err == nil && parsed.Hostname() != "" { + return id, raw, nil + } + } + if err := ctx.Err(); err != nil { + return 0, "", err + } + return unavailable() +} diff --git a/backend/internal/service/openai_oauth_create_request_proxy_test.go b/backend/internal/service/openai_oauth_create_request_proxy_test.go new file mode 100644 index 000000000000..b46137970f6c --- /dev/null +++ b/backend/internal/service/openai_oauth_create_request_proxy_test.go @@ -0,0 +1,118 @@ +package service + +import ( + "context" + "errors" + "net/http" + "testing" + "time" + + infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" + "github.com/Wei-Shaw/sub2api/internal/pkg/openai" + "github.com/stretchr/testify/require" +) + +type oauthRequestProxyRepo struct { + ProxyRepository + proxies map[int64]*Proxy +} + +func (r *oauthRequestProxyRepo) GetByID(_ context.Context, int64ID int64) (*Proxy, error) { + if proxy := r.proxies[int64ID]; proxy != nil { + return proxy, nil + } + return nil, errors.New("synthetic private proxy address") +} + +type oauthRequestProxyClient struct { + OpenAIOAuthClient + proxies []string +} + +func (c *oauthRequestProxyClient) ExchangeCode(_ context.Context, _, _, _, proxyURL, _ string) (*openai.TokenResponse, error) { + c.proxies = append(c.proxies, proxyURL) + return &openai.TokenResponse{AccessToken: "synthetic", ExpiresIn: 3600}, nil +} + +func oauthRequestProxyFixture(t *testing.T, request bool) (*OpenAIOAuthService, *oauthRequestProxyRepo, *oauthRequestProxyClient, *OpenAIExchangeCodeInput) { + t.Helper() + repo := &oauthRequestProxyRepo{proxies: map[int64]*Proxy{ + 11: {ID: 11, Protocol: "http", Host: "192.0.2.11", Port: 8080, Status: StatusActive}, + 22: {ID: 22, Protocol: "http", Host: "192.0.2.22", Port: 8080, Status: StatusActive}, + }} + client := &oauthRequestProxyClient{} + svc := NewOpenAIOAuthService(repo, client) + t.Cleanup(svc.Stop) + svc.sessionStore.Set("synthetic-session", &openai.OAuthSession{State: "synthetic-state", CodeVerifier: "verifier", ProxyURL: repo.proxies[11].URL(), RequestProxy: request, CreatedAt: time.Now()}) + return svc, repo, client, &OpenAIExchangeCodeInput{SessionID: "synthetic-session", State: "synthetic-state", Code: "synthetic-code", ProxyMode: OpenAIProxyModeRequest, ProxyIDs: []int64{11, 22}} +} + +func TestOpenAIOAuthRequestProxyExchangeKeepsOriginalExit(t *testing.T) { + for _, clientID := range []string{openai.ClientID, openai.ExcelClientID} { + t.Run(clientID, func(t *testing.T) { + svc, repo, client, input := oauthRequestProxyFixture(t, true) + session, _ := svc.sessionStore.Get(input.SessionID) + session.ClientID = clientID + input.ProxyIDs = []int64{22, 11} + override := int64(22) + input.ProxyID = &override + _, err := svc.ExchangeCode(context.Background(), input) + require.NoError(t, err) + require.Equal(t, []string{repo.proxies[11].URL()}, client.proxies, "group order or proxy_id must not replace the authorization exit") + }) + } +} + +func TestOpenAIOAuthRequestProxyExchangeRejectsInvalidOriginalExit(t *testing.T) { + for _, change := range []string{"removed from group", "deleted", "expired", "inactive", "URL changed", "empty group", "invalid group", "mode single", "mode omitted"} { + t.Run(change, func(t *testing.T) { + svc, repo, client, input := oauthRequestProxyFixture(t, true) + switch change { + case "removed from group": + input.ProxyIDs = []int64{22} + case "deleted": + delete(repo.proxies, 11) + case "expired": + expired := time.Now().Add(-time.Minute) + repo.proxies[11].ExpiresAt = &expired + case "inactive": + repo.proxies[11].Status = StatusDisabled + case "URL changed": + repo.proxies[11].Host = "192.0.2.99" + case "empty group": + input.ProxyIDs = nil + case "invalid group": + input.ProxyIDs = []int64{11, -1} + case "mode single": + input.ProxyMode = OpenAIProxyModeSingle + case "mode omitted": + input.ProxyMode = "" + } + _, err := svc.ExchangeCode(context.Background(), input) + require.Error(t, err) + require.Empty(t, client.proxies) + require.NotContains(t, err.Error(), "192.0.2") + require.NotContains(t, err.Error(), "synthetic private proxy address") + _, retained := svc.sessionStore.Get(input.SessionID) + require.True(t, retained, "a rejected exchange must not consume the session") + }) + } +} + +func TestOpenAIOAuthRequestProxyExchangeCannotUpgradeSingleSession(t *testing.T) { + svc, _, client, input := oauthRequestProxyFixture(t, false) + _, err := svc.ExchangeCode(context.Background(), input) + require.Equal(t, http.StatusBadRequest, infraerrors.Code(err)) + require.Empty(t, client.proxies) +} + +func TestOpenAIOAuthSingleProxyExchangeRetainsOverride(t *testing.T) { + svc, repo, client, input := oauthRequestProxyFixture(t, false) + input.ProxyMode = "" + input.ProxyIDs = nil + override := int64(22) + input.ProxyID = &override + _, err := svc.ExchangeCode(context.Background(), input) + require.NoError(t, err) + require.Equal(t, []string{repo.proxies[22].URL()}, client.proxies) +} diff --git a/backend/internal/service/openai_oauth_reauth.go b/backend/internal/service/openai_oauth_reauth.go index 6edfeb2b6d3b..771539e5e972 100644 --- a/backend/internal/service/openai_oauth_reauth.go +++ b/backend/internal/service/openai_oauth_reauth.go @@ -812,6 +812,11 @@ func (s *OpenAIOAuthReauthService) ClaimTaskWithEngines(ctx context.Context, wor _ = s.repo.MarkFailed(ctx, record.ID, workerID, "configured re-login proxy source is invalid") return nil, nil } + requestProxyEnabled := account.OpenAIRequestProxyEnabled() + if requestProxyEnabled && (engine != OpenAIOAuthReauthEngineLocal || proxySource != OpenAIOAuthReauthProxySourceAccount) { + _ = s.repo.MarkFailed(ctx, record.ID, workerID, "request proxy routing requires local re-login with the account proxy source") + return nil, nil + } proxyID := stored.ProxyID proxyError := "configured re-login proxy is unavailable" var proxyURL string @@ -821,7 +826,11 @@ func (s *OpenAIOAuthReauthService) ClaimTaskWithEngines(ctx context.Context, wor case OpenAIOAuthReauthProxySourceAccount: proxyID = account.ProxyID proxyError = "configured account proxy is unavailable" - proxyURL, proxyErr = s.reauthProxyURL(ctx, proxyID) + if requestProxyEnabled { + proxyURL, proxyErr = resolveOpenAIMaintenanceProxy(ctx, account, s.oauth.proxyRepo) + } else { + proxyURL, proxyErr = s.reauthProxyURL(ctx, proxyID) + } case OpenAIOAuthReauthProxySourceManagedProxy: proxyURL, proxyErr = s.reauthProxyURL(ctx, proxyID) case OpenAIOAuthReauthProxySourceMihomo: @@ -869,7 +878,7 @@ func (s *OpenAIOAuthReauthService) ClaimTaskWithEngines(ctx context.Context, wor } var auth *OpenAIAuthURLResult var authErr error - if proxySource == OpenAIOAuthReauthProxySourceMihomo { + if requestProxyEnabled || proxySource == OpenAIOAuthReauthProxySourceMihomo { auth, authErr = s.oauth.GenerateAuthURLWithProxyURL(ctx, proxyURL, "", PlatformOpenAI) } else { auth, authErr = s.oauth.GenerateAuthURL(ctx, proxyID, "", PlatformOpenAI) @@ -974,6 +983,21 @@ func (s *OpenAIOAuthReauthService) SubmitCallback(ctx context.Context, taskID in if err != nil || subtle.ConstantTimeCompare([]byte(currentCredentialsHash), []byte(record.ExpectedCredentialsHash)) != 1 { return s.failCallback(ctx, taskID, "account credentials changed while re-login was running", errors.New("credential snapshot mismatch")) } + if account.OpenAIRequestProxyEnabled() { + var session *openai.OAuthSession + var ok bool + if record.OAuthProfile == "siwc" { + session, ok = s.readSIWCSession(ctx, record.AuthSessionID, false) + } else if s.oauth.sessionStore != nil { + session, ok = s.oauth.sessionStore.Get(record.AuthSessionID) + } + if !ok || session == nil { + return s.failCallback(ctx, taskID, "authorization session is no longer available", errors.New("authorization session missing")) + } + if _, err := resolveOpenAIMaintenanceProxy(ctx, account, s.oauth.proxyRepo, session.ProxyURL); err != nil { + return s.failCallback(ctx, taskID, "authorization proxy is no longer in the available account proxy group", err) + } + } if record.OAuthProfile == "siwc" { if err := s.CompleteSIWCAuthorization(ctx, record.AccountID, record.AuthSessionID, callback, record); err != nil { return s.failCallback(ctx, taskID, "SIWC authorization failed; retry or complete browser consent", err) diff --git a/backend/internal/service/openai_oauth_reauth_request_proxy_test.go b/backend/internal/service/openai_oauth_reauth_request_proxy_test.go new file mode 100644 index 000000000000..281a70a036d7 --- /dev/null +++ b/backend/internal/service/openai_oauth_reauth_request_proxy_test.go @@ -0,0 +1,181 @@ +package service + +import ( + "context" + "net/url" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/pkg/openai" + "github.com/Wei-Shaw/sub2api/internal/pkg/redissession" + "github.com/alicebob/miniredis/v2" + "github.com/redis/go-redis/v9" + "github.com/stretchr/testify/require" +) + +type reauthRequestProxyRepo struct { + ProxyRepository + proxies map[int64]*Proxy +} + +func (r *reauthRequestProxyRepo) GetByID(_ context.Context, id int64) (*Proxy, error) { + return r.proxies[id], nil +} + +func TestOpenAIOAuthReauthRequestProxyKeepsSelectedExitThroughCallback(t *testing.T) { + svc, reader, _, _, client, _ := newReauthTestService("acct-1") + t.Cleanup(svc.oauth.Stop) + ctx := context.Background() + legacyID := int64(90) + reader.account.ProxyID = &legacyID + reader.account.Extra = map[string]any{ + "openai_proxy_mode": "request", + "openai_proxy_ids": []any{float64(1), float64(2)}, + } + reader.proxy = &Proxy{ID: legacyID, Status: StatusActive, Protocol: "http", Host: "outside.example", Port: 8080} + proxies := &reauthRequestProxyRepo{proxies: map[int64]*Proxy{ + 2: {ID: 2, Status: StatusActive, Protocol: "http", Host: "selected.example", Port: 8080}, + }} + svc.oauth.proxyRepo = proxies + _, err := svc.SaveConfig(ctx, 42, "user@example.com", "https://mail.example.com/code") + require.NoError(t, err) + _, err = svc.CreateTask(ctx, 42) + require.NoError(t, err) + + claim, err := svc.ClaimTask(ctx, "worker-a") + require.NoError(t, err) + require.NotNil(t, claim) + require.Equal(t, "http://selected.example:8080", claim.ProxyURL) + // A different member becoming available must not move an authorization + // session between the browser step and its code exchange. + proxies.proxies[1] = &Proxy{ID: 1, Status: StatusActive, Protocol: "http", Host: "earlier.example", Port: 8080} + state := reauthStateFromURL(t, claim.AuthURL) + task, err := svc.SubmitCallback(ctx, claim.TaskID, "worker-a", "http://localhost:1455/auth/callback?code=test-code&state="+url.QueryEscape(state)) + require.NoError(t, err) + require.Equal(t, OpenAIOAuthReauthStatusSucceeded, task.Status) + require.Equal(t, "http://selected.example:8080", client.proxyURL) + require.Equal(t, legacyID, *reader.account.ProxyID) +} + +func TestOpenAIOAuthReauthRequestProxyCallbackRejectsRemovedExit(t *testing.T) { + svc, reader, _, updater, client, _ := newReauthTestService("acct-1") + t.Cleanup(svc.oauth.Stop) + ctx := context.Background() + reader.account.Extra = map[string]any{ + "openai_proxy_mode": "request", + "openai_proxy_ids": []any{float64(2)}, + } + svc.oauth.proxyRepo = &reauthRequestProxyRepo{proxies: map[int64]*Proxy{ + 2: {ID: 2, Status: StatusActive, Protocol: "http", Host: "selected.example", Port: 8080}, + 3: {ID: 3, Status: StatusActive, Protocol: "http", Host: "replacement.example", Port: 8080}, + }} + _, err := svc.SaveConfig(ctx, 42, "user@example.com", "https://mail.example.com/code") + require.NoError(t, err) + _, err = svc.CreateTask(ctx, 42) + require.NoError(t, err) + claim, err := svc.ClaimTask(ctx, "worker-a") + require.NoError(t, err) + require.NotNil(t, claim) + require.Equal(t, "http://selected.example:8080", claim.ProxyURL) + + reader.account.Extra["openai_proxy_ids"] = []any{float64(3)} + state := reauthStateFromURL(t, claim.AuthURL) + _, err = svc.SubmitCallback(ctx, claim.TaskID, "worker-a", "http://localhost:1455/auth/callback?code=test-code&state="+url.QueryEscape(state)) + require.ErrorContains(t, err, "authorization proxy is no longer in the available account proxy group") + status, statusErr := svc.GetStatus(ctx, 42) + require.NoError(t, statusErr) + require.Equal(t, OpenAIOAuthReauthStatusFailed, status.Task.Status) + require.False(t, updater.applied) + require.Zero(t, client.exchanges, "an authorization session must not escape the current selected group") +} + +func TestOpenAIOAuthReauthRequestProxyCallbackRejectsPreviousSingleModeExit(t *testing.T) { + for _, legacyProxy := range []bool{false, true} { + name := "direct" + if legacyProxy { + name = "outside_proxy" + } + t.Run(name, func(t *testing.T) { + svc, reader, _, updater, client, _ := newReauthTestService("acct-1") + t.Cleanup(svc.oauth.Stop) + ctx := context.Background() + if legacyProxy { + id := int64(90) + reader.account.ProxyID = &id + reader.proxy = &Proxy{ID: id, Status: StatusActive, Protocol: "http", Host: "outside.example", Port: 8080} + } + _, err := svc.SaveConfig(ctx, 42, "user@example.com", "https://mail.example.com/code") + require.NoError(t, err) + _, err = svc.CreateTask(ctx, 42) + require.NoError(t, err) + claim, err := svc.ClaimTask(ctx, "worker-a") + require.NoError(t, err) + require.NotNil(t, claim) + reader.account.Extra = map[string]any{"openai_proxy_mode": "request", "openai_proxy_ids": []any{float64(2)}} + svc.oauth.proxyRepo = &reauthRequestProxyRepo{proxies: map[int64]*Proxy{ + 2: {ID: 2, Status: StatusActive, Protocol: "http", Host: "selected.example", Port: 8080}, + }} + state := reauthStateFromURL(t, claim.AuthURL) + _, err = svc.SubmitCallback(ctx, claim.TaskID, "worker-a", "http://localhost:1455/auth/callback?code=test-code&state="+url.QueryEscape(state)) + require.ErrorContains(t, err, "authorization proxy is no longer in the available account proxy group") + status, statusErr := svc.GetStatus(ctx, 42) + require.NoError(t, statusErr) + require.Equal(t, OpenAIOAuthReauthStatusFailed, status.Task.Status) + require.False(t, updater.applied) + require.Zero(t, client.exchanges) + }) + } +} + +func TestOpenAIOAuthReauthRequestProxyCallbackUsesSharedSIWCSession(t *testing.T) { + for _, removeExit := range []bool{false, true} { + name := "available" + if removeExit { + name = "removed" + } + t.Run(name, func(t *testing.T) { + mr := miniredis.RunT(t) + rdb := redis.NewClient(&redis.Options{Addr: mr.Addr()}) + t.Cleanup(func() { _ = rdb.Close() }) + svc, reader, repo, _, oldClient, _ := newReauthTestService("acct-1") + t.Cleanup(svc.oauth.Stop) + store := &siwcTestRepo{reauthTestRepo: repo} + svc.repo = store + svc.siwcSessionStore = redissession.New(rdb, siwcSessionPrefix, openai.SessionTTL) + client := &siwcTestClient{reauthTestOAuthClient: oldClient} + svc.oauth.oauthClient = client + reader.account.Extra = map[string]any{"openai_proxy_mode": "request", "openai_proxy_ids": []any{float64(2)}} + svc.oauth.proxyRepo = &reauthRequestProxyRepo{proxies: map[int64]*Proxy{ + 2: {ID: 2, Status: StatusActive, Protocol: "http", Host: "selected.example", Port: 8080}, + 3: {ID: 3, Status: StatusActive, Protocol: "http", Host: "replacement.example", Port: 8080}, + }} + ctx := context.Background() + savePasswordReauthConfig(t, svc) + _, err := svc.CreateTaskForProfile(ctx, 42, "siwc") + require.NoError(t, err) + claim, err := svc.ClaimTask(ctx, "worker-a") + require.NoError(t, err) + require.NotNil(t, claim) + require.Equal(t, "http://selected.example:8080", claim.ProxyURL) + if removeExit { + reader.account.Extra["openai_proxy_ids"] = []any{float64(3)} + } + state := reauthStateFromURL(t, claim.AuthURL) + _, err = svc.SubmitCallback(ctx, claim.TaskID, "worker-a", "http://127.0.0.1:1455/auth/callback?code=test-code&state="+url.QueryEscape(state)+"&client_id=issued") + if removeExit { + require.ErrorContains(t, err, "authorization proxy is no longer in the available account proxy group") + status, statusErr := svc.GetStatus(ctx, 42) + require.NoError(t, statusErr) + require.Equal(t, OpenAIOAuthReauthStatusFailed, status.Task.Status) + require.Zero(t, client.calls) + require.Zero(t, store.writes) + return + } + require.NoError(t, err) + status, statusErr := svc.SIWCStatus(ctx, 42) + require.NoError(t, statusErr) + require.True(t, status.Bound) + require.Equal(t, 1, client.calls) + require.Equal(t, 1, store.writes) + }) + } +} diff --git a/backend/internal/service/openai_oauth_request_proxy_test.go b/backend/internal/service/openai_oauth_request_proxy_test.go new file mode 100644 index 000000000000..7bf9373d0939 --- /dev/null +++ b/backend/internal/service/openai_oauth_request_proxy_test.go @@ -0,0 +1,125 @@ +package service + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/pkg/openai" + "github.com/imroc/req/v3" + "github.com/stretchr/testify/require" +) + +type openAIMaintenanceProxyRepo struct { + ProxyRepository + proxies map[int64]*Proxy + err error + requested []int64 +} + +func (r *openAIMaintenanceProxyRepo) GetByID(_ context.Context, id int64) (*Proxy, error) { + r.requested = append(r.requested, id) + if r.err != nil { + return nil, r.err + } + return r.proxies[id], nil +} + +type openAIMaintenanceOAuthClient struct { + openaiOAuthClientRefreshStub + proxies []string +} + +func (s *openAIMaintenanceOAuthClient) RefreshTokenWithClientID(_ context.Context, _, proxyURL, _ string) (*openai.TokenResponse, error) { + s.proxies = append(s.proxies, proxyURL) + return nil, errors.New("fake token endpoint") +} + +func TestOpenAIOAuthRefreshUsesSelectedRequestProxy(t *testing.T) { + expired := time.Now().Add(-time.Hour) + legacyID := int64(90) + repo := &openAIMaintenanceProxyRepo{proxies: map[int64]*Proxy{ + 1: {ID: 1, Status: StatusActive, Protocol: "http", Host: "expired.example", Port: 8080, ExpiresAt: &expired}, + 2: {ID: 2, Status: StatusDisabled, Protocol: "http", Host: "disabled.example", Port: 8080}, + 3: {ID: 3, Status: StatusActive, Protocol: "http", Host: "selected.example", Port: 8080}, + 90: {ID: 90, Status: StatusActive, Protocol: "http", Host: "legacy.example", Port: 8080}, + }} + client := &openAIMaintenanceOAuthClient{} + svc := NewOpenAIOAuthService(repo, client) + defer svc.Stop() + account := &Account{ID: 77, Platform: PlatformOpenAI, Type: AccountTypeOAuth, ProxyID: &legacyID, + Credentials: map[string]any{"refresh_token": "fake-refresh"}, + Extra: map[string]any{"openai_proxy_mode": "request", "openai_proxy_ids": []any{float64(1), float64(2), float64(3)}}, + } + _, err := svc.RefreshAccountToken(context.Background(), account) + require.ErrorContains(t, err, "fake token endpoint") + require.Equal(t, []string{"http://selected.example:8080"}, client.proxies) + require.Equal(t, []int64{1, 2, 3}, repo.requested) + require.Equal(t, legacyID, *account.ProxyID) +} + +func TestOpenAIOAuthRefreshRequestProxyUnavailableNeverCallsUpstream(t *testing.T) { + for _, tc := range []struct { + name string + ids []any + repo *openAIMaintenanceProxyRepo + }{ + {name: "empty selection"}, + {name: "repository unavailable", ids: []any{float64(1)}}, + {name: "missing member", ids: []any{float64(1)}, repo: &openAIMaintenanceProxyRepo{}}, + {name: "lookup error", ids: []any{float64(1)}, repo: &openAIMaintenanceProxyRepo{err: errors.New("http://private:secret@example.invalid")}}, + {name: "unsupported proxy", ids: []any{float64(1)}, repo: &openAIMaintenanceProxyRepo{proxies: map[int64]*Proxy{1: {ID: 1, Status: StatusActive, Protocol: "file", Host: "bad.example", Port: 80}}}}, + } { + t.Run(tc.name, func(t *testing.T) { + for _, hasRefresh := range []bool{false, true} { + client := &openAIMaintenanceOAuthClient{} + var repository ProxyRepository + if tc.repo != nil { + repository = tc.repo + } + svc := NewOpenAIOAuthService(repository, client) + defer svc.Stop() + privacyCalls := 0 + svc.SetPrivacyClientFactory(func(string) (*req.Client, error) { privacyCalls++; return nil, errors.New("unexpected enrichment") }) + account := &Account{Platform: PlatformOpenAI, Type: AccountTypeOAuth, Credentials: map[string]any{"access_token": "fake-access"}, Extra: map[string]any{"openai_proxy_mode": "request", "openai_proxy_ids": tc.ids}} + if hasRefresh { + account.Credentials["refresh_token"] = "fake-refresh" + } + _, err := svc.RefreshAccountToken(context.Background(), account) + require.ErrorContains(t, err, "direct fallback is disabled") + require.NotContains(t, err.Error(), "secret") + require.Empty(t, client.proxies) + require.Zero(t, privacyCalls) + } + }) + } +} + +func TestOpenAIOAuthRefreshExplicitSingleOverridesLegacyGroup(t *testing.T) { + id := int64(90) + repo := &openAIMaintenanceProxyRepo{proxies: map[int64]*Proxy{90: {ID: 90, Protocol: "http", Host: "single.example", Port: 8080}}} + client := &openAIMaintenanceOAuthClient{} + svc := NewOpenAIOAuthService(repo, client) + defer svc.Stop() + account := &Account{Platform: PlatformOpenAI, Type: AccountTypeOAuth, ProxyID: &id, Credentials: map[string]any{"refresh_token": "fake"}, Extra: map[string]any{"openai_proxy_mode": "single", "openai_excel_bps": true, "openai_excel_bps_proxy_mode": "request", "openai_excel_bps_proxy_ids": []any{float64(1)}}} + _, err := svc.RefreshAccountToken(context.Background(), account) + require.ErrorContains(t, err, "fake token endpoint") + require.Equal(t, []string{"http://single.example:8080"}, client.proxies) +} + +func TestOpenAIOAuthRefreshKeepsLogicalRequestExit(t *testing.T) { + repo := &openAIMaintenanceProxyRepo{proxies: map[int64]*Proxy{ + 1: {ID: 1, Status: StatusActive, Protocol: "http", Host: "first.example", Port: 8080}, + 2: {ID: 2, Status: StatusActive, Protocol: "http", Host: "leased.example", Port: 8080}, + }} + client := &openAIMaintenanceOAuthClient{} + svc := NewOpenAIOAuthService(repo, client) + defer svc.Stop() + account := &Account{ID: 77, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Credentials: map[string]any{"refresh_token": "fake-refresh"}, Extra: map[string]any{"openai_proxy_mode": "request", "openai_proxy_ids": []any{float64(1), float64(2)}}} + route := &openAIRequestProxyRoute{accountID: account.ID, proxy: "http://leased.example:8080"} + ctx := context.WithValue(context.Background(), openAIRequestProxyContextKey{}, route) + _, err := svc.RefreshAccountToken(ctx, account) + require.ErrorContains(t, err, "fake token endpoint") + require.Equal(t, []string{"http://leased.example:8080"}, client.proxies) +} diff --git a/backend/internal/service/openai_oauth_service.go b/backend/internal/service/openai_oauth_service.go index 58acd9cac154..69960f5480cf 100644 --- a/backend/internal/service/openai_oauth_service.go +++ b/backend/internal/service/openai_oauth_service.go @@ -48,6 +48,8 @@ func (s *OpenAIOAuthService) SetPrivacyClientFactory(factory PrivacyClientFactor type OpenAIAuthURLResult struct { AuthURL string `json:"auth_url"` SessionID string `json:"session_id"` + ProxyMode string `json:"proxy_mode,omitempty"` + ProxyID int64 `json:"proxy_id,omitempty"` } // GenerateAuthURL generates an OpenAI OAuth authorization URL @@ -67,6 +69,10 @@ func (s *OpenAIOAuthService) GenerateAuthURL(ctx context.Context, proxyID *int64 // GenerateAuthURLWithProxyURL creates a session with an already resolved egress URL. func (s *OpenAIOAuthService) GenerateAuthURLWithProxyURL(ctx context.Context, proxyURL, redirectURI, platform string, oauthClient ...string) (*OpenAIAuthURLResult, error) { + return s.generateAuthURLWithProxyURL(ctx, proxyURL, false, redirectURI, platform, oauthClient...) +} + +func (s *OpenAIOAuthService) generateAuthURLWithProxyURL(ctx context.Context, proxyURL string, requestProxy bool, redirectURI, platform string, oauthClient ...string) (*OpenAIAuthURLResult, error) { profile := "codex" if len(oauthClient) > 0 && strings.TrimSpace(oauthClient[0]) != "" { profile = strings.TrimSpace(oauthClient[0]) @@ -115,6 +121,7 @@ func (s *OpenAIOAuthService) GenerateAuthURLWithProxyURL(ctx context.Context, pr ClientID: clientID, RedirectURI: redirectURI, ProxyURL: strings.TrimSpace(proxyURL), + RequestProxy: requestProxy, CreatedAt: time.Now(), } s.sessionStore.Set(sessionID, session) @@ -138,6 +145,8 @@ type OpenAIExchangeCodeInput struct { State string RedirectURI string ProxyID *int64 + ProxyMode string + ProxyIDs []int64 } // OpenAITokenInfo represents the token information for OpenAI @@ -176,9 +185,21 @@ func (s *OpenAIOAuthService) ExchangeCode(ctx context.Context, input *OpenAIExch return nil, infraerrors.New(http.StatusBadRequest, "OPENAI_OAUTH_INVALID_STATE", "invalid oauth state") } - // Get proxy URL: prefer input.ProxyID, fallback to session.ProxyURL + requestProxy, err := openAIOAuthRequestProxySettings(input.ProxyMode, input.ProxyIDs) + if err != nil { + return nil, err + } + if requestProxy != session.RequestProxy { + return nil, infraerrors.BadRequest("OPENAI_OAUTH_PROXY_MODE_CHANGED", "Proxy mode changed; generate a new authorization URL") + } + proxyURL := session.ProxyURL - if input.ProxyID != nil { + if requestProxy { + _, proxyURL, err = s.resolveOAuthRequestProxy(ctx, input.ProxyIDs, session.ProxyURL) + if err != nil { + return nil, err + } + } else if input.ProxyID != nil { proxy, err := s.proxyRepo.GetByID(ctx, *input.ProxyID) if err != nil { return nil, infraerrors.Newf(http.StatusBadRequest, "OPENAI_OAUTH_PROXY_NOT_FOUND", "proxy not found: %v", err) @@ -381,7 +402,13 @@ func (s *OpenAIOAuthService) RefreshAccountToken(ctx context.Context, account *A } var proxyURL string - if account.ProxyID != nil && s.proxyRepo != nil { + if account.OpenAIRequestProxyEnabled() { + var err error + proxyURL, err = resolveOpenAIMaintenanceProxy(ctx, account, s.proxyRepo) + if err != nil { + return nil, err + } + } else if account.ProxyID != nil && s.proxyRepo != nil { proxy, err := s.proxyRepo.GetByID(ctx, *account.ProxyID) if err == nil && proxy != nil { proxyURL = proxy.URL() diff --git a/backend/internal/service/openai_plugin_transport.go b/backend/internal/service/openai_plugin_transport.go index 753844218f21..ca81d73454b1 100644 --- a/backend/internal/service/openai_plugin_transport.go +++ b/backend/internal/service/openai_plugin_transport.go @@ -15,6 +15,27 @@ func (s *OpenAIGatewayService) SetPluginManager(manager *PluginManager) { // doOpenAIUpstream 只在 OpenAI OAuth 能力绑定已启用时把真实请求交给插件。 // 插件返回标准 http.Response,响应解析、错误映射、SSE 和计费仍由现有核心链处理。 func (s *OpenAIGatewayService) doOpenAIUpstream(request *http.Request, proxyURL string, account *Account) (result *http.Response, resultErr error) { + route, scoped := openAIRequestProxyFromContext(request.Context(), account.ID) + // A fresh admission snapshot may disable request routing after acquisition. + // Reject before send rather than bypassing the scope's cancellation/body fence. + if route != nil && !account.OpenAIRequestProxyEnabled() { + return nil, denyOpenAITurn("account_binding_changed") + } + if account.OpenAIRequestProxyEnabled() { + if !scoped { + return nil, errOpenAIRequestProxyUnavailable + } + var bindErr error + request, bindErr = route.bind(request) + if bindErr != nil { + return nil, bindErr + } + proxyURL = route.proxy + defer func() { route.track(result) }() + if s.codexTicketPinsEgress(request, account) || account.AuthConnectionID != "" { + return nil, errOpenAIRequestProxyUnavailable + } + } if s.excelOAuthReauth != nil { if err := s.excelOAuthReauth.validateAuthConnectionPolicy(request.Context(), account); err != nil { return nil, err @@ -139,8 +160,38 @@ func (s *AccountTestService) doOpenAIAccountTestUpstream( account *Account, useTLSFallback bool, body []byte, -) (*http.Response, error) { +) (result *http.Response, resultErr error) { gateway := s.openaiGatewayService + if account.OpenAIRequestProxyEnabled() { + if account.AuthConnectionID != "" { + return nil, errOpenAIRequestProxyUnavailable + } + // Scope acquisition is independent of optional plugin/ticket services. + scopeService := gateway + if scopeService == nil { + scopeService = &OpenAIGatewayService{} + } + ctx, release, err := scopeService.beginOpenAIRequestProxy(request.Context(), nil, account) + if err != nil { + return nil, err + } + request = request.WithContext(ctx) + route, _ := openAIRequestProxyFromContext(ctx, account.ID) + request, err = route.bind(request) + if err != nil { + release() + return nil, err + } + proxyURL = route.proxy + defer func() { + if resultErr != nil || result == nil || result.Body == nil { + release() + return + } + route.track(result) + result.Body = &openAIRequestProxyOwnedBody{ReadCloser: result.Body, finish: release} + }() + } model := extractOpenAICodexTicketModel(body) if gateway != nil && !IsAstraSourceAcquisition(request.Context()) && request.URL != nil && request.URL.String() == chatgptCodexAPIURL && isOpenAICodexTicketAccount(account, model) && gateway.openAICodexTicketEnabledContext(request.Context()) && @@ -153,7 +204,7 @@ func (s *AccountTestService) doOpenAIAccountTestUpstream( request = request.WithContext(context.WithValue(request.Context(), astraCandySkipObservationKey{}, true)) return gateway.doOpenAIUpstream(request, proxyURL, account) } - if s.pluginManager != nil { + if s.pluginManager != nil && !account.OpenAIRequestProxyEnabled() { response, handled, err := s.pluginManager.RoundTripOpenAIOAuth(request.Context(), request, proxyURL, account) if handled { if options, ok := pelicanTestOptionsFromContext(request.Context()); ok && options.nativeOAuthTransport != nil && !IsAstraSourceAcquisition(request.Context()) { diff --git a/backend/internal/service/openai_proxy_routing.go b/backend/internal/service/openai_proxy_routing.go new file mode 100644 index 000000000000..474767a37025 --- /dev/null +++ b/backend/internal/service/openai_proxy_routing.go @@ -0,0 +1,141 @@ +package service + +import ( + "context" + "slices" + "strings" + "time" + + infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" +) + +const ( + OpenAIProxyModeKey = "openai_proxy_mode" + OpenAIProxyIDsKey = "openai_proxy_ids" + OpenAIProxyModeSingle = "single" + OpenAIProxyModeRequest = "request" +) + +func (a *Account) supportsOpenAIRequestProxies() bool { + return a != nil && a.Platform == PlatformOpenAI && a.Type == AccountTypeOAuth && + !a.IsShadow() && !a.IsOpenAIAgentIdentity() && !a.IsOpenAIPersonalAccessToken() +} + +// OpenAIProxyMode returns saved routing configuration. A legacy group remains +// saved when BPS is off, but OpenAIRequestProxyEnabled does not activate it. +func (a *Account) OpenAIProxyMode() string { + if a == nil { + return OpenAIProxyModeSingle + } + if raw, ok := a.Extra[OpenAIProxyModeKey]; ok { + if mode, valid := raw.(string); valid { + return mode + } + return "invalid" + } + if a.Extra[ExcelBPSProxyModeKey] == ExcelBPSProxyModeRequest { + return OpenAIProxyModeRequest + } + return OpenAIProxyModeSingle +} + +// OpenAIRequestProxyEnabled keeps invalid explicit configuration on the +// fail-closed route instead of silently reverting to a single/direct exit. +func (a *Account) OpenAIRequestProxyEnabled() bool { + if !a.supportsOpenAIRequestProxies() { + return false + } + if _, explicit := a.Extra[OpenAIProxyModeKey]; explicit { + return a.OpenAIProxyMode() != OpenAIProxyModeSingle + } + return a.IsExcelBPSEnabled() && a.OpenAIProxyMode() == OpenAIProxyModeRequest +} + +func (a *Account) OpenAIRequestProxyIDs() []int64 { + if a == nil { + return nil + } + key := ExcelBPSProxyIDsKey + if _, explicit := a.Extra[OpenAIProxyModeKey]; explicit { + if mode := a.OpenAIProxyMode(); mode != OpenAIProxyModeSingle && mode != OpenAIProxyModeRequest { + return nil + } + key = OpenAIProxyIDsKey + } + ids, _ := parseExcelBPSProxyIDs(a.Extra[key]) + return ids +} + +func (s *adminServiceImpl) validateOpenAIProxySettingsChange(ctx context.Context, previous, account *Account) error { + rawMode, supplied := account.Extra[OpenAIProxyModeKey] + if supplied && rawMode != OpenAIProxyModeSingle && rawMode != OpenAIProxyModeRequest { + return infraerrors.BadRequest("INVALID_OPENAI_PROXY_MODE", "OpenAI proxy mode must be single or request") + } + ids, valid := parseExcelBPSProxyIDs(account.Extra[OpenAIProxyIDsKey]) + if !valid { + return infraerrors.BadRequest("INVALID_OPENAI_PROXY_IDS", "OpenAI proxy IDs must be positive integers") + } + if !supplied && len(ids) == 0 { + return nil + } + if !supplied { + return infraerrors.BadRequest("INVALID_OPENAI_PROXY_MODE", "OpenAI proxy IDs require an explicit proxy mode") + } + if !account.supportsOpenAIRequestProxies() { + return infraerrors.BadRequest("INVALID_OPENAI_PROXY_ACCOUNT", "request proxies require an OpenAI OAuth account") + } + if rawMode != OpenAIProxyModeRequest { + return nil + } + if err := s.validateOpenAIRequestProxyConnection(ctx, previous, account); err != nil { + return err + } + if len(ids) == 0 { + return infraerrors.BadRequest("OPENAI_PROXY_GROUP_REQUIRED", "select at least one OpenAI proxy") + } + if previous != nil && previous.Extra[OpenAIProxyModeKey] == rawMode && + slices.Equal(previous.OpenAIRequestProxyIDs(), ids) && previous.OpenAIRequestProxyEnabled() { + return nil + } + if s.proxyRepo == nil { + return infraerrors.BadRequest("OPENAI_PROXY_NOT_FOUND", "selected OpenAI proxy not found or unavailable") + } + proxies, err := s.proxyRepo.ListByIDs(ctx, ids) + if err != nil { + return err + } + now := time.Now() + found := make(map[int64]bool, len(proxies)) + for _, proxy := range proxies { + found[proxy.ID] = proxy.IsActive() && !proxy.IsExpired(now) + } + for _, id := range ids { + if !found[id] { + return infraerrors.BadRequest("OPENAI_PROXY_NOT_FOUND", "selected OpenAI proxy not found or unavailable") + } + } + account.Extra[OpenAIProxyIDsKey] = ids + return nil +} + +func (s *adminServiceImpl) validateOpenAIRequestProxyConnection(ctx context.Context, previous, account *Account) error { + unsupported := func() error { + return infraerrors.BadRequest("OPENAI_PROXY_CONNECTION_UNSUPPORTED", "request proxies cannot override a fixed or managed OpenAI auth connection") + } + if strings.TrimSpace(account.AuthConnectionID) != "" || account.HasManagedOpenAIConnections() || + previous != nil && (strings.TrimSpace(previous.AuthConnectionID) != "" || previous.HasManagedOpenAIConnections()) { + return unsupported() + } + if account.ID > 0 && s.excelOAuthReauth != nil { + if repo, ok := s.excelOAuthReauth.repo.(OpenAIAuthConnectionRepository); ok { + managed, err := repo.AuthConnectionsManaged(ctx, account.ID) + if err != nil { + return infraerrors.ServiceUnavailable("OPENAI_PROXY_CONNECTION_CHECK_FAILED", "OpenAI authorization connection status is temporarily unavailable") + } + if managed { + return unsupported() + } + } + } + return nil +} diff --git a/backend/internal/service/openai_proxy_routing_test.go b/backend/internal/service/openai_proxy_routing_test.go new file mode 100644 index 000000000000..8bbc4a9617a0 --- /dev/null +++ b/backend/internal/service/openai_proxy_routing_test.go @@ -0,0 +1,214 @@ +//go:build unit + +package service + +import ( + "context" + "errors" + "net/http" + "testing" + "time" + + infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" + "github.com/stretchr/testify/require" +) + +func TestOpenAIProxyRoutingUsesExplicitModeBeforeLegacy(t *testing.T) { + for _, tc := range []struct { + name string + extra map[string]any + enabled bool + bps bool + ids []int64 + }{ + {"ordinary OAuth request", map[string]any{"openai_proxy_mode": "request", "openai_proxy_ids": []any{float64(11), float64(22), float64(11)}}, true, false, []int64{11, 22}}, + {"single overrides legacy", map[string]any{"openai_excel_bps": true, "openai_proxy_mode": "single", "openai_proxy_ids": []int64{22}, ExcelBPSProxyModeKey: "request", ExcelBPSProxyIDsKey: []int64{11}}, false, false, []int64{22}}, + {"new group overrides legacy", map[string]any{"openai_excel_bps": true, "openai_proxy_mode": "request", "openai_proxy_ids": []int64{22}, ExcelBPSProxyModeKey: "request", ExcelBPSProxyIDsKey: []int64{11}}, true, true, []int64{22}}, + {"legacy BPS request", map[string]any{"openai_excel_bps": true, ExcelBPSProxyModeKey: "request", ExcelBPSProxyIDsKey: []int64{11}}, true, true, []int64{11}}, + {"disabled legacy BPS stays inactive", map[string]any{"openai_excel_bps": false, ExcelBPSProxyModeKey: "request", ExcelBPSProxyIDsKey: []int64{11}}, false, false, []int64{11}}, + {"empty group fails closed", map[string]any{"openai_proxy_mode": "request"}, true, false, nil}, + {"invalid group fails closed", map[string]any{"openai_proxy_mode": "request", "openai_proxy_ids": []any{"11"}}, true, false, nil}, + {"invalid stored mode fails closed", map[string]any{"openai_proxy_mode": "invalid", "openai_proxy_ids": []int64{11}}, true, false, nil}, + } { + t.Run(tc.name, func(t *testing.T) { + account := &Account{Platform: PlatformOpenAI, Type: AccountTypeOAuth, Extra: tc.extra} + require.Equal(t, tc.enabled, account.OpenAIRequestProxyEnabled()) + require.Equal(t, tc.bps, account.ExcelBPSRequestProxyEnabled()) + require.Equal(t, tc.ids, account.OpenAIRequestProxyIDs()) + require.Equal(t, tc.ids, account.ExcelBPSRequestProxyIDs()) + }) + } +} + +func TestOpenAIProxyRoutingRejectsUnsupportedAccounts(t *testing.T) { + for _, credentials := range []map[string]any{{"auth_mode": "agentIdentity"}, {"auth_mode": "personalAccessToken"}, {"openai_auth_mode": "personal_access_token"}} { + account := &Account{Platform: PlatformOpenAI, Type: AccountTypeOAuth, Credentials: credentials, Extra: map[string]any{"openai_proxy_mode": "request", "openai_proxy_ids": []int64{11}}} + require.False(t, account.OpenAIRequestProxyEnabled()) + } +} + +func TestAdminOpenAIProxyConfigurationRoundTrip(t *testing.T) { + svc, _ := newBPSProxyConfigService() + proxyID := int64(11) + account, err := svc.CreateAccount(context.Background(), &CreateAccountInput{ + Name: "ordinary OAuth", Platform: PlatformOpenAI, Type: AccountTypeOAuth, SkipDefaultGroupBind: true, ProxyID: &proxyID, Concurrency: 6, + Extra: map[string]any{"openai_proxy_mode": "request", "openai_proxy_ids": []any{float64(11), float64(22), float64(11)}}, + }) + require.NoError(t, err) + require.True(t, account.OpenAIRequestProxyEnabled()) + require.Equal(t, []int64{11, 22}, account.OpenAIRequestProxyIDs()) + require.Equal(t, []int64{11, 22}, account.Extra[OpenAIProxyIDsKey]) + + account, err = svc.UpdateAccount(context.Background(), account.ID, &UpdateAccountInput{Extra: map[string]any{"unrelated": true}}) + require.NoError(t, err) + require.True(t, account.OpenAIRequestProxyEnabled(), "older forms retain explicit settings") + account, err = svc.UpdateAccount(context.Background(), account.ID, &UpdateAccountInput{Extra: map[string]any{"openai_proxy_mode": "single"}}) + require.NoError(t, err) + require.False(t, account.OpenAIRequestProxyEnabled()) + require.Equal(t, []int64{11, 22}, account.OpenAIRequestProxyIDs()) + require.Equal(t, &proxyID, account.ProxyID) + require.Equal(t, 6, account.Concurrency) +} + +func TestAdminOpenAIProxyRejectsInvalidConfiguration(t *testing.T) { + expired := time.Now().Add(-time.Minute) + for _, tc := range []struct { + name string + mode any + ids any + proxy *Proxy + }{ + {"unknown mode", "round-robin", []int64{11}, nil}, + {"null mode", nil, []int64{11}, nil}, + {"empty group", "request", []int64{}, nil}, + {"missing proxy", "request", []int64{99}, nil}, + {"fractional ID", "request", []any{11.5}, nil}, + {"string ID", "request", []any{"11"}, nil}, + {"disabled proxy", "request", []int64{11}, &Proxy{ID: 11, Status: StatusDisabled}}, + {"expired proxy", "request", []int64{11}, &Proxy{ID: 11, Status: StatusActive, ExpiresAt: &expired}}, + } { + t.Run(tc.name, func(t *testing.T) { + svc, _ := newBPSProxyConfigService() + if tc.proxy != nil { + svc.proxyRepo = &bpsProxyConfigProxies{proxies: []Proxy{*tc.proxy}} + } + _, err := svc.CreateAccount(context.Background(), &CreateAccountInput{Platform: PlatformOpenAI, Type: AccountTypeOAuth, SkipDefaultGroupBind: true, Extra: map[string]any{"openai_proxy_mode": tc.mode, "openai_proxy_ids": tc.ids}}) + require.Equal(t, http.StatusBadRequest, infraerrors.Code(err)) + }) + } +} + +func TestAdminOpenAIProxyIDsRequireExplicitMode(t *testing.T) { + svc, _ := newBPSProxyConfigService() + _, err := svc.CreateAccount(context.Background(), &CreateAccountInput{Platform: PlatformOpenAI, Type: AccountTypeOAuth, SkipDefaultGroupBind: true, Extra: map[string]any{OpenAIProxyIDsKey: []int64{11}}}) + require.Equal(t, http.StatusBadRequest, infraerrors.Code(err)) +} + +func TestAdminOpenAIProxyPartialAndBulkValidateMergedConfiguration(t *testing.T) { + for _, bulk := range []bool{false, true} { + svc, repo := newBPSProxyConfigService() + repo.account = &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Extra: map[string]any{"openai_proxy_mode": "request", "openai_proxy_ids": []int64{11}}} + var err error + if bulk { + _, err = svc.BulkUpdateAccounts(context.Background(), &BulkUpdateAccountsInput{AccountIDs: []int64{1}, Extra: map[string]any{"openai_proxy_ids": []any{}}}) + } else { + err = svc.UpdateAccountExtra(context.Background(), 1, map[string]any{"openai_proxy_ids": []any{}}) + } + require.Equal(t, http.StatusBadRequest, infraerrors.Code(err)) + require.Equal(t, []int64{11}, repo.account.OpenAIRequestProxyIDs()) + } +} + +func TestAdminOpenAIProxyRejectsFixedAuthConnection(t *testing.T) { + svc, repo := newBPSProxyConfigService() + repo.account = &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth, AuthConnectionID: "fixed-connection", Extra: map[string]any{}} + _, err := svc.UpdateAccount(context.Background(), 1, &UpdateAccountInput{Extra: map[string]any{OpenAIProxyModeKey: OpenAIProxyModeRequest, OpenAIProxyIDsKey: []int64{11}}}) + require.Equal(t, http.StatusBadRequest, infraerrors.Code(err)) + _, err = svc.UpdateAccount(context.Background(), 1, &UpdateAccountInput{Extra: map[string]any{OpenAIProxyModeKey: OpenAIProxyModeSingle}}) + require.NoError(t, err) +} + +func TestAdminOpenAIProxyRejectsManagedAuthConnections(t *testing.T) { + for _, legacy := range []bool{false, true} { + t.Run(map[bool]string{false: "explicit", true: "legacy"}[legacy], func(t *testing.T) { + svc, repo := newBPSProxyConfigService() + repo.account = &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Extra: map[string]any{"openai_connections_managed": true}} + extra := map[string]any{"openai_connections_managed": true, OpenAIProxyModeKey: OpenAIProxyModeRequest, OpenAIProxyIDsKey: []int64{11}} + if legacy { + extra = map[string]any{"openai_connections_managed": true, "openai_excel_bps": true, ExcelBPSProxyModeKey: ExcelBPSProxyModeRequest, ExcelBPSProxyIDsKey: []int64{11}} + } + _, err := svc.UpdateAccount(context.Background(), 1, &UpdateAccountInput{Extra: extra}) + require.Equal(t, http.StatusBadRequest, infraerrors.Code(err)) + }) + } +} + +func TestAdminOpenAIProxyCannotEraseManagedMarkerToEnableRequestMode(t *testing.T) { + for _, legacy := range []bool{false, true} { + t.Run(map[bool]string{false: "explicit", true: "legacy"}[legacy], func(t *testing.T) { + svc, repo := newBPSProxyConfigService() + repo.account = &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Extra: map[string]any{"openai_connections_managed": true}} + extra := map[string]any{OpenAIProxyModeKey: OpenAIProxyModeRequest, OpenAIProxyIDsKey: []int64{11}} + if legacy { + extra = map[string]any{"openai_excel_bps": true, ExcelBPSProxyModeKey: ExcelBPSProxyModeRequest, ExcelBPSProxyIDsKey: []int64{11}} + } + _, err := svc.UpdateAccount(context.Background(), 1, &UpdateAccountInput{Extra: extra}) + require.Equal(t, http.StatusBadRequest, infraerrors.Code(err)) + require.Equal(t, "OPENAI_PROXY_CONNECTION_UNSUPPORTED", infraerrors.Reason(err)) + }) + } +} + +type openAIProxyManagedPolicyRepo struct { + OpenAIOAuthReauthRepository + OpenAIAuthConnectionRepository + managed bool + err error +} + +func (r *openAIProxyManagedPolicyRepo) AuthConnectionsManaged(context.Context, int64) (bool, error) { + return r.managed, r.err +} + +func TestAdminOpenAIProxyChecksStoredManagedPolicy(t *testing.T) { + for _, legacy := range []bool{false, true} { + t.Run(map[bool]string{false: "explicit", true: "legacy"}[legacy], func(t *testing.T) { + svc, repo := newBPSProxyConfigService() + repo.account = &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Extra: map[string]any{}} + svc.excelOAuthReauth = &OpenAIOAuthReauthService{repo: &openAIProxyManagedPolicyRepo{managed: true}} + extra := map[string]any{OpenAIProxyModeKey: OpenAIProxyModeRequest, OpenAIProxyIDsKey: []int64{11}} + if legacy { + extra = map[string]any{"openai_excel_bps": true, ExcelBPSProxyModeKey: ExcelBPSProxyModeRequest, ExcelBPSProxyIDsKey: []int64{11}} + } + _, err := svc.UpdateAccount(context.Background(), 1, &UpdateAccountInput{Extra: extra}) + require.Equal(t, http.StatusBadRequest, infraerrors.Code(err)) + require.Equal(t, "OPENAI_PROXY_CONNECTION_UNSUPPORTED", infraerrors.Reason(err)) + }) + } +} + +func TestAdminOpenAIProxyManagedPolicyReadFailsClosed(t *testing.T) { + svc, repo := newBPSProxyConfigService() + repo.account = &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Extra: map[string]any{}} + svc.excelOAuthReauth = &OpenAIOAuthReauthService{repo: &openAIProxyManagedPolicyRepo{err: errors.New("sensitive database endpoint")}} + _, err := svc.UpdateAccount(context.Background(), 1, &UpdateAccountInput{Extra: map[string]any{OpenAIProxyModeKey: OpenAIProxyModeRequest, OpenAIProxyIDsKey: []int64{11}}}) + require.Equal(t, http.StatusServiceUnavailable, infraerrors.Code(err)) + require.NotContains(t, err.Error(), "sensitive database endpoint") +} + +func TestAdminOpenAIProxyMissingExitCanBeEditedOrDisabled(t *testing.T) { + for _, input := range []*UpdateAccountInput{{Name: "renamed"}, {Extra: map[string]any{"unrelated": true}}, {Extra: map[string]any{OpenAIProxyModeKey: OpenAIProxyModeSingle}}} { + svc, repo := newBPSProxyConfigService() + repo.account = &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Extra: map[string]any{OpenAIProxyModeKey: OpenAIProxyModeRequest, OpenAIProxyIDsKey: []int64{99}}} + updated, err := svc.UpdateAccount(context.Background(), 1, input) + require.NoError(t, err) + require.Equal(t, []int64{99}, updated.OpenAIRequestProxyIDs()) + } +} + +func TestAdminOpenAIProxyBulkCredentialChangeCannotBypassEligibility(t *testing.T) { + svc, repo := newBPSProxyConfigService() + repo.account = &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Extra: map[string]any{OpenAIProxyModeKey: OpenAIProxyModeRequest, OpenAIProxyIDsKey: []int64{11}}} + _, err := svc.BulkUpdateAccounts(context.Background(), &BulkUpdateAccountsInput{AccountIDs: []int64{1}, Credentials: map[string]any{"auth_mode": "personalAccessToken"}}) + require.Equal(t, http.StatusBadRequest, infraerrors.Code(err)) +} diff --git a/backend/internal/service/openai_proxy_runtime_fallback.go b/backend/internal/service/openai_proxy_runtime_fallback.go index 59b364d6b152..4b6cac7c4ec0 100644 --- a/backend/internal/service/openai_proxy_runtime_fallback.go +++ b/backend/internal/service/openai_proxy_runtime_fallback.go @@ -163,7 +163,7 @@ func (s *OpenAIGatewayService) doOpenAIProxyAttempt(req *http.Request, account * if err = s.fenceAuthConnectionEgress(req.Context(), req, account); err != nil { return nil, err } - if s.pluginManager != nil && account.AuthConnectionID == "" && !s.codexTicketRequestBound(req, account) { + if s.pluginManager != nil && !account.OpenAIRequestProxyEnabled() && account.AuthConnectionID == "" && !s.codexTicketRequestBound(req, account) { resp, handled, err := s.pluginManager.RoundTripOpenAIOAuth(req.Context(), req, target.url, account) if handled { if options, ok := pelicanTestOptionsFromContext(req.Context()); ok && options.nativeOAuthTransport != nil && !IsAstraSourceAcquisition(req.Context()) { @@ -194,7 +194,7 @@ func (s *OpenAIGatewayService) doUpstreamWithProxyFallback(ctx context.Context, primary.proxyID = account.Proxy.ID primary.proxyName = account.Proxy.Name } - if isControlledExperiment(ctx) || s.codexTicketPinsEgress(req, account) || account.Proxy == nil || primaryProxyURL == "" || + if account.OpenAIRequestProxyEnabled() || isControlledExperiment(ctx) || s.codexTicketPinsEgress(req, account) || account.Proxy == nil || primaryProxyURL == "" || primaryProxyURL != account.Proxy.URL() || (account.Proxy.FallbackMode != FallbackModeDirect && account.Proxy.FallbackMode != FallbackModeProxy) { return s.doOpenAIProxyAttempt(req, account, primary) diff --git a/backend/internal/service/openai_quota_request_proxy_test.go b/backend/internal/service/openai_quota_request_proxy_test.go new file mode 100644 index 000000000000..83db00b66b33 --- /dev/null +++ b/backend/internal/service/openai_quota_request_proxy_test.go @@ -0,0 +1,271 @@ +package service + +import ( + "context" + "errors" + "fmt" + "net" + "net/http" + "net/http/httptest" + "net/url" + "strconv" + "sync/atomic" + "testing" + "time" + + infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" + "github.com/imroc/req/v3" + "github.com/stretchr/testify/require" +) + +type quotaMaintenanceProxyRepo struct { + ProxyRepository + proxies map[int64]*Proxy + err error +} + +func (r *quotaMaintenanceProxyRepo) GetByID(_ context.Context, id int64) (*Proxy, error) { + if r.err != nil { + return nil, r.err + } + return r.proxies[id], nil +} + +func quotaMaintenanceProxy(t *testing.T, id int64, endpoint string) *Proxy { + t.Helper() + parsed, err := url.Parse(endpoint) + require.NoError(t, err) + host, portText, err := net.SplitHostPort(parsed.Host) + require.NoError(t, err) + port, err := strconv.Atoi(portText) + require.NoError(t, err) + return &Proxy{ID: id, Protocol: parsed.Scheme, Host: host, Port: port, Status: StatusActive} +} + +// Keep the actual transport behind local HTTP proxies. An unexpected direct or +// group-external URL fails before any transport can reach the network. +func quotaMaintenanceFactory(allowed ...string) PrivacyClientFactory { + return func(proxyURL string) (*req.Client, error) { + permitted := false + for _, candidate := range allowed { + permitted = permitted || proxyURL == candidate + } + if !permitted { + return nil, fmt.Errorf("unexpected quota proxy") + } + client := req.C().SetProxyURL(proxyURL).SetTimeout(2 * time.Second) + client.WrapRoundTripFunc(func(rt req.RoundTripper) req.RoundTripFunc { + return func(r *req.Request) (*req.Response, error) { + // Preserve the original hostname and path so the local server + // receives an HTTP proxy request for the real quota endpoint. + r.URL.Scheme = "http" + return rt.RoundTrip(r) + } + }) + return client, nil + } +} + +func quotaMaintenanceResponse(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch r.URL.Path { + case "/backend-api/wham/usage": + _, _ = w.Write([]byte(`{"plan_type":"plus","rate_limit_reset_credits":{"available_count":0}}`)) + case "/backend-api/wham/rate-limit-reset-credits": + _, _ = w.Write([]byte(`{"available_count":0,"credits":[]}`)) + case "/backend-api/wham/rate-limit-reset-credits/consume": + _, _ = w.Write([]byte(`{"code":"ok","windows_reset":1}`)) + default: + http.NotFound(w, r) + } +} + +func TestOpenAIQuotaMaintenanceRequestProxyUsesSelectedGroup(t *testing.T) { + var selectedHits, outsideHits atomic.Int32 + selected := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + selectedHits.Add(1) + require.True(t, r.URL.IsAbs(), "request must cross the actual local proxy boundary") + require.Equal(t, "chatgpt.com", r.URL.Hostname()) + quotaMaintenanceResponse(w, r) + })) + defer selected.Close() + outside := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + outsideHits.Add(1) + quotaMaintenanceResponse(w, r) + })) + defer outside.Close() + + legacy := quotaMaintenanceProxy(t, 99, outside.URL) + disabled := quotaMaintenanceProxy(t, 11, outside.URL) + disabled.Status = StatusDisabled + expired := quotaMaintenanceProxy(t, 22, outside.URL) + yesterday := time.Now().Add(-time.Hour) + expired.ExpiresAt = &yesterday + active := quotaMaintenanceProxy(t, 33, selected.URL) + proxies := "aMaintenanceProxyRepo{proxies: map[int64]*Proxy{11: disabled, 22: expired, 33: active, 99: legacy}} + account := &Account{ + ID: 100, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Status: StatusActive, + Credentials: map[string]any{"chatgpt_account_id": "quota-test-account"}, + ProxyID: &legacy.ID, Proxy: legacy, + Extra: map[string]any{"openai_proxy_mode": "request", "openai_proxy_ids": []int64{11, 22, 33}}, + } + accounts := &stubQuotaAccountRepo{accounts: map[int64]*Account{account.ID: account}} + tokens := &stubQuotaTokenCache{tokens: map[string]string{OpenAITokenCacheKey(account): "fake-token"}} + svc := NewOpenAIQuotaService(accounts, proxies, NewOpenAITokenProvider(accounts, tokens, nil), quotaMaintenanceFactory(selected.URL, outside.URL), nil) + + usage, err := svc.QueryUsage(context.Background(), account.ID) + require.NoError(t, err) + require.Equal(t, "plus", usage.PlanType) + require.EqualValues(t, 2, selectedHits.Load()) + require.Zero(t, outsideHits.Load(), "quota must not use the old group-external ProxyID") + require.EqualValues(t, 99, *account.ProxyID, "maintenance must not mutate the saved single proxy") + + result, err := svc.ResetCredit(context.Background(), account.ID) + require.NoError(t, err) + require.Equal(t, "ok", result.Code) + require.EqualValues(t, 3, selectedHits.Load()) + require.Zero(t, outsideHits.Load()) + + _, err = svc.ResetCreditTargeted(context.Background(), account.ID, "test-credit", "test-redeem") + require.NoError(t, err) + require.EqualValues(t, 4, selectedHits.Load()) + require.Zero(t, outsideHits.Load()) + + // Existing BPS request groups use the same maintenance boundary when the + // newer OpenAI-wide fields have not yet been saved. + account.Extra = map[string]any{ + "openai_excel_bps": true, + ExcelBPSProxyModeKey: ExcelBPSProxyModeRequest, + ExcelBPSProxyIDsKey: []int64{11, 22, 33}, + } + _, err = svc.QueryUsage(context.Background(), account.ID) + require.NoError(t, err) + _, err = svc.ResetCredit(context.Background(), account.ID) + require.NoError(t, err) + require.EqualValues(t, 7, selectedHits.Load()) + require.Zero(t, outsideHits.Load()) + require.EqualValues(t, 99, *account.ProxyID) +} + +func TestOpenAIQuotaMaintenanceRequestProxyUnavailableFailsBeforeToken(t *testing.T) { + expired := time.Now().Add(-time.Hour) + proxies := "aMaintenanceProxyRepo{proxies: map[int64]*Proxy{ + 1: {ID: 1, Status: StatusDisabled, Protocol: "http", Host: "disabled.invalid", Port: 8080}, + 2: {ID: 2, Status: StatusActive, Protocol: "http", Host: "expired.invalid", Port: 8080, ExpiresAt: &expired}, + 3: {ID: 3, Status: StatusActive, Protocol: "http", Port: 8080}, + 4: {ID: 4, Status: StatusActive, Protocol: "file", Host: "invalid.invalid", Port: 8080}, + 5: {ID: 5, Status: StatusActive, Protocol: "http", Host: "invalid.invalid", Port: 70000}, + }} + for _, tc := range []struct { + name string + mode any + ids any + repo ProxyRepository + }{ + {name: "empty group", mode: "request", repo: proxies}, + {name: "missing member", mode: "request", ids: []int64{99}, repo: proxies}, + {name: "inactive members", mode: "request", ids: []int64{1, 2}, repo: proxies}, + {name: "invalid members", mode: "request", ids: []int64{3, 4, 5}, repo: proxies}, + {name: "repository unavailable", mode: "request", ids: []int64{1}}, + {name: "lookup error", mode: "request", ids: []int64{1}, repo: "aMaintenanceProxyRepo{err: errors.New("http://private:secret@private.invalid:8080")}}, + {name: "invalid mode", mode: "round-robin", ids: []int64{1}, repo: proxies}, + {name: "invalid IDs", mode: "request", ids: []any{"1"}, repo: proxies}, + } { + t.Run(tc.name, func(t *testing.T) { + legacy := &Proxy{ID: 90, Status: StatusActive, Protocol: "http", Host: "private.invalid", Port: 8080, Username: "private", Password: "secret"} + account := &Account{ + ID: 100, Platform: PlatformOpenAI, Type: AccountTypeOAuth, ProxyID: &legacy.ID, Proxy: legacy, + Credentials: map[string]any{"chatgpt_account_id": "quota-test-account"}, + Extra: map[string]any{"openai_proxy_mode": tc.mode, "openai_proxy_ids": tc.ids, + "openai_excel_bps": true, ExcelBPSProxyModeKey: ExcelBPSProxyModeRequest, ExcelBPSProxyIDsKey: []int64{90}}, + } + accounts := &stubQuotaAccountRepo{accounts: map[int64]*Account{account.ID: account}} + factoryCalls := 0 + // A nil token provider would return NOT_CONFIGURED if validation + // happened after token acquisition instead of failing closed first. + svc := NewOpenAIQuotaService(accounts, tc.repo, nil, func(string) (*req.Client, error) { + factoryCalls++ + return nil, errors.New("unexpected privacy client") + }, nil) + for _, operation := range []struct { + name string + call func() error + }{ + {"query", func() error { _, err := svc.QueryUsage(context.Background(), account.ID); return err }}, + {"reset", func() error { _, err := svc.ResetCredit(context.Background(), account.ID); return err }}, + {"targeted reset", func() error { + _, err := svc.ResetCreditTargeted(context.Background(), account.ID, "test-credit", "test-redeem") + return err + }}, + } { + t.Run(operation.name, func(t *testing.T) { + err := operation.call() + require.Equal(t, http.StatusServiceUnavailable, infraerrors.Code(err)) + require.Equal(t, "OPENAI_PROXY_UNAVAILABLE", infraerrors.Reason(err)) + require.NotContains(t, err.Error(), "secret") + require.NotContains(t, err.Error(), "private.invalid") + require.Zero(t, factoryCalls) + }) + } + }) + } +} + +func TestOpenAIQuotaMaintenanceSinglePreservesExistingProxyResolution(t *testing.T) { + for _, eager := range []bool{true, false} { + t.Run(fmt.Sprintf("eager=%t", eager), func(t *testing.T) { + var hits atomic.Int32 + single := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + hits.Add(1) + quotaMaintenanceResponse(w, r) + })) + defer single.Close() + proxy := quotaMaintenanceProxy(t, 99, single.URL) + account := &Account{ + ID: 100, Platform: PlatformOpenAI, Type: AccountTypeOAuth, ProxyID: &proxy.ID, + Credentials: map[string]any{"chatgpt_account_id": "quota-test-account"}, + Extra: map[string]any{"openai_proxy_mode": "single", "openai_proxy_ids": []int64{404}, + "openai_excel_bps": true, ExcelBPSProxyModeKey: ExcelBPSProxyModeRequest, ExcelBPSProxyIDsKey: []int64{404}}, + } + var proxies ProxyRepository = "aMaintenanceProxyRepo{proxies: map[int64]*Proxy{proxy.ID: proxy}} + if eager { + account.Proxy = proxy + proxies = nil + } + accounts := &stubQuotaAccountRepo{accounts: map[int64]*Account{account.ID: account}} + tokens := &stubQuotaTokenCache{tokens: map[string]string{OpenAITokenCacheKey(account): "fake-token"}} + svc := NewOpenAIQuotaService(accounts, proxies, NewOpenAITokenProvider(accounts, tokens, nil), quotaMaintenanceFactory(single.URL), nil) + _, err := svc.QueryUsage(context.Background(), account.ID) + require.NoError(t, err) + _, err = svc.ResetCredit(context.Background(), account.ID) + require.NoError(t, err) + require.EqualValues(t, 3, hits.Load()) + }) + } +} + +func TestOpenAIQuotaMaintenanceShadowUsesParentRequestProxy(t *testing.T) { + var hits atomic.Int32 + selected := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + hits.Add(1) + require.Equal(t, "parent-workspace", r.Header.Get("ChatGPT-Account-ID")) + quotaMaintenanceResponse(w, r) + })) + defer selected.Close() + proxy := quotaMaintenanceProxy(t, 33, selected.URL) + parent := &Account{ID: 100, Platform: PlatformOpenAI, Type: AccountTypeOAuth, + Credentials: map[string]any{"chatgpt_account_id": "parent-workspace"}, + Extra: map[string]any{"openai_proxy_mode": "request", "openai_proxy_ids": []int64{33}}} + shadow := &Account{ID: 200, ParentAccountID: &parent.ID, Platform: PlatformOpenAI, Type: AccountTypeOAuth, QuotaDimension: QuotaDimensionSpark} + accounts := &stubQuotaAccountRepo{accounts: map[int64]*Account{parent.ID: parent, shadow.ID: shadow}} + tokens := &stubQuotaTokenCache{tokens: map[string]string{OpenAITokenCacheKey(parent): "parent-token"}} + proxies := "aMaintenanceProxyRepo{proxies: map[int64]*Proxy{33: proxy}} + svc := NewOpenAIQuotaService(accounts, proxies, NewOpenAITokenProvider(accounts, tokens, nil), quotaMaintenanceFactory(selected.URL), nil) + _, err := svc.QueryUsage(context.Background(), shadow.ID) + require.NoError(t, err) + require.EqualValues(t, 2, hits.Load()) + _, err = svc.ResetCredit(context.Background(), shadow.ID) + require.ErrorIs(t, err, ErrSparkShadowResetNotSupported) + require.Equal(t, http.StatusConflict, infraerrors.Code(err)) + require.EqualValues(t, 2, hits.Load()) +} diff --git a/backend/internal/service/openai_quota_service.go b/backend/internal/service/openai_quota_service.go index 6c73387571f8..89f23b79334e 100644 --- a/backend/internal/service/openai_quota_service.go +++ b/backend/internal/service/openai_quota_service.go @@ -571,6 +571,16 @@ func (s *OpenAIQuotaService) prepareUpstreamCall(ctx context.Context, accountID return "", "", "", false, infraerrors.New(http.StatusBadRequest, "OPENAI_QUOTA_MISSING_ACCOUNT_ID", "chatgpt_account_id is missing; please re-authorize this account") } + requestProxy := account.OpenAIRequestProxyEnabled() + if requestProxy { + // Validate the saved group before token maintenance can issue network + // requests. Request mode must never use the legacy single/direct exit. + proxyURL, err = resolveOpenAIMaintenanceProxy(ctx, account, s.proxyRepo) + if err != nil { + return "", "", "", false, err + } + } + if !account.IsOpenAIAgentIdentity() { if s.tokenProvider == nil { return "", "", "", false, infraerrors.New(http.StatusInternalServerError, "OPENAI_QUOTA_NOT_CONFIGURED", "openai quota token provider is not configured") @@ -590,7 +600,7 @@ func (s *OpenAIQuotaService) prepareUpstreamCall(ctx context.Context, accountID // instead of round-tripping the DB again. Fall back to proxyRepo only // when Proxy isn't pre-populated (defensive — e.g. callers that built // the Account by hand). - if account.ProxyID != nil { + if !requestProxy && account.ProxyID != nil { switch { case account.Proxy != nil: proxyURL = account.Proxy.URL() diff --git a/backend/internal/service/openai_request_proxy.go b/backend/internal/service/openai_request_proxy.go new file mode 100644 index 000000000000..1b0ffbd8a238 --- /dev/null +++ b/backend/internal/service/openai_request_proxy.go @@ -0,0 +1,158 @@ +package service + +import ( + "context" + "errors" + "io" + "net/http" + "sync" + + "github.com/Wei-Shaw/sub2api/internal/mihomo" + "github.com/gin-gonic/gin" +) + +var errOpenAIRequestProxyUnavailable = errors.New("selected OpenAI request proxies are unavailable") + +type openAIRequestProxyContextKey struct{} +type openAIRequestProxyRoute struct { + accountID int64 + proxy string + lease *mihomo.BPSLease + mu sync.Mutex + bodies []*openAIRequestProxyBody + cancelSends []context.CancelFunc + finished bool + once sync.Once +} + +func (r *openAIRequestProxyRoute) bind(req *http.Request) (*http.Request, error) { + r.mu.Lock() + defer r.mu.Unlock() + if r.finished { + return nil, errOpenAIRequestProxyUnavailable + } + ctx, cancel := context.WithCancel(req.Context()) + r.cancelSends = append(r.cancelSends, cancel) + return req.WithContext(ctx), nil +} + +type openAIRequestProxyBody struct { + io.ReadCloser + once sync.Once + err error +} + +func (b *openAIRequestProxyBody) Close() error { + b.once.Do(func() { b.err = b.ReadCloser.Close() }) + return b.err +} +func (r *openAIRequestProxyRoute) track(resp *http.Response) { + if resp == nil || resp.Body == nil { + return + } + b := &openAIRequestProxyBody{ReadCloser: resp.Body} + resp.Body = b + r.mu.Lock() + r.bodies = append(r.bodies, b) + closed := r.finished + r.mu.Unlock() + if closed { + _ = b.Close() + } +} +func (r *openAIRequestProxyRoute) finish() { + r.once.Do(func() { + r.mu.Lock() + r.finished = true + bodies := append([]*openAIRequestProxyBody(nil), r.bodies...) + cancels := append([]context.CancelFunc(nil), r.cancelSends...) + r.mu.Unlock() + for _, cancel := range cancels { + cancel() + } + for _, b := range bodies { + _ = b.Close() + } + r.lease.Release() + }) +} + +// Account tests return before their caller consumes the stream. Keep the +// request scope alive until that final body ends, closes, or is canceled. +type openAIRequestProxyOwnedBody struct { + io.ReadCloser + finish func() +} + +func (b *openAIRequestProxyOwnedBody) Read(p []byte) (int, error) { + n, err := b.ReadCloser.Read(p) + if err != nil { + b.finish() + } + return n, err +} +func (b *openAIRequestProxyOwnedBody) Close() error { + err := b.ReadCloser.Close() + b.finish() + return err +} + +// One logical HTTP turn owns its exit across payload repairs and continuations. +// The scope ends only after Forward finishes consuming its final response. +func (s *OpenAIGatewayService) beginOpenAIRequestProxy(ctx context.Context, c *gin.Context, account *Account) (context.Context, func(), error) { + noop := func() {} + if account == nil || !account.OpenAIRequestProxyEnabled() { + return ctx, noop, nil + } + if route, _ := ctx.Value(openAIRequestProxyContextKey{}).(*openAIRequestProxyRoute); route != nil { + if route.accountID == account.ID { + return ctx, noop, nil + } + return ctx, noop, writeOpenAIRequestProxyError(c, "openai_proxy_unavailable", "Selected proxy scope does not match the account") + } + lease, err := mihomo.AcquireBPSStaticRequestLease(ctx, account.ID, account.OpenAIRequestProxyIDs()) + if err != nil { + if ctx.Err() != nil { + return ctx, noop, ctx.Err() + } + return ctx, noop, writeOpenAIRequestProxyError(c, "openai_proxy_unavailable", "No selected proxy is ready; direct fallback is disabled") + } + route := &openAIRequestProxyRoute{accountID: account.ID, proxy: lease.ProxyURL, lease: lease} + release := route.finish + stop := context.AfterFunc(ctx, release) + return context.WithValue(ctx, openAIRequestProxyContextKey{}, route), func() { stop(); release() }, nil +} + +func writeOpenAIRequestProxyError(c *gin.Context, code, message string) error { + if c != nil && c.Writer != nil && !c.Writer.Written() { + c.JSON(http.StatusServiceUnavailable, gin.H{"error": gin.H{"type": "upstream_error", "code": code, "message": message}}) + } + return errOpenAIRequestProxyUnavailable +} + +func openAIRequestProxyFromContext(ctx context.Context, accountID int64) (*openAIRequestProxyRoute, bool) { + route, _ := ctx.Value(openAIRequestProxyContextKey{}).(*openAIRequestProxyRoute) + return route, route != nil && route.accountID == accountID && route.proxy != "" +} + +// ValidateOpenAIRequestProxyEgress lets transport adapters preserve a lease +// created by the gateway without exposing a way to create or replace it. +// The boolean distinguishes an ordinary request from an active scoped route. +func ValidateOpenAIRequestProxyEgress(ctx context.Context, accountID int64, proxyURL string) (bool, error) { + if ctx == nil { + return false, nil + } + route, _ := ctx.Value(openAIRequestProxyContextKey{}).(*openAIRequestProxyRoute) + if route == nil { + return false, nil + } + route.mu.Lock() + defer route.mu.Unlock() + if route.finished || route.accountID != accountID || route.proxy == "" || route.proxy != proxyURL { + return true, errOpenAIRequestProxyUnavailable + } + if err := ctx.Err(); err != nil { + return true, err + } + return true, nil +} diff --git a/backend/internal/service/openai_request_proxy_integration_test.go b/backend/internal/service/openai_request_proxy_integration_test.go new file mode 100644 index 000000000000..258806be143e --- /dev/null +++ b/backend/internal/service/openai_request_proxy_integration_test.go @@ -0,0 +1,335 @@ +//go:build bps_request_integration + +package service + +import ( + "bytes" + "context" + "fmt" + "io" + "net/http" + "net/http/httptest" + "sync" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/pkg/tlsfingerprint" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +type requestProxyAccountTestRepo struct { + AccountRepository + account *Account +} +type requestProxyAccountTestUpstream struct{ HTTPUpstream } + +func (u *requestProxyAccountTestUpstream) DoWithTLS(r *http.Request, p string, id int64, n int, _ *tlsfingerprint.Profile) (*http.Response, error) { + return u.HTTPUpstream.Do(r, p, id, n) +} + +func (r *requestProxyAccountTestRepo) GetByID(context.Context, int64) (*Account, error) { + return r.account, nil +} +func (r *requestProxyAccountTestRepo) UpdateExtra(context.Context, int64, map[string]any) error { + return nil +} + +func TestOpenAIRequestProxyAccountTestUsesSelectedExit(t *testing.T) { + observed := make(chan int, 1) + gateway, account := localBPSRequestProxyFixture(t, 3, func(id int, w http.ResponseWriter, r *http.Request) { + _, _ = io.Copy(io.Discard, r.Body) + observed <- id + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, bpsRequestCompletedWire) + }) + account.Extra["openai_excel_bps"] = false + account.Extra["openai_proxy_mode"] = "request" + account.Extra["openai_proxy_ids"] = []int64{2} + svc := &AccountTestService{accountRepo: &requestProxyAccountTestRepo{account: account}, openaiGatewayService: gateway, httpUpstream: &requestProxyAccountTestUpstream{gateway.httpUpstream}} + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/admin/accounts/300/test", nil) + err := svc.TestAccountConnection(c, account.ID, "gpt-5.4", "", "") + require.NoError(t, err) + require.Contains(t, rec.Body.String(), "test_complete") + require.Equal(t, 2, <-observed) +} + +func TestOpenAIRequestProxyImagesUsesSelectedExit(t *testing.T) { + observed := make(chan int, 1) + svc, account := localBPSRequestProxyFixture(t, 3, func(id int, w http.ResponseWriter, r *http.Request) { + _, _ = io.Copy(io.Discard, r.Body) + observed <- id + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, "data: {\"type\":\"response.completed\",\"response\":{\"status\":\"completed\",\"output\":[{\"type\":\"image_generation_call\",\"result\":\"aW1hZ2U=\"}]}}\n\n") + }) + account.Extra["openai_excel_bps"] = false + account.Extra["openai_proxy_mode"] = "request" + account.Extra["openai_proxy_ids"] = []int64{2} + body := []byte(`{"model":"gpt-image-1","prompt":"local fixture"}`) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/images/generations", bytes.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + parsed, err := svc.ParseOpenAIImagesRequest(c, body) + require.NoError(t, err) + result, err := svc.ForwardImages(t.Context(), c, account, body, parsed, "") + require.NoError(t, err) + require.NotNil(t, result) + require.Equal(t, 1, result.ImageCount) + require.Equal(t, 2, <-observed) +} + +func TestOpenAIRequestProxyImagesEndpointFallbackKeepsLogicalExit(t *testing.T) { + for _, status := range []int{http.StatusNotFound, http.StatusMethodNotAllowed} { + t.Run(fmt.Sprint(status), func(t *testing.T) { + observed := make(chan requestProxyObservation, 2) + svc, account := localBPSRequestProxyFixture(t, 3, func(id int, w http.ResponseWriter, r *http.Request) { + _, _ = io.Copy(io.Discard, r.Body) + observed <- requestProxyObservation{id: id, path: r.URL.Path} + if r.URL.Path == "/backend-api/codex/images/generations" { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + _, _ = io.WriteString(w, `{"error":{"message":"fixture endpoint unavailable"}}`) + return + } + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, "data: {\"type\":\"response.completed\",\"response\":{\"status\":\"completed\",\"output\":[{\"type\":\"image_generation_call\",\"result\":\"aW1hZ2U=\"}],\"usage\":{\"input_tokens\":1,\"output_tokens\":20}}}\n\n") + }) + account.Extra["openai_excel_bps"] = false + account.Extra["openai_proxy_mode"] = "request" + account.Extra["openai_proxy_ids"] = []int64{1, 2, 3} + body := []byte(`{"model":"gpt-image-2","prompt":"local fallback fixture"}`) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/images/generations", bytes.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + parsed, err := svc.ParseOpenAIImagesRequest(c, body) + require.NoError(t, err) + // Images must finish after a downstream disconnect, including an + // endpoint fallback, so billing can retain completed output usage. + ctx, cancel := context.WithCancel(t.Context()) + cancel() + result, err := svc.ForwardImages(ctx, c, account, body, parsed, "") + require.NoError(t, err) + require.NotNil(t, result) + require.Equal(t, 1, result.ImageCount) + require.Equal(t, 20, result.Usage.OutputTokens) + direct, fallback := <-observed, <-observed + require.Equal(t, "/backend-api/codex/images/generations", direct.path) + require.Equal(t, "/backend-api/codex/responses", fallback.path) + require.Equal(t, direct.id, fallback.id, "one Images operation must keep its selected exit across direct endpoint fallback") + }) + } +} + +func TestOpenAIRequestProxyForwardSameSessionDistributesSixThroughThree(t *testing.T) { + arrived := make(chan int, 6) + release := make(chan struct{}) + var once sync.Once + t.Cleanup(func() { once.Do(func() { close(release) }) }) + svc, account := localBPSRequestProxyFixture(t, 4, func(id int, w http.ResponseWriter, r *http.Request) { + _, _ = io.Copy(io.Discard, r.Body) + arrived <- id + select { + case <-release: + case <-r.Context().Done(): + return + } + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, bpsRequestCompletedWire) + }) + account.Extra["openai_excel_bps"] = false + account.Extra["openai_proxy_mode"] = "request" + account.Extra["openai_proxy_ids"] = []int64{1, 2, 3} + ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second) + defer cancel() + done := make(chan error, 6) + for i := 0; i < 6; i++ { + go func() { + code, response, err := forwardLocalBPSRequest(ctx, svc, account, []byte(`{"model":"gpt-5.4","input":"test","stream":true,"prompt_cache_key":"same-session"}`)) + if err == nil && (code != 200 || !bytes.Contains([]byte(response), []byte("response.completed"))) { + err = fmt.Errorf("incomplete OAuth response: status %d: %s", code, response) + } + done <- err + }() + } + hits := map[int]int{} + for i := 0; i < 6; i++ { + select { + case id := <-arrived: + hits[id]++ + case <-ctx.Done(): + t.Fatal("six OAuth requests did not reach selected local proxies") + } + } + once.Do(func() { close(release) }) + for i := 0; i < 6; i++ { + require.NoError(t, <-done) + } + require.Equal(t, map[int]int{1: 2, 2: 2, 3: 2}, hits) +} + +func TestOpenAIRequestProxyForwardCancellationReleasesExitWhileOtherStreamsStayBusy(t *testing.T) { + arrived := make(chan int, 4) + svc, account := localBPSRequestProxyFixture(t, 3, func(id int, w http.ResponseWriter, r *http.Request) { + _, _ = io.Copy(io.Discard, r.Body) + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, "data: {\"type\":\"response.created\",\"response\":{\"id\":\"r\",\"status\":\"in_progress\"}}\n\n") + w.(http.Flusher).Flush() + arrived <- id + <-r.Context().Done() + }) + account.Extra["openai_excel_bps"] = false + account.Extra["openai_proxy_mode"] = "request" + account.Extra["openai_proxy_ids"] = []int64{1, 2, 3} + ctx, cancel := context.WithTimeout(t.Context(), 8*time.Second) + defer cancel() + type running struct { + stop context.CancelFunc + done chan error + proxy int + } + start := func() running { + child, stop := context.WithCancel(ctx) + done := make(chan error, 1) + go func() { + _, _, err := forwardLocalBPSRequest(child, svc, account, []byte(`{"model":"gpt-5.4","input":"hold","stream":true}`)) + done <- err + }() + select { + case id := <-arrived: + return running{stop, done, id} + case <-ctx.Done(): + stop() + t.Fatal("OAuth stream did not start") + return running{} + } + } + a, b, c := start(), start(), start() + t.Cleanup(a.stop) + t.Cleanup(b.stop) + t.Cleanup(c.stop) + require.ElementsMatch(t, []int{1, 2, 3}, []int{a.proxy, b.proxy, c.proxy}) + a.stop() + select { + case <-a.done: + case <-ctx.Done(): + t.Fatal("canceled OAuth stream did not release") + } + d := start() + t.Cleanup(d.stop) + require.Equal(t, a.proxy, d.proxy) + for _, r := range []running{b, c, d} { + r.stop() + select { + case <-r.done: + case <-ctx.Done(): + t.Fatal("held OAuth stream did not finish") + } + } +} + +func TestOpenAIRequestProxyForwardFinishedRequestReleasesExit(t *testing.T) { + for _, rejected := range []bool{false, true} { + t.Run(fmt.Sprint("rejected=", rejected), func(t *testing.T) { + arrived := make(chan int, 4) + var mu sync.Mutex + calls := 0 + svc, account := localBPSRequestProxyFixture(t, 3, func(id int, w http.ResponseWriter, r *http.Request) { + _, _ = io.Copy(io.Discard, r.Body) + mu.Lock() + calls++ + order := calls + mu.Unlock() + arrived <- id + if order <= 2 { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, "data: {\"type\":\"response.created\",\"response\":{\"id\":\"held\",\"status\":\"in_progress\"}}\n\n") + w.(http.Flusher).Flush() + <-r.Context().Done() + return + } + if rejected && order == 3 { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusBadRequest) + _, _ = io.WriteString(w, `{"error":{"code":"bad_request","message":"fixture rejected"}}`) + return + } + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, bpsRequestCompletedWire) + }) + account.Extra["openai_excel_bps"] = false + account.Extra["openai_proxy_mode"] = "request" + account.Extra["openai_proxy_ids"] = []int64{1, 2, 3} + ctx, cancel := context.WithTimeout(t.Context(), 8*time.Second) + defer cancel() + body := []byte(`{"model":"gpt-5.4","input":"test","stream":true}`) + done := make(chan error, 2) + for i := 0; i < 2; i++ { + go func() { _, _, err := forwardLocalBPSRequest(ctx, svc, account, body); done <- err }() + select { + case <-arrived: + case <-ctx.Done(): + t.Fatal("held OAuth request did not start") + } + } + code, _, err := forwardLocalBPSRequest(ctx, svc, account, body) + if rejected { + require.Error(t, err) + require.Equal(t, http.StatusBadRequest, code) + } else { + require.NoError(t, err) + require.Equal(t, http.StatusOK, code) + } + finished := <-arrived + code, _, err = forwardLocalBPSRequest(ctx, svc, account, body) + require.NoError(t, err) + require.Equal(t, http.StatusOK, code) + require.Equal(t, finished, <-arrived, "finished request must release its least-in-flight slot while other exits remain busy") + cancel() + for i := 0; i < 2; i++ { + select { + case <-done: + case <-time.After(time.Second): + t.Fatal("held OAuth request did not finish") + } + } + }) + } +} + +func TestOpenAIRequestProxyCompatibilityUsesSelectedExit(t *testing.T) { + for _, entry := range []string{"native", "passthrough", "chat", "messages"} { + t.Run(entry, func(t *testing.T) { + observed := make(chan int, 1) + svc, account := localBPSRequestProxyFixture(t, 3, func(id int, w http.ResponseWriter, r *http.Request) { + _, _ = io.Copy(io.Discard, r.Body) + observed <- id + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, bpsRequestCompletedWire) + }) + account.Extra["openai_excel_bps"] = false + account.Extra["openai_passthrough"] = entry == "passthrough" + account.Extra["openai_proxy_mode"] = "request" + account.Extra["openai_proxy_ids"] = []int64{2} + body := []byte(`{"model":"gpt-5.4","messages":[{"role":"user","content":"test"}],"input":"test","max_tokens":32,"stream":true}`) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/"+entry, bytes.NewReader(body)) + var err error + switch entry { + case "chat": + _, err = svc.ForwardAsChatCompletions(t.Context(), c, account, body, "", "") + case "messages": + _, err = svc.ForwardAsAnthropic(t.Context(), c, account, body, "", "") + default: + _, err = svc.Forward(t.Context(), c, account, body) + } + require.NoError(t, err) + require.Equal(t, http.StatusOK, rec.Code) + require.Equal(t, 2, <-observed) + }) + } +} diff --git a/backend/internal/service/openai_request_proxy_test.go b/backend/internal/service/openai_request_proxy_test.go new file mode 100644 index 000000000000..caae0a11a71e --- /dev/null +++ b/backend/internal/service/openai_request_proxy_test.go @@ -0,0 +1,125 @@ +package service + +import ( + "bytes" + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + coderws "github.com/coder/websocket" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +func TestOpenAIRequestProxyForwardUnavailableDoesNotSendOutsideSelectedPool(t *testing.T) { + upstream := &httpUpstreamRecorder{resp: &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": {"text/event-stream"}}, Body: io.NopCloser(strings.NewReader("data: {\"type\":\"response.completed\",\"response\":{\"id\":\"r\",\"status\":\"completed\",\"output\":[]}}\n\n"))}} + svc := openAIClientToolsTestService(upstream) + account := excelAccount() + account.Extra["openai_excel_bps"] = false + account.Extra["openai_proxy_mode"] = "request" + account.Extra["openai_proxy_ids"] = []int64{987654321} + account.Proxy = &Proxy{Protocol: "http", Host: "unused.example", Port: 8080} + body := []byte(`{"model":"gpt-5.4","input":"test","stream":true}`) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewReader(body)) + _, err := svc.Forward(context.Background(), c, account, body) + require.Error(t, err) + require.Equal(t, http.StatusServiceUnavailable, rec.Code) + require.Contains(t, rec.Body.String(), "openai_proxy_unavailable") + require.Nil(t, upstream.lastReq, "selected pool failure must not send directly or through the old account proxy") +} + +func TestOpenAIRequestProxyCompatibilityUnavailableNeverSends(t *testing.T) { + for _, entry := range []string{"chat", "messages", "input_tokens", "count_tokens"} { + t.Run(entry, func(t *testing.T) { + upstream := &httpUpstreamRecorder{} + svc := openAIClientToolsTestService(upstream) + account := excelAccount() + account.Extra["openai_excel_bps"] = false + account.Extra["openai_proxy_mode"] = "request" + account.Extra["openai_proxy_ids"] = []int64{987654321} + body := []byte(`{"model":"gpt-5.4","messages":[{"role":"user","content":"test"}],"input":"test","max_tokens":32}`) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/"+entry, bytes.NewReader(body)) + var err error + switch entry { + case "chat": + _, err = svc.ForwardAsChatCompletions(t.Context(), c, account, body, "", "") + case "messages": + _, err = svc.ForwardAsAnthropic(t.Context(), c, account, body, "", "") + case "input_tokens": + err = svc.ForwardResponsesInputTokens(t.Context(), c, account, body) + case "count_tokens": + err = svc.ForwardCountTokensAsAnthropic(t.Context(), c, account, body, "") + } + require.Error(t, err) + require.Equal(t, http.StatusServiceUnavailable, rec.Code) + require.Contains(t, rec.Body.String(), "openai_proxy_unavailable") + require.Empty(t, upstream.requests) + }) + } +} + +func TestOpenAIRequestProxyWebSocketExplicitlyRejectsBeforeUpstream(t *testing.T) { + upstream := &httpUpstreamRecorder{} + svc := openAIClientToolsTestService(upstream) + account := excelAccount() + account.Extra["openai_excel_bps"] = false + account.Extra["openai_proxy_mode"] = "request" + account.Extra["openai_proxy_ids"] = []int64{1, 2} + serverErr := make(chan error, 1) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + conn, err := coderws.Accept(w, r, nil) + if err != nil { + serverErr <- err + return + } + defer conn.CloseNow() + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = r + serverErr <- svc.ProxyResponsesWebSocketFromClient(r.Context(), c, conn, account, "test-token", []byte(`{"type":"response.create","model":"gpt-5.4","input":"test"}`), nil) + })) + defer server.Close() + ctx, cancel := context.WithTimeout(t.Context(), 3*time.Second) + defer cancel() + client, _, err := coderws.Dial(ctx, "ws"+strings.TrimPrefix(server.URL, "http"), nil) + require.NoError(t, err) + defer client.CloseNow() + select { + case err := <-serverErr: + var closeErr *OpenAIWSClientCloseError + require.ErrorAs(t, err, &closeErr) + require.Contains(t, err.Error(), "requires HTTP/SSE") + case <-ctx.Done(): + t.Fatal("WebSocket request proxy rejection did not finish") + } + require.Empty(t, upstream.requests) +} + +func TestOpenAIRequestProxyExplicitSingleKeepsExistingProxy(t *testing.T) { + upstream := &httpUpstreamRecorder{resp: &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": {"text/event-stream"}}, Body: io.NopCloser(strings.NewReader("data: {\"type\":\"response.completed\",\"response\":{\"id\":\"single\",\"status\":\"completed\",\"output\":[],\"usage\":{\"input_tokens\":1,\"output_tokens\":1}}}\n\n"))}} + svc := openAIClientToolsTestService(upstream) + account := excelAccount() + account.Extra["openai_excel_bps"] = false + account.Extra["openai_proxy_mode"] = "single" + account.Extra["openai_proxy_ids"] = []int64{987654321} + account.Extra["openai_excel_bps_proxy_mode"] = "request" + account.Extra["openai_excel_bps_proxy_ids"] = []int64{987654321} + proxyID := int64(77) + account.ProxyID = &proxyID + account.Proxy = &Proxy{Protocol: "http", Host: "single.example", Port: 8080} + body := []byte(`{"model":"gpt-5.4","input":"test","stream":true}`) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewReader(body)) + _, err := svc.Forward(t.Context(), c, account, body) + require.NoError(t, err) + require.Equal(t, http.StatusOK, rec.Code) + require.Equal(t, account.Proxy.URL(), upstream.lastProxyURL) +} diff --git a/backend/internal/service/openai_session_export.go b/backend/internal/service/openai_session_export.go index 775f7a9979b2..b4763db1d840 100644 --- a/backend/internal/service/openai_session_export.go +++ b/backend/internal/service/openai_session_export.go @@ -247,7 +247,19 @@ func (s *OpenAIOAuthReauthService) ClaimSessionExportTask(ctx context.Context, w _ = s.sessionExportRepo.FinishSessionExportTask(ctx, record.ID, workerID, OpenAISessionExportStatusFailed, "totp_unavailable") return nil, nil } - proxyURL, err := s.reauthProxyURL(ctx, account.ProxyID) + var proxyURL string + if account.OpenAIRequestProxyEnabled() { + // The worker receives one fixed exit for its whole login flow. + // Explicit alternate sources cannot escape the selected account group. + source, sourceErr := normalizeReauthProxySource(config.ProxySource, config.ProxyID) + if sourceErr != nil || source != OpenAIOAuthReauthProxySourceAccount { + _ = s.sessionExportRepo.FinishSessionExportTask(ctx, record.ID, workerID, OpenAISessionExportStatusFailed, "proxy_unavailable") + return nil, nil + } + proxyURL, err = resolveOpenAIMaintenanceProxy(ctx, account, s.oauth.proxyRepo) + } else { + proxyURL, err = s.reauthProxyURL(ctx, account.ProxyID) + } if err != nil { _ = s.sessionExportRepo.FinishSessionExportTask(ctx, record.ID, workerID, OpenAISessionExportStatusFailed, "proxy_unavailable") return nil, nil diff --git a/backend/internal/service/openai_siwc.go b/backend/internal/service/openai_siwc.go index ef6ee2efd493..36ca7f9fd806 100644 --- a/backend/internal/service/openai_siwc.go +++ b/backend/internal/service/openai_siwc.go @@ -118,7 +118,12 @@ func (s *OpenAIOAuthReauthService) BeginSIWCAuthorization(ctx context.Context, i if err != nil { return nil, err } - proxy, err := s.reauthProxyURL(ctx, account.ProxyID) + var proxy string + if account.OpenAIRequestProxyEnabled() { + proxy, err = resolveOpenAIMaintenanceProxy(ctx, account, s.oauth.proxyRepo) + } else { + proxy, err = s.reauthProxyURL(ctx, account.ProxyID) + } if err != nil { return nil, err } @@ -212,6 +217,17 @@ func (s *OpenAIOAuthReauthService) CompleteSIWCAuthorization(ctx context.Context if clientID == "" || clientID == openai.SIWCDynamicClientID || q.Get("code") == "" { return infraerrors.BadRequest("OPENAI_SIWC_REGISTRATION_INCOMPLETE", "SIWC callback requires code and issued client ID") } + account, err := s.accountFor(ctx, id) + if err != nil { + return err + } + if account.OpenAIRequestProxyEnabled() { + // Keep the authorization attempt's exit fixed, but require that the + // saved exit is still an available member of the current selection. + if _, err = resolveOpenAIMaintenanceProxy(ctx, account, s.oauth.proxyRepo, session.ProxyURL); err != nil { + return err + } + } // Consume before exchanging; failed exchanges need a fresh authorization. consumed, valid := s.readSIWCSession(ctx, sessionID, true) if !valid || consumed.State != session.State || consumed.SIWCAccountID != id { @@ -230,7 +246,7 @@ func (s *OpenAIOAuthReauthService) CompleteSIWCAuthorization(ctx context.Context if identity == nil || token.RefreshToken == "" { return errors.New("SIWC credentials are incomplete") } - account, err := s.accountFor(ctx, id) + account, err = s.accountFor(ctx, id) if err != nil { return err } @@ -348,7 +364,12 @@ func (s *OpenAIOAuthReauthService) SIWCAccessToken(ctx context.Context, account if !ok { return "", errors.New("SIWC token client is unavailable") } - proxy, err := s.reauthProxyURL(refreshCtx, fresh.ProxyID) + var proxy string + if fresh.OpenAIRequestProxyEnabled() { + proxy, err = resolveOpenAIMaintenanceProxy(refreshCtx, fresh, s.oauth.proxyRepo) + } else { + proxy, err = s.reauthProxyURL(refreshCtx, fresh.ProxyID) + } if err != nil { return "", err } diff --git a/backend/internal/service/openai_siwc_gateway.go b/backend/internal/service/openai_siwc_gateway.go index 4847b2e9c0b9..a25230ab6516 100644 --- a/backend/internal/service/openai_siwc_gateway.go +++ b/backend/internal/service/openai_siwc_gateway.go @@ -143,6 +143,13 @@ func (s *OpenAIGatewayService) forwardSIWC(ctx context.Context, c *gin.Context, if _, err = normalizeSIWCBody(upstream); err != nil { return nil, err } + // Acquire before token lookup so a request-triggered SIWC refresh and the + // inference share one exit until the response is consumed or canceled. + proxyCtx, releaseProxy, err := s.beginOpenAIRequestProxy(ctx, c, account) + if err != nil { + return nil, err + } + defer releaseProxy() SetActualOpenAIUpstreamEndpoint(c, openAIResponsesUpstreamEndpoint) - return s.forwardOpenAIPassthrough(withOpenAITransportMode(ctx, "siwc"), c, account, body, upstream, reqModel, false, extractOpenAIReasoningEffortFromBody(body, reqModel), gjson.GetBytes(body, "stream").Bool(), start) + return s.forwardOpenAIPassthrough(withOpenAITransportMode(proxyCtx, "siwc"), c, account, body, upstream, reqModel, false, extractOpenAIReasoningEffortFromBody(body, reqModel), gjson.GetBytes(body, "stream").Bool(), start) } diff --git a/backend/internal/service/openai_siwc_request_proxy_integration_test.go b/backend/internal/service/openai_siwc_request_proxy_integration_test.go new file mode 100644 index 000000000000..ec3f7ed84d99 --- /dev/null +++ b/backend/internal/service/openai_siwc_request_proxy_integration_test.go @@ -0,0 +1,429 @@ +//go:build unit && bps_request_integration + +package service + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "sync" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/pkg/openai" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +func enableLocalSIWCRequestProxies(t *testing.T, gateway *OpenAIGatewayService, account *Account) { + t.Helper() + reauth, reader, repo, _, _, _ := newReauthTestService("acct-1") + t.Cleanup(reauth.oauth.Stop) + account.Credentials = cloneReauthMap(reader.account.Credentials) + account.Extra[OpenAISIWCEnabledKey] = true + account.Extra[OpenAIProxyModeKey] = OpenAIProxyModeRequest + account.Extra[OpenAIProxyIDsKey] = []int64{1, 2, 3} + reader.account = account + store := &siwcTestRepo{reauthTestRepo: repo} + raw, err := json.Marshal(siwcGrant{AccessToken: "independent-siwc", RefreshToken: "siwc-refresh", ClientID: "issued", Subject: "subscriber", Workspace: "acct-1", Email: "user@example.com", Scope: openai.SIWCDirectScope, ExpiresAt: time.Now().Add(time.Hour).Unix()}) + require.NoError(t, err) + store.ciphertext = "encrypted:" + string(raw) + reauth.repo = store + reauth.oauth.proxyRepo = gateway.proxyRepo + gateway.excelOAuthReauth = reauth +} + +func TestSIWCRequestProxyForwardUsesSelectedExit(t *testing.T) { + observed := make(chan int, 1) + svc, account := localBPSRequestProxyFixture(t, 4, func(id int, w http.ResponseWriter, r *http.Request) { + _, _ = io.Copy(io.Discard, r.Body) + require.Equal(t, "api.openai.com", r.URL.Host) + require.Equal(t, "/v1/responses", r.URL.Path) + require.Equal(t, "Bearer independent-siwc", r.Header.Get("Authorization")) + require.Empty(t, r.Header.Get("Cookie")) + require.Empty(t, r.Header.Get("ChatGPT-Account-ID")) + observed <- id + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, bpsRequestCompletedWire) + }) + enableLocalSIWCRequestProxies(t, svc, account) + account.Extra[OpenAIProxyIDsKey] = []int64{2} + code, response, err := forwardLocalBPSRequest(t.Context(), svc, account, []byte(`{"model":"gpt-5.4","input":"test","stream":true}`)) + require.NoError(t, err) + require.Equal(t, http.StatusOK, code) + require.Contains(t, response, "response.completed") + require.Equal(t, 2, <-observed) + require.Equal(t, "old-access", account.Credentials["access_token"]) +} + +func TestSIWCRequestProxyAccountTestUsesSelectedExit(t *testing.T) { + observed := make(chan int, 1) + gateway, account := localBPSRequestProxyFixture(t, 3, func(id int, w http.ResponseWriter, r *http.Request) { + _, _ = io.Copy(io.Discard, r.Body) + require.Equal(t, "Bearer independent-siwc", r.Header.Get("Authorization")) + observed <- id + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, "data: {\"type\":\"response.output_text.delta\",\"delta\":\"OK\"}\n\n") + _, _ = io.WriteString(w, "data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_test\",\"status\":\"completed\",\"output\":[{\"type\":\"message\",\"role\":\"assistant\",\"content\":[{\"type\":\"output_text\",\"text\":\"OK\"}]}],\"usage\":{\"input_tokens\":1,\"output_tokens\":1}}}\n\n") + }) + enableLocalSIWCRequestProxies(t, gateway, account) + account.Extra[OpenAIProxyIDsKey] = []int64{2} + svc := &AccountTestService{accountRepo: &requestProxyAccountTestRepo{account: account}, openaiGatewayService: gateway} + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/admin/accounts/300/test", nil) + require.NoError(t, svc.TestAccountConnection(c, account.ID, "gpt-5.4", "", "")) + require.Contains(t, rec.Body.String(), "test_complete") + require.Equal(t, 2, <-observed) +} + +type siwcRequestProxyAdmissionRepo struct { + AccountRepository + request, latest *Account + reads int +} + +func (r *siwcRequestProxyAdmissionRepo) GetOpenAITurnAdmission(context.Context, int64) (*Account, *Account, error) { + r.reads++ + if r.reads == 1 { + return r.request, nil, nil + } + return r.latest, nil, nil +} + +func TestSIWCRequestProxyAdmissionModeChangeRejectsBeforeSend(t *testing.T) { + for _, mode := range []string{OpenAIProxyModeRequest, OpenAIProxyModeSingle} { + t.Run(mode, func(t *testing.T) { + observed := make(chan int, 1) + svc, account := localBPSRequestProxyFixture(t, 3, func(id int, w http.ResponseWriter, _ *http.Request) { + observed <- id + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, bpsRequestCompletedWire) + }) + enableLocalSIWCRequestProxies(t, svc, account) + account.Status, account.Schedulable = StatusActive, true + account.Extra[OpenAIProxyIDsKey] = []int64{2} + proxy, err := svc.proxyRepo.GetByID(t.Context(), 2) + require.NoError(t, err) + account.ProxyID, account.Proxy = &proxy.ID, proxy + latest := *account + latest.Extra = cloneReauthMap(account.Extra) + latest.Extra[OpenAIProxyModeKey] = mode + repo := &siwcRequestProxyAdmissionRepo{request: account, latest: &latest} + svc.accountRepo, svc.requireLatestTurnAdmission = repo, true + svc.cfg.Gateway.Scheduling.OpenAITurnAdmissionCacheTTLSeconds = 0 + _, _, err = forwardLocalBPSRequest(t.Context(), svc, account, []byte(`{"model":"gpt-5.4","input":"test","stream":true}`)) + require.GreaterOrEqual(t, repo.reads, 2) + if mode == OpenAIProxyModeSingle { + require.Error(t, err) + require.True(t, IsOpenAITurnAdmissionError(err)) + require.Empty(t, observed, "a mode change must not bypass the acquired request scope even when the old single proxy matches its URL") + } else { + require.NoError(t, err) + require.Equal(t, 2, <-observed) + } + }) + } +} + +func TestSIWCRequestProxyCompatibilityUsesSelectedExit(t *testing.T) { + for _, path := range []string{"/v1/responses", "/v1/chat/completions", "/v1/messages"} { + for _, stream := range []bool{false, true} { + t.Run(fmt.Sprintf("%s/stream=%t", path, stream), func(t *testing.T) { + observed := make(chan int, 1) + svc, account := localBPSRequestProxyFixture(t, 3, func(id int, w http.ResponseWriter, r *http.Request) { + _, _ = io.Copy(io.Discard, r.Body) + observed <- id + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, bpsRequestCompletedWire) + }) + enableLocalSIWCRequestProxies(t, svc, account) + account.Extra[OpenAIProxyIDsKey] = []int64{2} + body := []byte(fmt.Sprintf(`{"model":"gpt-5.4","messages":[{"role":"user","content":"test"}],"input":"test","max_tokens":32,"stream":%t}`, stream)) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, path, bytes.NewReader(body)) + var result *OpenAIForwardResult + var err error + switch path { + case "/v1/chat/completions": + result, err = svc.ForwardAsChatCompletions(t.Context(), c, account, body, "", "") + case "/v1/messages": + result, err = svc.ForwardAsAnthropic(t.Context(), c, account, body, "", "") + default: + result, err = svc.Forward(t.Context(), c, account, body) + } + require.NoError(t, err) + require.NotNil(t, result) + require.Equal(t, http.StatusOK, rec.Code) + require.NotEmpty(t, rec.Body.String()) + require.Equal(t, 2, <-observed) + }) + } + } +} + +func TestSIWCRequestProxySameSessionDistributesSixThroughThree(t *testing.T) { + arrived := make(chan int, 6) + release := make(chan struct{}) + var once sync.Once + t.Cleanup(func() { once.Do(func() { close(release) }) }) + svc, account := localBPSRequestProxyFixture(t, 4, func(id int, w http.ResponseWriter, r *http.Request) { + _, _ = io.Copy(io.Discard, r.Body) + arrived <- id + select { + case <-release: + case <-r.Context().Done(): + return + } + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, bpsRequestCompletedWire) + }) + enableLocalSIWCRequestProxies(t, svc, account) + ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second) + defer cancel() + done := make(chan error, 6) + for i := 0; i < 6; i++ { + go func() { + code, response, err := forwardLocalBPSRequest(ctx, svc, account, []byte(`{"model":"gpt-5.4","input":"test","stream":true,"prompt_cache_key":"same-session"}`)) + if err == nil && (code != http.StatusOK || !strings.Contains(response, "response.completed")) { + err = fmt.Errorf("incomplete SIWC response: %d %s", code, response) + } + done <- err + }() + } + hits := map[int]int{} + for i := 0; i < 6; i++ { + select { + case id := <-arrived: + hits[id]++ + case <-ctx.Done(): + t.Fatal("six SIWC requests did not reach selected local proxies") + } + } + once.Do(func() { close(release) }) + for i := 0; i < 6; i++ { + require.NoError(t, <-done) + } + require.Equal(t, map[int]int{1: 2, 2: 2, 3: 2}, hits) + require.Equal(t, 6, account.Concurrency) +} + +func TestSIWCRequestProxyUnavailableNeverSends(t *testing.T) { + for _, invalid := range []any{[]int64{}, []int64{999999}, "invalid"} { + t.Run(fmt.Sprint(invalid), func(t *testing.T) { + observed := make(chan int, 1) + svc, account := localBPSRequestProxyFixture(t, 3, func(id int, _ http.ResponseWriter, _ *http.Request) { observed <- id }) + enableLocalSIWCRequestProxies(t, svc, account) + account.Extra[OpenAIProxyIDsKey] = invalid + // Observe every attempted send, including a direct/old-proxy attempt. + capture := &httpUpstreamRecorder{err: fmt.Errorf("unexpected send")} + svc.httpUpstream = capture + account.Proxy = &Proxy{ID: 99, Protocol: "http", Host: "old.invalid", Port: 8080, FallbackMode: "direct"} + code, response, err := forwardLocalBPSRequest(t.Context(), svc, account, []byte(`{"model":"gpt-5.4","input":"test","stream":true}`)) + require.Error(t, err) + require.Equal(t, http.StatusServiceUnavailable, code) + require.Contains(t, response, "openai_proxy_unavailable") + require.Empty(t, capture.requests) + require.Empty(t, observed) + }) + } +} + +func TestSIWCRequestProxyFinishedTurnReleasesExit(t *testing.T) { + for _, terminal := range []string{"completed", "rejected", "canceled", "transport_failure"} { + t.Run(terminal, func(t *testing.T) { + arrived := make(chan int, 4) + var mu sync.Mutex + calls := 0 + svc, account := localBPSRequestProxyFixture(t, 4, func(id int, w http.ResponseWriter, r *http.Request) { + _, _ = io.Copy(io.Discard, r.Body) + mu.Lock() + calls++ + order := calls + mu.Unlock() + arrived <- id + if order <= 2 || (order == 3 && terminal == "canceled") { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, "data: {\"type\":\"response.created\",\"response\":{\"id\":\"held\",\"status\":\"in_progress\"}}\n\n") + w.(http.Flusher).Flush() + <-r.Context().Done() + return + } + if order == 3 { + switch terminal { + case "rejected": + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusBadRequest) + _, _ = io.WriteString(w, `{"error":{"code":"bad_request","message":"fixture rejected"}}`) + return + case "transport_failure": + conn, _, err := w.(http.Hijacker).Hijack() + if err == nil { + _ = conn.Close() + } + return + } + } + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, bpsRequestCompletedWire) + }) + enableLocalSIWCRequestProxies(t, svc, account) + account.Proxy = &Proxy{ID: 99, Protocol: "http", Host: "old.invalid", Port: 8080, FallbackMode: "direct"} + ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second) + defer cancel() + body := []byte(`{"model":"gpt-5.4","input":"test","stream":true}`) + start := func() (context.CancelFunc, <-chan error, int) { + child, stop := context.WithCancel(ctx) + done := make(chan error, 1) + go func() { _, _, err := forwardLocalBPSRequest(child, svc, account, body); done <- err }() + select { + case id := <-arrived: + return stop, done, id + case <-ctx.Done(): + stop() + t.Fatal("SIWC stream did not start") + return nil, nil, 0 + } + } + stopA, doneA, proxyA := start() + defer stopA() + stopB, doneB, proxyB := start() + defer stopB() + stopTurn, doneTurn, finished := start() + defer stopTurn() + if terminal == "canceled" { + stopTurn() + } + select { + case err := <-doneTurn: + if terminal == "completed" { + require.NoError(t, err) + } else { + require.Error(t, err) + } + case <-ctx.Done(): + t.Fatal("finished SIWC turn did not release") + } + require.ElementsMatch(t, []int{1, 2, 3}, []int{proxyA, proxyB, finished}) + require.Empty(t, arrived, "a failed turn must not be replayed through another proxy") + code, _, err := forwardLocalBPSRequest(ctx, svc, account, body) + require.NoError(t, err) + require.Equal(t, http.StatusOK, code) + require.Equal(t, finished, <-arrived, "reuse the released exit while the other streams stay busy") + cancel() + for _, done := range []<-chan error{doneA, doneB} { + select { + case <-done: + case <-time.After(time.Second): + t.Fatal("held SIWC stream did not finish") + } + } + mu.Lock() + total := calls + mu.Unlock() + require.Equal(t, 4, total) + }) + } +} + +// Refresh uses a real local HTTP proxy just like inference; only the external +// OAuth endpoint is replaced, and the production grant/CAS path stays intact. +type siwcRequestProxyTokenClient struct{ *reauthTestOAuthClient } + +func (c *siwcRequestProxyTokenClient) SIWCToken(ctx context.Context, form url.Values, proxy, _ string) (*openai.TokenResponse, *openai.SIWCIdentity, error) { + u, err := url.Parse(proxy) + if err != nil || u.Host == "" { + return nil, nil, fmt.Errorf("refresh must use a configured proxy") + } + tr := &http.Transport{Proxy: http.ProxyURL(u)} + defer tr.CloseIdleConnections() + req, err := http.NewRequestWithContext(ctx, http.MethodPost, "http://auth.openai.test/oauth/token", strings.NewReader(form.Encode())) + if err != nil { + return nil, nil, err + } + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + resp, err := (&http.Client{Transport: tr}).Do(req) + if err != nil { + return nil, nil, err + } + defer resp.Body.Close() + var token openai.TokenResponse + err = json.NewDecoder(resp.Body).Decode(&token) + return &token, nil, err +} + +func TestSIWCRequestProxyRefreshAndInferenceKeepSelectedExit(t *testing.T) { + observed := make(chan requestProxyObservation, 2) + svc, account := localBPSRequestProxyFixture(t, 3, func(id int, w http.ResponseWriter, r *http.Request) { + raw, _ := io.ReadAll(r.Body) + observed <- requestProxyObservation{id: id, path: r.URL.Path, body: raw} + if r.URL.Path == "/oauth/token" { + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, `{"access_token":"refreshed-siwc","refresh_token":"rotated-siwc","expires_in":3600}`) + return + } + if r.Header.Get("Authorization") == "Bearer independent-siwc" { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, "data: {\"type\":\"response.created\",\"response\":{\"id\":\"held\",\"status\":\"in_progress\"}}\n\n") + w.(http.Flusher).Flush() + <-r.Context().Done() + return + } + require.Equal(t, "Bearer refreshed-siwc", r.Header.Get("Authorization")) + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, bpsRequestCompletedWire) + }) + enableLocalSIWCRequestProxies(t, svc, account) + // Keep one real inference busy, then expire the saved grant. The next + // request's refresh must follow its less-busy exit, rather than independently + // taking the first configured maintenance proxy. + ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second) + defer cancel() + heldCtx, stopHeld := context.WithCancel(ctx) + defer stopHeld() + heldDone := make(chan error, 1) + go func() { + _, _, err := forwardLocalBPSRequest(heldCtx, svc, account, []byte(`{"model":"gpt-5.4","input":"hold","stream":true}`)) + heldDone <- err + }() + var held requestProxyObservation + select { + case held = <-observed: + case <-ctx.Done(): + t.Fatal("initial SIWC request did not reach a selected proxy") + } + reauth := svc.excelOAuthReauth + store := reauth.repo.(*siwcTestRepo) + var grant siwcGrant + require.NoError(t, json.Unmarshal([]byte(strings.TrimPrefix(store.ciphertext, "encrypted:")), &grant)) + grant.ExpiresAt = 0 + raw, err := json.Marshal(grant) + require.NoError(t, err) + store.ciphertext = "encrypted:" + string(raw) + reauth.oauth.oauthClient = &siwcRequestProxyTokenClient{} + code, _, err := forwardLocalBPSRequest(ctx, svc, account, []byte(`{"model":"gpt-5.4","input":"test","stream":true}`)) + require.NoError(t, err) + require.Equal(t, http.StatusOK, code) + refresh, inference := <-observed, <-observed + require.Equal(t, "/oauth/token", refresh.path) + require.Equal(t, "/v1/responses", inference.path) + require.Equal(t, refresh.id, inference.id) + require.NotEqual(t, held.id, inference.id) + form, err := url.ParseQuery(string(refresh.body)) + require.NoError(t, err) + require.Equal(t, "siwc-refresh", form.Get("refresh_token")) + require.Equal(t, "old-refresh", account.Credentials["refresh_token"]) + stopHeld() + select { + case <-heldDone: + case <-ctx.Done(): + t.Fatal("held SIWC inference did not finish") + } +} diff --git a/backend/internal/service/openai_totp_rotation.go b/backend/internal/service/openai_totp_rotation.go index 1d43ba0ffd8b..cd7335153ef4 100644 --- a/backend/internal/service/openai_totp_rotation.go +++ b/backend/internal/service/openai_totp_rotation.go @@ -215,10 +215,17 @@ func (s *OpenAIOAuthReauthService) ClaimTOTPRotation(ctx context.Context, worker if err == nil { source, sourceErr := normalizeReauthProxySource(cfg.ProxySource, cfg.ProxyID) err = sourceErr + if err == nil && account.OpenAIRequestProxyEnabled() && source != OpenAIOAuthReauthProxySourceAccount { + err = errors.New("request proxy routing requires the account proxy source") + } if err == nil { switch source { case OpenAIOAuthReauthProxySourceAccount: - claim.ProxyURL, err = s.reauthProxyURL(ctx, account.ProxyID) + if account.OpenAIRequestProxyEnabled() { + claim.ProxyURL, err = resolveOpenAIMaintenanceProxy(ctx, account, s.oauth.proxyRepo) + } else { + claim.ProxyURL, err = s.reauthProxyURL(ctx, account.ProxyID) + } case OpenAIOAuthReauthProxySourceManagedProxy: claim.ProxyURL, err = s.reauthProxyURL(ctx, cfg.ProxyID) case OpenAIOAuthReauthProxySourceMihomo: diff --git a/backend/internal/service/openai_ws_forwarder_ingress.go b/backend/internal/service/openai_ws_forwarder_ingress.go index 32c94fe8e8ba..47b6bcbd6139 100644 --- a/backend/internal/service/openai_ws_forwarder_ingress.go +++ b/backend/internal/service/openai_ws_forwarder_ingress.go @@ -624,6 +624,9 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( return admissionErr } account = latest + if account.OpenAIRequestProxyEnabled() { + return NewOpenAIWSClientCloseError(coderws.StatusPolicyViolation, "Request proxy routing requires HTTP/SSE; WebSocket routing is unavailable", nil) + } if account.IsSIWCEnabled() { return NewOpenAIWSClientCloseError(coderws.StatusPolicyViolation, "SIWC accounts require HTTP/SSE", nil) } From 17073f053315c3846ebd7a2bb8cca6780fbe619e Mon Sep 17 00:00:00 2001 From: luotao21 Date: Mon, 16 Nov 2026 21:28:54 +0800 Subject: [PATCH 02/14] =?UTF-8?q?feat:=20=E6=95=B4=E5=90=88=E5=8D=95?= =?UTF-8?q?=E5=A4=9A=E4=BB=A3=E7=90=86=E5=85=A5=E5=8F=A3=E5=B9=B6=E5=A2=9E?= =?UTF-8?q?=E5=8A=A0=E6=89=B9=E9=87=8F=E9=80=89=E6=8B=A9=E5=92=8C=E8=BF=9E?= =?UTF-8?q?=E6=8E=A5=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- frontend/src/api/admin/accounts.ts | 8 +- .../account/BPSProxyRoutingSettings.vue | 360 ++++++++++++++++++ .../components/account/CreateAccountModal.vue | 132 ++++++- .../components/account/EditAccountModal.vue | 37 +- .../account/OpenAIProxySettings.vue | 53 +++ .../account/SIWCAccountSettings.vue | 1 + .../__tests__/BPSProxyRoutingSettings.spec.ts | 258 +++++++++++++ .../__tests__/CreateAccountModal.spec.ts | 339 ++++++++++++++++- .../EditAccountModal.autoBPS.spec.ts | 4 + ...ditAccountModal.grokForbiddenPause.spec.ts | 4 + ...tAccountModal.grokMediaEligibility.spec.ts | 5 +- .../EditAccountModal.grokUpstream.spec.ts | 7 + .../EditAccountModal.groupModelLimits.spec.ts | 5 +- .../__tests__/EditAccountModal.spec.ts | 230 +++++++++++ .../OpenAIProxyRouting.acceptance.spec.ts | 331 ++++++++++++++++ .../__tests__/useOpenAIOAuth.spec.ts | 19 + frontend/src/composables/useOpenAIOAuth.ts | 25 +- frontend/src/constants/newFeatureNotices.ts | 2 + .../src/i18n/locales/en/admin/accounts.ts | 37 ++ frontend/src/i18n/locales/en/siwc.ts | 1 + .../src/i18n/locales/zh/admin/accounts.ts | 37 ++ frontend/src/i18n/locales/zh/siwc.ts | 1 + frontend/src/views/admin/AccountsView.vue | 32 +- .../AccountsView.proxyCatalog.spec.ts | 167 ++++++++ 24 files changed, 2063 insertions(+), 32 deletions(-) create mode 100644 frontend/src/components/account/BPSProxyRoutingSettings.vue create mode 100644 frontend/src/components/account/OpenAIProxySettings.vue create mode 100644 frontend/src/components/account/__tests__/BPSProxyRoutingSettings.spec.ts create mode 100644 frontend/src/components/account/__tests__/OpenAIProxyRouting.acceptance.spec.ts create mode 100644 frontend/src/views/admin/__tests__/AccountsView.proxyCatalog.spec.ts diff --git a/frontend/src/api/admin/accounts.ts b/frontend/src/api/admin/accounts.ts index 2fc5a0292564..2e23f077428e 100644 --- a/frontend/src/api/admin/accounts.ts +++ b/frontend/src/api/admin/accounts.ts @@ -480,9 +480,9 @@ export async function resetTempUnschedulable(id: number): Promise<{ message: str */ export async function generateAuthUrl( endpoint: string, - config: { proxy_id?: number } -): Promise<{ auth_url: string; session_id: string }> { - const { data } = await apiClient.post<{ auth_url: string; session_id: string }>(endpoint, config) + config: { proxy_id?: number; proxy_mode?: 'single' | 'request'; proxy_ids?: number[] } +): Promise<{ auth_url: string; session_id: string; proxy_mode?: 'single' | 'request'; proxy_id?: number }> { + const { data } = await apiClient.post<{ auth_url: string; session_id: string; proxy_mode?: 'single' | 'request'; proxy_id?: number }>(endpoint, config) return data } @@ -494,7 +494,7 @@ export async function generateAuthUrl( */ export async function exchangeCode( endpoint: string, - exchangeData: { session_id: string; code: string; state?: string; proxy_id?: number } + exchangeData: { session_id: string; code: string; state?: string; proxy_id?: number; proxy_mode?: 'single' | 'request'; proxy_ids?: number[] } ): Promise> { const { data } = await apiClient.post>(endpoint, exchangeData) return data diff --git a/frontend/src/components/account/BPSProxyRoutingSettings.vue b/frontend/src/components/account/BPSProxyRoutingSettings.vue new file mode 100644 index 000000000000..caab57b541f7 --- /dev/null +++ b/frontend/src/components/account/BPSProxyRoutingSettings.vue @@ -0,0 +1,360 @@ + + + + + diff --git a/frontend/src/components/account/CreateAccountModal.vue b/frontend/src/components/account/CreateAccountModal.vue index 8ed52bfb27f1..c2fb5befe60b 100644 --- a/frontend/src/components/account/CreateAccountModal.vue +++ b/frontend/src/components/account/CreateAccountModal.vue @@ -3257,7 +3257,14 @@ - + + + { interface Props { show: boolean proxies: Proxy[] + proxiesLoading?: boolean + proxiesLoadError?: boolean groups: AdminGroup[] } const props = defineProps() const emit = defineEmits<{ close: [] + 'retry-proxies': [] created: [] }>() @@ -4626,6 +4637,52 @@ const step = ref(1) const openaiTwoFA = ref(false) const openaiBPSOAuth = ref(false) const bpsOAuthModels = ref([...DEFAULT_EXCEL_BPS_MODELS]) +const openaiProxyMode = ref<'single' | 'request'>('single') +const openaiProxyIds = ref([]) +const openaiAuthorizationProxy = ref<{ + sessionId: string + mode: 'single' | 'request' + proxyId: number | null + fingerprint: string | null +} | null>(null) +const openaiProxyFingerprint = (proxy: Proxy) => JSON.stringify([ + proxy.protocol, proxy.host, proxy.port, proxy.username ?? '', proxy.password ?? '', +]) +const resolveOpenAIMaintenanceProxyId = () => { + if (openaiProxyMode.value !== 'request') return form.proxy_id + return openaiProxyIds.value.find(id => props.proxies.some(proxy => proxy.id === id && proxy.status === 'active' && + (!proxy.expires_at || Date.parse(proxy.expires_at) > Date.now()))) ?? null +} +function validateOpenAIRequestProxies(): boolean { + if (form.platform !== 'openai' || accountCategory.value !== 'oauth-based' || openaiProxyMode.value !== 'request') return true + if (isOpenAITwoFA.value) { + appStore.showError(t('admin.accounts.openai.proxyTwoFAFirstImport')) + return false + } + if (openaiProxyIds.value.length === 0) { + appStore.showError(t('admin.accounts.openai.proxyRequired')) + return false + } + if (props.proxiesLoading || props.proxiesLoadError || resolveOpenAIMaintenanceProxyId() === null) { + appStore.showError(t('admin.accounts.openai.proxyNoUsable')) + return false + } + return true +} +function validateOpenAIAuthorizationProxy(): boolean { + const authorization = openaiAuthorizationProxy.value + if (authorization?.sessionId === openaiOAuth.sessionId.value && authorization.mode === openaiProxyMode.value) { + if (authorization.mode === 'single') return true + const proxy = props.proxies.find(candidate => candidate.id === authorization.proxyId) + if (!props.proxiesLoading && !props.proxiesLoadError && proxy && + openaiProxyIds.value.includes(proxy.id) && proxy.status === 'active' && + (!proxy.expires_at || Date.parse(proxy.expires_at) > Date.now()) && + openaiProxyFingerprint(proxy) === authorization.fingerprint) return true + } + openaiOAuth.error.value = t('admin.accounts.openai.proxyAuthorizationChanged') + appStore.showError(openaiOAuth.error.value) + return false +} const isOpenAIBPSOAuth = computed(() => form.platform === 'openai' && accountCategory.value === 'oauth-based' && openaiBPSOAuth.value) // Includes unresolved login ownership while the importer is paused for Retry. const twoFABusy = ref(false) @@ -6009,6 +6066,9 @@ const resetForm = () => { openaiTwoFA.value = false openaiBPSOAuth.value = false bpsOAuthModels.value = [...DEFAULT_EXCEL_BPS_MODELS] + openaiProxyMode.value = 'single' + openaiProxyIds.value = [] + openaiAuthorizationProxy.value = null autoBPS.reset() twoFABusy.value = false form.name = '' @@ -6165,6 +6225,8 @@ const buildOpenAIExtra = (base?: Record): Record m.trim()).filter(Boolean))] } if (accountCategory.value === 'oauth-based') { + extra.openai_proxy_mode = openaiProxyMode.value + extra.openai_proxy_ids = [...openaiProxyIds.value] extra.openai_oauth_responses_websockets_v2_mode = openaiOAuthResponsesWebSocketV2Mode.value extra.openai_oauth_responses_websockets_v2_enabled = isOpenAIWSModeEnabled(openaiOAuthResponsesWebSocketV2Mode.value) applyAccountRPMSettings(extra, { @@ -6254,7 +6316,7 @@ const buildOpenAIExtra = (base?: Record): Record 0 ? extra : undefined } -const buildOpenAICodexImportExtra = (): Record | undefined => { +const buildOpenAICodexImportExtra = (supportsProxyGroup = true): Record | undefined => { const extra = buildOpenAIExtra() if (!extra) { return undefined @@ -6262,6 +6324,10 @@ const buildOpenAICodexImportExtra = (): Record | undefined => { if (!openAILongContextBillingTouched.value) { delete extra.openai_long_context_billing_enabled } + if (!supportsProxyGroup) { + delete extra.openai_proxy_mode + delete extra.openai_proxy_ids + } return Object.keys(extra).length > 0 ? extra : undefined } @@ -6397,6 +6463,7 @@ const handleVertexServiceAccountDrop = async (event: DragEvent) => { } const handleSubmit = async () => { + if (!validateOpenAIRequestProxies()) return if (isOpenAIBPSOAuth.value && !bpsOAuthModels.value.some(model => model.trim())) { appStore.showError(t('admin.accounts.oauth.openai.excelModelsRequired')) return @@ -6711,7 +6778,23 @@ const goBackToBasicInfo = () => { const handleGenerateUrl = async () => { if (form.platform === 'openai') { - await openaiOAuth.generateAuthUrl(form.proxy_id, undefined, isOpenAIBPSOAuth.value ? 'excel' : 'codex') + if (!validateOpenAIRequestProxies()) return + const mode = openaiProxyMode.value + const fingerprints = new Map(props.proxies.map(proxy => [proxy.id, openaiProxyFingerprint(proxy)])) + openaiAuthorizationProxy.value = null + const generated = await openaiOAuth.generateAuthUrl( + mode === 'request' ? undefined : form.proxy_id, + undefined, + isOpenAIBPSOAuth.value ? 'excel' : 'codex', + mode === 'request' ? { mode, ids: [...openaiProxyIds.value] } : undefined, + ) + if (generated) { + const proxyId = mode === 'request' ? openaiOAuth.authorizationProxyId.value : form.proxy_id + openaiAuthorizationProxy.value = { + sessionId: openaiOAuth.sessionId.value, mode, proxyId, + fingerprint: proxyId === null ? null : fingerprints.get(proxyId) ?? null, + } + } } else if (form.platform === 'gemini') { await geminiOAuth.generateAuthUrl( form.proxy_id, @@ -7126,6 +7209,8 @@ const createdImportAccountIds = (result: CodexSessionImportResult) => const handleOpenAIExchange = async (authCode: string) => { const oauthClient = openaiOAuth if (!authCode.trim() || !oauthClient.sessionId.value) return + if (!validateOpenAIAuthorizationProxy()) return + if (!validateOpenAIRequestProxies()) return oauthClient.loading.value = true oauthClient.error.value = '' @@ -7142,7 +7227,8 @@ const handleOpenAIExchange = async (authCode: string) => { authCode.trim(), oauthClient.sessionId.value, stateToUse, - form.proxy_id + openaiProxyMode.value === 'request' ? undefined : form.proxy_id, + openaiProxyMode.value === 'request' ? { mode: 'request', ids: [...openaiProxyIds.value] } : undefined, ) if (!tokenInfo) return @@ -7261,9 +7347,29 @@ const isAgentIdentityImportContent = (content: string) => { } } +const containsUnsupportedProxyGroupIdentity = (content: string): boolean => { + const unsupported = (value: unknown): boolean => { + if (Array.isArray(value)) return value.some(unsupported) + if (!value || typeof value !== 'object') return false + const record = value as Record + const modes = [record.auth_mode, record.authMode, record.openai_auth_mode] + .map(mode => String(mode ?? '').trim().toLowerCase()) + return modes.some(mode => ['agentidentity', 'personalaccesstoken', 'personal_access_token'].includes(mode)) + || !!(record.agent_identity ?? record.agentIdentity) + } + try { + return unsupported(JSON.parse(content)) + } catch { + return content.split('\n').filter(line => line.trim()).some(line => { + try { return unsupported(JSON.parse(line)) } catch { return false } + }) + } +} + // Reuse Session import normalization and identity deduplication after 2FA login. const importTwoFACredential = async (credential: Record, email: string, login: TokenGuardReloginAccount, signal?: AbortSignal): Promise<'created' | 'skipped'> => { signal?.throwIfAborted() + if (!validateOpenAIRequestProxies()) throw new Error(t('admin.accounts.openai.proxyNoUsable')) const credentialExtras = buildOpenAICodexImportCredentialExtras() if (credentialExtras === null) throw new Error('invalid_account_settings') const result = await importWithUpstream({ @@ -7325,6 +7431,12 @@ const handleOpenAIImportCodexSession = async (content: string) => { oauthClient.error.value = t('admin.accounts.oauth.openai.agentIdentityInvalid') return } + const supportsProxyGroup = !containsUnsupportedProxyGroupIdentity(trimmed) + if (openaiProxyMode.value === 'request' && !supportsProxyGroup) { + oauthClient.error.value = t('admin.accounts.openai.proxyUnsupportedImport') + return + } + if (!validateOpenAIRequestProxies()) return const credentialExtras = buildOpenAICodexImportCredentialExtras() if (credentialExtras === null) { @@ -7335,7 +7447,7 @@ const handleOpenAIImportCodexSession = async (content: string) => { oauthClient.error.value = '' try { - const extra = buildOpenAICodexImportExtra() + const extra = buildOpenAICodexImportExtra(supportsProxyGroup) const result = await importWithUpstream({ content: trimmed, name: form.name, @@ -7402,6 +7514,10 @@ const handleOpenAIImportCodexSession = async (content: string) => { const handleOpenAIImportCodexPAT = async (accessToken: string) => { const oauthClient = openaiOAuth + if (openaiProxyMode.value === 'request') { + oauthClient.error.value = t('admin.accounts.openai.proxyUnsupportedImport') + return + } const trimmed = accessToken.trim() if (!trimmed) { oauthClient.error.value = t('admin.accounts.oauth.openai.codexPatEmpty') @@ -7417,7 +7533,7 @@ const handleOpenAIImportCodexPAT = async (accessToken: string) => { oauthClient.error.value = '' try { - const extra = buildOpenAICodexImportExtra() + const extra = buildOpenAICodexImportExtra(false) await createPATWithUpstream({ access_token: trimmed, name: form.name, @@ -7454,6 +7570,7 @@ const handleOpenAIImportCodexPAT = async (accessToken: string) => { const handleOpenAIBatchRT = async (refreshTokenInput: string, clientId?: string) => { const oauthClient = openaiOAuth if (!refreshTokenInput.trim()) return + if (!validateOpenAIRequestProxies()) return const refreshTokens = refreshTokenInput .split('\n') @@ -7477,9 +7594,10 @@ const handleOpenAIBatchRT = async (refreshTokenInput: string, clientId?: string) try { for (let i = 0; i < refreshTokens.length; i++) { try { + if (!validateOpenAIRequestProxies()) throw new Error(t('admin.accounts.openai.proxyNoUsable')) const tokenInfo = await oauthClient.validateRefreshToken( refreshTokens[i], - form.proxy_id, + resolveOpenAIMaintenanceProxyId(), clientId ) if (!tokenInfo) { diff --git a/frontend/src/components/account/EditAccountModal.vue b/frontend/src/components/account/EditAccountModal.vue index 77c6f8a29c0a..20a140565efc 100644 --- a/frontend/src/components/account/EditAccountModal.vue +++ b/frontend/src/components/account/EditAccountModal.vue @@ -2053,7 +2053,11 @@ - + + -
+
diff --git a/frontend/src/i18n/locales/en/admin/accounts.ts b/frontend/src/i18n/locales/en/admin/accounts.ts index 9b6ef4ca10e6..c97f97c8e9c9 100644 --- a/frontend/src/i18n/locales/en/admin/accounts.ts +++ b/frontend/src/i18n/locales/en/admin/accounts.ts @@ -863,6 +863,7 @@ export default { bpsProxyRouting: 'BPS proxy routing', proxyModeSingle: 'Single proxy', proxyModeRequest: 'Multiple proxies (distribute by request)', + proxyRequestRisk: 'Using multiple IPs for one account may increase verification challenges, rate limits or account restrictions. Throughput is not guaranteed. Keep total concurrency controlled; switch back to a single proxy or disable the account when needed.', proxyGroup: 'Account proxy group (from IP management)', proxyRequestHint: 'For ordinary OpenAI OAuth and BPS. Use only selected proxies, preferring the exit with the fewest in-flight account requests, including within one session. The account concurrency limit is unchanged; unavailable proxies never fall back to a direct connection. Authorization and maintenance use the first usable selected proxy.', proxyRequired: 'Select at least one proxy for request distribution', diff --git a/frontend/src/i18n/locales/zh/admin/accounts.ts b/frontend/src/i18n/locales/zh/admin/accounts.ts index 6e7b9394759c..adc82cc77ea4 100644 --- a/frontend/src/i18n/locales/zh/admin/accounts.ts +++ b/frontend/src/i18n/locales/zh/admin/accounts.ts @@ -981,6 +981,7 @@ export default { bpsProxyRouting: 'BPS 代理分配', proxyModeSingle: '单代理', proxyModeRequest: '多代理(按请求分散)', + proxyRequestRisk: '同账号使用多个 IP 可能增加异常验证、限流或账号限制风险,不保证提升吞吐。建议控制总并发;需要恢复单出口时切回单代理,或停用账号。', proxyGroup: '账号代理组(从 IP 管理选择)', proxyRequestHint: '适用于普通 OpenAI OAuth 和 BPS。仅使用所选代理,优先分配当前账号在途请求最少的出口,同会话可分散;账号总并发上限不变,不可用时不会直连。授权与维护使用组内首个有效代理。', proxyRequired: '按请求分散模式至少需要选择一个代理', From ffdcfe67d716da75701febac41ac379373b1ed1e Mon Sep 17 00:00:00 2001 From: luotao21 Date: Tue, 17 Nov 2026 01:15:38 +0800 Subject: [PATCH 07/14] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E4=B8=8A=E6=B8=B8?= =?UTF-8?q?=E6=96=B0=E5=A2=9E=E5=AE=88=E5=8D=AB=E6=B5=8B=E8=AF=95=E5=AF=BC?= =?UTF-8?q?=E8=87=B4=E5=8E=86=E5=8F=B2=E5=9B=9E=E6=94=BE=E5=87=86=E5=A4=87?= =?UTF-8?q?=E5=A4=B1=E8=B4=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../scripts/prepare-ws-inherited-model-red.py | 24 +++- .../test_ws_inherited_model_evidence.py | 126 +++++++++++++++++- 2 files changed, 146 insertions(+), 4 deletions(-) diff --git a/.github/scripts/prepare-ws-inherited-model-red.py b/.github/scripts/prepare-ws-inherited-model-red.py index 07ab89260388..44964264e048 100644 --- a/.github/scripts/prepare-ws-inherited-model-red.py +++ b/.github/scripts/prepare-ws-inherited-model-red.py @@ -13,6 +13,10 @@ BASELINE = "da526bfbab47efd40549cab98f1069f9b2b45b9f" FIXTURE = "backend/internal/handler/openai_ws_inherited_model_test.go" GUARDS = "backend/internal/service/openai_ws_owner_conflict_test.go" +# This upstream commit only prepends the independent pending-deadline fixture. +# Keep its full blob pinned; arbitrary changes to the candidate guards still fail. +GUARD_EXTENSION = "9dc66846a16609fb75b59a643563fae3284944cf" +GUARD_SOURCE_START = b"// Calls are learned only from the real response observer and successful write\n" def git(*args, **kwargs): @@ -50,8 +54,20 @@ def prepare(destination, evidence): fixture_blob = git("rev-parse", f"{candidate}:{FIXTURE}").decode().strip() if git("hash-object", FIXTURE).decode().strip() != fixture_blob: raise ValueError("dirty candidate fixture") - if Path(GUARDS).read_bytes() != (destination / GUARDS).read_bytes(): - raise ValueError("guard fixture changed; identical baseline/candidate guard tests required") + guard_blob = git("rev-parse", f"{candidate}:{GUARDS}").decode().strip() + if git("hash-object", GUARDS).decode().strip() != guard_blob: + raise ValueError("dirty candidate guard fixture") + baseline_guards = (destination / GUARDS).read_bytes() + candidate_guards = Path(GUARDS).read_bytes() + if candidate_guards != baseline_guards: + approved_guards = git("show", f"{GUARD_EXTENSION}:{GUARDS}") + if candidate_guards != approved_guards: + raise ValueError("guard fixture changed outside the pinned upstream extension") + if (baseline_guards.count(GUARD_SOURCE_START) != 1 + or candidate_guards.count(GUARD_SOURCE_START) != 1 + or baseline_guards.split(GUARD_SOURCE_START, 1)[1] + != candidate_guards.split(GUARD_SOURCE_START, 1)[1]): + raise ValueError("guard fixture changed; identical baseline/candidate guard tests required") shutil.copyfile(FIXTURE, destination / FIXTURE) if git("hash-object", str(destination / FIXTURE)).decode().strip() != fixture_blob: raise ValueError("candidate test copy mismatch") @@ -60,7 +76,9 @@ def prepare(destination, evidence): "baseline_tree": git("rev-parse", f"{BASELINE}^{{tree}}").decode().strip(), "baseline_backend_tree": git("rev-parse", f"{BASELINE}:backend").decode().strip(), "candidate_fixture_blob": fixture_blob, "fixture": FIXTURE, - "guard_fixture_blob": git("hash-object", GUARDS).decode().strip(), + "guard_fixture_blob": guard_blob, + "baseline_guard_fixture_blob": git("rev-parse", f"{BASELINE}:{GUARDS}").decode().strip(), + "approved_guard_extension": GUARD_EXTENSION if candidate_guards != baseline_guards else None, "verified_baseline_backend_blobs": len(entries), "production_changes_in_red": [], "candidate_test_overlays": [FIXTURE], } diff --git a/.github/scripts/test_ws_inherited_model_evidence.py b/.github/scripts/test_ws_inherited_model_evidence.py index ba6b4a61a83e..ce7da7efb400 100644 --- a/.github/scripts/test_ws_inherited_model_evidence.py +++ b/.github/scripts/test_ws_inherited_model_evidence.py @@ -1,15 +1,25 @@ -"""Synthetic parser checks only; these are never Go RED/GREEN evidence.""" +"""Parser and source-preparation checks; these are never Go RED/GREEN evidence.""" import importlib.util import json +import os +import subprocess +import tempfile import unittest +from contextlib import ExitStack from pathlib import Path +from unittest.mock import patch SPEC = importlib.util.spec_from_file_location( "evidence", Path(__file__).with_name("ws-inherited-model-evidence.py") ) GATE = importlib.util.module_from_spec(SPEC) SPEC.loader.exec_module(GATE) +PREPARE_SPEC = importlib.util.spec_from_file_location( + "prepare", Path(__file__).with_name("prepare-ws-inherited-model-red.py") +) +PREPARE = importlib.util.module_from_spec(PREPARE_SPEC) +PREPARE_SPEC.loader.exec_module(PREPARE) def transcript(suite="handler", phase="RED"): @@ -130,5 +140,119 @@ def test_status_phase_and_malformed_input(self): GATE.validate("handler", "RED", 1, raw) +class SourcePreparationTests(unittest.TestCase): + def isolated_git_environment(self, root): + env = {key: value for key, value in os.environ.items() if not key.startswith("GIT_")} + env.update(GIT_AUTHOR_NAME="Fixture", GIT_AUTHOR_EMAIL="fixture@example.invalid", + GIT_COMMITTER_NAME="Fixture", GIT_COMMITTER_EMAIL="fixture@example.invalid", + GIT_CONFIG_NOSYSTEM="1", GIT_CONFIG_GLOBAL=os.devnull, GIT_CONFIG_COUNT="3") + empty_template = root / "empty-template" + empty_template.mkdir(exist_ok=True) + for index, (key, value) in enumerate({ + "commit.gpgsign": "false", "core.hooksPath": os.devnull, + "init.templateDir": str(empty_template), + }.items()): + env[f"GIT_CONFIG_KEY_{index}"] = key + env[f"GIT_CONFIG_VALUE_{index}"] = value + return env + + def test_only_pinned_additive_guard_fixture_is_allowed(self): + for change in ("unchanged", "approved_extension", "new_unapproved_fixture", "dirty_guard", "changed_original_assertion"): + with self.subTest(change=change), tempfile.TemporaryDirectory() as tmp, ExitStack() as stack: + root = Path(tmp) + repo = root / "repo" + repo.mkdir() + env = self.isolated_git_environment(root) + + def git(*args, directory=repo): + return subprocess.check_output(["git", "-C", str(directory), *args], env=env, stderr=subprocess.PIPE).decode().strip() + + # A real external repository/index must survive both the fixture + # commands and prepare()'s independently spawned Git processes. + external = root / "external" + git("init", "-q", str(external)) + (external / "sentinel").write_text("external work must remain unchanged\n") + git("add", "sentinel", directory=external) + git("commit", "-qm", "external baseline", directory=external) + external_index = external / ".git/index" + index_before = external_index.read_bytes() + head_before = (external / ".git/HEAD").read_bytes() + external_commit_before = git("rev-parse", "HEAD", directory=external) + rejecting_hook = external / ".git/hooks/pre-commit" + rejecting_hook.parent.mkdir() + rejecting_hook.write_text("#!/bin/sh\nexit 99\n") + rejecting_hook.chmod(0o755) + untrusted_config = root / "untrusted-gitconfig" + untrusted_config.write_text(f'[commit]\n gpgsign = true\n[core]\n hooksPath = "{rejecting_hook.parent}"\n') + stack.enter_context(patch.dict(os.environ, { + "GIT_DIR": str(external / ".git"), "GIT_WORK_TREE": str(external), + "GIT_INDEX_FILE": str(external_index), + "GIT_COMMON_DIR": str(external / ".git"), + "GIT_OBJECT_DIRECTORY": str(external / ".git/objects"), + "GIT_CONFIG_GLOBAL": str(untrusted_config), + "GIT_CONFIG_COUNT": "0", + })) + env = self.isolated_git_environment(root) + + def commit(message): + git("add", ".") + git("commit", "--allow-empty", "-qm", message) + return git("rev-parse", "HEAD") + + git("init", "-q") + inherited_git_dir = subprocess.check_output(["git", "-C", str(repo), "rev-parse", "--absolute-git-dir"], stderr=subprocess.PIPE).decode().strip() + self.assertEqual((external / ".git").resolve(), Path(inherited_git_dir).resolve(), "contamination is active without isolation") + self.assertEqual((repo / ".git").resolve(), Path(git("rev-parse", "--absolute-git-dir")).resolve()) + guard = repo / PREPARE.GUARDS + guard.parent.mkdir(parents=True) + handler = repo / "backend/internal/handler/existing_test.go" + handler.parent.mkdir(parents=True) + handler.write_text("package handler\n") + original = PREPARE.GUARD_SOURCE_START.decode() + "// identical original assertion and helper bodies\n" + guard.write_text("package service\n" + original) + baseline = commit("baseline") + guard.write_text("package service\n// independent pending fixture\n" + original) + extension = commit("approved upstream extension") + fixture = repo / PREPARE.FIXTURE + fixture.parent.mkdir(parents=True, exist_ok=True) + fixture.write_text("package handler\n// identical candidate fixture\n") + if change == "unchanged": + guard.write_text("package service\n" + original) + elif change == "new_unapproved_fixture": + guard.write_text(guard.read_text() + "// arbitrary added fixture\n") + elif change == "changed_original_assertion": + guard.write_text(guard.read_text().replace("identical original assertion", "weakened original assertion")) + extension = commit("unacceptable approved extension changes existing guards") + commit("candidate") + if change == "dirty_guard": + guard.write_text(guard.read_text() + "// dirty guard\n") + destination, evidence = root / "baseline", root / "evidence" + with patch.dict(os.environ, env, clear=True), patch.object(PREPARE, "BASELINE", baseline), patch.object(PREPARE, "GUARD_EXTENSION", extension): + previous = Path.cwd() + os.chdir(repo) + try: + if change in {"unchanged", "approved_extension"}: + PREPARE.prepare(destination, evidence) + manifest = json.loads((evidence / "source-manifest.json").read_text()) + self.assertEqual([PREPARE.FIXTURE], manifest["candidate_test_overlays"]) + self.assertEqual([], manifest["production_changes_in_red"]) + self.assertEqual(git("show", baseline + ":" + PREPARE.GUARDS) + "\n", (destination / PREPARE.GUARDS).read_text()) + self.assertEqual(fixture.read_bytes(), (destination / PREPARE.FIXTURE).read_bytes()) + self.assertEqual(extension if change == "approved_extension" else None, manifest["approved_guard_extension"]) + else: + with self.assertRaisesRegex(ValueError, { + "new_unapproved_fixture": "outside the pinned upstream extension", + "dirty_guard": "dirty candidate guard", + "changed_original_assertion": "identical baseline/candidate guard tests", + }[change]): + PREPARE.prepare(destination, evidence) + finally: + os.chdir(previous) + self.assertEqual(index_before, external_index.read_bytes(), "external Git index must not be touched") + self.assertEqual(head_before, (external / ".git/HEAD").read_bytes()) + self.assertEqual(external_commit_before, git("rev-parse", "HEAD", directory=external)) + self.assertEqual("external work must remain unchanged\n", (external / "sentinel").read_text()) + + if __name__ == "__main__": unittest.main() From 0b08e01d57e3c1fe4415a8f71a5b014d0eaffe85 Mon Sep 17 00:00:00 2001 From: luotao21 Date: Tue, 17 Nov 2026 02:18:27 +0800 Subject: [PATCH 08/14] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E4=BB=A3=E7=90=86?= =?UTF-8?q?=E8=B7=AF=E7=94=B1=E6=B5=8B=E8=AF=95=E7=9A=84=E4=BE=9D=E8=B5=96?= =?UTF-8?q?=E8=BE=B9=E7=95=8C=E5=92=8C=E8=B5=84=E6=BA=90=E6=B8=85=E7=90=86?= =?UTF-8?q?=E6=A3=80=E6=9F=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../admin/account_bps_proxy_data_test.go | 9 ++++++-- backend/internal/mihomo/bps_request_test.go | 11 +++++----- ...openai_maintenance_remaining_proxy_test.go | 3 ++- ...nai_maintenance_task_request_proxy_test.go | 10 +++++---- .../openai_oauth_reauth_request_proxy_test.go | 10 +++------ .../service/openai_request_proxy_test.go | 4 ++-- .../internal/testutil/redissession/store.go | 21 +++++++++++++++++++ 7 files changed, 47 insertions(+), 21 deletions(-) create mode 100644 backend/internal/testutil/redissession/store.go diff --git a/backend/internal/handler/admin/account_bps_proxy_data_test.go b/backend/internal/handler/admin/account_bps_proxy_data_test.go index 1ecfafc79628..0d113539f6c3 100644 --- a/backend/internal/handler/admin/account_bps_proxy_data_test.go +++ b/backend/internal/handler/admin/account_bps_proxy_data_test.go @@ -26,9 +26,14 @@ func TestAccountDataBPSRequestProxyPortableRoundTrip(t *testing.T) { Data map[string]any `json:"data"` } require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &envelope)) - proxies := envelope.Data["proxies"].([]any) + proxies, ok := envelope.Data["proxies"].([]any) + require.True(t, ok) require.Len(t, proxies, 2) - account := envelope.Data["accounts"].([]any)[0].(map[string]any) + accounts, ok := envelope.Data["accounts"].([]any) + require.True(t, ok) + require.Len(t, accounts, 1) + account, ok := accounts[0].(map[string]any) + require.True(t, ok) require.NotContains(t, account["extra"], "openai_excel_bps_proxy_ids") require.Equal(t, []any{buildBPSProxyKey("http", "192.0.2.11", 8080, "", ""), buildBPSProxyKey("http", "192.0.2.22", 8080, "", "")}, account["bps_proxy_keys"]) // The same exits have different IDs in the destination database. diff --git a/backend/internal/mihomo/bps_request_test.go b/backend/internal/mihomo/bps_request_test.go index f010cc2d5437..28eef6649d07 100644 --- a/backend/internal/mihomo/bps_request_test.go +++ b/backend/internal/mihomo/bps_request_test.go @@ -2,6 +2,7 @@ package mihomo import ( "context" + "errors" "fmt" "io" "net/http" @@ -56,8 +57,8 @@ func TestBPSRequestPoolDistributesConcurrentRequestsThroughSelectedProxies(t *te errs <- err return } - defer resp.Body.Close() - _, err = io.ReadAll(resp.Body) + _, readErr := io.ReadAll(resp.Body) + err = errors.Join(readErr, resp.Body.Close()) if err != nil { errs <- err } @@ -66,12 +67,12 @@ func TestBPSRequestPoolDistributesConcurrentRequestsThroughSelectedProxies(t *te wg.Wait() close(errs) close(leases) + for lease := range leases { + lease.Release() + } for err := range errs { require.NoError(t, err) } - for lease := range leases { - defer lease.Release() - } mu.Lock() defer mu.Unlock() require.Equal(t, map[int]int{1: 2, 2: 2, 3: 2}, hits, fmt.Sprint(hits)) diff --git a/backend/internal/service/openai_maintenance_remaining_proxy_test.go b/backend/internal/service/openai_maintenance_remaining_proxy_test.go index 0be598f085a5..ba73721efd4c 100644 --- a/backend/internal/service/openai_maintenance_remaining_proxy_test.go +++ b/backend/internal/service/openai_maintenance_remaining_proxy_test.go @@ -115,7 +115,8 @@ func TestRemainingMaintenanceConnectionRequestModeRejectsBeforeSideEffects(t *te base, _, _, _, oldClient, _ := newReauthTestService("acct-1") defer base.oauth.Stop() svc.oauth = base.oauth - reader := svc.accounts.(*reauthTestAccountReader) + reader, ok := svc.accounts.(*reauthTestAccountReader) + require.True(t, ok) remainingMaintenanceSelection(reader, svc) client := &remainingMaintenanceClient{reauthTestOAuthClient: oldClient} svc.oauth.oauthClient = client diff --git a/backend/internal/service/openai_maintenance_task_request_proxy_test.go b/backend/internal/service/openai_maintenance_task_request_proxy_test.go index b6c6f4f14946..63501f46fa46 100644 --- a/backend/internal/service/openai_maintenance_task_request_proxy_test.go +++ b/backend/internal/service/openai_maintenance_task_request_proxy_test.go @@ -51,7 +51,8 @@ func newMaintenanceTaskProxyService(t *testing.T) (*OpenAIOAuthReauthService, *r t.Helper() svc, base := newRotationService(t) t.Cleanup(svc.oauth.Stop) - reader := svc.accounts.(*reauthTestAccountReader) + reader, ok := svc.accounts.(*reauthTestAccountReader) + require.True(t, ok) legacyID := int64(90) reader.account.ProxyID = &legacyID reader.account.Extra = map[string]any{ @@ -98,14 +99,15 @@ func TestOpenAIMaintenanceTaskRequestProxyRejectsUnavailableOrOutsideSources(t * for _, condition := range []string{"unavailable", "unavailable-direct", "fixed_connection", "managed_proxy", "mihomo"} { t.Run(operation+"/"+condition, func(t *testing.T) { svc, reader, rotation, session, proxies := newMaintenanceTaskProxyService(t) - if condition == "unavailable" || condition == "unavailable-direct" { + switch condition { + case "unavailable", "unavailable-direct": proxies.proxies = nil if condition == "unavailable-direct" { reader.account.ProxyID = nil } - } else if condition == "fixed_connection" { + case "fixed_connection": reader.account.AuthConnectionID = "outside-fixed-connection" - } else { + default: rotation.config.ProxySource = condition if condition == "managed_proxy" { id := int64(90) diff --git a/backend/internal/service/openai_oauth_reauth_request_proxy_test.go b/backend/internal/service/openai_oauth_reauth_request_proxy_test.go index 281a70a036d7..6db4076eaa5d 100644 --- a/backend/internal/service/openai_oauth_reauth_request_proxy_test.go +++ b/backend/internal/service/openai_oauth_reauth_request_proxy_test.go @@ -6,9 +6,7 @@ import ( "testing" "github.com/Wei-Shaw/sub2api/internal/pkg/openai" - "github.com/Wei-Shaw/sub2api/internal/pkg/redissession" - "github.com/alicebob/miniredis/v2" - "github.com/redis/go-redis/v9" + redissessiontest "github.com/Wei-Shaw/sub2api/internal/testutil/redissession" "github.com/stretchr/testify/require" ) @@ -133,14 +131,12 @@ func TestOpenAIOAuthReauthRequestProxyCallbackUsesSharedSIWCSession(t *testing.T name = "removed" } t.Run(name, func(t *testing.T) { - mr := miniredis.RunT(t) - rdb := redis.NewClient(&redis.Options{Addr: mr.Addr()}) - t.Cleanup(func() { _ = rdb.Close() }) + sessionStore := redissessiontest.New(t, siwcSessionPrefix, openai.SessionTTL) svc, reader, repo, _, oldClient, _ := newReauthTestService("acct-1") t.Cleanup(svc.oauth.Stop) store := &siwcTestRepo{reauthTestRepo: repo} svc.repo = store - svc.siwcSessionStore = redissession.New(rdb, siwcSessionPrefix, openai.SessionTTL) + svc.siwcSessionStore = sessionStore client := &siwcTestClient{reauthTestOAuthClient: oldClient} svc.oauth.oauthClient = client reader.account.Extra = map[string]any{"openai_proxy_mode": "request", "openai_proxy_ids": []any{float64(2)}} diff --git a/backend/internal/service/openai_request_proxy_test.go b/backend/internal/service/openai_request_proxy_test.go index caae0a11a71e..37b9f6929f89 100644 --- a/backend/internal/service/openai_request_proxy_test.go +++ b/backend/internal/service/openai_request_proxy_test.go @@ -80,7 +80,7 @@ func TestOpenAIRequestProxyWebSocketExplicitlyRejectsBeforeUpstream(t *testing.T serverErr <- err return } - defer conn.CloseNow() + defer func() { _ = conn.CloseNow() }() c, _ := gin.CreateTestContext(httptest.NewRecorder()) c.Request = r serverErr <- svc.ProxyResponsesWebSocketFromClient(r.Context(), c, conn, account, "test-token", []byte(`{"type":"response.create","model":"gpt-5.4","input":"test"}`), nil) @@ -90,7 +90,7 @@ func TestOpenAIRequestProxyWebSocketExplicitlyRejectsBeforeUpstream(t *testing.T defer cancel() client, _, err := coderws.Dial(ctx, "ws"+strings.TrimPrefix(server.URL, "http"), nil) require.NoError(t, err) - defer client.CloseNow() + defer func() { _ = client.CloseNow() }() select { case err := <-serverErr: var closeErr *OpenAIWSClientCloseError diff --git a/backend/internal/testutil/redissession/store.go b/backend/internal/testutil/redissession/store.go new file mode 100644 index 000000000000..00fb1b82ac58 --- /dev/null +++ b/backend/internal/testutil/redissession/store.go @@ -0,0 +1,21 @@ +// Package redissession provides isolated Redis-backed session stores for tests. +package redissession + +import ( + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/pkg/redissession" + "github.com/alicebob/miniredis/v2" + "github.com/redis/go-redis/v9" +) + +// New keeps Redis client setup outside service packages while exercising the +// production session store against an isolated server with the requested TTL. +func New(t *testing.T, prefix string, ttl time.Duration) *redissession.Store { + t.Helper() + server := miniredis.RunT(t) + client := redis.NewClient(&redis.Options{Addr: server.Addr()}) + t.Cleanup(func() { _ = client.Close() }) + return redissession.New(client, prefix, ttl) +} From 1ee33f898d59700e1252a9bd9c4f4cff78015895 Mon Sep 17 00:00:00 2001 From: luotao21 Date: Tue, 17 Nov 2026 02:20:12 +0800 Subject: [PATCH 09/14] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E5=8E=86=E5=8F=B2?= =?UTF-8?q?=E5=9B=9E=E6=94=BE=E8=84=9A=E6=9C=AC=E9=87=8D=E5=A4=8D=E5=A4=84?= =?UTF-8?q?=E7=90=86=E6=B5=8B=E8=AF=95=E5=A4=B9=E5=85=B7=E5=AF=BC=E8=87=B4?= =?UTF-8?q?=E5=A4=B1=E8=B4=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/scripts/test_assert_ws_readable.py | 105 ++++++++++++++++++ .../workflows/ws-readable-continuation.yml | 12 +- 2 files changed, 111 insertions(+), 6 deletions(-) diff --git a/.github/scripts/test_assert_ws_readable.py b/.github/scripts/test_assert_ws_readable.py index cd3ab772cf96..14e11228c80b 100644 --- a/.github/scripts/test_assert_ws_readable.py +++ b/.github/scripts/test_assert_ws_readable.py @@ -2,6 +2,11 @@ import importlib.util import json +import os +import re +import subprocess +import tempfile +import textwrap import unittest from pathlib import Path @@ -32,6 +37,106 @@ def raw(events): return "".join(json.dumps(event) + "\n" for event in events) +class ResidualFixtureOwnershipTest(unittest.TestCase): + repository = Path(__file__).resolve().parents[2] + + def residual_step(self): + workflow = (self.repository / ".github/workflows/ws-readable-continuation.yml").read_text() + return workflow.split(" - name: Residual headers tools and ticket actual transport counterexamples\n", 1)[1].split(" - name:", 1)[0] + + def inline_loop(self): + match = re.search(r"(?ms)^ for target in (backend/.*?); do\n.*?^ done$", self.residual_step()) + self.assertIsNotNone(match) + return textwrap.dedent(match.group()), match.group(1).split() + + def test_residual_fixtures_have_one_owner_in_shared_helper_chain(self): + _, inline = self.inline_loop() + self.assertEqual(len(inline), len(set(inline))) + pending = re.findall(r"\.github/scripts/([\w.-]+\.sh)", self.residual_step()) + visited, shared = set(), set() + while pending: + name = pending.pop() + if name in visited: + continue + visited.add(name) + source = (self.repository / ".github/scripts" / name).read_text() + pending.extend(re.findall(r"\$script_dir/([\w.-]+\.sh)", source)) + for pattern in re.findall(r"backend/[\w./*?-]+_test\.go", source): + shared.add(pattern) + shared.update(str(path.relative_to(self.repository)) for path in self.repository.glob(pattern)) + self.assertGreaterEqual(len(visited), 7) + self.assertFalse(set(inline) & shared, "a strict candidate-blob check cannot follow another owner's overlay") + self.assertIn("backend/internal/service/openai_excel_bps_search_business_test.go", inline) + self.assertIn("backend/internal/service/openai_excel_bps_search_test.go", shared) + for selected in ("backend/internal/handler/openai_409_ws_rebuild_test.go", "backend/internal/service/openai_409_ws_ticket_test.go"): + self.assertNotIn(selected, inline) + + def test_actual_shell_handoff_preserves_guards_and_rejects_duplicate_owner(self): + loop, inline = self.inline_loop() + replay = (self.repository / ".github/scripts/prepare-replay-red-fixtures.sh").read_text() + exclude = re.search(r"(?ms)^exclude_absent_fixture\(\) \{\n.*?^\}", replay).group() + group = exclude + "\ncontract=backend/internal/service/group.go\n" + replay.split("contract=backend/internal/service/group.go\n", 1)[1].split("\n# Older Account/search", 1)[0] + shared = re.search(r"for target in (.*?); do", group).group(1).split() + self.assertEqual(len(shared), 4) + duplicate = "backend/internal/service/admin_group_duplicate_test.go" + business = "backend/internal/service/openai_excel_bps_search_business_test.go" + absent = {business, "backend/internal/service/free_ultrafast_customer_cost_test.go"} + selected = {"backend/internal/handler/openai_409_ws_rebuild_test.go", "backend/internal/service/openai_409_ws_ticket_test.go"} + for scenario in ("valid", "duplicate", "dirty"): + with self.subTest(scenario=scenario), tempfile.TemporaryDirectory() as directory: + tree = Path(directory) + env = {key: value for key, value in os.environ.items() if not key.startswith("GIT_")} + env.update(GIT_CONFIG_NOSYSTEM="1", GIT_CONFIG_GLOBAL=os.devnull) + + def git(*args): + return subprocess.run(["git", "-c", "user.name=CI fixture", "-c", "user.email=fixture@example.invalid", "-c", "commit.gpgsign=false", "-c", "core.hooksPath=" + os.devnull, "-c", "init.templateDir=", *args], cwd=tree, env=env, check=True, capture_output=True, text=True, timeout=15).stdout.strip() + + def write(path, content): + target = tree / path + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text(content) + + git("init", "-q") + contract = "backend/internal/service/group.go" + write(contract, "package service\n") + for path in set(inline + shared) | selected: + if path not in absent: + write(path, "baseline\n") + git("add", ".") + git("commit", "-qm", "baseline") + baseline = git("rev-parse", "HEAD") + for path in set(inline + shared) | selected: + write(path, "candidate\n") + git("add", ".") + git("commit", "-qm", "candidate") + candidate = git("rev-parse", "HEAD") + evidence = tree / "evidence/ws-evidence" + evidence.mkdir(parents=True) + env.update(baseline=baseline, candidate=candidate, tree=str(tree), BASELINE_SHA=baseline, CANDIDATE_SHA=candidate, RUNNER_TEMP=str(evidence.parent), tested_tree=str(tree)) + if scenario == "dirty": + write(duplicate, "unexpected fixture mutation\n") + prepared = subprocess.run(["bash", "-c", "set -euo pipefail\n" + group], cwd=tree, env=env, capture_output=True, text=True, timeout=15) + if scenario == "dirty": + self.assertNotEqual(prepared.returncode, 0, "candidate-blob checks must remain strict") + continue + self.assertEqual(prepared.returncode, 0, prepared.stderr) + script = loop if scenario == "valid" else loop.replace("; do", " " + duplicate + "; do", 1) + result = subprocess.run(["bash", "-c", "set -euo pipefail\n" + script], cwd=tree, env=env, capture_output=True, text=True, timeout=15) + if scenario == "duplicate": + self.assertNotEqual(result.returncode, 0, "the former double-owner sequence must reproduce its failure") + continue + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(len((evidence / "residual-service-fixtures.txt").read_text().splitlines()), len(inline)) + for path in set(inline + shared): + if path in absent: + self.assertFalse((tree / path).exists()) + else: + self.assertEqual((tree / path).read_text(), "baseline\n") + for path in selected: + self.assertEqual((tree / path).read_text(), "candidate\n") + self.assertEqual((tree / contract).read_text(), "package service\n") + + class WSReadableEvidenceTest(unittest.TestCase): def test_recovered_audit_red_requires_actual_restored_B_completion(self): suite = "ws-recovered-audit" diff --git a/.github/workflows/ws-readable-continuation.yml b/.github/workflows/ws-readable-continuation.yml index 3beabf291eb3..892967982531 100644 --- a/.github/workflows/ws-readable-continuation.yml +++ b/.github/workflows/ws-readable-continuation.yml @@ -218,12 +218,12 @@ jobs: # PR855 route-evidence types and later production BPS search APIs # are absent in this baseline. Their unselected tests follow the # pinned historical APIs too; the selected ticket oracle stays current. - # Later UltraFast fields and the search-business helper dependency - # are absent too. Restore only these unrelated fixtures; never the - # selected ticket oracle or any candidate GREEN fixture. - # BPS search is already excluded with blob/contract proofs by the - # shared helpers above, so do not inspect/remove it a second time. - for target in backend/internal/service/temp_unsched_pending_test.go backend/internal/service/temp_unsched_stream_timing_test.go backend/internal/service/temp_unsched_ws_forward_test.go backend/internal/service/openai_auth_connection_status_test.go backend/internal/service/openai_auth_connections_account_type_test.go backend/internal/service/account_ops_balance_test.go backend/internal/service/openai_excel_bps_bridge_failure_test.go backend/internal/service/quality_5xx_immediate_test.go backend/internal/service/openai_ws_agent_recovery_test.go backend/internal/service/admin_group_duplicate_test.go backend/internal/service/admin_service_group_test.go backend/internal/service/api_key_auth_cache_openai_fast_test.go backend/internal/service/free_ultrafast_customer_cost_test.go backend/internal/service/openai_excel_bps_search_business_test.go; do + # The replay helper already owns the four UltraFast group fixtures + # and the base BPS search fixtures. Do not apply them twice here. + # The separate search-business fixture still depends on the removed + # search helper, so this loop alone owns its historical adaptation. + # Never change the selected ticket oracle or candidate GREEN tests. + for target in backend/internal/service/temp_unsched_pending_test.go backend/internal/service/temp_unsched_stream_timing_test.go backend/internal/service/temp_unsched_ws_forward_test.go backend/internal/service/openai_auth_connection_status_test.go backend/internal/service/openai_auth_connections_account_type_test.go backend/internal/service/account_ops_balance_test.go backend/internal/service/openai_excel_bps_bridge_failure_test.go backend/internal/service/quality_5xx_immediate_test.go backend/internal/service/openai_ws_agent_recovery_test.go backend/internal/service/openai_excel_bps_search_business_test.go; do candidate_blob=$(git rev-parse "$CANDIDATE_SHA:$target") test "$(git hash-object "$tested_tree/$target")" = "$candidate_blob" if git cat-file -e "$baseline:$target" 2>/dev/null; then From b9fd2eb94fad740ca0f44e05e75ec2850b94003c Mon Sep 17 00:00:00 2001 From: luotao21 Date: Tue, 17 Nov 2026 02:48:21 +0800 Subject: [PATCH 10/14] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E5=8E=86=E5=8F=B2?= =?UTF-8?q?=E5=9B=9E=E6=94=BE=E9=81=97=E6=BC=8F=E6=B5=8B=E8=AF=95=E8=BE=85?= =?UTF-8?q?=E5=8A=A9=E4=BB=A3=E7=A0=81=E7=9A=84=E7=BC=96=E8=AF=91=E4=BE=9D?= =?UTF-8?q?=E8=B5=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/scripts/test_assert_ws_readable.py | 91 +++++++++++++++++++ .../workflows/ws-readable-continuation.yml | 26 ++++++ 2 files changed, 117 insertions(+) diff --git a/.github/scripts/test_assert_ws_readable.py b/.github/scripts/test_assert_ws_readable.py index 14e11228c80b..b8e9d908127c 100644 --- a/.github/scripts/test_assert_ws_readable.py +++ b/.github/scripts/test_assert_ws_readable.py @@ -49,6 +49,97 @@ def inline_loop(self): self.assertIsNotNone(match) return textwrap.dedent(match.group()), match.group(1).split() + def test_actual_residual_rollback_and_exact_test_support_overlay(self): + step = self.residual_step() + rollback = re.search(r"(?ms)^ while IFS= read -r target; do\n.*?^ git -C .*?diff --exit-code .*?':!backend/\*\*/\*_test.go'$", step) + self.assertIsNotNone(rollback) + overlay = re.search(r"(?ms)^ # BEGIN residual Redis test-support overlay\n.*?^ # END residual Redis test-support overlay$", step) + self.assertIsNotNone(overlay) + self.assertLess(rollback.end(), overlay.start()) + self.assertEqual(step[:overlay.start()].count("':!backend/**/*_test.go'"), 1) + rollback = textwrap.dedent(rollback.group()) + overlay = textwrap.dedent(overlay.group()) + helper = "backend/internal/testutil/redissession/store.go" + production = "backend/internal/service/production.go" + unrelated = "backend/internal/service/new_production.go" + oauth = "backend/internal/service/openai_oauth_reauth_request_proxy_test.go" + selected = {"backend/internal/handler/openai_409_ws_rebuild_test.go", "backend/internal/service/openai_409_ws_ticket_test.go"} + fixture_sources = {path: "candidate selected test\n" for path in selected} + fixture_sources[oauth] = 'package service\nimport _ "github.com/Wei-Shaw/sub2api/internal/testutil/redissession"\n' + for scenario in ("valid", "dirty-source", "other-path", "other-production", "source-symlink", "unexpected-target"): + with self.subTest(scenario=scenario), tempfile.TemporaryDirectory() as directory: + source, red = Path(directory) / "candidate", Path(directory) / "red" + source.mkdir() + env = {key: value for key, value in os.environ.items() if not key.startswith("GIT_")} + env.update(GIT_CONFIG_NOSYSTEM="1", GIT_CONFIG_GLOBAL=os.devnull) + + def git(*args, cwd=source): + return subprocess.run(["git", "-c", "user.name=CI fixture", "-c", "user.email=fixture@example.invalid", "-c", "commit.gpgsign=false", "-c", "core.hooksPath=" + os.devnull, "-c", "init.templateDir=", *args], cwd=cwd, env=env, check=True, capture_output=True, text=True, timeout=15).stdout.strip() + + def write(root, path, content): + target = root / path + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text(content) + + def run(shell): + return subprocess.run(["bash", "-c", "set -euo pipefail\n" + shell], cwd=source, env=env, capture_output=True, text=True, timeout=15) + + git("init", "-q") + write(source, production, "package service // baseline\n") + for path in selected: + write(source, path, "baseline selected test\n") + git("add", ".") + git("commit", "-qm", "baseline") + baseline = git("rev-parse", "HEAD") + write(source, production, "package service // candidate\n") + write(source, unrelated, "package service // candidate-only production\n") + write(source, helper, "package redissession // candidate test support\n") + for path, content in fixture_sources.items(): + write(source, path, content) + git("add", ".") + git("commit", "-qm", "candidate") + candidate = git("rev-parse", "HEAD") + helper_blob = git("rev-parse", f"{candidate}:{helper}") + git("worktree", "add", "--detach", str(red), candidate) + evidence_dir = Path(directory) / "evidence/ws-evidence" + evidence_dir.mkdir(parents=True) + env.update(baseline=baseline, CANDIDATE_SHA=candidate, tested_tree=str(red), GITHUB_WORKSPACE=str(source), RUNNER_TEMP=str(evidence_dir.parent)) + + result = run(rollback) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertFalse((red / helper).exists(), "the actual old rollback must delete the new non-test helper") + self.assertFalse((red / unrelated).exists()) + self.assertIn("internal/testutil/redissession", (red / oauth).read_text(), "the importing candidate test survives the actual old rollback") + self.assertEqual((red / production).read_text(), "package service // baseline\n") + self.assertEqual(git("diff", "--name-only", baseline, "--", "backend/**/*.go", ":!backend/**/*_test.go", cwd=red), "") + script = overlay + if scenario == "dirty-source": + write(source, helper, "unexpected candidate helper mutation\n") + elif scenario == "other-path": + script = script.replace("helper=" + helper, "helper=" + unrelated, 1) + elif scenario == "other-production": + write(red, production, "unexpected production mutation\n") + elif scenario == "source-symlink": + (source / helper).unlink() + (source / helper).symlink_to(source / production) + elif scenario == "unexpected-target": + write(red, helper, "unexpected restored helper\n") + result = run(script) + manifest = evidence_dir / "residual-test-support.txt" + if scenario != "valid": + self.assertNotEqual(result.returncode, 0, "untrusted helper state or another production path must be rejected") + self.assertFalse(manifest.exists(), "rejected preparation must not produce a success manifest") + continue + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(git("hash-object", str(red / helper)), helper_blob) + self.assertEqual(git("diff", "--name-only", baseline, "--", "backend/**/*.go", ":!backend/**/*_test.go", cwd=red), helper) + self.assertEqual((red / production).read_text(), "package service // baseline\n") + self.assertFalse((red / unrelated).exists()) + for path, content in fixture_sources.items(): + self.assertEqual((red / path).read_text(), content) + fields = dict(field.split("=", 1) for field in manifest.read_text().split()) + self.assertEqual(fields, {"path": helper, "baseline": baseline, "baseline_blob": "absent", "candidate": candidate, "candidate_blob": helper_blob, "source_blob": helper_blob, "restored_blob": helper_blob}) + def test_residual_fixtures_have_one_owner_in_shared_helper_chain(self): _, inline = self.inline_loop() self.assertEqual(len(inline), len(set(inline))) diff --git a/.github/workflows/ws-readable-continuation.yml b/.github/workflows/ws-readable-continuation.yml index 892967982531..f13782444cb9 100644 --- a/.github/workflows/ws-readable-continuation.yml +++ b/.github/workflows/ws-readable-continuation.yml @@ -205,6 +205,32 @@ jobs: fi done < <(git diff --no-renames --name-only "$baseline" "$CANDIDATE_SHA" -- 'backend/**/*.go') git -C "$tested_tree" diff --exit-code "$baseline" -- 'backend/**/*.go' ':!backend/**/*_test.go' + # BEGIN residual Redis test-support overlay + # The complete production baseline is proved above. Restore only + # this candidate test dependency, with an explicit blob manifest. + helper=backend/internal/testutil/redissession/store.go + test "$helper" = backend/internal/testutil/redissession/store.go + if git cat-file -e "$baseline:$helper" 2>/dev/null; then exit 1; fi + candidate_blob=$(git rev-parse "$CANDIDATE_SHA:$helper") + test "$(git cat-file -t "$candidate_blob")" = blob + for support_dir in backend backend/internal backend/internal/testutil backend/internal/testutil/redissession; do + test ! -L "$GITHUB_WORKSPACE/$support_dir" + test ! -L "$tested_tree/$support_dir" + done + test -f "$GITHUB_WORKSPACE/$helper" + test ! -L "$GITHUB_WORKSPACE/$helper" + source_blob=$(git hash-object "$GITHUB_WORKSPACE/$helper") + test "$source_blob" = "$candidate_blob" + test ! -e "$tested_tree/$helper" + test ! -L "$tested_tree/$helper" + mkdir -p -- "$(dirname -- "$tested_tree/$helper")" + git show "$CANDIDATE_SHA:$helper" > "$tested_tree/$helper" + restored_blob=$(git hash-object "$tested_tree/$helper") + test "$restored_blob" = "$candidate_blob" + git -C "$tested_tree" diff --exit-code "$baseline" -- 'backend/**/*.go' ':!backend/**/*_test.go' ":!$helper" + test "$(git -C "$tested_tree" diff --name-only "$baseline" -- 'backend/**/*.go' ':!backend/**/*_test.go')" = "$helper" + printf 'path=%s baseline=%s baseline_blob=absent candidate=%s candidate_blob=%s source_blob=%s restored_blob=%s\n' "$helper" "$baseline" "$CANDIDATE_SHA" "$candidate_blob" "$source_blob" "$restored_blob" > "$RUNNER_TEMP/ws-evidence/residual-test-support.txt" + # END residual Redis test-support overlay fi git -C "$tested_tree" diff --exit-code "$CANDIDATE_SHA" -- 'backend/**/*_test.go' if [ "$PHASE" = RED ]; then From 282af9711141995d05317b3f39656d96eb34ce7f Mon Sep 17 00:00:00 2001 From: luotao21 Date: Tue, 17 Nov 2026 04:13:33 +0800 Subject: [PATCH 11/14] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E8=B4=A6=E5=8F=B7?= =?UTF-8?q?=E5=88=87=E6=8D=A2=E5=8D=95=E4=BB=A3=E7=90=86=E6=97=B6=E5=88=B7?= =?UTF-8?q?=E6=96=B0=E7=BB=95=E8=BF=87=E8=AF=B7=E6=B1=82=E5=87=BA=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../internal/service/openai_excel_oauth.go | 3 +- .../service/openai_maintenance_proxy.go | 26 +- .../internal/service/openai_oauth_service.go | 3 +- backend/internal/service/openai_siwc.go | 3 +- .../internal/service/openai_token_provider.go | 7 + .../pr885_config_switch_refresh_test.go | 322 +++++++++++++++++ .../service/pr885_oauth_config_switch_test.go | 327 ++++++++++++++++++ .../service/pr885_siwc_config_switch_test.go | 297 ++++++++++++++++ 8 files changed, 980 insertions(+), 8 deletions(-) create mode 100644 backend/internal/service/pr885_config_switch_refresh_test.go create mode 100644 backend/internal/service/pr885_oauth_config_switch_test.go create mode 100644 backend/internal/service/pr885_siwc_config_switch_test.go diff --git a/backend/internal/service/openai_excel_oauth.go b/backend/internal/service/openai_excel_oauth.go index ce62b68479f1..a9f833cc4b04 100644 --- a/backend/internal/service/openai_excel_oauth.go +++ b/backend/internal/service/openai_excel_oauth.go @@ -253,7 +253,8 @@ func (s *OpenAIOAuthReauthService) ExcelAccessToken(ctx context.Context, account return "", errors.New("saved Excel identity does not match the account") } var proxyURL string - if fresh.OpenAIRequestProxyEnabled() { + _, hasRequestRoute := openAIRequestProxyFromContext(ctx, fresh.ID) + if fresh.OpenAIRequestProxyEnabled() || hasRequestRoute { proxyURL, err = resolveOpenAIMaintenanceProxy(ctx, fresh, s.oauth.proxyRepo) } else { proxyURL, err = s.reauthProxyURL(ctx, fresh.ProxyID) diff --git a/backend/internal/service/openai_maintenance_proxy.go b/backend/internal/service/openai_maintenance_proxy.go index d379f8a45f0c..b2745e4f50ac 100644 --- a/backend/internal/service/openai_maintenance_proxy.go +++ b/backend/internal/service/openai_maintenance_proxy.go @@ -13,19 +13,30 @@ import ( // Maintenance uses a saved member without changing the account's single proxy. // Inference owns its independent least-in-flight lease for the logical request. func resolveOpenAIMaintenanceProxy(ctx context.Context, account *Account, repo ProxyRepository, expectedURL ...string) (string, error) { - if account == nil || !account.OpenAIRequestProxyEnabled() { + if account == nil { return "", nil } - if account.AuthConnectionID != "" || account.HasManagedOpenAIConnections() { - return "", infraerrors.New(http.StatusServiceUnavailable, "OPENAI_PROXY_CONNECTION_CONFLICT", "Request proxies require an ordinary OAuth account without a fixed authorization connection") - } + route, hasRoute := openAIRequestProxyFromContext(ctx, account.ID) unavailable := func() (string, error) { return "", infraerrors.New(http.StatusServiceUnavailable, "OPENAI_PROXY_UNAVAILABLE", "No selected OpenAI proxy is available; direct fallback is disabled") } + if !account.OpenAIRequestProxyEnabled() { + // A saved mode change cannot replace an in-flight request's exit. + if hasRoute { + return unavailable() + } + return "", nil + } + if account.AuthConnectionID != "" || account.HasManagedOpenAIConnections() { + return "", infraerrors.New(http.StatusServiceUnavailable, "OPENAI_PROXY_CONNECTION_CONFLICT", "Request proxies require an ordinary OAuth account without a fixed authorization connection") + } if repo == nil { return unavailable() } - if route, ok := openAIRequestProxyFromContext(ctx, account.ID); ok { + if hasRoute { + if _, err := ValidateOpenAIRequestProxyEgress(ctx, account.ID, route.proxy); err != nil { + return "", err + } if len(expectedURL) > 0 && expectedURL[0] != route.proxy { return unavailable() } @@ -54,6 +65,11 @@ func resolveOpenAIMaintenanceProxy(ctx context.Context, account *Account, repo P } parsed, err := url.Parse(raw) if err == nil && parsed.Hostname() != "" { + if hasRoute { + if _, err := ValidateOpenAIRequestProxyEgress(ctx, account.ID, raw); err != nil { + return "", err + } + } return raw, nil } } diff --git a/backend/internal/service/openai_oauth_service.go b/backend/internal/service/openai_oauth_service.go index 69960f5480cf..d0039a1a3019 100644 --- a/backend/internal/service/openai_oauth_service.go +++ b/backend/internal/service/openai_oauth_service.go @@ -402,7 +402,8 @@ func (s *OpenAIOAuthService) RefreshAccountToken(ctx context.Context, account *A } var proxyURL string - if account.OpenAIRequestProxyEnabled() { + _, hasRequestRoute := openAIRequestProxyFromContext(ctx, account.ID) + if account.OpenAIRequestProxyEnabled() || hasRequestRoute { var err error proxyURL, err = resolveOpenAIMaintenanceProxy(ctx, account, s.proxyRepo) if err != nil { diff --git a/backend/internal/service/openai_siwc.go b/backend/internal/service/openai_siwc.go index 36ca7f9fd806..8b4f731c1220 100644 --- a/backend/internal/service/openai_siwc.go +++ b/backend/internal/service/openai_siwc.go @@ -365,7 +365,8 @@ func (s *OpenAIOAuthReauthService) SIWCAccessToken(ctx context.Context, account return "", errors.New("SIWC token client is unavailable") } var proxy string - if fresh.OpenAIRequestProxyEnabled() { + _, hasRequestRoute := openAIRequestProxyFromContext(refreshCtx, fresh.ID) + if fresh.OpenAIRequestProxyEnabled() || hasRequestRoute { proxy, err = resolveOpenAIMaintenanceProxy(refreshCtx, fresh, s.oauth.proxyRepo) } else { proxy, err = s.reauthProxyURL(refreshCtx, fresh.ProxyID) diff --git a/backend/internal/service/openai_token_provider.go b/backend/internal/service/openai_token_provider.go index b10f52f65ef1..ebd839c5004d 100644 --- a/backend/internal/service/openai_token_provider.go +++ b/backend/internal/service/openai_token_provider.go @@ -8,6 +8,8 @@ import ( "strings" "sync/atomic" "time" + + infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" ) const ( @@ -175,6 +177,11 @@ func (p *OpenAITokenProvider) GetAccessToken(ctx context.Context, account *Accou result, err := p.refreshAPI.RefreshIfNeeded(ctx, account, p.executor, openAITokenRefreshSkew) if err != nil { + _, hasRequestRoute := openAIRequestProxyFromContext(ctx, account.ID) + if hasRequestRoute && (errors.Is(err, errOpenAIRequestProxyUnavailable) || infraerrors.Reason(err) == "OPENAI_PROXY_UNAVAILABLE") { + // A rejected request route must not fall back to the old token. + return "", err + } if p.refreshPolicy.OnRefreshError == ProviderRefreshErrorReturn { return "", err } diff --git a/backend/internal/service/pr885_config_switch_refresh_test.go b/backend/internal/service/pr885_config_switch_refresh_test.go new file mode 100644 index 000000000000..b566feed87ec --- /dev/null +++ b/backend/internal/service/pr885_config_switch_refresh_test.go @@ -0,0 +1,322 @@ +//go:build unit && bps_request_integration + +package service + +import ( + "context" + "fmt" + "io" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "sync" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/mihomo" + infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" + "github.com/Wei-Shaw/sub2api/internal/pkg/openai" + "github.com/stretchr/testify/require" +) + +// The barrier is at the account repository boundary: Forward has already +// acquired its request route, while the grant reader has not read fresh state. +// Admin updates use GetByID and are therefore not blocked by this barrier. +type pr885ConfigSwitchAccounts struct { + AccountRepository + mu sync.Mutex + account *Account + proxies ProxyRepository + ready chan context.Context + resume chan struct{} + once sync.Once +} + +func pr885ConfigSwitchClone(a *Account) *Account { + copy := *a + copy.Extra = cloneReauthMap(a.Extra) + copy.Credentials = cloneReauthMap(a.Credentials) + return © +} + +func (r *pr885ConfigSwitchAccounts) GetByID(_ context.Context, id int64) (*Account, error) { + r.mu.Lock() + defer r.mu.Unlock() + if r.account == nil || r.account.ID != id { + return nil, ErrAccountNotFound + } + return pr885ConfigSwitchClone(r.account), nil +} +func (r *pr885ConfigSwitchAccounts) Update(_ context.Context, a *Account) error { + r.mu.Lock() + defer r.mu.Unlock() + r.account = pr885ConfigSwitchClone(a) + return nil +} +func (r *pr885ConfigSwitchAccounts) ListShadowsByParent(context.Context, int64) ([]*Account, error) { + return nil, nil +} +func (r *pr885ConfigSwitchAccounts) GetAccount(ctx context.Context, id int64) (*Account, error) { + if _, ok := openAIRequestProxyFromContext(ctx, id); ok { + r.once.Do(func() { + r.ready <- ctx + select { + case <-r.resume: + case <-ctx.Done(): + } + }) + } + if err := ctx.Err(); err != nil { + return nil, err + } + return r.GetByID(ctx, id) +} +func (r *pr885ConfigSwitchAccounts) GetProxy(ctx context.Context, id int64) (*Proxy, error) { + return r.proxies.GetByID(ctx, id) +} + +// Exercise a real HTTP refresh send at the external transport boundary. Even +// direct sends are redirected to a local server, so a forbidden empty proxy is +// observed without ever contacting or resolving an external OAuth endpoint. +type pr885ConfigSwitchOAuth struct { + *excelRefreshTestClient + directURL string +} + +func (c *pr885ConfigSwitchOAuth) RefreshTokenWithClientID(ctx context.Context, rt, proxy, clientID string) (*openai.TokenResponse, error) { + tr := &http.Transport{} + defer tr.CloseIdleConnections() + endpoint := c.directURL + "/oauth/token" + if proxy != "" { + u, err := url.Parse(proxy) + if err != nil { + return nil, err + } + tr.Proxy = http.ProxyURL(u) + endpoint = "http://auth.openai.test/oauth/token" + } + req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, strings.NewReader("grant_type=refresh_token")) + if err != nil { + return nil, err + } + resp, err := (&http.Client{Transport: tr, Timeout: 3 * time.Second}).Do(req) + if err != nil { + return nil, err + } + _, _ = io.Copy(io.Discard, resp.Body) + _ = resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return nil, fmt.Errorf("controlled refresh status %d", resp.StatusCode) + } + return c.excelRefreshTestClient.RefreshTokenWithClientID(ctx, rt, proxy, clientID) +} + +// A held B and an explicitly reset A cursor make this behavioral pool check +// distinguish released A (load zero) from a leaked A (ties B and rotates to B). +func pr885ConfigSwitchRequireLeaseReturned(t *testing.T, accountID int64) { + t.Helper() + b, err := mihomo.AcquireBPSStaticRequestLease(t.Context(), accountID, []int64{2}) + require.NoError(t, err) + defer b.Release() + a, err := mihomo.AcquireBPSStaticRequestLease(t.Context(), accountID, []int64{1}) + require.NoError(t, err) + a.Release() + next, err := mihomo.AcquireBPSStaticRequestLease(t.Context(), accountID, []int64{1, 2}) + require.NoError(t, err) + defer next.Release() + require.Equal(t, int64(1), next.ProxyID, "completed/error/canceled request must return its A lease") +} + +func pr885RunConfigSwitchRefresh(t *testing.T, images bool, singleProxy int64, control string) { + t.Helper() + var mu sync.Mutex + var observed []requestProxyObservation + handler := func(id int, w http.ResponseWriter, r *http.Request) { + _, _ = io.Copy(io.Discard, r.Body) + mu.Lock() + observed = append(observed, requestProxyObservation{id: id, path: r.URL.Path}) + mu.Unlock() + if r.URL.Path == "/oauth/token" { + if control == "refresh_error" { + w.WriteHeader(http.StatusServiceUnavailable) + return + } + _, _ = io.WriteString(w, "{}") + return + } + if images { + resp := openAIImagesJSONResponse() + defer resp.Body.Close() + for k, v := range resp.Header { + w.Header()[k] = v + } + _, _ = io.Copy(w, resp.Body) + return + } + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, bpsRequestCompletedWire) + } + gateway, account := localBPSRequestProxyFixture(t, 2, handler) + direct := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { handler(0, w, r) })) + t.Cleanup(direct.Close) + reauth, reader, repo, _, _ := newExcelReauthTestService(t) + account.ID = reader.account.ID + account.Credentials = reader.account.Credentials + account.Extra[OpenAIProxyModeKey] = OpenAIProxyModeRequest + account.Extra[OpenAIProxyIDsKey] = []int64{1} + // Include both exercised models: restricting this to the image model makes + // Forward deliberately select its ordinary Codex passthrough instead of BPS. + account.Extra["openai_excel_bps_models"] = []any{"gpt-image-2", "gpt-6-astra"} + mihomo.SetBPSStaticRequestGroups(map[int64][]int64{account.ID: {1, 2}}) + accounts := &pr885ConfigSwitchAccounts{account: pr885ConfigSwitchClone(account), proxies: gateway.proxyRepo, ready: make(chan context.Context, 1), resume: make(chan struct{})} + var resumeOnce sync.Once + resume := func() { resumeOnce.Do(func() { close(accounts.resume) }) } + t.Cleanup(resume) + reauth.accounts = accounts + reauth.oauth.proxyRepo = gateway.proxyRepo + gateway.excelOAuthReauth = reauth + storeExcelTestCredentials(t, reauth, repo, excelTestCredentials("stale", time.Now().Add(-time.Hour))) + reauth.oauth.oauthClient = &pr885ConfigSwitchOAuth{excelRefreshTestClient: &excelRefreshTestClient{credentials: excelTestCredentials("fresh", time.Now().Add(time.Hour))}, directURL: direct.URL} + ctx, cancel := context.WithTimeout(t.Context(), 8*time.Second) + defer cancel() + cancelRequest := cancel + if images && control == "cancel" { + // Images intentionally detaches ordinary client cancellation. Cancel the + // production upstream owner so this control stops the actual route scope. + ctx, cancelRequest = WithAPIKeyAdmissionOwner(ctx) + defer cancelRequest() + } + type requestResult struct { + status int + body string + err error + } + done := make(chan requestResult, 1) + go func() { + if !images { + status, body, err := forwardLocalBPSRequest(ctx, gateway, account, []byte(`{"model":"gpt-6-astra","input":"config switch","stream":true}`)) + done <- requestResult{status: status, body: body, err: err} + return + } + body := []byte(`{"model":"gpt-image-2","prompt":"config switch"}`) + c, _ := newOpenAIImagesTestContext(t, body) + parsed, err := gateway.ParseOpenAIImagesRequest(c, body) + if err == nil { + _, err = gateway.ForwardImages(ctx, c, account, body, parsed, "") + } + done <- requestResult{err: err} + }() + var barrierCtx context.Context + select { + case barrierCtx = <-accounts.ready: + case result := <-done: + t.Fatalf("request ended before account-reread barrier: %v", result.err) + case <-ctx.Done(): + t.Fatal("missing account-reread barrier") + } + route, ok := openAIRequestProxyFromContext(barrierCtx, account.ID) + require.True(t, ok) + aProxy, err := gateway.proxyRepo.GetByID(t.Context(), 1) + require.NoError(t, err) + require.Equal(t, aProxy.URL(), route.proxy) + require.Equal(t, account.ID, route.accountID) + require.NotNil(t, route.lease) + require.Equal(t, int64(1), route.lease.ProxyID) + t.Logf("CONFIG_SWITCH_ROUTE_READY account=%d proxy=A", account.ID) + if control == "" { + extra := cloneReauthMap(account.Extra) + extra[OpenAIProxyModeKey] = OpenAIProxyModeSingle + admin := &adminServiceImpl{accountRepo: accounts, proxyRepo: gateway.proxyRepo} + saved, err := admin.UpdateAccount(t.Context(), account.ID, &UpdateAccountInput{Extra: extra, ProxyID: &singleProxy}) + require.NoError(t, err) + require.False(t, saved.OpenAIRequestProxyEnabled()) + if singleProxy == 0 { + require.Nil(t, saved.ProxyID) + } else { + require.Equal(t, singleProxy, *saved.ProxyID) + } + t.Logf("CONFIG_SWITCH_SINGLE_SAVED account=%d proxy_id=%d", account.ID, singleProxy) + } else { + // Controls retain request A, so refresh_error must reach the actual HTTP + // token endpoint rather than pass because config-switch rejection won. + fresh, err := accounts.GetByID(t.Context(), account.ID) + require.NoError(t, err) + require.True(t, fresh.OpenAIRequestProxyEnabled()) + require.Equal(t, []int64{1}, fresh.OpenAIRequestProxyIDs()) + } + if control == "cancel" { + cancelRequest() + require.ErrorIs(t, ctx.Err(), context.Canceled) + require.ErrorIs(t, barrierCtx.Err(), context.Canceled) + } + resume() + var completed requestResult + select { + case completed = <-done: + case <-ctx.Done(): + if control != "cancel" { + t.Fatal("request did not finish after admin save") + } + select { + case completed = <-done: + case <-time.After(2 * time.Second): + t.Fatal("canceled request did not finish") + } + } + mu.Lock() + seen := append([]requestProxyObservation(nil), observed...) + mu.Unlock() + pr885ConfigSwitchRequireLeaseReturned(t, account.ID) + for _, send := range seen { + require.Equal(t, 1, send.id, "CONFIG_SWITCH_REFRESH_EGRESS_ESCAPED path=%s observed_proxy=%d; B/direct sends must be zero", send.path, send.id) + } + if control != "" { + require.Error(t, completed.err) + if control == "cancel" { + require.Empty(t, seen, "cancellation at the reread barrier must prevent all sends") + } else { + require.Len(t, seen, 1, "refresh error control must make exactly one actual A refresh send") + require.Equal(t, "/oauth/token", seen[0].path) + } + return + } + require.Error(t, completed.err, "fresh single configuration must explicitly reject the request route") + require.Empty(t, seen, "config-switch rejection must precede every refresh/inference send") + if images { + require.Equal(t, "OPENAI_PROXY_UNAVAILABLE", infraerrors.Reason(completed.err)) + require.Equal(t, http.StatusServiceUnavailable, infraerrors.Code(completed.err)) + } else { + // Forward intentionally translates credential failures into its public + // BPS error; that boundary does not preserve the underlying error. + var rejected *excelBPSForwardError + require.ErrorAs(t, completed.err, &rejected) + require.Equal(t, "basispoints_auth_unavailable", rejected.code) + require.Equal(t, http.StatusBadGateway, completed.status) + require.JSONEq(t, `{"error":{"type":"server_error","code":"basispoints_auth_unavailable","message":"Excel OAuth credential is unavailable; see Credential Operations"}}`, completed.body) + } +} + +func TestExcelBPSRequestProxyConfigSwitchForward(t *testing.T) { + for _, tc := range []struct { + name string + proxy int64 + }{{"single_B", 2}, {"single_empty", 0}} { + t.Run(tc.name, func(t *testing.T) { pr885RunConfigSwitchRefresh(t, false, tc.proxy, "") }) + } +} +func TestExcelBPSRequestProxyConfigSwitchImages(t *testing.T) { + for _, tc := range []struct { + name string + proxy int64 + }{{"single_B", 2}, {"single_empty", 0}} { + t.Run(tc.name, func(t *testing.T) { pr885RunConfigSwitchRefresh(t, true, tc.proxy, "") }) + } +} +func TestExcelBPSRequestProxyConfigSwitchControls(t *testing.T) { + for _, images := range []bool{false, true} { + for _, control := range []string{"refresh_error", "cancel"} { + t.Run(fmt.Sprintf("images_%t/%s", images, control), func(t *testing.T) { pr885RunConfigSwitchRefresh(t, images, 2, control) }) + } + } +} diff --git a/backend/internal/service/pr885_oauth_config_switch_test.go b/backend/internal/service/pr885_oauth_config_switch_test.go new file mode 100644 index 000000000000..36a93581a2c5 --- /dev/null +++ b/backend/internal/service/pr885_oauth_config_switch_test.go @@ -0,0 +1,327 @@ +//go:build unit && bps_request_integration + +package service + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "sync" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/mihomo" + infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" + "github.com/Wei-Shaw/sub2api/internal/pkg/openai" + "github.com/stretchr/testify/require" +) + +// This barrier belongs to the real OAuthRefreshAPI repository re-read. Admin +// UpdateAccount receives the original context, so it can save normally while +// the request-scoped GetByID waits with the already acquired inference lease. +type pr885OAuthConfigSwitchAccounts struct { + AccountRepository + mu sync.Mutex + account *Account + ready chan *openAIRequestProxyRoute + resume chan struct{} + once sync.Once +} + +func pr885OAuthConfigSwitchClone(account *Account) *Account { + copy := *account + copy.Extra = cloneReauthMap(account.Extra) + copy.Credentials = cloneReauthMap(account.Credentials) + if account.ProxyID != nil { + id := *account.ProxyID + copy.ProxyID = &id + } + return © +} + +func (r *pr885OAuthConfigSwitchAccounts) GetByID(ctx context.Context, id int64) (*Account, error) { + if route, ok := openAIRequestProxyFromContext(ctx, id); ok { + r.once.Do(func() { + r.ready <- route + select { + case <-r.resume: + case <-ctx.Done(): + } + }) + } + if err := ctx.Err(); err != nil { + return nil, err + } + r.mu.Lock() + defer r.mu.Unlock() + if r.account == nil || r.account.ID != id { + return nil, ErrAccountNotFound + } + return pr885OAuthConfigSwitchClone(r.account), nil +} + +func (r *pr885OAuthConfigSwitchAccounts) Update(_ context.Context, account *Account) error { + r.mu.Lock() + defer r.mu.Unlock() + r.account = pr885OAuthConfigSwitchClone(account) + return nil +} + +func (r *pr885OAuthConfigSwitchAccounts) ListShadowsByParent(context.Context, int64) ([]*Account, error) { + return nil, nil +} + +type pr885OAuthConfigSwitchTokenClient struct { + openaiOAuthClientRefreshStub + directURL string +} + +func (c *pr885OAuthConfigSwitchTokenClient) RefreshTokenWithClientID(ctx context.Context, refreshToken, proxy, clientID string) (*openai.TokenResponse, error) { + transport := &http.Transport{} + defer transport.CloseIdleConnections() + endpoint := c.directURL + "/oauth/token" + if proxy != "" { + u, err := url.Parse(proxy) + if err != nil || u.Host == "" { + return nil, fmt.Errorf("invalid fixture proxy") + } + transport.Proxy = http.ProxyURL(u) + endpoint = "http://auth.openai.test/oauth/token" + } + form := url.Values{"grant_type": {"refresh_token"}, "refresh_token": {refreshToken}, "client_id": {clientID}} + req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, strings.NewReader(form.Encode())) + if err != nil { + return nil, err + } + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + resp, err := (&http.Client{Transport: transport, Timeout: 5 * time.Second}).Do(req) + if err != nil { + return nil, err + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + _, _ = io.Copy(io.Discard, resp.Body) + return nil, fmt.Errorf("controlled ordinary OAuth token endpoint status %d", resp.StatusCode) + } + var token openai.TokenResponse + err = json.NewDecoder(resp.Body).Decode(&token) + return &token, err +} + +func pr885OAuthConfigSwitchAssertLeaseReturned(t *testing.T, accountID int64) { + t.Helper() + spare, err := mihomo.AcquireBPSStaticRequestLease(t.Context(), accountID, []int64{2}) + require.NoError(t, err) + defer spare.Release() + cursor, err := mihomo.AcquireBPSStaticRequestLease(t.Context(), accountID, []int64{1}) + require.NoError(t, err) + cursor.Release() + next, err := mihomo.AcquireBPSStaticRequestLease(t.Context(), accountID, []int64{1, 2}) + require.NoError(t, err) + defer next.Release() + require.Equal(t, int64(1), next.ProxyID, "ordinary OAuth refresh rejection must return request lease A") +} + +type pr885OAuthConfigSwitchFixture struct { + gateway *OpenAIGatewayService + account *Account + accounts *pr885OAuthConfigSwitchAccounts + provider *OpenAITokenProvider + hits func() []requestProxyObservation +} + +func newPR885OAuthConfigSwitchFixture(t *testing.T) pr885OAuthConfigSwitchFixture { + t.Helper() + var observedMu sync.Mutex + var observed []requestProxyObservation + handle := func(id int, w http.ResponseWriter, r *http.Request) { + raw, _ := io.ReadAll(r.Body) + observedMu.Lock() + observed = append(observed, requestProxyObservation{id: id, path: r.URL.Path, body: raw}) + observedMu.Unlock() + if r.URL.Path == "/oauth/token" { + // A real HTTP error also exercises the provider's production + // default fallback policy. The fixture must not set Return to + // conceal an inference send after a routing rejection. + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusBadGateway) + _, _ = io.WriteString(w, `{"error":"controlled ordinary OAuth refresh failure"}`) + return + } + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, bpsRequestCompletedWire) + } + direct := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { handle(0, w, r) })) + t.Cleanup(direct.Close) + gateway, account := localBPSRequestProxyFixture(t, 3, handle) + delete(account.Extra, "openai_excel_bps") + account.Extra[OpenAISIWCEnabledKey] = false + account.Extra[OpenAIProxyModeKey] = OpenAIProxyModeRequest + account.Extra[OpenAIProxyIDsKey] = []int64{1} + account.Credentials["refresh_token"] = "ordinary-oauth-refresh" + account.Credentials["expires_at"] = time.Now().Add(-time.Hour).Format(time.RFC3339) + account.Credentials["client_id"] = "ordinary-oauth-client" + proxyA, err := gateway.proxyRepo.GetByID(t.Context(), 1) + require.NoError(t, err) + account.ProxyID, account.Proxy = &proxyA.ID, proxyA + accounts := &pr885OAuthConfigSwitchAccounts{ + account: pr885OAuthConfigSwitchClone(account), + ready: make(chan *openAIRequestProxyRoute, 1), resume: make(chan struct{}), + } + oauth := NewOpenAIOAuthService(gateway.proxyRepo, &pr885OAuthConfigSwitchTokenClient{directURL: direct.URL}) + t.Cleanup(oauth.Stop) + provider := NewOpenAITokenProvider(accounts, nil, oauth) + provider.SetRefreshAPI(NewOAuthRefreshAPI(accounts, nil), NewOpenAITokenRefresher(oauth, accounts)) + gateway.openAITokenProvider = provider + gateway.accountRepo = accounts + require.Equal(t, ProviderRefreshErrorUseExistingToken, provider.refreshPolicy.OnRefreshError, "preserve the real default provider policy") + return pr885OAuthConfigSwitchFixture{ + gateway: gateway, account: account, accounts: accounts, provider: provider, + hits: func() []requestProxyObservation { + observedMu.Lock() + defer observedMu.Unlock() + return append([]requestProxyObservation(nil), observed...) + }, + } +} + +func TestExcelBPSRequestProxyConfigSwitchOAuth(t *testing.T) { + for _, tc := range []struct { + name string + proxy int64 + }{{"single_B", 3}, {"single_empty", 0}} { + t.Run(tc.name, func(t *testing.T) { + f := newPR885OAuthConfigSwitchFixture(t) + gateway, account, accounts, provider := f.gateway, f.account, f.accounts, f.provider + ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second) + defer cancel() + done := make(chan error, 1) + go func() { + _, _, err := forwardLocalBPSRequest(ctx, gateway, account, []byte(`{"model":"gpt-5.4","input":"test","stream":true}`)) + done <- err + }() + var route *openAIRequestProxyRoute + select { + case route = <-accounts.ready: + case <-ctx.Done(): + t.Fatal("ordinary OAuth Forward did not reach the real refresh API GetByID barrier") + } + require.Equal(t, int64(1), route.lease.ProxyID) + require.Equal(t, int64(1), provider.SnapshotRuntimeMetrics().RefreshRequests) + t.Log("CONFIG_SWITCH_ROUTE_READY OAuth proxy_id=1 OAuthRefreshAPI_GetByID=true") + admin := &adminServiceImpl{accountRepo: accounts, proxyRepo: gateway.proxyRepo} + extra := cloneReauthMap(account.Extra) + extra[OpenAIProxyModeKey] = OpenAIProxyModeSingle + saved, err := admin.UpdateAccount(ctx, account.ID, &UpdateAccountInput{Extra: extra, ProxyID: &tc.proxy}) + require.NoError(t, err) + require.Equal(t, OpenAIProxyModeSingle, saved.Extra[OpenAIProxyModeKey]) + if tc.proxy == 0 { + require.Nil(t, saved.ProxyID) + } else { + require.NotNil(t, saved.ProxyID) + require.Equal(t, tc.proxy, *saved.ProxyID) + } + t.Logf("CONFIG_SWITCH_SINGLE_SAVED OAuth proxy_id=%d", tc.proxy) + close(accounts.resume) + select { + case err = <-done: + case <-ctx.Done(): + t.Fatal("ordinary OAuth Forward did not finish after configuration switch") + } + pr885OAuthConfigSwitchAssertLeaseReturned(t, account.ID) + hits := f.hits() + escaped := 0 + for _, hit := range hits { + if hit.id != 1 { + escaped++ + } + t.Logf("ordinary OAuth config switch observed proxy_id=%d path=%s", hit.id, hit.path) + } + require.Zero(t, escaped, "CONFIG_SWITCH_REFRESH_EGRESS_ESCAPED: ordinary OAuth refresh/inference escaped request proxy A (B/direct sends must be zero)") + require.Error(t, err, "a fresh single configuration must reject the request before refresh and inference") + require.Equal(t, "OPENAI_PROXY_UNAVAILABLE", infraerrors.Reason(err)) + require.Equal(t, http.StatusServiceUnavailable, infraerrors.Code(err)) + require.Empty(t, hits, "request routing rejection must not fall back to old-token inference") + }) + } +} + +// Compatibility controls stay outside the strict config-switch RED root. An +// ordinary upstream refresh error must retain the default old-token fallback. +func TestExcelBPSRequestProxyConfigSwitchOAuthControls(t *testing.T) { + t.Run("request_refresh_error", func(t *testing.T) { + f := newPR885OAuthConfigSwitchFixture(t) + ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second) + defer cancel() + type result struct { + code int + body string + err error + } + done := make(chan result, 1) + go func() { + code, body, err := forwardLocalBPSRequest(ctx, f.gateway, f.account, []byte(`{"model":"gpt-5.4","input":"test","stream":true}`)) + done <- result{code: code, body: body, err: err} + }() + select { + case route := <-f.accounts.ready: + require.Equal(t, int64(1), route.lease.ProxyID) + case <-ctx.Done(): + t.Fatal("ordinary OAuth refresh control did not reach the real refresh API GetByID barrier") + } + close(f.accounts.resume) + var completed result + select { + case completed = <-done: + case <-ctx.Done(): + t.Fatal("ordinary OAuth refresh-error fallback did not finish") + } + require.NoError(t, completed.err) + require.Equal(t, http.StatusOK, completed.code) + require.Contains(t, completed.body, "response.completed") + require.Equal(t, int64(1), f.provider.SnapshotRuntimeMetrics().RefreshRequests) + pr885OAuthConfigSwitchAssertLeaseReturned(t, f.account.ID) + hits := f.hits() + require.Len(t, hits, 2, "refresh error must fall back to one inference using the old token") + require.Equal(t, "/oauth/token", hits[0].path) + require.NotEqual(t, "/oauth/token", hits[1].path) + for _, hit := range hits { + require.Equal(t, 1, hit.id, "refresh and old-token inference must remain on request proxy A") + } + }) + for _, tc := range []struct { + name string + proxy int64 + }{ + {"single_B_no_route_refresh_error", 3}, + {"single_empty_no_route_refresh_error", 0}, + } { + t.Run(tc.name, func(t *testing.T) { + f := newPR885OAuthConfigSwitchFixture(t) + f.account.Extra[OpenAIProxyModeKey] = OpenAIProxyModeSingle + f.account.ProxyID, f.account.Proxy = nil, nil + if tc.proxy != 0 { + proxy, err := f.gateway.proxyRepo.GetByID(t.Context(), tc.proxy) + require.NoError(t, err) + f.account.ProxyID, f.account.Proxy = &proxy.ID, proxy + } + require.NoError(t, f.accounts.Update(t.Context(), f.account)) + _, hasRoute := openAIRequestProxyFromContext(t.Context(), f.account.ID) + require.False(t, hasRoute) + token, err := f.provider.GetAccessToken(t.Context(), f.account) + require.NoError(t, err) + require.Equal(t, f.account.GetCredential("access_token"), token) + require.NotEmpty(t, token) + require.Equal(t, int64(1), f.provider.SnapshotRuntimeMetrics().RefreshRequests) + hits := f.hits() + require.Len(t, hits, 1, "single compatibility control must perform a real refresh HTTP request") + require.Equal(t, int(tc.proxy), hits[0].id) + require.Equal(t, "/oauth/token", hits[0].path) + }) + } +} diff --git a/backend/internal/service/pr885_siwc_config_switch_test.go b/backend/internal/service/pr885_siwc_config_switch_test.go new file mode 100644 index 000000000000..a34cdb6615c7 --- /dev/null +++ b/backend/internal/service/pr885_siwc_config_switch_test.go @@ -0,0 +1,297 @@ +//go:build unit && bps_request_integration + +package service + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "sync" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/mihomo" + infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" + "github.com/Wei-Shaw/sub2api/internal/pkg/openai" + "github.com/stretchr/testify/require" +) + +// The account repository owns saved configuration while the request keeps its +// hydrated snapshot. Only the SIWC refresh re-read pauses: ordinary admin reads +// must remain available so UpdateAccount can finish before refresh resumes. +type pr885SIWCConfigSwitchAccounts struct { + AccountRepository + mu sync.Mutex + account *Account + proxies ProxyRepository + ready chan *openAIRequestProxyRoute + resume chan struct{} + once sync.Once +} + +func pr885SIWCConfigSwitchClone(account *Account) *Account { + copy := *account + copy.Extra = cloneReauthMap(account.Extra) + copy.Credentials = cloneReauthMap(account.Credentials) + if account.ProxyID != nil { + id := *account.ProxyID + copy.ProxyID = &id + } + return © +} + +func (r *pr885SIWCConfigSwitchAccounts) GetByID(context.Context, int64) (*Account, error) { + r.mu.Lock() + defer r.mu.Unlock() + return pr885SIWCConfigSwitchClone(r.account), nil +} + +func (r *pr885SIWCConfigSwitchAccounts) Update(_ context.Context, account *Account) error { + r.mu.Lock() + defer r.mu.Unlock() + r.account = pr885SIWCConfigSwitchClone(account) + return nil +} + +func (r *pr885SIWCConfigSwitchAccounts) ListShadowsByParent(context.Context, int64) ([]*Account, error) { + return nil, nil +} + +func (r *pr885SIWCConfigSwitchAccounts) GetAccount(ctx context.Context, id int64) (*Account, error) { + if route, ok := openAIRequestProxyFromContext(ctx, id); ok { + r.once.Do(func() { + r.ready <- route + select { + case <-r.resume: + case <-ctx.Done(): + } + }) + } + if err := ctx.Err(); err != nil { + return nil, err + } + return r.GetByID(ctx, id) +} + +func (r *pr885SIWCConfigSwitchAccounts) GetProxy(ctx context.Context, id int64) (*Proxy, error) { + return r.proxies.GetByID(ctx, id) +} + +// Both an explicitly selected proxy and direct mode execute real loopback HTTP. +// The empty-proxy branch must send, rather than reject in a fake OAuth client, +// otherwise old production could appear safe without testing its direct leak. +type pr885SIWCConfigSwitchTokenClient struct { + *reauthTestOAuthClient + directURL string +} + +func (c *pr885SIWCConfigSwitchTokenClient) SIWCToken(ctx context.Context, form url.Values, proxy, _ string) (*openai.TokenResponse, *openai.SIWCIdentity, error) { + transport := &http.Transport{} + defer transport.CloseIdleConnections() + if proxy != "" { + u, err := url.Parse(proxy) + if err != nil || u.Host == "" { + return nil, nil, fmt.Errorf("invalid fixture proxy") + } + transport.Proxy = http.ProxyURL(u) + } + req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.directURL+"/oauth/token", strings.NewReader(form.Encode())) + if err != nil { + return nil, nil, err + } + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + resp, err := (&http.Client{Transport: transport, Timeout: 5 * time.Second}).Do(req) + if err != nil { + return nil, nil, err + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + _, _ = io.Copy(io.Discard, resp.Body) + return nil, nil, fmt.Errorf("controlled SIWC refresh status %d", resp.StatusCode) + } + var token openai.TokenResponse + err = json.NewDecoder(resp.Body).Decode(&token) + return &token, nil, err +} + +func pr885SIWCConfigSwitchAssertLeaseReturned(t *testing.T, ctx context.Context, accountID int64) { + t.Helper() + // Hold the spare at load one, then make A the rotation cursor. A returned + // request lease leaves A at zero, so it must win. A leaked lease ties at one + // and rotates to the spare, making this a behavioral pool accounting check. + spare, err := mihomo.AcquireBPSStaticRequestLease(ctx, accountID, []int64{2}) + require.NoError(t, err) + defer spare.Release() + cursor, err := mihomo.AcquireBPSStaticRequestLease(ctx, accountID, []int64{1}) + require.NoError(t, err) + cursor.Release() + next, err := mihomo.AcquireBPSStaticRequestLease(ctx, accountID, []int64{1, 2}) + require.NoError(t, err) + defer next.Release() + require.Equal(t, int64(1), next.ProxyID, "SIWC config-switch completion must return its acquired lease") +} + +func pr885SIWCConfigSwitchRun(t *testing.T, singleProxyID int64, terminal string) { + t.Helper() + var observedMu sync.Mutex + var observed []requestProxyObservation + refreshReached := make(chan int, 1) + refreshCanceled := make(chan struct{}, 1) + handle := func(id int, w http.ResponseWriter, r *http.Request) { + raw, _ := io.ReadAll(r.Body) + observedMu.Lock() + observed = append(observed, requestProxyObservation{id: id, path: r.URL.Path, body: raw}) + observedMu.Unlock() + if r.URL.Path == "/oauth/token" { + if terminal != "" { + refreshReached <- id + } + if terminal == "refresh_cancel" { + <-r.Context().Done() + refreshCanceled <- struct{}{} + return + } + if terminal == "refresh_error" { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusBadGateway) + _, _ = io.WriteString(w, `{"error":"controlled SIWC refresh failure"}`) + return + } + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, `{"access_token":"refreshed-siwc","refresh_token":"rotated-siwc","expires_in":3600}`) + return + } + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, bpsRequestCompletedWire) + } + direct := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { handle(0, w, r) })) + t.Cleanup(direct.Close) + gateway, account := localBPSRequestProxyFixture(t, 3, handle) + enableLocalSIWCRequestProxies(t, gateway, account) + account.Extra[OpenAIProxyIDsKey] = []int64{1} + proxyA, err := gateway.proxyRepo.GetByID(t.Context(), 1) + require.NoError(t, err) + account.ProxyID, account.Proxy = &proxyA.ID, proxyA + accounts := &pr885SIWCConfigSwitchAccounts{ + account: pr885SIWCConfigSwitchClone(account), proxies: gateway.proxyRepo, + ready: make(chan *openAIRequestProxyRoute, 1), resume: make(chan struct{}), + } + reauth := gateway.excelOAuthReauth + reauth.accounts = accounts + store := reauth.repo.(*siwcTestRepo) + var grant siwcGrant + require.NoError(t, json.Unmarshal([]byte(strings.TrimPrefix(store.ciphertext, "encrypted:")), &grant)) + grant.ExpiresAt = 0 + raw, err := json.Marshal(grant) + require.NoError(t, err) + store.ciphertext = "encrypted:" + string(raw) + reauth.oauth.oauthClient = &pr885SIWCConfigSwitchTokenClient{directURL: direct.URL} + + ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second) + defer cancel() + type result struct { + code int + body string + err error + } + done := make(chan result, 1) + go func() { + code, body, err := forwardLocalBPSRequest(ctx, gateway, account, []byte(`{"model":"gpt-5.4","input":"test","stream":true}`)) + done <- result{code: code, body: body, err: err} + }() + var route *openAIRequestProxyRoute + select { + case route = <-accounts.ready: + case <-ctx.Done(): + t.Fatal("SIWC Forward did not reach refresh account re-read after route acquisition") + } + require.Equal(t, int64(1), route.lease.ProxyID) + t.Log("CONFIG_SWITCH_ROUTE_READY SIWC proxy_id=1") + if terminal == "" { + admin := &adminServiceImpl{accountRepo: accounts, proxyRepo: gateway.proxyRepo} + extra := cloneReauthMap(account.Extra) + extra[OpenAIProxyModeKey] = OpenAIProxyModeSingle + saved, err := admin.UpdateAccount(ctx, account.ID, &UpdateAccountInput{Extra: extra, ProxyID: &singleProxyID}) + require.NoError(t, err) + require.Equal(t, OpenAIProxyModeSingle, saved.Extra[OpenAIProxyModeKey]) + if singleProxyID == 0 { + require.Nil(t, saved.ProxyID) + } else { + require.NotNil(t, saved.ProxyID) + require.Equal(t, singleProxyID, *saved.ProxyID) + } + t.Logf("CONFIG_SWITCH_SINGLE_SAVED SIWC proxy_id=%d", singleProxyID) + } + close(accounts.resume) + if terminal != "" { + select { + case id := <-refreshReached: + require.Equal(t, 1, id, "refresh control must reach selected proxy A") + t.Logf("SIWC_REFRESH_CONTROL_REACHED terminal=%s proxy_id=%d", terminal, id) + case <-ctx.Done(): + t.Fatal("SIWC refresh control did not reach a real HTTP send") + } + if terminal == "refresh_cancel" { + cancel() + select { + case <-refreshCanceled: + t.Log("SIWC_REFRESH_CONTROL_CANCELED proxy_id=1") + case <-time.After(5 * time.Second): + t.Fatal("SIWC refresh HTTP request did not observe cancellation") + } + } + } + var completed result + select { + case completed = <-done: + case <-time.After(5 * time.Second): + t.Fatal("SIWC Forward did not finish after configuration switch") + } + pr885SIWCConfigSwitchAssertLeaseReturned(t, t.Context(), account.ID) + observedMu.Lock() + hits := append([]requestProxyObservation(nil), observed...) + observedMu.Unlock() + if terminal != "" { + require.Error(t, completed.err) + if terminal == "refresh_error" { + require.ErrorContains(t, completed.err, "controlled SIWC refresh status 502") + } + require.Len(t, hits, 1, "refresh error/cancellation must prevent inference and retry sends") + require.Equal(t, 1, hits[0].id) + require.Equal(t, "/oauth/token", hits[0].path) + return + } + escaped := 0 + for _, hit := range hits { + if hit.id != 1 { + escaped++ + } + t.Logf("SIWC config switch observed proxy_id=%d path=%s", hit.id, hit.path) + } + require.Zero(t, escaped, "CONFIG_SWITCH_REFRESH_EGRESS_ESCAPED: SIWC refresh/inference escaped request proxy A (B/direct sends must be zero)") + require.Error(t, completed.err, "switching fresh configuration to single must explicitly reject the acquired request scope") + require.Equal(t, "OPENAI_PROXY_UNAVAILABLE", infraerrors.Reason(completed.err)) + require.Equal(t, http.StatusServiceUnavailable, infraerrors.Code(completed.err)) + require.Empty(t, hits, "single configuration must reject before refresh or inference sends") +} + +func TestExcelBPSRequestProxyConfigSwitchSIWC(t *testing.T) { + for _, tc := range []struct { + name string + proxy int64 + }{{"single_B", 3}, {"single_empty", 0}} { + t.Run(tc.name, func(t *testing.T) { pr885SIWCConfigSwitchRun(t, tc.proxy, "") }) + } +} + +// These pass controls are intentionally outside the strict behavioral RED roots. +func TestExcelBPSRequestProxyConfigSwitchSIWCControls(t *testing.T) { + for _, terminal := range []string{"refresh_error", "refresh_cancel"} { + t.Run(terminal, func(t *testing.T) { pr885SIWCConfigSwitchRun(t, 3, terminal) }) + } +} From d7fb497ebd89cb14d4cd8e4bd2e7658b698c8402 Mon Sep 17 00:00:00 2001 From: luotao21 Date: Tue, 17 Nov 2026 04:13:54 +0800 Subject: [PATCH 12/14] =?UTF-8?q?=E8=A1=A5=E5=85=85=E9=85=8D=E7=BD=AE?= =?UTF-8?q?=E5=88=87=E6=8D=A2=E5=85=AB=E5=9C=BA=E6=99=AF=E7=9A=84=E4=B8=A5?= =?UTF-8?q?=E6=A0=BC=E7=BA=A2=E7=BB=BF=E5=9B=9E=E5=BD=92=E9=97=A8=E7=A6=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../assert-account-proxy-config-switch.py | 54 ++++++++++++ ...st_account_proxy_config_switch_evidence.py | 83 +++++++++++++++++++ .github/workflows/account-request-proxy.yml | 75 +++++++++++++++++ 3 files changed, 212 insertions(+) create mode 100644 .github/scripts/assert-account-proxy-config-switch.py create mode 100644 .github/scripts/test_account_proxy_config_switch_evidence.py diff --git a/.github/scripts/assert-account-proxy-config-switch.py b/.github/scripts/assert-account-proxy-config-switch.py new file mode 100644 index 000000000000..c47407eccc95 --- /dev/null +++ b/.github/scripts/assert-account-proxy-config-switch.py @@ -0,0 +1,54 @@ +"""Require all eight real config-switch cases; reject setup failures as RED.""" + +import json +import sys +from collections import Counter +from pathlib import Path + +PACKAGE = "github.com/Wei-Shaw/sub2api/internal/service" +ROOTS = {"TestExcelBPSRequestProxyConfigSwitch" + path for path in ("Forward", "Images", "SIWC", "OAuth")} +LEAVES = {root + "/" + mode for root in ROOTS for mode in ("single_B", "single_empty")} +NODES = ROOTS | LEAVES +ESCAPED = "CONFIG_SWITCH_REFRESH_EGRESS_ESCAPED" +REACHED = ("CONFIG_SWITCH_ROUTE_READY", "CONFIG_SWITCH_SINGLE_SAVED") + + +def validate(phase, code, text): + if phase not in {"RED", "GREEN"} or code != (1 if phase == "RED" else 0): + raise ValueError("wrong phase or Go exit status") + try: + events = [json.loads(line) for line in text.splitlines() if line.strip()] + except (ValueError, TypeError) as exc: + raise ValueError("non-JSON build/runtime output") from exc + if not events or any(not isinstance(event, dict) for event in events): + raise ValueError("missing JSON events") + if any(event.get("Package") != PACKAGE for event in events): + raise ValueError("wrong package") + output = "".join(event.get("Output", "") for event in events) + poison = ("[no tests to run]", "DATA RACE", "panic:", "fatal error:", "signal: killed", "undefined:", "build failed", "no required module provides package", "--- SKIP:") + if any(marker in output for marker in poison) or any(event.get("Action") in {"skip", "build-fail", "build-output"} or event.get("FailedBuild") for event in events): + raise ValueError("build/runtime/skip contamination") + named = [event for event in events if event.get("Test")] + if any(event["Test"] not in NODES for event in named): + raise ValueError("unexpected test") + runs = Counter(event["Test"] for event in named if event.get("Action") == "run") + terminal = "fail" if phase == "RED" else "pass" + ends = Counter(event["Test"] for event in named if event.get("Action") in {"pass", "fail", "skip"}) + if runs != Counter({name: 1 for name in NODES}) or ends != runs: + raise ValueError("missing or repeated test nodes") + if any(event.get("Action") != terminal for event in named if event.get("Action") in {"pass", "fail", "skip"}): + raise ValueError("wrong test verdict") + packages = [event["Action"] for event in events if not event.get("Test") and event.get("Action") in {"pass", "fail", "skip"}] + if packages != [terminal]: + raise ValueError("wrong package verdict") + for leaf in LEAVES: + own = "".join(event.get("Output", "") for event in named if event["Test"] == leaf) + if not all(marker in own for marker in REACHED): + raise ValueError("route barrier or real admin save not reached: " + leaf) + if (ESCAPED in own) != (phase == "RED"): + raise ValueError("wrong business failure: " + leaf) + return {"phase": phase, "go_exit": code, "roots": len(ROOTS), "leaves": len(LEAVES), "nodes": len(NODES)} + + +if __name__ == "__main__": + print(json.dumps(validate(sys.argv[1], int(sys.argv[2]), Path(sys.argv[3]).read_text()), sort_keys=True)) diff --git a/.github/scripts/test_account_proxy_config_switch_evidence.py b/.github/scripts/test_account_proxy_config_switch_evidence.py new file mode 100644 index 000000000000..d59ca7ab799b --- /dev/null +++ b/.github/scripts/test_account_proxy_config_switch_evidence.py @@ -0,0 +1,83 @@ +"""Validator self-tests; synthetic events are never business evidence.""" + +import importlib.util +import json +import unittest +from pathlib import Path + +SPEC = importlib.util.spec_from_file_location("gate", Path(__file__).with_name("assert-account-proxy-config-switch.py")) +GATE = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(GATE) + + +def evidence(phase): + terminal = "fail" if phase == "RED" else "pass" + events = [{"Action": "start"}] + for root in sorted(GATE.ROOTS): + events.append({"Action": "run", "Test": root}) + for leaf in sorted(name for name in GATE.LEAVES if name.startswith(root + "/")): + events.extend([{"Action": "run", "Test": leaf}, {"Action": "output", "Test": leaf, "Output": " ".join(GATE.REACHED) + (" " + GATE.ESCAPED if phase == "RED" else "")}, {"Action": terminal, "Test": leaf}]) + events.append({"Action": terminal, "Test": root}) + events.append({"Action": terminal}) + return [dict(event, Package=GATE.PACKAGE) for event in events] + + +def raw(events): + return "\n".join(json.dumps(event) for event in events) + + +class ConfigSwitchEvidenceTests(unittest.TestCase): + def test_complete_red_and_green(self): + for phase, code in (("RED", 1), ("GREEN", 0)): + self.assertEqual(8, GATE.validate(phase, code, raw(evidence(phase)))["leaves"]) + + def test_each_run_terminal_and_business_marker_required(self): + for phase, code in (("RED", 1), ("GREEN", 0)): + events = evidence(phase) + for index, event in enumerate(events): + if event["Action"] in {"run", "pass", "fail", "output"}: + with self.assertRaises(ValueError): + GATE.validate(phase, code, raw(events[:index] + events[index + 1:])) + if event["Action"] in {"run", "pass", "fail"}: + with self.assertRaises(ValueError): + GATE.validate(phase, code, raw(events + [event])) + if event["Action"] == "output": + for marker in (*GATE.REACHED, GATE.ESCAPED) if phase == "RED" else GATE.REACHED: + changed = [dict(value) for value in events] + changed[index]["Output"] = changed[index]["Output"].replace(marker, "unrelated") + with self.assertRaises(ValueError): + GATE.validate(phase, code, raw(changed)) + + def test_exit_verdict_scope_and_contamination_rejected(self): + for phase, code in (("RED", 1), ("GREEN", 0)): + events = evidence(phase) + for wrong in (0, 1, 2, 137): + if wrong != code: + with self.assertRaises(ValueError): + GATE.validate(phase, wrong, raw(events)) + for action in ("pass", "fail", "run", "skip", "build-fail"): + with self.assertRaises(ValueError): + GATE.validate(phase, code, raw(events + [{"Action": action, "Test": "Unrelated", "Package": GATE.PACKAGE}])) + for poison in ("[no tests to run]", "DATA RACE", "panic: bad", "undefined: fixture", "no required module provides package", "--- SKIP: fixture"): + with self.assertRaises(ValueError): + GATE.validate(phase, code, raw(events + [{"Action": "output", "Package": GATE.PACKAGE, "Output": poison}])) + for bad in ("", "not JSON", "[]", raw([dict(events[0], Package="other")]) + "\n" + raw(events)): + with self.assertRaises(ValueError): + GATE.validate(phase, code, bad) + + def test_mixed_verdict_and_wrong_phase_rejected(self): + for phase, code in (("RED", 1), ("GREEN", 0)): + events = evidence(phase) + for index, event in enumerate(events): + if event["Action"] not in {"pass", "fail"}: + continue + changed = [dict(value) for value in events] + changed[index]["Action"] = "pass" if phase == "RED" else "fail" + with self.assertRaises(ValueError): + GATE.validate(phase, code, raw(changed)) + with self.assertRaises(ValueError): + GATE.validate("OTHER", 1, raw(evidence("RED"))) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/workflows/account-request-proxy.yml b/.github/workflows/account-request-proxy.yml index 87917e799252..5d891bd36c62 100644 --- a/.github/workflows/account-request-proxy.yml +++ b/.github/workflows/account-request-proxy.yml @@ -4,6 +4,8 @@ on: paths: - 'backend/**' - '.github/workflows/account-request-proxy.yml' + - '.github/scripts/assert-account-proxy-config-switch.py' + - '.github/scripts/test_account_proxy_config_switch_evidence.py' permissions: contents: read jobs: @@ -26,6 +28,8 @@ jobs: sudo apt-get update sudo apt-get install -y --no-install-recommends redis-server fi + - name: Config switch evidence validator self-tests + run: python3 -B -m unittest discover -s .github/scripts -p test_account_proxy_config_switch_evidence.py -v - name: Account proxy leases, admission and HTTP transports working-directory: backend shell: bash @@ -64,11 +68,22 @@ jobs: "TestOpenAIRequestProxyFailureAttributesSelectedExit", "TestExcelBPSImagesRequestRefreshAndFallbackShareExit", } + for root in ("Forward", "Images", "SIWC", "OAuth"): + required.update("TestExcelBPSRequestProxyConfigSwitch" + root + "/" + mode for mode in ("single_B", "single_empty")) + required.update("TestExcelBPSRequestProxyConfigSwitchControls/images_" + images + "/" + control for images in ("false", "true") for control in ("refresh_error", "cancel")) + required.update("TestExcelBPSRequestProxyConfigSwitchSIWCControls/" + control for control in ("refresh_error", "refresh_cancel")) + required.update("TestExcelBPSRequestProxyConfigSwitchOAuthControls/" + control for control in ("request_refresh_error", "single_B_no_route_refresh_error", "single_empty_no_route_refresh_error")) passed = {event.get("Test") for event in events if event.get("Action") == "pass"} missing = required - passed if missing: raise SystemExit(f"Required routing evidence did not pass: {sorted(missing)}") PYTHON + - name: Require all eight config switch cases to pass + shell: bash + run: | + set -euo pipefail + (cd backend && go test -race -json -p 2 -tags=unit,bps_request_integration ./internal/service -run '^TestExcelBPSRequestProxyConfigSwitch(Forward|Images|SIWC|OAuth)$' -count=1 -timeout=2m) > "$RUNNER_TEMP/config-switch-green.jsonl" 2>&1 + python3 .github/scripts/assert-account-proxy-config-switch.py GREEN 0 "$RUNNER_TEMP/config-switch-green.jsonl" - name: Preserve raw routing evidence if: always() uses: actions/upload-artifact@v7 @@ -77,6 +92,66 @@ jobs: path: | ${{ runner.temp }}/account-proxy.jsonl ${{ runner.temp }}/account-proxy-redis.log + ${{ runner.temp }}/config-switch-green.jsonl + if-no-files-found: error + config-switch-red: + runs-on: ubuntu-24.04 + timeout-minutes: 25 + steps: + - uses: actions/checkout@v6 + with: + ref: ${{ github.event.pull_request.head.sha }} + fetch-depth: 0 + persist-credentials: false + - uses: actions/setup-go@v6 + with: + go-version-file: backend/go.mod + cache-dependency-path: backend/go.sum + - name: Download dependencies before capturing strict JSON evidence + working-directory: backend + run: go mod download + - name: Restore exact production files before the config switch fix + shell: bash + run: | + set -euo pipefail + baseline=017d54c819f1ca571a46a99138e0f73bfbb6cd23 + candidate=$(git rev-parse HEAD) + manifest="$RUNNER_TEMP/config-switch-red-source.txt" + printf 'candidate=%s baseline=%s\n' "$candidate" "$baseline" > "$manifest" + for file in openai_excel_oauth.go openai_siwc.go openai_maintenance_proxy.go openai_oauth_service.go openai_token_provider.go; do + target="backend/internal/service/$file" + candidate_blob=$(git rev-parse "$candidate:$target") + test "$(git hash-object "$target")" = "$candidate_blob" + git show "$baseline:$target" > "$target" + baseline_blob=$(git rev-parse "$baseline:$target") + test "$(git hash-object "$target")" = "$baseline_blob" + printf 'path=%s candidate_blob=%s restored_baseline_blob=%s\n' "$target" "$candidate_blob" "$baseline_blob" >> "$manifest" + done + for file in pr885_config_switch_refresh_test.go pr885_siwc_config_switch_test.go pr885_oauth_config_switch_test.go; do + target="backend/internal/service/$file" + blob=$(git rev-parse "$candidate:$target") + test "$(git hash-object "$target")" = "$blob" + printf 'unchanged_candidate_fixture=%s blob=%s\n' "$target" "$blob" >> "$manifest" + done + expected=$(printf '%s\n' backend/internal/service/openai_excel_oauth.go backend/internal/service/openai_maintenance_proxy.go backend/internal/service/openai_oauth_service.go backend/internal/service/openai_siwc.go backend/internal/service/openai_token_provider.go) + test "$(git diff --name-only -- 'backend/**/*.go' ':!backend/**/*_test.go')" = "$expected" + - name: Require all eight config switch failures to be behavioral + shell: bash + run: | + set -euo pipefail + set +e + (cd backend && go test -race -json -p 2 -tags=unit,bps_request_integration ./internal/service -run '^TestExcelBPSRequestProxyConfigSwitch(Forward|Images|SIWC|OAuth)$' -count=1 -timeout=2m) > "$RUNNER_TEMP/config-switch-red.jsonl" 2>&1 + result=$? + set -e + python3 .github/scripts/assert-account-proxy-config-switch.py RED "$result" "$RUNNER_TEMP/config-switch-red.jsonl" + - name: Preserve raw config switch RED evidence + if: always() + uses: actions/upload-artifact@v7 + with: + name: config-switch-red-${{ github.event.pull_request.head.sha }} + path: | + ${{ runner.temp }}/config-switch-red.jsonl + ${{ runner.temp }}/config-switch-red-source.txt if-no-files-found: error refresh-oracle-red: runs-on: ubuntu-24.04 From 94294626e2e6fa5c3b26e9866342ba13cf859bc2 Mon Sep 17 00:00:00 2001 From: luotao21 Date: Tue, 17 Nov 2026 04:20:25 +0800 Subject: [PATCH 13/14] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E5=8E=86=E5=8F=B2WS?= =?UTF-8?q?=E7=BA=A2=E7=81=AF=E5=9B=9E=E6=94=BE=E7=BC=96=E8=AF=91=E5=88=B0?= =?UTF-8?q?=E6=96=B0=E4=BB=A3=E7=90=86=E5=A4=B9=E5=85=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../prepare-request-proxy-historical-tests.py | 152 ++++++++++++ .../test_request_proxy_historical_tests.py | 231 ++++++++++++++++++ .../workflows/ws-readable-continuation.yml | 11 +- 3 files changed, 393 insertions(+), 1 deletion(-) create mode 100644 .github/scripts/prepare-request-proxy-historical-tests.py create mode 100644 .github/scripts/test_request_proxy_historical_tests.py diff --git a/.github/scripts/prepare-request-proxy-historical-tests.py b/.github/scripts/prepare-request-proxy-historical-tests.py new file mode 100644 index 000000000000..85b1421d8d71 --- /dev/null +++ b/.github/scripts/prepare-request-proxy-historical-tests.py @@ -0,0 +1,152 @@ +"""Isolate twelve unrelated PR885 unit fixtures from one historical WS RED.""" + +import json +import os +import re +import subprocess +import sys +from pathlib import Path + + +BASELINE_SHA = "94bb4a53e9e5057990cd851ab0620d99b116ad41" +CONTRACT = "backend/internal/service/openai_proxy_routing.go" +REDIS_HELPER = "backend/internal/testutil/redissession/store.go" +FIXTURES = ( + "backend/internal/service/admin_account_request_proxy_upstream_merge_test.go", + "backend/internal/service/openai_codex_models_request_proxy_test.go", + "backend/internal/service/openai_excel_bps_proxy_config_test.go", + "backend/internal/service/openai_excel_bps_request_proxy_test.go", + "backend/internal/service/openai_maintenance_remaining_proxy_test.go", + "backend/internal/service/openai_maintenance_task_request_proxy_test.go", + "backend/internal/service/openai_oauth_create_request_proxy_test.go", + "backend/internal/service/openai_oauth_reauth_request_proxy_test.go", + "backend/internal/service/openai_oauth_request_proxy_test.go", + "backend/internal/service/openai_proxy_routing_test.go", + "backend/internal/service/openai_quota_request_proxy_test.go", + "backend/internal/service/openai_request_proxy_test.go", +) +ORACLES = ( + "backend/internal/service/openai_409_ws_ticket_test.go", + "backend/internal/handler/openai_409_ws_rebuild_test.go", + "backend/internal/handler/openai_409_ws_oracle_test.go", +) + + +def git(tree, *args): + return subprocess.run( + ["git", "-C", str(tree), *args], check=True, capture_output=True, text=True, timeout=30 + ).stdout.strip() + + +def entry(tree, revision, relative): + raw = git(tree, "ls-tree", revision, "--", relative) + if not raw: + return None + metadata, path = raw.split("\t", 1) + mode, kind, blob = metadata.split() + if path != relative or mode != "100644" or kind != "blob": + raise ValueError("unexpected git entry: " + relative) + return blob + + +def safe_path(root, relative): + path = root + for part in Path(relative).parts: + if part in {"..", "."}: + raise ValueError("unexpected relative path") + path = path / part + if path.is_symlink(): + raise ValueError("symlink refused: " + str(path)) + return path + + +def candidate_file(tree, candidate, relative): + blob = entry(tree, candidate, relative) + path = safe_path(tree, relative) + if not blob or not path.is_file() or git(tree, "hash-object", "--", str(path)) != blob: + raise ValueError("missing or dirty candidate file: " + relative) + return blob, path + + +def prepare(baseline, root, candidate, destination): + # No CLI baseline override: the helper owns exactly this historical boundary. + if baseline != BASELINE_SHA: + raise ValueError("unsupported historical baseline") + if not re.fullmatch(r"[0-9a-f]{40}", candidate): + raise ValueError("candidate must be an exact commit SHA") + tree = Path(os.path.abspath(root)) + if tree.is_symlink() or not tree.is_dir(): + raise ValueError("invalid or symlinked worktree") + tree = tree.resolve() + if Path(git(tree, "rev-parse", "--show-toplevel")).resolve() != tree: + raise ValueError("expected the worktree root") + if git(tree, "rev-parse", "HEAD") != candidate: + raise ValueError("worktree HEAD is not candidate") + if git(tree, "rev-parse", baseline + "^{commit}") != baseline: + raise ValueError("baseline is not an exact commit") + + manifest = Path(os.path.abspath(destination)) + safe_path(Path(manifest.anchor), str(manifest.relative_to(manifest.anchor))) + if os.path.lexists(manifest) or not manifest.parent.is_dir() or manifest.is_relative_to(tree): + raise ValueError("manifest must be a new external evidence file") + + # The baseline lacks the actual production contract, not just a test name. + contract_path = safe_path(tree, CONTRACT) + contract_blob = entry(tree, candidate, CONTRACT) + if entry(tree, baseline, CONTRACT) or not contract_blob or os.path.lexists(contract_path): + raise ValueError("request proxy contract must be absent in historical production") + contract_source = git(tree, "show", candidate + ":" + CONTRACT) + if "OpenAIProxyModeKey" not in contract_source or "OpenAIRequestProxyEnabled" not in contract_source: + raise ValueError("candidate request proxy contract is unexpected") + + # Preserve the previously proved production baseline plus its sole explicit + # Redis test-support exception. Do not restore candidate production APIs. + if entry(tree, baseline, REDIS_HELPER): + raise ValueError("unexpected historical Redis test helper") + helper_blob, _ = candidate_file(tree, candidate, REDIS_HELPER) + production = git(tree, "diff", "--name-only", baseline, "--", "backend/**/*.go", ":!backend/**/*_test.go") + if production.splitlines() != [REDIS_HELPER]: + raise ValueError("unexpected production changes") + if git(tree, "ls-files", "--others", "--", "backend/**/*.go"): + raise ValueError("unexpected untracked backend Go files") + + oracles = {} + for relative in ORACLES: + blob, _ = candidate_file(tree, candidate, relative) + oracles[relative] = blob + + pending = [] + for relative in FIXTURES: + if entry(tree, baseline, relative): + raise ValueError("fixture is not candidate-only: " + relative) + blob, path = candidate_file(tree, candidate, relative) + pending.append((relative, blob, path)) + + # Preflight every path and blob before the first mutation. A later dirty + # fixture cannot leave an earlier fixture removed on a rejected preparation. + records = [] + for relative, blob, path in pending: + path.unlink() + records.append({"path": relative, "candidate_blob": blob, "baseline_blob": "absent", "actual": "absent"}) + result = { + "baseline": baseline, + "candidate": candidate, + "contract": {"path": CONTRACT, "baseline_blob": "absent", "candidate_blob": contract_blob, "actual": "absent"}, + "production_exception": {"path": REDIS_HELPER, "candidate_blob": helper_blob}, + "unchanged_oracles": oracles, + "fixtures": records, + } + with manifest.open("x") as stream: + json.dump(result, stream, sort_keys=True, indent=2) + stream.write("\n") + return result + + +if __name__ == "__main__": + if len(sys.argv) != 5: + raise SystemExit("usage: prepare-request-proxy-historical-tests.py BASELINE TREE CANDIDATE MANIFEST") + try: + result = prepare(*sys.argv[1:]) + except (ValueError, OSError, subprocess.SubprocessError) as exc: + raise SystemExit("historical request-proxy preparation refused: " + str(exc)) from exc + print("historical request-proxy fixtures isolated: " + str(len(result["fixtures"]))) diff --git a/.github/scripts/test_request_proxy_historical_tests.py b/.github/scripts/test_request_proxy_historical_tests.py new file mode 100644 index 000000000000..8333d0c72794 --- /dev/null +++ b/.github/scripts/test_request_proxy_historical_tests.py @@ -0,0 +1,231 @@ +"""Real temporary Git checks for the fixed historical proxy fixture boundary.""" + +import importlib.util +import json +import os +import re +import subprocess +import tempfile +import unittest +from pathlib import Path +from unittest import mock + + +SCRIPT = Path(__file__).with_name("prepare-request-proxy-historical-tests.py") +SPEC = importlib.util.spec_from_file_location("historical_proxy", SCRIPT) +HELPER = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(HELPER) + + +class HistoricalProxyFixtureTests(unittest.TestCase): + def git(self, *args): + return subprocess.run( + ["git", "-C", str(self.tree), "-c", "user.name=CI fixture", "-c", "user.email=fixture@example.invalid", + "-c", "commit.gpgsign=false", "-c", "core.hooksPath=" + os.devnull, "-c", "init.templateDir=", *args], + env=self.env, check=True, capture_output=True, text=True, timeout=15, + ).stdout.strip() + + def write(self, relative, content): + path = self.tree / relative + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(content) + return path + + def make_repository(self, baseline_fixture=False, baseline_contract=False): + temporary = tempfile.TemporaryDirectory() + self.addCleanup(temporary.cleanup) + directory = Path(temporary.name).resolve() + self.tree = directory / "tree" + self.tree.mkdir() + self.manifest = directory / "evidence" / "manifest.json" + self.manifest.parent.mkdir() + self.env = {key: value for key, value in os.environ.items() if not key.startswith("GIT_")} + self.env.update(GIT_CONFIG_NOSYSTEM="1", GIT_CONFIG_GLOBAL=os.devnull) + self.git("init", "-q") + self.production = "backend/internal/service/production.go" + self.write(self.production, "package service // historical production\n") + for path in HELPER.ORACLES: + self.write(path, "package service // historical selected oracle\n") + if baseline_fixture: + self.write(HELPER.FIXTURES[-1], "package service // preexisting fixture\n") + if baseline_contract: + self.write(HELPER.CONTRACT, "package service // preexisting contract\n") + self.git("add", ".") + self.git("commit", "-qm", "baseline") + self.baseline = self.git("rev-parse", "HEAD") + self.write(self.production, "package service // candidate production\n") + self.write(HELPER.CONTRACT, "package service\nconst OpenAIProxyModeKey = 1\nfunc OpenAIRequestProxyEnabled() {}\n") + self.write(HELPER.REDIS_HELPER, "package redissession // explicit candidate support\n") + for path in HELPER.FIXTURES: + self.write(path, "package service // candidate fixture " + path + "\n") + for path in HELPER.ORACLES: + self.write(path, "package service // candidate selected oracle " + path + "\n") + self.git("add", ".") + self.git("commit", "-qm", "candidate") + self.candidate = self.git("rev-parse", "HEAD") + self.write(self.production, self.git("show", self.baseline + ":" + self.production) + "\n") + (self.tree / HELPER.CONTRACT).unlink() + patch = mock.patch.object(HELPER, "BASELINE_SHA", self.baseline) + patch.start() + self.addCleanup(patch.stop) + + def run_helper(self, baseline=None, candidate=None): + with mock.patch.dict(os.environ, self.env, clear=True): + return HELPER.prepare(baseline or self.baseline, self.tree, candidate or self.candidate, self.manifest) + + def test_literal_scope_and_workflow_handoff(self): + self.assertEqual("94bb4a53e9e5057990cd851ab0620d99b116ad41", HELPER.BASELINE_SHA) + self.assertEqual(12, len(HELPER.FIXTURES)) + self.assertEqual(12, len(set(HELPER.FIXTURES))) + self.assertFalse(set(HELPER.FIXTURES) & set(HELPER.ORACLES)) + root = SCRIPT.resolve().parents[2] + workflow = (root / ".github/workflows/ws-readable-continuation.yml").read_text() + self.assertIn("- '.github/scripts/prepare-request-proxy-historical-tests.py'", workflow) + self.assertIn("- '.github/scripts/test_request_proxy_historical_tests.py'", workflow) + self.assertIn("-p 'test_request_proxy_historical_tests.py'", workflow) + residual = workflow.split(" - name: Residual headers tools and ticket actual transport counterexamples\n", 1)[1].split(" - name:", 1)[0] + invocation = 'python3 .github/scripts/prepare-request-proxy-historical-tests.py "$baseline" "$tested_tree" "$CANDIDATE_SHA" "$RUNNER_TEMP/ws-evidence/request-proxy-historical-tests.json"' + self.assertEqual(1, residual.count(invocation)) + self.assertRegex(residual, r"(?s)if \[ \"\$PHASE\" = RED \]; then.*" + re.escape(invocation) + r"\n fi") + self.assertIn("path: ${{ runner.temp }}/ws-evidence/", workflow) + inline = re.search(r"for target in (backend/.*?); do", residual).group(1).split() + self.assertFalse(set(inline) & set(HELPER.FIXTURES), "one historical owner per fixture") + for script in (root / ".github/scripts").glob("*.sh"): + source = script.read_text() + self.assertFalse(any(path in source for path in HELPER.FIXTURES), str(script)) + + def test_valid_preparation_changes_only_twelve_fixtures(self): + self.make_repository() + before = {str(path.relative_to(self.tree)): path.read_bytes() for path in (self.tree / "backend").rglob("*.go")} + result = self.run_helper() + after = {str(path.relative_to(self.tree)): path.read_bytes() for path in (self.tree / "backend").rglob("*.go")} + self.assertEqual(set(HELPER.FIXTURES), set(before) - set(after)) + self.assertEqual({path: content for path, content in before.items() if path not in HELPER.FIXTURES}, after) + self.assertEqual(result, json.loads(self.manifest.read_text())) + self.assertEqual(self.baseline, result["baseline"]) + self.assertEqual(self.candidate, result["candidate"]) + self.assertEqual(HELPER.REDIS_HELPER, self.git("diff", "--name-only", self.baseline, "--", "backend/**/*.go", ":!backend/**/*_test.go")) + for record in result["fixtures"]: + self.assertEqual(self.git("rev-parse", self.candidate + ":" + record["path"]), record["candidate_blob"]) + self.assertEqual("absent", record["baseline_blob"]) + self.assertEqual("absent", record["actual"]) + for path, blob in result["unchanged_oracles"].items(): + self.assertEqual(blob, self.git("hash-object", str(self.tree / path))) + + def test_dirty_last_fixture_is_rejected_before_any_removal(self): + self.make_repository() + self.write(HELPER.FIXTURES[-1], "dirty final candidate fixture\n") + with self.assertRaisesRegex(ValueError, "dirty candidate"): + self.run_helper() + self.assertTrue(all((self.tree / path).exists() for path in HELPER.FIXTURES)) + self.assertFalse(self.manifest.exists()) + + def test_external_git_environment_cannot_redirect_helper_or_mutate_foreign_repo(self): + self.make_repository() + foreign = self.tree.with_name("foreign") + foreign.mkdir() + + def foreign_git(*args): + return subprocess.run( + ["git", "-C", str(foreign), "-c", "user.name=CI fixture", "-c", "user.email=fixture@example.invalid", + "-c", "commit.gpgsign=false", "-c", "core.hooksPath=" + os.devnull, "-c", "init.templateDir=", *args], + env=self.env, check=True, capture_output=True, text=True, timeout=15, + ).stdout.strip() + + foreign_git("init", "-q") + working = foreign / "keep.txt" + working.write_text("foreign working data\n") + foreign_git("add", ".") + foreign_git("commit", "-qm", "foreign state") + index = foreign / ".git/index" + before = (foreign_git("rev-parse", "HEAD"), index.read_bytes(), working.read_bytes()) + poison = {"GIT_DIR": str(foreign / ".git"), "GIT_WORK_TREE": str(foreign), "GIT_INDEX_FILE": str(index)} + with mock.patch.dict(os.environ, poison): + result = self.run_helper() + self.assertTrue(all(os.environ[key] == value for key, value in poison.items())) + self.assertEqual(self.candidate, result["candidate"]) + self.assertEqual(12, len(result["fixtures"])) + self.assertEqual(before, (foreign_git("rev-parse", "HEAD"), index.read_bytes(), working.read_bytes())) + + def test_preexisting_baseline_fixture_is_rejected(self): + self.make_repository(baseline_fixture=True) + with self.assertRaisesRegex(ValueError, "candidate-only"): + self.run_helper() + self.assertTrue(all((self.tree / path).exists() for path in HELPER.FIXTURES)) + + def test_preexisting_baseline_contract_is_rejected(self): + self.make_repository(baseline_contract=True) + with self.assertRaisesRegex(ValueError, "contract must be absent"): + self.run_helper() + self.assertFalse(self.manifest.exists()) + + def test_dirty_unsupported_and_symlink_states_fail_closed(self): + scenarios = ( + "unsupported-baseline", "candidate-mismatch", "candidate-not-sha", "dirty-production", "dirty-helper", + "missing-helper", "missing-fixture", "fixture-directory", "fixture-symlink", "parent-symlink", + "helper-symlink", "root-symlink", "unexpected-contract", "unexpected-go-file", "ignored-go-file", + "dirty-ticket", "manifest-existing", "manifest-symlink", "manifest-parent-symlink", + ) + for scenario in scenarios: + with self.subTest(scenario=scenario): + self.make_repository() + baseline, candidate = self.baseline, self.candidate + path = self.tree / HELPER.FIXTURES[-1] + if scenario == "unsupported-baseline": + baseline = "0" * 40 + elif scenario == "candidate-mismatch": + candidate = self.baseline + elif scenario == "candidate-not-sha": + candidate = "HEAD" + elif scenario == "dirty-production": + self.write(self.production, "unexpected production change\n") + elif scenario == "dirty-helper": + self.write(HELPER.REDIS_HELPER, "unexpected helper change\n") + elif scenario == "missing-helper": + (self.tree / HELPER.REDIS_HELPER).unlink() + elif scenario == "missing-fixture": + path.unlink() + elif scenario == "fixture-directory": + path.unlink() + path.mkdir() + elif scenario == "fixture-symlink": + path.unlink() + path.symlink_to(self.tree / self.production) + elif scenario == "parent-symlink": + directory = self.tree / "backend/internal/service" + directory.rename(directory.with_name("real-service")) + directory.symlink_to(directory.with_name("real-service"), target_is_directory=True) + elif scenario == "helper-symlink": + helper = self.tree / HELPER.REDIS_HELPER + helper.unlink() + helper.symlink_to(self.tree / self.production) + elif scenario == "root-symlink": + alias = self.tree.with_name("tree-alias") + alias.symlink_to(self.tree, target_is_directory=True) + self.tree = alias + elif scenario == "unexpected-contract": + self.write(HELPER.CONTRACT, "unexpected contract restoration\n") + elif scenario == "unexpected-go-file": + self.write("backend/internal/service/unexpected.go", "package service\n") + elif scenario == "ignored-go-file": + self.write("backend/internal/service/unexpected.go", "package service\n") + self.write(".git/info/exclude", "unexpected.go\n") + elif scenario == "dirty-ticket": + self.write(HELPER.ORACLES[0], "unexpected ticket oracle mutation\n") + elif scenario == "manifest-existing": + self.manifest.write_text("existing evidence\n") + elif scenario == "manifest-symlink": + self.manifest.symlink_to(self.tree / self.production) + elif scenario == "manifest-parent-symlink": + directory = self.manifest.parent + directory.rename(directory.with_name("real-evidence")) + directory.symlink_to(directory.with_name("real-evidence"), target_is_directory=True) + with self.assertRaises((ValueError, subprocess.SubprocessError)): + self.run_helper(baseline, candidate) + self.assertTrue((self.tree / HELPER.FIXTURES[0]).is_file(), "reject before mutating first fixture") + if scenario not in {"manifest-existing", "manifest-symlink"}: + self.assertFalse(self.manifest.exists()) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/workflows/ws-readable-continuation.yml b/.github/workflows/ws-readable-continuation.yml index 19443db22c24..541f8b93fa44 100644 --- a/.github/workflows/ws-readable-continuation.yml +++ b/.github/workflows/ws-readable-continuation.yml @@ -17,6 +17,8 @@ on: - 'backend/internal/service/openai_agent_message*' - '.github/scripts/assert-ws-readable.py' - '.github/scripts/test_assert_ws_readable.py' + - '.github/scripts/prepare-request-proxy-historical-tests.py' + - '.github/scripts/test_request_proxy_historical_tests.py' - '.github/scripts/exclude-later-400-red-fixtures.sh' - '.github/scripts/exclude-later-http2-red-fixtures.sh' - 'backend/internal/service/openai_gateway_passthrough.go' @@ -39,11 +41,14 @@ jobs: run: | set -euo pipefail python3 -B -m unittest discover -s .github/scripts -p 'test_assert_ws_readable.py' -v 2>&1 | tee "$RUNNER_TEMP/ws-validator.log" + python3 -B -m unittest discover -s .github/scripts -p 'test_request_proxy_historical_tests.py' -v 2>&1 | tee "$RUNNER_TEMP/request-proxy-historical-validator.log" - uses: actions/upload-artifact@v7 if: always() with: name: ws-readable-validator-${{ github.event.pull_request.head.sha || github.sha }} - path: ${{ runner.temp }}/ws-validator.log + path: | + ${{ runner.temp }}/ws-validator.log + ${{ runner.temp }}/request-proxy-historical-validator.log if-no-files-found: error transport: needs: validator @@ -264,6 +269,9 @@ jobs: printf 'path=%s baseline=%s candidate=%s candidate_blob=%s baseline_blob=absent actual=absent\n' "$target" "$baseline" "$CANDIDATE_SHA" "$candidate_blob" >> "$RUNNER_TEMP/ws-evidence/residual-service-fixtures.txt" fi done + # PR885 unit fixtures require the later request-proxy contract. + # Keep the selected ticket oracle and the proved production baseline. + python3 .github/scripts/prepare-request-proxy-historical-tests.py "$baseline" "$tested_tree" "$CANDIDATE_SHA" "$RUNNER_TEMP/ws-evidence/request-proxy-historical-tests.json" fi for target in backend/internal/handler/openai_409_ws_rebuild_test.go backend/internal/handler/openai_409_ws_oracle_test.go backend/internal/service/openai_409_ws_ticket_test.go backend/internal/service/openai_ws_agent_recovery.go backend/internal/service/openai_ws_forwarder_payload.go backend/internal/service/openai_gateway_passthrough.go; do git hash-object "$tested_tree/$target" >> "$RUNNER_TEMP/ws-evidence/residual-blobs.txt" @@ -360,5 +368,6 @@ jobs: if: always() with: name: ws-readable-${{ matrix.phase }}-${{ env.CANDIDATE_SHA }} + # Includes the guarded request-proxy-historical-tests.json RED manifest. path: ${{ runner.temp }}/ws-evidence/ if-no-files-found: error From 1a5fbd120df908e8f409340d31c4dbcae643678e Mon Sep 17 00:00:00 2001 From: luotao21 Date: Tue, 17 Nov 2026 04:26:08 +0800 Subject: [PATCH 14/14] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E5=8E=86=E5=8F=B2WS?= =?UTF-8?q?=E5=9B=9E=E6=94=BE=E7=9A=84=E9=A2=84=E7=83=AD=E6=B5=8B=E8=AF=95?= =?UTF-8?q?API=E7=89=88=E6=9C=AC=E4=B8=8D=E5=8C=B9=E9=85=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../prepare-request-proxy-historical-tests.py | 26 +++++++++- .../test_request_proxy_historical_tests.py | 52 +++++++++++++++++-- .../workflows/ws-readable-continuation.yml | 1 + 3 files changed, 74 insertions(+), 5 deletions(-) diff --git a/.github/scripts/prepare-request-proxy-historical-tests.py b/.github/scripts/prepare-request-proxy-historical-tests.py index 85b1421d8d71..7a6c89f28ab4 100644 --- a/.github/scripts/prepare-request-proxy-historical-tests.py +++ b/.github/scripts/prepare-request-proxy-historical-tests.py @@ -1,4 +1,4 @@ -"""Isolate twelve unrelated PR885 unit fixtures from one historical WS RED.""" +"""Isolate twelve PR885 fixtures and restore one existing historical WS fixture.""" import json import os @@ -30,6 +30,9 @@ "backend/internal/handler/openai_409_ws_rebuild_test.go", "backend/internal/handler/openai_409_ws_oracle_test.go", ) +ADAPTED_FIXTURES = { + "backend/internal/service/openai_excel_bps_warm_test.go": "9dc2054fd0ab61d0465e1eb12ac060360bc80166", +} def git(tree, *args): @@ -122,12 +125,32 @@ def prepare(baseline, root, candidate, destination): blob, path = candidate_file(tree, candidate, relative) pending.append((relative, blob, path)) + adaptations = [] + for relative, expected_baseline_blob in ADAPTED_FIXTURES.items(): + baseline_blob = entry(tree, baseline, relative) + if baseline_blob != expected_baseline_blob: + raise ValueError("unexpected adapted fixture baseline blob: " + relative) + candidate_blob, path = candidate_file(tree, candidate, relative) + historical = subprocess.run( + ["git", "-C", str(tree), "show", baseline + ":" + relative], + check=True, capture_output=True, timeout=30, + ).stdout + adaptations.append((relative, candidate_blob, baseline_blob, path, historical)) + # Preflight every path and blob before the first mutation. A later dirty # fixture cannot leave an earlier fixture removed on a rejected preparation. records = [] for relative, blob, path in pending: path.unlink() records.append({"path": relative, "candidate_blob": blob, "baseline_blob": "absent", "actual": "absent"}) + adapted_records = [] + for relative, candidate_blob, baseline_blob, path, historical in adaptations: + path.write_bytes(historical) + actual_blob = git(tree, "hash-object", "--", str(path)) + if actual_blob != baseline_blob: + raise ValueError("adapted fixture restoration mismatch: " + relative) + adapted_records.append({"path": relative, "candidate_blob": candidate_blob, + "baseline_blob": baseline_blob, "actual_blob": actual_blob}) result = { "baseline": baseline, "candidate": candidate, @@ -135,6 +158,7 @@ def prepare(baseline, root, candidate, destination): "production_exception": {"path": REDIS_HELPER, "candidate_blob": helper_blob}, "unchanged_oracles": oracles, "fixtures": records, + "adapted_fixtures": adapted_records, } with manifest.open("x") as stream: json.dump(result, stream, sort_keys=True, indent=2) diff --git a/.github/scripts/test_request_proxy_historical_tests.py b/.github/scripts/test_request_proxy_historical_tests.py index 8333d0c72794..89395d48ca82 100644 --- a/.github/scripts/test_request_proxy_historical_tests.py +++ b/.github/scripts/test_request_proxy_historical_tests.py @@ -46,6 +46,10 @@ def make_repository(self, baseline_fixture=False, baseline_contract=False): self.write(self.production, "package service // historical production\n") for path in HELPER.ORACLES: self.write(path, "package service // historical selected oracle\n") + adapted_paths = tuple(HELPER.ADAPTED_FIXTURES) + self.adapted_historical = b"package service // historical preserved fixture\n\n" + for path in adapted_paths: + self.write(path, self.adapted_historical.decode()) if baseline_fixture: self.write(HELPER.FIXTURES[-1], "package service // preexisting fixture\n") if baseline_contract: @@ -53,11 +57,17 @@ def make_repository(self, baseline_fixture=False, baseline_contract=False): self.git("add", ".") self.git("commit", "-qm", "baseline") self.baseline = self.git("rev-parse", "HEAD") + adapted = {path: self.git("rev-parse", self.baseline + ":" + path) for path in adapted_paths} + adapted_patch = mock.patch.object(HELPER, "ADAPTED_FIXTURES", adapted) + adapted_patch.start() + self.addCleanup(adapted_patch.stop) self.write(self.production, "package service // candidate production\n") self.write(HELPER.CONTRACT, "package service\nconst OpenAIProxyModeKey = 1\nfunc OpenAIRequestProxyEnabled() {}\n") self.write(HELPER.REDIS_HELPER, "package redissession // explicit candidate support\n") for path in HELPER.FIXTURES: self.write(path, "package service // candidate fixture " + path + "\n") + for path in adapted_paths: + self.write(path, "package service // candidate extended fixture\n") for path in HELPER.ORACLES: self.write(path, "package service // candidate selected oracle " + path + "\n") self.git("add", ".") @@ -78,6 +88,9 @@ def test_literal_scope_and_workflow_handoff(self): self.assertEqual(12, len(HELPER.FIXTURES)) self.assertEqual(12, len(set(HELPER.FIXTURES))) self.assertFalse(set(HELPER.FIXTURES) & set(HELPER.ORACLES)) + self.assertEqual({"backend/internal/service/openai_excel_bps_warm_test.go": + "9dc2054fd0ab61d0465e1eb12ac060360bc80166"}, HELPER.ADAPTED_FIXTURES) + self.assertFalse(set(HELPER.ADAPTED_FIXTURES) & (set(HELPER.FIXTURES) | set(HELPER.ORACLES))) root = SCRIPT.resolve().parents[2] workflow = (root / ".github/workflows/ws-readable-continuation.yml").read_text() self.assertIn("- '.github/scripts/prepare-request-proxy-historical-tests.py'", workflow) @@ -89,18 +102,22 @@ def test_literal_scope_and_workflow_handoff(self): self.assertRegex(residual, r"(?s)if \[ \"\$PHASE\" = RED \]; then.*" + re.escape(invocation) + r"\n fi") self.assertIn("path: ${{ runner.temp }}/ws-evidence/", workflow) inline = re.search(r"for target in (backend/.*?); do", residual).group(1).split() - self.assertFalse(set(inline) & set(HELPER.FIXTURES), "one historical owner per fixture") + owned = set(HELPER.FIXTURES) | set(HELPER.ADAPTED_FIXTURES) + self.assertFalse(set(inline) & owned, "one historical owner per fixture") for script in (root / ".github/scripts").glob("*.sh"): source = script.read_text() - self.assertFalse(any(path in source for path in HELPER.FIXTURES), str(script)) + self.assertFalse(any(path in source for path in owned), str(script)) - def test_valid_preparation_changes_only_twelve_fixtures(self): + def test_valid_preparation_removes_twelve_and_restores_one_fixture(self): self.make_repository() before = {str(path.relative_to(self.tree)): path.read_bytes() for path in (self.tree / "backend").rglob("*.go")} result = self.run_helper() after = {str(path.relative_to(self.tree)): path.read_bytes() for path in (self.tree / "backend").rglob("*.go")} self.assertEqual(set(HELPER.FIXTURES), set(before) - set(after)) - self.assertEqual({path: content for path, content in before.items() if path not in HELPER.FIXTURES}, after) + expected = {path: content for path, content in before.items() if path not in HELPER.FIXTURES} + for path in HELPER.ADAPTED_FIXTURES: + expected[path] = self.adapted_historical + self.assertEqual(expected, after) self.assertEqual(result, json.loads(self.manifest.read_text())) self.assertEqual(self.baseline, result["baseline"]) self.assertEqual(self.candidate, result["candidate"]) @@ -111,6 +128,24 @@ def test_valid_preparation_changes_only_twelve_fixtures(self): self.assertEqual("absent", record["actual"]) for path, blob in result["unchanged_oracles"].items(): self.assertEqual(blob, self.git("hash-object", str(self.tree / path))) + self.assertEqual(1, len(result["adapted_fixtures"])) + for record in result["adapted_fixtures"]: + path = record["path"] + self.assertEqual(self.git("rev-parse", self.candidate + ":" + path), record["candidate_blob"]) + self.assertEqual(HELPER.ADAPTED_FIXTURES[path], record["baseline_blob"]) + self.assertEqual(record["baseline_blob"], self.git("hash-object", str(self.tree / path))) + self.assertEqual(record["baseline_blob"], record["actual_blob"]) + + def test_adapted_fixture_wrong_baseline_blob_rejected_before_mutation(self): + self.make_repository() + path = next(iter(HELPER.ADAPTED_FIXTURES)) + before = (self.tree / path).read_bytes() + with mock.patch.object(HELPER, "ADAPTED_FIXTURES", {path: "0" * 40}): + with self.assertRaisesRegex(ValueError, "adapted fixture baseline blob"): + self.run_helper() + self.assertEqual(before, (self.tree / path).read_bytes()) + self.assertTrue(all((self.tree / fixture).exists() for fixture in HELPER.FIXTURES)) + self.assertFalse(self.manifest.exists()) def test_dirty_last_fixture_is_rejected_before_any_removal(self): self.make_repository() @@ -165,6 +200,7 @@ def test_dirty_unsupported_and_symlink_states_fail_closed(self): "missing-helper", "missing-fixture", "fixture-directory", "fixture-symlink", "parent-symlink", "helper-symlink", "root-symlink", "unexpected-contract", "unexpected-go-file", "ignored-go-file", "dirty-ticket", "manifest-existing", "manifest-symlink", "manifest-parent-symlink", + "dirty-adapted", "missing-adapted", "adapted-symlink", ) for scenario in scenarios: with self.subTest(scenario=scenario): @@ -212,6 +248,14 @@ def test_dirty_unsupported_and_symlink_states_fail_closed(self): self.write(".git/info/exclude", "unexpected.go\n") elif scenario == "dirty-ticket": self.write(HELPER.ORACLES[0], "unexpected ticket oracle mutation\n") + elif scenario == "dirty-adapted": + self.write(next(iter(HELPER.ADAPTED_FIXTURES)), "dirty adapted fixture\n") + elif scenario == "missing-adapted": + (self.tree / next(iter(HELPER.ADAPTED_FIXTURES))).unlink() + elif scenario == "adapted-symlink": + adapted = self.tree / next(iter(HELPER.ADAPTED_FIXTURES)) + adapted.unlink() + adapted.symlink_to(self.tree / self.production) elif scenario == "manifest-existing": self.manifest.write_text("existing evidence\n") elif scenario == "manifest-symlink": diff --git a/.github/workflows/ws-readable-continuation.yml b/.github/workflows/ws-readable-continuation.yml index 541f8b93fa44..d704abba0011 100644 --- a/.github/workflows/ws-readable-continuation.yml +++ b/.github/workflows/ws-readable-continuation.yml @@ -270,6 +270,7 @@ jobs: fi done # PR885 unit fixtures require the later request-proxy contract. + # Restore the existing warm fixture to its pinned historical blob. # Keep the selected ticket oracle and the proved production baseline. python3 .github/scripts/prepare-request-proxy-historical-tests.py "$baseline" "$tested_tree" "$CANDIDATE_SHA" "$RUNNER_TEMP/ws-evidence/request-proxy-historical-tests.json" fi