Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 36 additions & 1 deletion .github/scripts/oauth-initial-model-selection-browser.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -94,8 +94,20 @@ try {
const scope = page.getByTestId('initial-model-selection')
const initialSection = page.getByTestId('initial-enabled').locator('xpath=ancestor::section')
const rotation = page.getByTestId('totp-rotate-on-429')
const disableScheduling = page.getByTestId('disable-scheduling-on-429')
assert.equal(await rotation.isChecked(), false)
assert.equal(await disableScheduling.isChecked(), false)
await initialSection.screenshot({ path: path.join(output, '429-off-desktop-zh.png') })
// The scheduling policy is independent of credential rotation. Exercise the
// real checkbox, API payload and reloaded page; do not infer this from labels.
await disableScheduling.check()
await save()
assert.equal(saved.openai_disable_scheduling_on_429, true)
assert.equal(saved.openai_totp_rotate_on_429, false)
await page.reload({ waitUntil: 'networkidle' })
assert.equal(await disableScheduling.isChecked(), true)
assert.equal(await rotation.isChecked(), false)
await initialSection.screenshot({ path: path.join(output, 'scheduling429-only-desktop-zh.png') })
assert.equal(await page.getByTestId('model-selection-enabled').isChecked(), false)
await scope.screenshot({ path: path.join(output, 'unset-desktop-zh.png') })
await page.getByTestId('model-selection-enabled').check()
Expand All @@ -104,6 +116,7 @@ try {
await save()
assert(saved.selected_models.includes('gpt-6.1-sol')); assert(!saved.selected_models.includes('gpt-6-luna'))
assert.equal(saved.openai_totp_rotate_on_429, true)
assert.equal(saved.openai_disable_scheduling_on_429, true)
await initialSection.screenshot({ path: path.join(output, '429-and-selection-desktop-zh.png') })
await scope.screenshot({ path: path.join(output, 'excluded-luna-desktop-zh.png') })
await page.setViewportSize({ width: 390, height: 1000 })
Expand All @@ -112,15 +125,25 @@ try {
assert(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth))
await page.reload({ waitUntil: 'networkidle' })
assert.equal(await rotation.isChecked(), true)
assert.equal(await disableScheduling.isChecked(), true)
assert.equal(await scope.locator('[data-model="gpt-6-luna"]').isChecked(), false)
await initialSection.screenshot({ path: path.join(output, '429-reloaded-mobile-zh.png') })
await disableScheduling.uncheck()
await save()
assert.equal(saved.openai_disable_scheduling_on_429, false)
assert.equal(saved.openai_totp_rotate_on_429, true)
await page.reload({ waitUntil: 'networkidle' })
assert.equal(await disableScheduling.isChecked(), false)
assert.equal(await rotation.isChecked(), true)
await disableScheduling.check()
await page.getByTestId('model-selection-none').click()
await page.getByTestId('model-selection-empty').waitFor()
await save(); assert.deepEqual(saved.selected_models, [])
await scope.screenshot({ path: path.join(output, 'none-mobile-zh.png') })
await page.getByTestId('model-selection-enabled').uncheck(); await save(); assert.equal(saved.selected_models, null)
await page.getByTestId('platform').selectOption('anthropic')
assert.equal(await rotation.count(), 0)
assert.equal(await disableScheduling.count(), 0)
await page.getByTestId('initial-group-6').check()
await page.getByTestId('model-selection-enabled').check()
assert.equal(await scope.locator('[data-model="gpt-6-luna"]').count(), 0)
Expand All @@ -129,11 +152,23 @@ try {
await page.getByTestId('model-selection-add').click(); await save()
assert(saved.selected_models.includes('custom-model'))
assert.equal(saved.openai_totp_rotate_on_429, false)
assert.equal(saved.openai_disable_scheduling_on_429, false)
await page.setViewportSize({ width: 1280, height: 1000 })
await open('?lang=en')
await scope.screenshot({ path: path.join(output, 'anthropic-custom-desktop-en.png') })
await page.getByTestId('platform').selectOption('openai')
await page.getByTestId('initial-group-5').check()
assert.equal(await disableScheduling.isChecked(), false)
await disableScheduling.check()
await save()
assert.equal(saved.openai_disable_scheduling_on_429, true)
assert.equal(saved.openai_totp_rotate_on_429, false)
await initialSection.screenshot({ path: path.join(output, 'scheduling429-only-desktop-en.png') })
await page.setViewportSize({ width: 390, height: 1000 })
await initialSection.screenshot({ path: path.join(output, 'scheduling429-only-mobile-en.png') })
assert(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth))
assert.deepEqual(errors, []); assert.deepEqual(external, [])
await fs.writeFile(path.join(output, 'verification.json'), JSON.stringify({ head, baselineSHA, synthetic: true, actualPage: 'AutoConfigView.vue', actualComponent: 'OAuthInitialModelSelection.vue', cssRoot: frontend, checks: ['old template before screenshot', 'unset', 'select catalog and exclude Luna', 'save and reload', 'empty explicitly denies all', 'turn off null', '429 opt-in and model selection save/reload together', '429 desktop/mobile screenshots', 'platform switch clears both options', 'custom exact name', 'desktop and mobile', 'no horizontal overflow', 'zh and en', 'no external requests'], requests, saves, errors, external }, null, 2))
await fs.writeFile(path.join(output, 'verification.json'), JSON.stringify({ head, baselineSHA, synthetic: true, actualPage: 'AutoConfigView.vue', actualComponent: 'OAuthInitialModelSelection.vue', cssRoot: frontend, checks: ['old template before screenshot', 'unset', 'select catalog and exclude Luna', 'save and reload', 'empty explicitly denies all', 'turn off null', '429 scheduling policy independent of rotation; both save/reload together', '429 scheduling opt-out preserves rotation after reload', '429 desktop/mobile screenshots', 'platform switch clears both 429 policies', 'custom exact name', 'desktop and mobile', 'no horizontal overflow', 'zh and en', 'no external requests'], requests, saves, errors, external }, null, 2))
} catch (error) {
await fs.writeFile(path.join(output, 'failure.json'), JSON.stringify({ head, error: String(error), errors, external, requests }, null, 2)); throw error
} finally { await browser.close(); await server.close(); await fs.rm(baselinePath, { force: true }) }
67 changes: 67 additions & 0 deletions backend/internal/handler/admin/account_auto_config_429_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
//go:build unit

package admin

import (
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"

"github.com/Wei-Shaw/sub2api/internal/config"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)

func TestAutoConfigDisableScheduling429SaveAndLegacyClient(t *testing.T) {
gin.SetMode(gin.TestMode)
original := service.DefaultOAuthAutoConfig()
raw, err := json.Marshal(original)
require.NoError(t, err)
repo := &opsHandlerWritableSettings{raw: string(raw)}
cfg := &config.Config{}
cfg.Runtime.Role = config.RuntimeRoleGateway
svc := service.ProvideAccountOpsService(repo, opsHandlerQueue{}, nil, nil, modelBillingHandlerGroups{}, cfg, nil, nil, nil, nil, nil)
svc.Stop()
handler := NewAccountOpsHandler(svc, nil)
router := gin.New()
router.PUT("/config", handler.SaveAutoConfig)
router.GET("/config", handler.GetAutoConfig)
for _, tc := range []struct {
name string
body string
status int
disable bool
rotateTOTP bool
}{
{"enable both", `{"openai_disable_scheduling_on_429":true,"openai_totp_rotate_on_429":true}`, http.StatusOK, true, true},
{"old client omits flags", `{"priority":6}`, http.StatusOK, true, true},
{"disable rotation independently", `{"openai_totp_rotate_on_429":false}`, http.StatusOK, true, false},
{"reject non boolean", `{"openai_disable_scheduling_on_429":"true"}`, http.StatusBadRequest, true, false},
{"explicit opt out", `{"openai_disable_scheduling_on_429":false}`, http.StatusOK, false, false},
} {
t.Run(tc.name, func(t *testing.T) {
before := repo.raw
written := httptest.NewRecorder()
request := httptest.NewRequest(http.MethodPut, "/config", strings.NewReader(tc.body))
request.Header.Set("Content-Type", "application/json")
router.ServeHTTP(written, request)
require.Equal(t, tc.status, written.Code, written.Body.String())
if tc.status != http.StatusOK {
require.Equal(t, before, repo.raw, "invalid values must not change stored settings")
}
read := httptest.NewRecorder()
router.ServeHTTP(read, httptest.NewRequest(http.MethodGet, "/config", nil))
require.Equal(t, http.StatusOK, read.Code)
var payload struct {
Data service.OAuthAutoConfig `json:"data"`
}
require.NoError(t, json.Unmarshal(read.Body.Bytes(), &payload))
require.Equal(t, tc.disable, payload.Data.OpenAIDisableSchedulingOn429)
require.Equal(t, tc.rotateTOTP, payload.Data.OpenAITOTPRotateOn429)
require.Equal(t, original.ExcelBPS, payload.Data.ExcelBPS)
})
}
}
7 changes: 4 additions & 3 deletions backend/internal/repository/account_repo.go
Original file line number Diff line number Diff line change
Expand Up @@ -1178,8 +1178,9 @@ func (r *accountRepository) UpdateCredentials(ctx context.Context, id int64, cre
// account still has the credential snapshot captured before protocol login.
// Re-authentication may take several minutes; the expected-value guard keeps a
// concurrent manual edit or token refresh from being overwritten by a stale
// callback. Successful swaps also restore the account's active/schedulable
// state and clear transient scheduling quarantine.
// callback. Successful swaps also restore the account's active state and clear
// transient scheduling quarantine. Admission and 429 scheduling policies retain
// the existing scheduling switch.
func (r *accountRepository) ApplyOpenAIOAuthReauth(
ctx context.Context,
taskID int64,
Expand Down Expand Up @@ -1226,7 +1227,7 @@ func (r *accountRepository) ApplyOpenAIOAuthReauth(
expires_at = COALESCE($14::timestamptz, a.expires_at),
status = $5,
error_message = '',
schedulable = CASE WHEN a.extra ? 'openai_two_fa_admission' THEN a.schedulable ELSE TRUE END,
schedulable = CASE WHEN a.extra ? 'openai_two_fa_admission' OR a.extra @> '{"openai_disable_scheduling_on_429":true}'::jsonb THEN a.schedulable ELSE TRUE END,
rate_limited_at = NULL,
rate_limit_reset_at = NULL,
overload_until = NULL,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ func TestAccountRepositoryApplyOpenAIOAuthReauthIsAtomic(t *testing.T) {
require.Contains(t, query, "task.worker_id = $10")
require.Contains(t, query, "expires_at = COALESCE($14::timestamptz, a.expires_at)")
require.Contains(t, query, "status = $5")
require.Contains(t, query, "schedulable = CASE WHEN a.extra ? 'openai_two_fa_admission' THEN a.schedulable ELSE TRUE END")
require.Contains(t, query, `schedulable = CASE WHEN a.extra ? 'openai_two_fa_admission' OR a.extra @> '{"openai_disable_scheduling_on_429":true}'::jsonb THEN a.schedulable ELSE TRUE END`)
require.Contains(t, query, "rate_limited_at = NULL")
require.Contains(t, query, "rate_limit_reset_at = NULL")
require.Contains(t, query, "overload_until = NULL")
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
//go:build integration

package repository

import (
"context"
"testing"

"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/stretchr/testify/require"
)

func TestOpenAIReauthPreserves429SchedulingPolicy(t *testing.T) {
for _, tc := range []struct {
name string
extra map[string]any
before bool
want bool
}{
{name: "legacy paused account", want: true},
{name: "opted out", extra: map[string]any{service.OpenAIDisableSchedulingOn429ExtraKey: false}, want: true},
{name: "429 paused account", extra: map[string]any{service.OpenAIDisableSchedulingOn429ExtraKey: true}},
{name: "opted in active account", extra: map[string]any{service.OpenAIDisableSchedulingOn429ExtraKey: true}, before: true, want: true},
{name: "string flag is not enabled", extra: map[string]any{service.OpenAIDisableSchedulingOn429ExtraKey: "true"}, want: true},
{name: "admission still preserved", extra: map[string]any{service.OpenAITwoFAAdmissionExtraKey: map[string]any{"state": "pending"}}},
} {
t.Run(tc.name, func(t *testing.T) {
ctx := context.Background()
tx := testEntTx(t)
repo := newAccountRepositoryWithSQL(tx.Client(), tx, nil)
old := map[string]any{"access_token": "old", "refresh_token": "old-rt"}
a := mustCreateAccount(t, tx.Client(), &service.Account{
Name: "reauth-scheduling", Platform: service.PlatformOpenAI,
Type: service.AccountTypeOAuth, Credentials: old, Extra: tc.extra,
})
require.NoError(t, tx.Client().Account.UpdateOneID(a.ID).SetSchedulable(tc.before).Exec(ctx))
rows, err := tx.Client().QueryContext(ctx, `INSERT INTO openai_oauth_reauth_tasks
(account_id,status,stage,expected_credentials_hash,worker_id)
VALUES ($1,$2,$3,'synthetic-hash','worker') RETURNING id`,
a.ID, service.OpenAIOAuthReauthStatusCallbackProcessing, service.OpenAIOAuthReauthStageApplyingCredentials)
require.NoError(t, err)
t.Cleanup(func() { _ = rows.Close() })
require.True(t, rows.Next(), "the callback task must be created in the account transaction")
var taskID int64
require.NoError(t, rows.Scan(&taskID))
require.NoError(t, rows.Err())
require.NoError(t, rows.Close())

applied, err := repo.ApplyOpenAIOAuthReauth(ctx, taskID, "worker", a.ID, old,
map[string]any{"access_token": "new", "refresh_token": "new-rt"}, nil)
require.NoError(t, err)
require.True(t, applied)
current, err := repo.GetByID(ctx, a.ID)
require.NoError(t, err)
require.Equal(t, tc.want, current.Schedulable)
require.Equal(t, "new", current.Credentials["access_token"], "preserving the scheduling switch must not block credential replacement")
})
}
}
46 changes: 24 additions & 22 deletions backend/internal/service/oauth_auto_config.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,28 +18,29 @@ const AutoConfigConcurrencyExtraKey = "auto_config_concurrency"

// Initial account fields, BPS defaults, model billing and concurrency upgrades are independent.
type OAuthAutoConfig struct {
OpenAITwoFAAdmission OpenAITwoFAAdmissionConfig `json:"openai_two_fa_admission"`
OpenAITOTPRotateOn429 bool `json:"openai_totp_rotate_on_429"`
QualityRule *OAuthInitialQualityRule `json:"quality_rule,omitempty"`
ModelMappings []OAuthModelMappingRule `json:"model_mappings"`
SelectedModels []string `json:"selected_models"`
ModelBilling ModelBillingConfig `json:"model_billing"`
ExcelBPS ExcelBPSDefaults `json:"excel_bps"`
UpdatedAt time.Time `json:"updated_at"`
Enabled bool `json:"enabled"`
Platform string `json:"platform"`
Priority int `json:"priority"`
LoadFactor int `json:"load_factor"`
Concurrency int `json:"concurrency"`
GroupIDs []int64 `json:"group_ids"`
UpgradeEnabled bool `json:"upgrade_enabled"`
UpgradeGroupIDs []int64 `json:"upgrade_group_ids"`
SuccessesPerStep int `json:"successes_per_step"`
UpgradeStep int `json:"upgrade_step"`
MaxConcurrency int `json:"max_concurrency"`
CooldownSeconds int `json:"cooldown_seconds"`
CostMultiplier float64 `json:"cost_multiplier"`
Revision string `json:"revision"`
OpenAITwoFAAdmission OpenAITwoFAAdmissionConfig `json:"openai_two_fa_admission"`
OpenAITOTPRotateOn429 bool `json:"openai_totp_rotate_on_429"`
OpenAIDisableSchedulingOn429 bool `json:"openai_disable_scheduling_on_429"`
QualityRule *OAuthInitialQualityRule `json:"quality_rule,omitempty"`
ModelMappings []OAuthModelMappingRule `json:"model_mappings"`
SelectedModels []string `json:"selected_models"`
ModelBilling ModelBillingConfig `json:"model_billing"`
ExcelBPS ExcelBPSDefaults `json:"excel_bps"`
UpdatedAt time.Time `json:"updated_at"`
Enabled bool `json:"enabled"`
Platform string `json:"platform"`
Priority int `json:"priority"`
LoadFactor int `json:"load_factor"`
Concurrency int `json:"concurrency"`
GroupIDs []int64 `json:"group_ids"`
UpgradeEnabled bool `json:"upgrade_enabled"`
UpgradeGroupIDs []int64 `json:"upgrade_group_ids"`
SuccessesPerStep int `json:"successes_per_step"`
UpgradeStep int `json:"upgrade_step"`
MaxConcurrency int `json:"max_concurrency"`
CooldownSeconds int `json:"cooldown_seconds"`
CostMultiplier float64 `json:"cost_multiplier"`
Revision string `json:"revision"`
}

func DefaultOAuthAutoConfig() OAuthAutoConfig {
Expand Down Expand Up @@ -195,6 +196,7 @@ func (s *adminServiceImpl) ApplyOAuthAutoConfig(ctx context.Context, input *Crea
input.Extra[AccountCostMultiplierExtraKey] = c.CostMultiplier
if input.Platform == PlatformOpenAI {
input.Extra[OpenAITOTPRotateOn429ExtraKey] = c.OpenAITOTPRotateOn429
input.Extra[OpenAIDisableSchedulingOn429ExtraKey] = c.OpenAIDisableSchedulingOn429
}
return nil
}
Expand Down
Loading
Loading