Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
fix(auth): close anonymous email enumeration and mail relay (T12) (#21290)
Danny Xu4a80dac02367
diff --git a/AGENTS.md b/AGENTS.mdindex 06e3c708c0..753dfd911c 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -138,6 +138,7 @@ psql -U bbdev bbdev- Write clean, minimal code; fewer lines is better- Prioritize simplicity for effective and maintainable software- Only include comments that are essential to understanding functionality or convey non-obvious information+- Keep comments short while preserving necessary information### Godiff --git a/backend/api/v1/auth_service.go b/backend/api/v1/auth_service.goindex 4668fd5812..6b7d7ffcdd 100644--- a/backend/api/v1/auth_service.go+++ b/backend/api/v1/auth_service.go@@ -294,44 +294,59 @@ func (s *AuthService) Signup(ctx context.Context, req *connect.Request[v1pb.Signreturn nil, err}- // Check if principal already exists.- existingUser, err := s.store.GetUserByEmail(ctx, email)+ // Whether signup is allowed at all never depends on the address, so decide it+ // without reading anything the address selects. Otherwise a registered+ // account and a stranger reach the same denial by different amounts of work+ // and are told apart by latency: SaaS refuses every signup outright, and+ // self-hosted takes its restriction from the singleton workspace, while+ // resolving by email costs one query for a member and two for a stranger.+ if s.profile.SaaS {+ return nil, connect.NewError(connect.CodePermissionDenied, errors.Errorf("sign up is disallowed for this workspace"))+ }+ workspaceID, err := s.store.GetWorkspaceID(ctx)if err != nil {- return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to find user by email"))+ return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to resolve workspace"))}- if existingUser != nil {- return nil, connect.NewError(connect.CodeAlreadyExists, errors.Errorf("email %s is already registered", request.Email))+ // Announce it on every exit path so denied signups still produce audit entries.+ common.SetAuditWorkspaceID(ctx, workspaceID)++ restriction, err := getAccountRestriction(ctx, s.store, s.licenseService, s.profile.SaaS, workspaceID)+ if err != nil {+ return nil, err+ }+ if restriction.DisallowSignup {+ return nil, connect.NewError(connect.CodePermissionDenied, errors.Errorf("sign up is disallowed for this workspace"))}- // Resolve the target workspace (read-only) so we can check restrictions BEFORE- // any write — otherwise a rejected signup would leave an orphan user/workspace behind.+ // Past the gates the address matters: resolve where it would land, read-only,+ // so a rejected signup leaves no orphan user or workspace behind.targetWorkspaceID, targetIsMember, err := s.resolveWorkspaceIDByEmail(ctx, email, "")if err != nil {return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to resolve target workspace"))}- // Announce the workspace on every exit path so denied signups (DisallowSignup,- // password restriction) still produce audit entries. Uses targetWorkspaceID (resolved- // before any writes) rather than the provisioned workspaceID.- defer func() { common.SetAuditWorkspaceID(ctx, targetWorkspaceID) }()-- restriction, err := getAccountRestriction(- ctx,- s.store,- s.licenseService,- s.profile.SaaS,- targetWorkspaceID,- )+ // Existence is checked only once the workspace would accept a signup at all.+ // Answering AlreadyExists ahead of that gate makes a workspace that refuses+ // every signup — every SaaS workspace, since the override above always sets+ // DisallowSignup — an account-existence oracle for anonymous callers.+ //+ // It stays ahead of the password policy, though. Only DisallowSignup decides+ // whether existence may be disclosed here; past it, a workspace that accepts+ // signups answers AlreadyExists to any caller who submits a valid password+ // anyway, so ordering the policy first would hide nothing and would tell a+ // registered user to pick a better password when what they need is to log in.+ existingUser, err := s.store.GetUserByEmail(ctx, email)if err != nil {- return nil, err+ return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to find user by email"))}- if restriction.DisallowSignup {- return nil, connect.NewError(connect.CodePermissionDenied, errors.Errorf("sign up is disallowed for this workspace %v", targetWorkspaceID))+ if existingUser != nil {+ return nil, connect.NewError(connect.CodeAlreadyExists, errors.Errorf("email %s is already registered", request.Email))}+if err := validatePasswordWithRestriction(request.Password, convertToStorePasswordRestriction(restriction.PasswordRestriction)); err != nil {return nil, err}- workspaceID, err := s.provisionResolvedWorkspace(ctx, email, targetWorkspaceID, targetIsMember)+ workspaceID, err = s.provisionResolvedWorkspace(ctx, email, targetWorkspaceID, targetIsMember)if err != nil {return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to provision workspace"))}diff --git a/backend/api/v1/auth_service_email_code.go b/backend/api/v1/auth_service_email_code.goindex 35197df15c..b30af4b6cc 100644--- a/backend/api/v1/auth_service_email_code.go+++ b/backend/api/v1/auth_service_email_code.go@@ -34,9 +34,21 @@ const (emailCodeExpiry = 10 * time.MinuteemailCodeResendCooldown = 60 * time.Second+ // How much sign-in-code mail this deployment may generate per window.+ emailCodeSendWindow = time.Hour+ emailCodeSendPerWindow = 1000+errMsgInvalidEmailCode = "invalid or expired code")+// signinCodeSendBudgetKey is the single sender bucket; see SendEmailLoginCode.+const signinCodeSendBudgetKey = "signin-code"++// errSendBudgetExhausted reports that the window is spent, so no mail went out.+// Distinguished from a delivery failure because the caller answers it with+// ResourceExhausted rather than Internal.+var errSendBudgetExhausted = errors.New("too many sign-in codes requested, please try again later")+// RequestPasswordReset sends a password reset email. Always returns success to avoid leaking email existence.func (s *AuthService) RequestPasswordReset(ctx context.Context, req *connect.Request[v1pb.RequestPasswordResetRequest]) (*connect.Response[emptypb.Empty], error) {email := normalizeEmail(req.Msg.Email)@@ -59,6 +71,7 @@ func (s *AuthService) RequestPasswordReset(ctx context.Context, req *connect.Reqstorepb.EmailVerificationCodePurpose_PASSWORD_RESET,"[Bytebase] Reset your password","Hi,\n\nYour password reset code is: %s\n\nThis code expires in %d minutes. If you didn't request this, you can safely ignore this email.\n\n— Bytebase",+ "", 0,); err != nil {slog.Warn("failed to send password reset email", slog.String("to", email), log.BBError(err))}@@ -162,6 +175,18 @@ func (s *AuthService) SendEmailLoginCode(ctx context.Context, req *connect.Requereturn nil, connect.NewError(connect.CodeFailedPrecondition, errors.Errorf("email code login is not enabled for this workspace"))}+ // One cap for the whole deployment, whatever workspace the caller names.+ // SaaS copies EMAIL_CONFIG into every workspace it creates+ // (getAdditionalWorkspaceSettings), so naming one does not change the sender+ // — keying on the workspace would just hand each of them its own budget+ // against a shared reputation, and the key is caller-supplied anyway.+ //+ // The 60s per-recipient cooldown bounds one address; only a sender-wide cap+ // bounds a campaign, which writes each address once. Accepted: spending the+ // cap delays sign-in codes deployment-wide until the window passes, and one+ // address can spend it as cheaply as many, since the cost is the requests.+ // Bounded and recoverable, unlike the deliverability damage it prevents.+// Send synchronously so the caller learns about actionable failures (missing EMAIL// setting, SMTP unreachable, etc.). No enumeration risk here: LOGIN always attempts to// send regardless of whether the email exists (sign-up is handled on verify).@@ -172,7 +197,11 @@ func (s *AuthService) SendEmailLoginCode(ctx context.Context, req *connect.Requestorepb.EmailVerificationCodePurpose_LOGIN,"[Bytebase] Your sign-in code","Hi,\n\nYour sign-in code is: %s\n\nThis code expires in %d minutes. If you didn't request this, you can safely ignore this email.\n\n— Bytebase",+ signinCodeSendBudgetKey, emailCodeSendPerWindow,); err != nil {+ if errors.Is(err, errSendBudgetExhausted) {+ return nil, connect.NewError(connect.CodeResourceExhausted, err)+ }return nil, connect.NewError(connect.CodeInternal, err)}@@ -288,16 +317,19 @@ func (s *AuthService) parseAndSetAuditWorkspace(ctx context.Context, email strinreturn "", err}if workspaceID != "" {- account, err := s.store.GetAccountByEmail(ctx, email)- if err == nil && account != nil && account.Type == storepb.PrincipalType_END_USER && !account.MemberDeleted {- workspace, err := s.store.FindWorkspace(ctx, &store.FindWorkspaceMessage{- WorkspaceID: &workspaceID,- Email: email,- IncludeAllUser: !s.profile.SaaS,- })- if err == nil && workspace != nil {- common.SetAuditWorkspaceID(ctx, workspace.ResourceID)- }+ account, accountErr := s.store.GetAccountByEmail(ctx, email)+ // Looked up for every address, not only one worth attributing. Callers+ // here are anonymous and can reach a response without a send — an+ // exhausted budget returns early — so a query skipped for strangers is a+ // query a member can be recognised by.+ workspace, workspaceErr := s.store.FindWorkspace(ctx, &store.FindWorkspaceMessage{+ WorkspaceID: &workspaceID,+ Email: email,+ IncludeAllUser: !s.profile.SaaS,+ })+ if accountErr == nil && account != nil && account.Type == storepb.PrincipalType_END_USER && !account.MemberDeleted &&+ workspaceErr == nil && workspace != nil {+ common.SetAuditWorkspaceID(ctx, workspace.ResourceID)}}return workspaceID, nil@@ -346,12 +378,13 @@ func resolvePreLoginEmailSetting(// and emails the plain code. Returns nil on a successful send as well as on silent-skip paths// (cooldown active, or PASSWORD_RESET for an unknown email) — both are intentionally// indistinguishable to the caller, since both correspond to "no new email was delivered".-// Returns an error only on actionable failures (missing EMAIL setting, SMTP failure, DB error).+// Returns an error only on actionable failures (missing EMAIL setting, SMTP failure, DB error,+// or an exhausted send budget — see sendBudget, which only the caller's budgets can produce).// Callers decide whether to propagate the error: `SendEmailLoginCode` surfaces it (users need// to know email delivery failed), `RequestPasswordReset` swallows it to avoid revealing that// the account exists.-func (s *AuthService) sendEmailVerificationCode(ctx context.Context, workspaceID, email string, purpose storepb.EmailVerificationCodePurpose, subject, bodyFmt string) error {- return sendEmailVerificationCode(ctx, s.store, s.secret, workspaceID, email, purpose, emailCodeTemplate{Subject: subject, BodyFmt: bodyFmt})+func (s *AuthService) sendEmailVerificationCode(ctx context.Context, workspaceID, email string, purpose storepb.EmailVerificationCodePurpose, subject, bodyFmt string, budgetKey string, budgetMax int) error {+ return sendEmailVerificationCode(ctx, s.store, s.secret, workspaceID, email, purpose, emailCodeTemplate{Subject: subject, BodyFmt: bodyFmt}, budgetKey, budgetMax)}// emailCodeTemplate is the message a verification code is delivered in.@@ -364,7 +397,7 @@ type emailCodeTemplate struct {// sendEmailVerificationCode is package-level because both AuthService (login// and password-reset codes) and UserService (the re-authentication code) send// them; the deps it needs are passed rather than reached through a receiver.-func sendEmailVerificationCode(ctx context.Context, stores *store.Store, secret, workspaceID, email string, purpose storepb.EmailVerificationCodePurpose, mail emailCodeTemplate) error {+func sendEmailVerificationCode(ctx context.Context, stores *store.Store, secret, workspaceID, email string, purpose storepb.EmailVerificationCodePurpose, mail emailCodeTemplate, budgetKey string, budgetMax int) error {// For password reset, only send to active end users — no upsert or email for other targets.// Login intentionally skips this account check because email-code login also supports signup.if purpose == storepb.EmailVerificationCodePurpose_PASSWORD_RESET {@@ -387,6 +420,25 @@ func sendEmailVerificationCode(ctx context.Context, stores *store.Store, secret,return errors.Errorf("cannot found email config for workspace %v", workspaceID)}+ // Claim before writing anything: the upsert below replaces the stored hash, so+ // claiming after it would let an exhausted budget destroy a code the recipient+ // still holds and send no replacement.+ //+ // Every request is counted, including one the cooldown will skip. Checking the+ // cooldown first would be cheaper but cannot be done atomically with the+ // claim, so concurrent requests would pass it together and be counted anyway,+ // and it would make the answer depend on whether that recipient has a recent+ // code. Draining the budget costs the same number of requests either way.+ if budgetKey != "" {+ granted, err := stores.ClaimAttempt(ctx, budgetKey, storepb.LoginAttemptKind_EMAIL_CODE_SEND, budgetMax, emailCodeSendWindow)+ if err != nil {+ return errors.Wrap(err, "failed to claim send budget")+ }+ if !granted {+ return errSendBudgetExhausted+ }+ }+code, err := generateEmailCode()if err != nil {return errors.Wrap(err, "failed to generate code")diff --git a/backend/api/v1/auth_service_lockout.go b/backend/api/v1/auth_service_lockout.goindex 234a225e6c..210c3736f4 100644--- a/backend/api/v1/auth_service_lockout.go+++ b/backend/api/v1/auth_service_lockout.go@@ -55,7 +55,7 @@ func (s *AuthService) claimLoginAttempt(ctx context.Context, identity string, ki// when it verifies a CredentialProof: a proof channel without that bound is a// guessing oracle.func claimLoginAttempt(ctx context.Context, stores *store.Store, identity string, kind storepb.LoginAttemptKind) error {- granted, err := stores.ClaimLoginAttempt(ctx, identity, kind, loginAttemptMax, loginAttemptWindow)+ granted, err := stores.ClaimAttempt(ctx, identity, kind, loginAttemptMax, loginAttemptWindow)if err != nil {return connect.NewError(connect.CodeInternal, err)}diff --git a/backend/api/v1/auth_service_test.go b/backend/api/v1/auth_service_test.goindex 92fafb3cd1..91120ea4d6 100644--- a/backend/api/v1/auth_service_test.go+++ b/backend/api/v1/auth_service_test.go@@ -169,6 +169,7 @@ func TestPasswordResetEmailSkipsDeletedUser(t *testing.T) {storepb.EmailVerificationCodePurpose_PASSWORD_RESET,"subject","code: %s, expires in %d minutes",+ "", 0,))}@@ -530,3 +531,218 @@ func TestSwitchWorkspaceInternalRefusesMCPCaller(t *testing.T) {webHeaders.Set("Authorization", "Bearer "+webToken)require.NoError(t, s.rejectMCPOriginatedTokenMint(context.Background(), webHeaders, "obtain a workspace token"))}++func TestSignupChecksRestrictionBeforeExistence(t *testing.T) {+ const secret = "test-secret"++ ctx := context.Background()+ stores := newAuthTestStore(t)+ licenseService, err := enterprise.NewLicenseService(common.ReleaseModeDev, stores, false, "")+ require.NoError(t, err)++ // The binding matters: signup resolves the workspace via FindWorkspace(email),+ // so a member resolves to a real ID and a stranger to none. Without it both+ // resolve to none and a denial naming the workspace would look identical.+ takenUser, err := stores.CreateUser(ctx, &store.UserMessage{+ Email: "[email protected]",+ Name: "Taken",+ PasswordHash: "unused",+ Profile: &storepb.UserProfile{},+ })+ require.NoError(t, err)+ _, err = stores.CreateWorkspace(ctx, &store.WorkspaceMessage{+ ResourceID: "signup-order-test",+ Payload: &storepb.WorkspacePayload{Title: "Signup order test"},+ }, takenUser.Email)+ require.NoError(t, err)++ signup := func(service *AuthService, email string) error {+ _, err := service.Signup(ctx, connect.NewRequest(&v1pb.SignupRequest{+ Email: email,+ Title: "Signup test",+ Password: "password-long-enough",+ }))+ return err+ }++ // SaaS forces DisallowSignup for every workspace, so the RPC can never+ // succeed there — and must not answer differently for an address that has+ // an account than for one that does not.+ t.Run("denied signup reveals nothing", func(t *testing.T) {+ service := NewAuthService(stores, secret, licenseService, &config.Profile{SaaS: true}, nil)+ takenErr := signup(service, "[email protected]")+ unknownErr := signup(service, "[email protected]")+ require.Equal(t, connect.CodePermissionDenied, connect.CodeOf(takenErr))+ require.Equal(t, connect.CodeOf(unknownErr), connect.CodeOf(takenErr))+ require.Equal(t, unknownErr.Error(), takenErr.Error())+ })++ // The reorder moved the check behind the DisallowSignup gate, not away.+ t.Run("allowed signup still reports a duplicate", func(t *testing.T) {+ service := NewAuthService(stores, secret, licenseService, &config.Profile{}, nil)+ require.Equal(t, connect.CodeAlreadyExists, connect.CodeOf(signup(service, "[email protected]")))+ })++ // Only DisallowSignup gates disclosure. Ordering the password policy first+ // hides nothing from a caller who submits a valid password, and tells a+ // registered user to fix their password when they should be logging in.+ t.Run("a duplicate outranks the password policy", func(t *testing.T) {+ service := NewAuthService(stores, secret, licenseService, &config.Profile{}, nil)+ _, err := service.Signup(ctx, connect.NewRequest(&v1pb.SignupRequest{+ Email: "[email protected]",+ Title: "Signup test",+ Password: "short",+ }))+ require.Equal(t, connect.CodeAlreadyExists, connect.CodeOf(err))+ })+}++// spendSendBudget drives the deployment bucket to its cap without sending mail.+// Claims until refused rather than a fixed count, since a send earlier in the+// test may already have taken a slot.+func spendSendBudget(ctx context.Context, t *testing.T, stores *store.Store) {+ t.Helper()+ claim := func() bool {+ granted, err := stores.ClaimAttempt(ctx, signinCodeSendBudgetKey, storepb.LoginAttemptKind_EMAIL_CODE_SEND, emailCodeSendPerWindow, emailCodeSendWindow)+ require.NoError(t, err)+ return granted+ }+ for range emailCodeSendPerWindow {+ if !claim() {+ return+ }+ }+ require.False(t, claim(), "the bucket must be spent")+}++// newBudgetTestService builds a SaaS service whose mail host refuses on connect,+// so Internal means a send reached delivery and ResourceExhausted means it was+// refused a budget slot.+func newBudgetTestService(t *testing.T, stores *store.Store) *AuthService {+ t.Helper()+ t.Setenv("EMAIL_CONFIG", `{"from":"[email protected]","type":"SMTP","smtp":{"host":"127.0.0.1","port":1,"encryption":"ENCRYPTION_NONE","authentication":"AUTHENTICATION_NONE"}}`)+ licenseService, err := enterprise.NewLicenseService(common.ReleaseModeDev, stores, false, "")+ require.NoError(t, err)+ return NewAuthService(stores, "test-secret", licenseService, &config.Profile{SaaS: true}, nil)+}++// TestSendEmailLoginCodeBudgetsEverySender pins that naming a workspace does not+// buy a separate budget. SaaS copies EMAIL_CONFIG into every workspace it+// creates, so a named send leaves over the same deployment sender; giving each+// workspace its own bucket would meter a shared reputation per tenant, and the+// workspace is caller-supplied besides.+func TestSendEmailLoginCodeBudgetsEverySender(t *testing.T) {+ const workspaceID = "email-code-shared-sender"++ ctx := context.Background()+ stores := newAuthTestStore(t)+ _, err := stores.CreateWorkspace(ctx, &store.WorkspaceMessage{+ ResourceID: workspaceID,+ Payload: &storepb.WorkspacePayload{Title: "Shared sender"},+ }, "[email protected]")+ require.NoError(t, err)+ _, err = stores.UpsertSetting(ctx, &store.SettingMessage{+ Name: storepb.SettingName_WORKSPACE_PROFILE,+ Workspace: workspaceID,+ Value: &storepb.WorkspaceProfileSetting{+ AllowEmailCodeSignin: true,+ PasswordRestriction: &storepb.WorkspaceProfileSetting_PasswordRestriction{MinLength: 8},+ },+ })+ require.NoError(t, err)+ // The workspace carries the deployment's own mail config, as SaaS signup writes it.+ _, err = stores.UpsertSetting(ctx, &store.SettingMessage{+ Name: storepb.SettingName_EMAIL,+ Workspace: workspaceID,+ Value: &storepb.EmailSetting{+ From: "[email protected]",+ Type: storepb.EmailSetting_SMTP,+ Config: &storepb.EmailSetting_Smtp{Smtp: &storepb.EmailSetting_SMTPConfig{+ Host: "127.0.0.1",+ Port: 1,+ Encryption: storepb.EmailSetting_SMTPConfig_ENCRYPTION_NONE,+ Authentication: storepb.EmailSetting_SMTPConfig_AUTHENTICATION_NONE,+ }},+ },+ })+ require.NoError(t, err)++ service := newBudgetTestService(t, stores)+ workspaceName := common.FormatWorkspace(workspaceID)+ spendSendBudget(ctx, t, stores)++ _, err = service.SendEmailLoginCode(ctx, connect.NewRequest(&v1pb.SendEmailLoginCodeRequest{+ Email: "[email protected]",+ Workspace: &workspaceName,+ }))+ require.Equal(t, connect.CodeResourceExhausted, connect.CodeOf(err),+ "naming a workspace must not escape the deployment budget")+}++// TestSendEmailLoginCodeBudgetsWorkspacelessSends pins the cap on the path a+// brand-new signup takes, where the 60s per-recipient cooldown never fires+// because a campaign writes each address exactly once.+func TestSendEmailLoginCodeBudgetsWorkspacelessSends(t *testing.T) {+ ctx := context.Background()+ stores := newAuthTestStore(t)+ service := newBudgetTestService(t, stores)++ send := func(email string) error {+ _, err := service.SendEmailLoginCode(ctx, connect.NewRequest(&v1pb.SendEmailLoginCodeRequest{Email: email}))+ return err+ }++ require.Equal(t, connect.CodeInternal, connect.CodeOf(send("[email protected]")),+ "a send within budget must fail only on delivery")+ spendSendBudget(ctx, t, stores)+ require.Equal(t, connect.CodeResourceExhausted, connect.CodeOf(send("[email protected]")))+ // The bucket is the sender, so a spent budget stops the next send whatever+ // address it names.+ require.Equal(t, connect.CodeResourceExhausted, connect.CodeOf(send("[email protected]")))+}++// TestSendEmailLoginCodeBudgetKeepsExistingCode pins that a refused budget is+// inert: the upsert replaces the stored hash, so claiming after it would let an+// exhausted bucket destroy a pending code and send no replacement. It also pins+// that the refusal does not depend on the recipient — an address mid-cooldown is+// answered exactly as any other, or an exhausted bucket would let a caller probe+// who had just been sent a code.+func TestSendEmailLoginCodeBudgetKeepsExistingCode(t *testing.T) {+ ctx := context.Background()+ stores := newAuthTestStore(t)+ service := newBudgetTestService(t, stores)++ send := func(email string) error {+ _, err := service.SendEmailLoginCode(ctx, connect.NewRequest(&v1pb.SendEmailLoginCodeRequest{Email: email}))+ return err+ }++ const victim = "[email protected]"+ const heldHash = "held-code-hash"+ seed := func(email, hash string, lastSent time.Time) {+ t.Helper()+ sent, err := stores.UpsertEmailVerificationCodeIfCooldownExpired(ctx, &store.EmailVerificationCodeMessage{+ Email: email,+ Purpose: storepb.EmailVerificationCodePurpose_LOGIN,+ CodeHash: hash,+ ExpiresAt: time.Now().Add(emailCodeExpiry),+ LastSentAt: lastSent,+ }, emailCodeResendCooldown)+ require.NoError(t, err)+ require.True(t, sent)+ }+ // A held code the upsert would replace once the cooldown passes.+ seed(victim, heldHash, time.Now().Add(-5*time.Minute))+ seed("[email protected]", "recent-code-hash", time.Now())++ spendSendBudget(ctx, t, stores)++ require.Equal(t, connect.CodeResourceExhausted, connect.CodeOf(send(victim)))+ row, err := stores.GetEmailVerificationCode(ctx, victim, storepb.EmailVerificationCodePurpose_LOGIN)+ require.NoError(t, err)+ require.NotNil(t, row, "a refused budget must not delete the code the recipient is holding")+ require.Equal(t, heldHash, row.CodeHash, "a refused budget must not replace it either")++ require.Equal(t, connect.CodeResourceExhausted, connect.CodeOf(send("[email protected]")),+ "an address mid-cooldown must be answered as any other is")+}diff --git a/backend/api/v1/user_service.go b/backend/api/v1/user_service.goindex edacc0fcf8..4bfe1d524e 100644--- a/backend/api/v1/user_service.go+++ b/backend/api/v1/user_service.go@@ -697,6 +697,10 @@ func (s *UserService) RequestReauthCode(ctx context.Context, request *connect.ReSubject: "[Bytebase] Confirm your identity",BodyFmt: "Hi,\n\nYour verification code is: %s\n\nThis code expires in %d minutes. If you didn't request this, you can safely ignore this email.\n\n— Bytebase",},+ // Unbudgeted: the caller is already authenticated and the recipient is+ // their own address, so this is not a path an anonymous sender can point+ // at a recipient list.+ "", 0,); err != nil {return nil, connect.NewError(connect.CodeInternal, err)}diff --git a/backend/generated-go/store/auth.pb.go b/backend/generated-go/store/auth.pb.goindex 39f8867993..a0aba7f2c3 100644--- a/backend/generated-go/store/auth.pb.go+++ b/backend/generated-go/store/auth.pb.go@@ -77,15 +77,32 @@ func (EmailVerificationCodePurpose) EnumDescriptor() ([]byte, []int) {return file_store_auth_proto_rawDescGZIP(), []int{0}}-// LoginAttemptKind names which credential's attempt limit a login_attempt row-// tracks. Stored as the enum name string in login_attempt.kind column.+// LoginAttemptKind names what a login_attempt row counts. Stored as the enum+// name string in login_attempt.kind column. The kind also says what the+// identity column holds: the three credential kinds below count failed guesses+// against a person, share one attempt limit, and are cleared by a successful+// verification.type LoginAttemptKind int32const (LoginAttemptKind_LOGIN_ATTEMPT_KIND_UNSPECIFIED LoginAttemptKind = 0LoginAttemptKind_PASSWORD LoginAttemptKind = 1- LoginAttemptKind_EMAIL_CODE LoginAttemptKind = 2- LoginAttemptKind_MFA LoginAttemptKind = 3+ // Submitting a 6-digit code. Sign-in, password reset and re-authentication+ // share one bucket per email, so a guess anywhere counts everywhere.+ LoginAttemptKind_EMAIL_CODE LoginAttemptKind = 2+ LoginAttemptKind_MFA LoginAttemptKind = 3+ // Sending those codes rather than guessing them — the opposite direction, and+ // the reason it is a separate kind. Its identity is the sending deployment+ // and not a person, so exhausting it throttles outbound+ // mail and locks no account, and nothing clears it because a delivered email+ // is the thing counted and there is no success to forgive.+ //+ // It also reads last_attempt_at differently: for this kind the column is the+ // window's start, not the latest send, so the count resets on a fixed+ // schedule. The kinds above intentionally reset only after a quiet window —+ // wrong for a volume budget, where a steady trickle would never reset and+ // "N per hour" would become "N ever".+ LoginAttemptKind_EMAIL_CODE_SEND LoginAttemptKind = 4)// Enum value maps for LoginAttemptKind.@@ -95,12 +112,14 @@ var (1: "PASSWORD",2: "EMAIL_CODE",3: "MFA",+ 4: "EMAIL_CODE_SEND",}LoginAttemptKind_value = map[string]int32{"LOGIN_ATTEMPT_KIND_UNSPECIFIED": 0,"PASSWORD": 1,"EMAIL_CODE": 2,"MFA": 3,+ "EMAIL_CODE_SEND": 4,})@@ -141,13 +160,14 @@ const file_store_auth_proto_rawDesc = "" +"\x05LOGIN\x10\x01\x12\x12\n" +"\x0ePASSWORD_RESET\x10\x02\x12\n" +"\n" +- "\x06REAUTH\x10\x03*]\n" ++ "\x06REAUTH\x10\x03*r\n" +"\x10LoginAttemptKind\x12\"\n" +"\x1eLOGIN_ATTEMPT_KIND_UNSPECIFIED\x10\x00\x12\f\n" +"\bPASSWORD\x10\x01\x12\x0e\n" +"\n" +"EMAIL_CODE\x10\x02\x12\a\n" +- "\x03MFA\x10\x03B\x8c\x01\n" ++ "\x03MFA\x10\x03\x12\x13\n" ++ "\x0fEMAIL_CODE_SEND\x10\x04B\x8c\x01\n" +"\x12com.bytebase.storeB\tAuthProtoP\x01Z\x12generated-go/store\xa2\x02\x03BSX\xaa\x02\x0eBytebase.Store\xca\x02\x0eBytebase\\Store\xe2\x02\x1aBytebase\\Store\\GPBMetadata\xea\x02\x0fBytebase::Storeb\x06proto3"var (diff --git a/backend/store/login_attempt.go b/backend/store/login_attempt.goindex 6d653f485d..38f66992f0 100644--- a/backend/store/login_attempt.go+++ b/backend/store/login_attempt.go@@ -17,22 +17,26 @@ import (// comfortably under this structural bound.const maxIdentityBytes = 2048-// ClaimLoginAttempt atomically takes one of maxAttempts slots for the identity-// before the credential is checked (docs/design/login-attempt-lockout.md).-// Returns (true, nil) when a slot was granted, or (false, nil) when the-// identity already holds maxAttempts and the latest was under window ago — the-// caller must refuse the attempt without touching the credential. A refused-// claim leaves the row untouched, so a lock lasts exactly window from the-// maxAttempts-th attempt; a claim more than window after the latest attempt-// restarts the counter at one. The row lock serializes concurrent claims and-// now() is database time, so replicas cannot disagree.-func (s *Store) ClaimLoginAttempt(ctx context.Context, identity string, kind storepb.LoginAttemptKind, maxAttempts int, window time.Duration) (bool, error) {+// ClaimAttempt records one attempt for (identity, kind) and reports whether it+// is within maxAttempts for the window. Call it before the thing being limited+// happens. Returns (false, nil) once the window is full, leaving the row+// untouched. The row lock serializes concurrent claims and now() is database+// time, so replicas cannot disagree.+//+// The kind decides what an attempt does to the window, as+// proto/store/store/auth.proto records. A credential kind is a lockout: every+// failure restarts the window, so a lock outlives the last attempt.+// EMAIL_CODE_SEND counts outbound mail, so its window is anchored to the first+// attempt — restarting it would mean a steady stream never resets and "N per+// window" would become "N ever".+func (s *Store) ClaimAttempt(ctx context.Context, identity string, kind storepb.LoginAttemptKind, maxAttempts int, window time.Duration) (bool, error) {// Backstop against programmer error — request fields that become identities- // are bounded at the proto edge, so an unkeyed or structurally oversized- // row here means a caller composed an identity from an unbounded source.+ // are bounded at the proto edge, so an unkeyed or structurally oversized row+ // here means a caller composed an identity from an unbounded source.if identity == "" || len(identity) > maxIdentityBytes || kind == storepb.LoginAttemptKind_LOGIN_ATTEMPT_KIND_UNSPECIFIED {- return false, errors.Errorf("login attempt requires a kind and an identity of at most %d bytes", maxIdentityBytes)+ return false, errors.Errorf("an attempt requires a kind and an identity of at most %d bytes", maxIdentityBytes)}+ restartWindowOnAttempt := kind != storepb.LoginAttemptKind_EMAIL_CODE_SENDq := qb.Q().Space(`INSERT INTO login_attempt (identity, kind, attempts, last_attempt_at)VALUES (?, ?, 1, now())@@ -41,11 +45,14 @@ func (s *Store) ClaimLoginAttempt(ctx context.Context, identity string, kind stoWHEN login_attempt.last_attempt_at < now() - make_interval(secs => ?) THEN 1ELSE login_attempt.attempts + 1END,- last_attempt_at = now()+ last_attempt_at = CASE+ WHEN ? OR login_attempt.last_attempt_at < now() - make_interval(secs => ?) THEN now()+ ELSE login_attempt.last_attempt_at+ ENDWHERE login_attempt.attempts < ?OR login_attempt.last_attempt_at < now() - make_interval(secs => ?)RETURNING 1- `, identity, kind.String(), window.Seconds(), maxAttempts, window.Seconds())+ `, identity, kind.String(), window.Seconds(), restartWindowOnAttempt, window.Seconds(), maxAttempts, window.Seconds())query, args, err := q.ToSQL()if err != nil {@@ -54,9 +61,9 @@ func (s *Store) ClaimLoginAttempt(ctx context.Context, identity string, kind stovar dummy intif err := s.GetDB().QueryRowContext(ctx, query, args...).Scan(&dummy); err != nil {if errors.Is(err, sql.ErrNoRows) {- return false, nil // locked out — no slot granted+ return false, nil // window full}- return false, errors.Wrap(err, "failed to claim login attempt")+ return false, errors.Wrap(err, "failed to claim attempt")}return true, nil}diff --git a/backend/store/login_attempt_test.go b/backend/store/login_attempt_test.goindex add21c446e..87e97fb2bb 100644--- a/backend/store/login_attempt_test.go+++ b/backend/store/login_attempt_test.go@@ -64,12 +64,12 @@ func TestLoginAttemptClaim(t *testing.T) {t.Run("grants exactly N slots then locks", func(t *testing.T) {const identity = "[email protected]"for i := range 5 {- granted, err := s.ClaimLoginAttempt(ctx, identity, storepb.LoginAttemptKind_EMAIL_CODE, 5, window)+ granted, err := s.ClaimAttempt(ctx, identity, storepb.LoginAttemptKind_EMAIL_CODE, 5, window)require.NoError(t, err)require.True(t, granted, "claim %d must be granted", i+1)}for range 2 {- granted, err := s.ClaimLoginAttempt(ctx, identity, storepb.LoginAttemptKind_EMAIL_CODE, 5, window)+ granted, err := s.ClaimAttempt(ctx, identity, storepb.LoginAttemptKind_EMAIL_CODE, 5, window)require.NoError(t, err)require.False(t, granted, "claims beyond N must be refused")}@@ -78,12 +78,12 @@ func TestLoginAttemptClaim(t *testing.T) {t.Run("locked claims do not extend the lock", func(t *testing.T) {const identity = "[email protected]"for range 3 {- granted, err := s.ClaimLoginAttempt(ctx, identity, storepb.LoginAttemptKind_PASSWORD, 3, window)+ granted, err := s.ClaimAttempt(ctx, identity, storepb.LoginAttemptKind_PASSWORD, 3, window)require.NoError(t, err)require.True(t, granted)}lockedAt := lastAttemptAt(identity, storepb.LoginAttemptKind_PASSWORD)- granted, err := s.ClaimLoginAttempt(ctx, identity, storepb.LoginAttemptKind_PASSWORD, 3, window)+ granted, err := s.ClaimAttempt(ctx, identity, storepb.LoginAttemptKind_PASSWORD, 3, window)require.NoError(t, err)require.False(t, granted)require.Equal(t, lockedAt, lastAttemptAt(identity, storepb.LoginAttemptKind_PASSWORD),@@ -93,21 +93,21 @@ func TestLoginAttemptClaim(t *testing.T) {t.Run("counter forgets after a quiet window", func(t *testing.T) {const identity = "[email protected]"for range 3 {- granted, err := s.ClaimLoginAttempt(ctx, identity, storepb.LoginAttemptKind_PASSWORD, 3, window)+ granted, err := s.ClaimAttempt(ctx, identity, storepb.LoginAttemptKind_PASSWORD, 3, window)require.NoError(t, err)require.True(t, granted)}- granted, err := s.ClaimLoginAttempt(ctx, identity, storepb.LoginAttemptKind_PASSWORD, 3, window)+ granted, err := s.ClaimAttempt(ctx, identity, storepb.LoginAttemptKind_PASSWORD, 3, window)require.NoError(t, err)require.False(t, granted, "identity must be locked before the window passes")backdate(identity, storepb.LoginAttemptKind_PASSWORD, window+time.Second)for range 3 {- granted, err := s.ClaimLoginAttempt(ctx, identity, storepb.LoginAttemptKind_PASSWORD, 3, window)+ granted, err := s.ClaimAttempt(ctx, identity, storepb.LoginAttemptKind_PASSWORD, 3, window)require.NoError(t, err)require.True(t, granted, "the counter must restart at one after D of quiet")}- granted, err = s.ClaimLoginAttempt(ctx, identity, storepb.LoginAttemptKind_PASSWORD, 3, window)+ granted, err = s.ClaimAttempt(ctx, identity, storepb.LoginAttemptKind_PASSWORD, 3, window)require.NoError(t, err)require.False(t, granted)})@@ -115,13 +115,13 @@ func TestLoginAttemptClaim(t *testing.T) {t.Run("clear deletes the row", func(t *testing.T) {const identity = "[email protected]"for range 3 {- granted, err := s.ClaimLoginAttempt(ctx, identity, storepb.LoginAttemptKind_PASSWORD, 3, window)+ granted, err := s.ClaimAttempt(ctx, identity, storepb.LoginAttemptKind_PASSWORD, 3, window)require.NoError(t, err)require.True(t, granted)}require.NoError(t, s.ClearLoginAttempt(ctx, identity, storepb.LoginAttemptKind_PASSWORD))for range 3 {- granted, err := s.ClaimLoginAttempt(ctx, identity, storepb.LoginAttemptKind_PASSWORD, 3, window)+ granted, err := s.ClaimAttempt(ctx, identity, storepb.LoginAttemptKind_PASSWORD, 3, window)require.NoError(t, err)require.True(t, granted, "success must forget every prior failure")}@@ -134,19 +134,19 @@ func TestLoginAttemptClaim(t *testing.T) {t.Run("kinds and identities are independent buckets", func(t *testing.T) {const identity = "[email protected]"for range 3 {- granted, err := s.ClaimLoginAttempt(ctx, identity, storepb.LoginAttemptKind_MFA, 3, window)+ granted, err := s.ClaimAttempt(ctx, identity, storepb.LoginAttemptKind_MFA, 3, window)require.NoError(t, err)require.True(t, granted)}- granted, err := s.ClaimLoginAttempt(ctx, identity, storepb.LoginAttemptKind_MFA, 3, window)+ granted, err := s.ClaimAttempt(ctx, identity, storepb.LoginAttemptKind_MFA, 3, window)require.NoError(t, err)require.False(t, granted)- granted, err = s.ClaimLoginAttempt(ctx, identity, storepb.LoginAttemptKind_PASSWORD, 3, window)+ granted, err = s.ClaimAttempt(ctx, identity, storepb.LoginAttemptKind_PASSWORD, 3, window)require.NoError(t, err)require.True(t, granted, "another kind for the same identity must have its own slots")- granted, err = s.ClaimLoginAttempt(ctx, "[email protected]", storepb.LoginAttemptKind_MFA, 3, window)+ granted, err = s.ClaimAttempt(ctx, "[email protected]", storepb.LoginAttemptKind_MFA, 3, window)require.NoError(t, err)require.True(t, granted, "another identity must have its own slots")})@@ -158,7 +158,7 @@ func TestLoginAttemptClaim(t *testing.T) {grants := make(chan bool, 20)for range 20 {wg.Go(func() {- granted, err := s.ClaimLoginAttempt(ctx, identity, storepb.LoginAttemptKind_PASSWORD, n, window)+ granted, err := s.ClaimAttempt(ctx, identity, storepb.LoginAttemptKind_PASSWORD, n, window)require.NoError(t, err)grants <- granted})@@ -175,11 +175,11 @@ func TestLoginAttemptClaim(t *testing.T) {})t.Run("unkeyed claims are refused outright", func(t *testing.T) {- _, err := s.ClaimLoginAttempt(ctx, "", storepb.LoginAttemptKind_PASSWORD, 3, window)+ _, err := s.ClaimAttempt(ctx, "", storepb.LoginAttemptKind_PASSWORD, 3, window)require.Error(t, err, "an empty identity must never write a row")- _, err = s.ClaimLoginAttempt(ctx, "[email protected]", storepb.LoginAttemptKind_LOGIN_ATTEMPT_KIND_UNSPECIFIED, 3, window)+ _, err = s.ClaimAttempt(ctx, "[email protected]", storepb.LoginAttemptKind_LOGIN_ATTEMPT_KIND_UNSPECIFIED, 3, window)require.Error(t, err, "an unspecified kind must never write a row")- _, err = s.ClaimLoginAttempt(ctx, strings.Repeat("a", 2049), storepb.LoginAttemptKind_PASSWORD, 3, window)+ _, err = s.ClaimAttempt(ctx, strings.Repeat("a", 2049), storepb.LoginAttemptKind_PASSWORD, 3, window)require.Error(t, err, "a structurally oversized identity must never write a row")})@@ -187,7 +187,7 @@ func TestLoginAttemptClaim(t *testing.T) {const staleIdentity = "[email protected]"const freshIdentity = "[email protected]"for _, identity := range []string{staleIdentity, freshIdentity} {- granted, err := s.ClaimLoginAttempt(ctx, identity, storepb.LoginAttemptKind_PASSWORD, 3, window)+ granted, err := s.ClaimAttempt(ctx, identity, storepb.LoginAttemptKind_PASSWORD, 3, window)require.NoError(t, err)require.True(t, granted)}@@ -204,3 +204,121 @@ func TestLoginAttemptClaim(t *testing.T) {require.Equal(t, 1, count, "rows attempted within the retention window must survive the purge")})}++// TestSendBudgetClaim covers the outbound send budget: the same ClaimAttempt as+// the lockout, under the window rule EMAIL_CODE_SEND selects.+func TestSendBudgetClaim(t *testing.T) {+ ctx := context.Background()+ container := testcontainer.GetTestPgContainer(ctx, t)+ t.Cleanup(func() { container.Close(ctx) })++ db := container.GetDB()+ require.NoError(t, migrator.MigrateSchema(ctx, db))++ pgURL := fmt.Sprintf(+ "host=%s port=%s user=postgres password=root-password database=postgres",+ container.GetHost(), container.GetPort(),+ )+ s, err := store.New(ctx, pgURL, false)+ require.NoError(t, err)+ t.Cleanup(func() { require.NoError(t, s.Close()) })++ const window = time.Hour+ const kind = storepb.LoginAttemptKind_EMAIL_CODE_SEND++ backdateWindow := func(key string, by time.Duration) {+ t.Helper()+ _, err := db.ExecContext(ctx, `+ UPDATE login_attempt SET last_attempt_at = last_attempt_at - make_interval(secs => $3)+ WHERE identity = $1 AND kind = $2+ `, key, kind.String(), by.Seconds())+ require.NoError(t, err)+ }++ t.Run("grants exactly max per window", func(t *testing.T) {+ const key = "sender-a"+ for i := range 3 {+ granted, err := s.ClaimAttempt(ctx, key, kind, 3, window)+ require.NoError(t, err)+ require.True(t, granted, "grant %d is within the window", i)+ }+ granted, err := s.ClaimAttempt(ctx, key, kind, 3, window)+ require.NoError(t, err)+ require.False(t, granted, "the window is full")+ })++ // Why EMAIL_CODE_SEND anchors its window to the first claim. Under a+ // credential kind's rule every grant restarts the window, so a steady trickle+ // never resets it and "3 per hour" would become "3 ever, until an hour of+ // silence", refusing traffic that never approached the rate.+ t.Run("a steady trickle does not accumulate across windows", func(t *testing.T) {+ const key = "sender-trickle"+ // Six sends, each arriving well inside the window but with the window+ // itself rolling over between every pair. A lockout counter would reach+ // its limit on the third; a fixed window starts over each time.+ for i := range 6 {+ granted, err := s.ClaimAttempt(ctx, key, kind, 3, window)+ require.NoError(t, err, "send %d", i)+ require.True(t, granted, "send %d must not be refused: no window ever held more than two", i)+ if i%2 == 1 {+ backdateWindow(key, window+time.Minute)+ }+ }+ })++ t.Run("a full window reopens once it expires", func(t *testing.T) {+ const key = "sender-expiry"+ for range 2 {+ granted, err := s.ClaimAttempt(ctx, key, kind, 2, window)+ require.NoError(t, err)+ require.True(t, granted)+ }+ granted, err := s.ClaimAttempt(ctx, key, kind, 2, window)+ require.NoError(t, err)+ require.False(t, granted)++ backdateWindow(key, window+time.Minute)+ granted, err = s.ClaimAttempt(ctx, key, kind, 2, window)+ require.NoError(t, err)+ require.True(t, granted, "a new window starts once the old one expires")+ })++ t.Run("refusals do not extend the window", func(t *testing.T) {+ const key = "sender-refusal"+ granted, err := s.ClaimAttempt(ctx, key, kind, 1, window)+ require.NoError(t, err)+ require.True(t, granted)+ var opened time.Time+ require.NoError(t, db.QueryRowContext(ctx, `+ SELECT last_attempt_at FROM login_attempt WHERE identity = $1 AND kind = $2+ `, key, kind.String()).Scan(&opened))++ for range 5 {+ granted, err := s.ClaimAttempt(ctx, key, kind, 1, window)+ require.NoError(t, err)+ require.False(t, granted)+ }+ var after time.Time+ require.NoError(t, db.QueryRowContext(ctx, `+ SELECT last_attempt_at FROM login_attempt WHERE identity = $1 AND kind = $2+ `, key, kind.String()).Scan(&after))+ require.True(t, opened.Equal(after), "hammering a full window must not push its expiry out")+ })++ t.Run("senders and kinds are independent", func(t *testing.T) {+ granted, err := s.ClaimAttempt(ctx, "sender-x", kind, 1, window)+ require.NoError(t, err)+ require.True(t, granted)+ granted, err = s.ClaimAttempt(ctx, "sender-y", kind, 1, window)+ require.NoError(t, err)+ require.True(t, granted, "one sender's full window must not bind another")+ granted, err = s.ClaimAttempt(ctx, "sender-x", storepb.LoginAttemptKind_PASSWORD, 1, window)+ require.NoError(t, err)+ require.True(t, granted, "a send budget must not consume a credential bucket")+ })++ t.Run("an unkeyed claim is refused outright", func(t *testing.T) {+ _, err := s.ClaimAttempt(ctx, "", kind, 1, window)+ require.Error(t, err)+ })+}diff --git a/backend/tests/login_attempt_collision_test.go b/backend/tests/login_attempt_collision_test.goindex b45f8cc466..9a5c4af382 100644--- a/backend/tests/login_attempt_collision_test.go+++ b/backend/tests/login_attempt_collision_test.go@@ -39,7 +39,7 @@ func TestCollision_LoginAttempt(t *testing.T) {// Fill the victim's PASSWORD bucket to its limit and park one attempt in// each neighboring bucket that shares one PK column with it.for range 3 {- granted, err := s.ClaimLoginAttempt(ctx, victim, storepb.LoginAttemptKind_PASSWORD, 3, window)+ granted, err := s.ClaimAttempt(ctx, victim, storepb.LoginAttemptKind_PASSWORD, 3, window)require.NoError(t, err)require.True(t, granted)}@@ -50,7 +50,7 @@ func TestCollision_LoginAttempt(t *testing.T) {{victim, storepb.LoginAttemptKind_MFA}, // same identity, other kind{neighbor, storepb.LoginAttemptKind_PASSWORD}, // same kind, other identity} {- granted, err := s.ClaimLoginAttempt(ctx, seed.identity, seed.kind, 3, window)+ granted, err := s.ClaimAttempt(ctx, seed.identity, seed.kind, 3, window)require.NoError(t, err)require.True(t, granted)}@@ -65,7 +65,7 @@ func TestCollision_LoginAttempt(t *testing.T) {}// The victim's lock must not leak into either neighbor.- granted, err := s.ClaimLoginAttempt(ctx, victim, storepb.LoginAttemptKind_PASSWORD, 3, window)+ granted, err := s.ClaimAttempt(ctx, victim, storepb.LoginAttemptKind_PASSWORD, 3, window)require.NoError(t, err)require.False(t, granted, "the victim bucket is at its limit")require.Equal(t, 1, attempts(victim, storepb.LoginAttemptKind_MFA))@@ -77,6 +77,17 @@ func TestCollision_LoginAttempt(t *testing.T) {require.Equal(t, 1, attempts(victim, storepb.LoginAttemptKind_MFA))require.Equal(t, 1, attempts(neighbor, storepb.LoginAttemptKind_PASSWORD))+ // The send budget writes the same table under a different kind and a+ // different window rule, so it must respect the same boundaries: charge its+ // own (identity, kind) and leave every neighbor sharing one column alone.+ granted, err = s.ClaimAttempt(ctx, victim, storepb.LoginAttemptKind_EMAIL_CODE_SEND, 3, window)+ require.NoError(t, err)+ require.True(t, granted)+ require.Equal(t, 1, attempts(victim, storepb.LoginAttemptKind_EMAIL_CODE_SEND))+ require.Equal(t, 1, attempts(victim, storepb.LoginAttemptKind_MFA), "a send bucket must not reach a credential bucket sharing its identity")+ require.Equal(t, 1, attempts(neighbor, storepb.LoginAttemptKind_PASSWORD))+ require.Zero(t, attempts(neighbor, storepb.LoginAttemptKind_EMAIL_CODE_SEND), "nor another identity sharing its kind")+// The time-scoped purge must not use the lock as a shortcut: backdate only// the neighbor and confirm the purge takes it and nothing else._, err = container.GetDB().ExecContext(ctx, `diff --git a/docs/design/v1-api-audit-2026-08.md b/docs/design/v1-api-audit-2026-08.mdindex e8434a956b..58db84ce8c 100644--- a/docs/design/v1-api-audit-2026-08.md+++ b/docs/design/v1-api-audit-2026-08.md@@ -10,7 +10,7 @@ noted. Fixed findings are removed and listed at the end.| | Problem | Severity ||---|---|---|-| T12 | Anonymous callers can enumerate emails, relay mail, and read your LDAP config | MED |+| T12 | Anonymous callers can read your LDAP config | MED || T18c | Three smaller ones: broken filter, unpaginated list, half-finished delete | MED |---@@ -66,23 +66,31 @@ irreversibly purged, and the error names only the one that failed — not the on### T12 · The unauthenticated surface — MED-12 RPCs allow calls with no credentials. Four are worth attention:--- **Email enumeration.** `Signup` answers "already registered" *before* it checks whether signup is- even allowed, so anyone can test whether an email has an account — on a workspace with signup- disabled. `auth_service.go:298-304` (existence), `:327-329` (restriction)-- **Open mail relay.** `SendEmailLoginCode` will send to any address over the customer's SMTP.- [#21177](https://github.com/bytebase/bytebase/pull/21177) added a domain check, but it only- applies if the domain-restriction license feature is on, enforcement is enabled, *and* a domain- list is set — no default deployment qualifies. The 60s cooldown is per recipient, so volume scales- with the address list. `auth_service_email_code.go:137-179`, `user_service.go:1443-1473`-- **LDAP config disclosure.** `ListIdentityProviders` hands any caller the SSO config for any- workspace ID they guess: LDAP host, port, bind DN, base DN, user filter, plus OAuth/OIDC endpoints- and client IDs. Passwords and secrets are redacted. `idp_service.go:55-85`, `:461-541`+12 RPCs allow calls with no credentials. Two are still open:++- **LDAP config disclosure.** `ListIdentityProviders` hands any caller the SSO config for the+ workspace they name: LDAP host, port, bind DN, base DN, user filter, plus OAuth/OIDC endpoints+ and client IDs. Passwords and secrets are redacted. No guessing is needed self-hosted —+ `GetWorkspace("workspaces/-")` is anonymous too and returns the singleton workspace ID, so the+ disclosure is a two-call chain; and self-hosted is where LDAP is configured.+ `idp_service.go:55-85`, `:461-541`, `workspace_service.go:64-74`++ The endpoint serves three journeys with three different needs — the anonymous login page (which+ needs the authorization-request fields and no LDAP config at all), the SSO admin console (which+ needs everything), and General settings (which needs `count > 0` to guard the+ disallow-password-signin toggle, and which every Workspace Member can reach). Redacting by caller+ closes it, but the durable fix is to give the login page its own message on `AuthenticationInfo`,+ following [#21184](https://github.com/bytebase/bytebase/pull/21184), so a new admin-side config+ field cannot become public by default. Tracked in+ [BYT-10156](https://linear.app/bytebase/issue/BYT-10156/listidentityproviders-leaks-ldap-config-to-anonymous-callers-t12).- **Workspace-existence oracle.** `GetAuthenticationRestriction` (which replaced the actuator leak,now fixed) is anonymous by design and doesn't need membership. Naming a real workspace returns- 200, a fake one returns `InvalidArgument`. The pre-login page genuinely needs most of these- fields; the oracle is the part worth closing. `auth_service.go:107-152`+ 200, a fake one returns `InvalidArgument`. Left open on purpose: workspace IDs are+ `RandomString(16)` with no rename path, so this confirms an ID already held rather than+ enumerating one, and the pre-login page needs the workspace's real settings — so returning+ defaults for an unknown workspace trades a genuine login-page error message for an oracle that+ still distinguishes any workspace with non-default auth settings. `auth_service.go:107-152`,+ `auth_service.go:437` (ID generation)### T18c-iii · `CheckRelease` error codes leak existence — MED · ✅ read myself@@ -139,6 +147,7 @@ constraints.| T7 | [#21102](https://github.com/bytebase/bytebase/pull/21102) — every `CheckRelease` target validated against the parent project before any schema read (its error codes still leak existence — T18c-iii) || T8 `CreateWorksheet` | [#21169](https://github.com/bytebase/bytebase/pull/21169) — `CreateSavedQuery` is now IAM-enforced; Workspace Member holds no saved-query permission, and new queries start creator-private || T12 `GetActuatorInfo` | [#21184](https://github.com/bytebase/bytebase/pull/21184) — anonymous access and the `name` field removed; workspace now comes from the token (the narrower surface that replaced it is T12) |+| T12 email enumeration, mail relay | Two of the four anonymous surfaces; LDAP disclosure and the existence oracle stay open and are what T12 is now. **`Signup`** checks the restriction before it checks existence, so a workspace that refuses every signup — every SaaS workspace, since the override always sets `DisallowSignup` — no longer answers `AlreadyExists` for registered addresses and `PermissionDenied` for the rest. The duplicate is still reported where signup is allowed; only the order moved, and denied duplicates now reach the deferred `SetAuditWorkspaceID` they used to return ahead of. **`SendEmailLoginCode`** caps sign-in-code mail at 1000/hour for the whole deployment, whatever workspace the caller names: SaaS copies `EMAIL_CONFIG` into every workspace it creates, so naming one does not change the sender, and keying on the workspace would hand each tenant its own budget against a shared reputation — with a caller-supplied key besides. The 60s per-recipient cooldown already bounded one address; only a sender-wide cap bounds a campaign, which writes each address exactly once. Claimed before the code row is written, so a refusal leaves a pending code intact, and before the cooldown is consulted, so the answer never depends on whether that recipient has a recent code. Reuses `login_attempt` under a new `EMAIL_CODE_SEND` kind — no migration, `kind` is text — but not its semantics: a lockout resets only after a quiet window, which for a volume budget would turn "1000 per hour" into "1000 ever, until an hour of silence", so this kind reads `last_attempt_at` as the window's start. Accepted: spending the cap delays sign-in codes deployment-wide until the window passes, and one address can spend it as cheaply as many since the cost is the requests — bounded and recoverable, unlike the deliverability damage it prevents. Nothing here varies by recipient: a member exemption, a redeemability gate and a cooldown pre-check were each implemented and removed, because on an endpoint answering anonymous callers any recipient-dependent branch is an oracle || T13 `SearchWorksheets` | [#21160](https://github.com/bytebase/bytebase/pull/21160) + [#21178](https://github.com/bytebase/bytebase/pull/21178) — visibility predicate pushed into SQL before `LIMIT` || T13 issue filters | `approval_status` and `current_approver` are matched in SQL before `LIMIT`, so a filtered page can no longer come back empty under a live page token. The status is a `CASE` over `payload->'approval'` mirroring `computeApprovalStatus`; `current_approver` cannot be resolved in SQL alone (binding conditions and group expansion are evaluated in Go), so the caller passes down the `(project, role)` pairs the named user holds, the same shape as the saved-query `AccessMembers` predicate. Accepted with it: the predicates are not indexable, so a filtered list scans until it has a full page of matches — measured on 50,000 issues across 40 projects, that is ~9 ms against ~14 ms for the same unfiltered query, and ~3.5 ms in the zero-match case, because PostgreSQL drives the join from the small `(project, role)` set, so no expression index is warranted yet. Deliberately unchanged: the filter still ignores rejection and self-approval, so a rejected issue names the holder of the *next* role as its current approver — masked in the default view, and worth its own fix || T18 worksheet write/delete | [#21169](https://github.com/bytebase/bytebase/pull/21169) + [#21181](https://github.com/bytebase/bytebase/pull/21181) — per-verb permissions; SQL Editor Read User can no longer rewrite or delete |diff --git a/proto/gen/grpc-doc/store/README.md b/proto/gen/grpc-doc/store/README.mdindex ceab63c542..8f9808cf04 100644--- a/proto/gen/grpc-doc/store/README.md+++ b/proto/gen/grpc-doc/store/README.md@@ -960,15 +960,21 @@ Stored as the enum name string in email_verification_code.purpose column.<a name="bytebase-store-LoginAttemptKind"></a>### LoginAttemptKind-LoginAttemptKind names which credential's attempt limit a login_attempt row-tracks. Stored as the enum name string in login_attempt.kind column.+LoginAttemptKind names what a login_attempt row counts. Stored as the enum+name string in login_attempt.kind column. The kind also says what the+identity column holds: the three credential kinds below count failed guesses+against a person, share one attempt limit, and are cleared by a successful+verification.| Name | Number | Description || ---- | ------ | ----------- || LOGIN_ATTEMPT_KIND_UNSPECIFIED | 0 | || PASSWORD | 1 | |-| EMAIL_CODE | 2 | |+| EMAIL_CODE | 2 | Submitting a 6-digit code. Sign-in, password reset and re-authentication share one bucket per email, so a guess anywhere counts everywhere. || MFA | 3 | |+| EMAIL_CODE_SEND | 4 | Sending those codes rather than guessing them — the opposite direction, and the reason it is a separate kind. Its identity is the sending deployment and not a person, so exhausting it throttles outbound mail and locks no account, and nothing clears it because a delivered email is the thing counted and there is no success to forgive.++It also reads last_attempt_at differently: for this kind the column is the window's start, not the latest send, so the count resets on a fixed schedule. The kinds above intentionally reset only after a quiet window — wrong for a volume budget, where a steady trickle would never reset and "N per hour" would become "N ever". |diff --git a/proto/gen/grpc-doc/store/index.html b/proto/gen/grpc-doc/store/index.htmlindex bdd30e5ae7..894c7e282f 100644--- a/proto/gen/grpc-doc/store/index.html+++ b/proto/gen/grpc-doc/store/index.html@@ -3207,7 +3207,7 @@ This information is not authenticated and should be treated accordingly. </p></t</table><h3 id="bytebase.store.LoginAttemptKind">LoginAttemptKind</h3>- <p>LoginAttemptKind names which credential's attempt limit a login_attempt row</p><p>tracks. Stored as the enum name string in login_attempt.kind column.</p>+ <p>LoginAttemptKind names what a login_attempt row counts. Stored as the enum</p><p>name string in login_attempt.kind column. The kind also says what the</p><p>identity column holds: the three credential kinds below count failed guesses</p><p>against a person, share one attempt limit, and are cleared by a successful</p><p>verification.</p><table class="enum-table"><thead><tr><td>Name</td><td>Number</td><td>Description</td></tr>@@ -3229,7 +3229,8 @@ This information is not authenticated and should be treated accordingly. </p></t<tr><td>EMAIL_CODE</td><td>2</td>- <td><p></p></td>+ <td><p>Submitting a 6-digit code. Sign-in, password reset and re-authentication+share one bucket per email, so a guess anywhere counts everywhere.</p></td></tr><tr>@@ -3238,6 +3239,22 @@ This information is not authenticated and should be treated accordingly. </p></t<td><p></p></td></tr>+ <tr>+ <td>EMAIL_CODE_SEND</td>+ <td>4</td>+ <td><p>Sending those codes rather than guessing them — the opposite direction, and+the reason it is a separate kind. Its identity is the sending deployment+and not a person, so exhausting it throttles outbound+mail and locks no account, and nothing clears it because a delivered email+is the thing counted and there is no success to forgive.++It also reads last_attempt_at differently: for this kind the column is the+window's start, not the latest send, so the count resets on a fixed+schedule. The kinds above intentionally reset only after a quiet window —+wrong for a volume budget, where a steady trickle would never reset and+"N per hour" would become "N ever".</p></td>+ </tr>+</tbody></table>diff --git a/proto/store/store/auth.proto b/proto/store/store/auth.protoindex 38d61a3dd2..34bf206b18 100644--- a/proto/store/store/auth.proto+++ b/proto/store/store/auth.proto@@ -15,11 +15,28 @@ enum EmailVerificationCodePurpose {REAUTH = 3;}-// LoginAttemptKind names which credential's attempt limit a login_attempt row-// tracks. Stored as the enum name string in login_attempt.kind column.+// LoginAttemptKind names what a login_attempt row counts. Stored as the enum+// name string in login_attempt.kind column. The kind also says what the+// identity column holds: the three credential kinds below count failed guesses+// against a person, share one attempt limit, and are cleared by a successful+// verification.enum LoginAttemptKind {LOGIN_ATTEMPT_KIND_UNSPECIFIED = 0;PASSWORD = 1;+ // Submitting a 6-digit code. Sign-in, password reset and re-authentication+ // share one bucket per email, so a guess anywhere counts everywhere.EMAIL_CODE = 2;MFA = 3;+ // Sending those codes rather than guessing them — the opposite direction, and+ // the reason it is a separate kind. Its identity is the sending deployment+ // and not a person, so exhausting it throttles outbound+ // mail and locks no account, and nothing clears it because a delivered email+ // is the thing counted and there is no success to forgive.+ //+ // It also reads last_attempt_at differently: for this kind the column is the+ // window's start, not the latest send, so the count resets on a fixed+ // schedule. The kinds above intentionally reset only after a quiet window —+ // wrong for a volume budget, where a steady trickle would never reset and+ // "N per hour" would become "N ever".+ EMAIL_CODE_SEND = 4;}