diff --git a/.github/scripts/issue1010_evidence.py b/.github/scripts/issue1010_evidence.py new file mode 100644 index 000000000000..770fcf48c653 --- /dev/null +++ b/.github/scripts/issue1010_evidence.py @@ -0,0 +1,72 @@ +"""Validate executed, per-leaf Go evidence for the Issue1010 native oracle.""" + +import json +from pathlib import Path +import sys + + +PACKAGE = "github.com/Wei-Shaw/sub2api/internal/integration/accountconnectiontiming" +ROOT = "TestGatewayAccountConnectionNativeHTTP" +KINDS = ("new_api", "sub2api") +PROTOCOLS = ("responses", "chat", "anthropic", "gemini") +LEAVES = {f"{ROOT}/{kind}/{protocol}" for kind in KINDS for protocol in PROTOCOLS} +# Each slash-delimited kind/protocol is one t.Run name, not two nested tests. +NODES = LEAVES | {ROOT} +ASSERTION = "gateway probe must reach synthetic upstream exactly once" +GUARD = "GATEWAY_PROTOCOLS_PENDING" +CONTAMINATION = ( + "[build failed]", "build-fail", "setup failed", "no tests to run", + "panic:", "fatal error:", "warning: data race", "race detected during execution", + "segmentation fault", "sigsegv", "sigabrt", "sigbus", "test timed out", + "signal: killed", "runtime: out of memory", +) + + +def validate(raw, mode): + if mode not in ("red", "green"): + raise ValueError(f"unknown evidence mode: {mode}") + if any(marker in raw.lower() for marker in CONTAMINATION): + raise ValueError("build/setup/crash/race/empty-test contamination") + events = [json.loads(line) for line in raw.splitlines() if line.startswith("{")] + if not events: + raise ValueError("missing executed Go test events") + terminal = "fail" if mode == "red" else "pass" + runs = {} + results = {} + output = {} + package_results = [] + for event in events: + action = event.get("Action") + if action == "skip": + raise ValueError("skipped oracle") + if event.get("Package") != PACKAGE: + raise ValueError("unexpected package or malformed Go event") + name = event.get("Test") + if name: + if name not in NODES: + raise ValueError(f"unexpected oracle test: {name}") + if action == "run": + runs[name] = runs.get(name, 0) + 1 + elif action in ("fail", "pass"): + results.setdefault(name, []).append(action) + elif action == "output": + output[name] = output.get(name, "") + event.get("Output", "") + elif action in ("fail", "pass"): + package_results.append(action) + if runs != dict.fromkeys(NODES, 1): + raise ValueError("missing or duplicate executed oracle tests") + if results != {name: [terminal] for name in NODES}: + raise ValueError("missing, duplicate or unexpected test outcomes") + if package_results != [terminal]: + raise ValueError("missing or unexpected package outcome") + if mode == "red": + for name in sorted(LEAVES): + leaf_output = output.get(name, "") + if ASSERTION not in leaf_output or GUARD not in leaf_output: + raise ValueError(f"{name}: missing its own business assertion or historical guard") + + +if __name__ == "__main__": + if len(sys.argv) != 3: + raise SystemExit("usage: issue1010_evidence.py red|green oracle.jsonl") + validate(Path(sys.argv[2]).read_text(), sys.argv[1]) diff --git a/.github/scripts/test_issue1010_evidence.py b/.github/scripts/test_issue1010_evidence.py new file mode 100644 index 000000000000..b26b418a7f08 --- /dev/null +++ b/.github/scripts/test_issue1010_evidence.py @@ -0,0 +1,70 @@ +"""Offline evidence-validator regressions; executed only in remote CI.""" + +import json +import unittest + +from issue1010_evidence import ASSERTION, GUARD, LEAVES, NODES, PACKAGE, validate + + +def oracle_events(mode): + terminal = "fail" if mode == "red" else "pass" + events = [{"Action": "start", "Package": PACKAGE}] + for name in sorted(NODES): + events.append({"Action": "run", "Package": PACKAGE, "Test": name}) + if name in LEAVES and mode == "red": + events.append({"Action": "output", "Package": PACKAGE, "Test": name, + "Output": f"{ASSERTION}: {GUARD}\n"}) + events.append({"Action": terminal, "Package": PACKAGE, "Test": name}) + events.append({"Action": terminal, "Package": PACKAGE}) + return events + + +def encode(events): + return "\n".join(json.dumps(event) for event in events) + + +class TestIssue1010RedEvidenceRejectsMixedGuardAndSetupFailures(unittest.TestCase): + def test_all_eight_expected_failures_and_passes(self): + for mode in ("red", "green"): + with self.subTest(mode=mode): + validate(encode(oracle_events(mode)), mode) + + def test_each_leaf_requires_its_own_assertion_and_guard(self): + for leaf in sorted(LEAVES): + for replacement in ("unrelated assertion", ASSERTION, GUARD): + with self.subTest(leaf=leaf, replacement=replacement): + events = oracle_events("red") + for event in events: + if event.get("Test") == leaf and event["Action"] == "output": + event["Output"] = replacement + with self.assertRaises(ValueError): + validate(encode(events), "red") + + def test_setup_build_skip_crash_race_and_missing_or_unexpected_failures(self): + leaf = sorted(LEAVES)[0] + for mode in ("red", "green"): + for defect in ("setup failed", "[build failed]", "panic: fixture", "WARNING: DATA RACE", + "skip", "missing", "extra-fail", "wrong-outcome", "duplicate"): + with self.subTest(mode=mode, defect=defect): + events = oracle_events(mode) + if defect == "missing": + events = [event for event in events if event.get("Test") != leaf] + elif defect == "skip": + events.append({"Action": "skip", "Package": PACKAGE, "Test": leaf}) + elif defect == "extra-fail": + events.append({"Action": "fail", "Package": PACKAGE, "Test": "UnexpectedSetup"}) + elif defect == "wrong-outcome": + for event in events: + if event.get("Test") == leaf and event["Action"] in ("pass", "fail"): + event["Action"] = "pass" if mode == "red" else "fail" + elif defect == "duplicate": + events.append({"Action": "run", "Package": PACKAGE, "Test": leaf}) + else: + events.append({"Action": "output", "Package": PACKAGE, "Test": leaf, + "Output": defect}) + with self.assertRaises(ValueError): + validate(encode(events), mode) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/workflows/issue1010-gateway-connection.yml b/.github/workflows/issue1010-gateway-connection.yml new file mode 100644 index 000000000000..ddbb0095e0d6 --- /dev/null +++ b/.github/workflows/issue1010-gateway-connection.yml @@ -0,0 +1,103 @@ +name: Issue1010 gateway connection + +on: + workflow_dispatch: + pull_request: + branches: [production] + paths: + - 'backend/internal/service/account*.go' + - 'backend/internal/service/gateway_protocol_admission.go' + - 'backend/internal/handler/admin/account_handler.go' + - 'backend/internal/integration/accountconnectiontiming/**' + - 'backend/internal/repository/http_upstream*.go' + - 'backend/go.mod' + - 'backend/go.sum' + - '.github/workflows/issue1010-gateway-connection.yml' + - '.github/scripts/issue1010_evidence.py' + - '.github/scripts/test_issue1010_evidence.py' + +permissions: + contents: read + +concurrency: + group: issue1010-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +# Temporary baseline evidence; archive this entry after acceptance. +jobs: + synthetic-upstream: + runs-on: ubuntu-latest + timeout-minutes: 30 + strategy: + fail-fast: false + matrix: + mode: [red, green] + env: + EXPECTED_HEAD: ${{ github.event.pull_request.head.sha || github.sha }} + BASELINE: 991cd30e2910d5eeb6ab55f6b7fc93e9a494e1a6 + MODE: ${{ matrix.mode }} + GOMAXPROCS: '2' + GOFLAGS: '-p=2' + steps: + - uses: actions/checkout@v6 + with: + ref: ${{ github.event.pull_request.head.sha || github.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: Prepare exact source and unchanged HTTP oracle + shell: bash + run: | + set -euo pipefail + test "$(git rev-parse HEAD)" = "$EXPECTED_HEAD" + mkdir -p evidence "$RUNNER_TEMP/issue1010-baseline" + git rev-parse HEAD > evidence/head.txt + printf '%s\n' "$BASELINE" > evidence/baseline.txt + if [ "$MODE" = red ]; then + git archive "$BASELINE" | tar -x -C "$RUNNER_TEMP/issue1010-baseline" + cp backend/internal/integration/accountconnectiontiming/gateway_account_connection_test.go \ + "$RUNNER_TEMP/issue1010-baseline/backend/internal/integration/accountconnectiontiming/" + cmp backend/internal/integration/accountconnectiontiming/gateway_account_connection_test.go \ + "$RUNNER_TEMP/issue1010-baseline/backend/internal/integration/accountconnectiontiming/gateway_account_connection_test.go" + fi + - name: Per-leaf evidence validator regressions + shell: bash + run: | + set -euo pipefail + python3 -m unittest discover -s .github/scripts -p 'test_issue1010_evidence.py' -v + - name: Same native HTTP oracle on baseline and candidate + shell: bash + run: | + set -euo pipefail + source_dir="$GITHUB_WORKSPACE/backend" + if [ "$MODE" = red ]; then source_dir="$RUNNER_TEMP/issue1010-baseline/backend"; fi + set +e + (cd "$source_dir" && go test -race -tags=unit ./internal/integration/accountconnectiontiming \ + -run '^TestGatewayAccountConnectionNativeHTTP$' -count=1 -json -timeout=10m) > evidence/oracle.jsonl 2>&1 + result=$? + set -e + cat evidence/oracle.jsonl + if [ "$MODE" = red ]; then test "$result" -ne 0; else test "$result" -eq 0; fi + python3 .github/scripts/issue1010_evidence.py "$MODE" evidence/oracle.jsonl + - name: Candidate error cancellation admission and legacy lifecycle regressions + if: matrix.mode == 'green' + working-directory: backend + shell: bash + run: | + set -euo pipefail + go test -race -tags=unit ./internal/integration/accountconnectiontiming \ + -run '^Test(GatewayAccountConnection(UpstreamFailureAndEOF|AdmissionNoEgress|ExplicitCompositeRoute|CancellationReleasesReader|NonSchedulableDiagnostic|SuccessSkipsRecoveryAfterKeepaliveCleanup|AdminMultiGroupSelection)|AccountConnectionTiming)' -count=1 -v -timeout=10m \ + 2>&1 | tee ../evidence/lifecycle.log + if grep -Eq -- 'no tests to run|--- SKIP:' ../evidence/lifecycle.log; then exit 1; fi + for name in TestGatewayAccountConnectionUpstreamFailureAndEOF TestGatewayAccountConnectionAdmissionNoEgress TestGatewayAccountConnectionCancellationReleasesReader TestGatewayAccountConnectionNonSchedulableDiagnostic TestGatewayAccountConnectionSuccessSkipsRecoveryAfterKeepaliveCleanup TestGatewayAccountConnectionAdminMultiGroupSelection; do + grep -F -- "--- PASS: $name" ../evidence/lifecycle.log + done + - uses: actions/upload-artifact@v7 + if: always() + with: + name: issue1010-${{ matrix.mode }}-${{ env.EXPECTED_HEAD }}-${{ github.run_attempt }} + path: evidence + if-no-files-found: error diff --git a/.github/workflows/issue817-grok-persistence.yml b/.github/workflows/issue817-grok-persistence.yml index 68147ad0caf3..50d74aa3dc78 100644 --- a/.github/workflows/issue817-grok-persistence.yml +++ b/.github/workflows/issue817-grok-persistence.yml @@ -97,8 +97,8 @@ jobs: git show "$original:$source" > "$source" test "$(git hash-object "$source")" = "$expected_blob" if [ "$BEHAVIOR" = red ]; then - # The pinned observer predates Ciallo. Retain its behavior and add - # only the candidate's zero-value field required by ciallo.go. + # Keep the historical observer business code. Add only the + # zero-value struct fields required by current helper callers. python3 - <<'PY' from pathlib import Path import subprocess @@ -110,8 +110,21 @@ jobs: anchor = b'\tmodelTraceAccounts sync.Map\n' if candidate.count(field) != 1 or field in historical or historical.count(anchor) != 1: raise SystemExit('unexpected Ciallo compatibility field or historical struct') - path.write_bytes(historical.replace(anchor, anchor + field, 1)) + old_options = b'type AccountTestOptions struct {\n\tImageDataURL string\n\tAudioDataURL string\n}\n' + current_options = b'type AccountTestOptions struct {\n\tImageDataURL string\n\tAudioDataURL string\n\tGroupID int64\n\tPlatform string\n}\n' + if historical.count(old_options) != 1 or candidate.count(current_options) != 1: + raise SystemExit('unexpected historical or candidate AccountTestOptions shape') + compatible = historical.replace(anchor, anchor + field, 1).replace(old_options, current_options, 1) + if compatible.replace(field, b'', 1).replace(current_options, old_options, 1) != historical: + raise SystemExit('compatibility overlay changed historical observer business code') + expected = subprocess.check_output(['git', 'hash-object', '--stdin'], input=compatible).strip() + path.write_bytes(compatible) + actual = subprocess.check_output(['git', 'hash-object', str(path)]).strip() + if actual != expected: + raise SystemExit('historical compatibility blob mismatch') + Path('evidence/observer-compile-compatibility-blob.txt').write_bytes(expected + b'\n') PY + git diff --exit-code HEAD -- '*test.go' else # The pinned repository predates the OpenAI rotation CAS tests. fixture=backend/internal/repository/account_repo_temp_unsched_test.go diff --git a/.github/workflows/issue959-gateway-regression.yml b/.github/workflows/issue959-gateway-regression.yml index 70c57af98c84..13b116107897 100644 --- a/.github/workflows/issue959-gateway-regression.yml +++ b/.github/workflows/issue959-gateway-regression.yml @@ -7,6 +7,7 @@ on: paths: - 'backend/internal/domain/constants.go' - 'backend/internal/service/**' + - 'backend/internal/integration/accountconnectiontiming/**' - 'backend/internal/handler/admin/account*' - 'backend/internal/handler/dto/account_mapper_redact_test.go' - 'backend/internal/repository/account_repo.go' @@ -118,6 +119,17 @@ jobs: grep -F -- '--- PASS: TestProcurementSnapshotMixedTargetsThroughUsageWriters' ../evidence/unit-race.log grep -F -- '--- PASS: TestProcurementSnapshotAdminDTOAndUserPrivacy' ../evidence/unit-race.log grep -F -- '--- PASS: TestObserverProcurementSnapshotFollowsExistingAccountCostScope' ../evidence/unit-race.log + - name: Gateway connection handler and synthetic upstream + working-directory: backend + shell: bash + run: | + set -euo pipefail + go test -race -tags=unit ./internal/integration/accountconnectiontiming \ + -run '^TestGatewayAccountConnection' -count=1 -v -timeout=10m \ + 2>&1 | tee ../evidence/gateway-connection.log + if grep -Eq -- 'no tests to run|--- SKIP:' ../evidence/gateway-connection.log; then exit 1; fi + grep -F -- '--- PASS: TestGatewayAccountConnectionNativeHTTP' ../evidence/gateway-connection.log + grep -F -- '--- PASS: TestGatewayAccountConnectionCancellationReleasesReader' ../evidence/gateway-connection.log - name: Shared account slots against isolated Redis working-directory: backend shell: bash diff --git a/backend/internal/handler/admin/account_handler.go b/backend/internal/handler/admin/account_handler.go index 0eb9fc4f2026..fdedbfc94c37 100644 --- a/backend/internal/handler/admin/account_handler.go +++ b/backend/internal/handler/admin/account_handler.go @@ -1420,9 +1420,11 @@ func (h *AccountHandler) Delete(c *gin.Context) { // TestAccountRequest represents the request body for testing an account type TestAccountRequest struct { - ModelID string `json:"model_id"` - Prompt string `json:"prompt"` - Mode string `json:"mode"` + ModelID string `json:"model_id"` + Prompt string `json:"prompt"` + Mode string `json:"mode"` + GroupID int64 `json:"group_id"` + Platform string `json:"platform"` // Optional media for Grok (and future) real generation tests. // ImageDataURL / AudioDataURL are data:;base64,... payloads. ImageDataURL string `json:"image_data_url"` @@ -1468,6 +1470,8 @@ func (h *AccountHandler) Test(c *gin.Context) { opts := service.AccountTestOptions{ ImageDataURL: req.ImageDataURL, AudioDataURL: req.AudioDataURL, + GroupID: req.GroupID, + Platform: req.Platform, } // Use AccountTestService to test the account with SSE streaming @@ -1476,7 +1480,7 @@ func (h *AccountHandler) Test(c *gin.Context) { return } - if h.rateLimitService != nil { + if h.rateLimitService != nil && !service.IsGatewayAccountTest(c.Request.Context()) { if _, err := h.rateLimitService.RecoverAccountAfterSuccessfulTest(c.Request.Context(), accountID); err != nil { _ = c.Error(err) } diff --git a/backend/internal/integration/accountconnectiontiming/gateway_account_connection_test.go b/backend/internal/integration/accountconnectiontiming/gateway_account_connection_test.go new file mode 100644 index 000000000000..0f3e2a6dd755 --- /dev/null +++ b/backend/internal/integration/accountconnectiontiming/gateway_account_connection_test.go @@ -0,0 +1,445 @@ +//go:build unit + +package accountconnectiontiming + +import ( + "context" + "encoding/json" + "io" + "maps" + "net/http" + "net/http/httptest" + "net/url" + "strconv" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/handler/admin" + "github.com/Wei-Shaw/sub2api/internal/pkg/openai_compat" + "github.com/Wei-Shaw/sub2api/internal/pkg/tlsfingerprint" + "github.com/Wei-Shaw/sub2api/internal/repository" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +type gatewayTestAccounts struct { + service.AccountRepository + account *service.Account + live *service.Account + group *service.Group + writes atomic.Int64 +} + +func cloneGatewayTestAccount(a *service.Account) *service.Account { + copy := *a + copy.Credentials = maps.Clone(a.Credentials) + copy.Extra = maps.Clone(a.Extra) + return © +} + +func (r *gatewayTestAccounts) GetByID(context.Context, int64) (*service.Account, error) { + return cloneGatewayTestAccount(r.account), nil +} + +func (r *gatewayTestAccounts) GatewayRequestAccount(context.Context, int64, int64) (*service.Account, *service.Group, error) { + current := r.account + if r.live != nil { + current = r.live + } + return cloneGatewayTestAccount(current), r.group, nil +} + +func (r *gatewayTestAccounts) SetError(context.Context, int64, string) error { + r.writes.Add(1) + return nil +} + +func (r *gatewayTestAccounts) UpdateExtra(context.Context, int64, map[string]any) error { + r.writes.Add(1) + return nil +} + +type gatewayTestTransport struct { + service.HTTPUpstream + calls atomic.Int64 + closed atomic.Int64 + seen chan gatewayTestEgress + firstRead chan struct{} + readOnce atomic.Bool +} + +type gatewayTestEgress struct { + url string + proxy string + id int64 + concurrency int +} + +type gatewayTestBody struct { + io.ReadCloser + closed *atomic.Int64 + once atomic.Bool + firstRead chan struct{} + readOnce *atomic.Bool +} + +func (b *gatewayTestBody) Read(p []byte) (int, error) { + n, err := b.ReadCloser.Read(p) + if n > 0 && b.firstRead != nil && b.readOnce.CompareAndSwap(false, true) { + close(b.firstRead) + } + return n, err +} + +func (b *gatewayTestBody) Close() error { + if b.once.CompareAndSwap(false, true) { + b.closed.Add(1) + } + return b.ReadCloser.Close() +} + +func (u *gatewayTestTransport) Do(req *http.Request, proxy string, id int64, concurrency int) (*http.Response, error) { + u.calls.Add(1) + u.seen <- gatewayTestEgress{req.URL.String(), proxy, id, concurrency} + resp, err := u.HTTPUpstream.Do(req, proxy, id, concurrency) + if resp != nil && resp.Body != nil { + resp.Body = &gatewayTestBody{ReadCloser: resp.Body, closed: &u.closed, firstRead: u.firstRead, readOnce: &u.readOnce} + } + return resp, err +} + +func (u *gatewayTestTransport) DoWithTLS(req *http.Request, proxy string, id int64, concurrency int, _ *tlsfingerprint.Profile) (*http.Response, error) { + return u.Do(req, proxy, id, concurrency) +} + +func newGatewayTestRouter(repo *gatewayTestAccounts, cfg *config.Config) (*gin.Engine, *gatewayTestTransport) { + upstream := &gatewayTestTransport{HTTPUpstream: repository.NewHTTPUpstream(cfg), seen: make(chan gatewayTestEgress, 16)} + svc := service.NewAccountTestService(repo, nil, nil, nil, nil, upstream, cfg, nil) + // A nonnil recovery service makes success exercise the handler's observation + // boundary too; attempting ordinary health recovery here would dereference + // its deliberately absent persistence dependencies. + h := admin.NewAccountHandler(nil, nil, nil, nil, nil, nil, &service.RateLimitService{}, nil, svc, nil, nil, nil, nil, nil) + router := gin.New() + router.POST("/api/v1/admin/accounts/:id/test", h.Test) + return router, upstream +} + +func gatewayTestFixture(base, platform string) (*gatewayTestAccounts, *config.Config) { + group := &service.Group{ID: 1010, Platform: platform, Status: service.StatusActive, Hydrated: true} + account := &service.Account{ + ID: 1010, Platform: service.PlatformGateway, Type: service.AccountTypeGateway, + Status: service.StatusActive, Schedulable: true, Concurrency: 1, Priority: 7, + GroupIDs: []int64{group.ID}, AccountGroups: []service.AccountGroup{{GroupID: group.ID}}, + Credentials: map[string]any{"upstream_kind": "new_api", "base_url": base, "api_key": "synthetic-gateway-key"}, + Extra: map[string]any{"synthetic_metadata": "preserve"}, + } + cfg := &config.Config{} + cfg.Security.URLAllowlist.AllowInsecureHTTP = true + return &gatewayTestAccounts{account: account, group: group}, cfg +} + +func gatewayTestRequest(router *gin.Engine, ctx context.Context, body string) *httptest.ResponseRecorder { + recorder := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, "/api/v1/admin/accounts/1010/test", strings.NewReader(body)).WithContext(ctx) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Authorization", "Bearer inbound-admin-must-not-leak") + router.ServeHTTP(recorder, req) + return recorder +} + +func gatewayTestStream(protocol string) string { + switch protocol { + case "anthropic": + return "data: {\"type\":\"content_block_delta\",\"delta\":{\"text\":\"synthetic answer\"}}\n\ndata: {\"type\":\"message_stop\"}\n\n" + case "gemini": + return "data: {\"candidates\":[{\"content\":{\"parts\":[{\"text\":\"synthetic answer\"}]},\"finishReason\":\"STOP\"}]}\n\n" + case "chat": + return "data: {\"choices\":[{\"delta\":{\"content\":\"synthetic answer\"}}]}\n\ndata: [DONE]\n\n" + default: + return "data: {\"type\":\"response.output_text.delta\",\"delta\":\"synthetic answer\"}\n\ndata: {\"type\":\"response.completed\"}\n\n" + } +} + +func TestGatewayAccountConnectionNativeHTTP(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, kind := range []string{"new_api", "sub2api"} { + for _, scenario := range []struct { + protocol string + platform string + model string + path string + }{ + {"responses", service.PlatformOpenAI, "gpt-6.1-sol", "/tenant/v1/responses"}, + {"chat", service.PlatformDeepseek, "deepseek-chat", "/tenant/v1/chat/completions"}, + {"anthropic", service.PlatformAnthropic, "claude-sonnet-4-6", "/tenant/v1/messages"}, + {"gemini", service.PlatformGemini, "gemini-3.1-pro", "/tenant/v1beta/models/gemini-3.1-pro:streamGenerateContent"}, + } { + t.Run(kind+"/"+scenario.protocol, func(t *testing.T) { + var hits, proxyHits atomic.Int64 + type received struct { + path string + query string + authorization string + key string + googleKey string + custom string + payload map[string]any + } + requests := make(chan received, 2) + origin := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + hits.Add(1) + defer func() { _ = r.Body.Close() }() + var payload map[string]any + _ = json.NewDecoder(r.Body).Decode(&payload) + requests <- received{r.URL.Path, r.URL.RawQuery, r.Header.Get("Authorization"), r.Header.Get("x-api-key"), r.Header.Get("x-goog-api-key"), r.Header.Get("X-Gateway-Fixture"), payload} + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, gatewayTestStream(scenario.protocol)) + })) + defer origin.Close() + proxyTransport := &http.Transport{} + defer proxyTransport.CloseIdleConnections() + proxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + proxyHits.Add(1) + forward := r.Clone(r.Context()) + forward.RequestURI = "" + resp, err := proxyTransport.RoundTrip(forward) + if err != nil { + http.Error(w, "synthetic proxy failure", http.StatusBadGateway) + return + } + defer func() { _ = resp.Body.Close() }() + for key, values := range resp.Header { + w.Header()[key] = values + } + w.WriteHeader(resp.StatusCode) + _, _ = io.Copy(w, resp.Body) + })) + defer proxy.Close() + repo, cfg := gatewayTestFixture(origin.URL+"/tenant/v1", scenario.platform) + repo.account.Credentials["upstream_kind"] = kind + // The wire name is another source key too. Applying mapping twice + // would change the requested protocol/model and fail this oracle. + repo.account.Credentials["model_mapping"] = map[string]any{"public-*": scenario.model, scenario.model: "wrong-second-mapping"} + repo.account.Credentials["header_override_enabled"] = true + repo.account.Credentials["header_overrides"] = map[string]any{"X-Gateway-Fixture": "own-account"} + if scenario.protocol == "chat" { + repo.account.Extra[openai_compat.ExtraKeyResponsesMode] = string(openai_compat.ResponsesSupportModeForceChatCompletions) + } + proxyURL, err := url.Parse(proxy.URL) + require.NoError(t, err) + port, err := strconv.Atoi(proxyURL.Port()) + require.NoError(t, err) + proxyID := int64(88) + repo.account.ProxyID = &proxyID + repo.account.Proxy = &service.Proxy{ID: proxyID, Protocol: "http", Host: proxyURL.Hostname(), Port: port} + before := cloneGatewayTestAccount(repo.account) + router, transport := newGatewayTestRouter(repo, cfg) + recorder := gatewayTestRequest(router, context.Background(), `{"model_id":"public-selected"}`) + require.Equal(t, int64(1), hits.Load(), "gateway probe must reach synthetic upstream exactly once: %s", recorder.Body.String()) + require.Equal(t, int64(1), proxyHits.Load(), "the saved account proxy must carry the actual request") + require.Equal(t, int64(1), transport.calls.Load()) + require.Equal(t, int64(1), transport.closed.Load()) + egress := <-transport.seen + require.Equal(t, origin.URL+scenario.path, strings.Split(egress.url, "?")[0]) + require.Equal(t, proxy.URL, egress.proxy) + require.Equal(t, repo.account.ID, egress.id) + require.Equal(t, repo.account.Concurrency, egress.concurrency) + request := <-requests + require.Equal(t, scenario.path, request.path) + if scenario.protocol == "gemini" { + require.Equal(t, "alt=sse", request.query) + require.Equal(t, "synthetic-gateway-key", request.googleKey) + require.Empty(t, request.authorization) + } else { + require.Equal(t, "own-account", request.custom) + require.Equal(t, scenario.model, request.payload["model"]) + if scenario.protocol == "anthropic" { + require.Equal(t, "synthetic-gateway-key", request.key) + require.Empty(t, request.authorization) + } else { + require.Equal(t, "Bearer synthetic-gateway-key", request.authorization) + } + } + body := recorder.Body.String() + require.Contains(t, body, "synthetic answer") + require.Equal(t, 1, strings.Count(body, `"type":"test_complete"`)) + require.Contains(t, body, `"success":true`) + require.NotContains(t, body, `"type":"error"`) + require.Zero(t, repo.writes.Load()) + require.Equal(t, before, repo.account, "probe must preserve neutral identity, credentials and runtime state") + }) + } + } +} + +func TestGatewayAccountConnectionUpstreamFailureAndEOF(t *testing.T) { + for _, protocol := range []string{"responses", "chat", "anthropic", "gemini"} { + for _, status := range []int{http.StatusUnauthorized, http.StatusForbidden, http.StatusTooManyRequests, http.StatusOK} { + t.Run(protocol+"/"+strconv.Itoa(status), func(t *testing.T) { + var hits atomic.Int64 + origin := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + hits.Add(1) + w.WriteHeader(status) + if status != http.StatusOK { + _, _ = io.WriteString(w, `{"error":{"message":"synthetic rejection"}}`) + } + })) + defer origin.Close() + platform, model := service.PlatformOpenAI, "gpt-6.1-sol" + if protocol == "anthropic" { + platform, model = service.PlatformAnthropic, "claude-sonnet-4-6" + } + if protocol == "gemini" { + platform, model = service.PlatformGemini, "gemini-3.1-pro" + } + repo, cfg := gatewayTestFixture(origin.URL, platform) + if protocol == "chat" { + repo.account.Extra[openai_compat.ExtraKeyResponsesSupported] = false + } + before := cloneGatewayTestAccount(repo.account) + router, transport := newGatewayTestRouter(repo, cfg) + recorder := gatewayTestRequest(router, context.Background(), `{"model_id":"`+model+`"}`) + require.Equal(t, int64(1), hits.Load()) + require.Equal(t, int64(1), transport.calls.Load(), "failure must not probe another protocol or model") + require.Equal(t, int64(1), transport.closed.Load()) + body := recorder.Body.String() + require.Equal(t, 1, strings.Count(body, `"type":"error"`)) + require.Zero(t, strings.Count(body, `"type":"test_complete"`)) + require.NotContains(t, body, `"success":true`) + if status != http.StatusOK { + require.Contains(t, body, "synthetic rejection") + } + require.Zero(t, repo.writes.Load()) + require.Equal(t, before, repo.account) + }) + } + } +} + +func TestGatewayAccountConnectionAdmissionNoEgress(t *testing.T) { + for _, scenario := range []string{"empty-model", "ambiguous-model", "multiple-groups", "wrong-group", "observer", "unbound", "oauth-group", "disabled-group", "allowlist", "binding-scope", "source-scope", "changed-key", "changed-proxy", "unsupported-model", "wrong-family", "unsafe-url", "mode"} { + t.Run(scenario, func(t *testing.T) { + repo, cfg := gatewayTestFixture("https://gateway.example/tenant/v1", service.PlatformOpenAI) + ctx := context.Background() + body := `{"model_id":"gpt-6.1-sol"}` + switch scenario { + case "empty-model": + body = `{}` + case "ambiguous-model": + repo.group.Platform = service.PlatformComposite + body = `{"model_id":"unknown-alias"}` + case "multiple-groups": + repo.account.GroupIDs = []int64{1010, 1011} + case "wrong-group": + body = `{"model_id":"gpt-6.1-sol","group_id":1011}` + case "observer": + ctx = service.WithObserverScope(ctx, []int64{1011}) + case "unbound": + repo.live = cloneGatewayTestAccount(repo.account) + repo.live.GroupIDs, repo.live.AccountGroups = nil, nil + case "oauth-group": + repo.group.RequireOAuthOnly = true + case "disabled-group": + repo.group.Status = service.StatusDisabled + case "allowlist": + repo.group.ModelAllowlist = service.GroupModelAllowlist{Enabled: true, Models: []string{"other-model"}} + case "binding-scope": + repo.account.AccountGroups[0].AllowedModels = []string{"other-model"} + case "source-scope": + repo.account.Credentials["model_mapping"] = map[string]any{"public-alias": "gpt-6.1-sol"} + case "changed-key": + repo.live = cloneGatewayTestAccount(repo.account) + repo.live.Credentials["api_key"] = "changed-synthetic-key" + case "changed-proxy": + repo.live = cloneGatewayTestAccount(repo.account) + id := int64(9) + repo.live.ProxyID = &id + case "unsupported-model": + body = `{"model_id":"text-embedding-3-large"}` + case "wrong-family": + body = `{"model_id":"claude-sonnet-4-6"}` + case "unsafe-url": + cfg.Security.URLAllowlist.Enabled = true + cfg.Security.URLAllowlist.UpstreamHosts = []string{"allowed.example"} + case "mode": + body = `{"model_id":"gpt-6.1-sol","mode":"compact"}` + } + router, transport := newGatewayTestRouter(repo, cfg) + recorder := gatewayTestRequest(router, ctx, body) + require.Zero(t, transport.calls.Load(), "rejected gateway scope must not leave the process") + require.Contains(t, recorder.Body.String(), `"type":"error"`) + require.NotContains(t, recorder.Body.String(), `"success":true`) + require.Zero(t, repo.writes.Load()) + }) + } +} + +func TestGatewayAccountConnectionExplicitCompositeRoute(t *testing.T) { + var hits atomic.Int64 + origin := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + hits.Add(1) + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, gatewayTestStream("responses")) + })) + defer origin.Close() + repo, cfg := gatewayTestFixture(origin.URL, service.PlatformComposite) + repo.account.GroupIDs = []int64{1010, 1011} + repo.account.Credentials["model_mapping"] = map[string]any{"public-selected": "private-wire-alias"} + router, transport := newGatewayTestRouter(repo, cfg) + ctx := service.WithObserverScope(context.Background(), []int64{1010}) + recorder := gatewayTestRequest(router, ctx, `{"model_id":"public-selected","group_id":1010,"platform":"openai"}`) + require.Contains(t, recorder.Body.String(), `"success":true`) + require.Equal(t, int64(1), hits.Load()) + require.Equal(t, int64(1), transport.closed.Load()) + require.Zero(t, repo.writes.Load()) +} + +func TestGatewayAccountConnectionCancellationReleasesReader(t *testing.T) { + entered, cancelled := make(chan struct{}), make(chan struct{}) + firstRead := make(chan struct{}) + var hits atomic.Int64 + origin := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + if hits.Add(1) == 1 { + _, _ = io.WriteString(w, "data: {\"type\":\"response.output_text.delta\",\"delta\":\"partial\"}\n\n") + timingFlush(w) + close(entered) + <-r.Context().Done() + close(cancelled) + return + } + _, _ = io.WriteString(w, gatewayTestStream("responses")) + })) + defer origin.Close() + repo, cfg := gatewayTestFixture(origin.URL, service.PlatformOpenAI) + router, transport := newGatewayTestRouter(repo, cfg) + transport.firstRead = firstRead + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + finished := make(chan *httptest.ResponseRecorder, 1) + go func() { finished <- gatewayTestRequest(router, ctx, `{"model_id":"gpt-6.1-sol"}`) }() + timingWait(t, entered) + // Server Flush precedes client response acquisition. Wait for the native + // parser's first positive body read so cancellation exercises an owned reader. + timingWait(t, firstRead) + cancel() + select { + case recorder := <-finished: + require.NotContains(t, recorder.Body.String(), `"success":true`) + case <-time.After(10 * time.Second): + t.Fatal("cancelled gateway handler did not return") + } + timingWait(t, cancelled) + require.Equal(t, int64(1), transport.closed.Load()) + // The next probe uses the same account/concurrency budget after cancellation. + recorder := gatewayTestRequest(router, context.Background(), `{"model_id":"gpt-6.1-sol","group_id":1010,"platform":"openai"}`) + require.Contains(t, recorder.Body.String(), `"success":true`) + require.Equal(t, int64(2), hits.Load()) + require.Equal(t, int64(2), transport.calls.Load()) + require.Equal(t, int64(2), transport.closed.Load()) + require.Zero(t, repo.writes.Load()) +} diff --git a/backend/internal/integration/accountconnectiontiming/gateway_account_diagnostic_test.go b/backend/internal/integration/accountconnectiontiming/gateway_account_diagnostic_test.go new file mode 100644 index 000000000000..ba581c9fee9e --- /dev/null +++ b/backend/internal/integration/accountconnectiontiming/gateway_account_diagnostic_test.go @@ -0,0 +1,338 @@ +//go:build unit + +package accountconnectiontiming + +import ( + "context" + "errors" + "io" + "maps" + "net/http" + "net/http/httptest" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/handler/admin" + "github.com/Wei-Shaw/sub2api/internal/repository" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +type gatewayDiagnosticAccounts struct { + service.AccountRepository + mu sync.Mutex + account *service.Account + groups map[int64]*service.Group + live map[int64]*service.Account + readErr map[int64]error + admitted []int64 + writes atomic.Int64 +} + +func (r *gatewayDiagnosticAccounts) GetByID(context.Context, int64) (*service.Account, error) { + r.mu.Lock() + defer r.mu.Unlock() + return cloneGatewayTestAccount(r.account), nil +} + +func (r *gatewayDiagnosticAccounts) GatewayRequestAccount(_ context.Context, _, id int64) (*service.Account, *service.Group, error) { + r.mu.Lock() + defer r.mu.Unlock() + r.admitted = append(r.admitted, id) + if err := r.readErr[id]; err != nil { + return nil, nil, err + } + current := r.account + if live := r.live[id]; live != nil { + current = live + } + return cloneGatewayTestAccount(current), r.groups[id], nil +} + +func (r *gatewayDiagnosticAccounts) SetError(context.Context, int64, string) error { + r.writes.Add(1) + return nil +} + +func (r *gatewayDiagnosticAccounts) UpdateExtra(context.Context, int64, map[string]any) error { + r.writes.Add(1) + return nil +} + +func gatewayDiagnosticFixture(base, platform string) (*gatewayDiagnosticAccounts, *config.Config) { + fixture, cfg := gatewayTestFixture(base, platform) + // Match createAccountRecord's stored gateway default, without enabling it. + fixture.account.Schedulable = false + return &gatewayDiagnosticAccounts{account: fixture.account, groups: map[int64]*service.Group{1010: fixture.group}}, cfg +} + +func gatewayDiagnosticRouter(repo service.AccountRepository, cfg *config.Config, recovery *service.RateLimitService) (*gin.Engine, *gatewayTestTransport) { + upstream := &gatewayTestTransport{HTTPUpstream: repository.NewHTTPUpstream(cfg), seen: make(chan gatewayTestEgress, 16)} + svc := service.NewAccountTestService(repo, nil, nil, nil, nil, upstream, cfg, nil) + if recovery == nil { + // Retain the nonnil recovery sentinel: an accidental callback must fail. + recovery = &service.RateLimitService{} + } + h := admin.NewAccountHandler(nil, nil, nil, nil, nil, nil, recovery, nil, svc, nil, nil, nil, nil, nil) + router := gin.New() + router.POST("/api/v1/admin/accounts/:id/test", h.Test) + return router, upstream +} + +func TestGatewayAccountConnectionNonSchedulableDiagnostic(t *testing.T) { + for _, kind := range []string{"new_api", "sub2api"} { + for _, state := range []string{"creation-default", "performance-paused", "error", "global-cooldown", "temporary-cooldown", "overloaded", "model-cooldown", "expired"} { + t.Run(kind+"/"+state, func(t *testing.T) { + var hits atomic.Int64 + origin := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + hits.Add(1) + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, gatewayTestStream("responses")) + })) + defer origin.Close() + repo, cfg := gatewayDiagnosticFixture(origin.URL, service.PlatformOpenAI) + repo.account.Credentials["upstream_kind"] = kind + future, past := time.Now().Add(time.Hour), time.Now().Add(-time.Hour) + switch state { + case "performance-paused": + repo.account.PerformancePaused = true + case "error": + repo.account.Status, repo.account.ErrorMessage = service.StatusError, "synthetic existing error" + case "global-cooldown": + repo.account.RateLimitResetAt = &future + case "temporary-cooldown": + repo.account.TempUnschedulableUntil = &future + case "overloaded": + repo.account.OverloadUntil = &future + case "model-cooldown": + repo.account.Extra["model_rate_limits"] = map[string]any{"gpt-6.1-sol": map[string]any{"rate_limit_reset_at": future.Format(time.RFC3339)}} + case "expired": + repo.account.ExpiresAt, repo.account.AutoPauseOnExpired = &past, true + } + before := cloneGatewayTestAccount(repo.account) + router, transport := gatewayDiagnosticRouter(repo, cfg, nil) + recorder := gatewayTestRequest(router, context.Background(), `{"model_id":"gpt-6.1-sol"}`) + require.Contains(t, recorder.Body.String(), `"success":true`) + require.Equal(t, 1, strings.Count(recorder.Body.String(), `"type":"test_complete"`)) + require.Equal(t, int64(1), hits.Load()) + require.Equal(t, int64(1), transport.calls.Load()) + require.Equal(t, int64(1), transport.closed.Load()) + require.Zero(t, repo.writes.Load()) + require.Equal(t, before, repo.account) + }) + } + } +} + +type gatewayRecoverySpy struct { + service.AccountRepository + repo *gatewayDiagnosticAccounts + reads atomic.Int64 + writes atomic.Int64 + canceled atomic.Bool +} + +func (r *gatewayRecoverySpy) GetByID(ctx context.Context, id int64) (*service.Account, error) { + r.reads.Add(1) + if ctx.Err() != nil { + r.canceled.Store(true) + } + return r.repo.GetByID(ctx, id) +} + +func (r *gatewayRecoverySpy) clear(ctx context.Context, field string) error { + r.writes.Add(1) + if ctx.Err() != nil { + r.canceled.Store(true) + } + r.repo.mu.Lock() + defer r.repo.mu.Unlock() + switch field { + case "error": + r.repo.account.Status, r.repo.account.ErrorMessage = service.StatusActive, "" + case "global": + r.repo.account.RateLimitedAt, r.repo.account.RateLimitResetAt, r.repo.account.OverloadUntil = nil, nil, nil + case "quota": + delete(r.repo.account.Extra, "antigravity_quota_scopes") + case "model": + delete(r.repo.account.Extra, "model_rate_limits") + case "temporary": + r.repo.account.TempUnschedulableUntil = nil + } + return nil +} + +func (r *gatewayRecoverySpy) ClearError(ctx context.Context, _ int64) error { + return r.clear(ctx, "error") +} + +func (r *gatewayRecoverySpy) ClearRateLimit(ctx context.Context, _ int64) error { + return r.clear(ctx, "global") +} + +func (r *gatewayRecoverySpy) ClearAntigravityQuotaScopes(ctx context.Context, _ int64) error { + return r.clear(ctx, "quota") +} + +func (r *gatewayRecoverySpy) ClearModelRateLimits(ctx context.Context, _ int64) error { + return r.clear(ctx, "model") +} + +func (r *gatewayRecoverySpy) ClearTempUnschedulable(ctx context.Context, _ int64) error { + return r.clear(ctx, "temporary") +} + +func TestGatewayAccountConnectionSuccessSkipsRecoveryAfterKeepaliveCleanup(t *testing.T) { + for _, legacy := range []bool{false, true} { + t.Run(map[bool]string{false: "gateway-observation", true: "legacy-recovers"}[legacy], func(t *testing.T) { + entered, release := make(chan struct{}), make(chan struct{}) + var hits atomic.Int64 + origin := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + hits.Add(1) + close(entered) + select { + case <-release: + case <-r.Context().Done(): + return + } + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, gatewayTestStream("responses")) + })) + defer origin.Close() + repo, cfg := gatewayDiagnosticFixture(origin.URL, service.PlatformOpenAI) + past := time.Now().Add(-time.Hour) + repo.account.RateLimitResetAt = &past + // Isolate cleanup from the separate default-false diagnostic case: + // this gateway already passes the old forwarding health gate. + repo.account.Schedulable = true + if legacy { + repo.account.Platform, repo.account.Type = service.PlatformOpenAI, service.AccountTypeAPIKey + repo.account.Status, repo.account.ErrorMessage = service.StatusError, "synthetic preexisting error" + } + spy := &gatewayRecoverySpy{repo: repo} + recovery := service.NewRateLimitService(spy, nil, cfg, nil, nil) + router, transport := gatewayDiagnosticRouter(repo, cfg, recovery) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + finished := make(chan *httptest.ResponseRecorder, 1) + go func() { finished <- gatewayTestRequest(router, ctx, `{"model_id":"gpt-6.1-sol"}`) }() + timingWait(t, entered) + // A cooldown added while the test is in flight must also survive an + // observational gateway success, even when the old global reset expired. + repo.mu.Lock() + repo.account.Extra = maps.Clone(repo.account.Extra) + repo.account.Extra["model_rate_limits"] = map[string]any{"unrelated-model": map[string]any{"rate_limit_reset_at": time.Now().Add(time.Hour).Format(time.RFC3339)}} + before := cloneGatewayTestAccount(repo.account) + repo.mu.Unlock() + close(release) + select { + case recorder := <-finished: + require.Contains(t, recorder.Body.String(), `"success":true`) + require.Equal(t, 1, strings.Count(recorder.Body.String(), `"type":"test_complete"`)) + case <-ctx.Done(): + t.Fatal("handler did not finish after upstream completion") + } + require.Equal(t, int64(1), hits.Load()) + require.Equal(t, int64(1), transport.closed.Load()) + require.Zero(t, repo.writes.Load()) + require.False(t, spy.canceled.Load(), "legacy recovery must receive the original valid context") + if legacy { + require.Equal(t, int64(2), spy.reads.Load()) + require.Equal(t, int64(5), spy.writes.Load()) + require.Equal(t, service.StatusActive, repo.account.Status) + require.Nil(t, repo.account.RateLimitResetAt) + require.NotContains(t, repo.account.Extra, "model_rate_limits") + } else { + require.Zero(t, spy.reads.Load()) + require.Zero(t, spy.writes.Load()) + require.Equal(t, before, repo.account) + } + }) + } +} + +func TestGatewayAccountConnectionAdminMultiGroupSelection(t *testing.T) { + for _, kind := range []string{"new_api", "sub2api"} { + for _, scenario := range []string{"unique-cross-platform", "observer-filter", "inactive-group", "removed-membership", "binding-filter", "allowlist-filter", "no-eligible-route", "same-protocol-ambiguous", "composite-private-alias", "storage-error", "explicit-route", "explicit-unauthorized"} { + t.Run(kind+"/"+scenario, func(t *testing.T) { + var hits atomic.Int64 + origin := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + hits.Add(1) + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, gatewayTestStream("responses")) + })) + defer origin.Close() + repo, cfg := gatewayDiagnosticFixture(origin.URL, service.PlatformOpenAI) + repo.account.Credentials["upstream_kind"] = kind + repo.account.GroupIDs = []int64{1011, 1010} + repo.account.AccountGroups = []service.AccountGroup{{GroupID: 1011}, {GroupID: 1010}} + repo.groups[1011] = &service.Group{ID: 1011, Platform: service.PlatformAnthropic, Status: service.StatusActive, Hydrated: true} + ctx := context.Background() + body := `{"model_id":"gpt-6.1-sol"}` + wantSuccess := true + switch scenario { + case "observer-filter": + repo.groups[1011].Platform = service.PlatformOpenAI + ctx = service.WithObserverScope(ctx, []int64{1010}) + case "inactive-group": + repo.groups[1011].Platform, repo.groups[1011].Status = service.PlatformOpenAI, service.StatusDisabled + case "removed-membership": + repo.groups[1011].Platform = service.PlatformOpenAI + live := cloneGatewayTestAccount(repo.account) + live.GroupIDs = []int64{1010} + live.AccountGroups = []service.AccountGroup{{GroupID: 1010}} + repo.live = map[int64]*service.Account{1011: live} + case "binding-filter": + repo.groups[1011].Platform = service.PlatformOpenAI + repo.account.AccountGroups[0].AllowedModels = []string{"other-model"} + case "allowlist-filter": + repo.groups[1011].Platform = service.PlatformOpenAI + repo.groups[1011].ModelAllowlist = service.GroupModelAllowlist{Enabled: true, Models: []string{"other-model"}} + case "no-eligible-route": + repo.groups[1010].Platform = service.PlatformAnthropic + wantSuccess = false + case "same-protocol-ambiguous": + repo.groups[1011].Platform = service.PlatformOpenAI + wantSuccess = false + case "composite-private-alias": + repo.groups[1010].Platform, repo.groups[1011].Platform = service.PlatformComposite, service.PlatformComposite + repo.account.Credentials["model_mapping"] = map[string]any{"public-selected": "private-wire-alias"} + body, wantSuccess = `{"model_id":"public-selected"}`, false + case "storage-error": + repo.readErr = map[int64]error{1011: errors.New("synthetic read failure")} + wantSuccess = false + case "explicit-route": + repo.groups[1011].Platform = service.PlatformOpenAI + body = `{"model_id":"gpt-6.1-sol","group_id":1010,"platform":"openai"}` + case "explicit-unauthorized": + ctx = service.WithObserverScope(ctx, []int64{1011}) + body, wantSuccess = `{"model_id":"gpt-6.1-sol","group_id":1010,"platform":"openai"}`, false + } + before := cloneGatewayTestAccount(repo.account) + router, transport := gatewayDiagnosticRouter(repo, cfg, nil) + recorder := gatewayTestRequest(router, ctx, body) + if wantSuccess { + require.Contains(t, recorder.Body.String(), `"success":true`) + require.Equal(t, int64(1), hits.Load()) + require.Equal(t, int64(1), transport.calls.Load()) + require.Equal(t, int64(1), transport.closed.Load()) + } else { + require.Contains(t, recorder.Body.String(), `"type":"error"`) + require.NotContains(t, recorder.Body.String(), `"success":true`) + require.Zero(t, hits.Load()) + require.Zero(t, transport.calls.Load()) + } + if scenario == "observer-filter" || scenario == "explicit-route" { + require.Equal(t, []int64{1010}, repo.admitted) + } + require.Zero(t, repo.writes.Load()) + require.Equal(t, before, repo.account) + }) + } + } +} diff --git a/backend/internal/service/account_test_gateway.go b/backend/internal/service/account_test_gateway.go new file mode 100644 index 000000000000..ef0e95aade69 --- /dev/null +++ b/backend/internal/service/account_test_gateway.go @@ -0,0 +1,185 @@ +package service + +import ( + "context" + "fmt" + "maps" + "slices" + "strings" + + "github.com/Wei-Shaw/sub2api/internal/domain" + "github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey" + "github.com/Wei-Shaw/sub2api/internal/pkg/openai_compat" + "github.com/gin-gonic/gin" +) + +type gatewayAccountTestKey struct{} + +// IsGatewayAccountTest identifies an observational probe of a shared gateway. +// Neither upstream failures nor a successful probe change its scheduling state. +func IsGatewayAccountTest(ctx context.Context) bool { + probe, _ := ctx.Value(gatewayAccountTestKey{}).(bool) + return probe +} + +func (s *AccountTestService) testGatewayAccountConnection(c *gin.Context, selected *Account, model, prompt, mode string, opts AccountTestOptions) error { + ctx := context.WithValue(c.Request.Context(), gatewayAccountTestKey{}, true) + c.Request = c.Request.WithContext(ctx) + model = strings.TrimSpace(model) + if model == "" || (mode != "" && mode != AccountTestModeDefault && mode != AccountTestModeGrokText) || opts.ImageDataURL != "" || opts.AudioDataURL != "" { + return s.sendErrorAndEnd(c, "Gateway connection tests require a selected text model and default mode") + } + groupID := opts.GroupID + if groupID < 0 { + return s.sendErrorAndEnd(c, ErrGatewayAccountGroup.Error()) + } + if groupID == 0 { + if group, _ := ctx.Value(ctxkey.Group).(*Group); group != nil { + groupID = group.ID + } + } + if groupID != 0 && !ObserverCanManageGroup(ctx, groupID) { + return s.sendErrorAndEnd(c, ErrObserverScope.Error()) + } + groupIDs := []int64{groupID} + if groupID == 0 { + groupIDs = slices.Clone(selected.GroupIDs) + for _, binding := range selected.AccountGroups { + groupIDs = append(groupIDs, binding.GroupID) + } + slices.Sort(groupIDs) + groupIDs = slices.Compact(groupIDs) + } + reader := gatewayAccountReader(s.accountRepo, nil) + if reader == nil { + return s.sendErrorAndEnd(c, "Gateway connection test admission is unavailable") + } + var route *gatewayAccountTestRoute + eligible := 0 + for _, id := range groupIDs { + if id <= 0 { + return s.sendErrorAndEnd(c, ErrGatewayAccountGroup.Error()) + } + if !ObserverCanManageGroup(ctx, id) { + continue + } + current, group, err := reader.GatewayRequestAccount(ctx, selected.ID, id) + // Storage uncertainty cannot be treated as an ineligible route: doing so + // could turn an ambiguous request into an arbitrary first-group choice. + if err != nil || current == nil || group == nil || group.ID != id { + return s.sendErrorAndEnd(c, "Gateway connection test could not load the account and selected group") + } + if current.ID != selected.ID || !current.IsGateway() || current.Platform != PlatformGateway || + ValidateGatewayAccountIdentity(current.Platform, current.Type, current.Credentials) != nil || current.ParentAccountID != nil || current.AuthConnectionID != "" { + return s.sendErrorAndEnd(c, ErrGatewayAccountIdentity.Error()) + } + candidate, err := resolveGatewayAccountTestRoute(ctx, selected, current, group, model, opts.Platform) + if err != nil { + return s.sendErrorAndEnd(c, fmt.Sprintf("Gateway connection test admission failed: %s", err.Error())) + } + if candidate != nil { + route = candidate + eligible++ + } + } + if eligible == 0 { + return s.sendErrorAndEnd(c, "Gateway connection test has no eligible model protocol and group; select a supported text model or explicit group_id/platform") + } + if eligible != 1 { + return s.sendErrorAndEnd(c, "Gateway connection test has multiple eligible groups; select an explicit group_id") + } + c.Request = c.Request.WithContext(route.ctx) + probe := &AccountTestService{accountRepo: s.accountRepo, httpUpstream: s.httpUpstream, cfg: s.cfg, tlsFPProfileService: s.tlsFPProfileService} + switch route.family { + case domain.PlatformGatewayOpenAI: + return probe.testOpenAIAccountConnection(c, route.account, route.model, prompt, AccountTestModeDefault) + case domain.PlatformGatewayAnthropic: + return probe.testClaudeAccountConnection(c, route.account, route.model) + case domain.PlatformGatewayGemini: + return probe.testGeminiAccountConnection(c, route.account, route.model, prompt) + default: + return s.sendErrorAndEnd(c, "Selected gateway protocol is not supported by connection tests") + } +} + +type gatewayAccountTestRoute struct { + ctx context.Context + account *Account + model string + family domain.PlatformGateway +} + +// A nil route is a known policy/protocol exclusion, not a storage failure. +func resolveGatewayAccountTestRoute(ctx context.Context, selected, current *Account, group *Group, model, platform string) (*gatewayAccountTestRoute, error) { + // Resolve on a copy: lazy model caches must not mutate the stored identity. + scope := *current + scope.Credentials = maps.Clone(current.Credentials) + scope.modelMappingCacheReady = false + wireModel := scope.GetMappedModel(model) + target := strings.TrimSpace(platform) + if target == "" { + target, _ = ResolvedTargetPlatformFromContext(ctx) + } + if target == "" && group.Platform != PlatformComposite { + target = group.Platform + } + detected, known := DetectModelPlatform(wireModel) + if target == "" && known { + target = detected + } + spec, concrete := domain.LookupPlatform(target) + if !concrete || target == PlatformTypeSafe { + return nil, nil + } + family := spec.Gateway + if target == PlatformAntigravity && known { + if detectedSpec, ok := domain.LookupPlatform(detected); ok { + family = detectedSpec.Gateway + } + } + if known { + detectedSpec, _ := domain.LookupPlatform(detected) + if detectedSpec.Gateway != family || detected == PlatformTypeSafe { + return nil, nil + } + } + if !gatewayAccountTestTextModel(wireModel) { + return nil, nil + } + ctx = context.WithValue(ctx, ctxkey.Group, group) + ctx = WithResolvedTargetPlatform(ctx, target) + view, err := gatewayDiagnosticAccountFromSnapshot(ctx, selected, current, group, family, model) + if err != nil { + if err == ErrGatewayAccountGroup || err == ErrGatewayProtocolsPending { + return nil, nil + } + return nil, err + } + // Admission checked the public source key and group policy. Apply its mapping + // exactly once, including wildcard aliases, before entering native adapters. + view.Credentials["model_mapping"] = map[string]any{wireModel: wireModel} + view.modelMappingCacheReady = false + // Probes use the site's own key and proxy, never provider plugins or borrowed + // credentials. Keep the existing explicit Responses/Chat selection only. + view.Extra = map[string]any{ + openai_compat.ExtraKeyResponsesMode: current.Extra[openai_compat.ExtraKeyResponsesMode], + openai_compat.ExtraKeyResponsesSupported: current.Extra[openai_compat.ExtraKeyResponsesSupported], + } + return &gatewayAccountTestRoute{ctx: ctx, account: view, model: wireModel, family: family}, nil +} + +func gatewayAccountTestTextModel(model string) bool { + name := strings.ToLower(strings.TrimSpace(model)) + if slash := strings.LastIndexByte(name, '/'); slash >= 0 { + name = name[slash+1:] + } + if name == "" || strings.Contains(name, "image") || strings.Contains(name, "video") || strings.Contains(name, "audio") || strings.Contains(name, "embedding") || strings.Contains(name, "moderation") { + return false + } + for _, prefix := range []string{"tts-", "whisper-", "dall-e-", "grok-voice", "jev-"} { + if strings.HasPrefix(name, prefix) { + return false + } + } + return true +} diff --git a/backend/internal/service/account_test_service.go b/backend/internal/service/account_test_service.go index f178cb697fe3..3985ede88a4e 100644 --- a/backend/internal/service/account_test_service.go +++ b/backend/internal/service/account_test_service.go @@ -76,6 +76,8 @@ type TestEvent struct { type AccountTestOptions struct { ImageDataURL string AudioDataURL string + GroupID int64 + Platform string } func firstAccountTestOptions(opts []AccountTestOptions) AccountTestOptions { @@ -390,7 +392,13 @@ func (s *AccountTestService) TestAccountConnection(c *gin.Context, accountID int if testErr == nil { testErr = c.Request.Context().Err() } + gatewayProbe := IsGatewayAccountTest(c.Request.Context()) stopKeepalive() + // Keepalive restores the caller's uncancelled context for legacy health + // recovery. Preserve only the trusted diagnostic classification on it. + if gatewayProbe { + c.Request = c.Request.WithContext(context.WithValue(c.Request.Context(), gatewayAccountTestKey{}, true)) + } s.finishAccountConnectionTiming(c, collector, testErr) }() started := requesttiming.AccountTestStarted(start) @@ -410,7 +418,7 @@ func (s *AccountTestService) TestAccountConnection(c *gin.Context, accountID int } bindAccountTestPlatform(c, account) if account.gatewayProtocolsPending() { - return s.sendErrorAndEnd(c, ErrGatewayProtocolsPending.Error()) + return s.testGatewayAccountConnection(c, account, modelID, prompt, mode, testOpts) } recordQualityBatchRoute(c, account, modelID, account.Platform+":"+account.GetAPIProtocol()) if expected, ok := ctx.Value(modelTraceContextKey{}).(modelTraceEnvironment); ok { @@ -739,7 +747,7 @@ func (s *AccountTestService) testClaudeAccountConnection(c *gin.Context, account errMsg := fmt.Sprintf("API returned %d: %s", resp.StatusCode, string(body)) // 403 表示账号被上游封禁,标记为 error 状态 - if resp.StatusCode == http.StatusForbidden && !isOAuth429Execution(ctx) { + if resp.StatusCode == http.StatusForbidden && !isOAuth429Execution(ctx) && !IsGatewayAccountTest(ctx) { _ = s.accountRepo.SetError(ctx, account.ID, errMsg) } @@ -1191,7 +1199,7 @@ func (s *AccountTestService) testOpenAIAccountConnection(c *gin.Context, account } } // 401 Unauthorized: 标记账号为永久错误 - if resp.StatusCode == http.StatusUnauthorized && s.accountRepo != nil && !IsAstraSourceAcquisition(ctx) && !aiRecoveryProbe { + if resp.StatusCode == http.StatusUnauthorized && s.accountRepo != nil && !IsAstraSourceAcquisition(ctx) && !aiRecoveryProbe && !IsGatewayAccountTest(ctx) { errMsg := fmt.Sprintf("Authentication failed (401): %s", string(body)) if !isOAuth429Execution(ctx) { _ = s.accountRepo.SetError(ctx, account.ID, errMsg) @@ -2529,7 +2537,7 @@ func (s *AccountTestService) testOpenAIChatCompletionsConnection( if resp.StatusCode == http.StatusTooManyRequests { s.reconcileOpenAI429State(ctx, account, resp.Header, body) } - if resp.StatusCode == http.StatusUnauthorized && s.accountRepo != nil { + if resp.StatusCode == http.StatusUnauthorized && s.accountRepo != nil && !IsGatewayAccountTest(ctx) { errMsg := fmt.Sprintf("Chat Completions authentication failed (401): %s", string(body)) if !isOAuth429Execution(ctx) { _ = s.accountRepo.SetError(ctx, account.ID, errMsg) diff --git a/backend/internal/service/gateway_protocol_admission.go b/backend/internal/service/gateway_protocol_admission.go index 1988429963ef..6aa1d9d467f2 100644 --- a/backend/internal/service/gateway_protocol_admission.go +++ b/backend/internal/service/gateway_protocol_admission.go @@ -118,6 +118,17 @@ func prepareGatewayProtocolAccount(ctx context.Context, selected *Account, reade } func gatewayProtocolAccountFromSnapshot(ctx context.Context, selected, current *Account, liveGroup *Group, family domain.PlatformGateway, model string) (*Account, error) { + return gatewayProtocolAccountFromSnapshotPolicy(ctx, selected, current, liveGroup, family, model, true) +} + +// Diagnostics retain identity and model policy without requiring forwarding +// eligibility. A paused or cooling account must remain available for diagnosis; +// no scheduling flag or health state on the account is changed to admit it. +func gatewayDiagnosticAccountFromSnapshot(ctx context.Context, selected, current *Account, liveGroup *Group, family domain.PlatformGateway, model string) (*Account, error) { + return gatewayProtocolAccountFromSnapshotPolicy(ctx, selected, current, liveGroup, family, model, false) +} + +func gatewayProtocolAccountFromSnapshotPolicy(ctx context.Context, selected, current *Account, liveGroup *Group, family domain.PlatformGateway, model string, enforceScheduling bool) (*Account, error) { group, _ := ctx.Value(ctxkey.Group).(*Group) if selected == nil || group == nil || model == "" { return nil, ErrGatewayProtocolsPending @@ -225,7 +236,7 @@ func gatewayProtocolAccountFromSnapshot(ctx context.Context, selected, current * delete(view.Extra, key) } view.modelMappingCacheReady = false - if !view.IsSchedulableForModelWithContext(ctx, selectionModel) || !view.IsSchedulableForModelWithContext(ctx, model) { + if enforceScheduling && (!view.IsSchedulableForModelWithContext(ctx, selectionModel) || !view.IsSchedulableForModelWithContext(ctx, model)) { return nil, ErrGatewayProtocolsPending } if family == domain.PlatformGatewayAnthropic {