{{ t('tokenGuardV2.ruleScopeHint') }}
diff --git a/.github/scripts/token-guard-v2-browser.mjs b/.github/scripts/token-guard-v2-browser.mjs new file mode 100644 index 000000000000..dd6b88604e47 --- /dev/null +++ b/.github/scripts/token-guard-v2-browser.mjs @@ -0,0 +1,189 @@ +// CI only: render the actual before/after Vue page and project CSS with offline APIs. +import assert from 'node:assert/strict' +import { execFileSync } from 'node:child_process' +import { createHash } from 'node:crypto' +import fs from 'node:fs/promises' +import { createRequire } from 'node:module' +import path from 'node:path' +import { pathToFileURL } from 'node:url' + +const root = process.cwd(), frontend = path.join(root, 'frontend') +const out = process.env.TOKEN_GUARD_SCREENSHOT_DIR +assert(process.env.CI && out, 'This browser fixture runs only in remote CI') +await fs.mkdir(out, { recursive: true }) +const head = execFileSync('git', ['rev-parse', 'HEAD'], { encoding: 'utf8' }).trim() +assert.equal(head, process.env.TOKEN_GUARD_EXPECTED_HEAD) +const baseline = 'dc1e1b072faa53ec2e6f0925be39d5d024ec1687' +const component = 'frontend/src/views/admin/ops/TokenGuardV2View.vue' +const baselineBytes = execFileSync('git', ['show', `${baseline}:${component}`]) +const baselinePath = path.join(out, 'BaselineTokenGuardV2View.vue') +await fs.writeFile(baselinePath, baselineBytes) +assert.deepEqual(await fs.readFile(baselinePath), execFileSync('git', ['show', `${baseline}:${component}`])) + +const requireFrontend = createRequire(path.join(frontend, 'package.json')) +const { createServer } = requireFrontend('vite') +const vueModule = requireFrontend('@vitejs/plugin-vue'), vue = vueModule.default || vueModule +const tailwind = requireFrontend('tailwindcss'), autoprefixer = requireFrontend('autoprefixer') +const { default: theme } = await import(pathToFileURL(path.join(frontend, 'tailwind.config.js'))) +const requireBrowser = createRequire(path.join(process.env.PLAYWRIGHT_ROOT, 'package.json')) +const { chromium } = requireBrowser('playwright') +const fixture = path.join(frontend, '.token-guard-v2-fixture') +await fs.mkdir(fixture, { recursive: true }) +const modules = { + layout: `import {h} from 'vue';export default {setup(_,{slots}){return()=>h('main',{class:'mx-auto max-w-7xl p-4 sm:p-6'},slots.default?.())}}`, + nav: `import {h} from 'vue';export default {setup(){return()=>h('nav',{class:'text-sm text-gray-500'},'Offline UI fixture · Synthetic accounts only')}}`, + auth: `import {reactive} from 'vue';const auth=reactive({user:{id:1,role:'admin'}});export const useAuthStore=()=>auth;`, + client: `async function request(method,url,data,options){const query=new URLSearchParams(options?.params??{});const response=await fetch('/fixture'+url+(query.size?'?'+query:''),{method,headers:{'Content-Type':'application/json'},body:data?JSON.stringify(data):undefined});if(!response.ok)throw Error('offline fixture '+response.status);return {data:await response.json()}}export const apiClient=Object.fromEntries(['get','post','put','patch','delete'].map(method=>[method,(url,data)=>method==='get'?request('GET',url,null,data):request(method.toUpperCase(),url,data)]));export const buildApiUrl=url=>'/fixture'+url;export const buildGatewayUrl=url=>'http://127.0.0.1:4187/fixture'+url;export default apiClient;`, +} +for (const [name, source] of Object.entries(modules)) await fs.writeFile(path.join(fixture, name + '.js'), source) +const entry = path.join(fixture, 'index.html') +await fs.writeFile(entry, `
`) +const server = await createServer({ root: frontend, configFile: false, plugins: [vue()], + resolve: { alias: [ + { find: '../client', replacement: path.join(fixture, 'client.js') }, + { find: '@/api/client', replacement: path.join(fixture, 'client.js') }, + { find: '@/stores/auth', replacement: path.join(fixture, 'auth.js') }, + { find: '@/components/layout/AppLayout.vue', replacement: path.join(fixture, 'layout.js') }, + { find: '@/components/admin/operations/SmartOpsNav.vue', replacement: path.join(fixture, 'nav.js') }, + { find: '@', replacement: path.join(frontend, 'src') }, + ] }, + css: { postcss: { plugins: [tailwind({ ...theme, content: [path.join(frontend, 'src/**/*.{vue,js,ts,jsx,tsx}'), baselinePath, path.join(root, '.github/scripts/token-guard-v2-browser.mjs')] }), autoprefixer()] } }, + define: { __INTLIFY_JIT_COMPILATION__: true }, + server: { host: '127.0.0.1', port: 4187, strictPort: true, fs: { allow: [root, out] } }, + optimizeDeps: { entries: [entry], include: ['vue', 'vue-i18n', 'pinia'] }, +}) + +const now = '2026-11-08T10:00:00Z' +const task = (accountID, status) => ({ id: accountID + 100, account_id: accountID, status, stage: status, attempt: 1, created_at: now, updated_at: now, ...(status === 'succeeded' ? { finished_at: now } : {}) }) +function account(id, extra = {}) { + return { account_id: id, account_name: `Synthetic parent ${id}`, account_status: 'active', schedulable: true, enabled: true, auto_relogin_enabled: true, + probe_state: 'auth', probe_detail: 'credential rejected', fail_streak: 1, last_probe_at: '2026-11-08T09:00:00Z', next_probe_at: now, + login_config: { account_id: id, login_email: `demo${id}@example.test`, credential_mode: 'password_totp', engine: 'local_worker', proxy_source: 'account', password_configured: true, totp_configured: true, configured: true }, + probe_failure: { code: 'requires_relogin', category: 'requires_relogin', stage: 'inspection', action: 'reauthorize' }, ...extra } +} +const initial = () => [account(42), account(43, { latest_task: task(43, 'queued') }), account(44, { latest_task: task(44, 'running') }), + account(45, { cooldown_until: '2099-11-08T10:00:00Z' }), account(46, { auto_relogin_exhausted: true, relogin_fail_streak: 3 }), + account(47, { latest_task: task(47, 'succeeded') }), account(48, { blocked_reason: 'automatic re-login could not be queued' })] +const requests = [], errors = [], shots = [], checks = [] +let rows = initial(), holdNextRead = null +const status = () => ({ accounts: structuredClone(rows), runtime_settings: { engine: 'local_worker', worker_concurrency: 3 }, worker: { state: 'running', mode: 'managed' }, + probe_interval_seconds: 1800, retry_interval_seconds: 300, relogin_cooldown_seconds: 1800, fail_streak_threshold: 2, relogin_backoff_max_seconds: 86400, relogin_max_failures: 3 }) +const guardPath = '/admin/account-ops/token-guard-v2/accounts' +const guardReads = () => requests.filter(r => r.pathname === guardPath && r.method === 'GET').length +function deferRead() { + let started, release + const began = new Promise(resolve => { started = resolve }) + const promise = new Promise(resolve => { release = resolve }) + holdNextRead = { started, promise } + return { began, release } +} +await server.listen() +const browser = await chromium.launch({ headless: true }) +async function newPage(viewport = { width: 1440, height: 1100 }) { + const page = await browser.newPage({ viewport }) + page.setDefaultTimeout(30000) + page.on('pageerror', error => errors.push(error.message)) + page.on('console', message => { if (message.type() === 'error') errors.push(message.text()) }) + await page.route('**/*', route => { + if (new URL(route.request().url()).origin === 'http://127.0.0.1:4187') return route.continue() + errors.push('External request blocked') + return route.abort() + }) + await page.route('**/fixture/**', async route => { + const pathname = new URL(route.request().url()).pathname.replace('/fixture', '') + const method = route.request().method() + requests.push({ pathname, method }) + let body + if (pathname === guardPath && method === 'GET') { + body = status() + if (holdNextRead) { const hold = holdNextRead; holdNextRead = null; hold.started(); await hold.promise } + } else if (pathname.endsWith('/42/probe') && method === 'POST') { + rows[0] = account(42, { probe_state: 'ok', probe_detail: 'credential accepted', fail_streak: 0, last_probe_at: '2026-11-08T10:01:00Z', probe_failure: undefined }) + body = rows[0] + } else if (pathname.endsWith('/42/relogin') && method === 'POST') { + rows[0] = account(42, { latest_task: task(42, 'queued') }); body = rows[0].latest_task + } else if (pathname.endsWith('/encryption')) body = { configured: true, source: 'server_config' } + else if (pathname === '/admin/accounts') body = { items: rows.map(a => ({ id: a.account_id, name: a.account_name, platform: 'openai', type: 'oauth', group_ids: [1] })), total: rows.length, page: 1, page_size: 200 } + else if (pathname === '/admin/groups/all') body = [{ id: 1, name: 'Synthetic group' }] + else if (pathname === '/admin/proxies/all') body = [] + else throw Error(`Unexpected offline API ${method} ${pathname}`) + await route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(body) }) + }) + return page +} +const url = 'http://127.0.0.1:4187/.token-guard-v2-fixture/index.html' +const targetRow = page => page.locator('tbody tr').filter({ hasText: 'Synthetic parent 42' }) +async function screenshot(page, name, source = head) { + await page.evaluate(() => document.fonts.ready) + await page.screenshot({ path: path.join(out, name), fullPage: true }) + shots.push({ name, source, viewport: page.viewportSize(), synthetic: true }) +} +try { + const before = await newPage() + await before.goto(url + '?baseline=1', { waitUntil: 'networkidle' }) + await targetRow(before).waitFor() + await screenshot(before, 'before-desktop.png', baseline) + const oldReads = guardReads() + await targetRow(before).getByRole('button', { name: '立即巡检', exact: true }).click() + await before.getByText('已完成 Synthetic parent 42 的即时巡检', { exact: true }).waitFor() + assert.equal(guardReads(), oldReads, 'Pinned baseline RED: action read is blocked by busyId') + assert.match(await targetRow(before).locator('td').nth(4).innerText(), /鉴权失败/) + checks.push({ name: 'baseline-action-read-blocked', pass: true, reads: oldReads, readsAfter: guardReads() }) + await screenshot(before, 'before-stale-after-inspection.png', baseline) + await before.close() + + rows = initial() + const page = await newPage() + await page.goto(url, { waitUntil: 'networkidle' }) + await page.getByTestId('automation-state-42').waitFor() + for (const [id, text] of [[42, '鉴权失败确认'], [43, '重登任务已排队'], [44, '正在重登'], [45, '自动重登冷却'], [46, '自动重登预算已耗尽'], [47, '新凭据已保存'], [48, '自动恢复暂不可用']]) { + assert((await page.getByTestId(`automation-state-${id}`).innerText()).includes(text)) + } + assert.equal(await page.getByTestId('probe-history-43').getAttribute('open'), null) + await screenshot(page, 'after-desktop-stages.png') + const held = deferRead(), readsBefore = guardReads() + await targetRow(page).getByRole('button', { name: '立即巡检', exact: true }).click() + await held.began + assert.equal(guardReads(), readsBefore + 1, 'Action triggers an immediate actual API read') + assert(await targetRow(page).getByRole('button', { name: '立即巡检', exact: true }).isDisabled(), 'Duplicate action remains blocked during readback') + await screenshot(page, 'after-inspection-readback-pending.png') + held.release() + await page.waitForFunction(() => document.querySelector('[data-testid="automation-state-42"]')?.textContent === '最近巡检鉴权通过') + assert.equal(await targetRow(page).getByRole('button', { name: '立即巡检', exact: true }).isDisabled(), false) + await screenshot(page, 'after-inspection-fresh-read.png') + checks.push({ name: 'immediate-readback-and-duplicate-action-block', pass: true, readsBefore, readsAfter: guardReads() }) + + // An older refresh may finish after the action's queued-state read. + const oldRead = deferRead() + await page.getByRole('button', { name: '刷新', exact: true }).click(); await oldRead.began + await targetRow(page).getByRole('button', { name: '立即重登', exact: true }).click() + await page.waitForFunction(() => document.querySelector('[data-testid="automation-state-42"]')?.textContent === '重登任务已排队') + oldRead.release() + await page.waitForLoadState('networkidle') + assert.equal(await page.getByTestId('automation-state-42').innerText(), '重登任务已排队', 'Old refresh must not overwrite the queued action read') + checks.push({ name: 'older-refresh-cannot-overwrite-queued-readback', pass: true }) + await screenshot(page, 'after-relogin-queued.png') + await page.setViewportSize({ width: 390, height: 844 }) + await page.getByTestId('automation-state-42').scrollIntoViewIfNeeded() + await screenshot(page, 'after-mobile-queued.png') + checks.push({ name: 'mobile-real-table', viewport: page.viewportSize(), horizontalTableScroll: await page.locator('.table-wrap').evaluate(el => el.scrollWidth > el.clientWidth) }) + await page.setViewportSize({ width: 1440, height: 1100 }) + await page.evaluate(() => document.documentElement.classList.add('dark')) + await screenshot(page, 'after-desktop-dark.png') + assert.deepEqual(errors, []) + await fs.writeFile(path.join(out, 'verification.json'), JSON.stringify({ head, baseline, baselineSha256: createHash('sha256').update(baselineBytes).digest('hex'), source: `https://github.com/ranxi2001/sub2api/actions/runs/${process.env.GITHUB_RUN_ID}`, actualComponents: ['TokenGuardV2View', 'CredentialEncryptionSetup', 'CredentialOperationFailure', 'Pagination'], mocks: ['HTTP APIs', 'auth', 'layout', 'navigation'], synthetic: true, productionCalls: 0, paidCalls: 0, shots, checks, requests, errors }, null, 2)) +} catch (error) { + for (const [index, page] of browser.contexts().flatMap(context => context.pages()).entries()) { + await page.screenshot({ path: path.join(out, `failure-${index}.png`), fullPage: true }).catch(() => {}) + await fs.writeFile(path.join(out, `failure-${index}.txt`), await page.locator('body').innerText()).catch(() => {}) + } + await fs.writeFile(path.join(out, 'failure.json'), JSON.stringify({ head, message: String(error), errors, requests, checks }, null, 2)) + throw error +} finally { + await browser.close(); await server.close(); await fs.rm(fixture, { recursive: true, force: true }) +} diff --git a/.github/workflows/token-guard-v2-scheduler.yml b/.github/workflows/token-guard-v2-scheduler.yml new file mode 100644 index 000000000000..6c6de036df22 --- /dev/null +++ b/.github/workflows/token-guard-v2-scheduler.yml @@ -0,0 +1,87 @@ +name: Credential patrol scheduling + +on: + pull_request: + paths: + - 'backend/internal/service/account_token_guard_v2*.go' + - 'backend/internal/repository/account_token_guard_v2*.go' + - 'backend/internal/service/openai_codex_models_service*.go' + - 'backend/internal/service/openai_credential_probe*.go' + - 'frontend/src/views/admin/ops/TokenGuardV2View.vue' + - 'frontend/src/views/admin/ops/__tests__/TokenGuardV2View.spec.ts' + - '.github/scripts/token-guard-v2-browser.mjs' + - '.github/workflows/token-guard-v2-scheduler.yml' + +permissions: + contents: read + +jobs: + scheduler: + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - uses: actions/checkout@v6 + with: + ref: ${{ github.event.pull_request.head.sha }} + - uses: actions/setup-go@v6 + with: + go-version-file: backend/go.mod + cache-dependency-path: backend/go.sum + - name: Scheduling, cancellation and retained re-login budget under race detector + shell: bash + run: | + set -euo pipefail + mkdir -p test-evidence + git rev-parse HEAD > test-evidence/head.txt + (cd backend && go test -race -tags=unit ./internal/service -run '^Test(AccountTokenGuardV2|ReloginBudget|ExhaustedRelogin|RestoredBudget)' -count=1 -v -timeout=10m) 2>&1 | tee test-evidence/scheduler.log + - name: PostgreSQL cutoff, lease fencing and budget persistence + shell: bash + env: + CI: 'true' + run: | + set -euo pipefail + (cd backend && go test -tags=integration ./internal/repository -run '^Test(AccountTokenGuardV2|ReloginBudget)' -count=1 -v -timeout=15m) 2>&1 | tee test-evidence/storage.log + if grep -Eq -- '--- SKIP:|no tests to run' test-evidence/storage.log; then exit 1; fi + - uses: actions/upload-artifact@v7 + if: always() + with: + name: credential-patrol-${{ github.event.pull_request.head.sha }} + path: test-evidence/ + if-no-files-found: error + + browser: + name: Actual credential operations UI / synthetic APIs + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - uses: actions/checkout@v6 + with: + ref: ${{ github.event.pull_request.head.sha }} + 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: Install isolated browser for CI only + run: | + npm install --prefix "$RUNNER_TEMP/token-guard-browser" --no-save --ignore-scripts playwright@1.56.1 + "$RUNNER_TEMP/token-guard-browser/node_modules/.bin/playwright" install --with-deps chromium + sudo apt-get install -y fonts-noto-cjk + - name: Real page before and after, readback and desktop/mobile screenshots + env: + CI: 'true' + TOKEN_GUARD_EXPECTED_HEAD: ${{ github.event.pull_request.head.sha }} + PLAYWRIGHT_ROOT: ${{ runner.temp }}/token-guard-browser/node_modules/playwright + TOKEN_GUARD_SCREENSHOT_DIR: ${{ runner.temp }}/token-guard-screenshots + run: node .github/scripts/token-guard-v2-browser.mjs + - uses: actions/upload-artifact@v7 + if: always() + with: + name: credential-patrol-ui-${{ github.event.pull_request.head.sha }} + path: ${{ runner.temp }}/token-guard-screenshots + if-no-files-found: error diff --git a/backend/internal/integration/credentialops/credential_operation_errors_test.go b/backend/internal/integration/credentialops/credential_operation_errors_test.go index 3faff164eaf3..e25682709128 100644 --- a/backend/internal/integration/credentialops/credential_operation_errors_test.go +++ b/backend/internal/integration/credentialops/credential_operation_errors_test.go @@ -41,7 +41,7 @@ func (credentialSeamEncryptor) Decrypt(value string) (string, error) { return va type credentialSeamProber struct{} -func (credentialSeamProber) FetchOpenAIModelsList(context.Context, *service.Account) (*service.OpenAIModelsResponse, error) { +func (credentialSeamProber) FetchOpenAIModelsListFresh(context.Context, *service.Account) (*service.OpenAIModelsResponse, error) { return nil, errors.New("account_retired") } diff --git a/backend/internal/repository/account_token_guard_v2.go b/backend/internal/repository/account_token_guard_v2.go index 2375b69268bf..44b91c4623c8 100644 --- a/backend/internal/repository/account_token_guard_v2.go +++ b/backend/internal/repository/account_token_guard_v2.go @@ -95,7 +95,7 @@ func (r *accountTokenGuardV2Repository) ListAccounts(ctx context.Context) ([]ser return result, rows.Err() } -func (r *accountTokenGuardV2Repository) ClaimDue(ctx context.Context, owner string, leaseDuration time.Duration, limit int) ([]service.AccountTokenGuardV2Record, error) { +func (r *accountTokenGuardV2Repository) ClaimDue(ctx context.Context, owner string, leaseDuration time.Duration, limit int, dueBefore time.Time) ([]service.AccountTokenGuardV2Record, error) { if limit <= 0 { limit = 10 } @@ -105,6 +105,7 @@ func (r *accountTokenGuardV2Repository) ClaimDue(ctx context.Context, owner stri FROM account_token_guard_v2_accounts WHERE enabled = TRUE AND next_probe_at <= NOW() + AND next_probe_at <= $4 AND (lease_until IS NULL OR lease_until < NOW()) ORDER BY next_probe_at ASC, account_id ASC LIMIT $1 @@ -122,7 +123,7 @@ func (r *accountTokenGuardV2Repository) ClaimDue(ctx context.Context, owner stri guard.cooldown_until, guard.blocked_reason, COALESCE(guard.lease_owner, ''), guard.lease_until, guard.created_at, guard.updated_at, guard.refresh_failure_code, guard.last_refresh_failure_at - `, limit, owner, int64(leaseDuration.Seconds())) + `, limit, owner, int64(leaseDuration.Seconds()), dueBefore) if err != nil { return nil, err } @@ -171,7 +172,7 @@ func (r *accountTokenGuardV2Repository) CompleteProbe(ctx context.Context, accou lease_owner = NULL, lease_until = NULL, updated_at = NOW() - WHERE account_id = $1 AND lease_owner = $2 + WHERE account_id = $1 AND lease_owner = $2 AND lease_until > NOW() `, accountID, owner, result.ProbeState, result.ProbeDetail, result.FailStreak, result.LastProbeAt, result.LastReauthAt, result.NextProbeAt, result.CooldownUntil, result.BlockedReason) @@ -188,6 +189,16 @@ func (r *accountTokenGuardV2Repository) CompleteProbe(ctx context.Context, accou return nil } +// ReleaseProbe abandons a claim without advancing its schedule or inspection +// history. Each claim has its own owner token, so a late release cannot clear a +// replacement claim after this lease expires. +func (r *accountTokenGuardV2Repository) ReleaseProbe(ctx context.Context, accountID int64, owner string) error { + _, err := r.db.ExecContext(ctx, `UPDATE account_token_guard_v2_accounts + SET lease_owner = NULL, lease_until = NULL, updated_at = NOW() + WHERE account_id = $1 AND lease_owner = $2`, accountID, owner) + return err +} + func (r *accountTokenGuardV2Repository) MarkReauthRequested(ctx context.Context, accountID int64, requestedAt, cooldownUntil time.Time) error { _, err := r.db.ExecContext(ctx, ` UPDATE account_token_guard_v2_accounts diff --git a/backend/internal/repository/account_token_guard_v2_integration_test.go b/backend/internal/repository/account_token_guard_v2_integration_test.go index adbaa2d8fafd..3bc65c76790b 100644 --- a/backend/internal/repository/account_token_guard_v2_integration_test.go +++ b/backend/internal/repository/account_token_guard_v2_integration_test.go @@ -26,11 +26,11 @@ func TestAccountTokenGuardV2RepositoryLeasesAndReauth(t *testing.T) { }) guard := NewAccountTokenGuardV2Repository(integrationDB) require.NoError(t, guard.UpsertAccount(ctx, account.ID, false, false)) - claimed, err := guard.ClaimDue(ctx, "instance-a", time.Minute, 10) + claimed, err := guard.ClaimDue(ctx, "instance-a", time.Minute, 10, time.Now()) require.NoError(t, err) require.Empty(t, claimed, "paused accounts must not be scheduled") require.NoError(t, guard.UpsertAccount(ctx, account.ID, true, true)) - claimed, err = guard.ClaimDue(ctx, "instance-a", time.Minute, 10) + claimed, err = guard.ClaimDue(ctx, "instance-a", time.Minute, 10, time.Now()) require.NoError(t, err) require.Len(t, claimed, 1) other, err := guard.ClaimAccount(ctx, account.ID, "instance-b", time.Minute) @@ -47,11 +47,11 @@ func TestAccountTokenGuardV2RepositoryLeasesAndReauth(t *testing.T) { require.Empty(t, stored.LeaseOwner) require.Nil(t, stored.LeaseUntil) require.Equal(t, service.AccountTokenGuardV2ProbeOK, stored.ProbeState) - claimed, err = guard.ClaimDue(ctx, "instance-b", time.Minute, 10) + claimed, err = guard.ClaimDue(ctx, "instance-b", time.Minute, 10, time.Now()) require.NoError(t, err) require.Empty(t, claimed) require.NoError(t, guard.RescheduleEnabled(ctx)) - claimed, err = guard.ClaimDue(ctx, "instance-b", time.Minute, 10) + claimed, err = guard.ClaimDue(ctx, "instance-b", time.Minute, 10, time.Now()) require.NoError(t, err) require.Len(t, claimed, 1) _, err = integrationDB.ExecContext(ctx, `UPDATE account_token_guard_v2_accounts SET lease_until = NOW() - INTERVAL '1 second' WHERE account_id = $1`, account.ID) diff --git a/backend/internal/repository/account_token_guard_v2_scheduler_integration_test.go b/backend/internal/repository/account_token_guard_v2_scheduler_integration_test.go new file mode 100644 index 000000000000..45a272789c15 --- /dev/null +++ b/backend/internal/repository/account_token_guard_v2_scheduler_integration_test.go @@ -0,0 +1,195 @@ +//go:build integration + +package repository + +import ( + "context" + "database/sql" + "fmt" + "sync" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/stretchr/testify/require" +) + +func newGuardSchedulerAccount(t *testing.T, nextProbe time.Time, enabled bool) int64 { + t.Helper() + account := mustCreateAccount(t, testEntClient(t), &service.Account{ + Name: "credential-guard-scheduler", Platform: service.PlatformOpenAI, Type: service.AccountTypeOAuth, + Credentials: map[string]any{"access_token": "synthetic"}, + }) + t.Cleanup(func() { + _, err := integrationDB.ExecContext(context.Background(), `DELETE FROM accounts WHERE id=$1`, account.ID) + require.NoError(t, err) + }) + guard := NewAccountTokenGuardV2Repository(integrationDB) + require.NoError(t, guard.UpsertAccount(context.Background(), account.ID, enabled, true)) + _, err := integrationDB.ExecContext(context.Background(), `UPDATE account_token_guard_v2_accounts SET next_probe_at=$2 WHERE account_id=$1`, account.ID, nextProbe) + require.NoError(t, err) + return account.ID +} + +func guardSchedulerDatabaseNow(t *testing.T) time.Time { + t.Helper() + var now time.Time + require.NoError(t, integrationDB.QueryRow(`SELECT clock_timestamp()`).Scan(&now)) + return now +} + +func TestAccountTokenGuardV2ClaimDueHonorsCycleCutoffAndDatabaseTime(t *testing.T) { + ctx := context.Background() + now := guardSchedulerDatabaseNow(t) + cutoff := now.Add(-time.Minute) + oldID := newGuardSchedulerAccount(t, cutoff.Add(-time.Second), true) + newID := newGuardSchedulerAccount(t, cutoff.Add(30*time.Second), true) + futureID := newGuardSchedulerAccount(t, now.Add(2*time.Hour), true) + newGuardSchedulerAccount(t, cutoff.Add(-time.Second), false) + guard := NewAccountTokenGuardV2Repository(integrationDB) + + claimed, err := guard.ClaimDue(ctx, "cutoff-old", time.Minute, 10, cutoff) + require.NoError(t, err) + require.Len(t, claimed, 1, "accounts becoming due after this cycle started wait for the next cycle") + require.Equal(t, oldID, claimed[0].AccountID) + require.NoError(t, guard.ReleaseProbe(ctx, oldID, "cutoff-old")) + + // Even a future caller cutoff cannot turn the repository into a claimant + // for accounts that have not reached their actual scheduled time. + claimed, err = guard.ClaimDue(ctx, "cutoff-future", time.Minute, 10, now.Add(3*time.Hour)) + require.NoError(t, err) + var ids []int64 + for _, record := range claimed { + ids = append(ids, record.AccountID) + } + require.ElementsMatch(t, []int64{oldID, newID}, ids) + record, err := guard.GetAccount(ctx, futureID) + require.NoError(t, err) + require.Empty(t, record.LeaseOwner) +} + +func TestAccountTokenGuardV2ExpiredClaimCannotCompleteOrReleaseReplacement(t *testing.T) { + ctx := context.Background() + now := guardSchedulerDatabaseNow(t) + id := newGuardSchedulerAccount(t, now.Add(-time.Minute), true) + guard := NewAccountTokenGuardV2Repository(integrationDB) + _, err := integrationDB.ExecContext(ctx, `UPDATE account_token_guard_v2_accounts + SET probe_state='auth', probe_detail='credential was rejected', fail_streak=7, + last_probe_at=$2, blocked_reason='automatic re-login cooling down' + WHERE account_id=$1`, id, now.Add(-2*time.Minute)) + require.NoError(t, err) + before, err := guard.GetAccount(ctx, id) + require.NoError(t, err) + oldClaim, err := guard.ClaimAccount(ctx, id, "claim-old", time.Minute) + require.NoError(t, err) + require.NotNil(t, oldClaim) + _, err = integrationDB.ExecContext(ctx, `UPDATE account_token_guard_v2_accounts + SET lease_until=NOW()-INTERVAL '1 second' WHERE account_id=$1`, id) + require.NoError(t, err) + completion := service.AccountTokenGuardV2ProbeCompletion{ + ProbeState: service.AccountTokenGuardV2ProbeOK, LastProbeAt: now, NextProbeAt: now.Add(time.Hour), + } + require.ErrorIs(t, guard.CompleteProbe(ctx, id, "claim-old", completion), sql.ErrNoRows, + "a stale result must be rejected even before a replacement is claimed") + + newClaim, err := guard.ClaimAccount(ctx, id, "claim-new", time.Minute) + require.NoError(t, err) + require.NotNil(t, newClaim) + require.ErrorIs(t, guard.CompleteProbe(ctx, id, "claim-old", completion), sql.ErrNoRows) + require.NoError(t, guard.ReleaseProbe(ctx, id, "claim-old"), "a late release is harmless and idempotent") + stored, err := guard.GetAccount(ctx, id) + require.NoError(t, err) + require.Equal(t, "claim-new", stored.LeaseOwner) + require.Equal(t, newClaim.LeaseUntil, stored.LeaseUntil) + + canceled, cancel := context.WithCancel(ctx) + cancel() + require.ErrorIs(t, guard.ReleaseProbe(canceled, id, "claim-new"), context.Canceled) + require.NoError(t, guard.ReleaseProbe(context.WithoutCancel(canceled), id, "claim-new"), + "cleanup must remain possible after the cycle is canceled") + require.NoError(t, guard.ReleaseProbe(ctx, id, "claim-new"), "repeated cleanup is harmless") + stored, err = guard.GetAccount(ctx, id) + require.NoError(t, err) + require.Empty(t, stored.LeaseOwner) + require.Nil(t, stored.LeaseUntil) + require.Equal(t, before.ProbeState, stored.ProbeState) + require.Equal(t, before.ProbeDetail, stored.ProbeDetail) + require.Equal(t, before.FailStreak, stored.FailStreak) + require.Equal(t, before.LastProbeAt, stored.LastProbeAt) + require.Equal(t, before.NextProbeAt, stored.NextProbeAt) + require.Equal(t, before.BlockedReason, stored.BlockedReason) + claimed, err := guard.ClaimDue(ctx, "claim-retry", time.Minute, 1, now) + require.NoError(t, err) + require.Len(t, claimed, 1, "release does not postpone the unfinished inspection") + require.Equal(t, id, claimed[0].AccountID) +} + +func TestAccountTokenGuardV2ConcurrentClaimsInspectAccountOnce(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + cutoff := guardSchedulerDatabaseNow(t).Add(-time.Hour) + id := newGuardSchedulerAccount(t, cutoff.Add(-time.Second), true) + guard := NewAccountTokenGuardV2Repository(integrationDB) + type claimResult struct { + owner string + records []service.AccountTokenGuardV2Record + err error + } + results := make(chan claimResult, 8) + start := make(chan struct{}) + var workers sync.WaitGroup + for i := range 8 { + workers.Add(1) + go func() { + defer workers.Done() + <-start + owner := fmt.Sprintf("claim-racer-%d", i) + records, err := guard.ClaimDue(ctx, owner, time.Minute, 1, cutoff) + results <- claimResult{owner: owner, records: records, err: err} + }() + } + close(start) + workers.Wait() + close(results) + count := 0 + for result := range results { + require.NoError(t, result.err) + for _, record := range result.records { + count++ + require.Equal(t, id, record.AccountID) + require.Equal(t, result.owner, record.LeaseOwner) + } + } + require.Equal(t, 1, count, "concurrent workers must never inspect the same live lease") +} + +func TestAccountTokenGuardV2ClaimDueCanDrainThirtyAccounts(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + cutoff := guardSchedulerDatabaseNow(t).Add(-time.Hour) + want := make(map[int64]bool) + for range 30 { + want[newGuardSchedulerAccount(t, cutoff.Add(-time.Second), true)] = true + } + guard := NewAccountTokenGuardV2Repository(integrationDB) + seen := make(map[int64]bool) + for i := 0; i < 31; i++ { + owner := fmt.Sprintf("claim-drain-%d", i) + claimed, err := guard.ClaimDue(ctx, owner, time.Minute, 1, cutoff) + require.NoError(t, err) + if len(claimed) == 0 { + break + } + require.Len(t, claimed, 1) + record := claimed[0] + require.True(t, want[record.AccountID]) + require.False(t, seen[record.AccountID], "one cycle must not reclaim an account it completed") + require.Equal(t, owner, record.LeaseOwner) + seen[record.AccountID] = true + now := time.Now() + require.NoError(t, guard.CompleteProbe(ctx, record.AccountID, owner, service.AccountTokenGuardV2ProbeCompletion{ + ProbeState: service.AccountTokenGuardV2ProbeOK, LastProbeAt: now, NextProbeAt: now.Add(time.Minute), + })) + } + require.Len(t, seen, 30, "a cycle can continue beyond the old ten-account batch") +} diff --git a/backend/internal/service/account_token_guard_v2.go b/backend/internal/service/account_token_guard_v2.go index 57e2a8f09b6a..7ec114e08daa 100644 --- a/backend/internal/service/account_token_guard_v2.go +++ b/backend/internal/service/account_token_guard_v2.go @@ -11,10 +11,12 @@ import ( "os" "strings" "sync" + "sync/atomic" "time" infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" "github.com/google/uuid" + "golang.org/x/sync/errgroup" ) const ( @@ -27,6 +29,8 @@ const ( AccountTokenGuardV2ProbeInterval = 30 * time.Minute AccountTokenGuardV2RetryInterval = 5 * time.Minute accountTokenGuardV2LeaseDuration = 2 * time.Minute + accountTokenGuardV2CycleDuration = 90 * time.Second + accountTokenGuardV2ProbeWorkers = 3 AccountTokenGuardV2ReloginCooldown = 30 * time.Minute AccountTokenGuardV2FailThreshold = 2 @@ -116,8 +120,9 @@ type AccountTokenGuardV2Repository interface { PruneDeletedAccounts(ctx context.Context) (int64, error) GetAccount(ctx context.Context, accountID int64) (*AccountTokenGuardV2Record, error) ListAccounts(ctx context.Context) ([]AccountTokenGuardV2Record, error) - ClaimDue(ctx context.Context, owner string, leaseDuration time.Duration, limit int) ([]AccountTokenGuardV2Record, error) + ClaimDue(ctx context.Context, owner string, leaseDuration time.Duration, limit int, dueBefore time.Time) ([]AccountTokenGuardV2Record, error) ClaimAccount(ctx context.Context, accountID int64, owner string, leaseDuration time.Duration) (*AccountTokenGuardV2Record, error) + ReleaseProbe(ctx context.Context, accountID int64, owner string) error CompleteProbe(ctx context.Context, accountID int64, owner string, result AccountTokenGuardV2ProbeCompletion) error MarkReauthRequested(ctx context.Context, accountID int64, requestedAt, cooldownUntil time.Time) error RescheduleEnabled(ctx context.Context) error @@ -134,7 +139,7 @@ type AccountTokenGuardV2AccountReader interface { } type AccountTokenGuardV2Prober interface { - FetchOpenAIModelsList(ctx context.Context, account *Account) (*OpenAIModelsResponse, error) + FetchOpenAIModelsListFresh(ctx context.Context, account *Account) (*OpenAIModelsResponse, error) } type AccountTokenGuardV2AccountInput struct { @@ -187,6 +192,7 @@ type AccountTokenGuardV2Service struct { reauth *OpenAIOAuthReauthService leaseOwner string + runMu sync.Mutex startOnce sync.Once rootCtx context.Context cancel context.CancelFunc @@ -258,7 +264,7 @@ func (s *AccountTokenGuardV2Service) Start() { ticker := time.NewTicker(time.Minute) defer ticker.Stop() runCycle := func() { - ctx, cancel := context.WithTimeout(s.rootCtx, 90*time.Second) + ctx, cancel := context.WithTimeout(s.rootCtx, accountTokenGuardV2CycleDuration) defer cancel() if rows, err := s.repo.ListAccounts(ctx); err == nil && len(rows) > 0 { s.reauth.EnsureWorker() @@ -402,6 +408,18 @@ func (s *AccountTokenGuardV2Service) recordView(ctx context.Context, record Acco } func (s *AccountTokenGuardV2Service) RunDue(ctx context.Context) (int, error) { + // A cycle waits for its probes and final lease writes before releasing this + // lock. Overlapping callers must not multiply the bounded worker pool. + if !s.runMu.TryLock() { + return 0, nil + } + defer s.runMu.Unlock() + startedAt := time.Now() + ctx, cancel := context.WithTimeout(ctx, accountTokenGuardV2CycleDuration) + defer cancel() + // Freeze eligibility at cycle start. A long cycle must not repeatedly probe + // accounts whose retry interval elapses while other accounts are running. + dueBefore := s.clockNow() // Clean all orphaned records, including paused accounts and future probes. // Only the database's account deletion state is authoritative, not read errors. removed, err := s.repo.PruneDeletedAccounts(ctx) @@ -411,17 +429,38 @@ func (s *AccountTokenGuardV2Service) RunDue(ctx context.Context) (int, error) { if removed > 0 { slog.Info("account_token_guard_v2_deleted_accounts_pruned", "count", removed) } - records, err := s.repo.ClaimDue(ctx, s.leaseOwner, accountTokenGuardV2LeaseDuration, 10) - if err != nil { - return 0, err - } - for i := range records { - if err := ctx.Err(); err != nil { - return i, err - } - s.runProbe(ctx, records[i]) + group, workCtx := errgroup.WithContext(ctx) + var completed atomic.Int64 + for range accountTokenGuardV2ProbeWorkers { + group.Go(func() error { + for { + if err := workCtx.Err(); err != nil { + return err + } + // Claim only when this slot is free: no leased account waits + // behind a slow probe, and every claim has its own fencing token. + owner := s.newProbeOwner() + records, err := s.repo.ClaimDue(workCtx, owner, accountTokenGuardV2LeaseDuration, 1, dueBefore) + if err != nil { + return err + } + if len(records) == 0 { + return nil + } + if err := s.runProbe(workCtx, records[0]); err != nil { + return err + } + completed.Add(1) + } + }) } - return len(records), nil + err = group.Wait() + slog.Info("account_token_guard_v2_cycle_completed", "processed", completed.Load(), "duration_ms", time.Since(startedAt).Milliseconds(), "cancelled", ctx.Err() != nil) + return int(completed.Load()), err +} + +func (s *AccountTokenGuardV2Service) newProbeOwner() string { + return s.leaseOwner + "/" + uuid.NewString() } func (s *AccountTokenGuardV2Service) ProbeNow(ctx context.Context, accountID int64) (*AccountTokenGuardV2Account, error) { @@ -432,14 +471,16 @@ func (s *AccountTokenGuardV2Service) ProbeNow(ctx context.Context, accountID int if existing == nil { return nil, infraerrors.New(http.StatusNotFound, "TOKEN_GUARD_V2_NOT_FOUND", "monitored account not found") } - record, err := s.repo.ClaimAccount(ctx, accountID, s.leaseOwner, accountTokenGuardV2LeaseDuration) + record, err := s.repo.ClaimAccount(ctx, accountID, s.newProbeOwner(), accountTokenGuardV2LeaseDuration) if err != nil { return nil, infraerrors.New(http.StatusInternalServerError, "TOKEN_GUARD_V2_CLAIM_FAILED", "failed to start account inspection") } if record == nil { return nil, infraerrors.Conflict("TOKEN_GUARD_V2_PROBE_BUSY", "account inspection is already running") } - s.runProbe(ctx, *record) + if err := s.runProbe(ctx, *record); err != nil { + return nil, err + } return s.accountView(ctx, accountID) } @@ -460,11 +501,24 @@ func (s *AccountTokenGuardV2Service) ReloginNow(ctx context.Context, accountID i return task, nil } -func (s *AccountTokenGuardV2Service) runProbe(ctx context.Context, record AccountTokenGuardV2Record) { +func (s *AccountTokenGuardV2Service) runProbe(ctx context.Context, record AccountTokenGuardV2Record) error { + owner := record.LeaseOwner + // CompleteProbe normally clears the lease. Early failures and cancellation + // still release this claim without changing the probe history or due time. + defer func() { + releaseCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second) + defer cancel() + if err := s.repo.ReleaseProbe(releaseCtx, record.AccountID, owner); err != nil { + slog.Warn("account_token_guard_v2_lease_release_failed", "account_id", record.AccountID) + } + }() + if err := ctx.Err(); err != nil { + return err + } rules, err := s.GetRules(ctx) if err != nil { slog.Warn("account_token_guard_v2_rules_read_failed", "error", err) - return + return err } now := s.clockNow() completion := AccountTokenGuardV2ProbeCompletion{ @@ -473,15 +527,21 @@ func (s *AccountTokenGuardV2Service) runProbe(ctx context.Context, record Accoun CooldownUntil: record.CooldownUntil, } account, err := s.accounts.GetAccount(ctx, record.AccountID) + if ctx.Err() != nil { + return ctx.Err() + } if err != nil || account == nil || account.Platform != PlatformOpenAI || account.Type != AccountTypeOAuth || account.IsCredentialShadow() || account.IsOpenAIPersonalAccessToken() || account.IsOpenAIAgentIdentity() { completion.ProbeDetail = "account is no longer an eligible OpenAI OAuth parent account" completion.BlockedReason = completion.ProbeDetail - s.completeProbe(ctx, record.AccountID, completion) - return + return s.completeProbe(ctx, record.AccountID, owner, completion) } probeCtx, cancel := context.WithTimeout(ctx, 30*time.Second) state, detail := s.probeAccount(probeCtx, account) cancel() + if err := ctx.Err(); err != nil { + // Stopping the scheduler is not an account authentication failure. + return err + } completion.ProbeState = state completion.ProbeDetail = detail completion.BlockedReason = "" @@ -489,11 +549,13 @@ func (s *AccountTokenGuardV2Service) runProbe(ctx context.Context, record Accoun pending := false if hasBudget { var updated *AccountTokenGuardV2Record - updated, pending, err = budgetRepo.ReconcileReloginBudget(ctx, record.AccountID, s.leaseOwner, rules, now, state) + updated, pending, err = budgetRepo.ReconcileReloginBudget(ctx, record.AccountID, owner, rules, now, state) + if ctx.Err() != nil { + return ctx.Err() + } if err != nil || updated == nil { completion.BlockedReason = "re-login budget could not be reconciled" - s.completeProbe(ctx, record.AccountID, completion) - return + return s.completeProbe(ctx, record.AccountID, owner, completion) } record = *updated completion.CooldownUntil = record.CooldownUntil @@ -522,8 +584,11 @@ func (s *AccountTokenGuardV2Service) runProbe(ctx context.Context, record Accoun } if hasBudget && record.Enabled && record.AutoReloginEnabled && !record.AutoReloginExhausted && !pending && completion.FailStreak >= rules.FailStreakThreshold && !cooldownActive { task, taskErr := s.reauth.createTaskForProfile(ctx, record.AccountID, "codex", func(createCtx context.Context, id int64, hash string) (*OpenAIOAuthReauthTaskRecord, error) { - return budgetRepo.CreateAutomaticRelogin(createCtx, id, hash, s.leaseOwner, rules, s.clockNow()) + return budgetRepo.CreateAutomaticRelogin(createCtx, id, hash, owner, rules, s.clockNow()) }) + if ctx.Err() != nil { + return ctx.Err() + } if taskErr == nil && task != nil { completion.LastReauthAt = &now cooldown := now.Add(time.Duration(rules.ReloginCooldownSeconds) * time.Second) @@ -534,25 +599,40 @@ func (s *AccountTokenGuardV2Service) runProbe(ctx context.Context, record Accoun } else if taskErr != nil { completion.BlockedReason = "automatic re-login could not be queued" completion.ProbeDetail = detail + "; " + completion.BlockedReason + slog.Warn("account_token_guard_v2_relogin_queue_failed", "account_id", record.AccountID, "reason", safeTokenGuardReloginReason(taskErr)) } } } - s.completeProbe(ctx, record.AccountID, completion) + if ctx.Err() != nil { + return ctx.Err() + } + return s.completeProbe(ctx, record.AccountID, owner, completion) +} + +func safeTokenGuardReloginReason(err error) string { + switch reason := infraerrors.Reason(err); reason { + case "OPENAI_REAUTH_UNAVAILABLE", "OPENAI_REAUTH_WORKER_UNAVAILABLE", "OPENAI_REAUTH_CONFIG_REQUIRED", "OPENAI_REAUTH_CONFIG_READ_FAILED", "OPENAI_REAUTH_CONFIG_DECRYPT_FAILED", "OPENAI_REAUTH_ENCRYPTION_KEY_REQUIRED", "OPENAI_REAUTH_CREDENTIAL_SNAPSHOT_FAILED", "OPENAI_REAUTH_ACCOUNT_NOT_FOUND", "OPENAI_REAUTH_ACCOUNT_INVALID", "OPENAI_REAUTH_TASK_CREATE_FAILED": + return reason + default: + return "unknown" + } } -func (s *AccountTokenGuardV2Service) completeProbe(ctx context.Context, accountID int64, completion AccountTokenGuardV2ProbeCompletion) { +func (s *AccountTokenGuardV2Service) completeProbe(ctx context.Context, accountID int64, owner string, completion AccountTokenGuardV2ProbeCompletion) error { persistCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second) defer cancel() - if err := s.repo.CompleteProbe(persistCtx, accountID, s.leaseOwner, completion); err != nil { + if err := s.repo.CompleteProbe(persistCtx, accountID, owner, completion); err != nil { slog.Warn("account_token_guard_v2_probe_save_failed", "account_id", accountID, "error", err) + return err } + return nil } func (s *AccountTokenGuardV2Service) probeAccount(ctx context.Context, account *Account) (string, string) { if strings.TrimSpace(account.GetCredential("access_token")) == "" { return AccountTokenGuardV2ProbeAuth, "account has no access token" } - _, err := s.prober.FetchOpenAIModelsList(ctx, account) + _, err := s.prober.FetchOpenAIModelsListFresh(ctx, account) if err == nil { return AccountTokenGuardV2ProbeOK, "credential accepted" } diff --git a/backend/internal/service/account_token_guard_v2_budget_test.go b/backend/internal/service/account_token_guard_v2_budget_test.go index 122625f9f545..836b05d69f49 100644 --- a/backend/internal/service/account_token_guard_v2_budget_test.go +++ b/backend/internal/service/account_token_guard_v2_budget_test.go @@ -12,6 +12,8 @@ import ( ) func (r *accountTokenGuardV2TestRepo) ReconcileReloginBudget(_ context.Context, _ int64, _ string, rules AccountTokenGuardV2Rules, at time.Time, state string) (*AccountTokenGuardV2Record, bool, error) { + r.mu.Lock() + defer r.mu.Unlock() if r.record == nil { return nil, false, errors.New("missing record") } @@ -32,6 +34,8 @@ func (r *accountTokenGuardV2TestRepo) CreateAutomaticRelogin(ctx context.Context } func (r *accountTokenGuardV2TestRepo) ResumeReloginBudget(_ context.Context, _ int64, rules AccountTokenGuardV2Rules, now time.Time) error { + r.mu.Lock() + defer r.mu.Unlock() if r.record == nil { return errors.New("missing record") } @@ -126,7 +130,7 @@ func TestExhaustedReloginStillProbesAndManualFailureDoesNotRestartAutomation(t * AccountID: 42, Enabled: true, AutoReloginEnabled: true, ReloginFailStreak: 3, AutoReloginExhausted: true, }} svc := NewAccountTokenGuardV2Service(repo, nil, reader, accountTokenGuardV2TestProber{err: errors.New("invalid token")}, reauth) - svc.runProbe(context.Background(), *repo.record) + require.NoError(t, svc.runProbe(context.Background(), *repo.record)) require.NotNil(t, repo.completion) require.Equal(t, AccountTokenGuardV2ProbeAuth, repo.completion.ProbeState) require.Contains(t, repo.completion.BlockedReason, "exhausted") @@ -135,7 +139,7 @@ func TestExhaustedReloginStillProbesAndManualFailureDoesNotRestartAutomation(t * // A manually initiated failure is accounted too; observing it cannot resume. now := time.Now() repo.outcomes = []AccountReloginOutcome{{ID: 9, Status: OpenAIOAuthReauthStatusFailed, FinishedAt: &now}} - svc.runProbe(context.Background(), *repo.record) + require.NoError(t, svc.runProbe(context.Background(), *repo.record)) require.True(t, repo.record.AutoReloginExhausted) require.Zero(t, tasks.createCalls) } @@ -182,16 +186,16 @@ func TestRestoredBudgetPlainOKKeepsCooldownBeforeAnotherAuthProbe(t *testing.T) require.NoError(t, err) until := now.Add(time.Minute) now = now.Add(time.Second) - svc.runProbe(ctx, *repo.record) + require.NoError(t, svc.runProbe(ctx, *repo.record)) require.Equal(t, AccountTokenGuardV2ProbeOK, repo.completion.ProbeState) require.Equal(t, &until, repo.completion.CooldownUntil) prober.err = errors.New("invalid token") now = until.Add(-time.Nanosecond) - svc.runProbe(ctx, *repo.record) + require.NoError(t, svc.runProbe(ctx, *repo.record)) require.Zero(t, tasks.createCalls) require.Equal(t, &until, repo.completion.CooldownUntil) now = until - svc.runProbe(ctx, *repo.record) + require.NoError(t, svc.runProbe(ctx, *repo.record)) require.Equal(t, 1, tasks.createCalls, "the explicit recovery cooldown opens only at its boundary") } diff --git a/backend/internal/service/account_token_guard_v2_scheduler_test.go b/backend/internal/service/account_token_guard_v2_scheduler_test.go new file mode 100644 index 000000000000..a5bb1cf6d7c1 --- /dev/null +++ b/backend/internal/service/account_token_guard_v2_scheduler_test.go @@ -0,0 +1,509 @@ +package service + +import ( + "context" + "errors" + "sort" + "sync" + "sync/atomic" + "testing" + "time" + + infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" + "github.com/stretchr/testify/require" +) + +type schedulerProbeClaim struct { + id int64 + owner string +} + +// This queue models exclusive claims and rescheduling, including across workers. +// It deliberately has no budget interface: scheduler tests never create logins. +type schedulerProbeQueue struct { + mu sync.Mutex + records map[int64]AccountTokenGuardV2Record + claims []schedulerProbeClaim + completed []schedulerProbeClaim + released []schedulerProbeClaim + cutoffs []time.Time + releaseErrs []error +} + +func newSchedulerProbeQueue(count int, at time.Time) *schedulerProbeQueue { + r := &schedulerProbeQueue{records: make(map[int64]AccountTokenGuardV2Record)} + for id := 1; id <= count; id++ { + r.records[int64(id)] = AccountTokenGuardV2Record{ + AccountID: int64(id), Enabled: true, AutoReloginEnabled: true, + ProbeState: AccountTokenGuardV2ProbePending, NextProbeAt: at.Add(-time.Minute), + } + } + return r +} + +func (r *schedulerProbeQueue) UpsertAccount(context.Context, int64, bool, bool) error { + return errors.New("unexpected scheduler test upsert") +} +func (r *schedulerProbeQueue) DeleteAccount(context.Context, int64) error { + return errors.New("unexpected scheduler test delete") +} +func (r *schedulerProbeQueue) PruneDeletedAccounts(context.Context) (int64, error) { + return 0, nil +} +func (r *schedulerProbeQueue) GetAccount(_ context.Context, id int64) (*AccountTokenGuardV2Record, error) { + r.mu.Lock() + defer r.mu.Unlock() + record, ok := r.records[id] + if !ok { + return nil, nil + } + return &record, nil +} +func (r *schedulerProbeQueue) ListAccounts(context.Context) ([]AccountTokenGuardV2Record, error) { + r.mu.Lock() + defer r.mu.Unlock() + records := make([]AccountTokenGuardV2Record, 0, len(r.records)) + for _, record := range r.records { + records = append(records, record) + } + return records, nil +} +func (r *schedulerProbeQueue) ClaimDue(ctx context.Context, owner string, duration time.Duration, limit int, dueBefore time.Time) ([]AccountTokenGuardV2Record, error) { + r.mu.Lock() + defer r.mu.Unlock() + if err := ctx.Err(); err != nil { + return nil, err + } + r.cutoffs = append(r.cutoffs, dueBefore) + var due []AccountTokenGuardV2Record + for _, record := range r.records { + if record.Enabled && record.LeaseOwner == "" && !record.NextProbeAt.After(dueBefore) { + due = append(due, record) + } + } + sort.Slice(due, func(i, j int) bool { + if due[i].NextProbeAt.Equal(due[j].NextProbeAt) { + return due[i].AccountID < due[j].AccountID + } + return due[i].NextProbeAt.Before(due[j].NextProbeAt) + }) + if len(due) > limit { + due = due[:limit] + } + for i := range due { + due[i] = r.claimLocked(due[i], owner, duration) + } + return due, nil +} +func (r *schedulerProbeQueue) claimLocked(record AccountTokenGuardV2Record, owner string, duration time.Duration) AccountTokenGuardV2Record { + until := time.Now().Add(duration) + record.LeaseOwner, record.LeaseUntil = owner, &until + r.records[record.AccountID] = record + r.claims = append(r.claims, schedulerProbeClaim{record.AccountID, owner}) + return record +} +func (r *schedulerProbeQueue) ClaimAccount(ctx context.Context, id int64, owner string, duration time.Duration) (*AccountTokenGuardV2Record, error) { + r.mu.Lock() + defer r.mu.Unlock() + if err := ctx.Err(); err != nil { + return nil, err + } + record, ok := r.records[id] + if !ok || record.LeaseOwner != "" { + return nil, nil + } + record = r.claimLocked(record, owner, duration) + return &record, nil +} +func (r *schedulerProbeQueue) CompleteProbe(_ context.Context, id int64, owner string, result AccountTokenGuardV2ProbeCompletion) error { + r.mu.Lock() + defer r.mu.Unlock() + record := r.records[id] + if owner == "" || record.LeaseOwner != owner { + return errors.New("scheduler test completion lost its claim") + } + r.completed = append(r.completed, schedulerProbeClaim{id, owner}) + record.ProbeState, record.ProbeDetail = result.ProbeState, result.ProbeDetail + record.FailStreak, record.LastProbeAt = result.FailStreak, &result.LastProbeAt + record.NextProbeAt = result.NextProbeAt + record.LeaseOwner, record.LeaseUntil = "", nil + r.records[id] = record + return nil +} +func (r *schedulerProbeQueue) ReleaseProbe(ctx context.Context, id int64, owner string) error { + r.mu.Lock() + defer r.mu.Unlock() + r.released = append(r.released, schedulerProbeClaim{id, owner}) + r.releaseErrs = append(r.releaseErrs, ctx.Err()) + if err := ctx.Err(); err != nil { + return err + } + record := r.records[id] + if record.LeaseOwner == owner { + record.LeaseOwner, record.LeaseUntil = "", nil + r.records[id] = record + } + return nil +} +func (r *schedulerProbeQueue) MarkReauthRequested(context.Context, int64, time.Time, time.Time) error { + return errors.New("unexpected scheduler test re-login") +} +func (r *schedulerProbeQueue) RescheduleEnabled(context.Context) error { return nil } + +type schedulerProbeReader struct{} + +func (schedulerProbeReader) GetAccount(_ context.Context, id int64) (*Account, error) { + return &Account{ID: id, Platform: PlatformOpenAI, Type: AccountTypeOAuth, + Credentials: map[string]any{"access_token": "synthetic-scheduler-token"}}, nil +} +func (schedulerProbeReader) GetProxy(context.Context, int64) (*Proxy, error) { return nil, nil } + +type schedulerProbeFunc func(context.Context, *Account) (*OpenAIModelsResponse, error) + +func (f schedulerProbeFunc) FetchOpenAIModelsListFresh(ctx context.Context, account *Account) (*OpenAIModelsResponse, error) { + return f(ctx, account) +} + +type schedulerCycleResult struct { + count int + err error +} + +func schedulerStartCycle(svc *AccountTokenGuardV2Service, ctx context.Context) <-chan schedulerCycleResult { + done := make(chan schedulerCycleResult, 1) + go func() { + count, err := svc.RunDue(ctx) + done <- schedulerCycleResult{count, err} + }() + return done +} + +func schedulerAwaitCycle(t *testing.T, done <-chan schedulerCycleResult) schedulerCycleResult { + t.Helper() + select { + case result := <-done: + return result + case <-time.After(3 * time.Second): + t.Fatal("scheduler did not finish its bounded work") + return schedulerCycleResult{} + } +} + +func schedulerAwaitStarted(t *testing.T, started <-chan int64, count int) { + t.Helper() + for i := 0; i < count; i++ { + select { + case <-started: + case <-time.After(3 * time.Second): + t.Fatal("scheduler did not fill its available probe slots") + } + } +} + +func TestAccountTokenGuardV2SchedulerDrainsThirtyDueAccounts(t *testing.T) { + at := time.Now() + repo := newSchedulerProbeQueue(30, at) + svc := NewAccountTokenGuardV2Service(repo, nil, schedulerProbeReader{}, accountTokenGuardV2TestProber{}, nil) + t.Cleanup(svc.cancel) + svc.now = func() time.Time { return at } + result := schedulerAwaitCycle(t, schedulerStartCycle(svc, context.Background())) + require.NoError(t, result.err) + require.Equal(t, 30, result.count) + repo.mu.Lock() + defer repo.mu.Unlock() + require.Len(t, repo.completed, 30, "one cycle must drain beyond the old batch of ten") + owners := make(map[string]bool) + for _, claim := range repo.claims { + require.NotEmpty(t, claim.owner) + require.False(t, owners[claim.owner], "each acquisition needs a fresh lease token") + owners[claim.owner] = true + } + for _, completion := range repo.completed { + require.True(t, owners[completion.owner], "completion must use the acquired token") + } + for _, record := range repo.records { + require.Equal(t, AccountTokenGuardV2ProbeOK, record.ProbeState) + require.Empty(t, record.LeaseOwner) + } +} + +func TestAccountTokenGuardV2SchedulerKeepsCycleCutoffWhenClockAdvances(t *testing.T) { + at := time.Now() + repo := newSchedulerProbeQueue(4, at) + future := repo.records[4] + future.NextProbeAt = at.Add(30 * time.Second) + repo.records[4] = future + var clock atomic.Int64 + clock.Store(at.UnixNano()) + prober := schedulerProbeFunc(func(context.Context, *Account) (*OpenAIModelsResponse, error) { + clock.Store(at.Add(2 * time.Minute).UnixNano()) + return nil, nil + }) + svc := NewAccountTokenGuardV2Service(repo, nil, schedulerProbeReader{}, prober, nil) + t.Cleanup(svc.cancel) + svc.now = func() time.Time { return time.Unix(0, clock.Load()) } + result := schedulerAwaitCycle(t, schedulerStartCycle(svc, context.Background())) + require.NoError(t, result.err) + require.Equal(t, 3, result.count) + repo.mu.Lock() + defer repo.mu.Unlock() + require.Nil(t, repo.records[4].LastProbeAt, "future work belongs to the next cycle") + for _, cutoff := range repo.cutoffs { + require.True(t, cutoff.Equal(at), "all claims in a cycle share its starting cutoff") + } +} + +func TestAccountTokenGuardV2SchedulerRefillsSlotsWhileOneProbeIsSlow(t *testing.T) { + const total = 20 + repo := newSchedulerProbeQueue(total, time.Now()) + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + started := make(chan int64, total) + fastCompleted := make(chan struct{}, total) + slowGate, firstWaveGate := make(chan struct{}), make(chan struct{}) + var active, peak atomic.Int32 + prober := schedulerProbeFunc(func(ctx context.Context, account *Account) (*OpenAIModelsResponse, error) { + current := active.Add(1) + defer active.Add(-1) + for previous := peak.Load(); current > previous; previous = peak.Load() { + if peak.CompareAndSwap(previous, current) { + break + } + } + started <- account.ID + gate := firstWaveGate + if account.ID == 1 { + gate = slowGate + } + select { + case <-ctx.Done(): + return nil, ctx.Err() + case <-gate: + } + if account.ID != 1 { + fastCompleted <- struct{}{} + } + return nil, nil + }) + svc := NewAccountTokenGuardV2Service(repo, nil, schedulerProbeReader{}, prober, nil) + t.Cleanup(svc.cancel) + done := schedulerStartCycle(svc, ctx) + schedulerAwaitStarted(t, started, 3) + close(firstWaveGate) + for i := 0; i < total-1; i++ { + select { + case <-fastCompleted: + case <-time.After(3 * time.Second): + t.Fatal("a slow probe prevented available slots from draining later accounts") + } + } + require.EqualValues(t, 3, peak.Load(), "probe concurrency must stay bounded at three") + close(slowGate) + result := schedulerAwaitCycle(t, done) + require.NoError(t, result.err) + require.Equal(t, total, result.count) +} + +func TestAccountTokenGuardV2SchedulerCancellationReleasesOnlyRunningClaims(t *testing.T) { + repo := newSchedulerProbeQueue(30, time.Now()) + for id, record := range repo.records { + record.FailStreak = 2 + repo.records[id] = record + } + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + started := make(chan int64, 30) + prober := schedulerProbeFunc(func(ctx context.Context, account *Account) (*OpenAIModelsResponse, error) { + started <- account.ID + <-ctx.Done() + // Cancellation must win even when a transport reports an auth-shaped error. + return nil, errors.New("invalid token") + }) + svc := NewAccountTokenGuardV2Service(repo, nil, schedulerProbeReader{}, prober, nil) + t.Cleanup(svc.cancel) + done := schedulerStartCycle(svc, ctx) + schedulerAwaitStarted(t, started, 3) + repo.mu.Lock() + claimed := len(repo.claims) + repo.mu.Unlock() + require.Equal(t, 3, claimed, "queued accounts must not be leased before a slot is free") + cancel() + result := schedulerAwaitCycle(t, done) + require.ErrorIs(t, result.err, context.Canceled) + repo.mu.Lock() + defer repo.mu.Unlock() + require.Len(t, repo.claims, 3) + require.Len(t, repo.released, 3) + for _, err := range repo.releaseErrs { + require.NoError(t, err, "lease cleanup must survive caller cancellation") + } + for _, record := range repo.records { + require.Empty(t, record.LeaseOwner) + require.Equal(t, 2, record.FailStreak, "a cancelled request is not another auth failure") + require.NotEqual(t, AccountTokenGuardV2ProbeAuth, record.ProbeState) + } +} + +func TestAccountTokenGuardV2SchedulerOverlappingCyclesDoNotMultiplyConcurrency(t *testing.T) { + repo := newSchedulerProbeQueue(12, time.Now()) + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + started := make(chan int64, 12) + gate := make(chan struct{}) + prober := schedulerProbeFunc(func(ctx context.Context, account *Account) (*OpenAIModelsResponse, error) { + started <- account.ID + select { + case <-ctx.Done(): + return nil, ctx.Err() + case <-gate: + return nil, nil + } + }) + svc := NewAccountTokenGuardV2Service(repo, nil, schedulerProbeReader{}, prober, nil) + t.Cleanup(svc.cancel) + first := schedulerStartCycle(svc, ctx) + schedulerAwaitStarted(t, started, 3) + second := schedulerAwaitCycle(t, schedulerStartCycle(svc, ctx)) + require.Zero(t, second.count, "an overlapping cycle must not start another worker pool") + repo.mu.Lock() + claimed := len(repo.claims) + repo.mu.Unlock() + require.Equal(t, 3, claimed) + close(gate) + result := schedulerAwaitCycle(t, first) + require.NoError(t, result.err) + require.Equal(t, 12, result.count) +} + +func TestAccountTokenGuardV2ManualProbeUsesFreshClaimToken(t *testing.T) { + reauth, reader, _, _, _, _ := newReauthTestService("acct-1") + repo := newSchedulerProbeQueue(0, time.Now()) + repo.records[42] = AccountTokenGuardV2Record{AccountID: 42, Enabled: true} + svc := NewAccountTokenGuardV2Service(repo, nil, reader, accountTokenGuardV2TestProber{}, reauth) + t.Cleanup(svc.cancel) + for attempt := 0; attempt < 2; attempt++ { + view, err := svc.ProbeNow(context.Background(), 42) + require.NoError(t, err) + require.Equal(t, AccountTokenGuardV2ProbeOK, view.ProbeState) + } + repo.mu.Lock() + defer repo.mu.Unlock() + require.Len(t, repo.claims, 2) + require.Len(t, repo.completed, 2) + require.NotEqual(t, repo.claims[0].owner, repo.claims[1].owner) + require.Equal(t, repo.claims, repo.completed, "manual completions must retain their claim token") +} + +type schedulerBudgetQueue struct { + *schedulerProbeQueue + budgetOwners []string + createOwners []string + cancelAtReconcile context.CancelFunc + cancelAtCreate context.CancelFunc +} + +func (r *schedulerBudgetQueue) ReconcileReloginBudget(_ context.Context, id int64, owner string, _ AccountTokenGuardV2Rules, _ time.Time, _ string) (*AccountTokenGuardV2Record, bool, error) { + r.mu.Lock() + defer r.mu.Unlock() + record := r.records[id] + if owner == "" || owner != record.LeaseOwner { + return nil, false, errors.New("budget reconciliation used a stale lease token") + } + r.budgetOwners = append(r.budgetOwners, owner) + if r.cancelAtReconcile != nil { + r.cancelAtReconcile() + } + return &record, false, nil +} +func (r *schedulerBudgetQueue) CreateAutomaticRelogin(_ context.Context, id int64, _ string, owner string, _ AccountTokenGuardV2Rules, _ time.Time) (*OpenAIOAuthReauthTaskRecord, error) { + r.mu.Lock() + defer r.mu.Unlock() + if owner == "" || owner != r.records[id].LeaseOwner { + return nil, errors.New("automatic re-login used a stale lease token") + } + r.createOwners = append(r.createOwners, owner) + if r.cancelAtCreate != nil { + r.cancelAtCreate() + } + return &OpenAIOAuthReauthTaskRecord{ID: 1, AccountID: id, Status: OpenAIOAuthReauthStatusQueued}, nil +} +func (*schedulerBudgetQueue) ResumeReloginBudget(context.Context, int64, AccountTokenGuardV2Rules, time.Time) error { + return errors.New("unexpected scheduler test budget recovery") +} + +func TestAccountTokenGuardV2AutomaticReloginPreservesProbeClaimToken(t *testing.T) { + reauth, reader, reauthRepo, _, _, _ := newReauthTestService("acct-1") + require.NoError(t, reauthRepo.UpsertConfig(context.Background(), reauthEmailConfig(42, "user@example.test", "encrypted:https://mail.example.test/code"))) + repo := &schedulerBudgetQueue{schedulerProbeQueue: newSchedulerProbeQueue(0, time.Now())} + repo.records[42] = AccountTokenGuardV2Record{AccountID: 42, Enabled: true, AutoReloginEnabled: true, FailStreak: 1} + svc := NewAccountTokenGuardV2Service(repo, nil, reader, accountTokenGuardV2TestProber{err: errors.New("invalid token")}, reauth) + t.Cleanup(svc.cancel) + _, err := svc.ProbeNow(context.Background(), 42) + require.NoError(t, err) + repo.mu.Lock() + defer repo.mu.Unlock() + require.Len(t, repo.claims, 1) + owner := repo.claims[0].owner + require.Equal(t, []string{owner}, repo.budgetOwners) + require.Equal(t, []string{owner}, repo.createOwners) + require.Equal(t, []schedulerProbeClaim{{42, owner}}, repo.completed) +} + +func TestAccountTokenGuardV2CancellationAfterProbePreservesInspectionHistory(t *testing.T) { + for _, stage := range []string{"budget reconciliation", "task creation"} { + t.Run(stage, func(t *testing.T) { + reauth, reader, reauthRepo, _, _, _ := newReauthTestService("acct-1") + require.NoError(t, reauthRepo.UpsertConfig(context.Background(), reauthEmailConfig(42, "user@example.test", "encrypted:https://mail.example.test/code"))) + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + repo := &schedulerBudgetQueue{schedulerProbeQueue: newSchedulerProbeQueue(0, time.Now())} + original := AccountTokenGuardV2Record{ + AccountID: 42, Enabled: true, AutoReloginEnabled: true, FailStreak: 1, + ProbeState: AccountTokenGuardV2ProbePending, ProbeDetail: "previous inspection", + BlockedReason: "previous automation state", NextProbeAt: time.Now().Add(-time.Minute), + } + repo.records[42] = original + if stage == "budget reconciliation" { + repo.cancelAtReconcile = cancel + } else { + repo.cancelAtCreate = cancel + } + svc := NewAccountTokenGuardV2Service(repo, nil, reader, accountTokenGuardV2TestProber{err: errors.New("invalid token")}, reauth) + t.Cleanup(svc.cancel) + view, err := svc.ProbeNow(ctx, 42) + require.ErrorIs(t, err, context.Canceled) + require.Nil(t, view) + repo.mu.Lock() + defer repo.mu.Unlock() + require.Empty(t, repo.completed, "cancellation must not publish another inspection outcome") + require.Len(t, repo.released, 1) + require.NoError(t, repo.releaseErrs[0], "cleanup must use a context independent of the cancelled operation") + require.Equal(t, original, repo.records[42], "leave the prior failure count, due time and diagnostics unchanged") + require.Len(t, repo.budgetOwners, 1) + if stage == "budget reconciliation" { + require.Empty(t, repo.createOwners, "a cancelled reconciliation must not start a login") + } else { + require.Len(t, repo.createOwners, 1, "an already-created task keeps its own durable lifecycle") + } + }) + } +} + +func TestSafeTokenGuardReloginReasonDoesNotExposeProviderDetails(t *testing.T) { + for _, test := range []struct { + name string + err error + want string + }{ + {"allowlisted reason", infraerrors.ServiceUnavailable("OPENAI_REAUTH_WORKER_UNAVAILABLE", "synthetic-private-provider-response"), "OPENAI_REAUTH_WORKER_UNAVAILABLE"}, + {"unlisted application reason", infraerrors.ServiceUnavailable("OPENAI_REAUTH_MODE_UNAVAILABLE", "synthetic-private-provider-response"), "unknown"}, + {"arbitrary reason", infraerrors.ServiceUnavailable("synthetic-private-reason", "synthetic-private-provider-response"), "unknown"}, + {"plain provider error", errors.New("synthetic-private-provider-response"), "unknown"}, + } { + t.Run(test.name, func(t *testing.T) { + reason := safeTokenGuardReloginReason(test.err) + require.Equal(t, test.want, reason) + require.NotContains(t, reason, "synthetic-private") + }) + } +} diff --git a/backend/internal/service/account_token_guard_v2_test.go b/backend/internal/service/account_token_guard_v2_test.go index d02bf929bd8f..fa635af05963 100644 --- a/backend/internal/service/account_token_guard_v2_test.go +++ b/backend/internal/service/account_token_guard_v2_test.go @@ -15,6 +15,7 @@ import ( ) type accountTokenGuardV2TestRepo struct { + mu sync.Mutex createTask func(context.Context, int64, string) (*OpenAIOAuthReauthTaskRecord, error) outcomes []AccountReloginOutcome record *AccountTokenGuardV2Record @@ -27,6 +28,8 @@ type accountTokenGuardV2TestRepo struct { } func (r *accountTokenGuardV2TestRepo) PruneDeletedAccounts(context.Context) (int64, error) { + r.mu.Lock() + defer r.mu.Unlock() if r.pruneErr != nil { return 0, r.pruneErr } @@ -38,6 +41,8 @@ func (r *accountTokenGuardV2TestRepo) PruneDeletedAccounts(context.Context) (int } func (r *accountTokenGuardV2TestRepo) UpsertAccount(_ context.Context, accountID int64, enabled, autoRelogin bool) error { + r.mu.Lock() + defer r.mu.Unlock() if r.record == nil { r.record = &AccountTokenGuardV2Record{AccountID: accountID, NextProbeAt: time.Now()} } @@ -46,10 +51,14 @@ func (r *accountTokenGuardV2TestRepo) UpsertAccount(_ context.Context, accountID return nil } func (r *accountTokenGuardV2TestRepo) DeleteAccount(context.Context, int64) error { + r.mu.Lock() + defer r.mu.Unlock() r.record = nil return nil } func (r *accountTokenGuardV2TestRepo) GetAccount(context.Context, int64) (*AccountTokenGuardV2Record, error) { + r.mu.Lock() + defer r.mu.Unlock() if r.record == nil { return nil, nil } @@ -57,26 +66,46 @@ func (r *accountTokenGuardV2TestRepo) GetAccount(context.Context, int64) (*Accou return ©, nil } func (r *accountTokenGuardV2TestRepo) ListAccounts(context.Context) ([]AccountTokenGuardV2Record, error) { + r.mu.Lock() + defer r.mu.Unlock() if r.record == nil { return nil, nil } return []AccountTokenGuardV2Record{*r.record}, nil } -func (r *accountTokenGuardV2TestRepo) ClaimDue(context.Context, string, time.Duration, int) ([]AccountTokenGuardV2Record, error) { +func (r *accountTokenGuardV2TestRepo) ClaimDue(_ context.Context, owner string, duration time.Duration, _ int, dueBefore time.Time) ([]AccountTokenGuardV2Record, error) { + r.mu.Lock() + defer r.mu.Unlock() r.claimed = true - if r.record == nil || r.claimBusy { + if r.record == nil || r.claimBusy || !r.record.Enabled || r.record.NextProbeAt.After(dueBefore) || (r.record.LeaseUntil != nil && r.record.LeaseUntil.After(time.Now())) { return nil, nil } + until := time.Now().Add(duration) + r.record.LeaseOwner, r.record.LeaseUntil = owner, &until return []AccountTokenGuardV2Record{*r.record}, nil } -func (r *accountTokenGuardV2TestRepo) ClaimAccount(context.Context, int64, string, time.Duration) (*AccountTokenGuardV2Record, error) { +func (r *accountTokenGuardV2TestRepo) ClaimAccount(_ context.Context, _ int64, owner string, duration time.Duration) (*AccountTokenGuardV2Record, error) { + r.mu.Lock() + defer r.mu.Unlock() if r.record == nil || r.claimBusy { return nil, nil } + until := time.Now().Add(duration) + r.record.LeaseOwner, r.record.LeaseUntil = owner, &until copy := *r.record return ©, nil } +func (r *accountTokenGuardV2TestRepo) ReleaseProbe(_ context.Context, _ int64, owner string) error { + r.mu.Lock() + defer r.mu.Unlock() + if r.record != nil && r.record.LeaseOwner == owner { + r.record.LeaseOwner, r.record.LeaseUntil = "", nil + } + return nil +} func (r *accountTokenGuardV2TestRepo) CompleteProbe(_ context.Context, _ int64, _ string, result AccountTokenGuardV2ProbeCompletion) error { + r.mu.Lock() + defer r.mu.Unlock() r.completion = &result if r.record != nil { r.record.ProbeState = result.ProbeState @@ -87,6 +116,7 @@ func (r *accountTokenGuardV2TestRepo) CompleteProbe(_ context.Context, _ int64, r.record.NextProbeAt = result.NextProbeAt r.record.CooldownUntil = result.CooldownUntil r.record.BlockedReason = result.BlockedReason + r.record.LeaseOwner, r.record.LeaseUntil = "", nil } return nil } @@ -94,6 +124,8 @@ func (r *accountTokenGuardV2TestRepo) MarkReauthRequested(context.Context, int64 return nil } func (r *accountTokenGuardV2TestRepo) RescheduleEnabled(context.Context) error { + r.mu.Lock() + defer r.mu.Unlock() r.rescheduled = true return nil } @@ -115,15 +147,16 @@ type accountTokenGuardV2TestProber struct{ err error } type accountTokenGuardV2BlockingRepo struct { accountTokenGuardV2TestRepo - started chan struct{} - finished chan struct{} - once sync.Once + started chan struct{} + finished chan struct{} + once sync.Once + finishedOnce sync.Once } -func (r *accountTokenGuardV2BlockingRepo) ClaimDue(ctx context.Context, _ string, _ time.Duration, _ int) ([]AccountTokenGuardV2Record, error) { +func (r *accountTokenGuardV2BlockingRepo) ClaimDue(ctx context.Context, _ string, _ time.Duration, _ int, _ time.Time) ([]AccountTokenGuardV2Record, error) { r.once.Do(func() { close(r.started) }) <-ctx.Done() - close(r.finished) + r.finishedOnce.Do(func() { close(r.finished) }) return nil, ctx.Err() } @@ -147,7 +180,7 @@ func TestAccountTokenGuardV2StopCancelsCycle(t *testing.T) { svc.Stop() } -func (p accountTokenGuardV2TestProber) FetchOpenAIModelsList(context.Context, *Account) (*OpenAIModelsResponse, error) { +func (p accountTokenGuardV2TestProber) FetchOpenAIModelsListFresh(context.Context, *Account) (*OpenAIModelsResponse, error) { return nil, p.err } @@ -175,7 +208,7 @@ func TestAccountTokenGuardV2Explicit403PolicyDoesNotQueueRelogin(t *testing.T) { svc := NewAccountTokenGuardV2Service(guardRepo, nil, reader, accountTokenGuardV2TestProber{err: fmt.Errorf("wrapped: %w", &codexModelsManifestUpstreamError{ err: errors.New("unauthorized synthetic-private"), statusCode: http.StatusForbidden, body: []byte(body), })}, reauth) - svc.runProbe(context.Background(), *guardRepo.record) + require.NoError(t, svc.runProbe(context.Background(), *guardRepo.record)) require.NotNil(t, guardRepo.completion) require.Equal(t, AccountTokenGuardV2ProbeTransient, guardRepo.completion.ProbeState) require.Equal(t, accountTokenGuardV2PolicyBlocked, guardRepo.completion.BlockedReason) @@ -220,7 +253,7 @@ func TestAccountTokenGuardV2SecondAuthFailureQueuesRelogin(t *testing.T) { record, err := guardRepo.GetAccount(context.Background(), 42) require.NoError(t, err) - svc.runProbe(context.Background(), *record) + require.NoError(t, svc.runProbe(context.Background(), *record)) require.NotNil(t, guardRepo.completion) require.Equal(t, AccountTokenGuardV2ProbeAuth, guardRepo.completion.ProbeState) @@ -246,7 +279,7 @@ func TestAccountTokenGuardV2ActiveReloginTaskIsNotDuplicated(t *testing.T) { record, err := guardRepo.GetAccount(context.Background(), 42) require.NoError(t, err) - svc.runProbe(context.Background(), *record) + require.NoError(t, svc.runProbe(context.Background(), *record)) require.Same(t, existing, reauthRepo.task) require.Equal(t, 1, reauthRepo.createCalls) @@ -313,14 +346,34 @@ func TestAccountTokenGuardV2RulesRejectInvalidRange(t *testing.T) { } func TestAccountTokenGuardV2InvalidSavedRulesDoNotQueueRelogin(t *testing.T) { - reauth, reader, reauthRepo, _, _, _ := newReauthTestService("acct-1") - record := AccountTokenGuardV2Record{AccountID: 42, Enabled: true, AutoReloginEnabled: true, FailStreak: 2} - repo := &accountTokenGuardV2TestRepo{record: &record} - settings := &accountTokenGuardV2TestSettings{raw: "invalid-json"} - svc := NewAccountTokenGuardV2Service(repo, settings, reader, accountTokenGuardV2TestProber{err: errors.New("invalid token")}, reauth) - svc.runProbe(context.Background(), record) - require.Zero(t, reauthRepo.createCalls) - require.Nil(t, repo.completion) + for _, test := range []struct{ name, raw, wantError string }{ + {"invalid JSON", "invalid-json", "invalid character"}, + {"invalid interval", `{"probe_interval_seconds":59,"retry_interval_seconds":60,"relogin_cooldown_seconds":1800,"fail_streak_threshold":2}`, "probe_interval_seconds"}, + } { + t.Run(test.name, func(t *testing.T) { + reauth, reader, reauthRepo, _, _, _ := newReauthTestService("acct-1") + next := time.Now().Add(-time.Minute) + until := time.Now().Add(time.Minute) + record := AccountTokenGuardV2Record{ + AccountID: 42, Enabled: true, AutoReloginEnabled: true, FailStreak: 2, + NextProbeAt: next, LeaseOwner: "invalid-rules-claim", LeaseUntil: &until, + } + repo := &accountTokenGuardV2TestRepo{record: &record} + settings := &accountTokenGuardV2TestSettings{raw: test.raw} + svc := NewAccountTokenGuardV2Service(repo, settings, reader, accountTokenGuardV2TestProber{err: errors.New("invalid token")}, reauth) + t.Cleanup(svc.cancel) + + require.ErrorContains(t, svc.runProbe(context.Background(), record), test.wantError) + + require.Zero(t, reauthRepo.createCalls) + require.Nil(t, repo.completion) + require.Equal(t, 2, repo.record.FailStreak) + require.Equal(t, next, repo.record.NextProbeAt) + require.Nil(t, repo.record.LastProbeAt) + require.Empty(t, repo.record.LeaseOwner) + require.Nil(t, repo.record.LeaseUntil) + }) + } } func TestAccountTokenGuardV2CustomRulesDriveProbe(t *testing.T) { @@ -340,7 +393,7 @@ func TestAccountTokenGuardV2CustomRulesDriveProbe(t *testing.T) { record, err := guardRepo.GetAccount(context.Background(), 42) require.NoError(t, err) - svc.runProbe(context.Background(), *record) + require.NoError(t, svc.runProbe(context.Background(), *record)) require.Equal(t, 1, reauthRepo.createCalls) require.WithinDuration(t, guardRepo.completion.LastProbeAt.Add(45*time.Second), guardRepo.completion.NextProbeAt, time.Second) diff --git a/backend/internal/service/credential_operation_failure_test.go b/backend/internal/service/credential_operation_failure_test.go index d22bd3682b04..dc467d7d8b5d 100644 --- a/backend/internal/service/credential_operation_failure_test.go +++ b/backend/internal/service/credential_operation_failure_test.go @@ -163,7 +163,7 @@ func TestCredentialOperationProbePersistsEvidenceWithoutChangingAccountOrBudget( credentials, err := json.Marshal(reader.account.Credentials) require.NoError(t, err) svc := NewAccountTokenGuardV2Service(repo, nil, reader, accountTokenGuardV2TestProber{err: &codexModelsManifestUpstreamError{err: errors.New("synthetic-private"), statusCode: http.StatusBadRequest, body: fixture.Payload}}, reauth) - svc.runProbe(context.Background(), *repo.record) + require.NoError(t, svc.runProbe(context.Background(), *repo.record)) require.NotNil(t, repo.completion) failure := probeOperationFailure(repo.record.ProbeState, repo.record.ProbeDetail, repo.record.LastProbeAt) require.NotNil(t, failure) diff --git a/backend/internal/service/openai_codex_models_service.go b/backend/internal/service/openai_codex_models_service.go index d39319398f85..e89649713f2e 100644 --- a/backend/internal/service/openai_codex_models_service.go +++ b/backend/internal/service/openai_codex_models_service.go @@ -1738,6 +1738,7 @@ func (s *OpenAIGatewayService) FetchCodexModelsManifest(ctx context.Context, acc } func (s *OpenAIGatewayService) fetchNativeCodexModelsManifest(ctx context.Context, account *Account, clientVersion, ifNoneMatch string) (*OpenAIModelsResponse, error) { + useCache := !isFreshOpenAICredentialProbe(ctx) if account == nil { return nil, infraerrors.New(http.StatusInternalServerError, "OPENAI_CODEX_MODELS_ACCOUNT_REQUIRED", "account is required") } @@ -1838,7 +1839,14 @@ func (s *OpenAIGatewayService) fetchNativeCodexModelsManifest(ctx context.Contex accountConcurrency: account.Concurrency, useAPIKeyUpstream: useAPIKeyUpstream, } + if !useCache { + request.headers.Del("If-None-Match") + request.headers.Set("Cache-Control", "no-cache") + } if useAPIKeyUpstream { + if !useCache { + return s.fetchCodexModelsManifestUpstream(ctx, request, "") + } return s.fetchCachedOpenAIModels(ctx, request, s.fetchCodexModelsManifestUpstreamForRequest(request), ifNoneMatch) } // OAuth 账号同样经过账号级缓存;闭包保留 agent identity 任务恢复逻辑, @@ -1867,6 +1875,12 @@ func (s *OpenAIGatewayService) fetchNativeCodexModelsManifest(ctx context.Contex setOpenAIChatGPTAccountHeaders(request.headers, credAccount) return s.fetchCodexModelsManifestUpstream(fetchCtx, request, ifNoneMatch) } + if !useCache { + // Credential inspection must observe this request's upstream response. + // Neither cached success, stale fallback nor an independent background + // refresh can verify the current token or the current inspection lease. + return oauthFetch(ctx, "") + } return s.fetchCachedOpenAIModels(ctx, request, oauthFetch, ifNoneMatch) } diff --git a/backend/internal/service/openai_credential_probe.go b/backend/internal/service/openai_credential_probe.go new file mode 100644 index 000000000000..ef63a4d7c90c --- /dev/null +++ b/backend/internal/service/openai_credential_probe.go @@ -0,0 +1,47 @@ +package service + +import ( + "context" + "errors" + + infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" +) + +type openAICredentialProbeContextKey struct{} + +func isFreshOpenAICredentialProbe(ctx context.Context) bool { + fresh, _ := ctx.Value(openAICredentialProbeContextKey{}).(bool) + return fresh +} + +// FetchOpenAIModelsListFresh verifies an OAuth parent account against the native +// Codex endpoint. It does not use model-catalog caches or merge Excel/BPS access: +// a separate inference grant cannot establish this parent token's health. +func (s *OpenAIGatewayService) FetchOpenAIModelsListFresh(ctx context.Context, account *Account) (*OpenAIModelsResponse, error) { + if err := ctx.Err(); err != nil { + return nil, err + } + if s == nil || account == nil || !account.IsOpenAIOAuth() || account.IsCredentialShadow() || account.IsOpenAIPersonalAccessToken() || account.IsOpenAIAgentIdentity() { + return nil, infraerrors.BadRequest("OPENAI_CREDENTIAL_PROBE_ACCOUNT_INVALID", "credential inspection requires an OpenAI OAuth parent account") + } + clientVersion := CodexCanonicalClientVersion() + if s.settingService != nil { + clientVersion = s.settingService.GetOpenAICodexClientVersion(ctx) + } + probeCtx := context.WithValue(ctx, openAICredentialProbeContextKey{}, true) + response, err := s.fetchNativeCodexModelsManifest(probeCtx, account, clientVersion, "") + if ctx.Err() != nil { + return nil, ctx.Err() + } + if err != nil { + return nil, err + } + if response == nil || response.NotModified { + return nil, invalidOpenAIModelsList(errors.New("credential inspection requires a current model response")) + } + body, err := standardOpenAIModelsBody(response.Body, true) + if err != nil { + return nil, invalidOpenAIModelsList(err) + } + return &OpenAIModelsResponse{Body: body, ETag: codexModelsManifestBodyETag(body)}, nil +} diff --git a/backend/internal/service/openai_credential_probe_test.go b/backend/internal/service/openai_credential_probe_test.go new file mode 100644 index 000000000000..3e93a0f47819 --- /dev/null +++ b/backend/internal/service/openai_credential_probe_test.go @@ -0,0 +1,237 @@ +package service + +import ( + "context" + "net/http" + "net/http/httptest" + "sync/atomic" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +type credentialProbeHTTPFixture struct { + status atomic.Int32 + calls atomic.Int32 + headers chan http.Header +} + +func newCredentialProbeHTTPFixture(t *testing.T) *credentialProbeHTTPFixture { + t.Helper() + f := &credentialProbeHTTPFixture{headers: make(chan http.Header, 16)} + f.status.Store(http.StatusOK) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, request *http.Request) { + f.calls.Add(1) + f.headers <- request.Header.Clone() + w.Header().Set("Content-Type", "application/json") + w.Header().Set("ETag", `"synthetic-catalog"`) + status := int(f.status.Load()) + w.WriteHeader(status) + switch status { + case http.StatusOK: + _, _ = w.Write([]byte(`{"models":[{"slug":"gpt-6-sol"}]}`)) + case http.StatusUnauthorized: + _, _ = w.Write([]byte(`{"error":{"code":"invalid_token","message":"synthetic-private-provider-response"}}`)) + case http.StatusForbidden: + _, _ = w.Write([]byte(`{"error":{"code":"session_blocked_by_cyber_policy","message":"synthetic-private-provider-response"}}`)) + } + })) + original := chatgptCodexModelsURL + chatgptCodexModelsURL = server.URL + t.Cleanup(func() { + chatgptCodexModelsURL = original + server.Close() + }) + return f +} + +func credentialProbeCacheSize(gateway *OpenAIGatewayService) int { + gateway.openAIModelsCache.mu.Lock() + defer gateway.openAIModelsCache.mu.Unlock() + return len(gateway.openAIModelsCache.entries) +} + +func TestAccountTokenGuardV2FreshProbeBypassesWarmAndStaleSuccess(t *testing.T) { + for _, test := range []struct { + name string + age time.Duration + }{{"warm", 0}, {"stale", 2 * time.Minute}} { + t.Run(test.name, func(t *testing.T) { + upstream := newCredentialProbeHTTPFixture(t) + gateway := &OpenAIGatewayService{} + account := newCodexModelsTestAccount() + _, err := gateway.FetchOpenAIModelsList(context.Background(), account) + require.NoError(t, err) + require.EqualValues(t, 1, upstream.calls.Load()) + if test.age != 0 { + expireCodexModelsManifestCache(gateway, test.age) + } + upstream.status.Store(http.StatusUnauthorized) + response, err := gateway.FetchOpenAIModelsListFresh(context.Background(), account) + require.Nil(t, response) + var rejected *codexModelsManifestUpstreamError + require.ErrorAs(t, err, &rejected) + require.Equal(t, http.StatusUnauthorized, rejected.statusCode) + require.EqualValues(t, 2, upstream.calls.Load(), "every inspection must wait for its own current upstream response") + require.Equal(t, 1, credentialProbeCacheSize(gateway)) + }) + } +} + +func TestAccountTokenGuardV2FreshProbeDoesNotReadOrPublishCatalogCache(t *testing.T) { + upstream := newCredentialProbeHTTPFixture(t) + gateway := &OpenAIGatewayService{} + account := newCodexModelsTestAccount() + fresh, err := gateway.FetchOpenAIModelsListFresh(context.Background(), account) + require.NoError(t, err) + require.Contains(t, string(fresh.Body), `"id":"gpt-6-sol"`) + require.Zero(t, credentialProbeCacheSize(gateway), "an inspection must not publish shared directory evidence") + firstHeaders := <-upstream.headers + require.Empty(t, firstHeaders.Get("If-None-Match")) + require.Equal(t, "no-cache", firstHeaders.Get("Cache-Control")) + require.Equal(t, "Bearer test-access-token", firstHeaders.Get("Authorization")) + require.Equal(t, "acc-123", firstHeaders.Get("ChatGPT-Account-ID")) + + _, err = gateway.FetchOpenAIModelsList(context.Background(), account) + require.NoError(t, err) + _, err = gateway.FetchOpenAIModelsList(context.Background(), account) + require.NoError(t, err) + require.EqualValues(t, 2, upstream.calls.Load(), "ordinary directory callers still share their cached catalog") + ordinaryHeaders := <-upstream.headers + require.Empty(t, ordinaryHeaders.Get("Cache-Control")) + gateway.openAIModelsCache.mu.Lock() + var originalExpiry time.Time + for _, entry := range gateway.openAIModelsCache.entries { + originalExpiry = entry.expiresAt + } + gateway.openAIModelsCache.mu.Unlock() + + _, err = gateway.FetchOpenAIModelsListFresh(context.Background(), account) + require.NoError(t, err) + require.EqualValues(t, 3, upstream.calls.Load()) + secondHeaders := <-upstream.headers + require.Empty(t, secondHeaders.Get("If-None-Match"), "a cached upstream ETag must not turn an inspection into a catalog revalidation") + gateway.openAIModelsCache.mu.Lock() + defer gateway.openAIModelsCache.mu.Unlock() + require.Len(t, gateway.openAIModelsCache.entries, 1) + for _, entry := range gateway.openAIModelsCache.entries { + require.Equal(t, originalExpiry, entry.expiresAt, "inspections must not extend directory cache validity") + } +} + +func TestAccountTokenGuardV2FreshProbeRejectsUnexpectedNotModified(t *testing.T) { + upstream := newCredentialProbeHTTPFixture(t) + gateway := &OpenAIGatewayService{} + account := newCodexModelsTestAccount() + _, err := gateway.FetchOpenAIModelsList(context.Background(), account) + require.NoError(t, err) + upstream.status.Store(http.StatusNotModified) + response, err := gateway.FetchOpenAIModelsListFresh(context.Background(), account) + require.Error(t, err) + require.Nil(t, response, "304 must not reuse a previous inspection result") + _, err = gateway.FetchOpenAIModelsList(context.Background(), account) + require.NoError(t, err, "ordinary model reads retain their existing cache behavior") + require.EqualValues(t, 2, upstream.calls.Load()) +} + +func TestAccountTokenGuardV2FreshProbeCannotUseBPSGrantAsNativeProof(t *testing.T) { + upstream := newCredentialProbeHTTPFixture(t) + upstream.status.Store(http.StatusUnauthorized) + var bpsCalls atomic.Int32 + gateway := openAIClientToolsTestService(nil) + gateway.httpUpstream = &codexModelsHTTPUpstreamStub{do: func(_ *http.Request, _ string, _ int64, _ int) (*http.Response, error) { + bpsCalls.Add(1) + return ordinaryModelsUpstreamResponse(bpsAccessFixture), nil + }} + account := excelAccount() + models, err := gateway.FetchOpenAIModelsList(context.Background(), account) + require.NoError(t, err) + require.Contains(t, string(models.Body), "gpt-7-new") + require.EqualValues(t, 1, bpsCalls.Load()) + require.Zero(t, upstream.calls.Load(), "an all-BPS catalog intentionally does not inspect the native credential") + guard := &AccountTokenGuardV2Service{prober: gateway} + state, detail := guard.probeAccount(context.Background(), account) + require.Equal(t, AccountTokenGuardV2ProbeAuth, state) + require.EqualValues(t, 1, upstream.calls.Load()) + require.EqualValues(t, 1, bpsCalls.Load(), "credential inspection must not consult the separate BPS grant") + require.NotContains(t, detail, "synthetic-private") +} + +func TestAccountTokenGuardV2FreshProbePreserves403PolicyClassification(t *testing.T) { + upstream := newCredentialProbeHTTPFixture(t) + upstream.status.Store(http.StatusForbidden) + guard := &AccountTokenGuardV2Service{prober: &OpenAIGatewayService{}} + state, detail := guard.probeAccount(context.Background(), newCodexModelsTestAccount()) + require.Equal(t, AccountTokenGuardV2ProbeTransient, state) + require.Equal(t, accountTokenGuardV2PolicyBlocked, detail) + require.EqualValues(t, 1, upstream.calls.Load()) +} + +func TestAccountTokenGuardV2FreshProbeCancellationStopsItsUpstreamRequest(t *testing.T) { + started, stopped := make(chan struct{}), make(chan struct{}) + server := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, request *http.Request) { + close(started) + <-request.Context().Done() + close(stopped) + })) + original := chatgptCodexModelsURL + chatgptCodexModelsURL = server.URL + t.Cleanup(func() { + chatgptCodexModelsURL = original + server.Close() + }) + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + gateway := &OpenAIGatewayService{} + done := make(chan error, 1) + go func() { + _, err := gateway.FetchOpenAIModelsListFresh(ctx, newCodexModelsTestAccount()) + done <- err + }() + select { + case <-started: + case <-time.After(3 * time.Second): + t.Fatal("credential inspection did not reach the mock upstream") + } + cancel() + select { + case err := <-done: + require.ErrorIs(t, err, context.Canceled) + case <-time.After(3 * time.Second): + t.Fatal("credential inspection ignored caller cancellation") + } + select { + case <-stopped: + case <-time.After(3 * time.Second): + t.Fatal("a background upstream request survived the cancelled inspection") + } + require.Zero(t, credentialProbeCacheSize(gateway)) +} + +func TestAccountTokenGuardV2FreshProbeCannotResetBudgetUsingCachedSuccess(t *testing.T) { + upstream := newCredentialProbeHTTPFixture(t) + gateway := &OpenAIGatewayService{} + reauth, reader, _, _, _, _ := newReauthTestService("acct-1") + _, err := gateway.FetchOpenAIModelsList(context.Background(), reader.account) + require.NoError(t, err) + finishedAt := time.Now().Add(-time.Minute) + repo := &accountTokenGuardV2TestRepo{ + record: &AccountTokenGuardV2Record{ + AccountID: 42, Enabled: true, AutoReloginEnabled: true, + ReloginFailStreak: 2, AutoReloginExhausted: true, + }, + outcomes: []AccountReloginOutcome{{ID: 7, Status: OpenAIOAuthReauthStatusSucceeded, FinishedAt: &finishedAt}}, + } + upstream.status.Store(http.StatusUnauthorized) + guard := NewAccountTokenGuardV2Service(repo, nil, reader, gateway, reauth) + t.Cleanup(guard.cancel) + view, err := guard.ProbeNow(context.Background(), 42) + require.NoError(t, err) + require.Equal(t, AccountTokenGuardV2ProbeAuth, view.ProbeState) + require.Equal(t, 3, view.ReloginFailStreak, "a currently rejected token cannot clear its previous re-login failures") + require.True(t, view.AutoReloginExhausted) + require.EqualValues(t, 2, upstream.calls.Load()) + require.NotNil(t, view.ProbeFailure) + require.Equal(t, "requires_relogin", view.ProbeFailure.Code) +} diff --git a/docs/account-token-guard-v2.md b/docs/account-token-guard-v2.md index 77a38760b646..86a2380021ff 100644 --- a/docs/account-token-guard-v2.md +++ b/docs/account-token-guard-v2.md @@ -18,10 +18,16 @@ 3. 在账号列表的“运行开关”列即时切换“自动巡检”和“自动重登”,修改即保存;账号编辑弹窗仅保存登录凭据,保留已有开关。自动巡检开关控制后续自动巡检;手动巡检、手动重登仍可使用。暂停或移除巡检账号不会取消已经进入重登队列的任务。 4. 在“巡检规则”页配置间隔、阈值和冷却。默认正常巡检 30 分钟、鉴权失败复检 5 分钟、失败阈值 2 次、重登冷却 30 分钟。保存规则后已启用账号立即重新排期;后台每分钟领取一次到期账号,实际时间有调度误差。 -巡检读取现有 access token,通过现有 OpenAI 模型列表请求判断凭据状态,不发送付费生成请求。401 或明确的令牌拒绝归为鉴权失败;一般 403 归授权拒绝,手机号/安全验证与账号退役不触发自动重登。其余异常归为临时失败。模型列表可访问并不能证明所有生成模型、额度或权限可用。每轮最多领取 10 个账号,轮次预算 90 秒,单次探测预算 30 秒。数据库租约防止多个实例同时巡检同一账号。 +巡检读取母账号现有 access token,使用专用原生 Codex 模型列表鉴权请求,不发送付费生成请求。该路径不读取或回填共享目录缓存,不发送条件 ETag,不使用过期缓存兜底或后台刷新,也不把 BPS 混合目录的成功作为母账号鉴权成功;没有本次有效响应的 304 不计为成功。普通模型目录请求仍使用原缓存。401 或明确的令牌拒绝归为鉴权失败;一般 403 归授权拒绝,手机号/安全验证与账号退役不触发自动重登。其余异常归为临时失败。模型列表可访问并不能证明所有生成模型、额度或权限可用。 + +后台每分钟开始一轮,每个实例使用 3 个独立巡检位,在 90 秒轮次预算内持续处理本轮开始时已到期的账号;每个空闲位只领取 1 个,单次探测预算 30 秒。巡检并发与重登 Worker 并发独立。慢请求仍可能造成积压,页面的“下次巡检”是最早可执行时间,不承诺该时刻完成或所有账号都在一分钟内扫完。 + +每次领取使用独立租约标识,预算核算、自动重登入队及巡检回写均核对本次租约;旧巡检无法覆盖重新领取后的状态。服务取消或巡检规则读取失败时,以独立短超时归还未完成租约,不改变历史巡检结果、失败计数和下次计划;本轮等待清理结束后才退出。停止服务本身不计为账号鉴权失败。正常探测超时仍按原有临时失败处理。 鉴权失败达到阈值且开启自动重登时,创建持久化任务,由独立 Worker 执行。活跃任务的唯一索引防止重复排队。重登成功前校验账号身份及原凭据快照;原子写回新凭据、完成任务、恢复账号调度并写入调度通知。并发手动编辑或令牌刷新后,旧任务不能覆盖新凭据。 +“巡检失败次数”与“重登失败预算”分别计数。页面根据开关、登录资料、活跃任务、失败预算、冷却和鉴权失败阈值显示当前自动恢复阶段;历史巡检异常保留在详情。点击立即巡检或立即重登后立即重新读取状态,不必等待下一次 30 秒页面轮询;规则、账号和运行设置的保存操作互斥,不会打断操作后的回读。冷却截止后,尚未更新的旧冷却原因不再显示为服务不可用。重登任务显示成功后,仍需后续新鲜巡检通过才能证明凭据已恢复。自动重登入队失败的服务日志只记录账号内部编号与固定错误码,不记录上游原文或秘密。 + 通过 2FA 自动登记时使用 password_totp 和账号代理,加密保存密码与 TOTP。首次登录仍复用外部登录服务,之后的自动重登由程序管理的本地 Worker 处理。导入成功但登记失败时,当前弹窗保留登录结果和输入,重试无需再次登录。 账号只要登记在凭证运营中,旧凭证守护就跳过其自动巡检和重登,并拒绝旧页面的手动重登,包括在凭证运营中暂停的账号。删除凭证运营登记后,账号才可能再次进入旧守护所配置的范围,旧守护仍需自己的登录资料。 diff --git a/frontend/src/i18n/locales/en/tokenGuardV2.ts b/frontend/src/i18n/locales/en/tokenGuardV2.ts index 1a1c769c41fb..30c8bd11de73 100644 --- a/frontend/src/i18n/locales/en/tokenGuardV2.ts +++ b/frontend/src/i18n/locales/en/tokenGuardV2.ts @@ -36,6 +36,22 @@ export default { } }, reloginBudgetCount: 'Re-login failure budget: {count}/{limit}', + lastInspectionFailure: 'Last inspection failure (history)', + automationStates: { + paused: 'Automatic inspections paused', + disabled: 'Automatic re-login disabled; inspections continue', + configuration: 'Login configuration is incomplete; automatic re-login unavailable', + queued: 'Re-login task queued', + running: 'Re-login in progress; waiting for the task to finish', + verifying: 'New credentials saved; waiting for a later inspection to verify them', + cooldown: 'Automatic re-login cooling down until {until}', + blocked: 'Automatic recovery is unavailable; review the service status and failure details', + waiting: 'Authentication failure confirmation: {count}/{limit}; waiting for the next inspection', + scheduled: 'Re-login threshold reached; waiting for automatic processing', + healthy: 'Latest inspection accepted the credentials', + retryInspection: 'Waiting for the next inspection retry', + inspectionPending: 'Waiting for the first inspection' + }, reloginBudgetExhausted: 'Automatic re-login exhausted; inspections continue', reloginBackoffUntil: 'Re-login cooldown until', resumeReloginBudget: 'Restore budget (no immediate login)', diff --git a/frontend/src/i18n/locales/zh/tokenGuardV2.ts b/frontend/src/i18n/locales/zh/tokenGuardV2.ts index 170a152438e0..de08f367d581 100644 --- a/frontend/src/i18n/locales/zh/tokenGuardV2.ts +++ b/frontend/src/i18n/locales/zh/tokenGuardV2.ts @@ -36,6 +36,22 @@ export default { } }, reloginBudgetCount: '重登失败预算:{count}/{limit}', + lastInspectionFailure: '上次巡检异常(历史记录)', + automationStates: { + paused: '自动巡检已暂停', + disabled: '自动重登已关闭,巡检继续', + configuration: '登录配置不完整,无法自动重登', + queued: '重登任务已排队', + running: '正在重登,等待任务完成', + verifying: '新凭据已保存,等待后续巡检验证', + cooldown: '自动重登冷却至 {until}', + blocked: '自动恢复暂不可用,请查看服务状态与异常详情', + waiting: '鉴权失败确认:{count}/{limit},等待下一次巡检', + scheduled: '已达到重登阈值,等待自动处理', + healthy: '最近巡检鉴权通过', + retryInspection: '等待下一次巡检重试', + inspectionPending: '等待首次巡检' + }, reloginBudgetExhausted: '自动重登预算已耗尽,巡检继续', reloginBackoffUntil: '重登冷却至', resumeReloginBudget: '恢复预算(不立即重登)', diff --git a/frontend/src/views/admin/ops/TokenGuardV2View.vue b/frontend/src/views/admin/ops/TokenGuardV2View.vue index f4771c010891..a1ddc6f737ef 100644 --- a/frontend/src/views/admin/ops/TokenGuardV2View.vue +++ b/frontend/src/views/admin/ops/TokenGuardV2View.vue @@ -9,10 +9,10 @@{{ t('tokenGuardV2.description') }}
{{ t('tokenGuardV2.ruleScopeHint') }}