From 7a417668d54ab1fc5bade1447a5145cf930d96dc Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sat, 14 Nov 2026 19:13:09 +0800 Subject: [PATCH 1/8] test: define selected upstream moderation acceptance and remote baseline --- .../workflows/moderation-upstream-scope.yml | 71 +++++++++++++++++++ .../handler/moderation_upstream_scope_test.go | 51 +++++++++++++ 2 files changed, 122 insertions(+) create mode 100644 .github/workflows/moderation-upstream-scope.yml create mode 100644 backend/internal/handler/moderation_upstream_scope_test.go diff --git a/.github/workflows/moderation-upstream-scope.yml b/.github/workflows/moderation-upstream-scope.yml new file mode 100644 index 000000000000..e62f8d6b7eb7 --- /dev/null +++ b/.github/workflows/moderation-upstream-scope.yml @@ -0,0 +1,71 @@ +name: Moderation upstream scope acceptance +on: + push: + branches: [feat/moderation-upstream-account-scope] + workflow_dispatch: +permissions: + contents: read +concurrency: + group: moderation-upstream-scope-${{ github.ref }} + cancel-in-progress: false +jobs: + behavioral-red: + runs-on: ubuntu-latest + timeout-minutes: 25 + steps: + - uses: actions/checkout@v6 + with: + fetch-depth: 0 + - uses: actions/setup-go@v6 + with: + go-version-file: backend/go.mod + cache-dependency-path: backend/go.sum + - name: Pinned original implementation with candidate regression + run: | + mkdir -p "$RUNNER_TEMP/moderation-scope" + git rev-parse HEAD > "$RUNNER_TEMP/moderation-scope/head.txt" + cp backend/internal/handler/moderation_upstream_scope_test.go "$RUNNER_TEMP/scope_test.go" + git checkout --detach 4189ed821 + cp "$RUNNER_TEMP/scope_test.go" backend/internal/handler/moderation_upstream_scope_test.go + cd backend + set +e + go test ./internal/handler -run '^TestModerationUpstreamScopeUnselectedDoesNotAudit$' -count=1 -v > "$RUNNER_TEMP/moderation-scope/red.log" 2>&1 + result=$? + set -e + cat "$RUNNER_TEMP/moderation-scope/red.log" + test "$result" -ne 0 + ! grep -Eiq 'build failed|no tests to run|undefined:|--- SKIP:' "$RUNNER_TEMP/moderation-scope/red.log" + grep -q 'unselected upstream account must make zero audit calls' "$RUNNER_TEMP/moderation-scope/red.log" + - uses: actions/upload-artifact@v7 + if: always() + with: + name: moderation-scope-red-${{ github.sha }} + path: ${{ runner.temp }}/moderation-scope + ui-baseline: + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@v6 + - uses: pnpm/action-setup@v6 + with: + version: 9 + - uses: actions/setup-node@v6 + with: + node-version: '22' + cache: pnpm + cache-dependency-path: frontend/pnpm-lock.yaml + - run: pnpm --dir frontend install --frozen-lockfile + - name: Isolated browser + run: | + npm install --prefix "$RUNNER_TEMP/scope-browser" --no-save --ignore-scripts playwright@1.56.1 + node "$RUNNER_TEMP/scope-browser/node_modules/playwright/cli.js" install --with-deps chromium + - name: Render actual baseline settings + env: + EVIDENCE_DIR: ${{ runner.temp }}/moderation-scope-ui + SUB2API_PLAYWRIGHT_MODULE: ${{ runner.temp }}/scope-browser/node_modules/playwright/index.mjs + run: node .github/scripts/moderation-scope-preview.mjs + - uses: actions/upload-artifact@v7 + if: always() + with: + name: moderation-scope-ui-${{ github.sha }} + path: ${{ runner.temp }}/moderation-scope-ui diff --git a/backend/internal/handler/moderation_upstream_scope_test.go b/backend/internal/handler/moderation_upstream_scope_test.go new file mode 100644 index 000000000000..5d033ea61ee2 --- /dev/null +++ b/backend/internal/handler/moderation_upstream_scope_test.go @@ -0,0 +1,51 @@ +package handler + +import ( + "context" + "fmt" + "net/http" + "net/http/httptest" + "sync/atomic" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/service" + coderws "github.com/coder/websocket" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +// Uses the real handler, scheduler and forwarding transport. Both providers are +// loopback fixtures; counting actual received frames distinguishes admission +// from a configuration-only assertion. +func TestModerationUpstreamScopeUnselectedDoesNotAudit(t *testing.T) { + var audits, generationWrites atomic.Int32 + audit := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + audits.Add(1) + _, _ = w.Write([]byte(`{"results":[{"category_scores":{"sexual":0.99}}]}`)) + })) + defer audit.Close() + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + conn, err := coderws.Accept(w, r, nil) + if err != nil { return } + defer func() { _ = conn.CloseNow() }() + ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second) + defer cancel() + if _, _, err := conn.Read(ctx); err != nil { return } + generationWrites.Add(1) + _ = conn.Write(ctx, coderws.MessageText, []byte(`{"type":"response.completed","response":{"id":"resp_scope","model":"gpt-5.1","usage":{"input_tokens":1,"output_tokens":1}}}`)) + _, _, _ = conn.Read(ctx) + })) + defer upstream.Close() + h := newOpenAIWSPassthroughHandlerHarness(t, upstream.URL, map[string]string{ + service.SettingKeyContentModerationConfig: fmt.Sprintf(`{"enabled":true,"mode":"pre_block","all_groups":true,"sample_rate":100,"base_url":%q,"api_keys":["fixture-key"],"upstream_account_scope":"selected","upstream_account_ids":[9952]}`, audit.URL), + }) + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + require.NoError(t, h.clientConn.Write(ctx, coderws.MessageText, []byte(`{"type":"response.create","model":"gpt-5.1","input":"synthetic fixture text"}`))) + _, event, err := h.clientConn.Read(ctx) + require.NoError(t, err) + require.Equal(t, int32(0), audits.Load(), "unselected upstream account must make zero audit calls") + require.Equal(t, "response.completed", gjson.GetBytes(event, "type").String()) + require.Equal(t, int32(1), generationWrites.Load()) +} From 0ae69182fc6aba8a7e6896c047bedc446b946b89 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sat, 14 Nov 2026 19:13:25 +0800 Subject: [PATCH 2/8] test: include remote rendered baseline fixture and frozen scope design --- .github/scripts/moderation-scope-preview.mjs | 68 +++++++++++++++++++ .../moderation-upstream-account-scope.md | 15 ++++ 2 files changed, 83 insertions(+) create mode 100644 .github/scripts/moderation-scope-preview.mjs create mode 100644 docs/implementation/moderation-upstream-account-scope.md diff --git a/.github/scripts/moderation-scope-preview.mjs b/.github/scripts/moderation-scope-preview.mjs new file mode 100644 index 000000000000..b2bfa5aab20b --- /dev/null +++ b/.github/scripts/moderation-scope-preview.mjs @@ -0,0 +1,68 @@ +// Actual Vue view + shared components; synthetic API adapter; GitHub Actions only. +import assert from 'node:assert/strict' +import { createHash } from 'node:crypto' +import { execFileSync } from 'node:child_process' +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { createRequire } from 'node:module' +import { tmpdir } from 'node:os' +import { dirname, join } from 'node:path' +import { pathToFileURL } from 'node:url' +const repo=process.cwd(), root=join(repo,'frontend'), output=process.env.EVIDENCE_DIR +if(!output || !process.env.GITHUB_ACTIONS) throw Error('GitHub Actions only') +const req=createRequire(join(root,'package.json')) +const {createServer}=await import(pathToFileURL(join(dirname(req.resolve('vite/package.json')),'dist/node/index.js')).href) +const vue=(await import(pathToFileURL(req.resolve('@vitejs/plugin-vue')).href)).default +const {chromium}=await import(pathToFileURL(process.env.SUB2API_PLAYWRIGHT_MODULE).href) +const head=execFileSync('git',['rev-parse','HEAD'],{encoding:'utf8'}).trim() +const hash=x=>createHash('sha256').update(x).digest('hex') +const entryName=`.moderation-preview-${process.pid}.js`, entry=join(root,entryName), cacheDir=mkdtempSync(join(tmpdir(),'moderation-preview-')) +const captures=[],errors=[] +let server,browser +mkdirSync(output,{recursive:true}) +try{ +writeFileSync(entry,` +import {createApp} from 'vue'; import {createPinia} from 'pinia'; +import {createRouter,createMemoryHistory} from 'vue-router'; +import {i18n,loadLocaleMessages} from '/src/i18n/index.ts'; +import {apiClient} from '/src/api/client.ts'; +import View from '/src/views/admin/RiskControlView.vue'; import '/src/style.css'; +const locale=new URL(location.href).searchParams.get('locale')||'en'; +await loadLocaleMessages(locale);i18n.global.locale.value=locale; +const cfg={enabled:true,mode:'pre_block',base_url:'https://audit.example',model:'fixture-moderation',api_key_statuses:[],api_key_masks:[],api_key_count:0,timeout_ms:3000,sample_rate:100,all_groups:true,group_ids:[],worker_count:4,queue_size:32768,block_status:403,block_message:'Synthetic fixture',thresholds:{},blocked_keywords:[],model_filter:{type:'all',models:[]}}; +apiClient.defaults.adapter=async config=>{let data; const u=config.url; +if(u==='/admin/risk-control/config')data=cfg; +else if(u==='/admin/groups/all')data=[{id:4301,name:'Demo OpenAI',platform:'openai'},{id:4302,name:'Demo Anthropic',platform:'anthropic'}]; +else if(u==='/admin/proxies/all')data=[]; +else if(u==='/admin/risk-control/status')data={enabled:true,risk_control_enabled:true,mode:'pre_block',worker_count:4,api_key_statuses:[],pre_block_api_key_loads:[]}; +else if(u==='/admin/risk-control/logs')data={items:[],total:0,page:1,page_size:20}; +else throw Error('Unexpected offline API '+u); +return {config,status:200,statusText:'OK',headers:{},data:{code:0,data}};}; +const router=createRouter({history:createMemoryHistory(),routes:[{path:'/:pathMatch(.*)*',component:View}]}); +const app=createApp(View);app.use(createPinia());app.use(i18n);app.use(router);await router.isReady();app.mount('#app'); +window.__t=key=>i18n.global.t(key); +`,{flag:'wx'}) +process.chdir(root) +server=await createServer({root,configFile:false,cacheDir,resolve:{alias:{'@':join(root,'src')}},plugins:[{ +name:'fixture-layout',enforce:'pre',load(id){if(id===join(root,'src/components/layout/AppLayout.vue'))return ''}, +configureServer(vite){vite.middlewares.use((req,res,next)=>{if(req.url==='/'||req.url?.startsWith('/?')){res.setHeader('Content-Type','text/html');res.end('
')}else if(req.url==='/favicon.ico'){res.statusCode=204;res.end()}else next()})}},vue()],server:{host:'127.0.0.1',port:4299,strictPort:true},optimizeDeps:{entries:[],include:['vue','pinia','vue-router','vue-i18n','axios']}}) +await server.listen();browser=await chromium.launch({headless:true}) +for(const locale of ['en','zh'])for(const [device,width,height] of [['desktop',1280,1000],['mobile',390,844]]){ + const page=await browser.newPage({viewport:{width,height}}) + page.on('pageerror',e=>errors.push(e.message)) + await page.route('**/*',route=>new URL(route.request().url()).origin==='http://127.0.0.1:4299'?route.continue():route.abort()) + await page.goto('http://127.0.0.1:4299/?locale='+locale,{waitUntil:'networkidle'}) + const label=await page.evaluate(()=>window.__t('admin.riskControl.openSettings')) + await page.getByRole('button',{name:label,exact:true}).click() + const scope=await page.evaluate(()=>window.__t('admin.riskControl.tabs.scope')) + await page.getByRole('button',{name:scope,exact:true}).click() + await page.locator('[role="dialog"]').waitFor() + assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true) + const file='before-'+device+'-'+locale+'.png';await page.screenshot({path:join(output,file),fullPage:true}) + captures.push({file,sha256:hash(readFileSync(join(output,file))),viewport:{width,height},locale}) + await page.close() +} +assert.deepEqual(errors,[]) +}finally{ +writeFileSync(join(output,'manifest.json'),JSON.stringify({head,captures,errors,boundary:'Actual RiskControlView, BaseDialog, shared components, project CSS and locales. Layout shell fixture; synthetic offline axios API. No real upstreams.'},null,2)+'\n') +await browser?.close();await server?.close();rmSync(entry,{force:true});rmSync(cacheDir,{recursive:true,force:true}) +} diff --git a/docs/implementation/moderation-upstream-account-scope.md b/docs/implementation/moderation-upstream-account-scope.md new file mode 100644 index 000000000000..42d44a8d1f2c --- /dev/null +++ b/docs/implementation/moderation-upstream-account-scope.md @@ -0,0 +1,15 @@ +# Frozen semantics and execution plan + +Base: 4189ed821 (origin/production). Sole application writer; all runtime validation and screenshots in GitHub Actions; no production, paid probes, merge or deployment. + +Existing group scope is explicit: all_groups=true includes every group (including no group); all_groups=false uses group_ids, and an empty list matches nothing. Preserve this exactly. New upstream_account_scope defaults to all for missing legacy data; selected intersects the original request group/model filters with stable current-site upstream account IDs. selected with an empty list matches nothing, never everything. All groups plus selected accounts is the explicit account-only mode. Reject unknown scope on save and fail closed on persisted unknown values. + +The selected IDs denote provider accounts, not the caller/user/API key. Validate IDs, supported real platform/type and existence server-side. Persist account binding metadata (platform, type and group membership at selection); revalidate before selected generation, reject stale/deleted/moved bindings with an observable error instead of silently broadening policy. Account group movement must not broaden coverage. No SQL schema migration: additive settings JSON; missing fields preserve legacy behavior. Before rolling back to old binaries, reset scope to all (old binaries ignore account restrictions and would audit more traffic). + +Trace: handler checkSecurityAudit currently executes before scheduler selection; coordinator adapts legacy ContentModerationService.Check and independently executes prompt audit/penalty admission. HTTP completion cache currently marks the whole request. OpenAI ResponsesWebSocket audits first_turn before selection; per-turn BeforeRequestWithClientPayload sees the selected connection account and is shared by native/passthrough paths. A request may retry/fail over through multiple selected accounts. + +Keep existing pre-route admission and prompt audit semantics. Defer ONLY account-scoped content moderation until an actual account is selected, before generation. Retain a frozen original audit identity/content for HTTP failover and the original client frame for each WS turn. Scope-check each selected attempt before reusing an allowed audit; an unselected attempt must not mark moderation complete. Cache completed selected audit only for the same logical content/turn; next WS turn starts fresh. Preserve permission, group, queue and billing revalidation and release paths. + +Acceptance starts with a real WS handler/scheduler + loopback audit/provider fixture: a non-selected account must produce generation with zero audit calls. Baseline currently audits and blocks; RED must be a business assertion. Extend with selected deny (zero generation writes), HTTP types/stream modes, failover, WS next turn/native/pool/bridge, persistence/validation, selector integration and A→B→C badge behavior. Capture rendered original UI remotely before changing it. No external provider/network fixture requests. + +UI: reuse QualityAccountSelector with fixed manual selection, server search and pagination, stable selected-ID union across hidden pages, cancellable/fenced asynchronous reads and batch selection. Account filters describe discovery only; saved IDs control policy. Chinese and English explain group AND account semantics and empty selection. Add registered NewFeatureBadge. From 3c89befc8c9465045bf282e8ddb0ea800b8161c6 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sat, 14 Nov 2026 19:17:41 +0800 Subject: [PATCH 3/8] feat: gate moderation on actual selected upstream before generation --- .../workflows/moderation-upstream-scope.yml | 21 +++ backend/cmd/server/wire_gen.go | 2 +- .../handler/moderation_upstream_scope.go | 140 ++++++++++++++ .../handler/moderation_upstream_scope_test.go | 8 +- .../handler/openai_gateway_handler.go | 11 +- backend/internal/handler/openai_live.go | 7 + .../openai_ws_v2_passthrough_cyber_test.go | 2 +- .../internal/handler/security_audit_helper.go | 1 + backend/internal/securityaudit/coordinator.go | 2 +- .../securityaudit/coordinator_legacy.go | 1 + .../internal/securityaudit/prompt_types.go | 35 ++-- .../service/antigravity_gateway_claude.go | 4 + .../service/antigravity_gateway_compat.go | 8 + .../service/antigravity_gateway_gemini.go | 4 + .../service/antigravity_gateway_upstream.go | 4 + .../internal/service/content_moderation.go | 69 +++++-- .../content_moderation_upstream_scope.go | 178 ++++++++++++++++++ backend/internal/service/gateway_forward.go | 4 + .../gateway_forward_as_chat_completions.go | 4 + .../service/gateway_forward_as_responses.go | 4 + backend/internal/service/gateway_systemone.go | 4 + .../gemini_chat_completions_compat_service.go | 4 + .../service/gemini_messages_compat_service.go | 8 + .../openai_gateway_chat_completions.go | 4 + .../service/openai_gateway_forward.go | 4 + .../service/openai_gateway_messages.go | 4 + backend/internal/service/openai_images.go | 4 + backend/internal/service/openai_live.go | 7 + backend/internal/service/openai_live_types.go | 1 + backend/internal/service/wire.go | 3 +- 30 files changed, 518 insertions(+), 34 deletions(-) create mode 100644 backend/internal/handler/moderation_upstream_scope.go create mode 100644 backend/internal/service/content_moderation_upstream_scope.go diff --git a/.github/workflows/moderation-upstream-scope.yml b/.github/workflows/moderation-upstream-scope.yml index e62f8d6b7eb7..ed078bde2164 100644 --- a/.github/workflows/moderation-upstream-scope.yml +++ b/.github/workflows/moderation-upstream-scope.yml @@ -69,3 +69,24 @@ jobs: with: name: moderation-scope-ui-${{ github.sha }} path: ${{ runner.temp }}/moderation-scope-ui + backend-green: + runs-on: ubuntu-latest + timeout-minutes: 25 + steps: + - uses: actions/checkout@v6 + - uses: actions/setup-go@v6 + with: + go-version-file: backend/go.mod + cache-dependency-path: backend/go.sum + - name: Selected upstream execution and admission regressions + run: | + mkdir -p "$RUNNER_TEMP/moderation-scope-green" + git rev-parse HEAD > "$RUNNER_TEMP/moderation-scope-green/head.txt" + set -o pipefail + cd backend + go test -race -tags=unit ./internal/handler ./internal/service ./internal/securityaudit -run 'TestModerationUpstream|TestOpenAIResponsesWebSocket_ContentModeration|Test.*SecurityAudit|Test.*Queue.*Auth|Test.*Turn.*Admission' -count=1 -v -timeout=10m 2>&1 | tee "$RUNNER_TEMP/moderation-scope-green/green.log" + - uses: actions/upload-artifact@v7 + if: always() + with: + name: moderation-scope-green-${{ github.sha }} + path: ${{ runner.temp }}/moderation-scope-green diff --git a/backend/cmd/server/wire_gen.go b/backend/cmd/server/wire_gen.go index 80007197c510..53d8e7eecf54 100644 --- a/backend/cmd/server/wire_gen.go +++ b/backend/cmd/server/wire_gen.go @@ -366,7 +366,7 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) { channelMonitorRequestTemplateHandler := admin.NewChannelMonitorRequestTemplateHandler(channelMonitorRequestTemplateService) contentModerationRepository := repository.NewContentModerationRepository(db) contentModerationHashCache := repository.NewContentModerationHashCache(redisClient) - contentModerationService := service.ProvideContentModerationService(settingRepository, contentModerationRepository, contentModerationHashCache, groupRepository, userRepository, proxyRepository, apiKeyAuthCacheInvalidator, emailService, db, secretEncryptor, configConfig) + contentModerationService := service.ProvideContentModerationService(accountRepository, settingRepository, contentModerationRepository, contentModerationHashCache, groupRepository, userRepository, proxyRepository, apiKeyAuthCacheInvalidator, emailService, db, secretEncryptor, configConfig) contentModerationHandler := admin.NewContentModerationHandlerWithSafetyPrompt(contentModerationService, safetyPromptStore, settingService) configManager := securityaudit.NewConfigManager(db, settingRepository, redisClient, secretEncryptor, configConfig) postgreSQLRepository := securityaudit.NewPostgreSQLRepository(db) diff --git a/backend/internal/handler/moderation_upstream_scope.go b/backend/internal/handler/moderation_upstream_scope.go new file mode 100644 index 000000000000..9d6aa2ace17c --- /dev/null +++ b/backend/internal/handler/moderation_upstream_scope.go @@ -0,0 +1,140 @@ +package handler + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "strings" + "sync" + + "github.com/Wei-Shaw/sub2api/internal/securityaudit" + middleware2 "github.com/Wei-Shaw/sub2api/internal/server/middleware" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "go.uber.org/zap" +) + +const upstreamAuditStateKey = "content_moderation.upstream_state" + +type upstreamAuditState struct { + mu sync.Mutex + request securityaudit.Request + config *service.ContentModerationConfig + configErr error + legacy *service.ContentModerationService + coordinator *securityaudit.Coordinator + log *zap.Logger + turn int + completed *securityaudit.Decision +} + +func prepareUpstreamAudit(c *gin.Context, log *zap.Logger, coordinator *securityaudit.Coordinator, legacy *service.ContentModerationService, apiKey *service.APIKey, subject middleware2.AuthSubject, protocol, model string, body []byte, stage string) { + if legacy == nil { + return + } + turn, _ := securityAuditWSTurn(c) + if old, ok := c.Get(upstreamAuditStateKey); ok { + if state, ok := old.(*upstreamAuditState); ok && state.turn == turn && state.request.Stage == stage { + return + } + } + cfg, err := legacy.UpstreamModerationConfig(c.Request.Context()) + state := &upstreamAuditState{request: buildSecurityAuditRequest(c, apiKey, subject, protocol, model, body, stage).Clone(), config: cfg, configErr: err, legacy: legacy, coordinator: coordinator, log: log, turn: turn} + c.Set(upstreamAuditStateKey, state) + service.SetUpstreamModerationGate(c, func(ctx context.Context, account *service.Account) error { + decision := state.check(ctx, account) + if decision == nil || decision.AllowNextStage { + return nil + } + writeSelectedUpstreamAuditError(c, decision) + return errors.New(securityAuditMessage(decision)) + }) +} + +func checkSelectedUpstreamAudit(c *gin.Context, ctx context.Context, account *service.Account) *securityaudit.Decision { + if value, ok := c.Get(upstreamAuditStateKey); ok { + if state, ok := value.(*upstreamAuditState); ok { + return state.check(ctx, account) + } + } + return nil +} + +func (s *upstreamAuditState) check(ctx context.Context, account *service.Account) *securityaudit.Decision { + s.mu.Lock() + defer s.mu.Unlock() + if s.configErr != nil { + return upstreamAuditUnavailable(s.log, account, s.configErr) + } + if s.config == nil { + return nil + } + req := s.request.Clone() + req.UpstreamAccount, req.UpstreamConfig, req.SkipPrompt = account, s.config, true + input := service.ContentModerationCheckInput{ + RequestID: req.RequestID, UserID: req.UserID, UserEmail: req.UserEmail, + APIKeyID: req.APIKeyID, APIKeyName: req.APIKeyName, GroupID: req.GroupID, GroupName: req.GroupName, + Endpoint: req.Endpoint, Provider: req.Provider, Model: req.Model, Protocol: req.Protocol, Body: req.Body, + UpstreamAccount: account, UpstreamConfig: s.config, + } + if req.PenaltyContext.OriginalGroupID != nil { + input.GroupID, input.GroupName = req.PenaltyContext.OriginalGroupID, req.PenaltyContext.OriginalGroupName + } + applies, err := s.legacy.UpstreamModerationApplies(ctx, s.config, input) + if err != nil { + return upstreamAuditUnavailable(s.log, account, err) + } + if !applies { + return nil + } // Never mark an unselected attempt as audited. + if s.completed != nil { + return s.completed + } + coordinator := s.coordinator + if coordinator == nil { + coordinator = securityaudit.NewCoordinator(securityaudit.NewLegacyModerationAdapter(s.legacy), nil) + } + logSecurityAuditStart(s.log, req, len(req.Body), false) + decision := coordinator.Check(ctx, req) + logSecurityAuditDone(s.log, req, decision, false) + // One logical turn owns one immutable request. Nested protocol adapters and + // failover attempts share its decision; a new WS turn owns a fresh state. + s.completed = &decision + return &decision +} + +func upstreamAuditUnavailable(log *zap.Logger, account *service.Account, err error) *securityaudit.Decision { + var id int64 + if account != nil { + id = account.ID + } + if log != nil { + log.Error("content_moderation.upstream_scope_unavailable", zap.Int64("account_id", id), zap.Error(err)) + } + return &securityaudit.Decision{Kind: securityaudit.DecisionBlock, HTTPStatus: http.StatusServiceUnavailable, ErrorCode: "moderation_upstream_scope_unavailable", ClientMessage: "Upstream moderation scope is unavailable; administrator review required"} +} + +func writeSelectedUpstreamAuditError(c *gin.Context, decision *securityaudit.Decision) { + status, code, message := securityAuditStatus(decision), securityAuditErrorCode(decision), securityAuditMessage(decision) + service.MarkOpsClientBusinessLimited(c, service.OpsClientBusinessLimitedReasonLocalPolicyDenied) + service.SetOpsLocalErrorType(c, "permission_error", code) + payload := gin.H{"error": gin.H{"type": "permission_error", "code": code, "message": message}} + if strings.HasSuffix(c.Request.URL.Path, "/messages") { + payload["type"] = "error" + } + if strings.Contains(c.Request.URL.Path, "/v1beta/") { + payload = gin.H{"error": gin.H{"code": status, "message": message, "status": "PERMISSION_DENIED"}} + } + if c.Writer.Written() { + service.MarkOpsStreamError(c, code, message, status) + data, _ := json.Marshal(payload) + _, _ = fmt.Fprintf(c.Writer, "event: error\ndata: %s\n\n", data) + _ = service.FlushGatewayResponse(c.Writer) + } else { + c.JSON(status, payload) + } + service.MarkResponseCommitted(c) + c.Abort() +} diff --git a/backend/internal/handler/moderation_upstream_scope_test.go b/backend/internal/handler/moderation_upstream_scope_test.go index 5d033ea61ee2..cb05a63e8cef 100644 --- a/backend/internal/handler/moderation_upstream_scope_test.go +++ b/backend/internal/handler/moderation_upstream_scope_test.go @@ -27,11 +27,15 @@ func TestModerationUpstreamScopeUnselectedDoesNotAudit(t *testing.T) { defer audit.Close() upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { conn, err := coderws.Accept(w, r, nil) - if err != nil { return } + if err != nil { + return + } defer func() { _ = conn.CloseNow() }() ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second) defer cancel() - if _, _, err := conn.Read(ctx); err != nil { return } + if _, _, err := conn.Read(ctx); err != nil { + return + } generationWrites.Add(1) _ = conn.Write(ctx, coderws.MessageText, []byte(`{"type":"response.completed","response":{"id":"resp_scope","model":"gpt-5.1","usage":{"input_tokens":1,"output_tokens":1}}}`)) _, _, _ = conn.Read(ctx) diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index aeb7fc8a9fee..4187b3523c16 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -3609,6 +3609,11 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) { closeOpenAIClientWS(wsConn, coderws.StatusPolicyViolation, "billing check failed") return } + if decision := checkSelectedUpstreamAudit(c, ctx, account); decision != nil && !decision.AllowNextStage { + writeSecurityAuditWSError(ctx, wsConn, decision) + closeOpenAIClientWS(wsConn, securityAuditWSCloseStatus(decision), securityAuditWSCloseReason(decision)) + return + } hooks := &service.OpenAIWSIngressHooks{ ClientLifecycleContext: clientLifecycleCtx, InitialRequestModel: reqModel, @@ -3722,7 +3727,11 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) { middleware2.MarkIngressRejected(c, middleware2.IngressRejectModelNotAllowed) return service.NewOpenAIWSClientCloseError(coderws.StatusPolicyViolation, fmt.Sprintf("Model %q is not available for your account in this group", denied), nil) } - if decision := h.checkSecurityAuditStage(c, reqLog, apiKey, subject, service.ContentModerationProtocolOpenAIResponses, model, payload, "subsequent_turn"); decision != nil && !decision.AllowNextStage { + if decision := h.checkSecurityAuditStage(c, reqLog, apiKey, subject, service.ContentModerationProtocolOpenAIResponses, model, clientPayload, "subsequent_turn"); decision != nil && !decision.AllowNextStage { + writeSecurityAuditWSError(ctx, wsConn, decision) + return service.NewOpenAIWSClientCloseError(securityAuditWSCloseStatus(decision), securityAuditWSCloseReason(decision), nil) + } + if decision := checkSelectedUpstreamAudit(c, c.Request.Context(), account); decision != nil && !decision.AllowNextStage { writeSecurityAuditWSError(ctx, wsConn, decision) return service.NewOpenAIWSClientCloseError(securityAuditWSCloseStatus(decision), securityAuditWSCloseReason(decision), nil) } diff --git a/backend/internal/handler/openai_live.go b/backend/internal/handler/openai_live.go index e6a6a508f840..ff912d1f5405 100644 --- a/backend/internal/handler/openai_live.go +++ b/backend/internal/handler/openai_live.go @@ -1,6 +1,7 @@ package handler import ( + "context" "encoding/json" "errors" "io" @@ -128,6 +129,9 @@ func (h *OpenAIGatewayHandler) Live(c *gin.Context) { } identity := liveCallIdentity(c, apiKey, subject.UserID, subscription) + identity.BeforeGeneration = func(ctx context.Context, account *service.Account) error { + return service.CheckUpstreamModeration(ctx, c, account) + } identity.KeyReservation = keyReservation if keyReservation != nil { // Use the limit that actually admitted the reservation: while waiting, @@ -141,6 +145,9 @@ func (h *OpenAIGatewayHandler) Live(c *gin.Context) { identity.UserRequestID = userResult.RequestID created, err := h.gatewayService.CreateLiveCall(c.Request.Context(), request, identity, subject.Concurrency) if err != nil { + if c.IsAborted() { + return + } h.writeLiveCreateError(c, err) return } diff --git a/backend/internal/handler/openai_ws_v2_passthrough_cyber_test.go b/backend/internal/handler/openai_ws_v2_passthrough_cyber_test.go index 8e33dd68d321..775ae83d5ab2 100644 --- a/backend/internal/handler/openai_ws_v2_passthrough_cyber_test.go +++ b/backend/internal/handler/openai_ws_v2_passthrough_cyber_test.go @@ -66,7 +66,6 @@ func newOpenAIWSPassthroughHandlerHarnessWithKey(t *testing.T, upstreamURL strin } settingRepo := &contentModerationHandlerSettingRepo{values: settings} moderationRepo := &contentModerationHandlerTestRepo{} - moderationSvc := service.NewContentModerationService(settingRepo, moderationRepo, nil, nil, nil, nil, nil, nil) settingSvc := service.NewSettingService(settingRepo, nil) groupID := int64(4301) @@ -110,6 +109,7 @@ func newOpenAIWSPassthroughHandlerHarnessWithKey(t *testing.T, upstreamURL strin if accountRepo == nil { accountRepo = &openAIWSUsageHandlerAccountRepoStub{account: account} } + moderationSvc := service.NewContentModerationService(settingRepo, moderationRepo, nil, nil, nil, nil, nil, nil, accountRepo) usageRepo := &openAIWSUsageHandlerUsageLogRepoStub{created: make(chan *service.UsageLog, 8)} billingCacheSvc := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil) gatewaySvc := service.NewOpenAIGatewayService( diff --git a/backend/internal/handler/security_audit_helper.go b/backend/internal/handler/security_audit_helper.go index ce73e5b74a5a..bbcd5353526e 100644 --- a/backend/internal/handler/security_audit_helper.go +++ b/backend/internal/handler/security_audit_helper.go @@ -71,6 +71,7 @@ func runSecurityAudit(c *gin.Context, reqLog *zap.Logger, coordinator *securitya if c == nil || c.Request == nil { return nil } + prepareUpstreamAudit(c, reqLog, coordinator, legacy, apiKey, subject, protocol, model, body, stage) if legacy != nil { c.Set("content_moderation.user_version", legacy.CaptureModerationUserVersion(c.Request.Context(), subject.UserID)) } diff --git a/backend/internal/securityaudit/coordinator.go b/backend/internal/securityaudit/coordinator.go index 61d977b6f7c9..cb37ecb900fd 100644 --- a/backend/internal/securityaudit/coordinator.go +++ b/backend/internal/securityaudit/coordinator.go @@ -72,7 +72,7 @@ func (c *Coordinator) Check(ctx context.Context, req Request) (decision Decision req.GroupName = req.PenaltyContext.OriginalGroupName } mode := ModeOff - if c.prompt != nil { + if c.prompt != nil && !req.SkipPrompt { mode = c.prompt.EffectiveMode() } switch mode { diff --git a/backend/internal/securityaudit/coordinator_legacy.go b/backend/internal/securityaudit/coordinator_legacy.go index bfc4d66b2f88..334f527657a7 100644 --- a/backend/internal/securityaudit/coordinator_legacy.go +++ b/backend/internal/securityaudit/coordinator_legacy.go @@ -19,6 +19,7 @@ func (a *LegacyModerationAdapter) Check(ctx context.Context, req Request) (*Lega return nil, nil } decision, err := a.service.Check(ctx, service.ContentModerationCheckInput{ + UpstreamAccount: req.UpstreamAccount, UpstreamConfig: req.UpstreamConfig, RequestID: req.RequestID, UserID: req.UserID, UserEmail: req.UserEmail, APIKeyID: req.APIKeyID, APIKeyName: req.APIKeyName, GroupID: cloneInt64Ptr(req.GroupID), GroupName: req.GroupName, Endpoint: req.Endpoint, Provider: req.Provider, diff --git a/backend/internal/securityaudit/prompt_types.go b/backend/internal/securityaudit/prompt_types.go index 0cd96f518f90..bcd9de53b9f1 100644 --- a/backend/internal/securityaudit/prompt_types.go +++ b/backend/internal/securityaudit/prompt_types.go @@ -2,6 +2,8 @@ package securityaudit import ( "context" + + "github.com/Wei-Shaw/sub2api/internal/service" "time" ) @@ -67,21 +69,24 @@ const ( ) type Request struct { - RequestID string - UserID int64 - Username string - UserEmail string - APIKeyID int64 - APIKeyName string - GroupID *int64 - GroupName string - Provider string - Endpoint string - Protocol string - Model string - Body []byte - Stage string - PenaltyContext PenaltyRequestContext + UpstreamAccount *service.Account + UpstreamConfig *service.ContentModerationConfig + SkipPrompt bool + RequestID string + UserID int64 + Username string + UserEmail string + APIKeyID int64 + APIKeyName string + GroupID *int64 + GroupName string + Provider string + Endpoint string + Protocol string + Model string + Body []byte + Stage string + PenaltyContext PenaltyRequestContext } func (r Request) Clone() Request { diff --git a/backend/internal/service/antigravity_gateway_claude.go b/backend/internal/service/antigravity_gateway_claude.go index 53330fa82677..98232989097a 100644 --- a/backend/internal/service/antigravity_gateway_claude.go +++ b/backend/internal/service/antigravity_gateway_claude.go @@ -28,6 +28,10 @@ import ( // ├─ 成功 → 正常返回 // └─ 失败 → 设置模型限流 + 清除粘性绑定 → 切换账号 func (s *AntigravityGatewayService) Forward(ctx context.Context, c *gin.Context, account *Account, body []byte, isStickySession bool) (*ForwardResult, error) { + if err := CheckUpstreamModeration(ctx, c, account); err != nil { + return nil, err + } + beginUpstreamResponseModelObservation(c) // 上游透传账号直接转发,不走 OAuth token 刷新 if account.Type == AccountTypeUpstream { diff --git a/backend/internal/service/antigravity_gateway_compat.go b/backend/internal/service/antigravity_gateway_compat.go index 8673a490c5b5..5529c3263d2b 100644 --- a/backend/internal/service/antigravity_gateway_compat.go +++ b/backend/internal/service/antigravity_gateway_compat.go @@ -59,6 +59,10 @@ func (s *AntigravityGatewayService) ForwardAsChatCompletions( body []byte, _ *ParsedRequest, ) (*ForwardResult, error) { + if err := CheckUpstreamModeration(ctx, c, account); err != nil { + return nil, err + } + if err := s.validateAntigravityCompatAccount(c, account); err != nil { return nil, err } @@ -106,6 +110,10 @@ func (s *AntigravityGatewayService) ForwardAsResponses( body []byte, _ *ParsedRequest, ) (*ForwardResult, error) { + if err := CheckUpstreamModeration(ctx, c, account); err != nil { + return nil, err + } + if err := s.validateAntigravityCompatAccount(c, account); err != nil { return nil, err } diff --git a/backend/internal/service/antigravity_gateway_gemini.go b/backend/internal/service/antigravity_gateway_gemini.go index 7a4fc61afba3..3a4b2c5405c3 100644 --- a/backend/internal/service/antigravity_gateway_gemini.go +++ b/backend/internal/service/antigravity_gateway_gemini.go @@ -42,6 +42,10 @@ func WithForwardGeminiSession(groupID int64, sessionHash string) ForwardGeminiOp } func (s *AntigravityGatewayService) ForwardGemini(ctx context.Context, c *gin.Context, account *Account, originalModel string, action string, stream bool, body []byte, isStickySession bool, options ...ForwardGeminiOption) (*ForwardResult, error) { + if err := CheckUpstreamModeration(ctx, c, account); err != nil { + return nil, err + } + beginUpstreamResponseModelObservation(c) startTime := time.Now() forwardOpts := forwardGeminiOptions{} diff --git a/backend/internal/service/antigravity_gateway_upstream.go b/backend/internal/service/antigravity_gateway_upstream.go index beb6ea5d3987..4570b704696e 100644 --- a/backend/internal/service/antigravity_gateway_upstream.go +++ b/backend/internal/service/antigravity_gateway_upstream.go @@ -19,6 +19,10 @@ import ( // ForwardUpstream 使用 base_url + /v1/messages + 双 header 认证透传上游 Claude 请求 func (s *AntigravityGatewayService) ForwardUpstream(ctx context.Context, c *gin.Context, account *Account, body []byte) (*ForwardResult, error) { + if err := CheckUpstreamModeration(ctx, c, account); err != nil { + return nil, err + } + beginUpstreamResponseModelObservation(c) startTime := time.Now() sessionID := getSessionID(c) diff --git a/backend/internal/service/content_moderation.go b/backend/internal/service/content_moderation.go index 9b9cbaa94b52..676ee5a4a4b0 100644 --- a/backend/internal/service/content_moderation.go +++ b/backend/internal/service/content_moderation.go @@ -153,12 +153,15 @@ func ContentModerationCategories(engine ...string) []string { } type ContentModerationConfig struct { - Engine string `json:"engine,omitempty"` - TypeSafe *ContentModerationEngineConfig `json:"typesafe,omitempty"` - Enabled bool `json:"enabled"` - Mode string `json:"mode"` - BaseURL string `json:"base_url"` - Model string `json:"model"` + UpstreamAccountScope string `json:"upstream_account_scope"` + UpstreamAccountIDs []int64 `json:"upstream_account_ids"` + UpstreamAccountBindings map[int64]ModerationUpstreamBinding `json:"upstream_account_bindings,omitempty"` + Engine string `json:"engine,omitempty"` + TypeSafe *ContentModerationEngineConfig `json:"typesafe,omitempty"` + Enabled bool `json:"enabled"` + Mode string `json:"mode"` + BaseURL string `json:"base_url"` + Model string `json:"model"` // ProxyID 指定审计请求使用的代理服务器(IP管理-代理服务器),nil 表示直连。 ProxyID *int64 `json:"proxy_id,omitempty"` APIKey string `json:"api_key,omitempty"` @@ -194,6 +197,8 @@ type ContentModerationConfig struct { } type ContentModerationConfigView struct { + UpstreamAccountScope string `json:"upstream_account_scope"` + UpstreamAccountIDs []int64 `json:"upstream_account_ids"` Engine string `json:"engine"` EngineConfigs map[string]*ContentModerationConfigView `json:"engine_configs,omitempty"` Enabled bool `json:"enabled"` @@ -295,12 +300,14 @@ type ContentModerationTestAuditResult struct { } type UpdateContentModerationConfigInput struct { - Engine *string `json:"engine"` - EngineConfigs map[string]UpdateContentModerationEngineInput `json:"engine_configs"` - Enabled *bool `json:"enabled"` - Mode *string `json:"mode"` - BaseURL *string `json:"base_url"` - Model *string `json:"model"` + UpstreamAccountScope *string `json:"upstream_account_scope"` + UpstreamAccountIDs *[]int64 `json:"upstream_account_ids"` + Engine *string `json:"engine"` + EngineConfigs map[string]UpdateContentModerationEngineInput `json:"engine_configs"` + Enabled *bool `json:"enabled"` + Mode *string `json:"mode"` + BaseURL *string `json:"base_url"` + Model *string `json:"model"` // ProxyID nil 表示不修改;<=0 表示清除代理(恢复直连);>0 表示指定代理。 ProxyID *int64 `json:"proxy_id"` APIKey *string `json:"api_key"` @@ -339,6 +346,8 @@ type ContentModerationModelFilter struct { } type ContentModerationCheckInput struct { + UpstreamAccount *Account + UpstreamConfig *ContentModerationConfig // Frozen policy for a selected attempt. moderationVersion *int64 riskControlLogOnly bool // Captured at admission and retained by asynchronous tasks. RequestID string @@ -537,6 +546,7 @@ type ContentModerationHashCache interface { } type ContentModerationService struct { + accountRepo AccountRepository cyberEvidence *cyberevidence.Service settingRepo SettingRepository repo ContentModerationRepository @@ -621,6 +631,7 @@ func NewContentModerationService( proxyRepo ProxyRepository, authCacheInvalidator APIKeyAuthCacheInvalidator, emailService *EmailService, + accounts ...AccountRepository, ) *ContentModerationService { svc := &ContentModerationService{ settingRepo: settingRepo, @@ -636,6 +647,9 @@ func NewContentModerationService( asyncQueue: make(chan contentModerationTask, maxContentModerationQueueSize), keyHealth: make(map[string]*contentModerationKeyHealth), } + if len(accounts) > 0 { + svc.accountRepo = accounts[0] + } if settingRepo != nil && repo != nil { for i := 0; i < svc.workerCount; i++ { go svc.worker(i) @@ -664,6 +678,9 @@ func (s *ContentModerationService) UpdateConfig(ctx context.Context, input Updat if err != nil { return nil, err } + if err := s.updateUpstreamScope(ctx, cfg, input); err != nil { + return nil, err + } if input.Engine != nil { if !validModerationEngine(*input.Engine) { return nil, infraerrors.BadRequest("INVALID_CONTENT_MODERATION_ENGINE", "内容审计引擎无效") @@ -913,6 +930,9 @@ func (s *ContentModerationService) Check(ctx context.Context, input ContentModer } }() cfg := runtimeSnapshot.config + if input.UpstreamConfig != nil { + cfg = input.UpstreamConfig + } if securityPenaltyOwnsEnforcement(ctx) { cfg = cloneContentModerationConfig(cfg) cfg.AutoBanEnabled = false @@ -983,6 +1003,20 @@ func (s *ContentModerationService) Check(ctx context.Context, input ContentModer "configured_models", cfg.ModelFilter.Models) return allow, nil } + if cfg.UpstreamAccountScope != "" && cfg.UpstreamAccountScope != ModerationUpstreamAll { + // Pre-route checks retain prompt/penalty admission but defer content + // moderation until a real scheduler selection exists. + if input.UpstreamAccount == nil && cfg.UpstreamAccountScope == ModerationUpstreamSelected { + return allow, nil + } + applies, scopeErr := s.UpstreamModerationApplies(ctx, cfg, input) + if scopeErr != nil { + return moderationUpstreamUnavailable(input, scopeErr), nil + } + if !applies { + return allow, nil + } + } if cfg.Mode == ContentModerationModePreBlock { if (moderationState == nil || !moderationState.KeywordExempt) && cfg.KeywordBlockingMode != ContentModerationKeywordModeAPIOnly && len(cfg.BlockedKeywords) > 0 { keywordText := extractContentModerationKeywordText(input.Protocol, input.Body) @@ -2304,6 +2338,12 @@ func cloneContentModerationConfig(cfg *ContentModerationConfig) *ContentModerati clone.APIKeys = append([]string(nil), cfg.APIKeys...) clone.APIKeyBaseURLs = cloneModerationKeyURLs(cfg.APIKeyBaseURLs) clone.GroupIDs = append([]int64(nil), cfg.GroupIDs...) + clone.UpstreamAccountIDs = append([]int64(nil), cfg.UpstreamAccountIDs...) + clone.UpstreamAccountBindings = make(map[int64]ModerationUpstreamBinding, len(cfg.UpstreamAccountBindings)) + for id, binding := range cfg.UpstreamAccountBindings { + binding.GroupIDs = append([]int64(nil), binding.GroupIDs...) + clone.UpstreamAccountBindings[id] = binding + } clone.BlockedKeywords = append([]string(nil), cfg.BlockedKeywords...) clone.Thresholds = cloneFloatMap(cfg.Thresholds) clone.CategorySettings = maps.Clone(cfg.CategorySettings) @@ -2391,6 +2431,9 @@ func (cfg *ContentModerationConfig) normalize(engine ...string) { if cfg.NonHitRetentionDays > maxContentModerationNonHitRetentionDays { cfg.NonHitRetentionDays = maxContentModerationNonHitRetentionDays } + if cfg.UpstreamAccountScope == "" { + cfg.UpstreamAccountScope = ModerationUpstreamAll + } cfg.GroupIDs = normalizeInt64IDs(cfg.GroupIDs) // Persisted flat fields belong to OpenAI, even when TypeSafe is selected. // Effective profiles pass their engine explicitly. @@ -2620,6 +2663,8 @@ func (s *ContentModerationService) configView(cfg *ContentModerationConfig) *Con SampleRate: cfg.SampleRate, AllGroups: cfg.AllGroups, GroupIDs: append([]int64(nil), cfg.GroupIDs...), + UpstreamAccountScope: cfg.UpstreamAccountScope, + UpstreamAccountIDs: append([]int64(nil), cfg.UpstreamAccountIDs...), RecordNonHits: cfg.RecordNonHits, Thresholds: cloneFloatMap(cfg.Thresholds), CategorySettings: mergeModerationCategorySettings(cfg.Engine, nil, cfg.CategorySettings), diff --git a/backend/internal/service/content_moderation_upstream_scope.go b/backend/internal/service/content_moderation_upstream_scope.go new file mode 100644 index 000000000000..12cde13b3bd0 --- /dev/null +++ b/backend/internal/service/content_moderation_upstream_scope.go @@ -0,0 +1,178 @@ +package service + +import ( + "context" + "fmt" + "log/slog" + "slices" + + infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" + "github.com/gin-gonic/gin" +) + +const ( + ModerationUpstreamAll = "all" + ModerationUpstreamSelected = "selected" +) + +// Bindings are server-owned snapshots, never accepted from an update DTO. +// Keeping membership as well as ID prevents account moves from widening scope. +type ModerationUpstreamBinding struct { + Platform string `json:"platform"` + Type string `json:"type"` + GroupIDs []int64 `json:"group_ids"` +} + +func moderationUpstreamBinding(a *Account) ModerationUpstreamBinding { + groups := append([]int64(nil), a.GroupIDs...) + slices.Sort(groups) + return ModerationUpstreamBinding{Platform: a.Platform, Type: a.Type, GroupIDs: slices.Compact(groups)} +} + +func validModerationUpstreamAccount(a *Account) bool { + if a == nil || a.ID <= 0 { + return false + } + switch a.Platform { + case PlatformAnthropic: + return a.Type == AccountTypeOAuth || a.Type == AccountTypeSetupToken || a.Type == AccountTypeAPIKey || a.Type == AccountTypeBedrock || a.Type == AccountTypeUpstream + case PlatformOpenAI: + return a.Type == AccountTypeOAuth || a.Type == AccountTypeSetupToken || a.Type == AccountTypeAPIKey || a.Type == AccountTypeUpstream + case PlatformGemini: + return a.Type == AccountTypeOAuth || a.Type == AccountTypeAPIKey || a.Type == AccountTypeServiceAccount || a.Type == AccountTypeUpstream + case PlatformAntigravity, PlatformGrok: + return a.Type == AccountTypeOAuth || a.Type == AccountTypeAPIKey + case PlatformDeepseek, PlatformKimi, PlatformZhipu, PlatformMiniMax, PlatformQwen, PlatformTypeSafe: + return a.Type == AccountTypeAPIKey + default: + return false + } +} + +func (s *ContentModerationService) updateUpstreamScope(ctx context.Context, cfg *ContentModerationConfig, input UpdateContentModerationConfigInput) error { + if input.UpstreamAccountScope != nil { + if *input.UpstreamAccountScope != ModerationUpstreamAll && *input.UpstreamAccountScope != ModerationUpstreamSelected { + return infraerrors.BadRequest("INVALID_MODERATION_UPSTREAM_SCOPE", "Unknown upstream account scope") + } + cfg.UpstreamAccountScope = *input.UpstreamAccountScope + } + if cfg.UpstreamAccountScope == "" { + cfg.UpstreamAccountScope = ModerationUpstreamAll + } + if cfg.UpstreamAccountScope != ModerationUpstreamAll && cfg.UpstreamAccountScope != ModerationUpstreamSelected { + return infraerrors.BadRequest("INVALID_MODERATION_UPSTREAM_SCOPE", "Unknown upstream account scope") + } + if input.UpstreamAccountIDs != nil { + for _, id := range *input.UpstreamAccountIDs { + if id <= 0 { + return infraerrors.BadRequest("INVALID_MODERATION_UPSTREAM_ACCOUNT", "Account IDs must be positive") + } + } + cfg.UpstreamAccountIDs = normalizeInt64IDs(*input.UpstreamAccountIDs) + } + if len(cfg.UpstreamAccountIDs) > 10000 { + return infraerrors.BadRequest("INVALID_MODERATION_UPSTREAM_ACCOUNT", "At most 10000 accounts may be selected") + } + bindings := make(map[int64]ModerationUpstreamBinding, len(cfg.UpstreamAccountIDs)) + for _, id := range cfg.UpstreamAccountIDs { + if s.accountRepo == nil { + return infraerrors.BadRequest("INVALID_MODERATION_UPSTREAM_ACCOUNT", "Account validation unavailable") + } + a, err := s.accountRepo.GetByID(ctx, id) + if err != nil || !validModerationUpstreamAccount(a) { + return infraerrors.BadRequest("INVALID_MODERATION_UPSTREAM_ACCOUNT", fmt.Sprintf("Upstream account %d is missing or has an unsupported platform/type", id)) + } + binding := moderationUpstreamBinding(a) + if input.UpstreamAccountIDs == nil { + previous, ok := cfg.UpstreamAccountBindings[id] + if !ok || previous.Platform != binding.Platform || previous.Type != binding.Type || !slices.Equal(previous.GroupIDs, binding.GroupIDs) { + return infraerrors.BadRequest("STALE_MODERATION_UPSTREAM_ACCOUNT", fmt.Sprintf("Review and reselect changed upstream account %d", id)) + } + } + bindings[id] = binding + } + cfg.UpstreamAccountBindings = bindings + return nil +} + +// UpstreamModerationConfig returns an owned snapshot for one logical request or +// WS turn. A failover must reuse that snapshot and original content/identity. +func (s *ContentModerationService) UpstreamModerationConfig(ctx context.Context) (*ContentModerationConfig, error) { + if s == nil || s.settingRepo == nil { + return nil, nil + } + snapshot, err := s.loadRuntimeSnapshot(ctx) + if err != nil { + return nil, err + } + cfg := snapshot.config + if !snapshot.riskControlEnabled || !cfg.Enabled || cfg.Mode == ContentModerationModeOff || cfg.UpstreamAccountScope == ModerationUpstreamAll || cfg.UpstreamAccountScope == "" { + return nil, nil + } + return cloneContentModerationConfig(cfg), nil +} + +// UpstreamModerationApplies checks every actual selection, including on a cached +// audit. Stale scheduler data is never sufficient to validate the binding. +func (s *ContentModerationService) UpstreamModerationApplies(ctx context.Context, cfg *ContentModerationConfig, input ContentModerationCheckInput) (bool, error) { + if cfg == nil { + return false, nil + } + if cfg.UpstreamAccountScope != ModerationUpstreamSelected { + return false, fmt.Errorf("unknown upstream account scope %q", cfg.UpstreamAccountScope) + } + if !cfg.includesGroup(input.GroupID) || !cfg.includesModel(input.Model) { + return false, nil + } + a := input.UpstreamAccount + if a == nil || !slices.Contains(cfg.UpstreamAccountIDs, a.ID) { + return false, nil + } + binding, ok := cfg.UpstreamAccountBindings[a.ID] + if !ok || s.accountRepo == nil { + return false, fmt.Errorf("missing upstream binding for account %d", a.ID) + } + current, err := s.accountRepo.GetByID(ctx, a.ID) + if err != nil || !validModerationUpstreamAccount(current) { + return false, fmt.Errorf("upstream account %d is unavailable", a.ID) + } + for _, candidate := range []*Account{a, current} { + actual := moderationUpstreamBinding(candidate) + if actual.Platform != binding.Platform || actual.Type != binding.Type || !slices.Equal(actual.GroupIDs, binding.GroupIDs) { + return false, fmt.Errorf("upstream account %d binding changed; review scope", a.ID) + } + } + return true, nil +} + +func moderationUpstreamUnavailable(input ContentModerationCheckInput, err error) *ContentModerationDecision { + var accountID int64 + if input.UpstreamAccount != nil { + accountID = input.UpstreamAccount.ID + } + slog.Error("content_moderation.upstream_scope_unavailable", "account_id", accountID, "request_id", input.RequestID, "error", err) + return &ContentModerationDecision{Blocked: true, Action: ContentModerationActionBlock, StatusCode: 503, Message: "Upstream moderation scope is unavailable; administrator review required"} +} + +const upstreamModerationGateKey = "content_moderation.selected_upstream_gate" + +type upstreamModerationGate func(context.Context, *Account) error + +func SetUpstreamModerationGate(c *gin.Context, gate func(context.Context, *Account) error) { + if c != nil { + c.Set(upstreamModerationGateKey, upstreamModerationGate(gate)) + } +} + +// CheckUpstreamModeration runs after scheduling/admission and before any provider +// generation write. Protocol adapters may nest; the registered gate deduplicates. +func CheckUpstreamModeration(ctx context.Context, c *gin.Context, account *Account) error { + if c != nil { + if value, ok := c.Get(upstreamModerationGateKey); ok { + if gate, ok := value.(upstreamModerationGate); ok && gate != nil { + return gate(ctx, account) + } + } + } + return nil +} diff --git a/backend/internal/service/gateway_forward.go b/backend/internal/service/gateway_forward.go index 089a2c6a158a..78d72369e575 100644 --- a/backend/internal/service/gateway_forward.go +++ b/backend/internal/service/gateway_forward.go @@ -89,6 +89,10 @@ func sleepWithContext(ctx context.Context, d time.Duration) error { // Forward 转发请求到Claude API func (s *GatewayService) Forward(ctx context.Context, c *gin.Context, account *Account, parsed *ParsedRequest) (result *ForwardResult, err error) { + if err := CheckUpstreamModeration(ctx, c, account); err != nil { + return nil, err + } + startTime := time.Now() if parsed == nil { return nil, fmt.Errorf("parse request: empty request") diff --git a/backend/internal/service/gateway_forward_as_chat_completions.go b/backend/internal/service/gateway_forward_as_chat_completions.go index eb010552c377..2bb94e40eb7a 100644 --- a/backend/internal/service/gateway_forward_as_chat_completions.go +++ b/backend/internal/service/gateway_forward_as_chat_completions.go @@ -33,6 +33,10 @@ func (s *GatewayService) ForwardAsChatCompletions( body []byte, parsed *ParsedRequest, ) (*ForwardResult, error) { + if err := CheckUpstreamModeration(ctx, c, account); err != nil { + return nil, err + } + startTime := time.Now() // 1. Parse Chat Completions request diff --git a/backend/internal/service/gateway_forward_as_responses.go b/backend/internal/service/gateway_forward_as_responses.go index e10f635cfbef..02ef52d67078 100644 --- a/backend/internal/service/gateway_forward_as_responses.go +++ b/backend/internal/service/gateway_forward_as_responses.go @@ -35,6 +35,10 @@ func (s *GatewayService) ForwardAsResponses( body []byte, parsed *ParsedRequest, ) (*ForwardResult, error) { + if err := CheckUpstreamModeration(ctx, c, account); err != nil { + return nil, err + } + startTime := time.Now() normalizedBody, normalized, err := normalizeOpenAIResponsesLegacyIngressWithConfig(s.cfg, body) diff --git a/backend/internal/service/gateway_systemone.go b/backend/internal/service/gateway_systemone.go index b023d77aa115..b50a45c80b49 100644 --- a/backend/internal/service/gateway_systemone.go +++ b/backend/internal/service/gateway_systemone.go @@ -31,6 +31,10 @@ func (e *SystemOneUpstreamError) Error() string { } func (s *GatewayService) ForwardSystemOne(ctx context.Context, c *gin.Context, account *Account, body []byte) (*SystemOneForwardResult, error) { + if err := CheckUpstreamModeration(ctx, c, account); err != nil { + return nil, err + } + started := time.Now() if account == nil || !account.IsTypeSafe() || account.Type != AccountTypeAPIKey { return nil, errors.New("invalid typesafe account") diff --git a/backend/internal/service/gemini_chat_completions_compat_service.go b/backend/internal/service/gemini_chat_completions_compat_service.go index 0af20e0216e8..9201f8e62f2e 100644 --- a/backend/internal/service/gemini_chat_completions_compat_service.go +++ b/backend/internal/service/gemini_chat_completions_compat_service.go @@ -28,6 +28,10 @@ func (s *GeminiMessagesCompatService) ForwardAsChatCompletions( account *Account, body []byte, ) (*ForwardResult, error) { + if err := CheckUpstreamModeration(ctx, c, account); err != nil { + return nil, err + } + startTime := time.Now() var ccReq apicompat.ChatCompletionsRequest diff --git a/backend/internal/service/gemini_messages_compat_service.go b/backend/internal/service/gemini_messages_compat_service.go index bbb3ba796a0c..0cc61bd74218 100644 --- a/backend/internal/service/gemini_messages_compat_service.go +++ b/backend/internal/service/gemini_messages_compat_service.go @@ -541,6 +541,10 @@ func (s *GeminiMessagesCompatService) HasAntigravityAccounts(ctx context.Context } func (s *GeminiMessagesCompatService) Forward(ctx context.Context, c *gin.Context, account *Account, body []byte) (*ForwardResult, error) { + if err := CheckUpstreamModeration(ctx, c, account); err != nil { + return nil, err + } + beginUpstreamResponseModelObservation(c) beginGeminiImageOutputObservation(c) startTime := time.Now() @@ -1107,6 +1111,10 @@ func isGeminiSignatureRelatedError(respBody []byte) bool { } func (s *GeminiMessagesCompatService) ForwardNative(ctx context.Context, c *gin.Context, account *Account, originalModel string, action string, stream bool, body []byte) (*ForwardResult, error) { + if err := CheckUpstreamModeration(ctx, c, account); err != nil { + return nil, err + } + beginUpstreamResponseModelObservation(c) beginGeminiImageOutputObservation(c) startTime := time.Now() diff --git a/backend/internal/service/openai_gateway_chat_completions.go b/backend/internal/service/openai_gateway_chat_completions.go index 28025584c842..12bd3542bc89 100644 --- a/backend/internal/service/openai_gateway_chat_completions.go +++ b/backend/internal/service/openai_gateway_chat_completions.go @@ -62,6 +62,7 @@ func (s *OpenAIGatewayService) ForwardAsChatCompletions( promptCacheKey string, defaultMappedModel string, ) (*OpenAIForwardResult, error) { + admittedCtx, admissionErr := s.beginPriorityLatencyTurn(ctx, c, account, gjson.GetBytes(body, "model").String()) if admissionErr != nil { return nil, admissionErr @@ -108,6 +109,9 @@ func (s *OpenAIGatewayService) forwardAsChatCompletions( return nil, admissionErr } account = latest + if err := CheckUpstreamModeration(ctx, c, account); err != nil { + return nil, err + } rememberOpenCodeInboundBody(c, body) beginUpstreamResponseModelObservation(c) ClearActualOpenAIUpstreamEndpoint(c) diff --git a/backend/internal/service/openai_gateway_forward.go b/backend/internal/service/openai_gateway_forward.go index 330f8c6c9b4c..5233d566d901 100644 --- a/backend/internal/service/openai_gateway_forward.go +++ b/backend/internal/service/openai_gateway_forward.go @@ -91,6 +91,7 @@ func prismBrowserResponsesURL(baseURL string) string { // Forward forwards request to OpenAI API func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, account *Account, body []byte) (result *OpenAIForwardResult, resultErr error) { + defer func() { if result != nil && c != nil { result.AuthConnectionID = c.GetString("openai_auth_connection_id") @@ -147,6 +148,9 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco return nil, markOpenAIInitialAdmissionError(admissionErr) } account = latest + if err := CheckUpstreamModeration(ctx, c, account); err != nil { + return nil, err + } if err := s.checkOpenAIAgentRecoveryDispatch(ctx, c, account, body); err != nil { return nil, err } diff --git a/backend/internal/service/openai_gateway_messages.go b/backend/internal/service/openai_gateway_messages.go index eac26eb348c4..faf8a5d35d19 100644 --- a/backend/internal/service/openai_gateway_messages.go +++ b/backend/internal/service/openai_gateway_messages.go @@ -33,6 +33,7 @@ func (s *OpenAIGatewayService) ForwardAsAnthropic( promptCacheKey string, defaultMappedModel string, ) (*OpenAIForwardResult, error) { + admittedCtx, admissionErr := s.beginPriorityLatencyTurn(ctx, c, account, gjson.GetBytes(body, "model").String()) if admissionErr != nil { return nil, admissionErr @@ -66,6 +67,9 @@ func (s *OpenAIGatewayService) forwardAsAnthropic( return nil, admissionErr } account = latest + if err := CheckUpstreamModeration(ctx, c, account); err != nil { + return nil, err + } // 工具 Schema 清洗必须先于所有分流:下游每条路径(原生 Anthropic 直通、 // Chat Completions 转换、Responses 转换)都会把 tools 原样带给上游,而 // xAI / Moonshot 等严格校验方会因 input_schema 里的 required:null 或 diff --git a/backend/internal/service/openai_images.go b/backend/internal/service/openai_images.go index b54547bd2bcc..d097f2d69730 100644 --- a/backend/internal/service/openai_images.go +++ b/backend/internal/service/openai_images.go @@ -625,6 +625,7 @@ func (s *OpenAIGatewayService) ForwardImages( parsed *OpenAIImagesRequest, channelMappedModel string, ) (*OpenAIForwardResult, error) { + if parsed == nil { return nil, fmt.Errorf("parsed images request is required") } @@ -637,6 +638,9 @@ func (s *OpenAIGatewayService) ForwardImages( return nil, admissionErr } account = latest + if err := CheckUpstreamModeration(ctx, c, account); err != nil { + return nil, err + } if err := parsed.ValidateAccountModels(account, channelMappedModel); err != nil { return nil, err } diff --git a/backend/internal/service/openai_live.go b/backend/internal/service/openai_live.go index ea65e52574d3..4266084afda7 100644 --- a/backend/internal/service/openai_live.go +++ b/backend/internal/service/openai_live.go @@ -195,6 +195,13 @@ func (s *OpenAIGatewayService) CreateLiveCall( } account := selection.Account + if identity.BeforeGeneration != nil { + if err := identity.BeforeGeneration(ctx, account); err != nil { + selection.ReleaseFunc() + releaseJoint() + return nil, err + } + } if joint.leaseID == "" { leaseID := generateRequestID() acquireCtx, cancelAcquire := context.WithTimeout(ctx, liveRedisOperationTimeout) diff --git a/backend/internal/service/openai_live_types.go b/backend/internal/service/openai_live_types.go index a7c768d3d4c8..92a553f1c634 100644 --- a/backend/internal/service/openai_live_types.go +++ b/backend/internal/service/openai_live_types.go @@ -43,6 +43,7 @@ type LiveCallRequest struct { } type LiveCallIdentity struct { + BeforeGeneration func(context.Context, *Account) error APIKeyConcurrencyLimit int APIKeyID int64 UserID int64 diff --git a/backend/internal/service/wire.go b/backend/internal/service/wire.go index f5292274376d..25e6270d366d 100644 --- a/backend/internal/service/wire.go +++ b/backend/internal/service/wire.go @@ -1353,8 +1353,9 @@ func ProvideCRSSyncService(accounts AccountRepository, proxies ProxyRepository, } // ProvideContentModerationService reuses the existing fixed TOTP AES-GCM key. -func ProvideContentModerationService(settings SettingRepository, repo ContentModerationRepository, hashes ContentModerationHashCache, groups GroupRepository, users UserRepository, proxies ProxyRepository, invalidator APIKeyAuthCacheInvalidator, email *EmailService, db *sql.DB, cipher SecretEncryptor, cfg *config.Config) *ContentModerationService { +func ProvideContentModerationService(accounts AccountRepository, settings SettingRepository, repo ContentModerationRepository, hashes ContentModerationHashCache, groups GroupRepository, users UserRepository, proxies ProxyRepository, invalidator APIKeyAuthCacheInvalidator, email *EmailService, db *sql.DB, cipher SecretEncryptor, cfg *config.Config) *ContentModerationService { s := NewContentModerationService(settings, repo, hashes, groups, users, proxies, invalidator, email) + s.accountRepo = accounts s.cyberEvidence = cyberevidence.New(cyberevidence.NewSQLStore(db), cipher, cfg != nil && cfg.Totp.EncryptionKeyConfigured) return s } From 4917f65e4feec4b80f35915f108f18bfca467c72 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sat, 14 Nov 2026 19:23:23 +0800 Subject: [PATCH 4/8] feat: integrate shared upstream selector and expand route acceptance --- .../workflows/moderation-upstream-scope.yml | 8 +- .../internal/handler/batch_image_handler.go | 7 ++ .../handler/moderation_upstream_http_test.go | 119 ++++++++++++++++++ .../handler/moderation_upstream_scope.go | 5 + .../handler/moderation_upstream_ws_test.go | 98 +++++++++++++++ .../handler/openai_ws_client_identity_test.go | 10 +- backend/internal/repository/account_repo.go | 6 +- .../internal/service/batch_image_public.go | 26 ++-- .../content_moderation_upstream_scope.go | 2 +- .../content_moderation_upstream_scope_test.go | 86 +++++++++++++ backend/internal/service/grok_audio.go | 4 + backend/internal/service/grok_media.go | 4 + frontend/src/api/admin/riskControl.ts | 4 + .../ModerationUpstreamAccountSelector.vue | 86 +++++++++++++ .../ModerationUpstreamAccountSelector.spec.ts | 56 +++++++++ frontend/src/constants/newFeatureNotices.ts | 1 + .../src/i18n/locales/en/admin/channels.ts | 11 ++ .../src/i18n/locales/zh/admin/channels.ts | 11 ++ frontend/src/views/admin/RiskControlView.vue | 15 +++ .../admin/__tests__/RiskControlView.spec.ts | 2 + 20 files changed, 544 insertions(+), 17 deletions(-) create mode 100644 backend/internal/handler/moderation_upstream_http_test.go create mode 100644 backend/internal/handler/moderation_upstream_ws_test.go create mode 100644 backend/internal/service/content_moderation_upstream_scope_test.go create mode 100644 frontend/src/components/admin/moderation/ModerationUpstreamAccountSelector.vue create mode 100644 frontend/src/components/admin/moderation/__tests__/ModerationUpstreamAccountSelector.spec.ts diff --git a/.github/workflows/moderation-upstream-scope.yml b/.github/workflows/moderation-upstream-scope.yml index ed078bde2164..8bb27336fad3 100644 --- a/.github/workflows/moderation-upstream-scope.yml +++ b/.github/workflows/moderation-upstream-scope.yml @@ -7,7 +7,7 @@ permissions: contents: read concurrency: group: moderation-upstream-scope-${{ github.ref }} - cancel-in-progress: false + cancel-in-progress: true jobs: behavioral-red: runs-on: ubuntu-latest @@ -41,7 +41,7 @@ jobs: with: name: moderation-scope-red-${{ github.sha }} path: ${{ runner.temp }}/moderation-scope - ui-baseline: + ui-evidence: runs-on: ubuntu-latest timeout-minutes: 20 steps: @@ -55,6 +55,10 @@ jobs: cache: pnpm cache-dependency-path: frontend/pnpm-lock.yaml - run: pnpm --dir frontend install --frozen-lockfile + - name: Frontend integration and existing selector regressions + run: | + pnpm --dir frontend exec vitest run src/components/admin/moderation/__tests__/ModerationUpstreamAccountSelector.spec.ts src/components/admin/operations/__tests__/QualityAccountSelector.spec.ts src/views/admin/__tests__/RiskControlView.spec.ts src/components/common/__tests__/NewFeatureBadge.spec.ts + pnpm --dir frontend run build - name: Isolated browser run: | npm install --prefix "$RUNNER_TEMP/scope-browser" --no-save --ignore-scripts playwright@1.56.1 diff --git a/backend/internal/handler/batch_image_handler.go b/backend/internal/handler/batch_image_handler.go index 33f024b7dbe8..444577aaf1ed 100644 --- a/backend/internal/handler/batch_image_handler.go +++ b/backend/internal/handler/batch_image_handler.go @@ -1,6 +1,7 @@ package handler import ( + "context" "encoding/json" "errors" "io" @@ -45,8 +46,14 @@ func (h *BatchImageHandler) Submit(c *gin.Context) { if sessionID := service.ExtractClientSessionID(c); sessionID != "" { req.SessionID = &sessionID } + req.BeforeGeneration = func(ctx context.Context, account *service.Account) error { + return service.CheckUpstreamModeration(ctx, c, account) + } got, err := h.service.Submit(c.Request.Context(), owner, req, c.GetHeader("Idempotency-Key")) if err != nil { + if c.IsAborted() { + return + } batchImageError(c, err) return } diff --git a/backend/internal/handler/moderation_upstream_http_test.go b/backend/internal/handler/moderation_upstream_http_test.go new file mode 100644 index 000000000000..f1f0baf45f20 --- /dev/null +++ b/backend/internal/handler/moderation_upstream_http_test.go @@ -0,0 +1,119 @@ +//go:build unit + +package handler + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "sync/atomic" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/Wei-Shaw/sub2api/internal/testutil" + "github.com/stretchr/testify/require" +) + +func TestModerationUpstreamHTTPSelectionAndFailover(t *testing.T) { + for _, accountType := range []string{service.AccountTypeAPIKey, service.AccountTypeOAuth} { + for _, stream := range []bool{false, true} { + for _, scenario := range []string{"unselected", "deny", "failover-deny", "failover-allow"} { + t.Run(fmt.Sprintf("%s/stream=%t/%s", accountType, stream, scenario), func(t *testing.T) { + var audits, writesA, writesB atomic.Int32 + audit := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + audits.Add(1) + body, _ := io.ReadAll(r.Body) + require.Contains(t, string(body), "frozen original input") + score := "0.99" + if scenario == "failover-allow" { + score = "0.01" + } + _, _ = fmt.Fprintf(w, `{"results":[{"category_scores":{"sexual":%s}}]}`, score) + })) + defer audit.Close() + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + isA := strings.Contains(r.Header.Get("Authorization"), "fixture-a") + if isA { + writesA.Add(1) + } else { + writesB.Add(1) + } + if isA && strings.HasPrefix(scenario, "failover") { + w.WriteHeader(503) + _, _ = w.Write([]byte(`{"error":{"message":"fixture overloaded"}}`)) + return + } + if stream || accountType == service.AccountTypeOAuth { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, "data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_scope\",\"model\":\"gpt-5.1\",\"status\":\"completed\",\"output\":[],\"usage\":{\"input_tokens\":1,\"output_tokens\":1}}}\n\n") + } else { + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, `{"id":"resp_scope","status":"completed","model":"gpt-5.1","output":[],"usage":{"input_tokens":1,"output_tokens":1}}`) + } + })) + defer upstream.Close() + accounts := []service.Account{} + for i, token := range []string{"fixture-a", "fixture-b"} { + accounts = append(accounts, service.Account{ID: int64(i + 1), Name: token, Platform: service.PlatformOpenAI, Type: accountType, Status: service.StatusActive, Schedulable: true, Priority: i, GroupIDs: []int64{3131, 3132}, Credentials: map[string]any{"api_key": token, "access_token": token, "base_url": upstream.URL}, Extra: map[string]any{"codex_fingerprint_mode": "off"}}) + } + cfg := &config.Config{} + cfg.Security.URLAllowlist.AllowPrivateHosts = true + cfg.Security.URLAllowlist.AllowInsecureHTTP = true + target, err := url.Parse(upstream.URL) + require.NoError(t, err) + route := issue600LocalTransport{target: target, transport: http.DefaultTransport} + transport := issue600LocalHTTPUpstream{HTTPUpstream: testutil.NewRealHTTPUpstream(cfg), route: route} + h := newOpenAIResponsesFailoverTestHandler(t, transport, accounts...) + ids := []int64{1} + if scenario == "unselected" { + ids = []int64{99} + } + if scenario == "failover-deny" { + ids = []int64{2} + } + if scenario == "failover-allow" { + ids = []int64{1, 2} + } + bindings := map[int64]service.ModerationUpstreamBinding{} + for _, a := range accounts { + bindings[a.ID] = service.ModerationUpstreamBinding{Platform: a.Platform, Type: a.Type, GroupIDs: a.GroupIDs} + } + policy := map[string]any{"enabled": true, "mode": "pre_block", "all_groups": true, "sample_rate": 100, "base_url": audit.URL, "api_keys": []string{"fixture-audit"}, "upstream_account_scope": "selected", "upstream_account_ids": ids, "upstream_account_bindings": bindings} + raw, err := json.Marshal(policy) + require.NoError(t, err) + repo := &contentModerationHandlerSettingRepo{values: map[string]string{service.SettingKeyRiskControlEnabled: "true", service.SettingKeyContentModerationConfig: string(raw)}} + h.contentModerationService = service.NewContentModerationService(repo, &contentModerationHandlerTestRepo{}, nil, nil, nil, nil, nil, nil, openAIImagesFailoverAccountRepo{accounts: accounts}) + c, rec := newOpenAIResponsesFailoverTestContext(t, context.Background()) + c.Request.Body = io.NopCloser(strings.NewReader(fmt.Sprintf(`{"model":"gpt-5.1","stream":%t,"input":"frozen original input"}`, stream))) + h.Responses(c) + if scenario == "unselected" { + require.Zero(t, audits.Load()) + require.Equal(t, int32(1), writesA.Load()) + require.Contains(t, rec.Body.String(), "resp_scope") + } else { + require.Equal(t, int32(1), audits.Load(), "same logical content must be audited once across retry/failover") + if scenario == "failover-allow" { + require.Positive(t, writesA.Load()) + require.Equal(t, int32(1), writesB.Load()) + require.Contains(t, rec.Body.String(), "resp_scope") + } else { + require.Zero(t, writesB.Load()) + require.Contains(t, rec.Body.String(), "content_policy_violation") + if scenario == "deny" { + require.Zero(t, writesA.Load()) + } else { + require.Positive(t, writesA.Load()) + } + } + } + }) + } + } + } +} diff --git a/backend/internal/handler/moderation_upstream_scope.go b/backend/internal/handler/moderation_upstream_scope.go index 9d6aa2ace17c..3f091b7abaa3 100644 --- a/backend/internal/handler/moderation_upstream_scope.go +++ b/backend/internal/handler/moderation_upstream_scope.go @@ -37,12 +37,17 @@ func prepareUpstreamAudit(c *gin.Context, log *zap.Logger, coordinator *security turn, _ := securityAuditWSTurn(c) if old, ok := c.Get(upstreamAuditStateKey); ok { if state, ok := old.(*upstreamAuditState); ok && state.turn == turn && state.request.Stage == stage { + bindUpstreamAuditGate(c, state) return } } cfg, err := legacy.UpstreamModerationConfig(c.Request.Context()) state := &upstreamAuditState{request: buildSecurityAuditRequest(c, apiKey, subject, protocol, model, body, stage).Clone(), config: cfg, configErr: err, legacy: legacy, coordinator: coordinator, log: log, turn: turn} c.Set(upstreamAuditStateKey, state) + bindUpstreamAuditGate(c, state) +} + +func bindUpstreamAuditGate(c *gin.Context, state *upstreamAuditState) { service.SetUpstreamModerationGate(c, func(ctx context.Context, account *service.Account) error { decision := state.check(ctx, account) if decision == nil || decision.AllowNextStage { diff --git a/backend/internal/handler/moderation_upstream_ws_test.go b/backend/internal/handler/moderation_upstream_ws_test.go new file mode 100644 index 000000000000..925376807072 --- /dev/null +++ b/backend/internal/handler/moderation_upstream_ws_test.go @@ -0,0 +1,98 @@ +package handler + +import ( + "context" + "encoding/json" + "strings" + "fmt" + "net/http" + "net/http/httptest" + "sync/atomic" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/service" + coderws "github.com/coder/websocket" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + + +func TestModerationUpstreamWebSocketModesAndTurns(t *testing.T) { + for _, mode := range []string{service.OpenAIWSIngressModePassthrough, service.OpenAIWSIngressModeCtxPool, service.OpenAIWSIngressModeHTTPBridge} { + for _, namespace := range []string{"none", "oauth"} { + for _, scenario := range []string{"unselected", "deny", "next-turn", "failover"} { + t.Run(mode+"/"+namespace+"/"+scenario, func(t *testing.T) { + var audits atomic.Int32 + audit := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + n := audits.Add(1) + score := "0.99" + if scenario == "next-turn" && n == 1 { + score = "0.01" + } + _, _ = fmt.Fprintf(w, `{"results":[{"category_scores":{"sexual":%s}}]}`, score) + })) + defer audit.Close() + accountType := service.AccountTypeAPIKey + if namespace == "oauth" { + accountType = service.AccountTypeOAuth + } + ids := []int64{9951} + if scenario == "unselected" { + ids = []int64{9953} + } + raw, err := json.Marshal(map[string]any{"enabled": true, "mode": "pre_block", "all_groups": true, "sample_rate": 100, "base_url": audit.URL, "api_keys": []string{"fixture"}, "upstream_account_scope": "selected", "upstream_account_ids": ids, "upstream_account_bindings": map[int64]service.ModerationUpstreamBinding{9951: {Platform: service.PlatformOpenAI, Type: accountType, GroupIDs: []int64{4301}}}}) + require.NoError(t, err) + opts := issue600FixtureOptions{moderationSettings: map[string]string{service.SettingKeyContentModerationConfig: string(raw)}} + if scenario == "failover" { + if namespace != "oauth" { + return + } + opts.switchAccount = true + } + h, up := newIssue600NetworkHarness(t, mode, namespace, false, nil, opts) + payload := `{"type":"response.create","model":"gpt-5.1","input":"synthetic scope first"}` + if scenario == "unselected" { + issue600Send(t, h, payload, 1, false) + issue600Send(t, h, strings.ReplaceAll(payload, "first", "second"), 2, false) + require.Zero(t, audits.Load()) + } else { + if scenario == "next-turn" { + issue600Send(t, h, payload, 1, false) + payload = strings.ReplaceAll(payload, "first", "second") + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + require.NoError(t, h.clientConn.Write(ctx, coderws.MessageText, []byte(payload))) + _, event, readErr := h.clientConn.Read(ctx) + if readErr == nil { + require.Equal(t, "error", gjson.GetBytes(event, "type").String()) + require.Contains(t, string(event), "content_policy_violation") + } else { + require.Equal(t, coderws.StatusPolicyViolation, coderws.CloseStatus(readErr)) + } + expected := int32(1) + if scenario == "next-turn" { + expected = 2 + } + require.Equal(t, expected, audits.Load()) + } + issue600Finish(t, h, nil) + frames, _ := up.snapshot() + expectedWrites := 0 + if scenario == "unselected" { + expectedWrites = 2 + } + if scenario == "next-turn" { + expectedWrites = 1 + } + require.Len(t, frames, expectedWrites, "selected deny must precede actual generation writes") + if scenario == "failover" { + rejected, _ := up.rejectedSnapshot() + require.NotEmpty(t, rejected, "unselected first account must be tried before selected failover denial") + } + }) + } + } + } +} diff --git a/backend/internal/handler/openai_ws_client_identity_test.go b/backend/internal/handler/openai_ws_client_identity_test.go index 01bdc232d803..66254b2c19ad 100644 --- a/backend/internal/handler/openai_ws_client_identity_test.go +++ b/backend/internal/handler/openai_ws_client_identity_test.go @@ -82,9 +82,10 @@ type issue600SwitchRepo struct { func (r *issue600SwitchRepo) UpdateExtra(context.Context, int64, map[string]any) error { return nil } type issue600FixtureOptions struct { - switchAccount bool - switchAfterTurns int - disableCyber bool + moderationSettings map[string]string + switchAccount bool + switchAfterTurns int + disableCyber bool } type issue600Upstream struct { @@ -211,6 +212,9 @@ func newIssue600NetworkHarness(t *testing.T, mode, namespace string, strict bool http.DefaultClient = &http.Client{Transport: route} t.Cleanup(func() { http.DefaultClient = oldClient }) settings := map[string]string{service.SettingKeyCyberSessionIdentityStrictEnabled: strconv.FormatBool(strict)} + for key, value := range opts.moderationSettings { + settings[key] = value + } if opts.disableCyber { settings[service.SettingKeyCyberSessionBlockEnabled] = "false" } diff --git a/backend/internal/repository/account_repo.go b/backend/internal/repository/account_repo.go index c4e1f7730471..7a5529e52d9f 100644 --- a/backend/internal/repository/account_repo.go +++ b/backend/internal/repository/account_repo.go @@ -1443,7 +1443,11 @@ func (r *accountRepository) accountListFilteredQuery(platform, accountType, stat q = q.Where(predicate) } if search != "" { - q = q.Where(dbaccount.NameContainsFold(search)) + if id, err := strconv.ParseInt(strings.TrimPrefix(strings.TrimSpace(search), "#"), 10, 64); err == nil && id > 0 { + q = q.Where(dbaccount.Or(dbaccount.IDEQ(id), dbaccount.NameContainsFold(search))) + } else { + q = q.Where(dbaccount.NameContainsFold(search)) + } } if groupID == service.AccountListGroupUngrouped { q = q.Where(dbaccount.Not(dbaccount.HasAccountGroups())) diff --git a/backend/internal/service/batch_image_public.go b/backend/internal/service/batch_image_public.go index cb10a285be7d..fa3fe38f66e7 100644 --- a/backend/internal/service/batch_image_public.go +++ b/backend/internal/service/batch_image_public.go @@ -48,16 +48,17 @@ type BatchImageUserGroupRateRepository interface { } type BatchImageSubmitRequest struct { - Model string `json:"model"` - TaskName string `json:"task_name"` - ParentBatchID string `json:"parent_batch_id"` - Provider string `json:"provider"` - Items []BatchImageSubmitItem `json:"items"` - ResponseMimeType string `json:"response_mime_type"` - AspectRatio string `json:"aspect_ratio"` - ImageSize string `json:"image_size"` - Metadata map[string]string `json:"metadata"` - SessionID *string `json:"-"` + BeforeGeneration func(context.Context, *Account) error `json:"-"` + Model string `json:"model"` + TaskName string `json:"task_name"` + ParentBatchID string `json:"parent_batch_id"` + Provider string `json:"provider"` + Items []BatchImageSubmitItem `json:"items"` + ResponseMimeType string `json:"response_mime_type"` + AspectRatio string `json:"aspect_ratio"` + ImageSize string `json:"image_size"` + Metadata map[string]string `json:"metadata"` + SessionID *string `json:"-"` } type BatchImageSubmitItem struct { @@ -235,6 +236,11 @@ func (s *BatchImagePublicService) Submit(ctx context.Context, owner BatchImageOw if err != nil { return nil, err } + if req.BeforeGeneration != nil { + if err := req.BeforeGeneration(ctx, account); err != nil { + return nil, err + } + } pricingSnapshot, err := s.resolvePricingSnapshot(ctx, owner, normalized, provider.Name(), account) if err != nil { return nil, err diff --git a/backend/internal/service/content_moderation_upstream_scope.go b/backend/internal/service/content_moderation_upstream_scope.go index 12cde13b3bd0..dd6b0137150e 100644 --- a/backend/internal/service/content_moderation_upstream_scope.go +++ b/backend/internal/service/content_moderation_upstream_scope.go @@ -42,7 +42,7 @@ func validModerationUpstreamAccount(a *Account) bool { return a.Type == AccountTypeOAuth || a.Type == AccountTypeAPIKey || a.Type == AccountTypeServiceAccount || a.Type == AccountTypeUpstream case PlatformAntigravity, PlatformGrok: return a.Type == AccountTypeOAuth || a.Type == AccountTypeAPIKey - case PlatformDeepseek, PlatformKimi, PlatformZhipu, PlatformMiniMax, PlatformQwen, PlatformTypeSafe: + case PlatformDeepseek, PlatformKimi, PlatformZhipu, PlatformMiniMax, PlatformQwen, PlatformTypeSafe, PlatformOpenCodeGo, PlatformCommandCode, PlatformCline, PlatformMistral: return a.Type == AccountTypeAPIKey default: return false diff --git a/backend/internal/service/content_moderation_upstream_scope_test.go b/backend/internal/service/content_moderation_upstream_scope_test.go new file mode 100644 index 000000000000..7db2580c9a3b --- /dev/null +++ b/backend/internal/service/content_moderation_upstream_scope_test.go @@ -0,0 +1,86 @@ +package service + +import ( + "context" + "encoding/json" + "testing" + + "github.com/stretchr/testify/require" +) + +type moderationScopeAccounts struct { + AccountRepository + accounts map[int64]*Account +} + +func (r *moderationScopeAccounts) GetByID(_ context.Context, id int64) (*Account, error) { + a := r.accounts[id] + if a == nil { + return nil, ErrAccountNotFound + } + return a, nil +} + +func TestModerationUpstreamPersistenceAndValidation(t *testing.T) { + ctx := context.Background() + repo := &contentModerationTestSettingRepo{values: map[string]string{SettingKeyRiskControlEnabled: "true"}} + accounts := &moderationScopeAccounts{accounts: map[int64]*Account{1: {ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth, GroupIDs: []int64{10, 20}}, 2: {ID: 2, Platform: PlatformAnthropic, Type: AccountTypeAPIKey, GroupIDs: []int64{20}}}} + s := NewContentModerationService(repo, nil, nil, nil, nil, nil, nil, nil, accounts) + legacy, err := s.GetConfig(ctx) + require.NoError(t, err) + require.Equal(t, ModerationUpstreamAll, legacy.UpstreamAccountScope) + selected := ModerationUpstreamSelected + ids := []int64{2, 1, 1} + view, err := s.UpdateConfig(ctx, UpdateContentModerationConfigInput{UpstreamAccountScope: &selected, UpstreamAccountIDs: &ids}) + require.NoError(t, err) + require.ElementsMatch(t, []int64{1, 2}, view.UpstreamAccountIDs) + fresh := NewContentModerationService(repo, nil, nil, nil, nil, nil, nil, nil, accounts) + reloaded, err := fresh.GetConfig(ctx) + require.NoError(t, err) + require.Equal(t, view.UpstreamAccountIDs, reloaded.UpstreamAccountIDs) + require.Equal(t, selected, reloaded.UpstreamAccountScope) + for _, invalid := range []string{"unknown", "", "ALL"} { + _, err = fresh.UpdateConfig(ctx, UpdateContentModerationConfigInput{UpstreamAccountScope: &invalid}) + require.Error(t, err) + } + for _, invalid := range [][]int64{{0}, {-1}, {999}} { + _, err = fresh.UpdateConfig(ctx, UpdateContentModerationConfigInput{UpstreamAccountIDs: &invalid}) + require.Error(t, err) + } + accounts.accounts[3] = &Account{ID: 3, Platform: "customer", Type: AccountTypeAPIKey} + invalid := []int64{3} + _, err = fresh.UpdateConfig(ctx, UpdateContentModerationConfigInput{UpstreamAccountIDs: &invalid}) + require.Error(t, err) + accounts.accounts[3] = &Account{ID: 3, Platform: PlatformOpenAI, Type: "bps"} + _, err = fresh.UpdateConfig(ctx, UpdateContentModerationConfigInput{UpstreamAccountIDs: &invalid}) + require.Error(t, err) + var stored ContentModerationConfig + require.NoError(t, json.Unmarshal([]byte(repo.values[SettingKeyContentModerationConfig]), &stored)) + group := int64(10) + stored.AllGroups = false + stored.GroupIDs = []int64{10, 20} + input := ContentModerationCheckInput{GroupID: &group, Model: "gpt-5.1", UpstreamAccount: accounts.accounts[1]} + applies, err := fresh.UpstreamModerationApplies(ctx, &stored, input) + require.NoError(t, err) + require.True(t, applies) + group = 30 + applies, err = fresh.UpstreamModerationApplies(ctx, &stored, input) + require.NoError(t, err) + require.False(t, applies) + group = 10 + accounts.accounts[1].GroupIDs = []int64{30} + _, err = fresh.UpstreamModerationApplies(ctx, &stored, input) + require.Error(t, err, "moving accounts cannot widen scope") + _, err = fresh.UpdateConfig(ctx, UpdateContentModerationConfigInput{}) + require.Error(t, err, "unrelated saves cannot silently rebind a moved account") + delete(accounts.accounts, 1) + _, err = fresh.UpstreamModerationApplies(ctx, &stored, input) + require.Error(t, err, "deleted account must fail closed") + stored.UpstreamAccountIDs = nil + applies, err = fresh.UpstreamModerationApplies(ctx, &stored, input) + require.NoError(t, err) + require.False(t, applies, "empty selected must not mean all") + stored.UpstreamAccountScope = "future" + _, err = fresh.UpstreamModerationApplies(ctx, &stored, input) + require.Error(t, err) +} diff --git a/backend/internal/service/grok_audio.go b/backend/internal/service/grok_audio.go index e4b27594765b..1829b270bf1f 100644 --- a/backend/internal/service/grok_audio.go +++ b/backend/internal/service/grok_audio.go @@ -36,6 +36,10 @@ var supportedGrokVoiceHTTPEndpoints = map[string]struct{}{ // The response is intentionally passed through because TTS returns audio bytes // while STT returns JSON and xAI may add format-specific headers. func (s *OpenAIGatewayService) ForwardGrokVoice(ctx context.Context, c *gin.Context, account *Account, endpoint string, body []byte, contentType string) (*OpenAIForwardResult, error) { + if err := CheckUpstreamModeration(ctx, c, account); err != nil { + return nil, err + } + if s == nil || account == nil { return nil, fmt.Errorf("grok voice service/account is required") } diff --git a/backend/internal/service/grok_media.go b/backend/internal/service/grok_media.go index 8f4d50092df2..d579446b7d21 100644 --- a/backend/internal/service/grok_media.go +++ b/backend/internal/service/grok_media.go @@ -656,6 +656,10 @@ func (s *OpenAIGatewayService) ForwardGrokMedia( body []byte, contentType string, ) (*OpenAIForwardResult, error) { + if err := CheckUpstreamModeration(ctx, c, account); err != nil { + return nil, err + } + startTime := time.Now() if account == nil { return nil, fmt.Errorf("grok account is required") diff --git a/frontend/src/api/admin/riskControl.ts b/frontend/src/api/admin/riskControl.ts index 55a034a4afd7..f014fd4b72a1 100644 --- a/frontend/src/api/admin/riskControl.ts +++ b/frontend/src/api/admin/riskControl.ts @@ -20,6 +20,8 @@ export interface ContentModerationModelFilter { } export interface ContentModerationConfig { + upstream_account_scope?: 'all' | 'selected' + upstream_account_ids?: number[] engine?: ModerationEngine engine_configs?: Record enabled: boolean @@ -109,6 +111,8 @@ export interface ContentModerationTestAuditResult { } export interface UpdateContentModerationConfig { + upstream_account_scope?: 'all' | 'selected' + upstream_account_ids?: number[] engine?: ModerationEngine engine_configs?: Partial> enabled?: boolean diff --git a/frontend/src/components/admin/moderation/ModerationUpstreamAccountSelector.vue b/frontend/src/components/admin/moderation/ModerationUpstreamAccountSelector.vue new file mode 100644 index 000000000000..456d281bd44e --- /dev/null +++ b/frontend/src/components/admin/moderation/ModerationUpstreamAccountSelector.vue @@ -0,0 +1,86 @@ + + + diff --git a/frontend/src/components/admin/moderation/__tests__/ModerationUpstreamAccountSelector.spec.ts b/frontend/src/components/admin/moderation/__tests__/ModerationUpstreamAccountSelector.spec.ts new file mode 100644 index 000000000000..4301f64e6fc8 --- /dev/null +++ b/frontend/src/components/admin/moderation/__tests__/ModerationUpstreamAccountSelector.spec.ts @@ -0,0 +1,56 @@ +import { describe, expect, it, vi, beforeEach } from 'vitest' +import { defineComponent, ref } from 'vue' +import { flushPromises, mount } from '@vue/test-utils' +import Selector from '../ModerationUpstreamAccountSelector.vue' +import QualityAccountSelector from '@/components/admin/operations/QualityAccountSelector.vue' + +const { list } = vi.hoisted(() => ({ list: vi.fn() })) +vi.mock('@/api/admin', () => ({ adminAPI: { accounts: { list } } })) +vi.mock('vue-i18n', () => ({ useI18n: () => ({ t: (key: string) => key }) })) +const row = (id: number) => ({ id, name: `Fixture ${id}`, platform: 'openai', type: 'oauth' }) +const response = (ids: number[], page = 1, pages = 3) => ({ items: ids.map(row), page, pages, total: 125 }) +function mountPicker() { + return mount(defineComponent({ components: { Selector }, setup() { return { ids: ref([999]), scope: ref('selected') } }, template: '' })) +} +beforeEach(() => list.mockReset()) +describe('Moderation real QualityAccountSelector integration', () => { + it('retains hidden IDs across search, type/group filters, pagination and batch union', async () => { + list.mockResolvedValue(response([1, 2])) + const wrapper = mountPicker(); await flushPromises() + expect(wrapper.findComponent(QualityAccountSelector).exists()).toBe(true) + await wrapper.get('[data-testid="quality-select-page"]').trigger('click') + expect(wrapper.vm.ids).toEqual([999, 1, 2]) + list.mockResolvedValue(response([51], 2)) + wrapper.findComponent(QualityAccountSelector).vm.$emit('search', 2); await flushPromises() + expect(list.mock.lastCall?.[0]).toBe(2) + await wrapper.get('[data-account-id="51"] input').setValue(true) + await wrapper.get('#moderation-upstream-search').setValue('#125'); await flushPromises() + await wrapper.get('[data-testid="quality-account-type"]').setValue('oauth'); await flushPromises() + await wrapper.get('[data-testid="quality-account-group"]').setValue('1'); await flushPromises() + expect(list.mock.lastCall?.[2]).toMatchObject({ search: '#125', type: 'oauth', group: '1' }) + list.mockResolvedValueOnce(response([125], 1, 2)).mockResolvedValueOnce(response([126], 2, 2)) + await wrapper.get('[data-testid="quality-select-all"]').trigger('click'); await flushPromises() + expect(wrapper.vm.ids).toEqual([999, 1, 2, 51, 125, 126]) + wrapper.unmount() + }) + it('fences late page responses and a batch after clear or filter change', async () => { + let oldPage!: (value: ReturnType) => void + list.mockImplementationOnce(() => new Promise(resolve => { oldPage = resolve })) + const wrapper = mountPicker() + list.mockResolvedValue(response([125])) + await wrapper.get('#moderation-upstream-search').setValue('#125'); await flushPromises() + oldPage(response([1])); await flushPromises() + expect(wrapper.find('[data-account-id="125"]').exists()).toBe(true) + expect(wrapper.find('[data-account-id="1"]').exists()).toBe(false) + let batch!: (value: ReturnType) => void + list.mockImplementationOnce(() => new Promise(resolve => { batch = resolve })) + await wrapper.get('[data-testid="quality-select-all"]').trigger('click') + await wrapper.get('[data-testid="quality-clear-selection"]').trigger('click') + batch(response([1], 1, 1)); await flushPromises() + expect(wrapper.vm.ids).toEqual([]) + await wrapper.get('[data-testid="moderation-upstream-all"]').setValue(true) + expect(wrapper.findComponent(QualityAccountSelector).exists()).toBe(false) + expect(wrapper.vm.ids).toEqual([]) + wrapper.unmount() + }) +}) diff --git a/frontend/src/constants/newFeatureNotices.ts b/frontend/src/constants/newFeatureNotices.ts index fc323280a365..5da3cbe06d2a 100644 --- a/frontend/src/constants/newFeatureNotices.ts +++ b/frontend/src/constants/newFeatureNotices.ts @@ -4,6 +4,7 @@ * browser; use a new ID to announce the feature again in a later release. */ export const NEW_FEATURE_NOTICES = { + moderationUpstreamAccountScope: 'moderation-upstream-account-scope', adminUsagePlatform: 'admin-usage-platform-filter-initial-announcement', usageTrendRate: 'usage-trend-tooltip-rpm-tpm-initial-announcement', priorityCacheWeight: 'priority-cache-weight-initial-announcement', diff --git a/frontend/src/i18n/locales/en/admin/channels.ts b/frontend/src/i18n/locales/en/admin/channels.ts index 7f1c4fa3d425..389cc442a76a 100644 --- a/frontend/src/i18n/locales/en/admin/channels.ts +++ b/frontend/src/i18n/locales/en/admin/channels.ts @@ -494,6 +494,17 @@ export default { allGroups: 'All Groups', allGroupsHint: 'Auditing all groups', selectedGroupsHint: 'Auditing selected groups', + upstreamAccounts: "Upstream account scope", + upstreamAccountsHint: "Audit only when the actual selected upstream account AND the group/model rules below match. These are provider accounts on this site, not customers. Choose All groups below for an account-only policy.", + allUpstreamAccounts: "All upstream accounts (existing behavior)", + selectedUpstreamAccounts: "Only selected upstream accounts", + emptyUpstreamAccounts: "No accounts selected: this policy audits no requests.", + findUpstreamAccounts: "Find upstream accounts by name or #ID", + upstreamSelectionHint: "Filters only change this list. Selected IDs remain selected across pages and filters. Deleted accounts or changed platform, type or group membership require review and reselection; affected requests fail closed.", + upstreamAccountsLoadFailed: "Could not load all accounts. Selection was preserved. Retry or select fewer than 10,000 accounts.", + upstreamType: "Upstream", + bedrockType: "AWS Bedrock", + serviceAccountType: "Service account", groupScope: 'Audit Groups', groupScopeHint: 'Switch on for all groups, or turn off to choose specific groups.', selectedGroups: 'Selected Groups', diff --git a/frontend/src/i18n/locales/zh/admin/channels.ts b/frontend/src/i18n/locales/zh/admin/channels.ts index 5b0b3ba25918..6f1a80bae770 100644 --- a/frontend/src/i18n/locales/zh/admin/channels.ts +++ b/frontend/src/i18n/locales/zh/admin/channels.ts @@ -494,6 +494,17 @@ export default { allGroups: '全部分组', allGroupsHint: '当前审计全部分组', selectedGroupsHint: '当前审计指定分组', + upstreamAccounts: "上游账号范围", + upstreamAccountsHint: "仅实际调度的上游账号与下方分组、模型规则同时匹配时审计。这里选择本站的供应商账号,不是调用者或客户。下方选择“全部分组”可仅按账号限制。", + allUpstreamAccounts: "全部上游账号(保持原有行为)", + selectedUpstreamAccounts: "仅指定上游账号", + emptyUpstreamAccounts: "尚未选择账号:此规则不会审计任何请求。", + findUpstreamAccounts: "按名称或 #ID 查找上游账号", + upstreamSelectionHint: "筛选仅改变列表;翻页或修改筛选不会丢失已选 ID。账号删除或平台、类型、分组归属变化后,受影响请求将安全拒绝,需检查并重新选择。", + upstreamAccountsLoadFailed: "无法加载完整账号列表,已保留原选择。请重试或将选择控制在 10,000 个以内。", + upstreamType: "上游账号", + bedrockType: "AWS Bedrock", + serviceAccountType: "服务账号", groupScope: '审计分组', groupScopeHint: '开启右侧开关表示全部分组,关闭后选择指定分组。', selectedGroups: '指定分组', diff --git a/frontend/src/views/admin/RiskControlView.vue b/frontend/src/views/admin/RiskControlView.vue index 1182b4cd9201..ecebff5b5d87 100644 --- a/frontend/src/views/admin/RiskControlView.vue +++ b/frontend/src/views/admin/RiskControlView.vue @@ -410,6 +410,7 @@ > {{ tab.label }} +
@@ -753,6 +754,9 @@
+ + +

{{ t('admin.riskControl.groupScope') }}

@@ -1209,6 +1213,10 @@ import { moderationThresholdDefaults, moderationCategorySettings, moderationScoreRows as buildModerationScoreRows, optionalModerationCategories } from '@/utils/contentModerationCategories' import { computed, onMounted, onUnmounted, reactive, ref, toRaw } from 'vue' import { useI18n } from 'vue-i18n' +import ModerationUpstreamAccountSelector from '@/components/admin/moderation/ModerationUpstreamAccountSelector.vue' +import NewFeatureBadge from '@/components/common/NewFeatureBadge.vue' +import { NEW_FEATURE_NOTICES } from '@/constants/newFeatureNotices' +import { useAuthStore } from '@/stores/auth' import AppLayout from '@/components/layout/AppLayout.vue' import BaseDialog from '@/components/common/BaseDialog.vue' import SecurityAuditNav from '@/components/admin/security/SecurityAuditNav.vue' @@ -1275,6 +1283,7 @@ const { t } = useI18n() const moderationUsersMounted = ref(false) const moderationUsersExpanded = ref(false) const appStore = useAppStore() +const auth = useAuthStore() const defaultBlockMessage = () => t('admin.riskControl.defaultBlockMessage') const loading = ref(true) @@ -1323,6 +1332,8 @@ const configForm = reactive({ timeout_ms: 3000, retry_count: 2, sample_rate: 100, + upstream_account_scope: 'all' as 'all' | 'selected', + upstream_account_ids: [] as number[], all_groups: true, group_ids: [] as number[], record_non_hits: false, @@ -1850,6 +1861,8 @@ function applyConfig(config: ContentModerationConfig) { configForm.timeout_ms = config.timeout_ms || 3000 configForm.retry_count = config.retry_count ?? 2 configForm.sample_rate = config.sample_rate ?? 100 + configForm.upstream_account_scope = config.upstream_account_scope ?? 'all' + configForm.upstream_account_ids = [...(config.upstream_account_ids ?? [])] configForm.all_groups = config.all_groups configForm.group_ids = Array.isArray(config.group_ids) ? [...config.group_ids] : [] configForm.record_non_hits = config.record_non_hits @@ -1959,6 +1972,8 @@ async function saveConfig() { timeout_ms: Number(configForm.timeout_ms) || 3000, retry_count: Number(configForm.retry_count) || 0, sample_rate: Number(configForm.sample_rate) || 0, + upstream_account_scope: configForm.upstream_account_scope, + upstream_account_ids: [...configForm.upstream_account_ids], all_groups: configForm.all_groups, group_ids: configForm.all_groups ? [] : [...configForm.group_ids], record_non_hits: configForm.record_non_hits, diff --git a/frontend/src/views/admin/__tests__/RiskControlView.spec.ts b/frontend/src/views/admin/__tests__/RiskControlView.spec.ts index 1752d168ea18..a5b2691d4d12 100644 --- a/frontend/src/views/admin/__tests__/RiskControlView.spec.ts +++ b/frontend/src/views/admin/__tests__/RiskControlView.spec.ts @@ -1,5 +1,6 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import { defineComponent, h } from 'vue' +import { createPinia } from 'pinia' import { config, flushPromises, mount, RouterLinkStub } from '@vue/test-utils' import SecurityAuditNav from '@/components/admin/security/SecurityAuditNav.vue' import type { DOMWrapper, VueWrapper } from '@vue/test-utils' @@ -59,6 +60,7 @@ vi.mock('@/api/admin/riskControl', () => ({ manageModerationUser: vi.fn(), })) config.global.stubs.RouterLink = RouterLinkStub +config.global.plugins = [...(config.global.plugins ?? []), createPinia()] vi.mock('@/stores/app', () => ({ useAppStore: () => ({ From 816d090528f006877d24b3e6ac3748dca9479cc7 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sat, 14 Nov 2026 19:41:36 +0800 Subject: [PATCH 5/8] fix: close moderation dispatch gaps and isolate local policy denials --- .github/scripts/moderation-scope-preview.mjs | 131 ++++++++++++------ .../workflows/moderation-upstream-scope.yml | 13 +- .../admin/content_moderation_handler.go | 15 +- .../admin/moderation_upstream_scope_test.go | 115 +++++++++++++++ backend/internal/handler/gateway_handler.go | 6 + .../gateway_handler_chat_completions.go | 3 + .../handler/gateway_handler_responses.go | 3 + backend/internal/handler/gateway_systemone.go | 3 + .../internal/handler/gateway_web_search.go | 3 + .../handler/gemini_cached_contents_handler.go | 4 + .../internal/handler/gemini_v1beta_handler.go | 3 + backend/internal/handler/grok_audio.go | 3 + backend/internal/handler/grok_media.go | 3 + .../moderation_upstream_dispatch_test.go | 88 ++++++++++++ .../handler/moderation_upstream_http_test.go | 39 ++++-- .../moderation_upstream_images_test.go | 99 +++++++++++++ .../handler/moderation_upstream_scope.go | 34 ++++- .../moderation_upstream_systemone_test.go | 71 ++++++++++ .../handler/moderation_upstream_ws_test.go | 39 +++++- .../internal/handler/openai_alpha_search.go | 3 + .../handler/openai_chat_completions.go | 3 + backend/internal/handler/openai_embeddings.go | 3 + .../handler/openai_gateway_handler.go | 20 ++- backend/internal/handler/openai_images.go | 3 + .../openai_images_native_route_test.go | 7 +- .../content_moderation_upstream_scope.go | 16 ++- .../content_moderation_upstream_scope_test.go | 2 + backend/internal/service/minimax_h3.go | 4 + .../service/openai_account_scheduler.go | 4 +- .../internal/service/openai_alpha_search.go | 4 + backend/internal/service/openai_embeddings.go | 4 + backend/internal/service/seedance.go | 4 + .../moderation-upstream-account-scope.md | 11 ++ .../ModerationUpstreamAccountSelector.vue | 4 +- .../common/__tests__/NewFeatureBadge.spec.ts | 1 + .../src/i18n/locales/en/admin/channels.ts | 2 +- .../src/i18n/locales/zh/admin/channels.ts | 2 +- frontend/src/views/admin/RiskControlView.vue | 12 +- .../admin/__tests__/RiskControlView.spec.ts | 37 +++++ 39 files changed, 736 insertions(+), 85 deletions(-) create mode 100644 backend/internal/handler/admin/moderation_upstream_scope_test.go create mode 100644 backend/internal/handler/moderation_upstream_dispatch_test.go create mode 100644 backend/internal/handler/moderation_upstream_images_test.go create mode 100644 backend/internal/handler/moderation_upstream_systemone_test.go diff --git a/.github/scripts/moderation-scope-preview.mjs b/.github/scripts/moderation-scope-preview.mjs index b2bfa5aab20b..2221f062b233 100644 --- a/.github/scripts/moderation-scope-preview.mjs +++ b/.github/scripts/moderation-scope-preview.mjs @@ -1,4 +1,4 @@ -// Actual Vue view + shared components; synthetic API adapter; GitHub Actions only. +// Remote-only actual RiskControlView/selector/CSS; all APIs are synthetic. import assert from 'node:assert/strict' import { createHash } from 'node:crypto' import { execFileSync } from 'node:child_process' @@ -7,62 +7,113 @@ import { createRequire } from 'node:module' import { tmpdir } from 'node:os' import { dirname, join } from 'node:path' import { pathToFileURL } from 'node:url' -const repo=process.cwd(), root=join(repo,'frontend'), output=process.env.EVIDENCE_DIR -if(!output || !process.env.GITHUB_ACTIONS) throw Error('GitHub Actions only') +const repo=process.cwd(),root=join(repo,'frontend'),output=process.env.EVIDENCE_DIR +if(!output || !process.env.GITHUB_ACTIONS)throw Error('GitHub Actions only') const req=createRequire(join(root,'package.json')) const {createServer}=await import(pathToFileURL(join(dirname(req.resolve('vite/package.json')),'dist/node/index.js')).href) const vue=(await import(pathToFileURL(req.resolve('@vitejs/plugin-vue')).href)).default const {chromium}=await import(pathToFileURL(process.env.SUB2API_PLAYWRIGHT_MODULE).href) -const head=execFileSync('git',['rev-parse','HEAD'],{encoding:'utf8'}).trim() -const hash=x=>createHash('sha256').update(x).digest('hex') -const entryName=`.moderation-preview-${process.pid}.js`, entry=join(root,entryName), cacheDir=mkdtempSync(join(tmpdir(),'moderation-preview-')) -const captures=[],errors=[] -let server,browser +const git=(...args)=>execFileSync('git',args,{cwd:repo,encoding:'utf8'}).trimEnd() +const head=git('rev-parse','HEAD'),base='4189ed821d6e4308b2f5fc3791b73d2eb53cda8a',hash=x=>createHash('sha256').update(x).digest('hex') +const sourceFiles=['frontend/src/views/admin/RiskControlView.vue','frontend/src/i18n/locales/en/admin/channels.ts','frontend/src/i18n/locales/zh/admin/channels.ts','frontend/src/constants/newFeatureNotices.ts','frontend/src/components/common/BaseDialog.vue','frontend/src/components/admin/operations/QualityAccountSelector.vue','frontend/src/style.css','frontend/tailwind.config.js','frontend/postcss.config.js'] +const sources=Object.fromEntries(sourceFiles.map(file=>[file,{before:hash(git('show',`${base}:${file}`)),after:hash(readFileSync(join(repo,file),'utf8').trimEnd())}])) +sources['frontend/src/components/admin/moderation/ModerationUpstreamAccountSelector.vue']={after:hash(readFileSync(join(root,'src/components/admin/moderation/ModerationUpstreamAccountSelector.vue'),'utf8').trimEnd())} +const entryName=`.moderation-preview-${process.pid}.js`,entry=join(root,entryName),cacheDir=mkdtempSync(join(tmpdir(),'moderation-preview-')) +const captures=[],assertions=[],errors=[],reachability=[] +let before=true,server,browser,page mkdirSync(output,{recursive:true}) try{ writeFileSync(entry,` -import {createApp} from 'vue'; import {createPinia} from 'pinia'; -import {createRouter,createMemoryHistory} from 'vue-router'; -import {i18n,loadLocaleMessages} from '/src/i18n/index.ts'; -import {apiClient} from '/src/api/client.ts'; -import View from '/src/views/admin/RiskControlView.vue'; import '/src/style.css'; -const locale=new URL(location.href).searchParams.get('locale')||'en'; -await loadLocaleMessages(locale);i18n.global.locale.value=locale; -const cfg={enabled:true,mode:'pre_block',base_url:'https://audit.example',model:'fixture-moderation',api_key_statuses:[],api_key_masks:[],api_key_count:0,timeout_ms:3000,sample_rate:100,all_groups:true,group_ids:[],worker_count:4,queue_size:32768,block_status:403,block_message:'Synthetic fixture',thresholds:{},blocked_keywords:[],model_filter:{type:'all',models:[]}}; -apiClient.defaults.adapter=async config=>{let data; const u=config.url; -if(u==='/admin/risk-control/config')data=cfg; -else if(u==='/admin/groups/all')data=[{id:4301,name:'Demo OpenAI',platform:'openai'},{id:4302,name:'Demo Anthropic',platform:'anthropic'}]; +import {createApp,h} from 'vue';import {createPinia} from 'pinia';import {createRouter,createMemoryHistory} from 'vue-router'; +import {i18n,loadLocaleMessages} from '/src/i18n/index.ts';import {apiClient} from '/src/api/client.ts'; +import {useAuthStore} from '/src/stores/auth.ts';import Badge from '/src/components/common/NewFeatureBadge.vue'; +import View from '/src/views/admin/RiskControlView.vue';import '/src/style.css'; +const locale=new URL(location.href).searchParams.get('locale')||'en';await loadLocaleMessages(locale);i18n.global.locale.value=locale; +const defaults={enabled:true,mode:'pre_block',base_url:'https://audit.example',model:'fixture-moderation',api_key_statuses:[],api_key_masks:[],api_key_count:0,timeout_ms:3000,sample_rate:100,all_groups:true,group_ids:[],worker_count:4,queue_size:32768,block_status:403,block_message:'Synthetic fixture',thresholds:{},blocked_keywords:[],model_filter:{type:'all',models:[]},upstream_account_scope:'selected',upstream_account_ids:[121,999]}; +let cfg=JSON.parse(localStorage.getItem('fixture-config')||'null')||defaults; +const catalogue=Array.from({length:125},(_,i)=>({id:i+1,name:'Demo account '+(i+1),platform:'openai',type:i%2?'oauth':'apikey',group_ids:[i%2?4301:4302]})); +window.__writes=[];window.__reads=[];window.__held=[]; +apiClient.defaults.adapter=async config=>{let data;const u=config.url;window.__reads.push({url:u,params:config.params}); +if(u==='/admin/risk-control/config'){ + if(config.method==='put'){const body=JSON.parse(config.data);window.__writes.push(body);cfg={...cfg,...body};localStorage.setItem('fixture-config',JSON.stringify(cfg));} + data=structuredClone(cfg); +}else if(u==='/admin/accounts'){ + const p=config.params;let rows=catalogue.filter(a=>(!p.search||a.name.toLowerCase().includes(p.search.toLowerCase())||String(a.id)===p.search.replace(/^#/,''))&&(!p.type||a.type===p.type)&&(!p.group||a.group_ids.includes(Number(p.group)))); + data={items:rows.slice((p.page-1)*p.page_size,p.page*p.page_size),total:rows.length,page:p.page,pages:Math.ceil(rows.length/p.page_size),page_size:p.page_size}; + if(window.__holdNext){window.__holdNext=false;await new Promise(resolve=>window.__held.push(resolve));} +}else if(u==='/admin/groups/all')data=[{id:4301,name:'Demo OpenAI A',platform:'openai'},{id:4302,name:'Demo OpenAI B',platform:'openai'}]; else if(u==='/admin/proxies/all')data=[]; else if(u==='/admin/risk-control/status')data={enabled:true,risk_control_enabled:true,mode:'pre_block',worker_count:4,api_key_statuses:[],pre_block_api_key_loads:[]}; else if(u==='/admin/risk-control/logs')data={items:[],total:0,page:1,page_size:20}; else throw Error('Unexpected offline API '+u); return {config,status:200,statusText:'OK',headers:{},data:{code:0,data}};}; +const pinia=createPinia();const auth=useAuthStore(pinia);auth.user={id:7,role:'admin',username:'Fixture admin'}; +const storage='sub2api:new-feature-notices:v1:7';if(!localStorage.getItem(storage))localStorage.setItem(storage,JSON.stringify(['fixture-feature-a'])); const router=createRouter({history:createMemoryHistory(),routes:[{path:'/:pathMatch(.*)*',component:View}]}); -const app=createApp(View);app.use(createPinia());app.use(i18n);app.use(router);await router.isReady();app.mount('#app'); -window.__t=key=>i18n.global.t(key); +const app=createApp({render:()=>h('div',[h(View),h('div',{'data-testid':'fixture-badges'},[h(Badge,{noticeId:'fixture-feature-a',userId:7}),h(Badge,{noticeId:'fixture-feature-c',userId:7})])])}); +app.use(pinia);app.use(i18n);app.use(router);await router.isReady();app.mount('#app');window.__t=key=>i18n.global.t(key); `,{flag:'wx'}) process.chdir(root) server=await createServer({root,configFile:false,cacheDir,resolve:{alias:{'@':join(root,'src')}},plugins:[{ -name:'fixture-layout',enforce:'pre',load(id){if(id===join(root,'src/components/layout/AppLayout.vue'))return ''}, -configureServer(vite){vite.middlewares.use((req,res,next)=>{if(req.url==='/'||req.url?.startsWith('/?')){res.setHeader('Content-Type','text/html');res.end('
')}else if(req.url==='/favicon.ico'){res.statusCode=204;res.end()}else next()})}},vue()],server:{host:'127.0.0.1',port:4299,strictPort:true},optimizeDeps:{entries:[],include:['vue','pinia','vue-router','vue-i18n','axios']}}) + name:'fixture-layout-and-pinned-baseline',enforce:'pre',load(id){ + if(id===join(root,'src/components/layout/AppLayout.vue'))return '' + if(before&&!id.includes('?')){const file=sourceFiles.find(file=>join(repo,file)===id);if(file)return git('show',`${base}:${file}`)} + },configureServer(vite){vite.middlewares.use((req,res,next)=>{if(req.url==='/'||req.url?.startsWith('/?')){res.setHeader('Content-Type','text/html');res.end('
')}else if(req.url==='/favicon.ico'){res.statusCode=204;res.end()}else next()})}},vue()],server:{host:'127.0.0.1',port:4299,strictPort:true},optimizeDeps:{entries:[],include:['vue','pinia','vue-router','vue-i18n','axios']}}) await server.listen();browser=await chromium.launch({headless:true}) -for(const locale of ['en','zh'])for(const [device,width,height] of [['desktop',1280,1000],['mobile',390,844]]){ - const page=await browser.newPage({viewport:{width,height}}) - page.on('pageerror',e=>errors.push(e.message)) - await page.route('**/*',route=>new URL(route.request().url()).origin==='http://127.0.0.1:4299'?route.continue():route.abort()) - await page.goto('http://127.0.0.1:4299/?locale='+locale,{waitUntil:'networkidle'}) - const label=await page.evaluate(()=>window.__t('admin.riskControl.openSettings')) - await page.getByRole('button',{name:label,exact:true}).click() - const scope=await page.evaluate(()=>window.__t('admin.riskControl.tabs.scope')) - await page.getByRole('button',{name:scope,exact:true}).click() - await page.locator('[role="dialog"]').waitFor() +const settle=async()=>{ + await page.waitForFunction(()=>{const d=document.querySelector('[role="dialog"]'),p=d?.querySelector('.modal-content');return d&&p&&getComputedStyle(d).opacity==='1'&&getComputedStyle(p).opacity==='1'&&!d.className.includes('modal-enter')&&d.getAnimations({subtree:true}).every(a=>a.playState==='finished')}) + await page.evaluate(()=>new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve)))) +} +const openScope=async()=>{ + await page.getByRole('button',{name:await page.evaluate(()=>window.__t('admin.riskControl.openSettings')),exact:true}).click() + await settle() + const scope=page.getByRole('button',{name:await page.evaluate(()=>window.__t('admin.riskControl.tabs.scope')),exact:true}) + await scope.click();await settle() + await page.waitForFunction(label=>Array.from(document.querySelectorAll('[role="dialog"] button')).some(el=>el.textContent.trim()===label&&el.classList.contains('bg-primary-50')),await scope.textContent().then(x=>x.trim())) + const css=await page.locator('.modal-overlay').evaluate(el=>({position:getComputedStyle(el).position,display:getComputedStyle(el).display})) + assert.deepEqual(css,{position:'fixed',display:'flex'}) assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true) - const file='before-'+device+'-'+locale+'.png';await page.screenshot({path:join(output,file),fullPage:true}) - captures.push({file,sha256:hash(readFileSync(join(output,file))),viewport:{width,height},locale}) - await page.close() } -assert.deepEqual(errors,[]) -}finally{ -writeFileSync(join(output,'manifest.json'),JSON.stringify({head,captures,errors,boundary:'Actual RiskControlView, BaseDialog, shared components, project CSS and locales. Layout shell fixture; synthetic offline axios API. No real upstreams.'},null,2)+'\n') -await browser?.close();await server?.close();rmSync(entry,{force:true});rmSync(cacheDir,{recursive:true,force:true}) +const reach=async(locator,label)=>{ + for(let i=0;i<25;i++){ + const bounds=await locator.evaluate(el=>{const r=el.getBoundingClientRect(),p=el.closest('.modal-body')?.getBoundingClientRect();const x=r.x+r.width/2,y=r.y+r.height/2,hit=document.elementFromPoint(x,y);return {x,y,top:r.top,bottom:r.bottom,inside:r.left>=0&&r.right<=innerWidth&&r.top>=(p?.top??0)&&r.bottom<=(p?.bottom??innerHeight),hit:hit===el||el.contains(hit),parentTop:p?.top??0}}) + if(bounds.inside&&bounds.hit){reachability.push({label,...bounds});return} + const box=await page.locator('.modal-body').boundingBox();await page.mouse.move(box.x+box.width/2,box.y+box.height/2);await page.mouse.wheel(0,bounds.toperrors.push(e.message)) + await page.route('**/*',route=>{const u=new URL(route.request().url());if(u.origin==='http://127.0.0.1:4299'||u.protocol==='data:')return route.continue();errors.push('external request '+u.origin);return route.abort()}) + await page.goto('http://127.0.0.1:4299/?locale='+locale,{waitUntil:'networkidle'});await openScope() + if(!before){await page.locator('[data-account-id="50"]').waitFor();await reach(page.getByTestId('quality-select-page'),'select page '+device+' '+locale)} + const file=phase+'-'+device+'-'+locale+'.png';await page.screenshot({path:join(output,file),fullPage:true});captures.push({file,sha256:hash(readFileSync(join(output,file))),viewport:{width,height},locale,source:before?base:head,settled:true,activeTab:'scope'}) + if(!before&&locale==='en'&&device==='desktop'){ + const picker=page.getByTestId('moderation-upstream-selector'),search=page.locator('#moderation-upstream-search') + assert.equal(await picker.locator('[data-account-id]').count(),50) + await picker.getByTestId('quality-select-page').click() + await reach(picker.getByRole('button',{name:await page.evaluate(()=>window.__t('qualityOps.nextAccountPage'))}),'next page') + await picker.getByRole('button',{name:await page.evaluate(()=>window.__t('qualityOps.nextAccountPage'))}).click();await picker.locator('[data-account-id="51"]').waitFor() + await picker.locator('[data-account-id="51"] input').check() + await reach(search,'search');await search.fill('#125');await picker.locator('[data-account-id="125"]').waitFor();assert.equal(await picker.locator('[data-account-id]').count(),1) + await picker.locator('[data-account-id="125"] input').check() + await page.evaluate(()=>window.__holdNext=true);await search.fill('Demo account 1');await page.waitForFunction(()=>window.__held.length===1) + await search.fill('#124');await picker.locator('[data-account-id="124"]').waitFor();await page.evaluate(()=>window.__held.shift()());await page.waitForTimeout(100);assert.equal(await picker.locator('[data-account-id]').count(),1) + await search.fill('Demo account');await picker.getByTestId('quality-account-type').selectOption('oauth');await picker.getByTestId('quality-account-group').selectOption('4301');await page.waitForFunction(()=>document.querySelectorAll('[data-account-id]').length===50) + await picker.getByTestId('quality-select-all').click();await page.waitForFunction(()=>document.querySelector('[data-testid="quality-select-all"]').disabled===false) + const save=page.getByRole('button',{name:await page.evaluate(()=>window.__t('admin.riskControl.saveConfig')),exact:true});await save.click();await page.locator('[role="dialog"]').waitFor({state:'detached'}) + const written=await page.evaluate(()=>window.__writes.at(-1));assert(written.upstream_account_ids.includes(999));assert(written.upstream_account_ids.includes(121));assert(written.upstream_account_ids.includes(125));assert(written.upstream_account_ids.includes(124));assert.equal(written.upstream_account_scope,'selected') + await page.reload({waitUntil:'networkidle'});await openScope();await picker.locator('[data-account-id="50"]').waitFor();assert.equal(await picker.locator('[data-account-id="50"] input').isChecked(),true) + await picker.getByTestId('quality-clear-selection').click();await page.getByRole('button',{name:await page.evaluate(()=>window.__t('common.cancel')),exact:true}).click();await page.locator('[role="dialog"]').waitFor({state:'detached'});await openScope();await picker.locator('[data-account-id="50"]').waitFor();assert.equal(await picker.locator('[data-account-id="50"] input').isChecked(),true) + const badges=page.locator('[role="dialog"] [data-testid="new-feature-badge"]');assert.equal(await badges.count(),2);await badges.last().click();assert.equal(await badges.count(),0) + await page.reload({waitUntil:'networkidle'});await openScope();assert.equal(await page.locator('[role="dialog"] [data-testid="new-feature-badge"]').count(),0);assert.equal(await page.locator('[data-testid="fixture-badges"] [data-testid="new-feature-badge"]').count(),1) + assertions.push('Real parent/selector: name and #ID, type/group filters, pages, hidden selected IDs, batch union, late response fence, save/reload, cancel/reopen; A dismissed/B visible/shared dismissal/reload/C visible. Synthetic API transport; server persistence independently covered by authenticated Go handler tests.') + } + await page.close();page=undefined + } +} +assert.deepEqual(errors,[]) +}catch(error){if(page)await page.screenshot({path:join(output,'failure.png'),fullPage:true}).catch(()=>{});errors.push(error.stack);throw error} +finally{writeFileSync(join(output,'manifest.json'),JSON.stringify({head,base,sources,sourceHashNormalization:'trimEnd',captures,reachability,assertions,errors,boundary:'Actual RiskControlView, shared QualityAccountSelector, BaseDialog, project CSS/locales; layout shell and synthetic offline APIs only; pinned baseline and candidate, transitions settled and active scope tab asserted.'},null,2)+'\n');await browser?.close();await server?.close();rmSync(entry,{force:true});rmSync(cacheDir,{recursive:true,force:true})} diff --git a/.github/workflows/moderation-upstream-scope.yml b/.github/workflows/moderation-upstream-scope.yml index 8bb27336fad3..5f9bd60f1176 100644 --- a/.github/workflows/moderation-upstream-scope.yml +++ b/.github/workflows/moderation-upstream-scope.yml @@ -7,7 +7,7 @@ permissions: contents: read concurrency: group: moderation-upstream-scope-${{ github.ref }} - cancel-in-progress: true + cancel-in-progress: false jobs: behavioral-red: runs-on: ubuntu-latest @@ -34,7 +34,8 @@ jobs: set -e cat "$RUNNER_TEMP/moderation-scope/red.log" test "$result" -ne 0 - ! grep -Eiq 'build failed|no tests to run|undefined:|--- SKIP:' "$RUNNER_TEMP/moderation-scope/red.log" + if grep -Eiq 'build failed|no tests to run|undefined:|--- SKIP:|panic:|fatal error:|DATA RACE|signal:|segmentation fault' "$RUNNER_TEMP/moderation-scope/red.log"; then exit 1; fi + grep -q -- '--- FAIL: TestModerationUpstreamScopeUnselectedDoesNotAudit' "$RUNNER_TEMP/moderation-scope/red.log" grep -q 'unselected upstream account must make zero audit calls' "$RUNNER_TEMP/moderation-scope/red.log" - uses: actions/upload-artifact@v7 if: always() @@ -46,6 +47,8 @@ jobs: timeout-minutes: 20 steps: - uses: actions/checkout@v6 + with: + fetch-depth: 0 - uses: pnpm/action-setup@v6 with: version: 9 @@ -88,7 +91,11 @@ jobs: git rev-parse HEAD > "$RUNNER_TEMP/moderation-scope-green/head.txt" set -o pipefail cd backend - go test -race -tags=unit ./internal/handler ./internal/service ./internal/securityaudit -run 'TestModerationUpstream|TestOpenAIResponsesWebSocket_ContentModeration|Test.*SecurityAudit|Test.*Queue.*Auth|Test.*Turn.*Admission' -count=1 -v -timeout=10m 2>&1 | tee "$RUNNER_TEMP/moderation-scope-green/green.log" + go test -race -tags=unit ./internal/handler ./internal/handler/admin ./internal/service ./internal/securityaudit -run 'TestModerationUpstream|TestOpenAIResponsesWebSocket_ContentModeration|Test.*SecurityAudit|Test.*Queue.*Auth|Test.*Turn.*Admission|TestAPIKeyAdmissionRealForwardingHandlersRejectBeforeUpstream|TestOpenAIWSRevalidationFollowup|TestOpenAIWSRevalidationNativeImagePermissionTiming' -count=1 -v -timeout=10m 2>&1 | tee "$RUNNER_TEMP/moderation-scope-green/green.log" + if grep -Eiq 'build failed|no tests to run|undefined:|--- SKIP:|panic:|fatal error:|DATA RACE|signal:|segmentation fault' "$RUNNER_TEMP/moderation-scope-green/green.log"; then exit 1; fi + for name in TestModerationUpstreamScopeUnselectedDoesNotAudit TestModerationUpstreamHTTPSelectionAndFailover TestModerationUpstreamWebSocketModesAndTurns TestModerationUpstreamPersistenceAndValidation TestModerationUpstreamAdminSaveReloadAndAuthorization TestModerationUpstreamWebSocketTurnIdentityAfterFailover TestModerationUpstreamImagesJSONKeepaliveAndAsync TestModerationUpstreamSystemOneLocalDenial; do + grep -q -- "--- PASS: $name" "$RUNNER_TEMP/moderation-scope-green/green.log" + done - uses: actions/upload-artifact@v7 if: always() with: diff --git a/backend/internal/handler/admin/content_moderation_handler.go b/backend/internal/handler/admin/content_moderation_handler.go index 0d954c3c4af8..ab9d018ce477 100644 --- a/backend/internal/handler/admin/content_moderation_handler.go +++ b/backend/internal/handler/admin/content_moderation_handler.go @@ -30,12 +30,14 @@ func NewContentModerationHandlerWithSafetyPrompt(svc *service.ContentModerationS } type contentModerationConfigRequest struct { - Engine *string `json:"engine"` - EngineConfigs map[string]service.UpdateContentModerationEngineInput `json:"engine_configs"` - Enabled *bool `json:"enabled"` - Mode *string `json:"mode"` - BaseURL *string `json:"base_url"` - Model *string `json:"model"` + UpstreamAccountScope *string `json:"upstream_account_scope"` + UpstreamAccountIDs *[]int64 `json:"upstream_account_ids"` + Engine *string `json:"engine"` + EngineConfigs map[string]service.UpdateContentModerationEngineInput `json:"engine_configs"` + Enabled *bool `json:"enabled"` + Mode *string `json:"mode"` + BaseURL *string `json:"base_url"` + Model *string `json:"model"` // 审计请求使用的代理服务器:null 不修改;0 清除(直连);>0 指定代理。 ProxyID *int64 `json:"proxy_id"` APIKey *string `json:"api_key"` @@ -102,6 +104,7 @@ func (h *ContentModerationHandler) UpdateConfig(c *gin.Context) { } cfg, err := h.service.UpdateConfig(c.Request.Context(), service.UpdateContentModerationConfigInput{ Engine: req.Engine, EngineConfigs: req.EngineConfigs, + UpstreamAccountScope: req.UpstreamAccountScope, UpstreamAccountIDs: req.UpstreamAccountIDs, Enabled: req.Enabled, Mode: req.Mode, BaseURL: req.BaseURL, diff --git a/backend/internal/handler/admin/moderation_upstream_scope_test.go b/backend/internal/handler/admin/moderation_upstream_scope_test.go new file mode 100644 index 000000000000..65be66da2868 --- /dev/null +++ b/backend/internal/handler/admin/moderation_upstream_scope_test.go @@ -0,0 +1,115 @@ +package admin + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/server/middleware" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +type moderationUpstreamAccounts struct { + service.AccountRepository + account *service.Account +} + +func (r moderationUpstreamAccounts) GetByID(_ context.Context, id int64) (*service.Account, error) { + if r.account != nil && r.account.ID == id { + return r.account, nil + } + return nil, service.ErrAccountNotFound +} + +type moderationUpstreamUsers struct { + service.UserRepository + actor *service.User +} + +func (r moderationUpstreamUsers) GetByID(context.Context, int64) (*service.User, error) { + return r.actor, nil +} + +// Real admin authentication -> JSON DTO -> service validation -> persisted +// setting -> a fresh service/handler GET. No browser adapter stands in for this. +func TestModerationUpstreamAdminSaveReloadAndAuthorization(t *testing.T) { + gin.SetMode(gin.TestMode) + settings := &moderationEngineSettings{value: `{"all_groups":true}`} + account := &service.Account{ID: 51, Platform: service.PlatformOpenAI, Type: service.AccountTypeOAuth, GroupIDs: []int64{11, 12}} + accounts := moderationUpstreamAccounts{account: account} + auth := service.NewAuthService(nil, nil, nil, nil, &config.Config{JWT: config.JWTConfig{Secret: "fixture-moderation-secret", ExpireHour: 1}}, nil, nil, nil, nil, nil, nil, nil, nil) + for _, role := range []string{"", service.RoleUser, service.RoleObserver, service.RoleAdmin} { + t.Run(role, func(t *testing.T) { + actor := &service.User{ID: 7, Role: role, Status: service.StatusActive} + h := NewContentModerationHandler(service.NewContentModerationService(settings, nil, nil, nil, nil, nil, nil, nil, accounts)) + router := gin.New() + router.Use(gin.HandlerFunc(middleware.NewAdminAuthMiddleware(auth, service.NewUserService(moderationUpstreamUsers{actor: actor}, nil, nil, nil), nil, nil))) + router.PUT("/api/v1/admin/risk-control/config", h.UpdateConfig) + request := httptest.NewRequest(http.MethodPut, "/api/v1/admin/risk-control/config", strings.NewReader(`{"upstream_account_scope":"selected","upstream_account_ids":[51]}`)) + request.Header.Set("Content-Type", "application/json") + if role != "" { + token, err := auth.GenerateToken(context.Background(), actor) + require.NoError(t, err) + request.Header.Set("Authorization", "Bearer "+token) + } + w := httptest.NewRecorder() + router.ServeHTTP(w, request) + if role == service.RoleAdmin { + require.Equal(t, 200, w.Code, w.Body.String()) + } else { + require.Contains(t, []int{401, 403}, w.Code) + require.Equal(t, `{"all_groups":true}`, settings.value) + } + }) + } + fresh := NewContentModerationHandler(service.NewContentModerationService(settings, nil, nil, nil, nil, nil, nil, nil, accounts)) + router := gin.New() + router.GET("/config", fresh.GetConfig) + router.PUT("/config", fresh.UpdateConfig) + w := httptest.NewRecorder() + router.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/config", nil)) + var got struct { + Data service.ContentModerationConfigView `json:"data"` + } + require.NoError(t, json.Unmarshal(w.Body.Bytes(), &got)) + require.Equal(t, "selected", got.Data.UpstreamAccountScope) + require.Equal(t, []int64{51}, got.Data.UpstreamAccountIDs) + saved := settings.value + for _, body := range []string{`{"upstream_account_scope":"unknown"}`, `{"upstream_account_ids":[0]}`, `{"upstream_account_ids":[999]}`, `{"upstream_account_ids":[51],"upstream_account_scope":"bad"}`} { + req := httptest.NewRequest(http.MethodPut, "/config", strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + w = httptest.NewRecorder() + router.ServeHTTP(w, req) + require.Equal(t, 400, w.Code, w.Body.String()) + require.Equal(t, saved, settings.value) + } + for _, kind := range []string{"unsupported-platform", "unsupported-type"} { + oldPlatform, oldType := account.Platform, account.Type + if kind == "unsupported-platform" { + account.Platform = "customer" + } else { + account.Type = "bps" + } + req := httptest.NewRequest(http.MethodPut, "/config", strings.NewReader(`{"upstream_account_ids":[51]}`)) + req.Header.Set("Content-Type", "application/json") + w = httptest.NewRecorder() + router.ServeHTTP(w, req) + require.Equal(t, 400, w.Code) + require.Equal(t, saved, settings.value) + account.Platform, account.Type = oldPlatform, oldType + } + for _, body := range []string{`{"upstream_account_scope":"selected","upstream_account_ids":[]}`, `{"upstream_account_scope":"all","upstream_account_ids":[]}`} { + req := httptest.NewRequest(http.MethodPut, "/config", strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + w = httptest.NewRecorder() + router.ServeHTTP(w, req) + require.Equal(t, 200, w.Code, w.Body.String()) + } + +} diff --git a/backend/internal/handler/gateway_handler.go b/backend/internal/handler/gateway_handler.go index 02eb084a09e9..44a567444d4c 100644 --- a/backend/internal/handler/gateway_handler.go +++ b/backend/internal/handler/gateway_handler.go @@ -519,6 +519,9 @@ func (h *GatewayHandler) Messages(c *gin.Context) { if accountReleaseFunc != nil { accountReleaseFunc() } + if service.IsUpstreamModerationDenied(err) { + return + } if err != nil { var failoverErr *service.UpstreamFailoverError if errors.As(err, &failoverErr) { @@ -935,6 +938,9 @@ func (h *GatewayHandler) Messages(c *gin.Context) { if accountReleaseFunc != nil { accountReleaseFunc() } + if service.IsUpstreamModerationDenied(err) { + return + } // 提交 usage 记录。成功路径与"流中断但 Forward 已观测到 usage 的部分结果" // 错误路径共用:后者若不入账,上游已计量的请求会完全漏记漏计费(#5148)。 diff --git a/backend/internal/handler/gateway_handler_chat_completions.go b/backend/internal/handler/gateway_handler_chat_completions.go index cf0143381f1e..0aba1d09d5e8 100644 --- a/backend/internal/handler/gateway_handler_chat_completions.go +++ b/backend/internal/handler/gateway_handler_chat_completions.go @@ -326,6 +326,9 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) { if accountReleaseFunc != nil { accountReleaseFunc() } + if service.IsUpstreamModerationDenied(err) { + return + } // 提交 usage 记录。成功路径与"流中断但 Forward 已观测到 usage 的部分结果" // 错误路径共用;failover 错误恒定 result=nil,不会重复计费。 diff --git a/backend/internal/handler/gateway_handler_responses.go b/backend/internal/handler/gateway_handler_responses.go index cac45ce82f70..5662ec896b8e 100644 --- a/backend/internal/handler/gateway_handler_responses.go +++ b/backend/internal/handler/gateway_handler_responses.go @@ -308,6 +308,9 @@ func (h *GatewayHandler) Responses(c *gin.Context) { if accountReleaseFunc != nil { accountReleaseFunc() } + if service.IsUpstreamModerationDenied(err) { + return + } // 提交 usage 记录。成功路径与"流中断但 Forward 已观测到 usage 的部分结果" // 错误路径共用;failover 错误恒定 result=nil,不会重复计费。 diff --git a/backend/internal/handler/gateway_systemone.go b/backend/internal/handler/gateway_systemone.go index 89344135dd17..f965744a4795 100644 --- a/backend/internal/handler/gateway_systemone.go +++ b/backend/internal/handler/gateway_systemone.go @@ -192,6 +192,9 @@ func (h *GatewayHandler) SystemOne(c *gin.Context) { if accountRelease != nil { accountRelease() } + if service.IsUpstreamModerationDenied(forwardErr) { + return + } service.SetOpsLatencyMs(c, service.OpsResponseLatencyMsKey, time.Since(forwardStart).Milliseconds()) if forwardErr != nil { diff --git a/backend/internal/handler/gateway_web_search.go b/backend/internal/handler/gateway_web_search.go index 77c535d384c0..b39f6cc1c2ad 100644 --- a/backend/internal/handler/gateway_web_search.go +++ b/backend/internal/handler/gateway_web_search.go @@ -194,6 +194,9 @@ func (h *GatewayHandler) WebSearch(c *gin.Context) { account = selected.Account accountReleaseFunc = release + if gateErr := service.CheckUpstreamModeration(c.Request.Context(), c, account); gateErr != nil { + return + } if isXSearch { nativeResp, providerName, err = h.doGrokNativeXSearch(c.Request.Context(), c, account, req, searchModel, maxResults) } else { diff --git a/backend/internal/handler/gemini_cached_contents_handler.go b/backend/internal/handler/gemini_cached_contents_handler.go index 70f7c5525a4a..522a0d3f525e 100644 --- a/backend/internal/handler/gemini_cached_contents_handler.go +++ b/backend/internal/handler/gemini_cached_contents_handler.go @@ -256,6 +256,10 @@ func (h *GatewayHandler) GeminiCachedContentsCreate(c *gin.Context) { return } + if gateErr := service.CheckUpstreamModeration(c.Request.Context(), c, account); gateErr != nil { + accountReleaseFunc() + return + } upstream, err := svc.CreateUpstream(c.Request.Context(), account, req, mappedModel, publicID, ttl) accountReleaseFunc() if err != nil { diff --git a/backend/internal/handler/gemini_v1beta_handler.go b/backend/internal/handler/gemini_v1beta_handler.go index 631e86f9acaf..1052fcb64f60 100644 --- a/backend/internal/handler/gemini_v1beta_handler.go +++ b/backend/internal/handler/gemini_v1beta_handler.go @@ -804,6 +804,9 @@ func (h *GatewayHandler) GeminiV1BetaModels(c *gin.Context) { if accountReleaseFunc != nil { accountReleaseFunc() } + if service.IsUpstreamModerationDenied(err) { + return + } if err != nil { var failoverErr *service.UpstreamFailoverError if errors.As(err, &failoverErr) { diff --git a/backend/internal/handler/grok_audio.go b/backend/internal/handler/grok_audio.go index e3495d19a5bc..01258f790edf 100644 --- a/backend/internal/handler/grok_audio.go +++ b/backend/internal/handler/grok_audio.go @@ -391,6 +391,9 @@ func (h *OpenAIGatewayHandler) GrokVoice(c *gin.Context, endpoint string) { defer release() return h.gatewayService.ForwardGrokVoice(c.Request.Context(), c, account, endpoint, body, contentType) }() + if service.IsUpstreamModerationDenied(forwardErr) { + return + } if forwardErr == nil { h.recordGrokVoiceUsage(c, apiKey, account, subscription, endpoint, body, result) return diff --git a/backend/internal/handler/grok_media.go b/backend/internal/handler/grok_media.go index 96192bc140af..dc39fa68cb22 100644 --- a/backend/internal/handler/grok_media.go +++ b/backend/internal/handler/grok_media.go @@ -425,6 +425,9 @@ func (h *OpenAIGatewayHandler) handleGrokMedia(c *gin.Context, endpoint service. } return h.gatewayService.ForwardGrokMedia(requestCtx, c, account, endpoint, requestID, body, contentType) }() + if service.IsUpstreamModerationDenied(err) { + return + } forwardDurationMs := time.Since(forwardStart).Milliseconds() upstreamLatencyMs, _ := getContextInt64(c, service.OpsUpstreamLatencyMsKey) diff --git a/backend/internal/handler/moderation_upstream_dispatch_test.go b/backend/internal/handler/moderation_upstream_dispatch_test.go new file mode 100644 index 000000000000..935eea255e0c --- /dev/null +++ b/backend/internal/handler/moderation_upstream_dispatch_test.go @@ -0,0 +1,88 @@ +//go:build unit + +package handler + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "sync/atomic" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/pkg/tlsfingerprint" + middleware "github.com/Wei-Shaw/sub2api/internal/server/middleware" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +type moderationLoopbackUpstream struct{ *nativeImageRouteUpstream } + +func (u moderationLoopbackUpstream) DoWithTLS(r *http.Request, p string, id int64, n int, _ *tlsfingerprint.Profile) (*http.Response, error) { + return u.Do(r, p, id, n) +} + +func TestModerationUpstreamHTTPDispatchFamilies(t *testing.T) { + for _, tc := range []struct { + name, path, body, platform string + call func(*OpenAIGatewayHandler, *gin.Context) + }{ + {"chat", "/v1/chat/completions", `{"model":"gpt-5.1","messages":[{"role":"user","content":"fixture input"}]}`, service.PlatformOpenAI, (*OpenAIGatewayHandler).ChatCompletions}, + {"messages", "/v1/messages", `{"model":"gpt-5.1","max_tokens":20,"messages":[{"role":"user","content":"fixture input"}]}`, service.PlatformOpenAI, (*OpenAIGatewayHandler).Messages}, + {"embeddings", "/v1/embeddings", `{"model":"text-embedding-3-small","input":"fixture input"}`, service.PlatformOpenAI, (*OpenAIGatewayHandler).Embeddings}, + {"alpha", "/v1/alpha/search", `{"model":"gpt-5.1","commands":{"search_query":[{"q":"fixture input"}]}}`, service.PlatformOpenAI, (*OpenAIGatewayHandler).AlphaSearch}, + {"grok-tts", "/v1/audio/speech", `{"input":"fixture input","voice":"eve"}`, service.PlatformGrok, func(h *OpenAIGatewayHandler, c *gin.Context) { h.GrokVoice(c, "tts") }}, + } { + for _, selected := range []bool{false, true} { + t.Run(fmt.Sprintf("%s/selected=%t", tc.name, selected), func(t *testing.T) { + var audits, writes atomic.Int32 + audit := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + audits.Add(1) + _, _ = io.WriteString(w, `{"results":[{"category_scores":{"sexual":0.99}}]}`) + })) + defer audit.Close() + provider := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + writes.Add(1) + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(400) + _, _ = io.WriteString(w, `{"error":{"message":"fixture generation refused"}}`) + })) + defer provider.Close() + target, err := url.Parse(provider.URL) + require.NoError(t, err) + upstream := moderationLoopbackUpstream{&nativeImageRouteUpstream{target: target, client: provider.Client()}} + account := service.Account{ID: 1, Name: "fixture", Platform: tc.platform, Type: service.AccountTypeAPIKey, Status: service.StatusActive, Schedulable: true, GroupIDs: []int64{3131, 3132}, Credentials: map[string]any{"api_key": "fixture", "base_url": "https://fixture.example"}} + h := newOpenAIResponsesFailoverTestHandler(t, upstream, account) + id := 99 + if selected { + id = 1 + } + raw := fmt.Sprintf(`{"enabled":true,"mode":"pre_block","all_groups":true,"sample_rate":100,"base_url":%q,"api_keys":["fixture"],"upstream_account_scope":"selected","upstream_account_ids":[%d],"upstream_account_bindings":{"1":{"platform":%q,"type":"apikey","group_ids":[3131,3132]}}}`, audit.URL, id, tc.platform) + settings := &contentModerationHandlerSettingRepo{values: map[string]string{service.SettingKeyRiskControlEnabled: "true", service.SettingKeyContentModerationConfig: raw}} + h.contentModerationService = service.NewContentModerationService(settings, &contentModerationHandlerTestRepo{}, nil, nil, nil, nil, nil, nil, openAIImagesFailoverAccountRepo{accounts: []service.Account{account}}) + c, w := newOpenAIResponsesFailoverTestContext(t, context.Background()) + c.Request = httptest.NewRequest(http.MethodPost, tc.path, strings.NewReader(tc.body)) + c.Request.Header.Set("Content-Type", "application/json") + key, _ := middleware.GetAPIKeyFromContext(c) + key.Group.Platform = tc.platform + key.Group.AllowMessagesDispatch = true + tc.call(h, c) + if selected { + require.Equal(t, 403, w.Code, w.Body.String()) + require.Equal(t, int32(1), audits.Load()) + require.Zero(t, writes.Load()) + require.True(t, json.Valid(w.Body.Bytes()), w.Body.String()) + require.Zero(t, h.gatewayService.SnapshotOpenAIAccountSchedulerMetrics().RuntimeStatsAccountCount) + } else { + require.Zero(t, audits.Load()) + require.Positive(t, writes.Load(), w.Body.String()) + } + }) + } + } +} diff --git a/backend/internal/handler/moderation_upstream_http_test.go b/backend/internal/handler/moderation_upstream_http_test.go index f1f0baf45f20..31616c60bb19 100644 --- a/backend/internal/handler/moderation_upstream_http_test.go +++ b/backend/internal/handler/moderation_upstream_http_test.go @@ -14,18 +14,17 @@ import ( "sync/atomic" "testing" - "github.com/Wei-Shaw/sub2api/internal/config" "github.com/Wei-Shaw/sub2api/internal/service" - "github.com/Wei-Shaw/sub2api/internal/testutil" "github.com/stretchr/testify/require" ) func TestModerationUpstreamHTTPSelectionAndFailover(t *testing.T) { for _, accountType := range []string{service.AccountTypeAPIKey, service.AccountTypeOAuth} { for _, stream := range []bool{false, true} { - for _, scenario := range []string{"unselected", "deny", "failover-deny", "failover-allow"} { + for _, scenario := range []string{"unselected", "deny", "failover-deny", "failover-allow", "group-mismatch", "empty-groups", "empty-accounts", "multi-group"} { t.Run(fmt.Sprintf("%s/stream=%t/%s", accountType, stream, scenario), func(t *testing.T) { var audits, writesA, writesB atomic.Int32 + skipAudit := scenario == "unselected" || scenario == "group-mismatch" || scenario == "empty-groups" || scenario == "empty-accounts" audit := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { audits.Add(1) body, _ := io.ReadAll(r.Body) @@ -60,15 +59,11 @@ func TestModerationUpstreamHTTPSelectionAndFailover(t *testing.T) { defer upstream.Close() accounts := []service.Account{} for i, token := range []string{"fixture-a", "fixture-b"} { - accounts = append(accounts, service.Account{ID: int64(i + 1), Name: token, Platform: service.PlatformOpenAI, Type: accountType, Status: service.StatusActive, Schedulable: true, Priority: i, GroupIDs: []int64{3131, 3132}, Credentials: map[string]any{"api_key": token, "access_token": token, "base_url": upstream.URL}, Extra: map[string]any{"codex_fingerprint_mode": "off"}}) + accounts = append(accounts, service.Account{ID: int64(i + 1), Name: token, Platform: service.PlatformOpenAI, Type: accountType, Status: service.StatusActive, Schedulable: true, Priority: i, GroupIDs: []int64{3131, 3132}, Credentials: map[string]any{"api_key": token, "access_token": token, "base_url": "https://fixture.example"}, Extra: map[string]any{"codex_fingerprint_mode": "off"}}) } - cfg := &config.Config{} - cfg.Security.URLAllowlist.AllowPrivateHosts = true - cfg.Security.URLAllowlist.AllowInsecureHTTP = true target, err := url.Parse(upstream.URL) require.NoError(t, err) - route := issue600LocalTransport{target: target, transport: http.DefaultTransport} - transport := issue600LocalHTTPUpstream{HTTPUpstream: testutil.NewRealHTTPUpstream(cfg), route: route} + transport := moderationLoopbackUpstream{&nativeImageRouteUpstream{target: target, client: upstream.Client()}} h := newOpenAIResponsesFailoverTestHandler(t, transport, accounts...) ids := []int64{1} if scenario == "unselected" { @@ -80,11 +75,24 @@ func TestModerationUpstreamHTTPSelectionAndFailover(t *testing.T) { if scenario == "failover-allow" { ids = []int64{1, 2} } + if scenario == "empty-accounts" { + ids = nil + } bindings := map[int64]service.ModerationUpstreamBinding{} for _, a := range accounts { bindings[a.ID] = service.ModerationUpstreamBinding{Platform: a.Platform, Type: a.Type, GroupIDs: a.GroupIDs} } policy := map[string]any{"enabled": true, "mode": "pre_block", "all_groups": true, "sample_rate": 100, "base_url": audit.URL, "api_keys": []string{"fixture-audit"}, "upstream_account_scope": "selected", "upstream_account_ids": ids, "upstream_account_bindings": bindings} + if scenario == "group-mismatch" || scenario == "empty-groups" || scenario == "multi-group" { + policy["all_groups"] = false + policy["group_ids"] = []int64{3132} + if scenario == "empty-groups" { + policy["group_ids"] = []int64{} + } + if scenario == "multi-group" { + policy["group_ids"] = []int64{3131, 3132} + } + } raw, err := json.Marshal(policy) require.NoError(t, err) repo := &contentModerationHandlerSettingRepo{values: map[string]string{service.SettingKeyRiskControlEnabled: "true", service.SettingKeyContentModerationConfig: string(raw)}} @@ -92,14 +100,19 @@ func TestModerationUpstreamHTTPSelectionAndFailover(t *testing.T) { c, rec := newOpenAIResponsesFailoverTestContext(t, context.Background()) c.Request.Body = io.NopCloser(strings.NewReader(fmt.Sprintf(`{"model":"gpt-5.1","stream":%t,"input":"frozen original input"}`, stream))) h.Responses(c) - if scenario == "unselected" { + if scenario == "deny" { + require.Zero(t, h.gatewayService.SnapshotOpenAIAccountSchedulerMetrics().RuntimeStatsAccountCount, "local deny must not create an upstream health sample") + require.Equal(t, 1, strings.Count(rec.Body.String(), `"error":`), "local deny emits exactly one error") + require.True(t, json.Valid(rec.Body.Bytes())) + } + if skipAudit { require.Zero(t, audits.Load()) - require.Equal(t, int32(1), writesA.Load()) + require.Equal(t, int32(1), writesA.Load(), rec.Body.String()) require.Contains(t, rec.Body.String(), "resp_scope") } else { require.Equal(t, int32(1), audits.Load(), "same logical content must be audited once across retry/failover") if scenario == "failover-allow" { - require.Positive(t, writesA.Load()) + require.Positive(t, writesA.Load(), rec.Body.String()) require.Equal(t, int32(1), writesB.Load()) require.Contains(t, rec.Body.String(), "resp_scope") } else { @@ -108,7 +121,7 @@ func TestModerationUpstreamHTTPSelectionAndFailover(t *testing.T) { if scenario == "deny" { require.Zero(t, writesA.Load()) } else { - require.Positive(t, writesA.Load()) + require.Positive(t, writesA.Load(), rec.Body.String()) } } } diff --git a/backend/internal/handler/moderation_upstream_images_test.go b/backend/internal/handler/moderation_upstream_images_test.go new file mode 100644 index 000000000000..0f22082500c5 --- /dev/null +++ b/backend/internal/handler/moderation_upstream_images_test.go @@ -0,0 +1,99 @@ +//go:build unit + +package handler + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +func TestModerationUpstreamImagesJSONKeepaliveAndAsync(t *testing.T) { + for _, scenario := range []string{"fast", "slow", "async"} { + t.Run(scenario, func(t *testing.T) { + var audits atomic.Int32 + release := make(chan struct{}) + + audit := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + audits.Add(1) + if scenario == "slow" { + time.Sleep(1200 * time.Millisecond) + } + if scenario == "async" { + <-release + } + _, _ = io.WriteString(w, `{"results":[{"category_scores":{"sexual":0.99}}]}`) + })) + defer func() { + select { + case <-release: + default: + close(release) + } + audit.Close() + }() + var h *OpenAIGatewayHandler + store := &asyncImageMemoryStore{tasks: map[string]*service.ImageTaskRecord{}} + server, calls := newNativeImageRoute(t, 0, 200, func(handler *OpenAIGatewayHandler, accounts service.AccountRepository, router *gin.Engine) { + h = handler + raw := fmt.Sprintf(`{"enabled":true,"mode":"pre_block","all_groups":true,"sample_rate":100,"timeout_ms":3000,"base_url":%q,"api_keys":["fixture"],"upstream_account_scope":"selected","upstream_account_ids":[1],"upstream_account_bindings":{"1":{"platform":"openai","type":"apikey","group_ids":[]}}}`, audit.URL) + settings := &contentModerationHandlerSettingRepo{values: map[string]string{service.SettingKeyRiskControlEnabled: "true", service.SettingKeyContentModerationConfig: raw}} + h.contentModerationService = service.NewContentModerationService(settings, &contentModerationHandlerTestRepo{}, nil, nil, nil, nil, nil, nil, accounts) + tasks := service.NewImageTaskServiceWithUploader(store, nil, time.Hour, time.Minute) + async := NewAsyncImageHandler(tasks, h) + router.POST("/v1/images/generations/async", async.Submit) + router.GET("/fixture-health", func(c *gin.Context) { c.JSON(200, gin.H{"fixture": "ok"}) }) + }) + endpoint := server.URL + "/v1/images/generations" + if scenario == "async" { + endpoint += "/async" + } + response, err := server.Client().Post(endpoint, "application/json", strings.NewReader(`{"model":"gpt-image-1","prompt":"fixture"}`)) + require.NoError(t, err) + body, err := io.ReadAll(response.Body) + _ = response.Body.Close() + require.NoError(t, err) + require.True(t, json.Valid(body), string(body)) + require.NotContains(t, string(body), "event:") + if scenario == "async" { + require.Equal(t, 202, response.StatusCode) + id := gjson.GetBytes(body, "id").String() + require.NotEmpty(t, id) + health, err := server.Client().Get(server.URL + "/fixture-health") + require.NoError(t, err) + healthBody, _ := io.ReadAll(health.Body) + _ = health.Body.Close() + require.JSONEq(t, `{"fixture":"ok"}`, string(healthBody)) + close(release) + require.Eventually(t, func() bool { + task, e := store.Get(context.Background(), id) + return e == nil && task.Status == service.ImageTaskStatusFailed && strings.Contains(string(task.Error), "content_policy_violation") + }, 5*time.Second, 10*time.Millisecond) + } else { + expected := 403 + if scenario == "slow" { + expected = 200 + require.True(t, strings.HasPrefix(string(body), " \n"), "fixture must actually send a JSON keepalive") + } + require.Equal(t, expected, response.StatusCode) + require.Contains(t, string(body), "content_policy_violation") + require.Equal(t, 1, strings.Count(string(body), `"error":`)) + } + require.Equal(t, int32(1), audits.Load()) + require.Zero(t, calls.Load()) + require.Zero(t, h.gatewayService.SnapshotOpenAIAccountSchedulerMetrics().RuntimeStatsAccountCount) + }) + } +} diff --git a/backend/internal/handler/moderation_upstream_scope.go b/backend/internal/handler/moderation_upstream_scope.go index 3f091b7abaa3..87b1a9c83c76 100644 --- a/backend/internal/handler/moderation_upstream_scope.go +++ b/backend/internal/handler/moderation_upstream_scope.go @@ -3,7 +3,6 @@ package handler import ( "context" "encoding/json" - "errors" "fmt" "net/http" "strings" @@ -13,6 +12,7 @@ import ( middleware2 "github.com/Wei-Shaw/sub2api/internal/server/middleware" "github.com/Wei-Shaw/sub2api/internal/service" "github.com/gin-gonic/gin" + "github.com/tidwall/gjson" "go.uber.org/zap" ) @@ -48,13 +48,19 @@ func prepareUpstreamAudit(c *gin.Context, log *zap.Logger, coordinator *security } func bindUpstreamAuditGate(c *gin.Context, state *upstreamAuditState) { + // WS ingress owns protocol errors and per-turn selection checks. Its HTTP + // bridge must never write an HTTP error to the upgraded response writer. + if isSecurityAuditWebSocketStage(state.request.Stage) { + service.SetUpstreamModerationGate(c, nil) + return + } service.SetUpstreamModerationGate(c, func(ctx context.Context, account *service.Account) error { decision := state.check(ctx, account) if decision == nil || decision.AllowNextStage { return nil } writeSelectedUpstreamAuditError(c, decision) - return errors.New(securityAuditMessage(decision)) + return &service.UpstreamModerationDeniedError{Message: securityAuditMessage(decision)} }) } @@ -78,6 +84,21 @@ func (s *upstreamAuditState) check(ctx context.Context, account *service.Account } req := s.request.Clone() req.UpstreamAccount, req.UpstreamConfig, req.SkipPrompt = account, s.config, true + // Keep the original request frozen; derive audit text only for transport + // envelopes not understood by the legacy prompt extractor. Prompt audit + // still receives the untouched ingress request at its existing stage. + if req.Protocol == "openai_alpha_search" { + req.Protocol = service.ContentModerationProtocolOpenAIResponses + req.Body, _ = json.Marshal(map[string]string{"input": string(req.Body)}) + } else if req.Protocol == service.ContentModerationProtocolOpenAIImages && gjson.GetBytes(req.Body, "request.items").IsArray() { + prompts := []string{} + for _, item := range gjson.GetBytes(req.Body, "request.items").Array() { + prompts = append(prompts, item.Get("prompt").String()) + } + req.Body, _ = json.Marshal(map[string]string{"prompt": strings.Join(prompts, "\n")}) + } else if isSecurityAuditWebSocketStage(req.Stage) && gjson.GetBytes(req.Body, "response.input").Exists() { + req.Body = []byte(gjson.GetBytes(req.Body, "response").Raw) + } input := service.ContentModerationCheckInput{ RequestID: req.RequestID, UserID: req.UserID, UserEmail: req.UserEmail, APIKeyID: req.APIKeyID, APIKeyName: req.APIKeyName, GroupID: req.GroupID, GroupName: req.GroupName, @@ -132,7 +153,14 @@ func writeSelectedUpstreamAuditError(c *gin.Context, decision *securityaudit.Dec if strings.Contains(c.Request.URL.Path, "/v1beta/") { payload = gin.H{"error": gin.H{"code": status, "message": message, "status": "PERMISSION_DENIED"}} } - if c.Writer.Written() { + if service.OpenAIImagesJSONKeepalivePresent(c) { + committed := service.StopOpenAIImagesJSONKeepaliveCommitted(c) + if committed { + c.JSON(http.StatusOK, payload) + } else { + c.JSON(status, payload) + } + } else if c.Writer.Written() { service.MarkOpsStreamError(c, code, message, status) data, _ := json.Marshal(payload) _, _ = fmt.Fprintf(c.Writer, "event: error\ndata: %s\n\n", data) diff --git a/backend/internal/handler/moderation_upstream_systemone_test.go b/backend/internal/handler/moderation_upstream_systemone_test.go new file mode 100644 index 000000000000..8396a5ec4f22 --- /dev/null +++ b/backend/internal/handler/moderation_upstream_systemone_test.go @@ -0,0 +1,71 @@ +//go:build unit + +package handler + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey" + middleware "github.com/Wei-Shaw/sub2api/internal/server/middleware" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/Wei-Shaw/sub2api/internal/testutil" + "github.com/stretchr/testify/require" +) + +func TestModerationUpstreamSystemOneLocalDenial(t *testing.T) { + for _, stale := range []bool{false, true} { + t.Run(fmt.Sprint(stale), func(t *testing.T) { + var audits, generations atomic.Int32 + audit := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + audits.Add(1) + _, _ = w.Write([]byte(`{"results":[{"category_scores":{"sexual":0.99}}]}`)) + })) + defer audit.Close() + provider := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { generations.Add(1); w.WriteHeader(500) })) + defer provider.Close() + group := &service.Group{ID: 9, Platform: service.PlatformTypeSafe, Status: service.StatusActive, Hydrated: true} + account := service.Account{ID: 1, Name: "fixture", Platform: service.PlatformTypeSafe, Type: service.AccountTypeAPIKey, Status: service.StatusActive, Schedulable: true, GroupIDs: []int64{9}, Credentials: map[string]any{"api_key": "fixture", "base_url": provider.URL}} + accounts := openAIImagesFailoverAccountRepo{accounts: []service.Account{account}} + snapshot := service.NewSchedulerSnapshotService(&fakeSchedulerCache{accounts: []*service.Account{&account}}, nil, nil, nil, nil) + cfg := &config.Config{RunMode: config.RunModeSimple} + cfg.Security.URLAllowlist.AllowPrivateHosts = true + cfg.Security.URLAllowlist.AllowInsecureHTTP = true + gateway := service.NewGatewayService(accounts, &fakeGroupRepo{group: group}, nil, nil, nil, nil, nil, nil, cfg, snapshot, nil, nil, nil, nil, nil, testutil.NewRealHTTPUpstream(cfg), nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) + billing := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil) + defer billing.Stop() + membership := 9 + if stale { + membership = 10 + } + raw := fmt.Sprintf(`{"enabled":true,"mode":"pre_block","all_groups":true,"sample_rate":100,"base_url":%q,"api_keys":["fixture"],"upstream_account_scope":"selected","upstream_account_ids":[1],"upstream_account_bindings":{"1":{"platform":"typesafe","type":"apikey","group_ids":[%d]}}}`, audit.URL, membership) + settings := &contentModerationHandlerSettingRepo{values: map[string]string{service.SettingKeyRiskControlEnabled: "true", service.SettingKeyContentModerationConfig: raw}} + h := &GatewayHandler{gatewayService: gateway, billingCacheService: billing, concurrencyHelper: NewConcurrencyHelper(service.NewConcurrencyService(&fakeConcurrencyCache{}), SSEPingFormatClaude, 0), cfg: cfg, contentModerationService: service.NewContentModerationService(settings, &contentModerationHandlerTestRepo{}, nil, nil, nil, nil, nil, nil, accounts)} + c, w := newSystemOneHandlerContext(validSystemOneHandlerBody) + c.Request = c.Request.WithContext(context.WithValue(c.Request.Context(), ctxkey.Group, group)) + c.Set(string(middleware.ContextKeyAPIKey), &service.APIKey{ID: 7, UserID: 8, GroupID: &group.ID, Group: group, User: &service.User{ID: 8, Status: service.StatusActive}}) + c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: 8}) + h.SystemOne(c) + code := 403 + if stale { + code = 503 + } + require.Equal(t, code, w.Code, w.Body.String()) + require.True(t, json.Valid(w.Body.Bytes()), w.Body.String()) + require.Equal(t, 1, strings.Count(w.Body.String(), `"error":`)) + require.Zero(t, generations.Load()) + if stale { + require.Zero(t, audits.Load()) + } else { + require.Equal(t, int32(1), audits.Load()) + } + }) + } +} diff --git a/backend/internal/handler/moderation_upstream_ws_test.go b/backend/internal/handler/moderation_upstream_ws_test.go index 925376807072..d4a7ee20c028 100644 --- a/backend/internal/handler/moderation_upstream_ws_test.go +++ b/backend/internal/handler/moderation_upstream_ws_test.go @@ -3,10 +3,11 @@ package handler import ( "context" "encoding/json" - "strings" "fmt" + "io" "net/http" "net/http/httptest" + "strings" "sync/atomic" "testing" "time" @@ -17,11 +18,13 @@ import ( "github.com/tidwall/gjson" ) - func TestModerationUpstreamWebSocketModesAndTurns(t *testing.T) { for _, mode := range []string{service.OpenAIWSIngressModePassthrough, service.OpenAIWSIngressModeCtxPool, service.OpenAIWSIngressModeHTTPBridge} { for _, namespace := range []string{"none", "oauth"} { for _, scenario := range []string{"unselected", "deny", "next-turn", "failover"} { + if scenario == "failover" && namespace != "oauth" { + continue + } t.Run(mode+"/"+namespace+"/"+scenario, func(t *testing.T) { var audits atomic.Int32 audit := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -45,9 +48,6 @@ func TestModerationUpstreamWebSocketModesAndTurns(t *testing.T) { require.NoError(t, err) opts := issue600FixtureOptions{moderationSettings: map[string]string{service.SettingKeyContentModerationConfig: string(raw)}} if scenario == "failover" { - if namespace != "oauth" { - return - } opts.switchAccount = true } h, up := newIssue600NetworkHarness(t, mode, namespace, false, nil, opts) @@ -96,3 +96,32 @@ func TestModerationUpstreamWebSocketModesAndTurns(t *testing.T) { } } } + +func TestModerationUpstreamWebSocketTurnIdentityAfterFailover(t *testing.T) { + var audits atomic.Int32 + audit := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + audits.Add(1) + body, _ := io.ReadAll(r.Body) + score := "0.01" + if strings.Contains(string(body), "blocked-third") { + score = "0.99" + } + _, _ = fmt.Fprintf(w, `{"results":[{"category_scores":{"sexual":%s}}]}`, score) + })) + defer audit.Close() + raw, err := json.Marshal(map[string]any{"enabled": true, "mode": "pre_block", "all_groups": true, "sample_rate": 100, "base_url": audit.URL, "api_keys": []string{"fixture"}, "upstream_account_scope": "selected", "upstream_account_ids": []int64{9951, 9952}, "upstream_account_bindings": map[int64]service.ModerationUpstreamBinding{9951: {Platform: service.PlatformOpenAI, Type: service.AccountTypeOAuth, GroupIDs: []int64{4301}}, 9952: {Platform: service.PlatformOpenAI, Type: service.AccountTypeOAuth, GroupIDs: []int64{4301}}}}) + require.NoError(t, err) + h, up := newIssue600NetworkHarness(t, service.OpenAIWSIngressModeHTTPBridge, "oauth", false, nil, issue600FixtureOptions{switchAfterTurns: 1, moderationSettings: map[string]string{service.SettingKeyContentModerationConfig: string(raw)}}) + issue600Send(t, h, `{"type":"response.create","model":"gpt-5.1","input":"first"}`, 1, false) + issue600Send(t, h, `{"type":"response.create","model":"gpt-5.1","input":"second"}`, 2, false) + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + require.NoError(t, h.clientConn.Write(ctx, coderws.MessageText, []byte(`{"type":"response.create","model":"gpt-5.1","input":"blocked-third"}`))) + _, event, err := h.clientConn.Read(ctx) + require.NoError(t, err) + require.Contains(t, string(event), "content_policy_violation") + issue600Finish(t, h, nil) + frames, _ := up.snapshot() + require.Len(t, frames, 2) + require.Equal(t, int32(3), audits.Load(), "replay does not audit twice; genuinely new third turn must audit") +} diff --git a/backend/internal/handler/openai_alpha_search.go b/backend/internal/handler/openai_alpha_search.go index 3359ae6b309d..c826b810003f 100644 --- a/backend/internal/handler/openai_alpha_search.go +++ b/backend/internal/handler/openai_alpha_search.go @@ -216,6 +216,9 @@ func (h *OpenAIGatewayHandler) AlphaSearch(c *gin.Context) { } return h.gatewayService.ForwardAlphaSearch(rpmAdmission.forwardContext(c.Request.Context(), account), c, account, forwardBody) }() + if service.IsUpstreamModerationDenied(err) { + return + } if h.handleOpenAIRPMForwardError(c, err, streamStarted, false) { return } diff --git a/backend/internal/handler/openai_chat_completions.go b/backend/internal/handler/openai_chat_completions.go index 219e1dfe5065..4e004262b42f 100644 --- a/backend/internal/handler/openai_chat_completions.go +++ b/backend/internal/handler/openai_chat_completions.go @@ -290,6 +290,9 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) { }() return h.gatewayService.ForwardAsChatCompletions(rpmAdmission.forwardContext(c.Request.Context(), account), c, account, forwardBody, promptCacheKey, "") }() + if service.IsUpstreamModerationDenied(err) { + return + } if retryOpenAIInitialAdmission(c, err, result, body, account.ID, failedAccountIDs, &switchCount, maxAccountSwitches) { lastAdmissionErr = err reqLog.Info("openai_chat_completions.admission_reselecting", zap.Int64("account_id", account.ID), zap.Int("switch_count", switchCount)) diff --git a/backend/internal/handler/openai_embeddings.go b/backend/internal/handler/openai_embeddings.go index 634e84a3a711..2d0369966c5b 100644 --- a/backend/internal/handler/openai_embeddings.go +++ b/backend/internal/handler/openai_embeddings.go @@ -215,6 +215,9 @@ func (h *OpenAIGatewayHandler) Embeddings(c *gin.Context) { }() return h.gatewayService.ForwardEmbeddings(c.Request.Context(), c, account, forwardBody, "") }() + if service.IsUpstreamModerationDenied(err) { + return + } forwardDurationMs := time.Since(forwardStart).Milliseconds() upstreamLatencyMs, _ := getContextInt64(c, service.OpsUpstreamLatencyMsKey) diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index 4187b3523c16..741b64c508da 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -1171,6 +1171,9 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { }() return h.gatewayService.Forward(rpmAdmission.forwardContext(c.Request.Context(), account), c, account, attemptBody) }() + if service.IsUpstreamModerationDenied(err) { + return + } if result != nil { result.HeaderTimeoutRetries = headerTimeoutRetries } @@ -1837,6 +1840,9 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) { }() return h.gatewayService.ForwardAsAnthropic(rpmAdmission.forwardContext(c.Request.Context(), account), c, account, forwardBody, promptCacheKey, defaultMappedModel) }() + if service.IsUpstreamModerationDenied(err) { + return + } if result != nil { result.HeaderTimeoutRetries = headerTimeoutRetries } @@ -3129,6 +3135,11 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) { ctx = c.Request.Context() setOpsEndpointContext(c, "", int16(service.RequestTypeWSV2)) + // Connection-wide audit identity survives proxy restarts/failover, whose + // transport-local turn counters restart at 1. Replays keep the current + // state; only newly received follow-up frames advance this counter. + moderationLogicalTurn := 1 + c.Set(securityAuditWSTurnContextKey, moderationLogicalTurn) if decision := h.checkSecurityAuditStage(c, reqLog, apiKey, subject, service.ContentModerationProtocolOpenAIResponses, reqModel, firstMessage, "first_turn"); decision != nil && !decision.AllowNextStage { writeSecurityAuditWSError(ctx, wsConn, decision) closeOpenAIClientWS(wsConn, securityAuditWSCloseStatus(decision), securityAuditWSCloseReason(decision)) @@ -3661,7 +3672,10 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) { return nil }, BeforeRequestWithClientPayload: func(turn int, payload, clientPayload []byte, originalModel string) error { - c.Set(securityAuditWSTurnContextKey, turn) + if turn > 1 { + moderationLogicalTurn++ + } + c.Set(securityAuditWSTurnContextKey, moderationLogicalTurn) service.BeginOpsStreamTurn(c, turn) // 连接级 cyber session gate 也在 BeforeRequest 先执行,使 native 与 // passthrough ingress 都能在 BeforeTurn 及上游写入前无副作用地拒绝。 @@ -3729,11 +3743,11 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) { } if decision := h.checkSecurityAuditStage(c, reqLog, apiKey, subject, service.ContentModerationProtocolOpenAIResponses, model, clientPayload, "subsequent_turn"); decision != nil && !decision.AllowNextStage { writeSecurityAuditWSError(ctx, wsConn, decision) - return service.NewOpenAIWSClientCloseError(securityAuditWSCloseStatus(decision), securityAuditWSCloseReason(decision), nil) + return service.NewOpenAIWSClientCloseError(securityAuditWSCloseStatus(decision), securityAuditWSCloseReason(decision), errOpenAIWSLocalAdmissionRejected) } if decision := checkSelectedUpstreamAudit(c, c.Request.Context(), account); decision != nil && !decision.AllowNextStage { writeSecurityAuditWSError(ctx, wsConn, decision) - return service.NewOpenAIWSClientCloseError(securityAuditWSCloseStatus(decision), securityAuditWSCloseReason(decision), nil) + return service.NewOpenAIWSClientCloseError(securityAuditWSCloseStatus(decision), securityAuditWSCloseReason(decision), errOpenAIWSLocalAdmissionRejected) } return nil }, diff --git a/backend/internal/handler/openai_images.go b/backend/internal/handler/openai_images.go index 6d473bbff408..da83c4e1c4e6 100644 --- a/backend/internal/handler/openai_images.go +++ b/backend/internal/handler/openai_images.go @@ -304,6 +304,9 @@ func (h *OpenAIGatewayHandler) Images(c *gin.Context) { }() return h.gatewayService.ForwardImages(rpmAdmission.forwardContext(requestCtx, account), c, account, body, parsed, channelMapping.MappedModel) }() + if service.IsUpstreamModerationDenied(err) { + return + } if h.handleOpenAIRPMForwardError(c, err, streamStarted, false) { return } diff --git a/backend/internal/handler/openai_images_native_route_test.go b/backend/internal/handler/openai_images_native_route_test.go index 0694e1fe328c..a3aa6803e28d 100644 --- a/backend/internal/handler/openai_images_native_route_test.go +++ b/backend/internal/handler/openai_images_native_route_test.go @@ -40,7 +40,7 @@ func (u *nativeImageRouteUpstream) Do(req *http.Request, _ string, _ int64, _ in return u.client.Do(forwarded) } -func newNativeImageRoute(t *testing.T, delay time.Duration, status int) (*httptest.Server, *atomic.Int64) { +func newNativeImageRoute(t *testing.T, delay time.Duration, status int, configure ...func(*OpenAIGatewayHandler, service.AccountRepository, *gin.Engine)) (*httptest.Server, *atomic.Int64) { t.Helper() gin.SetMode(gin.TestMode) var calls atomic.Int64 @@ -90,11 +90,14 @@ func newNativeImageRoute(t *testing.T, delay time.Duration, status int) (*httpte router := gin.New() router.Use(func(c *gin.Context) { groupID := int64(1) - c.Set(string(middleware.ContextKeyAPIKey), &service.APIKey{ID: 1, GroupID: &groupID, Group: &service.Group{ID: 1, AllowImageGeneration: true}, User: &service.User{ID: 1}}) + c.Set(string(middleware.ContextKeyAPIKey), &service.APIKey{ID: 1, UserID: 1, GroupID: &groupID, Group: &service.Group{ID: 1, Platform: service.PlatformOpenAI, AllowImageGeneration: true}, User: &service.User{ID: 1}}) c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: 1}) }) router.POST("/v1/images/generations", handler.Images) router.POST("/v1/images/edits", handler.Images) + for _, apply := range configure { + apply(handler, repo, router) + } server := httptest.NewServer(router) t.Cleanup(server.Close) return server, &calls diff --git a/backend/internal/service/content_moderation_upstream_scope.go b/backend/internal/service/content_moderation_upstream_scope.go index dd6b0137150e..a58d8108e753 100644 --- a/backend/internal/service/content_moderation_upstream_scope.go +++ b/backend/internal/service/content_moderation_upstream_scope.go @@ -2,6 +2,7 @@ package service import ( "context" + "errors" "fmt" "log/slog" "slices" @@ -50,6 +51,7 @@ func validModerationUpstreamAccount(a *Account) bool { } func (s *ContentModerationService) updateUpstreamScope(ctx context.Context, cfg *ContentModerationConfig, input UpdateContentModerationConfigInput) error { + previousIDs := append([]int64(nil), cfg.UpstreamAccountIDs...) if input.UpstreamAccountScope != nil { if *input.UpstreamAccountScope != ModerationUpstreamAll && *input.UpstreamAccountScope != ModerationUpstreamSelected { return infraerrors.BadRequest("INVALID_MODERATION_UPSTREAM_SCOPE", "Unknown upstream account scope") @@ -83,10 +85,10 @@ func (s *ContentModerationService) updateUpstreamScope(ctx context.Context, cfg return infraerrors.BadRequest("INVALID_MODERATION_UPSTREAM_ACCOUNT", fmt.Sprintf("Upstream account %d is missing or has an unsupported platform/type", id)) } binding := moderationUpstreamBinding(a) - if input.UpstreamAccountIDs == nil { + if slices.Contains(previousIDs, id) { previous, ok := cfg.UpstreamAccountBindings[id] if !ok || previous.Platform != binding.Platform || previous.Type != binding.Type || !slices.Equal(previous.GroupIDs, binding.GroupIDs) { - return infraerrors.BadRequest("STALE_MODERATION_UPSTREAM_ACCOUNT", fmt.Sprintf("Review and reselect changed upstream account %d", id)) + return infraerrors.BadRequest("STALE_MODERATION_UPSTREAM_ACCOUNT", fmt.Sprintf("Remove and save before reselecting changed upstream account %d", id)) } } bindings[id] = binding @@ -176,3 +178,13 @@ func CheckUpstreamModeration(ctx context.Context, c *gin.Context, account *Accou } return nil } + +// UpstreamModerationDeniedError marks a local policy response already written +// by the ingress gate. It must never enter provider retry/health/usage handling. +type UpstreamModerationDeniedError struct{ Message string } + +func (e *UpstreamModerationDeniedError) Error() string { return e.Message } +func IsUpstreamModerationDenied(err error) bool { + var denied *UpstreamModerationDeniedError + return errors.As(err, &denied) +} diff --git a/backend/internal/service/content_moderation_upstream_scope_test.go b/backend/internal/service/content_moderation_upstream_scope_test.go index 7db2580c9a3b..babc32995f90 100644 --- a/backend/internal/service/content_moderation_upstream_scope_test.go +++ b/backend/internal/service/content_moderation_upstream_scope_test.go @@ -73,6 +73,8 @@ func TestModerationUpstreamPersistenceAndValidation(t *testing.T) { require.Error(t, err, "moving accounts cannot widen scope") _, err = fresh.UpdateConfig(ctx, UpdateContentModerationConfigInput{}) require.Error(t, err, "unrelated saves cannot silently rebind a moved account") + _, err = fresh.UpdateConfig(ctx, UpdateContentModerationConfigInput{UpstreamAccountIDs: &ids}) + require.Error(t, err, "resubmitting unchanged IDs cannot silently rebind moved accounts") delete(accounts.accounts, 1) _, err = fresh.UpstreamModerationApplies(ctx, &stored, input) require.Error(t, err, "deleted account must fail closed") diff --git a/backend/internal/service/minimax_h3.go b/backend/internal/service/minimax_h3.go index 3284948d8c57..96d18f06d579 100644 --- a/backend/internal/service/minimax_h3.go +++ b/backend/internal/service/minimax_h3.go @@ -126,6 +126,10 @@ func validMiniMaxH3OutputURL(raw string) bool { } func (s *OpenAIGatewayService) ForwardMiniMaxH3(ctx context.Context, c *gin.Context, account *Account, endpoint GrokMediaEndpoint, taskID string, body []byte) (*OpenAIForwardResult, error) { + if err := CheckUpstreamModeration(ctx, c, account); err != nil { + return nil, err + } + if !endpoint.IsMiniMaxH3() || !account.SupportsOpenAIEndpointCapability(OpenAIEndpointCapabilityMiniMaxH3) { return nil, fmt.Errorf("MiniMax-H3 requires a MiniMax pay-as-you-go API key account with a custom base URL") } diff --git a/backend/internal/service/openai_account_scheduler.go b/backend/internal/service/openai_account_scheduler.go index f97d6d37ad49..452a6d0a615d 100644 --- a/backend/internal/service/openai_account_scheduler.go +++ b/backend/internal/service/openai_account_scheduler.go @@ -3165,7 +3165,7 @@ func (s *OpenAIGatewayService) ReportOpenAIAccountScheduleResult(account *Accoun if account == nil { return false } - if !success && len(observedErr) > 0 && isGrokRequestScopedFailure(observedErr[0]) { + if !success && len(observedErr) > 0 && (isGrokRequestScopedFailure(observedErr[0]) || IsUpstreamModerationDenied(observedErr[0])) { return false } // A failed managed proxy acquisition says nothing about account health. @@ -3201,7 +3201,7 @@ func (s *OpenAIGatewayService) ReportOpenAIAccountScheduleResult(account *Accoun // ObserveOpenAIAccountHealthFailure records failures that cannot reach the // scheduler-result path, for example after semantic response bytes were sent. func (s *OpenAIGatewayService) ObserveOpenAIAccountHealthFailure(ctx context.Context, account *Account, observedErr error) bool { - if s == nil || s.rateLimitService == nil || account == nil || observedErr == nil || isGrokRequestScopedFailure(observedErr) { + if s == nil || s.rateLimitService == nil || account == nil || observedErr == nil || isGrokRequestScopedFailure(observedErr) || IsUpstreamModerationDenied(observedErr) { return false } return s.rateLimitService.ObserveOpenAIAPIKeyHealthFailure(ctx, account, observedErr) diff --git a/backend/internal/service/openai_alpha_search.go b/backend/internal/service/openai_alpha_search.go index 64802b8397a5..a820d56503bf 100644 --- a/backend/internal/service/openai_alpha_search.go +++ b/backend/internal/service/openai_alpha_search.go @@ -27,6 +27,10 @@ const ( // *OpenAIForwardResult(WebSearchCalls=1,供按次计费);上游错误被原样透传 // 给客户端时返回 (nil, nil),不产生计费。 func (s *OpenAIGatewayService) ForwardAlphaSearch(ctx context.Context, c *gin.Context, account *Account, body []byte) (*OpenAIForwardResult, error) { + if err := CheckUpstreamModeration(ctx, c, account); err != nil { + return nil, err + } + if s == nil || c == nil || account == nil { return nil, fmt.Errorf("service, context, and account are required") } diff --git a/backend/internal/service/openai_embeddings.go b/backend/internal/service/openai_embeddings.go index df62417604dd..b86eaaaa4995 100644 --- a/backend/internal/service/openai_embeddings.go +++ b/backend/internal/service/openai_embeddings.go @@ -24,6 +24,10 @@ func (s *OpenAIGatewayService) ForwardEmbeddings( body []byte, defaultMappedModel string, ) (*OpenAIForwardResult, error) { + if err := CheckUpstreamModeration(ctx, c, account); err != nil { + return nil, err + } + managed := account.HasManagedOpenAIConnections() if account != nil && account.Platform == PlatformOpenAI && s.excelOAuthReauth != nil { if repo, ok := s.excelOAuthReauth.repo.(OpenAIAuthConnectionRepository); ok { diff --git a/backend/internal/service/seedance.go b/backend/internal/service/seedance.go index 36d9b0ca0672..ba24132052b7 100644 --- a/backend/internal/service/seedance.go +++ b/backend/internal/service/seedance.go @@ -73,6 +73,10 @@ func buildSeedanceURL(base string, endpoint GrokMediaEndpoint, taskID string) (s // ForwardSeedance preserves the Ark protocol, including multimodal content and // future fields. Only model is rewritten using the account's configured mapping. func (s *OpenAIGatewayService) ForwardSeedance(ctx context.Context, c *gin.Context, account *Account, endpoint GrokMediaEndpoint, taskID string, body []byte) (*OpenAIForwardResult, error) { + if err := CheckUpstreamModeration(ctx, c, account); err != nil { + return nil, err + } + if !account.SupportsOpenAIEndpointCapability(OpenAIEndpointCapabilitySeedance) || !endpoint.IsSeedance() { return nil, fmt.Errorf("seedance requires an OpenAI API key account with a custom base URL") } diff --git a/docs/implementation/moderation-upstream-account-scope.md b/docs/implementation/moderation-upstream-account-scope.md index 42d44a8d1f2c..ed25d54baa31 100644 --- a/docs/implementation/moderation-upstream-account-scope.md +++ b/docs/implementation/moderation-upstream-account-scope.md @@ -13,3 +13,14 @@ Keep existing pre-route admission and prompt audit semantics. Defer ONLY account Acceptance starts with a real WS handler/scheduler + loopback audit/provider fixture: a non-selected account must produce generation with zero audit calls. Baseline currently audits and blocks; RED must be a business assertion. Extend with selected deny (zero generation writes), HTTP types/stream modes, failover, WS next turn/native/pool/bridge, persistence/validation, selector integration and A→B→C badge behavior. Capture rendered original UI remotely before changing it. No external provider/network fixture requests. UI: reuse QualityAccountSelector with fixed manual selection, server search and pagination, stable selected-ID union across hidden pages, cancellable/fenced asynchronous reads and batch selection. Account filters describe discovery only; saved IDs control policy. Chinese and English explain group AND account semantics and empty selection. Add registered NewFeatureBadge. + + +## Review repairs and explicit operational semantics + +The admin HTTP DTO passes scope and IDs to service validation; stored binding metadata remains server-owned. A retained ID whose platform/type/group membership changed cannot be silently rebound by an unrelated save or by resubmitting the same IDs. Remove it and save, then select it again to explicitly approve a new binding. Switching to all clears the selection in the UI. + +Post-selection policy errors use a typed local denial. HTTP callers return after their existing slot/queue release, and the scheduler also ignores that error defensively. WebSocket denials carry the existing local-admission sentinel. JSON image keepalive responses finish with one JSON document; SSE stays framed as an error event. Async workers rebind the immutable state to their own response context. + +Audit turn identity is connection-wide, independent of transport counters that restart during same-account retry or failover. A replay retains the prior decision; a newly received client turn advances the audit identity even when its body is identical. All legacy audit entry points were traced, including protocol adapters, media, batch submit, Live creation, cached-content creation, embeddings and alpha/standalone search. Alpha commands and batch-item prompts are derived from the frozen original request for selected-account moderation; existing pre-route prompt auditing is unchanged. + +Remote fixtures distinguish configuration persistence, actual generation writes, and rendered UI. Neither an offline browser adapter nor a configuration-only test proves routing acceptance. The acceptance workflow requires named tests and rejects compilation/setup errors, panic, race, skipped/missing tests and crashes. diff --git a/frontend/src/components/admin/moderation/ModerationUpstreamAccountSelector.vue b/frontend/src/components/admin/moderation/ModerationUpstreamAccountSelector.vue index 456d281bd44e..6ad61a6ab05a 100644 --- a/frontend/src/components/admin/moderation/ModerationUpstreamAccountSelector.vue +++ b/frontend/src/components/admin/moderation/ModerationUpstreamAccountSelector.vue @@ -33,6 +33,7 @@ import QualityAccountSelector from '@/components/admin/operations/QualityAccount import { qualityAccountTypeOptions } from '@/utils/qualityAccountFilter' const { t } = useI18n() +const emit = defineEmits<{ busy: [value: boolean] }>() defineProps<{ groups: { id: number; name: string }[] }>() const selected = defineModel({ required: true }) const scope = defineModel<'all' | 'selected'>('scope', { required: true }) @@ -82,5 +83,6 @@ async function selectAll() { } // Filters only discover accounts; selection is an independent persistent ID set. watch([search, group, type, scope], () => { void loadPage(1) }, { immediate: true, flush: 'sync' }) -onBeforeUnmount(invalidate) +watch(selecting, value => emit('busy', value), { flush: 'sync' }) +onBeforeUnmount(() => { invalidate(); emit('busy', false) }) diff --git a/frontend/src/components/common/__tests__/NewFeatureBadge.spec.ts b/frontend/src/components/common/__tests__/NewFeatureBadge.spec.ts index ead9d40f0fa5..c1abfc07db41 100644 --- a/frontend/src/components/common/__tests__/NewFeatureBadge.spec.ts +++ b/frontend/src/components/common/__tests__/NewFeatureBadge.spec.ts @@ -23,6 +23,7 @@ describe('NewFeatureBadge', () => { it.each([ + ['moderation upstream scope', NEW_FEATURE_NOTICES.moderationUpstreamAccountScope], ['admin usage platform', NEW_FEATURE_NOTICES.adminUsagePlatform], ['user ID copy', NEW_FEATURE_NOTICES.userIdCopy], ['Antigravity usage query', NEW_FEATURE_NOTICES.antigravityUsageQuery], diff --git a/frontend/src/i18n/locales/en/admin/channels.ts b/frontend/src/i18n/locales/en/admin/channels.ts index 389cc442a76a..7e150e713c70 100644 --- a/frontend/src/i18n/locales/en/admin/channels.ts +++ b/frontend/src/i18n/locales/en/admin/channels.ts @@ -500,7 +500,7 @@ export default { selectedUpstreamAccounts: "Only selected upstream accounts", emptyUpstreamAccounts: "No accounts selected: this policy audits no requests.", findUpstreamAccounts: "Find upstream accounts by name or #ID", - upstreamSelectionHint: "Filters only change this list. Selected IDs remain selected across pages and filters. Deleted accounts or changed platform, type or group membership require review and reselection; affected requests fail closed.", + upstreamSelectionHint: "Filters only change this list. Selected IDs remain selected across pages and filters. Deleted accounts or changed platform, type or group membership require review; affected requests fail closed. Remove the account and save before selecting it again.", upstreamAccountsLoadFailed: "Could not load all accounts. Selection was preserved. Retry or select fewer than 10,000 accounts.", upstreamType: "Upstream", bedrockType: "AWS Bedrock", diff --git a/frontend/src/i18n/locales/zh/admin/channels.ts b/frontend/src/i18n/locales/zh/admin/channels.ts index 6f1a80bae770..59dc8ef450ce 100644 --- a/frontend/src/i18n/locales/zh/admin/channels.ts +++ b/frontend/src/i18n/locales/zh/admin/channels.ts @@ -500,7 +500,7 @@ export default { selectedUpstreamAccounts: "仅指定上游账号", emptyUpstreamAccounts: "尚未选择账号:此规则不会审计任何请求。", findUpstreamAccounts: "按名称或 #ID 查找上游账号", - upstreamSelectionHint: "筛选仅改变列表;翻页或修改筛选不会丢失已选 ID。账号删除或平台、类型、分组归属变化后,受影响请求将安全拒绝,需检查并重新选择。", + upstreamSelectionHint: "筛选仅改变列表;翻页或修改筛选不会丢失已选 ID。账号删除或平台、类型、分组归属变化后,受影响请求将安全拒绝,需检查、移除该账号并保存后再重新选择。", upstreamAccountsLoadFailed: "无法加载完整账号列表,已保留原选择。请重试或将选择控制在 10,000 个以内。", upstreamType: "上游账号", bedrockType: "AWS Bedrock", diff --git a/frontend/src/views/admin/RiskControlView.vue b/frontend/src/views/admin/RiskControlView.vue index ecebff5b5d87..f170cf596bb6 100644 --- a/frontend/src/views/admin/RiskControlView.vue +++ b/frontend/src/views/admin/RiskControlView.vue @@ -754,7 +754,7 @@
- +
@@ -1116,7 +1116,7 @@