diff --git a/.github/scripts/moderation-scope-preview.mjs b/.github/scripts/moderation-scope-preview.mjs
new file mode 100644
index 000000000000..3e28b034d2a4
--- /dev/null
+++ b/.github/scripts/moderation-scope-preview.mjs
@@ -0,0 +1,133 @@
+// 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'
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, 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 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 gitBytes=(ref,file)=>execFileSync('git',['show',`${ref}:${file}`],{cwd:repo})
+const sources=Object.fromEntries(sourceFiles.map(file=>[file,{before:hash(gitBytes(base,file)),after:hash(gitBytes(head,file))}]))
+for(const file of sourceFiles)assert.equal(hash(readFileSync(join(repo,file))),sources[file].after,'candidate worktree must match committed bytes')
+sources['frontend/src/components/admin/moderation/ModerationUpstreamAccountSelector.vue']={after:hash(gitBytes(head,'frontend/src/components/admin/moderation/ModerationUpstreamAccountSelector.vue'))}
+assert.equal(hash(readFileSync(join(root,'src/components/admin/moderation/ModerationUpstreamAccountSelector.vue'))),sources['frontend/src/components/admin/moderation/ModerationUpstreamAccountSelector.vue'].after)
+const entryName=`.moderation-preview-${process.pid}.js`,entry=join(root,entryName),cacheDir=mkdtempSync(join(tmpdir(),'moderation-preview-'))
+const captures=[],assertions=[],errors=[],reachability=[]
+const baselineTree=join(cacheDir,'baseline')
+assert.equal(git('rev-parse',`${base}:frontend/pnpm-lock.yaml`),git('rev-parse',`${head}:frontend/pnpm-lock.yaml`),'baseline and candidate use identical dependency lock')
+git('worktree','add','--detach',baselineTree,base)
+symlinkSync(join(root,'node_modules'),join(baselineTree,'frontend/node_modules'),'dir')
+const frontendTrees={before:git('rev-parse',`${base}:frontend`),after:git('rev-parse',`${head}:frontend`)}
+let before=true,server,browser,page
+mkdirSync(output,{recursive:true})
+try{
+writeFileSync(entry,`
+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:225},(_,i)=>({id:i+1,name:'Demo account '+(i+1),platform:'openai',moderation_scope_eligible:true,type:i%2?'oauth':'apikey',group_ids:[i%2?4301:4302]}));
+window.__writes=[];window.__reads=[];window.__held=[];window.__saved=()=>structuredClone(cfg);
+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({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'})
+const startServer=async(activeRoot)=>{
+process.chdir(activeRoot)
+server=await createServer({root:activeRoot,configFile:false,cacheDir,resolve:{alias:{'@':join(activeRoot,'src')}},plugins:[{
+ name:'fixture-layout-and-pinned-baseline',enforce:'pre',load(id){
+ if(id===join(activeRoot,'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})
+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 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:false});captures.push({file,sha256:hash(readFileSync(join(output,file))),viewport:{width,height},locale,source:before?base:head,settled:true,activeTab:'scope'})
+ if(!before){
+ const picker=page.getByTestId('moderation-upstream-selector'),search=page.locator('#moderation-upstream-search')
+ assert.equal(await picker.locator('[data-account-id]').count(),50)
+ await reach(picker.getByTestId('quality-select-page'),'select page '+device+' '+locale);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 reach(picker.locator('[data-account-id="51"] input'),'account row '+device+' '+locale);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 reach(picker.locator('[data-account-id="125"] input'),'searched account '+device+' '+locale);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 reach(picker.getByTestId('quality-account-type'),'type filter '+device+' '+locale);await picker.getByTestId('quality-account-type').selectOption('oauth');await reach(picker.getByTestId('quality-account-group'),'group filter '+device+' '+locale);await picker.getByTestId('quality-account-group').selectOption('4301');await page.waitForFunction(()=>document.querySelectorAll('[data-account-id]').length===50)
+ await reach(picker.getByTestId('quality-select-all'),'batch '+device+' '+locale);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 reach(save,'save '+device+' '+locale);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');const expected=[...new Set([999,121,...Array.from({length:51},(_,i)=>i+1),125,...Array.from({length:112},(_,i)=>(i+1)*2)])].sort((a,b)=>a-b);assert.deepEqual([...written.upstream_account_ids].sort((a,b)=>a-b),expected)
+ 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);assert.deepEqual((await page.evaluate(()=>window.__saved().upstream_account_ids)).sort((a,b)=>a-b),expected)
+ await reach(picker.getByTestId('quality-clear-selection'),'clear '+device+' '+locale);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 reach(badges.last(),'notice '+device+' '+locale);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(device+' '+locale+': 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 is a separate PostgreSQL acceptance job, never inferred from this API adapter.')
+ }
+ await page.close();page=undefined
+ }
+ await server.close();server=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,frontendTrees,sources,sourceHashNormalization:'exact bytes',captures,reachability,assertions,errors,boundary:'Actual RiskControlView, shared QualityAccountSelector, BaseDialog, project CSS/locales; layout shell and synthetic offline APIs only; separate full baseline/candidate frontend trees with identical dependency lock, transitions settled and active scope tab asserted.'},null,2)+'\n');await browser?.close();await server?.close();rmSync(entry,{force:true});git('worktree','remove','--force',baselineTree);rmSync(cacheDir,{recursive:true,force:true})}
diff --git a/.github/workflows/issue805-owner-policy.yml b/.github/workflows/issue805-owner-policy.yml
index 6ff182d8c19d..292e805d75b4 100644
--- a/.github/workflows/issue805-owner-policy.yml
+++ b/.github/workflows/issue805-owner-policy.yml
@@ -100,6 +100,25 @@ jobs:
test ! -e "$omission_test"
echo "$omission_test test=candidate-only candidate=$candidate actual=absent reason=unavailable-unit-helpers" >> "$RUNNER_TEMP/issue805-evidence/red-blobs.txt"
fi
+ # Account-scope tests require production symbols introduced after
+ # this baseline. Keep them in GREEN and their dedicated acceptance;
+ # omit only this unrelated feature from the disposable old-source RED.
+ while IFS= read -r target; do
+ candidate=$(git rev-parse "$EXPECTED_HEAD_SHA:$target")
+ rm -- "$target"
+ test ! -e "$target"
+ echo "$target test=candidate-only candidate=$candidate actual=absent reason=moderation-scope-not-in-baseline" >> "$RUNNER_TEMP/issue805-evidence/red-blobs.txt"
+ done < <(git ls-files 'backend/internal/handler/moderation_upstream*_test.go')
+ # The shared WS fixture gained an optional moderation repository only
+ # in PR848; its pre-feature version preserves the Issue805 contract.
+ target=backend/internal/handler/openai_ws_v2_passthrough_cyber_test.go
+ fixture_base=4189ed821d6e4308b2f5fc3791b73d2eb53cda8a
+ git fetch --no-tags --depth=1 origin "$fixture_base"
+ git show "$fixture_base:$target" > "$target"
+ expected=$(git rev-parse "$fixture_base:$target")
+ actual=$(git hash-object "$target")
+ test "$expected" = "$actual"
+ echo "$target test=pre-moderation-scope expected=$expected actual=$actual" >> "$RUNNER_TEMP/issue805-evidence/red-blobs.txt"
# The selected regression and its shared harness must remain exact
# candidate blobs. The clean GREEN checkout retains all new tests.
for target in backend/internal/handler/openai_issue805_delivery_test.go backend/internal/handler/openai_issue805_owner_policy_test.go backend/internal/handler/openai_issue805_ws_test.go backend/internal/handler/openai_issue715_recovery_test.go; do
diff --git a/.github/workflows/moderation-upstream-scope.yml b/.github/workflows/moderation-upstream-scope.yml
new file mode 100644
index 000000000000..4972109608f5
--- /dev/null
+++ b/.github/workflows/moderation-upstream-scope.yml
@@ -0,0 +1,126 @@
+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
+ 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()
+ with:
+ name: moderation-scope-red-${{ github.sha }}
+ path: ${{ runner.temp }}/moderation-scope
+ ui-evidence:
+ runs-on: ubuntu-latest
+ timeout-minutes: 20
+ steps:
+ - uses: actions/checkout@v6
+ with:
+ fetch-depth: 0
+ - 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: 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
+ 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
+ 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/handler/admin ./internal/service ./internal/securityaudit -run 'TestModerationUpstream|TestOpenAIResponsesWebSocket_ContentModeration|Test.*SecurityAudit|Test.*Queue.*Auth|Test.*Turn.*Admission|TestCoordinator|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 TestModerationUpstreamHTTPDispatchFamilies TestModerationUpstreamWebSocketCurrentAliasControlsScope TestModerationUpstreamEligibility TestModerationUpstreamAccountCatalogEligibility; do
+ grep -q -- "--- PASS: $name" "$RUNNER_TEMP/moderation-scope-green/green.log"
+ done
+ - uses: actions/upload-artifact@v7
+ if: always()
+ with:
+ name: moderation-scope-green-${{ github.sha }}
+ path: ${{ runner.temp }}/moderation-scope-green
+ postgres-persistence:
+ 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: Authenticated handler and real PostgreSQL persistence
+ run: |
+ mkdir -p "$RUNNER_TEMP/moderation-scope-postgres"
+ git rev-parse HEAD > "$RUNNER_TEMP/moderation-scope-postgres/head.txt"
+ set -o pipefail
+ cd backend
+ go test -tags=integration ./internal/repository -run '^TestModerationUpstreamPostgresAdminRoundTrip$' -count=1 -v -timeout=10m 2>&1 | tee "$RUNNER_TEMP/moderation-scope-postgres/postgres.log"
+ if grep -Eiq 'build failed|no tests to run|undefined:|--- SKIP:|panic:|fatal error:|DATA RACE|signal:|segmentation fault' "$RUNNER_TEMP/moderation-scope-postgres/postgres.log"; then exit 1; fi
+ grep -q -- '--- PASS: TestModerationUpstreamPostgresAdminRoundTrip' "$RUNNER_TEMP/moderation-scope-postgres/postgres.log"
+ - uses: actions/upload-artifact@v7
+ if: always()
+ with:
+ name: moderation-scope-postgres-${{ github.sha }}
+ path: ${{ runner.temp }}/moderation-scope-postgres
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/admin/account_handler.go b/backend/internal/handler/admin/account_handler.go
index f5472028a7ec..c363db2bd344 100644
--- a/backend/internal/handler/admin/account_handler.go
+++ b/backend/internal/handler/admin/account_handler.go
@@ -225,6 +225,7 @@ type CheckMixedChannelRequest struct {
// AccountWithConcurrency extends Account with real-time concurrency info
type AccountWithConcurrency struct {
+ ModerationScopeEligible bool `json:"moderation_scope_eligible"`
*dto.Account
simpleMode bool `json:"-"`
CurrentConcurrency int `json:"current_concurrency"`
@@ -242,6 +243,7 @@ type AccountWithConcurrency struct {
// for lite=1. It embeds dto.AccountListItem instead of the full dto.Account,
// so groups/account_groups never appear in the list payload.
type AccountListItemWithConcurrency struct {
+ ModerationScopeEligible bool `json:"moderation_scope_eligible"`
*dto.AccountListItem
CurrentConcurrency int `json:"current_concurrency"`
SchedulerScore *AccountSchedulerScore `json:"scheduler_score,omitempty"`
@@ -412,9 +414,10 @@ func (h *AccountHandler) isSimpleMode() bool {
func (h *AccountHandler) buildAccountResponseWithRuntime(ctx context.Context, account *service.Account) AccountWithConcurrency {
item := AccountWithConcurrency{
- Account: dto.AccountForObserver(ctx, h.accountResponseFromService(account)),
- simpleMode: h.isSimpleMode(),
- CurrentConcurrency: 0,
+ Account: dto.AccountForObserver(ctx, h.accountResponseFromService(account)),
+ ModerationScopeEligible: service.ModerationUpstreamAccountEligible(account),
+ simpleMode: h.isSimpleMode(),
+ CurrentConcurrency: 0,
}
if account == nil {
return item
@@ -878,11 +881,12 @@ func (h *AccountHandler) List(c *gin.Context) {
}
}
item := AccountWithConcurrency{
- Account: accountResponse,
- simpleMode: h.isSimpleMode(),
- CurrentConcurrency: concurrencyCounts[acc.ID],
- SchedulerScore: schedulerScores[acc.ID],
- SchedulerScores: schedulerGroupScores[acc.ID],
+ Account: accountResponse,
+ ModerationScopeEligible: service.ModerationUpstreamAccountEligible(acc),
+ simpleMode: h.isSimpleMode(),
+ CurrentConcurrency: concurrencyCounts[acc.ID],
+ SchedulerScore: schedulerScores[acc.ID],
+ SchedulerScores: schedulerGroupScores[acc.ID],
}
// 添加窗口费用(仅当启用时)
@@ -929,15 +933,16 @@ func (h *AccountHandler) List(c *gin.Context) {
for i := range result {
item := result[i]
compact[i] = AccountListItemWithConcurrency{
- AccountListItem: dto.AccountListItemFromAccount(item.Account),
- CurrentConcurrency: item.CurrentConcurrency,
- SchedulerScore: item.SchedulerScore,
- SchedulerScores: item.SchedulerScores,
- CurrentWindowCost: item.CurrentWindowCost,
- ActiveSessions: item.ActiveSessions,
- CurrentRPM: item.CurrentRPM,
- RPMPaused: item.RPMPaused,
- RPMResetAt: item.RPMResetAt,
+ AccountListItem: dto.AccountListItemFromAccount(item.Account),
+ ModerationScopeEligible: item.ModerationScopeEligible,
+ CurrentConcurrency: item.CurrentConcurrency,
+ SchedulerScore: item.SchedulerScore,
+ SchedulerScores: item.SchedulerScores,
+ CurrentWindowCost: item.CurrentWindowCost,
+ ActiveSessions: item.ActiveSessions,
+ CurrentRPM: item.CurrentRPM,
+ RPMPaused: item.RPMPaused,
+ RPMResetAt: item.RPMResetAt,
}
}
etag := buildAccountsListETag(compact, total, page, pageSize, platform, accountType, status, search, true)
diff --git a/backend/internal/handler/admin/account_handler_list_test.go b/backend/internal/handler/admin/account_handler_list_test.go
index f4304eb93de0..c780fd027911 100644
--- a/backend/internal/handler/admin/account_handler_list_test.go
+++ b/backend/internal/handler/admin/account_handler_list_test.go
@@ -405,3 +405,26 @@ func TestAccountHandlerListSchedulerScoreIgnoresPagination(t *testing.T) {
require.Less(t, payload.Data.Items[0].SchedulerScore.BaseScore, 3.75)
require.Empty(t, payload.Data.Items[0].SchedulerScores)
}
+
+func TestModerationUpstreamAccountCatalogEligibility(t *testing.T) {
+ router, adminSvc := setupAccountListRouter()
+ adminSvc.accounts = []service.Account{
+ {ID: 801, Name: "Vertex fixture", Platform: service.PlatformAnthropic, Type: service.AccountTypeServiceAccount, Credentials: map[string]any{}},
+ {ID: 802, Name: "Unsupported fixture", Platform: service.PlatformTypeSafe, Type: service.AccountTypeOAuth, Credentials: map[string]any{}},
+ }
+ w := httptest.NewRecorder()
+ router.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/api/v1/admin/accounts?lite=1", nil))
+ require.Equal(t, 200, w.Code)
+ var got struct {
+ Data struct {
+ Items []struct {
+ ID int64 `json:"id"`
+ Eligible bool `json:"moderation_scope_eligible"`
+ } `json:"items"`
+ } `json:"data"`
+ }
+ require.NoError(t, json.Unmarshal(w.Body.Bytes(), &got))
+ require.Len(t, got.Data.Items, 2)
+ require.True(t, got.Data.Items[0].Eligible)
+ require.False(t, got.Data.Items[1].Eligible)
+}
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..044420b96bb8
--- /dev/null
+++ b/backend/internal/handler/admin/moderation_upstream_scope_test.go
@@ -0,0 +1,119 @@
+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) GetUserAvatar(context.Context, int64) (*service.UserAvatar, error) {
+ return nil, nil
+}
+
+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/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/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/image_task_handler.go b/backend/internal/handler/image_task_handler.go
index e00b23c17f1b..977ad888a1ee 100644
--- a/backend/internal/handler/image_task_handler.go
+++ b/backend/internal/handler/image_task_handler.go
@@ -244,6 +244,14 @@ func (h *AsyncImageHandler) run(taskID, platform string, taskCtx *gin.Context, r
h.failTask(taskID, http.StatusGatewayTimeout, imageTaskErrorPayload("timeout_error", "image generation task timed out"))
return
}
+ // JSON whitespace keepalives may commit 200 before a local policy denial.
+ // The worker's semantic result is independent of that transport status.
+ if status, ok := taskCtx.Get(upstreamAuditFailureStatusKey); ok {
+ if code, ok := status.(int); ok && code >= 400 {
+ h.failTask(taskID, code, extractImageTaskError(body))
+ return
+ }
+ }
statusCode := recorder.Code
if statusCode == 0 {
statusCode = http.StatusOK
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..e3c62739d6fb
--- /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","second independent 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
new file mode 100644
index 000000000000..d4f97fbe68c1
--- /dev/null
+++ b/backend/internal/handler/moderation_upstream_http_test.go
@@ -0,0 +1,132 @@
+//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/service"
+ "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", "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)
+ 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": "https://fixture.example"}, Extra: map[string]any{"codex_fingerprint_mode": "off"}})
+ }
+ target, err := url.Parse(upstream.URL)
+ require.NoError(t, err)
+ transport := moderationLoopbackUpstream{&nativeImageRouteUpstream{target: target, client: upstream.Client()}}
+ 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}
+ }
+ 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)}}
+ 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 == "deny" || scenario == "multi-group" {
+ 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(), 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(), rec.Body.String())
+ 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" || scenario == "multi-group" {
+ require.Zero(t, writesA.Load())
+ } else {
+ 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..7388ec966dba
--- /dev/null
+++ b/backend/internal/handler/moderation_upstream_images_test.go
@@ -0,0 +1,103 @@
+//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, workerStatus atomic.Int32
+ release := make(chan struct{})
+
+ audit := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ audits.Add(1)
+ if scenario == "slow" || scenario == "async" {
+ 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)
+ async.execute = func(_ string, c *gin.Context) { h.Images(c); workerStatus.Store(int32(c.Writer.Status())) }
+ 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":`))
+ }
+ if scenario == "async" {
+ require.Equal(t, int32(200), workerStatus.Load(), "async denial must actually follow a committed worker keepalive")
+ }
+ 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
new file mode 100644
index 000000000000..a82b1e669ae1
--- /dev/null
+++ b/backend/internal/handler/moderation_upstream_scope.go
@@ -0,0 +1,188 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "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"
+ "github.com/tidwall/gjson"
+ "go.uber.org/zap"
+)
+
+const upstreamAuditStateKey = "content_moderation.upstream_state"
+const upstreamAuditFailureStatusKey = "content_moderation.local_failure_status"
+
+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 {
+ bindUpstreamAuditGate(c, state)
+ return
+ }
+ }
+ cfg, err := legacy.UpstreamModerationConfig(c.Request.Context())
+ state := &upstreamAuditState{request: securityaudit.Request{Stage: stage}, config: cfg, configErr: err, legacy: legacy, coordinator: coordinator, log: log, turn: turn}
+ // Legacy group-only traffic needs no retained content copy or account gate.
+ if cfg != nil || err != nil {
+ state.request = buildSecurityAuditRequest(c, apiKey, subject, protocol, model, body, stage).Clone()
+ if isSecurityAuditWebSocketStage(stage) {
+ state.request.Model = strings.TrimSpace(model)
+ }
+ }
+ c.Set(upstreamAuditStateKey, state)
+ bindUpstreamAuditGate(c, state)
+}
+
+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 &service.UpstreamModerationDeniedError{Message: 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
+ // 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 == "openai_embeddings" && gjson.GetBytes(req.Body, "input").IsArray() {
+ parts := []string{}
+ for _, item := range gjson.GetBytes(req.Body, "input").Array() {
+ parts = append(parts, item.String())
+ }
+ req.Body, _ = json.Marshal(map[string]string{"input": strings.Join(parts, "\n")})
+ } 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,
+ 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)
+ c.Set(upstreamAuditFailureStatusKey, status)
+ 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 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)
+ _ = 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
new file mode 100644
index 000000000000..cb05a63e8cef
--- /dev/null
+++ b/backend/internal/handler/moderation_upstream_scope_test.go
@@ -0,0 +1,55 @@
+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())
+}
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
new file mode 100644
index 000000000000..057ca711bae7
--- /dev/null
+++ b/backend/internal/handler/moderation_upstream_ws_test.go
@@ -0,0 +1,157 @@
+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"
+ 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"} {
+ 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) {
+ 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" {
+ 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")
+ }
+ })
+ }
+ }
+ }
+}
+
+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")
+}
+
+func TestModerationUpstreamWebSocketCurrentAliasControlsScope(t *testing.T) {
+ for _, mode := range []string{service.OpenAIWSIngressModePassthrough, service.OpenAIWSIngressModeCtxPool, service.OpenAIWSIngressModeHTTPBridge} {
+ t.Run(mode, func(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)
+ require.Contains(t, string(body), "second blocked input")
+ _, _ = w.Write([]byte(`{"results":[{"category_scores":{"sexual":0.99}}]}`))
+ }))
+ defer audit.Close()
+ raw, err := json.Marshal(map[string]any{"enabled": true, "mode": "pre_block", "all_groups": true, "model_filter": map[string]any{"type": "include", "models": []string{"public-b"}}, "sample_rate": 100, "base_url": audit.URL, "api_keys": []string{"fixture"}, "upstream_account_scope": "selected", "upstream_account_ids": []int64{9951}, "upstream_account_bindings": map[int64]service.ModerationUpstreamBinding{9951: {Platform: service.PlatformOpenAI, Type: service.AccountTypeAPIKey, GroupIDs: []int64{4301}}}})
+ require.NoError(t, err)
+ h, up := newIssue600NetworkHarness(t, mode, "none", false, nil, issue600FixtureOptions{modelMapping: map[string]string{"public-a": "gpt-5.1", "public-b": "gpt-5.1"}, moderationSettings: map[string]string{service.SettingKeyContentModerationConfig: string(raw)}})
+ issue600Send(t, h, `{"type":"response.create","model":"public-a","input":"first"}`, 1, false)
+ require.Zero(t, audits.Load())
+ 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":"public-b","input":"second blocked input"}`)))
+ _, 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, 1)
+ require.Equal(t, int32(1), audits.Load())
+ })
+ }
+}
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_count_tokens.go b/backend/internal/handler/openai_gateway_count_tokens.go
index ca183a6b0975..97df730974dd 100644
--- a/backend/internal/handler/openai_gateway_count_tokens.go
+++ b/backend/internal/handler/openai_gateway_count_tokens.go
@@ -133,6 +133,9 @@ func (h *OpenAIGatewayHandler) ResponsesInputTokens(c *gin.Context) {
}
setOpsSelectedAccount(c, account.ID, account.Platform)
+ if err := service.CheckUpstreamModeration(c.Request.Context(), c, account); err != nil {
+ return
+ }
if err := h.gatewayService.ForwardResponsesInputTokens(c.Request.Context(), c, account, forwardBody); err != nil {
reqLog.Error("openai_input_tokens.forward_failed", zap.Int64("account_id", account.ID), zap.Error(err))
}
diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go
index aeb7fc8a9fee..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))
@@ -3609,6 +3620,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,
@@ -3656,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 及上游写入前无副作用地拒绝。
@@ -3722,9 +3741,13 @@ 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), 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/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_client_identity_test.go b/backend/internal/handler/openai_ws_client_identity_test.go
index 01bdc232d803..745001f94356 100644
--- a/backend/internal/handler/openai_ws_client_identity_test.go
+++ b/backend/internal/handler/openai_ws_client_identity_test.go
@@ -82,9 +82,11 @@ 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
+ modelMapping map[string]string
+ switchAccount bool
+ switchAfterTurns int
+ disableCyber bool
}
type issue600Upstream struct {
@@ -211,6 +213,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"
}
@@ -218,7 +223,7 @@ func newIssue600NetworkHarness(t *testing.T, mode, namespace string, strict bool
if addr := os.Getenv("ISSUE600_REDIS_ADDR"); addr != "" {
gatewayCache = testutil.NewIsolatedRedisGatewayCache(t, addr)
}
- h := newOpenAIWSPassthroughHandlerHarnessWithCache(t, upstream.URL, headers, settings, gatewayCache, func(a *service.Account, cfg *config.Config, up *service.HTTPUpstream, repo *service.AccountRepository) {
+ h := newOpenAIWSPassthroughHandlerHarnessWithKey(t, upstream.URL, headers, settings, gatewayCache, func(key *service.APIKey) { key.ModelMapping = opts.modelMapping }, func(a *service.Account, cfg *config.Config, up *service.HTTPUpstream, repo *service.AccountRepository) {
a.Extra["codex_fingerprint_mode"] = "off"
a.Extra["openai_apikey_responses_websockets_v2_mode"] = mode
if namespace != "none" {
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/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/repository/moderation_upstream_scope_export_test.go b/backend/internal/repository/moderation_upstream_scope_export_test.go
new file mode 100644
index 000000000000..f2ae2654d262
--- /dev/null
+++ b/backend/internal/repository/moderation_upstream_scope_export_test.go
@@ -0,0 +1,15 @@
+//go:build integration
+
+package repository
+
+import (
+ "database/sql"
+ "testing"
+
+ "github.com/Wei-Shaw/sub2api/ent"
+)
+
+// Test-only bridge keeps real HTTP handlers out of repository's import graph.
+func ModerationScopeTestClient(t *testing.T) (*ent.Client, *sql.DB) {
+ return testEntClient(t), integrationDB
+}
diff --git a/backend/internal/repository/moderation_upstream_scope_integration_test.go b/backend/internal/repository/moderation_upstream_scope_integration_test.go
new file mode 100644
index 000000000000..4c19aa9a694d
--- /dev/null
+++ b/backend/internal/repository/moderation_upstream_scope_integration_test.go
@@ -0,0 +1,126 @@
+//go:build integration
+
+package repository_test
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/Wei-Shaw/sub2api/internal/config"
+ "github.com/Wei-Shaw/sub2api/internal/handler/admin"
+ "github.com/Wei-Shaw/sub2api/internal/pkg/pagination"
+ "github.com/Wei-Shaw/sub2api/internal/repository"
+ "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"
+)
+
+func TestModerationUpstreamPostgresAdminRoundTrip(t *testing.T) {
+ ctx := context.Background()
+ client, moderationDB := repository.ModerationScopeTestClient(t)
+ accounts := repository.NewAccountRepository(client, moderationDB, nil)
+ groups := repository.NewGroupRepository(client, moderationDB)
+ settings := repository.NewSettingRepository(client)
+ old, oldErr := settings.GetValue(ctx, service.SettingKeyContentModerationConfig)
+ t.Cleanup(func() {
+ if oldErr == nil {
+ _ = settings.Set(ctx, service.SettingKeyContentModerationConfig, old)
+ } else {
+ _ = settings.Delete(ctx, service.SettingKeyContentModerationConfig)
+ }
+ })
+ require.NoError(t, settings.Set(ctx, service.SettingKeyContentModerationConfig, `{"all_groups":true}`))
+ suffix := time.Now().UnixNano()
+ account := &service.Account{Name: fmt.Sprintf("moderation-scope-%d", suffix), Platform: service.PlatformOpenAI, Type: service.AccountTypeOAuth, Status: service.StatusActive, Schedulable: true, Credentials: map[string]any{}, Extra: map[string]any{}}
+ require.NoError(t, accounts.Create(ctx, account))
+ t.Cleanup(func() {
+ _, _ = moderationDB.ExecContext(ctx, `DELETE FROM scheduler_outbox WHERE account_id=$1`, account.ID)
+ _, _ = moderationDB.ExecContext(ctx, `DELETE FROM accounts WHERE id=$1`, account.ID)
+ })
+ group := &service.Group{Name: fmt.Sprintf("moderation-scope-group-%d", suffix), Platform: service.PlatformOpenAI, Status: service.StatusActive, SubscriptionType: service.SubscriptionTypeStandard, RateMultiplier: 1}
+ require.NoError(t, groups.Create(ctx, group))
+ t.Cleanup(func() { _, _ = moderationDB.ExecContext(ctx, `DELETE FROM groups WHERE id=$1`, group.ID) })
+ user, err := client.User.Create().SetEmail(fmt.Sprintf("moderation-scope-%d@example.invalid", suffix)).SetPasswordHash("synthetic-not-a-login").SetRole(service.RoleAdmin).SetStatus(service.StatusActive).Save(ctx)
+ require.NoError(t, err)
+ t.Cleanup(func() { _, _ = moderationDB.ExecContext(ctx, `DELETE FROM users WHERE id=$1`, user.ID) })
+ users := repository.NewUserRepository(client, moderationDB)
+ actor, err := users.GetByID(ctx, user.ID)
+ require.NoError(t, err)
+ auth := service.NewAuthService(nil, nil, nil, nil, &config.Config{JWT: config.JWTConfig{Secret: "synthetic-moderation-integration-secret", ExpireHour: 1}}, nil, nil, nil, nil, nil, nil, nil, nil)
+ token, err := auth.GenerateToken(ctx, actor)
+ require.NoError(t, err)
+ newRouter := func() *gin.Engine {
+ h := admin.NewContentModerationHandler(service.NewContentModerationService(settings, nil, nil, groups, nil, nil, nil, nil, accounts))
+ r := gin.New()
+ r.Use(gin.HandlerFunc(middleware.NewAdminAuthMiddleware(auth, service.NewUserService(users, nil, nil, nil), nil, nil)))
+ r.PUT("/api/v1/admin/risk-control/config", h.UpdateConfig)
+ r.GET("/api/v1/admin/risk-control/config", h.GetConfig)
+ return r
+ }
+ request := func(router *gin.Engine, method, body, bearer string) *httptest.ResponseRecorder {
+ r := httptest.NewRequest(method, "/api/v1/admin/risk-control/config", strings.NewReader(body))
+ r.Header.Set("Content-Type", "application/json")
+ if bearer != "" {
+ r.Header.Set("Authorization", "Bearer "+bearer)
+ }
+ w := httptest.NewRecorder()
+ router.ServeHTTP(w, r)
+ return w
+ }
+ body := fmt.Sprintf(`{"upstream_account_scope":"selected","upstream_account_ids":[%d]}`, account.ID)
+ w := request(newRouter(), http.MethodPut, body, "")
+ require.Equal(t, 401, w.Code)
+ w = request(newRouter(), http.MethodPut, body, token)
+ require.Equal(t, 200, w.Code, w.Body.String())
+ var stored service.ContentModerationConfig
+ raw, err := settings.GetValue(ctx, service.SettingKeyContentModerationConfig)
+ require.NoError(t, err)
+ require.NoError(t, json.Unmarshal([]byte(raw), &stored))
+ require.Equal(t, []int64{account.ID}, stored.UpstreamAccountIDs)
+ require.Equal(t, service.PlatformOpenAI, stored.UpstreamAccountBindings[account.ID].Platform)
+ w = request(newRouter(), http.MethodGet, "", token)
+ require.Equal(t, 200, w.Code)
+ 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{account.ID}, got.Data.UpstreamAccountIDs)
+ // Search #ID, name, type/group and pagination use the real current-site query.
+ matches, page, err := accounts.ListWithFilters(ctx, pagination.PaginationParams{Page: 1, PageSize: 1}, "openai", "oauth", "", fmt.Sprintf("#%d", account.ID), service.AccountListGroupUngrouped, "")
+ require.NoError(t, err)
+ require.Len(t, matches, 1)
+ require.Equal(t, account.ID, matches[0].ID)
+ require.EqualValues(t, 1, page.Total)
+ require.NoError(t, accounts.BindGroups(ctx, account.ID, []int64{group.ID}))
+ s := service.NewContentModerationService(settings, nil, nil, groups, nil, nil, nil, nil, accounts)
+ current, err := accounts.GetByID(ctx, account.ID)
+ require.NoError(t, err)
+ _, err = s.UpstreamModerationApplies(ctx, &stored, service.ContentModerationCheckInput{UpstreamAccount: current})
+ require.Error(t, err)
+ w = request(newRouter(), http.MethodPut, body, token)
+ require.Equal(t, 400, w.Code, w.Body.String())
+ // Rebinding requires a successful removal save, then a deliberate re-add.
+ w = request(newRouter(), http.MethodPut, `{"upstream_account_scope":"selected","upstream_account_ids":[]}`, token)
+ require.Equal(t, 200, w.Code, w.Body.String())
+ w = request(newRouter(), http.MethodPut, body, token)
+ require.Equal(t, 200, w.Code, w.Body.String())
+ raw, err = settings.GetValue(ctx, service.SettingKeyContentModerationConfig)
+ require.NoError(t, err)
+ require.NoError(t, json.Unmarshal([]byte(raw), &stored))
+ require.Equal(t, []int64{group.ID}, stored.UpstreamAccountBindings[account.ID].GroupIDs)
+ require.NoError(t, accounts.Delete(ctx, account.ID))
+ w = request(newRouter(), http.MethodPut, body, token)
+ require.Equal(t, 400, w.Code, w.Body.String())
+ w = request(newRouter(), http.MethodPut, `{"upstream_account_scope":"selected","upstream_account_ids":[]}`, token)
+ require.Equal(t, 200, w.Code, w.Body.String())
+ w = request(newRouter(), http.MethodPut, `{"upstream_account_scope":"all"}`, token)
+ require.Equal(t, 200, w.Code, w.Body.String())
+}
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/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.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..4b69ba683a74
--- /dev/null
+++ b/backend/internal/service/content_moderation_upstream_scope.go
@@ -0,0 +1,190 @@
+package service
+
+import (
+ "context"
+ "errors"
+ "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 ModerationUpstreamAccountEligible(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 == AccountTypeServiceAccount || 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, PlatformOpenCodeGo, PlatformCommandCode, PlatformCline, PlatformMistral:
+ return a.Type == AccountTypeAPIKey
+ default:
+ return false
+ }
+}
+
+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")
+ }
+ 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 || !ModerationUpstreamAccountEligible(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 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("Remove and save before reselecting 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 || !ModerationUpstreamAccountEligible(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
+}
+
+// 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
new file mode 100644
index 000000000000..c7b28dbbdda5
--- /dev/null
+++ b/backend/internal/service/content_moderation_upstream_scope_test.go
@@ -0,0 +1,103 @@
+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")
+ _, 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")
+ 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)
+}
+
+func TestModerationUpstreamEligibility(t *testing.T) {
+ for _, test := range []struct {
+ platform, kind string
+ allowed bool
+ }{
+ {PlatformAnthropic, AccountTypeServiceAccount, true}, {PlatformAnthropic, AccountTypeBedrock, true},
+ {PlatformOpenAI, AccountTypeOAuth, true}, {PlatformOpenAI, AccountTypeAPIKey, true},
+ {PlatformGemini, AccountTypeServiceAccount, true}, {PlatformGrok, AccountTypeOAuth, true},
+ {PlatformTypeSafe, AccountTypeAPIKey, true}, {PlatformOpenAI, "bps", false},
+ {PlatformTypeSafe, AccountTypeOAuth, false}, {"customer", AccountTypeAPIKey, false},
+ } {
+ require.Equal(t, test.allowed, ModerationUpstreamAccountEligible(&Account{ID: 1, Platform: test.platform, Type: test.kind}), "%s/%s", test.platform, test.kind)
+ }
+}
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/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/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/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/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/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
}
diff --git a/docs/implementation/moderation-upstream-account-scope.md b/docs/implementation/moderation-upstream-account-scope.md
new file mode 100644
index 000000000000..083279fa5474
--- /dev/null
+++ b/docs/implementation/moderation-upstream-account-scope.md
@@ -0,0 +1,31 @@
+# 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.
+
+
+## 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.
+
+
+The account catalog returns `moderation_scope_eligible` from the same backend predicate used by save validation (including Anthropic Vertex service accounts). The moderation wrapper uses that field for individual, page and bulk selection; unknown eligibility is disabled. Existing quality/account-ops callers retain their own selector contracts. A separate searchable selected-ID manager permits removal of a deleted/hidden ID without clearing valid selections. Failed discovery clears only visible rows; selected IDs remain stable. Pending saves lock edits and close/reopen until completion.
+
+WebSocket selected auditing uses the current client alias on each genuine turn, independent of the handshake's public-model context. Embedding string arrays and all batch prompts are included in the frozen content. Async image tasks retain the semantic policy status even when a whitespace keepalive already committed HTTP 200, so denial remains a failed task.
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..d812ffcfa62c
--- /dev/null
+++ b/frontend/src/components/admin/moderation/ModerationUpstreamAccountSelector.vue
@@ -0,0 +1,101 @@
+
+
+
+
+
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..bfe0d715463a
--- /dev/null
+++ b/frontend/src/components/admin/moderation/__tests__/ModerationUpstreamAccountSelector.spec.ts
@@ -0,0 +1,97 @@
+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', moderation_scope_eligible: true })
+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()
+ })
+ it('uses server eligibility for rows and every batch page, and removes hidden IDs individually', async () => {
+ list.mockResolvedValue(response([1, 2]))
+ const wrapper = mountPicker(); await flushPromises()
+ list.mockResolvedValue({ ...response([1, 2]), items: [row(1), { ...row(2), moderation_scope_eligible: false }] })
+ await wrapper.get('#moderation-upstream-search').setValue('mixed'); await flushPromises()
+ expect((wrapper.get('[data-account-id="2"] input').element as HTMLInputElement).disabled).toBe(true)
+ await wrapper.get('[data-testid="quality-select-page"]').trigger('click')
+ expect(wrapper.vm.ids).toEqual([999, 1])
+ list.mockResolvedValueOnce({ ...response([2, 3], 1, 2), items: [{ ...row(2), moderation_scope_eligible: false }, row(3)] }).mockResolvedValueOnce(response([4], 2, 2))
+ await wrapper.get('[data-testid="quality-select-all"]').trigger('click'); await flushPromises()
+ expect(wrapper.vm.ids).toEqual([999, 1, 3, 4])
+ await wrapper.get('[data-testid="moderation-selected-search"]').setValue('#999')
+ await wrapper.get('[data-testid="moderation-remove-999"]').trigger('click')
+ expect(wrapper.vm.ids).toEqual([1, 3, 4])
+ wrapper.unmount()
+ })
+ it('invalidates discovery rows on failed filtering, retries, and fences batch filter/unmount races', async () => {
+ list.mockResolvedValue(response([1]))
+ const wrapper = mountPicker(); await flushPromises()
+ list.mockRejectedValueOnce(new Error('offline fixture'))
+ await wrapper.get('#moderation-upstream-search').setValue('new filter'); await flushPromises()
+ expect(wrapper.find('[data-account-id]').exists()).toBe(false)
+ expect((wrapper.get('[data-testid="quality-select-page"]').element as HTMLButtonElement).disabled).toBe(true)
+ expect(wrapper.vm.ids).toEqual([999])
+ list.mockResolvedValue(response([3]))
+ await wrapper.get('#moderation-upstream-search').trigger('keydown', { key: 'Enter' }); await flushPromises()
+ expect(wrapper.find('[data-account-id="3"]').exists()).toBe(true)
+ let release!: (value: ReturnType) => void
+ list.mockImplementationOnce(() => new Promise(resolve => { release = resolve }))
+ await wrapper.get('[data-testid="quality-select-all"]').trigger('click')
+ list.mockResolvedValue(response([4]))
+ await wrapper.get('#moderation-upstream-search').setValue('changed during batch'); await flushPromises()
+ release(response([55], 1, 1)); await flushPromises()
+ expect(wrapper.vm.ids).toEqual([999])
+ list.mockImplementationOnce(() => new Promise(resolve => { release = resolve }))
+ await wrapper.get('[data-testid="quality-select-all"]').trigger('click')
+ const vm = wrapper.vm
+ wrapper.unmount(); release(response([66], 1, 1)); await flushPromises()
+ expect(vm.ids).toEqual([999])
+ })
+
+})
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/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..385ea8010b8a 100644
--- a/frontend/src/i18n/locales/en/admin/channels.ts
+++ b/frontend/src/i18n/locales/en/admin/channels.ts
@@ -494,6 +494,21 @@ export default {
allGroups: 'All Groups',
allGroupsHint: 'Auditing all groups',
selectedGroupsHint: 'Auditing selected groups',
+ manageSelectedUpstream: "Manage selected IDs ({count})",
+ findSelectedUpstream: "Find a selected ID, including deleted accounts",
+ selectedUpstreamRecoveryHint: "Showing up to 50 selected IDs. Find an exact ID to remove it without changing other selections.",
+ ineligibleUpstreamAccount: "This platform/type is not supported for moderation scope.",
+ 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; 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",
+ 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..035fe3c6baca 100644
--- a/frontend/src/i18n/locales/zh/admin/channels.ts
+++ b/frontend/src/i18n/locales/zh/admin/channels.ts
@@ -494,6 +494,21 @@ export default {
allGroups: '全部分组',
allGroupsHint: '当前审计全部分组',
selectedGroupsHint: '当前审计指定分组',
+ manageSelectedUpstream: "管理已选 ID({count})",
+ findSelectedUpstream: "查找已选 ID(含已删除账号)",
+ selectedUpstreamRecoveryHint: "最多显示 50 个已选 ID。输入完整 ID 可单独移除,不改变其他选择。",
+ ineligibleUpstreamAccount: "此平台与类型组合不支持上游审计范围。",
+ 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/types/index.ts b/frontend/src/types/index.ts
index dd8dd7bedf4b..e5843f14aa1e 100644
--- a/frontend/src/types/index.ts
+++ b/frontend/src/types/index.ts
@@ -1423,6 +1423,7 @@ export interface GrokModelDiagnostics {
}
export interface Account {
+ moderation_scope_eligible?: boolean
upstream_channel_binding?: import('@/api/admin/upstreamChannels').ChannelBinding
excel_bps_credential_state?: ExcelBPSCredentialState
id: number
diff --git a/frontend/src/views/admin/RiskControlView.vue b/frontend/src/views/admin/RiskControlView.vue
index 1182b4cd9201..559020b430f7 100644
--- a/frontend/src/views/admin/RiskControlView.vue
+++ b/frontend/src/views/admin/RiskControlView.vue
@@ -397,8 +397,8 @@
-
-
+
+
+
-
-