From 185f9c992000b69dc6441871a8a7c86e1be054a6 Mon Sep 17 00:00:00 2001 From: DaydreamCoding <22166516+DaydreamCoding@users.noreply.github.com> Date: Tue, 30 Jun 2026 12:38:06 +0800 Subject: [PATCH] =?UTF-8?q?fix(auth-signup):=20=E5=B9=B3=E5=8F=B0=E9=85=8D?= =?UTF-8?q?=E9=A2=9D=E5=BF=AB=E7=85=A7=E8=84=B1=E7=A6=BB=E6=B3=A8=E5=86=8C?= =?UTF-8?q?=E4=BA=8B=E5=8A=A1=20+=20grok=20=E8=A1=A5=E5=85=A5=20CHECK=20?= =?UTF-8?q?=E7=BA=A6=E6=9D=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 自助注册(含钉钉/OAuth)报 500→404 的根因:grok 自 2026-06 进入默认平台配额 (default_platform_quotas / auth_source_*),但 user_platform_quotas 的 CHECK 约束(迁移 142)仅允许 anthropic/openai/gemini/antigravity。注册时 snapshotPlatformQuotaDefaults 写 grok 行违反约束 → 整个注册事务被 Postgres 标记 aborted → consumePendingOAuthBrowserSessionTx 撞 "transaction aborted" → 500 → clearCookies → 用户重试拿到 404(PENDING_AUTH_SESSION_NOT_FOUND)。 影响面:所有新自助注册(不限钉钉)。 修复(两层): - 事务隔离(fix①):snapshotPlatformQuotaDefaults 用 ent.WithoutTx 剥离调用方事务, 在基础连接 autocommit 执行。best-effort 快照失败永不毒化注册主事务,从根上消除 "事务内 fail-open 形同虚设"陷阱——今后任何平台/约束漂移都不会再连累注册。 - 迁移 157:把 grok 加入 user_platform_quotas.platform 的 CHECK 约束,与代码平台 列表(domain/constants.go PlatformGrok)对齐(DROP IF EXISTS + ADD,可重入)。 新增 ent.WithoutTx(ctx) helper(手写文件,不动生成代码)。 测试: - 单测 TestSnapshotPlatformQuotaDefaults_DetachesCallerTransaction(RED→GREEN): 快照即便在事务 ctx 中也必须用脱离事务的 ctx 调 repo。 - 集成测试 TestUserPlatformQuotaRepository_BulkInsertInitial_GrokAllowed: 迁移 157 后 grok 可写入(真实 postgres 容器验证)。 验证:go build ./... / go vet -tags unit ./... / 全量单测(-tags unit,45 包) / 平台配额+迁移集成测试 全绿。 Co-Authored-By: Claude Opus 4.8 --- backend/ent/tx_context.go | 17 +++++++++ ...er_platform_quota_repo_integration_test.go | 26 +++++++++++++ backend/internal/service/auth_service.go | 5 +++ .../auth_service_platform_quota_test.go | 37 ++++++++++++++++++- .../157_user_platform_quotas_add_grok.sql | 16 ++++++++ 5 files changed, 100 insertions(+), 1 deletion(-) create mode 100644 backend/ent/tx_context.go create mode 100644 backend/migrations/157_user_platform_quotas_add_grok.sql diff --git a/backend/ent/tx_context.go b/backend/ent/tx_context.go new file mode 100644 index 0000000000..c722ddc146 --- /dev/null +++ b/backend/ent/tx_context.go @@ -0,0 +1,17 @@ +package ent + +import "context" + +// WithoutTx 返回一个剥离了所附 *Tx 的 ctx 副本,使调用方可以在基础 client +// (autocommit)上执行 best-effort、非关键的副作用,而不加入——也就不会毒化—— +// 外层事务。 +// +// Postgres 语义:事务内任一语句失败即把整个事务标记为 aborted,后续语句全部被拒, +// 直到 ROLLBACK。因此对 fail-open 的副作用(如注册时的默认平台配额快照)必须做事务 +// 隔离,否则一条无关紧要的写入失败会连累调用方的关键事务。 +func WithoutTx(ctx context.Context) context.Context { + if TxFromContext(ctx) == nil { + return ctx + } + return context.WithValue(ctx, txCtxKey{}, (*Tx)(nil)) +} diff --git a/backend/internal/repository/user_platform_quota_repo_integration_test.go b/backend/internal/repository/user_platform_quota_repo_integration_test.go index 39e2f6e0ba..4a8d1b5896 100644 --- a/backend/internal/repository/user_platform_quota_repo_integration_test.go +++ b/backend/internal/repository/user_platform_quota_repo_integration_test.go @@ -72,6 +72,32 @@ func TestUserPlatformQuotaRepository_BulkInsertInitial_Empty(t *testing.T) { require.NoError(t, repo.BulkInsertInitial(txCtx, []UserPlatformQuotaRecord{})) } +// TestUserPlatformQuotaRepository_BulkInsertInitial_GrokAllowed 回归迁移 157: +// grok 平台必须能写入 user_platform_quotas(CHECK 约束已含 grok)。 +// 历史 bug:grok 不在约束内 → 注册写默认配额违约 → 注册事务 aborted → 自助注册 500/404。 +func TestUserPlatformQuotaRepository_BulkInsertInitial_GrokAllowed(t *testing.T) { + ctx := context.Background() + tx := testEntTx(t) + txCtx := dbent.NewTxContext(ctx, tx) + client := tx.Client() + + userID := mustCreateUserForQuota(t, client) + repo := NewUserPlatformQuotaRepository(client) + + daily := 9.0 + records := []UserPlatformQuotaRecord{ + {UserID: userID, Platform: "grok", DailyLimitUSD: &daily}, + } + require.NoError(t, repo.BulkInsertInitial(txCtx, records), + "grok 平台应可写入(迁移 157 后 CHECK 约束已含 grok)") + + rec, err := repo.GetByUserPlatform(txCtx, userID, "grok") + require.NoError(t, err) + require.NotNil(t, rec, "grok 配额行应已写入") + require.NotNil(t, rec.DailyLimitUSD) + require.InDelta(t, 9.0, *rec.DailyLimitUSD, 1e-9) +} + func TestUserPlatformQuotaRepository_GetByUserPlatform(t *testing.T) { ctx := context.Background() tx := testEntTx(t) diff --git a/backend/internal/service/auth_service.go b/backend/internal/service/auth_service.go index 0be249d415..2849ddfc2f 100644 --- a/backend/internal/service/auth_service.go +++ b/backend/internal/service/auth_service.go @@ -1665,6 +1665,11 @@ func (s *AuthService) snapshotPlatformQuotaDefaults(ctx context.Context, userID if s.userPlatformQuotaRepo == nil || plan == nil || len(plan.PlatformQuotas) == 0 { return nil } + // 平台配额快照是 best-effort(fail-open):必须脱离调用方事务执行。 + // 否则某平台违反 user_platform_quotas 的 CHECK 约束(如尚未进约束的新平台)会让 + // 整个调用方事务被 Postgres 标记 aborted,把"无关紧要的默认配额快照"放大成 + // "整笔注册失败"(OAuth pending 路径曾因此 500 → 清 cookie → 404)。 + ctx = dbent.WithoutTx(ctx) records := make([]UserPlatformQuotaRecord, 0, len(plan.PlatformQuotas)) for platform, q := range plan.PlatformQuotas { rec := UserPlatformQuotaRecord{ diff --git a/backend/internal/service/auth_service_platform_quota_test.go b/backend/internal/service/auth_service_platform_quota_test.go index 46069814b0..31e2b21677 100644 --- a/backend/internal/service/auth_service_platform_quota_test.go +++ b/backend/internal/service/auth_service_platform_quota_test.go @@ -7,19 +7,23 @@ import ( "fmt" "testing" "time" + + dbent "github.com/Wei-Shaw/sub2api/ent" ) // fakeInsertRecorder 记录 BulkInsertInitial 调用,实现 UserPlatformQuotaRepository port。 type fakeInsertRecorder struct { records []UserPlatformQuotaRecord err error + lastCtx context.Context // 捕获最后一次 BulkInsertInitial 收到的 ctx(用于断言事务隔离) } func (f *fakeInsertRecorder) GetByUserPlatform(_ context.Context, _ int64, _ string) (*UserPlatformQuotaRecord, error) { return nil, nil } -func (f *fakeInsertRecorder) BulkInsertInitial(_ context.Context, recs []UserPlatformQuotaRecord) error { +func (f *fakeInsertRecorder) BulkInsertInitial(ctx context.Context, recs []UserPlatformQuotaRecord) error { + f.lastCtx = ctx if f.err != nil { return f.err } @@ -77,6 +81,37 @@ func TestSnapshotPlatformQuotaDefaults_PassesToRepoBulkInsert(t *testing.T) { } } +// TestSnapshotPlatformQuotaDefaults_DetachesCallerTransaction 锁定 fix① 不变量: +// 平台配额快照是 best-effort,必须脱离调用方事务执行——这样它失败(例如某平台 +// 违反 user_platform_quotas 的 CHECK 约束)也不会把调用方的注册主事务标记为 aborted。 +// 历史 bug:snapshot 在 OAuth pending handler 的 binding tx 中执行,grok 违约毒化整个 +// 事务 → consumePendingOAuthBrowserSessionTx 撞 "transaction aborted" → 500 → 清 cookie → 404。 +func TestSnapshotPlatformQuotaDefaults_DetachesCallerTransaction(t *testing.T) { + fakeRepo := &fakeInsertRecorder{} + s := &AuthService{userPlatformQuotaRepo: fakeRepo} + + five := 5.0 + plan := &signupGrantPlan{ + PlatformQuotas: map[string]*DefaultPlatformQuotaSetting{ + "anthropic": {DailyLimitUSD: &five}, + }, + } + + // 模拟调用方(OAuth pending handler)在事务 ctx 中调用快照 + txCtx := dbent.NewTxContext(context.Background(), &dbent.Tx{}) + + if err := s.snapshotPlatformQuotaDefaults(txCtx, 999, plan); err != nil { + t.Fatalf("snapshot should not error (fail-open): %v", err) + } + + if fakeRepo.lastCtx == nil { + t.Fatal("expected BulkInsertInitial to be called") + } + if dbent.TxFromContext(fakeRepo.lastCtx) != nil { + t.Error("快照必须脱离调用方事务执行(best-effort,失败不得毒化注册事务),但 repo 收到了仍携带事务的 ctx") + } +} + func TestSnapshotPlatformQuotaDefaults_NilPlanIsNoop(t *testing.T) { fakeRepo := &fakeInsertRecorder{} s := &AuthService{userPlatformQuotaRepo: fakeRepo} diff --git a/backend/migrations/157_user_platform_quotas_add_grok.sql b/backend/migrations/157_user_platform_quotas_add_grok.sql new file mode 100644 index 0000000000..8c9430b976 --- /dev/null +++ b/backend/migrations/157_user_platform_quotas_add_grok.sql @@ -0,0 +1,16 @@ +-- 把 grok 平台加入 user_platform_quotas.platform 的 CHECK 约束。 +-- +-- 背景:grok 自 2026-06 起进入默认平台配额(default_platform_quotas / +-- auth_source_default_*_platform_quotas),但 142 建表时的 CHECK 仅允许 +-- anthropic/openai/gemini/antigravity。自助注册时 snapshotPlatformQuotaDefaults +-- 会写入 grok 默认配额行 → 违反 CHECK → 整个注册事务被标记 aborted → +-- OAuth pending 路径 consume 会话时撞 "transaction aborted" → 500 → 清 cookie → 404。 +-- +-- 修复:把约束与代码平台列表(internal/domain/constants.go 的 PlatformGrok)对齐。 +-- DROP ... IF EXISTS 保证可重入;新约束是旧约束的超集,存量行(仅 4 平台)瞬时校验通过。 +ALTER TABLE user_platform_quotas + DROP CONSTRAINT IF EXISTS user_platform_quotas_platform_check; + +ALTER TABLE user_platform_quotas + ADD CONSTRAINT user_platform_quotas_platform_check + CHECK (platform IN ('anthropic', 'openai', 'gemini', 'antigravity', 'grok'));