Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

feat(auth): bound credential guessing with a per-identity login_attempt table (#21234)

Danny Xu791ffe65bb16
diff --git a/backend/api/mcp/gen/openapi.yaml b/backend/api/mcp/gen/openapi.yaml
index adba27f889..a74de510e7 100644
--- a/backend/api/mcp/gen/openapi.yaml
+++ b/backend/api/mcp/gen/openapi.yaml
@@ -11767,10 +11767,12 @@ components:
token:
type: string
title: token
+ maxLength: 65536
description: External OIDC token (JWT) from CI/CD platform.
email:
type: string
title: email
+ maxLength: 254
description: |-
Workload Identity email for identifying which identity to authenticate as.
Format: {name}@workload.bytebase.com
@@ -14961,11 +14963,19 @@ components:
email:
type: string
title: email
- description: User's email address.
+ maxLength: 254
+ description: |-
+ User's email address.
+ Bounded so an oversized identity is refused at the edge before any
+ handler runs; the login-attempt lockout keys rows by this value.
password:
type: string
title: password
- description: User's password for authentication.
+ description: |
+ User's password for authentication. Bounded for abuse only: LDAP
+ directories may accept passwords beyond bcrypt's 72-byte limit, and the
+ local-password path rejects longer inputs itself.
+ string.max_bytes = 512
web:
type: boolean
title: web
@@ -14975,6 +14985,7 @@ components:
idpName:
type: string
title: idp_name
+ maxLength: 256
description: |-
The name of the identity provider.
Format: idps/{idp}
@@ -14987,24 +14998,28 @@ components:
- string
- "null"
title: otp_code
+ maxLength: 64
description: The otp_code is used to verify the user's identity by MFA.
recoveryCode:
type:
- string
- "null"
title: recovery_code
+ maxLength: 64
description: The recovery_code is used to recovery the user's identity with MFA.
mfaTempToken:
type:
- string
- "null"
title: mfa_temp_token
+ maxLength: 4096
description: The mfa_temp_token is used to verify the user's identity by MFA.
emailCode:
type:
- string
- "null"
title: email_code
+ maxLength: 64
description: |-
6-digit code from email for passwordless login/signup.
Pairs with `email`. Mutually exclusive with `password` and `idp_name`.
@@ -15013,6 +15028,7 @@ components:
- string
- "null"
title: workspace
+ maxLength: 256
description: |-
Preferred workspace to land in after login. If the user is a member of this
workspace, the token is issued for it; otherwise falls back to the default
@@ -15622,6 +15638,7 @@ components:
code:
type: string
title: code
+ maxLength: 4096
description: Authorization code from OAuth2 provider.
title: OAuth2IdentityProviderContext
additionalProperties: false
@@ -15685,6 +15702,7 @@ components:
code:
type: string
title: code
+ maxLength: 4096
description: Authorization code from OIDC provider.
title: OIDCIdentityProviderContext
additionalProperties: false
@@ -17332,12 +17350,17 @@ components:
email:
type: string
title: email
- description: The email address of the account to reset.
+ maxLength: 254
+ description: |-
+ The email address of the account to reset.
+ Bounded so an oversized identity is refused at the edge before any
+ handler runs; the login-attempt lockout keys rows by this value.
workspace:
type:
- string
- "null"
title: workspace
+ maxLength: 256
description: |-
Optional workspace context captured at send time, used to locate the EMAIL setting,
and later (at verify time) for signup gate checks and workspace assignment.
@@ -17351,15 +17374,22 @@ components:
email:
type: string
title: email
- description: The email address of the account.
+ maxLength: 254
+ description: |-
+ The email address of the account.
+ Bounded so an oversized identity is refused at the edge before any
+ handler runs; the login-attempt lockout keys rows by this value.
code:
type: string
title: code
+ maxLength: 64
description: The 6-digit code from the reset email.
newPassword:
type: string
title: new_password
- description: The new password to set.
+ description: |
+ The new password to set.
+ string.max_bytes = 72
title: ResetPasswordRequest
additionalProperties: false
bytebase.v1.Restriction:
@@ -18873,12 +18903,17 @@ components:
email:
type: string
title: email
- description: The email address to send the code to.
+ maxLength: 254
+ description: |-
+ The email address to send the code to.
+ Bounded so an oversized identity is refused at the edge before any
+ handler runs; the login-attempt lockout keys rows by this value.
workspace:
type:
- string
- "null"
title: workspace
+ maxLength: 256
description: |-
Optional workspace context captured at send time, used to locate the EMAIL setting,
and later (at verify time) for signup gate checks and workspace assignment.
@@ -19161,14 +19196,21 @@ components:
email:
type: string
title: email
- description: The email for the new account.
+ maxLength: 254
+ description: |-
+ The email for the new account.
+ Bounded so an oversized identity is refused at the edge before any
+ handler runs; the login-attempt lockout keys rows by this value.
password:
type: string
title: password
- description: The password for the new account.
+ description: |
+ The password for the new account.
+ string.max_bytes = 72
title:
type: string
title: title
+ maxLength: 200
description: The display name of the user.
title: SignupRequest
additionalProperties: false
@@ -19430,6 +19472,7 @@ components:
workspace:
type: string
title: workspace
+ maxLength: 256
description: |-
The target workspace to switch to.
Format: workspaces/{workspace}
@@ -19442,18 +19485,21 @@ components:
- string
- "null"
title: otp_code
+ maxLength: 64
description: OTP code for MFA verification. Required if the target workspace enforces MFA.
recoveryCode:
type:
- string
- "null"
title: recovery_code
+ maxLength: 64
description: Recovery code for MFA verification (alternative to otp_code).
mfaTempToken:
type:
- string
- "null"
title: mfa_temp_token
+ maxLength: 4096
description: Temporary MFA token from a previous SwitchWorkspace call that returned mfa_temp_token.
title: SwitchWorkspaceRequest
additionalProperties: false
@@ -20907,6 +20953,7 @@ components:
email:
type: string
title: email
+ maxLength: 254
description: The new email address.
title: UpdateEmailRequest
additionalProperties: false
@@ -21359,6 +21406,7 @@ components:
email:
type: string
title: email
+ maxLength: 254
description: The email address of the user, used for login and notifications.
title:
type: string
@@ -21368,7 +21416,9 @@ components:
password:
type: string
title: password
- description: The password for authentication. Only used during user creation or password updates.
+ description: |
+ The password for authentication. Only used during user creation or password updates.
+ string.max_bytes = 72
mfaEnabled:
type: boolean
title: mfa_enabled
diff --git a/backend/api/v1/account_email_validation.go b/backend/api/v1/account_email_validation.go
index 71ce99e56c..8dae7d95b7 100644
--- a/backend/api/v1/account_email_validation.go
+++ b/backend/api/v1/account_email_validation.go
@@ -1,11 +1,19 @@
package v1
import (
+ "strings"
+
"github.com/pkg/errors"
"github.com/bytebase/bytebase/backend/common"
)
+// normalizeEmail canonicalizes a submitted email for lookups, lockout
+// identities, and audit resources — these must all key the same string.
+func normalizeEmail(email string) string {
+ return strings.ToLower(strings.TrimSpace(email))
+}
+
func validateServiceAccountEmail(email string) error {
if err := common.ValidateEmail(email); err != nil {
return err
diff --git a/backend/api/v1/audit.go b/backend/api/v1/audit.go
index 58c4cb41e2..c38fa504bb 100644
--- a/backend/api/v1/audit.go
+++ b/backend/api/v1/audit.go
@@ -438,17 +438,17 @@ func getRequestResource(request any, method string) string {
case *v1pb.CreateUserRequest:
return r.GetUser().GetName()
case *v1pb.LoginRequest:
- return strings.ToLower(strings.TrimSpace(r.GetEmail()))
+ return normalizeEmail(r.GetEmail())
case *v1pb.SignupRequest:
return r.GetEmail()
case *v1pb.ExchangeTokenRequest:
return r.GetEmail()
case *v1pb.RequestPasswordResetRequest:
- return strings.ToLower(strings.TrimSpace(r.GetEmail()))
+ return normalizeEmail(r.GetEmail())
case *v1pb.ResetPasswordRequest:
- return strings.ToLower(strings.TrimSpace(r.GetEmail()))
+ return normalizeEmail(r.GetEmail())
case *v1pb.SendEmailLoginCodeRequest:
- return strings.ToLower(strings.TrimSpace(r.GetEmail()))
+ return normalizeEmail(r.GetEmail())
case *v1pb.CreateInstanceRequest:
if r.GetParent() == "" {
return common.FormatInstance(r.GetInstanceId())
diff --git a/backend/api/v1/auth_service.go b/backend/api/v1/auth_service.go
index 3f3e5ef389..3a1b6bfaa4 100644
--- a/backend/api/v1/auth_service.go
+++ b/backend/api/v1/auth_service.go
@@ -2,17 +2,11 @@ package v1
import (
"context"
- "crypto/hmac"
- "crypto/rand"
- "crypto/sha256"
"crypto/subtle"
- "encoding/hex"
- "fmt"
"log/slog"
"net/http"
"os"
"slices"
- "strings"
"time"
"connectrpc.com/connect"
@@ -25,53 +19,32 @@ import (
"github.com/bytebase/bytebase/backend/api/auth"
"github.com/bytebase/bytebase/backend/common"
"github.com/bytebase/bytebase/backend/common/log"
- "github.com/bytebase/bytebase/backend/common/qb"
"github.com/bytebase/bytebase/backend/component/config"
"github.com/bytebase/bytebase/backend/component/iam"
"github.com/bytebase/bytebase/backend/enterprise"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"
"github.com/bytebase/bytebase/backend/generated-go/v1/v1connect"
- "github.com/bytebase/bytebase/backend/plugin/idp/ldap"
- "github.com/bytebase/bytebase/backend/plugin/idp/oauth2"
- "github.com/bytebase/bytebase/backend/plugin/idp/oidc"
"github.com/bytebase/bytebase/backend/plugin/idp/wif"
- "github.com/bytebase/bytebase/backend/plugin/mailer"
"github.com/bytebase/bytebase/backend/store"
- "github.com/bytebase/bytebase/backend/utils"
)
const (
- emailCodeLength = 6
- emailCodeExpiry = 10 * time.Minute
- emailCodeMaxAttempts = 5
- emailCodeResendCooldown = 60 * time.Second
-
// mfaTempTokenDuration is the duration for MFA temporary tokens.
// Following industry standards (Okta: 5 minutes, Auth0: 10 minutes, AWS Cognito: 3 minutes).
// A short duration reduces the attack window for TOTP brute-force attempts.
mfaTempTokenDuration = 5 * time.Minute
- // Login rate limiting configuration.
- // Password phase: 10 failed attempts within 10 minutes.
- passwordMaxFailedAttempts = 10 // Will be used for password rate limiting
- passwordLockoutWindow = 10 * time.Minute // Will be used for password rate limiting
-
- // MFA phase: 5 failed attempts within 5 minutes.
- mfaMaxFailedAttempts = 5
- mfaLockoutWindow = 5 * time.Minute
-
// Error messages for authentication failures.
- // These constants are used both for error responses and for querying audit logs during rate limiting.
errMsgInvalidCredentials = "invalid email or password"
errMsgInvalidMFACode = "invalid MFA code"
errMsgInvalidRecoveryCode = "invalid recovery code"
- errMsgTooManyPassword = "too many failed login attempts, please try again later" // Will be used for password rate limiting
- errMsgTooManyMFA = "too many failed MFA attempts, please try again later"
)
+const setCookieHeader = "Set-Cookie"
+
var (
- invalidCredentialsError = connect.NewError(connect.CodeUnauthenticated, errors.Errorf(errMsgInvalidCredentials))
+ invalidCredentialsError = connect.NewError(connect.CodeUnauthenticated, errors.New(errMsgInvalidCredentials))
)
type loginAuthMethod string
@@ -92,23 +65,17 @@ func loginAuthMethodFromRequest(request *v1pb.LoginRequest) loginAuthMethod {
return loginAuthMethodPassword
}
-func loginAuthMethodFromString(method string) loginAuthMethod {
- switch loginAuthMethod(method) {
- case loginAuthMethodIDP:
- return loginAuthMethodIDP
- case loginAuthMethodEmailCode:
- return loginAuthMethodEmailCode
- default:
- return loginAuthMethodPassword
- }
-}
-
func loginAuthMethodFromMFATempToken(token, secret string) (string, loginAuthMethod, error) {
email, method, err := auth.GetUserEmailAndLoginMethodFromMFATempToken(token, secret)
if err != nil {
return "", loginAuthMethodPassword, err
}
- return email, loginAuthMethodFromString(method), nil
+ switch m := loginAuthMethod(method); m {
+ case loginAuthMethodIDP, loginAuthMethodEmailCode:
+ return email, m, nil
+ default:
+ return email, loginAuthMethodPassword, nil
+ }
}
func (m loginAuthMethod) requiresPasswordReset() bool {
@@ -218,54 +185,57 @@ func (s *AuthService) Login(ctx context.Context, req *connect.Request[v1pb.Login
if err != nil {
return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to resolve workspace"))
}
- // If the user has no workspace (e.g. left all workspaces), provision a new one.
+ // If the user has no workspace (e.g. left all workspaces), provision one.
if workspaceID == "" {
- workspaceID, err = s.provisionWorkspaceForNewUser(ctx, loginUser.Email)
+ targetWorkspaceID, isMember, err := s.resolveWorkspaceIDByEmail(ctx, loginUser.Email, preferredWS)
+ if err != nil {
+ return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to resolve target workspace"))
+ }
+ workspaceID, err = s.provisionResolvedWorkspace(ctx, loginUser.Email, targetWorkspaceID, isMember)
if err != nil {
return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to provision workspace"))
}
}
common.SetAuditWorkspaceID(ctx, workspaceID)
- // 3. Post-auth checks (deleted, domain, license)
- if err := s.validateLoginPermissions(ctx, loginUser, workspaceID, request); err != nil {
+ // 4. Post-auth checks (deleted, domain, license). The fetched restriction
+ // is reused by needResetPassword below to spare a duplicate settings read.
+ restriction, err := s.validateLoginPermissions(ctx, loginUser, workspaceID, request)
+ if err != nil {
return nil, err
}
- // 4. Check if MFA challenge needed (returns early with temp token)
+ // 5. Check if MFA challenge needed (returns early with temp token)
if resp, err := s.checkMFARequired(ctx, loginUser, workspaceID, mfaSecondLogin, loginMethod); err != nil {
return nil, err
} else if resp != nil {
return resp, nil
}
- // 5. Generate token (workspace already resolved)
+ // 6. Generate token (workspace already resolved)
token, err := s.generateLoginToken(ctx, loginUser, workspaceID)
if err != nil {
return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to generate access token"))
}
- // 6. Build response and finalize
- requireResetPassword := loginMethod.requiresPasswordReset() && s.needResetPassword(ctx, loginUser, workspaceID)
- return s.finalizeLogin(ctx, req, loginUser, token, workspaceID, requireResetPassword)
+ // 7. Build response and finalize
+ requireResetPassword := loginMethod.requiresPasswordReset() && s.needResetPassword(ctx, loginUser, workspaceID, restriction)
+ return s.finalizeLogin(ctx, req.Header(), request.Web, loginUser, token, workspaceID, requireResetPassword)
}
-func (s *AuthService) needResetPassword(ctx context.Context, user *store.UserMessage, workspaceID string) bool {
+func (s *AuthService) needResetPassword(ctx context.Context, user *store.UserMessage, workspaceID string, restriction *v1pb.Restriction) bool {
// Reset password restriction only works for end user with email & password login.
if user.Type != storepb.PrincipalType_END_USER {
return false
}
- restriction, err := getAccountRestriction(
- ctx,
- s.store,
- s.licenseService,
- s.profile.SaaS,
- workspaceID,
- )
- if err != nil {
- slog.Error("failed to get workspace restriction", log.BBError(err), slog.String("workspace", workspaceID))
- return false
+ if restriction == nil {
+ var err error
+ restriction, err = getAccountRestriction(ctx, s.store, s.licenseService, s.profile.SaaS, workspaceID)
+ if err != nil {
+ slog.Error("failed to get workspace restriction", log.BBError(err), slog.String("workspace", workspaceID))
+ return false
+ }
}
// Don't need to reset password if password signin is not allowed.
@@ -310,7 +280,7 @@ func (s *AuthService) needResetPassword(ctx context.Context, user *store.UserMes
// - Otherwise, creates a new workspace with the user as admin.
func (s *AuthService) Signup(ctx context.Context, req *connect.Request[v1pb.SignupRequest]) (*connect.Response[v1pb.LoginResponse], error) {
request := req.Msg
- email := strings.ToLower(strings.TrimSpace(request.Email))
+ email := normalizeEmail(request.Email)
if email == "" {
return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("email must be set"))
}
@@ -335,7 +305,7 @@ func (s *AuthService) Signup(ctx context.Context, req *connect.Request[v1pb.Sign
// 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.
- targetWorkspaceID, _, err := s.resolveWorkspaceIDByEmail(ctx, email)
+ targetWorkspaceID, targetIsMember, err := s.resolveWorkspaceIDByEmail(ctx, email, "")
if err != nil {
return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to resolve target workspace"))
}
@@ -361,7 +331,7 @@ func (s *AuthService) Signup(ctx context.Context, req *connect.Request[v1pb.Sign
return nil, err
}
- workspaceID, err := s.provisionWorkspaceForNewUser(ctx, email)
+ workspaceID, err := s.provisionResolvedWorkspace(ctx, email, targetWorkspaceID, targetIsMember)
if err != nil {
return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to provision workspace"))
}
@@ -382,55 +352,13 @@ func (s *AuthService) Signup(ctx context.Context, req *connect.Request[v1pb.Sign
return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to create user"))
}
- // Step 3: Generate token and finalize login.
- tokenDuration := auth.GetAccessTokenDuration(ctx, s.store, s.licenseService, workspaceID)
- token, err := auth.GenerateAccessToken(user.Email, workspaceID, s.secret, tokenDuration)
+ // Step 3: Generate token and finalize login. Signup is always web-based —
+ // finalizeLogin sets the tokens as HTTP-only cookies.
+ token, err := s.generateLoginToken(ctx, user, workspaceID)
if err != nil {
return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to generate access token"))
}
-
- response := &v1pb.LoginResponse{}
- resp := connect.NewResponse(response)
-
- // Signup is always web-based — set tokens as HTTP-only cookies.
- origin := req.Header().Get("Origin")
- cookie := auth.GetTokenCookie(ctx, s.store, s.licenseService, workspaceID, origin, token)
- resp.Header().Add("Set-Cookie", cookie.String())
-
- refreshToken, err := auth.GenerateOpaqueToken()
- if err != nil {
- return nil, connect.NewError(connect.CodeInternal, errors.Wrap(err, "failed to generate refresh token"))
- }
- refreshTokenDuration := auth.GetRefreshTokenDuration(ctx, s.store, s.licenseService, workspaceID)
- if err := s.store.CreateWebRefreshToken(ctx, &store.WebRefreshTokenMessage{
- TokenHash: auth.HashToken(refreshToken),
- UserEmail: user.Email,
- ExpiresAt: time.Now().Add(refreshTokenDuration),
- }); err != nil {
- return nil, connect.NewError(connect.CodeInternal, errors.Wrap(err, "failed to create refresh token"))
- }
- refreshCookie := auth.GetRefreshTokenCookie(origin, refreshToken, refreshTokenDuration)
- resp.Header().Add("Set-Cookie", refreshCookie.String())
-
- // Update last login time and workspace.
- if _, err := s.store.UpdateUser(ctx, user, &store.UpdateUserMessage{
- Profile: &storepb.UserProfile{
- LastLoginTime: timestamppb.Now(),
- Source: user.Profile.GetSource(),
- LastLoginWorkspace: workspaceID,
- },
- }); err != nil {
- slog.Error("failed to update user profile", log.BBError(err), slog.String("user", user.Email))
- }
-
- v1User, err := convertToUser(ctx, s.iamManager, user)
- if err != nil {
- return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to convert user"))
- }
- v1User.Workspace = common.FormatWorkspace(workspaceID)
- response.User = v1User
-
- return resp, nil
+ return s.finalizeLogin(ctx, req.Header(), true, user, token, workspaceID, false)
}
// resolveWorkspaceIDByEmail determines which workspace a signing-up email would
@@ -441,7 +369,24 @@ func (s *AuthService) Signup(ctx context.Context, req *connect.Request[v1pb.Sign
// resolveWorkspaceIDByEmail returns (workspaceID, isMember).
// isMember is true when the user already has an IAM binding in the returned workspace.
// When false, the returned workspaceID is the self-host singleton (user needs to be added).
-func (s *AuthService) resolveWorkspaceIDByEmail(ctx context.Context, email string) (string, bool, error) {
+// A non-empty preferredWorkspaceID wins when it is one of the email's own
+// memberships — mirroring resolveWorkspaceForLogin for existing users — so a
+// multi-invited email lands in the workspace the login flow named rather than
+// the oldest invitation.
+func (s *AuthService) resolveWorkspaceIDByEmail(ctx context.Context, email, preferredWorkspaceID string) (string, bool, error) {
+ if preferredWorkspaceID != "" {
+ preferredWS, err := s.store.FindWorkspace(ctx, &store.FindWorkspaceMessage{
+ WorkspaceID: &preferredWorkspaceID,
+ Email: email,
+ IncludeAllUser: !s.profile.SaaS,
+ })
+ if err != nil {
+ return "", false, errors.Wrapf(err, "failed to find workspace")
+ }
+ if preferredWS != nil {
+ return preferredWS.ResourceID, true, nil
+ }
+ }
existingWS, err := s.store.FindWorkspace(ctx, &store.FindWorkspaceMessage{
Email: email,
IncludeAllUser: !s.profile.SaaS,
@@ -462,19 +407,15 @@ func (s *AuthService) resolveWorkspaceIDByEmail(ctx context.Context, email strin
return "", false, nil
}
-// provisionWorkspaceForNewUser returns a workspace ID for a freshly-created user.
-// If the email was pre-invited to existing workspaces (via IAM), returns the first one.
-// Otherwise creates a new workspace (SaaS: per-user; self-hosted: joins the singleton).
-// Called by both the Signup RPC and the email-code signup branch of Login.
-func (s *AuthService) provisionWorkspaceForNewUser(ctx context.Context, email string) (string, error) {
- // Step 1: Resolve the target workspace. isMember indicates whether the user already has
- // an IAM binding. For pre-invited users we must NOT patch IAM — PatchWorkspaceIamPolicy
- // is a set-replacement that would downgrade an admin to member.
- workspaceID, isMember, err := s.resolveWorkspaceIDByEmail(ctx, email)
- if err != nil {
- return "", err
- }
+// provisionResolvedWorkspace assigns a workspace for a user who has none: the
+// pre-invited workspace (or self-hosted singleton) resolved by the caller via
+// resolveWorkspaceIDByEmail — callers that gate-check first reuse that same
+// snapshot here — or a freshly created workspace with the user as admin.
+// isMember indicates whether the user already has an IAM binding; for
+// pre-invited users we must NOT patch IAM — PatchWorkspaceIamPolicy is a
+// set-replacement that would downgrade an admin to member.
+func (s *AuthService) provisionResolvedWorkspace(ctx context.Context, email, workspaceID string, isMember bool) (string, error) {
if workspaceID != "" {
if !s.profile.SaaS && !isMember {
// Self-hosted, new user joining the singleton workspace — add as member.
@@ -489,7 +430,7 @@ func (s *AuthService) provisionWorkspaceForNewUser(ctx context.Context, email st
return workspaceID, nil
}
- // Step 2: No existing workspace — create a new one with the user as admin.
+ // No existing workspace — create a new one with the user as admin.
wsID, err := common.RandomString(16)
if err != nil {
return "", errors.Wrap(err, "failed to generate workspace ID")
@@ -521,8 +462,8 @@ func (s *AuthService) clearSessionAndSetCookies(ctx context.Context, reqHeaders
}
}
origin := reqHeaders.Get("Origin")
- respHeaders.Add("Set-Cookie", auth.GetTokenCookie(ctx, s.store, s.licenseService, workspaceID, origin, "").String())
- respHeaders.Add("Set-Cookie", auth.GetRefreshTokenCookie(origin, "", 0).String())
+ respHeaders.Add(setCookieHeader, auth.GetTokenCookie(ctx, s.store, s.licenseService, workspaceID, origin, "").String())
+ respHeaders.Add(setCookieHeader, auth.GetRefreshTokenCookie(origin, "", 0).String())
}
// Refresh exchanges a refresh token for new access and refresh tokens.
@@ -596,34 +537,28 @@ func (s *AuthService) Refresh(ctx context.Context, req *connect.Request[v1pb.Ref
return nil, connect.NewError(connect.CodeInternal, errors.Wrap(err, "failed to generate access token"))
}
- newRefreshToken, err := auth.GenerateOpaqueToken()
- if err != nil {
- return nil, connect.NewError(connect.CodeInternal, errors.Wrap(err, "failed to generate refresh token"))
- }
-
- // Inherit expiration from the original token (absolute session lifetime)
- if err := s.store.CreateWebRefreshToken(ctx, &store.WebRefreshTokenMessage{
- TokenHash: auth.HashToken(newRefreshToken),
- UserEmail: user.Email,
- ExpiresAt: stored.ExpiresAt,
- }); err != nil {
- return nil, connect.NewError(connect.CodeInternal, errors.Wrap(err, "failed to create refresh token"))
- }
-
- // 6. Set cookies and return
+ // 6. Rotate the session: the new refresh token inherits the original
+ // expiration (absolute session lifetime).
resp := connect.NewResponse(&v1pb.RefreshResponse{})
- origin := req.Header().Get("Origin")
- resp.Header().Add("Set-Cookie", auth.GetTokenCookie(ctx, s.store, s.licenseService, workspaceID, origin, accessToken).String())
- resp.Header().Add("Set-Cookie", auth.GetRefreshTokenCookie(origin, newRefreshToken, time.Until(stored.ExpiresAt)).String())
-
+ if err := s.issueSessionCookies(ctx, resp.Header(), req.Header().Get("Origin"), user.Email, workspaceID, accessToken, stored.ExpiresAt); err != nil {
+ return nil, err
+ }
return resp, nil
}
func (s *AuthService) getAndVerifyUser(ctx context.Context, request *v1pb.LoginRequest) (*store.UserMessage, error) {
- email := strings.ToLower(strings.TrimSpace(request.Email))
-
- // Check if user is locked out due to too many failed password attempts.
- if err := s.checkPasswordLockout(ctx, email); err != nil {
+ email := normalizeEmail(request.Email)
+ // An invalid-syntax email can never be an account; reject it before the
+ // claim with the same error a wrong password gets.
+ if !common.IsValidEmail(email) {
+ return nil, invalidCredentialsError
+ }
+ // Claim an attempt slot before the credential is checked; unknown emails
+ // lock at the same attempt with the same error (no existence oracle).
+ // A successful login holds its slot only until the clear below, so more
+ // than loginAttemptMax concurrent correct logins for one identity can see
+ // transient refusals — accepted; they end when the first clear lands.
+ if err := s.claimLoginAttempt(ctx, email, storepb.LoginAttemptKind_PASSWORD); err != nil {
return nil, err
}
@@ -652,309 +587,13 @@ func (s *AuthService) getAndVerifyUser(ctx context.Context, request *v1pb.LoginR
if user == nil {
return nil, connect.NewError(connect.CodeUnauthenticated, errors.Errorf("user %q not found", account.Email))
}
+ s.clearLoginAttempt(ctx, email, storepb.LoginAttemptKind_PASSWORD)
return user, nil
}
-// getOrCreateUserWithIDP authenticates a user via an identity provider (SSO).
-// Login API has allow_without_credential, so there's no workspace in the token context.
-// We resolve workspace from the IDP entity (IDP resource_id is globally unique).
-func (s *AuthService) getOrCreateUserWithIDP(ctx context.Context, request *v1pb.LoginRequest) (*store.UserMessage, error) {
- idpID, err := common.GetIdentityProviderID(request.IdpName)
- if err != nil {
- return nil, connect.NewError(connect.CodeInvalidArgument, errors.Wrapf(err, "failed to get identity provider ID"))
- }
- // Look up IDP without workspace filter — IDP resource_id is globally unique.
- // The workspace is resolved from the IDP entity.
- idp, err := s.store.GetIdentityProviderByID(ctx, idpID)
- if err != nil {
- return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to get identity provider"))
- }
- if idp == nil {
- return nil, connect.NewError(connect.CodeNotFound, errors.Errorf("identity provider not found"))
- }
-
- // For workspace-scoped IDPs, use the IDP's workspace.
- // For global IDPs (SaaS), workspace is resolved after authentication from user membership.
- workspaceID := idp.Workspace
- externalURL, err := utils.GetEffectiveExternalURL(ctx, s.store, s.profile, workspaceID)
- if err != nil {
- return nil, err
- }
-
- var userInfo *storepb.IdentityProviderUserInfo
- switch idp.Type {
- case storepb.IdentityProviderType_OAUTH2:
- oauth2Context := request.IdpContext.GetOauth2Context()
- if oauth2Context == nil {
- return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("missing OAuth2 context"))
- }
- oauth2IdentityProvider, err := oauth2.NewIdentityProvider(idp.Config.GetOauth2Config())
- if err != nil {
- return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to create new OAuth2 identity provider"))
- }
- redirectURL := fmt.Sprintf("%s/oauth/callback", externalURL)
- token, err := oauth2IdentityProvider.ExchangeToken(ctx, redirectURL, oauth2Context.Code)
- if err != nil {
- return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to exchange token"))
- }
- userInfo, _, err = oauth2IdentityProvider.UserInfo(token)
- if err != nil {
- return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to get user info"))
- }
- case storepb.IdentityProviderType_OIDC:
- oidcContext := request.IdpContext.GetOidcContext()
- if oidcContext == nil {
- return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("missing OIDC context"))
- }
-
- oidcIDP, err := oidc.NewIdentityProvider(ctx, idp.Config.GetOidcConfig())
- if err != nil {
- return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to create new OIDC identity provider"))
- }
-
- redirectURL := fmt.Sprintf("%s/oidc/callback", externalURL)
- token, err := oidcIDP.ExchangeToken(ctx, redirectURL, oidcContext.Code)
- if err != nil {
- return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to exchange token"))
- }
-
- userInfo, _, err = oidcIDP.UserInfo(ctx, token, "")
- if err != nil {
- return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to get user info"))
- }
- case storepb.IdentityProviderType_LDAP:
- idpConfig := idp.Config.GetLdapConfig()
- ldapIDP, err := ldap.NewIdentityProvider(
- ldap.IdentityProviderConfig{
- Host: idpConfig.Host,
- Port: int(idpConfig.Port),
- SkipTLSVerify: idpConfig.SkipTlsVerify,
- BindDN: idpConfig.BindDn,
- BindPassword: idpConfig.BindPassword,
- BaseDN: idpConfig.BaseDn,
- UserFilter: idpConfig.UserFilter,
- SecurityProtocol: idpConfig.SecurityProtocol,
- FieldMapping: idpConfig.FieldMapping,
- },
- )
- if err != nil {
- return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to create new LDAP identity provider"))
- }
-
- userInfo, err = ldapIDP.Authenticate(request.Email, request.Password)
- if err != nil {
- return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to get user info"))
- }
- default:
- return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("identity provider type %s not supported", idp.Type.String()))
- }
- if userInfo == nil {
- return nil, connect.NewError(connect.CodeNotFound, errors.Errorf("failed to get user info from identity provider %q", idp.Title))
- }
- if userInfo.Identifier == "" {
- return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("missing identifier in user info from identity provider %q", idp.Title))
- }
- // The userinfo's email comes from identity provider, it has to be converted to lower-case.
- email := strings.ToLower(userInfo.Identifier)
- if err := common.ValidateEmail(email); err != nil {
- // If the email is invalid, we will try to use the domain and identifier to construct the email.
- domain := extractDomain(idp.Domain)
- if domain != "" {
- email = strings.ToLower(fmt.Sprintf("%s@%s", email, domain))
- } else {
- return nil, connect.NewError(connect.CodeInvalidArgument, errors.Wrapf(err, "invalid email %q", userInfo.Identifier))
- }
- }
-
- user, err := s.store.GetUserByEmail(ctx, email)
- if err != nil {
- return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to list users by email %s", email))
- }
- // User login through global SSO, then we should auth-resolve the workspace id.
- if user != nil && workspaceID == "" {
- wsID, err := s.resolveWorkspaceForLogin(ctx, user, "")
- if err != nil {
- slog.Warn("failed to resolve workspace", slog.String("user", user.Email), log.BBError(err))
- }
- workspaceID = wsID
- }
- // First time login through SSO
- if user == nil {
- if workspaceID != "" {
- if err := validateEmailWithDomains(ctx, s.licenseService, s.store, workspaceID, email, false); err != nil {
- return nil, err
- }
-
- // We will only block new create creation and still allow SSO login from existing users.
- featurePlan := v1pb.PlanFeature_FEATURE_ENTERPRISE_SSO
- if idp.Type == storepb.IdentityProviderType_OAUTH2 && googleGitHubDomains[idp.Domain] {
- featurePlan = v1pb.PlanFeature_FEATURE_GOOGLE_AND_GITHUB_SSO
- }
- if err := s.licenseService.IsFeatureEnabled(ctx, workspaceID, featurePlan); err != nil {
- return nil, connect.NewError(connect.CodePermissionDenied, err)
- }
-
- if err := userCountGuard(ctx, s.store, s.licenseService, workspaceID, nil, s.profile.SaaS); err != nil {
- return nil, err
- }
- }
-
- // Create new user from identity provider.
- password, err := common.RandomString(20)
- if err != nil {
- return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to generate random password"))
- }
- passwordHash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
- if err != nil {
- return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to generate password hash"))
- }
-
- newUser, err := s.store.CreateUser(ctx, &store.UserMessage{
- Name: userInfo.DisplayName,
- Email: email,
- Phone: userInfo.Phone,
- Type: storepb.PrincipalType_END_USER,
- PasswordHash: string(passwordHash),
- })
- if err != nil {
- return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to create user"))
- }
-
- user = newUser
- }
-
- if workspaceID == "" {
- // Global IDP: create a new workspace for the user (same as Signup flow).
- wsID, err := common.RandomString(16)
- if err != nil {
- return nil, connect.NewError(connect.CodeInternal, errors.Wrap(err, "failed to generate workspace ID"))
- }
- ws, err := s.store.CreateWorkspace(ctx, &store.WorkspaceMessage{
- ResourceID: wsID,
- Payload: &storepb.WorkspacePayload{Title: "Default Workspace"},
- AdditionalSettings: s.getAdditionalWorkspaceSettings(),
- }, email)
- if err != nil {
- return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to create workspace"))
- }
- workspaceID = ws.ResourceID
- } else {
- // Workspace-scoped IDP: add user as member only if not already in the workspace.
- ws, err := s.store.FindWorkspace(ctx, &store.FindWorkspaceMessage{
- WorkspaceID: &workspaceID,
- Email: email,
- IncludeAllUser: !s.profile.SaaS,
- })
- if err != nil {
- return nil, connect.NewError(connect.CodeInternal, errors.Wrap(err, "failed to check workspace membership"))
- }
- if ws == nil {
- if _, err := s.store.PatchWorkspaceIamPolicy(ctx, &store.PatchIamPolicyMessage{
- Workspace: workspaceID,
- Member: common.FormatUserEmail(email),
- Roles: []string{common.FormatRole(store.WorkspaceMemberRole)},
- }); err != nil {
- return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to add user to workspace"))
- }
- }
- }
-
- if user.MemberDeleted {
- if err := userCountGuard(ctx, s.store, s.licenseService, workspaceID, nil, s.profile.SaaS); err != nil {
- return nil, err
- }
- // Undelete the user when login via SSO.
- user, err = s.store.UpdateUser(ctx, user, &store.UpdateUserMessage{Delete: &undeletePatch})
- if err != nil {
- return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to undelete user"))
- }
- }
-
- if userInfo.HasGroups {
- if err := s.syncUserGroups(ctx, user, workspaceID, userInfo.Groups); err != nil {
- return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to sync user groups"))
- }
- }
- return user, nil
-}
-
-// countRecentLoginFailures counts the number of failed login attempts for a given email
-// within the specified time window, matching any of the provided error messages.
-func (s *AuthService) countRecentLoginFailures(ctx context.Context, email string, window time.Duration, errMessages ...string) (int, error) {
- if len(errMessages) == 0 {
- return 0, errors.New("at least one error message is required")
- }
-
- windowStart := time.Now().Add(-window)
-
- // Build filter query for login failures.
- filterQ := qb.Q().Space("TRUE")
- filterQ.And("payload->>'method' = ?", v1connect.AuthServiceLoginProcedure)
- filterQ.And("payload->>'resource' = ?", email)
- filterQ.And("(payload->'status'->>'code')::int != 0")
-
- // Build OR condition for error messages.
- if len(errMessages) == 1 {
- filterQ.And("payload->'status'->>'message' = ?", errMessages[0])
- } else {
- // For multiple messages, build: (msg = ? OR msg = ? OR ...)
- orConditions := qb.Q()
- for i, msg := range errMessages {
- if i == 0 {
- orConditions.Space("payload->'status'->>'message' = ?", msg)
- } else {
- orConditions.Or("payload->'status'->>'message' = ?", msg)
- }
- }
- filterQ.And("(?)", orConditions)
- }
-
- filterQ.And("created_at >= ?", windowStart)
-
- // Search across all workspaces — lockout is per-email, not per-workspace.
- logs, err := s.store.SearchAuditLogs(ctx, &store.AuditLogFind{
- FilterQ: filterQ,
- })
- if err != nil {
- return 0, errors.Wrapf(err, "failed to search audit logs for login failures")
- }
-
- return len(logs), nil
-}
-
-// checkPasswordLockout checks if the user has exceeded the password failure rate limit.
-// Returns an error if the user is locked out due to too many failed password attempts.
-func (s *AuthService) checkPasswordLockout(ctx context.Context, email string) error {
- count, err := s.countRecentLoginFailures(ctx, email, passwordLockoutWindow, errMsgInvalidCredentials)
- if err != nil {
- return connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to count recent password failures"))
- }
-
- if count >= passwordMaxFailedAttempts {
- return connect.NewError(connect.CodeResourceExhausted, errors.Errorf(errMsgTooManyPassword))
- }
-
- return nil
-}
-
-// checkMFALockout checks if the user has exceeded the MFA failure rate limit.
-// Returns an error if the user is locked out due to too many failed MFA attempts.
-func (s *AuthService) checkMFALockout(ctx context.Context, email string) error {
- count, err := s.countRecentLoginFailures(ctx, email, mfaLockoutWindow, errMsgInvalidMFACode, errMsgInvalidRecoveryCode)
- if err != nil {
- return connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to count recent MFA failures"))
- }
-
- if count >= mfaMaxFailedAttempts {
- return connect.NewError(connect.CodeResourceExhausted, errors.Errorf(errMsgTooManyMFA))
- }
-
- return nil
-}
-
func challengeMFACode(user *store.UserMessage, mfaCode string) error {
- if !validateWithCodeAndSecret(mfaCode, user.MFAConfig.OtpSecret) {
- return connect.NewError(connect.CodeUnauthenticated, errors.Errorf(errMsgInvalidMFACode))
+ if !totp.Validate(mfaCode, user.MFAConfig.OtpSecret) {
+ return connect.NewError(connect.CodeUnauthenticated, errors.New(errMsgInvalidMFACode))
}
return nil
}
@@ -976,65 +615,7 @@ func (s *AuthService) challengeRecoveryCode(ctx context.Context, user *store.Use
return nil
}
}
- return connect.NewError(connect.CodeUnauthenticated, errors.Errorf(errMsgInvalidRecoveryCode))
-}
-
-// validateWithCodeAndSecret validates the given code against the given secret.
-func validateWithCodeAndSecret(code, secret string) bool {
- return totp.Validate(code, secret)
-}
-
-// syncUserGroups syncs the user groups with the given groups.
-// The given groups are the groups that the user belongs to in the identity provider.
-// Supported groups format: ["group1", "group2", ...], ["[email protected]", ...]
-func (s *AuthService) syncUserGroups(ctx context.Context, user *store.UserMessage, workspaceID string, groups []string) error {
- bbGroups, err := s.store.ListGroups(ctx, &store.FindGroupMessage{Workspace: workspaceID})
- if err != nil {
- return connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to list groups"))
- }
-
- groupChanged := false
- for _, bbGroup := range bbGroups {
- var isMember bool
- for _, group := range groups {
- if bbGroup.Email == group || bbGroup.Title == group {
- isMember = true
- break
- }
- }
- isBBGroupMember := getMemberInGroup(user, bbGroup) != nil
- if isMember != isBBGroupMember {
- if isMember {
- // Add the user to the group.
- bbGroup.Payload.Members = append(bbGroup.Payload.Members, &storepb.GroupMember{
- Role: storepb.GroupMember_MEMBER,
- Member: common.FormatUserEmail(user.Email),
- })
- } else {
- // Remove the user from the group.
- bbGroup.Payload.Members = slices.DeleteFunc(bbGroup.Payload.Members, func(member *storepb.GroupMember) bool {
- return member.Member == common.FormatUserEmail(user.Email)
- })
- }
- if _, err := s.store.UpdateGroup(ctx, &store.UpdateGroupMessage{
- ID: bbGroup.ID,
- Workspace: bbGroup.Workspace,
- Payload: bbGroup.Payload,
- }); err != nil {
- return connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to update group %q", bbGroup.Email))
- }
- groupChanged = true
- }
- }
-
- // Reload IAM cache if group membership changed.
- if groupChanged {
- if err := s.iamManager.ReloadCache(ctx); err != nil {
- return connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to reload IAM cache"))
- }
- }
-
- return nil
+ return connect.NewError(connect.CodeUnauthenticated, errors.New(errMsgInvalidRecoveryCode))
}
// authenticateLogin handles all authentication paths: password, IDP, or MFA completion.
@@ -1066,6 +647,16 @@ func (s *AuthService) completeMFALogin(ctx context.Context, request *v1pb.LoginR
if err != nil {
return nil, loginAuthMethodPassword, err
}
+ // A request carrying no code at all is not a guess: nothing is compared,
+ // so nothing may consume an attempt slot.
+ if request.OtpCode == nil && request.RecoveryCode == nil {
+ return nil, loginAuthMethodPassword, connect.NewError(connect.CodeUnauthenticated, errors.Errorf("OTP or recovery code is required for MFA"))
+ }
+ // Claim an MFA slot for the email inside the signed temp token: slots are
+ // per identity, so a fresh temp token does not buy fresh guesses.
+ if err := s.claimLoginAttempt(ctx, userEmail, storepb.LoginAttemptKind_MFA); err != nil {
+ return nil, loginAuthMethodPassword, err
+ }
user, err := s.store.GetUserByEmail(ctx, userEmail)
if err != nil {
return nil, loginAuthMethodPassword, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to find user"))
@@ -1073,39 +664,29 @@ func (s *AuthService) completeMFALogin(ctx context.Context, request *v1pb.LoginR
if user == nil {
return nil, loginAuthMethodPassword, invalidCredentialsError
}
- if err := s.checkMFALockout(ctx, user.Email); err != nil {
- return nil, loginAuthMethodPassword, err
- }
- if request.OtpCode != nil {
- if err := challengeMFACode(user, *request.OtpCode); err != nil {
- return nil, loginAuthMethodPassword, err
- }
- } else if request.RecoveryCode != nil {
- if err := s.challengeRecoveryCode(ctx, user, *request.RecoveryCode); err != nil {
- return nil, loginAuthMethodPassword, err
- }
- } else {
- return nil, loginAuthMethodPassword, connect.NewError(connect.CodeUnauthenticated, errors.Errorf("OTP or recovery code is required for MFA"))
+ if err := s.challengeMFAAndClear(ctx, user, userEmail, request.OtpCode, request.RecoveryCode); err != nil {
+ return nil, loginAuthMethodPassword, err
}
return user, loginMethod, nil
}
-// validateLoginPermissions checks if the user is allowed to login.
-func (s *AuthService) validateLoginPermissions(ctx context.Context, user *store.UserMessage, workspaceID string, request *v1pb.LoginRequest) error {
+// validateLoginPermissions checks if the user is allowed to login. It returns
+// the account restriction it fetched (nil when the checks were skipped) so the
+// caller can reuse it.
+func (s *AuthService) validateLoginPermissions(ctx context.Context, user *store.UserMessage, workspaceID string, request *v1pb.LoginRequest) (*v1pb.Restriction, error) {
if user.MemberDeleted {
- return connect.NewError(connect.CodeUnauthenticated, errors.Errorf("user has been deactivated by administrators"))
+ return nil, connect.NewError(connect.CodeUnauthenticated, errors.Errorf("user has been deactivated by administrators"))
}
// Login restrictions only apply to end users.
if user.Type != storepb.PrincipalType_END_USER {
- return nil
+ return nil, nil
}
// Skip restrictions for MFA second login (already validated in first step)
- mfaSecondLogin := request.GetMfaTempToken() != ""
- if mfaSecondLogin {
- return nil
+ if request.GetMfaTempToken() != "" {
+ return nil, nil
}
restriction, err := getAccountRestriction(
@@ -1116,21 +697,22 @@ func (s *AuthService) validateLoginPermissions(ctx context.Context, user *store.
workspaceID,
)
if err != nil {
- return err
+ return nil, err
}
if request.GetIdpName() == "" {
if request.Password != "" && restriction.DisallowPasswordSignin {
- return connect.NewError(connect.CodePermissionDenied, errors.Errorf("password signin is disallowed"))
+ return nil, connect.NewError(connect.CodePermissionDenied, errors.Errorf("password signin is disallowed"))
}
- if request.EmailCode != nil && *request.EmailCode != "" {
- if !restriction.AllowEmailCodeSignin {
- return connect.NewError(connect.CodeFailedPrecondition, errors.Errorf("email code login is not enabled for this workspace"))
- }
+ if request.EmailCode != nil && *request.EmailCode != "" && !restriction.AllowEmailCodeSignin {
+ return nil, connect.NewError(connect.CodeFailedPrecondition, errors.Errorf("email code login is not enabled for this workspace"))
}
}
// Check domain restriction
- return validateEmailWithDomains(ctx, s.licenseService, s.store, workspaceID, user.Email, false)
+ if err := validateEmailWithDomains(ctx, s.licenseService, s.store, workspaceID, user.Email, false); err != nil {
+ return nil, err
+ }
+ return restriction, nil
}
// checkMFARequired checks if MFA is required and returns a response with temp token if so.
@@ -1297,11 +879,8 @@ func (s *AuthService) SwitchWorkspace(ctx context.Context, req *connect.Request[
// Check MFA requirement for the target workspace.
mfaSecondStep := request.GetMfaTempToken() != ""
if mfaSecondStep {
- // Check MFA lockout before verifying.
- if err := s.checkMFALockout(ctx, user.Email); err != nil {
- return nil, err
- }
- // Verify the MFA temp token and OTP/recovery code.
+ // Verify the MFA temp token, then claim from the same per-identity
+ // bucket the login MFA step draws from.
mfaEmail, err := auth.GetUserEmailFromMFATempToken(*request.MfaTempToken, s.secret)
if err != nil {
return nil, connect.NewError(connect.CodeUnauthenticated, errors.New("invalid MFA temp token"))
@@ -1309,17 +888,16 @@ func (s *AuthService) SwitchWorkspace(ctx context.Context, req *connect.Request[
if mfaEmail != user.Email {
return nil, connect.NewError(connect.CodeUnauthenticated, errors.New("MFA token does not match user"))
}
- if request.OtpCode != nil {
- if err := challengeMFACode(user, *request.OtpCode); err != nil {
- return nil, err
- }
- } else if request.RecoveryCode != nil {
- if err := s.challengeRecoveryCode(ctx, user, *request.RecoveryCode); err != nil {
- return nil, err
- }
- } else {
+ // An argument error is not a guess — refuse it before the claim.
+ if request.OtpCode == nil && request.RecoveryCode == nil {
return nil, connect.NewError(connect.CodeInvalidArgument, errors.New("OTP or recovery code required"))
}
+ if err := s.claimLoginAttempt(ctx, mfaEmail, storepb.LoginAttemptKind_MFA); err != nil {
+ return nil, err
+ }
+ if err := s.challengeMFAAndClear(ctx, user, mfaEmail, request.OtpCode, request.RecoveryCode); err != nil {
+ return nil, err
+ }
} else {
// First step: check if MFA is required for the target workspace.
if resp, err := s.checkMFARequired(ctx, user, workspaceID, false, loginAuthMethodPassword); err != nil {
@@ -1424,23 +1002,9 @@ func (s *AuthService) switchWorkspaceInternal(ctx context.Context, user *store.U
sessionExpiresAt = time.Now().Add(auth.GetRefreshTokenDuration(ctx, s.store, s.licenseService, workspaceID))
}
- origin := reqHeaders.Get("Origin")
- cookie := auth.GetTokenCookie(ctx, s.store, s.licenseService, workspaceID, origin, token)
- resp.Header().Add("Set-Cookie", cookie.String())
-
- newRefreshToken, err := auth.GenerateOpaqueToken()
- if err != nil {
- return nil, connect.NewError(connect.CodeInternal, errors.Wrap(err, "failed to generate refresh token"))
- }
- if err := s.store.CreateWebRefreshToken(ctx, &store.WebRefreshTokenMessage{
- TokenHash: auth.HashToken(newRefreshToken),
- UserEmail: user.Email,
- ExpiresAt: sessionExpiresAt,
- }); err != nil {
- return nil, connect.NewError(connect.CodeInternal, errors.Wrap(err, "failed to create refresh token"))
+ if err := s.issueSessionCookies(ctx, resp.Header(), reqHeaders.Get("Origin"), user.Email, workspaceID, token, sessionExpiresAt); err != nil {
+ return nil, err
}
- refreshCookie := auth.GetRefreshTokenCookie(origin, newRefreshToken, time.Until(sessionExpiresAt))
- resp.Header().Add("Set-Cookie", refreshCookie.String())
} else {
response.Token = token
}
@@ -1455,36 +1019,23 @@ func (s *AuthService) switchWorkspaceInternal(ctx context.Context, user *store.U
return resp, nil
}
-// finalizeLogin builds the response, sets cookies if needed, and updates the user profile.
-func (s *AuthService) finalizeLogin(ctx context.Context, req *connect.Request[v1pb.LoginRequest], user *store.UserMessage, token string, workspaceID string, requireResetPassword bool) (*connect.Response[v1pb.LoginResponse], error) {
+// finalizeLogin builds the response, sets cookies if needed, and updates the
+// user profile. Shared by Login and Signup.
+func (s *AuthService) finalizeLogin(ctx context.Context, header http.Header, web bool, user *store.UserMessage, token string, workspaceID string, requireResetPassword bool) (*connect.Response[v1pb.LoginResponse], error) {
response := &v1pb.LoginResponse{
RequireResetPassword: requireResetPassword,
}
resp := connect.NewResponse(response)
- if req.Msg.Web {
+ if web {
if user.Type != storepb.PrincipalType_END_USER {
return nil, connect.NewError(connect.CodePermissionDenied, errors.Errorf("only users can use web login"))
}
- origin := req.Header().Get("Origin")
- cookie := auth.GetTokenCookie(ctx, s.store, s.licenseService, workspaceID, origin, token)
- resp.Header().Add("Set-Cookie", cookie.String())
-
- // Issue refresh token for web login
- refreshToken, err := auth.GenerateOpaqueToken()
- if err != nil {
- return nil, connect.NewError(connect.CodeInternal, errors.Wrap(err, "failed to generate refresh token"))
- }
- refreshTokenDuration := auth.GetRefreshTokenDuration(ctx, s.store, s.licenseService, workspaceID)
- if err := s.store.CreateWebRefreshToken(ctx, &store.WebRefreshTokenMessage{
- TokenHash: auth.HashToken(refreshToken),
- UserEmail: user.Email,
- ExpiresAt: time.Now().Add(refreshTokenDuration),
- }); err != nil {
- return nil, connect.NewError(connect.CodeInternal, errors.Wrap(err, "failed to create refresh token"))
+ // A fresh session: the refresh token gets the full refresh duration.
+ d := auth.GetRefreshTokenDuration(ctx, s.store, s.licenseService, workspaceID)
+ if err := s.issueSessionCookies(ctx, resp.Header(), header.Get("Origin"), user.Email, workspaceID, token, time.Now().Add(d)); err != nil {
+ return nil, err
}
- refreshCookie := auth.GetRefreshTokenCookie(origin, refreshToken, refreshTokenDuration)
- resp.Header().Add("Set-Cookie", refreshCookie.String())
} else {
// For non-web clients (CLI, API), return the token in the response body.
response.Token = token
@@ -1513,6 +1064,27 @@ func (s *AuthService) finalizeLogin(ctx context.Context, req *connect.Request[v1
return resp, nil
}
+// issueSessionCookies mints one web session: it stores a refresh token
+// expiring at refreshExpiresAt and sets both HTTP-only cookies on respHeader.
+// The refresh cookie lives until that same expiry (its max age truncates to
+// whole seconds).
+func (s *AuthService) issueSessionCookies(ctx context.Context, respHeader http.Header, origin, userEmail, workspaceID, accessToken string, refreshExpiresAt time.Time) error {
+ respHeader.Add(setCookieHeader, auth.GetTokenCookie(ctx, s.store, s.licenseService, workspaceID, origin, accessToken).String())
+ refreshToken, err := auth.GenerateOpaqueToken()
+ if err != nil {
+ return connect.NewError(connect.CodeInternal, errors.Wrap(err, "failed to generate refresh token"))
+ }
+ if err := s.store.CreateWebRefreshToken(ctx, &store.WebRefreshTokenMessage{
+ TokenHash: auth.HashToken(refreshToken),
+ UserEmail: userEmail,
+ ExpiresAt: refreshExpiresAt,
+ }); err != nil {
+ return connect.NewError(connect.CodeInternal, errors.Wrap(err, "failed to create refresh token"))
+ }
+ respHeader.Add(setCookieHeader, auth.GetRefreshTokenCookie(origin, refreshToken, time.Until(refreshExpiresAt)).String())
+ return nil
+}
+
// ExchangeToken exchanges an external OIDC token for a Bytebase access token.
// Used by CI/CD pipelines with Workload Identity Federation.
func (s *AuthService) ExchangeToken(ctx context.Context, req *connect.Request[v1pb.ExchangeTokenRequest]) (*connect.Response[v1pb.ExchangeTokenResponse], error) {
@@ -1637,107 +1209,6 @@ func getAccountRestriction(
return restriction, nil
}
-// 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 := strings.ToLower(strings.TrimSpace(req.Msg.Email))
- if email == "" {
- return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("email is required"))
- }
-
- workspaceID, err := s.parseAndSetAuditWorkspace(ctx, email, req.Msg.Workspace)
- if err != nil {
- return nil, connect.NewError(connect.CodeInvalidArgument, err)
- }
-
- // Send synchronously, but swallow errors to avoid email enumeration — a fast silent
- // "success" for unknown emails must be indistinguishable from an SMTP failure for
- // known ones. Errors are logged server-side for operator visibility.
- if err := s.sendEmailVerificationCode(
- ctx,
- workspaceID,
- email,
- storepb.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",
- ); err != nil {
- slog.Warn("failed to send password reset email", slog.String("to", email), log.BBError(err))
- }
-
- return connect.NewResponse(&emptypb.Empty{}), nil
-}
-
-// ResetPassword verifies the 6-digit code and updates the user's password.
-// Also revokes all refresh tokens to force re-login.
-func (s *AuthService) ResetPassword(ctx context.Context, req *connect.Request[v1pb.ResetPasswordRequest]) (*connect.Response[emptypb.Empty], error) {
- email := strings.ToLower(strings.TrimSpace(req.Msg.Email))
- if email == "" {
- return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("email is required"))
- }
- if req.Msg.Code == "" {
- return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("code is required"))
- }
- if req.Msg.NewPassword == "" {
- return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("new_password is required"))
- }
-
- codeRow, err := s.verifyEmailCode(ctx, email, storepb.EmailVerificationCodePurpose_PASSWORD_RESET, req.Msg.Code)
- if err != nil {
- return nil, err
- }
- if codeRow.Workspace != "" {
- common.SetAuditWorkspaceID(ctx, codeRow.Workspace)
- }
-
- user, err := s.store.GetUserByEmail(ctx, email)
- if err != nil {
- return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to find user"))
- }
- if user == nil {
- return nil, connect.NewError(connect.CodeNotFound, errors.Errorf("user not found"))
- }
-
- // Validate the user is a member of the workspace captured at send time.
- // Reject if forged — prevents bypassing password policy via a weaker workspace.
- if codeRow.Workspace != "" {
- ws, err := s.store.FindWorkspace(ctx, &store.FindWorkspaceMessage{
- WorkspaceID: &codeRow.Workspace,
- Email: email,
- IncludeAllUser: !s.profile.SaaS,
- })
- if err != nil {
- return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to verify workspace membership"))
- }
- if ws == nil {
- return nil, connect.NewError(connect.CodePermissionDenied, errors.Errorf("user is not a member of the workspace"))
- }
- }
- restriction, err := getAccountRestriction(ctx, s.store, s.licenseService, s.profile.SaaS, codeRow.Workspace)
- if err != nil {
- return nil, err
- }
- if err := validatePasswordWithRestriction(req.Msg.NewPassword, convertToStorePasswordRestriction(restriction.PasswordRestriction)); err != nil {
- return nil, err
- }
-
- passwordHash, err := bcrypt.GenerateFromPassword([]byte(req.Msg.NewPassword), bcrypt.DefaultCost)
- if err != nil {
- return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to hash password"))
- }
- passwordHashStr := string(passwordHash)
- if _, err := s.store.UpdateUser(ctx, user, &store.UpdateUserMessage{
- Email: &user.Email,
- PasswordHash: &passwordHashStr,
- }); err != nil {
- return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to update password"))
- }
-
- if err := s.store.DeleteWebRefreshTokensByUser(ctx, user.Email); err != nil {
- slog.Warn("failed to revoke refresh tokens after password reset", log.BBError(err))
- }
-
- return connect.NewResponse(&emptypb.Empty{}), nil
-}
-
// parseOptionalWorkspace extracts the workspace ID from an optional "workspaces/{id}"
// resource name. Returns empty when the caller has no workspace context yet
// (SaaS brand-new signup flow).
@@ -1748,333 +1219,6 @@ func parseOptionalWorkspace(name *string) (string, error) {
return common.GetWorkspaceID(*name)
}
-// generateEmailCode returns a cryptographically-random 6-digit numeric code.
-func generateEmailCode() (string, error) {
- const digits = "0123456789"
- b := make([]byte, emailCodeLength)
- if _, err := rand.Read(b); err != nil {
- return "", err
- }
- for i := range b {
- b[i] = digits[int(b[i])%len(digits)]
- }
- return string(b), nil
-}
-
-// hashEmailCode returns HMAC-SHA256(code) hex-encoded, keyed with the server's auth secret.
-// HMAC with a server-side secret (vs. bare SHA-256) prevents offline brute force of the
-// 10^6-size code space if the DB is ever compromised — the attacker would also need the
-// auth secret to verify candidate codes.
-func (s *AuthService) hashEmailCode(code string) string {
- mac := hmac.New(sha256.New, []byte(s.secret))
- mac.Write([]byte(code))
- return hex.EncodeToString(mac.Sum(nil))
-}
-
-// SendEmailLoginCode sends a 6-digit verification code. Always returns success
-// (no email enumeration). Rate limit: 60-sec resend cooldown enforced atomically
-// via the store — effective cap ≈ 60 sends/hour/email.
-func (s *AuthService) SendEmailLoginCode(ctx context.Context, req *connect.Request[v1pb.SendEmailLoginCodeRequest]) (*connect.Response[emptypb.Empty], error) {
- email := strings.ToLower(strings.TrimSpace(req.Msg.Email))
- if email == "" {
- return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("email is required"))
- }
- workspaceID, err := s.parseAndSetAuditWorkspace(ctx, email, req.Msg.Workspace)
- if err != nil {
- return nil, connect.NewError(connect.CodeInvalidArgument, err)
- }
- if workspaceID != "" {
- if err := validateEmailWithDomains(ctx, s.licenseService, s.store, workspaceID, email, false); err != nil {
- return nil, err
- }
- } else if err := validateEndUserEmail(email); err != nil {
- return nil, err
- }
-
- // Gate on AllowEmailCodeSignin — no point emailing a code the workspace won't accept.
- // getAccountRestriction handles all cases (including empty workspace for brand-new SaaS
- // signup, where it resolves via EMAIL_CONFIG + SaaS override).
- restriction, err := getAccountRestriction(ctx, s.store, s.licenseService, s.profile.SaaS, workspaceID)
- if err != nil {
- return nil, err
- }
- if !restriction.AllowEmailCodeSignin {
- return nil, connect.NewError(connect.CodeFailedPrecondition, errors.Errorf("email code login is not enabled for this workspace"))
- }
-
- // 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).
- if err := s.sendEmailVerificationCode(
- ctx,
- workspaceID,
- email,
- storepb.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",
- ); err != nil {
- return nil, connect.NewError(connect.CodeInternal, err)
- }
-
- return connect.NewResponse(&emptypb.Empty{}), nil
-}
-
-// parseAndSetAuditWorkspace parses the requested workspace and attributes the
-// audit event only when the email belongs to an active user in that workspace.
-// Membership affects audit attribution only; the parsed workspace ID is still
-// returned for email-setting resolution and verification-code storage.
-func (s *AuthService) parseAndSetAuditWorkspace(ctx context.Context, email string, workspaceName *string) (string, error) {
- workspaceID, err := parseOptionalWorkspace(workspaceName)
- if err != nil {
- return "", 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)
- }
- }
- }
- return workspaceID, nil
-}
-
-// resolvePreLoginEmailSetting returns the EMAIL setting to use for unauthenticated flows
-// (email-code sign-in, password reset). Resolution order:
-// 1. If `workspaceID` is provided, use that workspace's EMAIL setting. The frontend
-// resolves the workspace (from the route query or actuator context) and always passes
-// it when one exists — self-host, multi-workspace SaaS, and pre-invited emails all
-// flow through this path.
-// 2. EMAIL_CONFIG env var — deployment-wide fallback for SaaS brand-new signup, where
-// the caller has no workspace context yet (no pre-invite, no workspace in the URL).
-func resolvePreLoginEmailSetting(
- ctx context.Context,
- stores *store.Store,
- workspaceID string,
-) (*storepb.EmailSetting, error) {
- if workspaceID != "" {
- emailSettingMsg, err := stores.GetSetting(ctx, workspaceID, storepb.SettingName_EMAIL)
- if err != nil {
- return nil, errors.Wrap(err, "failed to load email setting")
- }
- if emailSettingMsg == nil {
- return nil, nil
- }
- es, ok := emailSettingMsg.Value.(*storepb.EmailSetting)
- if !ok {
- return nil, nil
- }
- return es, nil
- }
-
- if raw := os.Getenv("EMAIL_CONFIG"); raw != "" {
- emailSetting := &storepb.EmailSetting{}
- if err := common.ProtojsonUnmarshaler.Unmarshal([]byte(raw), emailSetting); err != nil {
- return nil, errors.Wrap(err, "failed to parse EMAIL_CONFIG")
- }
- return emailSetting, nil
- }
-
- return nil, nil
-}
-
-// sendEmailVerificationCode generates a code, atomically stores its hash (subject to cooldown),
-// 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).
-// 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. `bodyFmt` must contain one %s for the 6-digit code.
-func (s *AuthService) sendEmailVerificationCode(ctx context.Context, workspaceID, email string, purpose storepb.EmailVerificationCodePurpose, subject, bodyFmt string) 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 {
- account, err := s.store.GetAccountByEmail(ctx, email)
- if err != nil {
- return errors.Wrap(err, "failed to look up account for password reset")
- }
- if account == nil || account.Type != storepb.PrincipalType_END_USER || account.MemberDeleted {
- return nil // silent: account doesn't exist
- }
- }
-
- // Resolve the EMAIL setting FIRST — fail fast if misconfigured so we don't write a
- // verification row we can't actually deliver.
- emailSetting, err := resolvePreLoginEmailSetting(ctx, s.store, workspaceID)
- if err != nil {
- return err
- }
- if emailSetting == nil {
- return errors.Errorf("cannot found email config for workspace %v", workspaceID)
- }
-
- code, err := generateEmailCode()
- if err != nil {
- return errors.Wrap(err, "failed to generate code")
- }
-
- now := time.Now()
- sent, err := s.store.UpsertEmailVerificationCodeIfCooldownExpired(ctx, &store.EmailVerificationCodeMessage{
- Email: email,
- Purpose: purpose,
- CodeHash: s.hashEmailCode(code),
- ExpiresAt: now.Add(emailCodeExpiry),
- LastSentAt: now,
- Workspace: workspaceID,
- }, emailCodeResendCooldown)
- if err != nil {
- return errors.Wrap(err, "failed to upsert verification code")
- }
- if !sent {
- return nil // cooldown active — silent skip
- }
-
- sender, err := mailer.NewSender(emailSetting)
- if err != nil {
- return errors.Wrap(err, "failed to create mail sender")
- }
-
- body := fmt.Sprintf(bodyFmt, code, int(emailCodeExpiry.Minutes()))
- if err := sender.Send(ctx, &mailer.SendRequest{
- To: []string{email},
- Subject: subject,
- TextBody: body,
- }); err != nil {
- // Delete the row so the cooldown doesn't block an immediate retry.
- // Match on code_hash to avoid wiping a newer code from a concurrent request.
- _ = s.store.DeleteEmailVerificationCodeIfMatch(ctx, email, purpose, s.hashEmailCode(code))
- return errors.Wrap(err, "failed to send email")
- }
- return nil
-}
-
-// verifyEmailCode checks a submitted code against the stored row.
-// Enforces expiry, attempt limit (5), and constant-time hash compare.
-// On successful match, deletes the row (one-time use) and returns it so the
-// caller can use its captured workspace context (e.g. for gate checks and
-// workspace assignment on the email-code signup path).
-func (s *AuthService) verifyEmailCode(ctx context.Context, email string, purpose storepb.EmailVerificationCodePurpose, submittedCode string) (*store.EmailVerificationCodeMessage, error) {
- row, err := s.store.GetEmailVerificationCode(ctx, email, purpose)
- if err != nil {
- return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to get email verification code"))
- }
- if row == nil {
- return nil, connect.NewError(connect.CodeUnauthenticated, errors.Errorf("invalid or expired code"))
- }
- if time.Now().After(row.ExpiresAt) {
- _ = s.store.DeleteEmailVerificationCodeIfMatch(ctx, email, purpose, row.CodeHash)
- return nil, connect.NewError(connect.CodeUnauthenticated, errors.Errorf("invalid or expired code"))
- }
- if row.Attempts >= emailCodeMaxAttempts {
- _ = s.store.DeleteEmailVerificationCodeIfMatch(ctx, email, purpose, row.CodeHash)
- return nil, connect.NewError(connect.CodeUnauthenticated, errors.Errorf("too many attempts"))
- }
- if subtle.ConstantTimeCompare([]byte(s.hashEmailCode(submittedCode)), []byte(row.CodeHash)) != 1 {
- _ = s.store.IncrementEmailVerificationCodeAttempts(ctx, email, purpose)
- return nil, connect.NewError(connect.CodeUnauthenticated, errors.Errorf("invalid or expired code"))
- }
- _ = s.store.DeleteEmailVerificationCodeIfMatch(ctx, email, purpose, row.CodeHash)
- return row, nil
-}
-
-// authenticateEmailCodeLogin handles the email + 6-digit code flow.
-// Existing users: verify code → return user (downstream pipeline handles workspace-level gates).
-// Unknown emails: verify code → gate checks on pre-invited workspace → create user + provision workspace.
-func (s *AuthService) authenticateEmailCodeLogin(ctx context.Context, request *v1pb.LoginRequest) (*store.UserMessage, error) {
- if request.Password != "" || request.GetIdpName() != "" {
- return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("email_code is mutually exclusive with password and idp_name"))
- }
- email := strings.ToLower(strings.TrimSpace(request.Email))
- if email == "" {
- return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("email is required"))
- }
-
- codeRow, err := s.verifyEmailCode(ctx, email, storepb.EmailVerificationCodePurpose_LOGIN, *request.EmailCode)
- if err != nil {
- return nil, err
- }
- if codeRow.Workspace != "" {
- if err := validateEmailWithDomains(ctx, s.licenseService, s.store, codeRow.Workspace, email, false); err != nil {
- return nil, err
- }
- } else if err := validateEndUserEmail(email); err != nil {
- return nil, err
- }
-
- // Existing user → return. allow_email_code_signin is checked later in validateLoginPermissions
- // against the actually-resolved login workspace (which may not match the send-time workspace
- // for multi-workspace users — resolveWorkspaceForLogin prefers LastLoginWorkspace).
- user, err := s.store.GetUserByEmail(ctx, email)
- if err != nil {
- return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to find user"))
- }
- if user != nil {
- return user, nil
- }
-
- // Gate checks run BEFORE user creation to prevent orphan accounts.
- // We only consult AllowEmailCodeSignin here: DisallowSignup governs password self-service
- // signup (the Signup RPC), not email-code onboarding — the two paths are independent.
- // Admins who want to block new users via email-code set AllowEmailCodeSignin=false.
- restriction, err := getAccountRestriction(ctx, s.store, s.licenseService, s.profile.SaaS, codeRow.Workspace)
- if err != nil {
- return nil, err
- }
- if !restriction.AllowEmailCodeSignin {
- return nil, connect.NewError(connect.CodeFailedPrecondition, errors.Errorf("email code login is not enabled for this workspace"))
- }
- // Signup is always allowed for SaaS
- if !s.profile.SaaS {
- if restriction.DisallowSignup {
- return nil, connect.NewError(connect.CodePermissionDenied, errors.Errorf("sign up is disallowed for this workspace"))
- }
- }
-
- // Provision workspace BEFORE creating the user so retries are self-healing: if user
- // creation fails, the next attempt's FindWorkspace(email) finds the already-provisioned
- // workspace via its IAM binding and returns it. The reverse order would leave a user
- // without a workspace, and subsequent retries would early-return via GetUserByEmail and
- // never re-run provisioning — permanently stuck. Matches the Signup RPC's ordering.
- if _, err := s.provisionWorkspaceForNewUser(ctx, email); err != nil {
- return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to provision workspace"))
- }
-
- // Create principal with random bcrypt password.
- randomBytes := make([]byte, 32)
- if _, err := rand.Read(randomBytes); err != nil {
- return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to generate random password"))
- }
- passwordHash, err := bcrypt.GenerateFromPassword(randomBytes, bcrypt.DefaultCost)
- if err != nil {
- return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to hash password"))
- }
-
- // Derive display name from email local-part.
- name := email
- if i := strings.Index(email, "@"); i > 0 {
- name = email[:i]
- }
-
- newUser, err := s.store.CreateUser(ctx, &store.UserMessage{
- Email: email,
- Name: name,
- Type: storepb.PrincipalType_END_USER,
- PasswordHash: string(passwordHash),
- Profile: &storepb.UserProfile{},
- })
- if err != nil {
- return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to create user"))
- }
-
- return newUser, nil
-}
-
// getAdditionalWorkspaceSettings returns extra settings to inject during workspace creation.
// In SaaS mode with Gemini API key configured, injects AI settings.
func (*AuthService) getAdditionalWorkspaceSettings() []store.AdditionalSetting {
diff --git a/backend/api/v1/auth_service_email_code.go b/backend/api/v1/auth_service_email_code.go
new file mode 100644
index 0000000000..2cec737244
--- /dev/null
+++ b/backend/api/v1/auth_service_email_code.go
@@ -0,0 +1,469 @@
+package v1
+
+import (
+ "context"
+ "crypto/hmac"
+ "crypto/rand"
+ "crypto/sha256"
+ "crypto/subtle"
+ "encoding/hex"
+ "fmt"
+ "log/slog"
+ "os"
+ "strings"
+ "time"
+
+ "connectrpc.com/connect"
+ "github.com/pkg/errors"
+ "golang.org/x/crypto/bcrypt"
+ "google.golang.org/protobuf/types/known/emptypb"
+
+ "github.com/bytebase/bytebase/backend/common"
+ "github.com/bytebase/bytebase/backend/common/log"
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+ v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"
+ "github.com/bytebase/bytebase/backend/plugin/mailer"
+ "github.com/bytebase/bytebase/backend/store"
+)
+
+// Emailed verification codes: sending 6-digit codes for sign-in and password
+// reset, and verifying them under the EMAIL_CODE lockout.
+
+const (
+ emailCodeLength = 6
+ emailCodeExpiry = 10 * time.Minute
+ emailCodeResendCooldown = 60 * time.Second
+
+ errMsgInvalidEmailCode = "invalid or expired code"
+)
+
+// 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)
+ if email == "" {
+ return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("email is required"))
+ }
+
+ workspaceID, err := s.parseAndSetAuditWorkspace(ctx, email, req.Msg.Workspace)
+ if err != nil {
+ return nil, connect.NewError(connect.CodeInvalidArgument, err)
+ }
+
+ // Send synchronously, but swallow errors to avoid email enumeration — a fast silent
+ // "success" for unknown emails must be indistinguishable from an SMTP failure for
+ // known ones. Errors are logged server-side for operator visibility.
+ if err := s.sendEmailVerificationCode(
+ ctx,
+ workspaceID,
+ email,
+ storepb.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",
+ ); err != nil {
+ slog.Warn("failed to send password reset email", slog.String("to", email), log.BBError(err))
+ }
+
+ return connect.NewResponse(&emptypb.Empty{}), nil
+}
+
+// ResetPassword verifies the 6-digit code and updates the user's password.
+// Also revokes all refresh tokens to force re-login.
+func (s *AuthService) ResetPassword(ctx context.Context, req *connect.Request[v1pb.ResetPasswordRequest]) (*connect.Response[emptypb.Empty], error) {
+ email := normalizeEmail(req.Msg.Email)
+ if email == "" {
+ return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("email is required"))
+ }
+ if req.Msg.Code == "" {
+ return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("code is required"))
+ }
+ if req.Msg.NewPassword == "" {
+ return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("new_password is required"))
+ }
+
+ if err := s.verifyEmailCode(ctx, email, storepb.EmailVerificationCodePurpose_PASSWORD_RESET, req.Msg.Code); err != nil {
+ return nil, err
+ }
+
+ user, err := s.store.GetUserByEmail(ctx, email)
+ if err != nil {
+ return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to find user"))
+ }
+ if user == nil {
+ return nil, connect.NewError(connect.CodeNotFound, errors.Errorf("user not found"))
+ }
+
+ // The code proved control of the email, so the user is known: the password
+ // policy and the audit workspace come from the user's own memberships — the
+ // singleton on self-hosted — never from anything the caller sent.
+ workspaceID, err := s.resolveWorkspaceForLogin(ctx, user, "")
+ if err != nil {
+ return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to resolve workspace"))
+ }
+ common.SetAuditWorkspaceID(ctx, workspaceID)
+ restriction, err := getAccountRestriction(ctx, s.store, s.licenseService, s.profile.SaaS, workspaceID)
+ if err != nil {
+ return nil, err
+ }
+ if err := validatePasswordWithRestriction(req.Msg.NewPassword, convertToStorePasswordRestriction(restriction.PasswordRestriction)); err != nil {
+ return nil, err
+ }
+
+ passwordHash, err := bcrypt.GenerateFromPassword([]byte(req.Msg.NewPassword), bcrypt.DefaultCost)
+ if err != nil {
+ return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to hash password"))
+ }
+ passwordHashStr := string(passwordHash)
+ if _, err := s.store.UpdateUser(ctx, user, &store.UpdateUserMessage{
+ Email: &user.Email,
+ PasswordHash: &passwordHashStr,
+ }); err != nil {
+ return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to update password"))
+ }
+
+ if err := s.store.DeleteWebRefreshTokensByUser(ctx, user.Email); err != nil {
+ slog.Warn("failed to revoke refresh tokens after password reset", log.BBError(err))
+ }
+
+ // The user proved control of the email and holds a fresh password: a lock
+ // they guessed themselves into must not outlive the reset.
+ s.clearLoginAttempt(ctx, email, storepb.LoginAttemptKind_PASSWORD)
+
+ return connect.NewResponse(&emptypb.Empty{}), nil
+}
+
+// SendEmailLoginCode sends a 6-digit verification code. Always returns success
+// (no email enumeration). Rate limit: 60-sec resend cooldown enforced atomically
+// via the store — effective cap ≈ 60 sends/hour/email.
+func (s *AuthService) SendEmailLoginCode(ctx context.Context, req *connect.Request[v1pb.SendEmailLoginCodeRequest]) (*connect.Response[emptypb.Empty], error) {
+ email := normalizeEmail(req.Msg.Email)
+ if email == "" {
+ return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("email is required"))
+ }
+ workspaceID, err := s.parseAndSetAuditWorkspace(ctx, email, req.Msg.Workspace)
+ if err != nil {
+ return nil, connect.NewError(connect.CodeInvalidArgument, err)
+ }
+ if workspaceID != "" {
+ if err := validateEmailWithDomains(ctx, s.licenseService, s.store, workspaceID, email, false); err != nil {
+ return nil, err
+ }
+ } else if err := validateEndUserEmail(email); err != nil {
+ return nil, err
+ }
+
+ // Gate on AllowEmailCodeSignin — no point emailing a code the workspace won't accept.
+ // getAccountRestriction handles all cases (including empty workspace for brand-new SaaS
+ // signup, where it resolves via EMAIL_CONFIG + SaaS override).
+ restriction, err := getAccountRestriction(ctx, s.store, s.licenseService, s.profile.SaaS, workspaceID)
+ if err != nil {
+ return nil, err
+ }
+ if !restriction.AllowEmailCodeSignin {
+ return nil, connect.NewError(connect.CodeFailedPrecondition, errors.Errorf("email code login is not enabled for this workspace"))
+ }
+
+ // 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).
+ if err := s.sendEmailVerificationCode(
+ ctx,
+ workspaceID,
+ email,
+ storepb.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",
+ ); err != nil {
+ return nil, connect.NewError(connect.CodeInternal, err)
+ }
+
+ return connect.NewResponse(&emptypb.Empty{}), nil
+}
+
+// authenticateEmailCodeLogin handles the email + 6-digit code flow.
+// Existing users: verify code → return user (downstream pipeline handles workspace-level gates).
+// Unknown emails: verify code → gate checks on pre-invited workspace → create user + provision workspace.
+func (s *AuthService) authenticateEmailCodeLogin(ctx context.Context, request *v1pb.LoginRequest) (*store.UserMessage, error) {
+ if request.Password != "" || request.GetIdpName() != "" {
+ return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("email_code is mutually exclusive with password and idp_name"))
+ }
+ email := normalizeEmail(request.Email)
+ if email == "" {
+ return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("email is required"))
+ }
+
+ if err := s.verifyEmailCode(ctx, email, storepb.EmailVerificationCodePurpose_LOGIN, *request.EmailCode); err != nil {
+ return nil, err
+ }
+
+ // Existing user → return. Domain and allow_email_code_signin are checked later
+ // in validateLoginPermissions against the actually-resolved login workspace
+ // (which may not match the send-time workspace for multi-workspace users —
+ // resolveWorkspaceForLogin prefers LastLoginWorkspace).
+ user, err := s.store.GetUserByEmail(ctx, email)
+ if err != nil {
+ return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to find user"))
+ }
+ if user != nil {
+ return user, nil
+ }
+
+ // Gate checks run BEFORE user creation to prevent orphan accounts, against
+ // the workspace the email would land in — the workspace whose invitation the
+ // email holds, or the self-hosted singleton; provisioning below reuses this
+ // resolution. A brand-new SaaS signup has neither and gets the SaaS defaults.
+ preferredWS, _ := parseOptionalWorkspace(request.Workspace)
+ targetWorkspaceID, targetIsMember, err := s.resolveWorkspaceIDByEmail(ctx, email, preferredWS)
+ if err != nil {
+ return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to resolve target workspace"))
+ }
+ if targetWorkspaceID != "" {
+ if err := validateEmailWithDomains(ctx, s.licenseService, s.store, targetWorkspaceID, email, false); err != nil {
+ return nil, err
+ }
+ } else if err := validateEndUserEmail(email); err != nil {
+ return nil, err
+ }
+
+ // We only consult AllowEmailCodeSignin here: DisallowSignup governs password self-service
+ // signup (the Signup RPC), not email-code onboarding — the two paths are independent.
+ // Admins who want to block new users via email-code set AllowEmailCodeSignin=false.
+ restriction, err := getAccountRestriction(ctx, s.store, s.licenseService, s.profile.SaaS, targetWorkspaceID)
+ if err != nil {
+ return nil, err
+ }
+ if !restriction.AllowEmailCodeSignin {
+ return nil, connect.NewError(connect.CodeFailedPrecondition, errors.Errorf("email code login is not enabled for this workspace"))
+ }
+ // Signup is always allowed for SaaS.
+ if !s.profile.SaaS && restriction.DisallowSignup {
+ return nil, connect.NewError(connect.CodePermissionDenied, errors.Errorf("sign up is disallowed for this workspace"))
+ }
+
+ // Provision workspace BEFORE creating the user so retries are self-healing: if user
+ // creation fails, the next attempt's FindWorkspace(email) finds the already-provisioned
+ // workspace via its IAM binding and returns it. The reverse order would leave a user
+ // without a workspace, and subsequent retries would early-return via GetUserByEmail and
+ // never re-run provisioning — permanently stuck. Matches the Signup RPC's ordering.
+ if _, err := s.provisionResolvedWorkspace(ctx, email, targetWorkspaceID, targetIsMember); err != nil {
+ return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to provision workspace"))
+ }
+
+ // Create principal with random bcrypt password.
+ randomBytes := make([]byte, 32)
+ if _, err := rand.Read(randomBytes); err != nil {
+ return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to generate random password"))
+ }
+ passwordHash, err := bcrypt.GenerateFromPassword(randomBytes, bcrypt.DefaultCost)
+ if err != nil {
+ return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to hash password"))
+ }
+
+ // Derive display name from email local-part.
+ name := email
+ if i := strings.Index(email, "@"); i > 0 {
+ name = email[:i]
+ }
+
+ newUser, err := s.store.CreateUser(ctx, &store.UserMessage{
+ Email: email,
+ Name: name,
+ Type: storepb.PrincipalType_END_USER,
+ PasswordHash: string(passwordHash),
+ Profile: &storepb.UserProfile{},
+ })
+ if err != nil {
+ return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to create user"))
+ }
+
+ return newUser, nil
+}
+
+// parseAndSetAuditWorkspace parses the requested workspace and attributes the
+// audit event only when the email belongs to an active user in that workspace.
+// Membership affects audit attribution only; the parsed workspace ID is still
+// returned for email-setting resolution and verification-code storage.
+func (s *AuthService) parseAndSetAuditWorkspace(ctx context.Context, email string, workspaceName *string) (string, error) {
+ workspaceID, err := parseOptionalWorkspace(workspaceName)
+ if err != nil {
+ return "", 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)
+ }
+ }
+ }
+ return workspaceID, nil
+}
+
+// resolvePreLoginEmailSetting returns the EMAIL setting to use for unauthenticated flows
+// (email-code sign-in, password reset). Resolution order:
+// 1. If `workspaceID` is provided, use that workspace's EMAIL setting. The frontend
+// resolves the workspace (from the route query or actuator context) and always passes
+// it when one exists — self-host, multi-workspace SaaS, and pre-invited emails all
+// flow through this path.
+// 2. EMAIL_CONFIG env var — deployment-wide fallback for SaaS brand-new signup, where
+// the caller has no workspace context yet (no pre-invite, no workspace in the URL).
+func resolvePreLoginEmailSetting(
+ ctx context.Context,
+ stores *store.Store,
+ workspaceID string,
+) (*storepb.EmailSetting, error) {
+ if workspaceID != "" {
+ emailSettingMsg, err := stores.GetSetting(ctx, workspaceID, storepb.SettingName_EMAIL)
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to load email setting")
+ }
+ if emailSettingMsg == nil {
+ return nil, nil
+ }
+ es, ok := emailSettingMsg.Value.(*storepb.EmailSetting)
+ if !ok {
+ return nil, nil
+ }
+ return es, nil
+ }
+
+ if raw := os.Getenv("EMAIL_CONFIG"); raw != "" {
+ emailSetting := &storepb.EmailSetting{}
+ if err := common.ProtojsonUnmarshaler.Unmarshal([]byte(raw), emailSetting); err != nil {
+ return nil, errors.Wrap(err, "failed to parse EMAIL_CONFIG")
+ }
+ return emailSetting, nil
+ }
+
+ return nil, nil
+}
+
+// sendEmailVerificationCode generates a code, atomically stores its hash (subject to cooldown),
+// 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).
+// 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. `bodyFmt` must contain one %s for the 6-digit code.
+func (s *AuthService) sendEmailVerificationCode(ctx context.Context, workspaceID, email string, purpose storepb.EmailVerificationCodePurpose, subject, bodyFmt string) 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 {
+ account, err := s.store.GetAccountByEmail(ctx, email)
+ if err != nil {
+ return errors.Wrap(err, "failed to look up account for password reset")
+ }
+ if account == nil || account.Type != storepb.PrincipalType_END_USER || account.MemberDeleted {
+ return nil // silent: account doesn't exist
+ }
+ }
+
+ // Resolve the EMAIL setting FIRST — fail fast if misconfigured so we don't write a
+ // verification row we can't actually deliver.
+ emailSetting, err := resolvePreLoginEmailSetting(ctx, s.store, workspaceID)
+ if err != nil {
+ return err
+ }
+ if emailSetting == nil {
+ return errors.Errorf("cannot found email config for workspace %v", workspaceID)
+ }
+
+ code, err := generateEmailCode()
+ if err != nil {
+ return errors.Wrap(err, "failed to generate code")
+ }
+
+ now := time.Now()
+ sent, err := s.store.UpsertEmailVerificationCodeIfCooldownExpired(ctx, &store.EmailVerificationCodeMessage{
+ Email: email,
+ Purpose: purpose,
+ CodeHash: s.hashEmailCode(code),
+ ExpiresAt: now.Add(emailCodeExpiry),
+ LastSentAt: now,
+ }, emailCodeResendCooldown)
+ if err != nil {
+ return errors.Wrap(err, "failed to upsert verification code")
+ }
+ if !sent {
+ return nil // cooldown active — silent skip
+ }
+
+ sender, err := mailer.NewSender(emailSetting)
+ if err != nil {
+ return errors.Wrap(err, "failed to create mail sender")
+ }
+
+ body := fmt.Sprintf(bodyFmt, code, int(emailCodeExpiry.Minutes()))
+ if err := sender.Send(ctx, &mailer.SendRequest{
+ To: []string{email},
+ Subject: subject,
+ TextBody: body,
+ }); err != nil {
+ // Delete the row so the cooldown doesn't block an immediate retry.
+ // Match on code_hash to avoid wiping a newer code from a concurrent request.
+ _ = s.store.DeleteEmailVerificationCodeIfMatch(ctx, email, purpose, s.hashEmailCode(code))
+ return errors.Wrap(err, "failed to send email")
+ }
+ return nil
+}
+
+// verifyEmailCode checks a submitted code against the stored row for the email.
+// An EMAIL_CODE slot is claimed before the row is even loaded, so guessing is
+// bounded per identity across codes and purposes, and a lock is not an oracle
+// for whether a code is pending. Wrong guesses leave the row in place — the
+// resend cooldown always has a row to evaluate.
+func (s *AuthService) verifyEmailCode(ctx context.Context, email string, purpose storepb.EmailVerificationCodePurpose, submittedCode string) error {
+ // An invalid-syntax email can hold neither an account nor a code; reject it
+ // before the claim so garbage never writes a row.
+ if !common.IsValidEmail(email) {
+ return connect.NewError(connect.CodeUnauthenticated, errors.New(errMsgInvalidEmailCode))
+ }
+ if err := s.claimLoginAttempt(ctx, email, storepb.LoginAttemptKind_EMAIL_CODE); err != nil {
+ return err
+ }
+ row, err := s.store.GetEmailVerificationCode(ctx, email, purpose)
+ if err != nil {
+ return connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to get email verification code"))
+ }
+ if row == nil {
+ return connect.NewError(connect.CodeUnauthenticated, errors.New(errMsgInvalidEmailCode))
+ }
+ if time.Now().After(row.ExpiresAt) {
+ _ = s.store.DeleteEmailVerificationCodeIfMatch(ctx, email, purpose, row.CodeHash)
+ return connect.NewError(connect.CodeUnauthenticated, errors.New(errMsgInvalidEmailCode))
+ }
+ if subtle.ConstantTimeCompare([]byte(s.hashEmailCode(submittedCode)), []byte(row.CodeHash)) != 1 {
+ return connect.NewError(connect.CodeUnauthenticated, errors.New(errMsgInvalidEmailCode))
+ }
+ _ = s.store.DeleteEmailVerificationCodeIfMatch(ctx, email, purpose, row.CodeHash)
+ s.clearLoginAttempt(ctx, email, storepb.LoginAttemptKind_EMAIL_CODE)
+ return nil
+}
+
+// generateEmailCode returns a cryptographically-random 6-digit numeric code.
+func generateEmailCode() (string, error) {
+ const digits = "0123456789"
+ b := make([]byte, emailCodeLength)
+ if _, err := rand.Read(b); err != nil {
+ return "", err
+ }
+ for i := range b {
+ b[i] = digits[int(b[i])%len(digits)]
+ }
+ return string(b), nil
+}
+
+// hashEmailCode returns HMAC-SHA256(code) hex-encoded, keyed with the server's auth secret.
+// HMAC with a server-side secret (vs. bare SHA-256) prevents offline brute force of the
+// 10^6-size code space if the DB is ever compromised — the attacker would also need the
+// auth secret to verify candidate codes.
+func (s *AuthService) hashEmailCode(code string) string {
+ mac := hmac.New(sha256.New, []byte(s.secret))
+ mac.Write([]byte(code))
+ return hex.EncodeToString(mac.Sum(nil))
+}
diff --git a/backend/api/v1/auth_service_idp.go b/backend/api/v1/auth_service_idp.go
new file mode 100644
index 0000000000..6c81151218
--- /dev/null
+++ b/backend/api/v1/auth_service_idp.go
@@ -0,0 +1,330 @@
+package v1
+
+import (
+ "context"
+ "fmt"
+ "log/slog"
+ "slices"
+ "strings"
+
+ "connectrpc.com/connect"
+ "github.com/pkg/errors"
+ "golang.org/x/crypto/bcrypt"
+
+ "github.com/bytebase/bytebase/backend/common"
+ "github.com/bytebase/bytebase/backend/common/log"
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+ v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"
+ "github.com/bytebase/bytebase/backend/plugin/idp/ldap"
+ "github.com/bytebase/bytebase/backend/plugin/idp/oauth2"
+ "github.com/bytebase/bytebase/backend/plugin/idp/oidc"
+ "github.com/bytebase/bytebase/backend/store"
+ "github.com/bytebase/bytebase/backend/utils"
+)
+
+// Single sign-on: authenticating a Login request against an identity
+// provider (OAuth2, OIDC, or LDAP) and provisioning the user it names.
+
+// getOrCreateUserWithIDP authenticates a user via an identity provider (SSO).
+// Login API has allow_without_credential, so there's no workspace in the token context.
+// We resolve workspace from the IDP entity (IDP resource_id is globally unique).
+func (s *AuthService) getOrCreateUserWithIDP(ctx context.Context, request *v1pb.LoginRequest) (*store.UserMessage, error) {
+ idpID, err := common.GetIdentityProviderID(request.IdpName)
+ if err != nil {
+ return nil, connect.NewError(connect.CodeInvalidArgument, errors.Wrapf(err, "failed to get identity provider ID"))
+ }
+ // Look up IDP without workspace filter — IDP resource_id is globally unique.
+ // The workspace is resolved from the IDP entity.
+ idp, err := s.store.GetIdentityProviderByID(ctx, idpID)
+ if err != nil {
+ return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to get identity provider"))
+ }
+ if idp == nil {
+ return nil, connect.NewError(connect.CodeNotFound, errors.Errorf("identity provider not found"))
+ }
+
+ // For workspace-scoped IDPs, use the IDP's workspace.
+ // For global IDPs (SaaS), workspace is resolved after authentication from user membership.
+ workspaceID := idp.Workspace
+ externalURL, err := utils.GetEffectiveExternalURL(ctx, s.store, s.profile, workspaceID)
+ if err != nil {
+ return nil, err
+ }
+
+ var userInfo *storepb.IdentityProviderUserInfo
+ switch idp.Type {
+ case storepb.IdentityProviderType_OAUTH2:
+ userInfo, err = oauth2UserInfo(ctx, idp, request, externalURL)
+ case storepb.IdentityProviderType_OIDC:
+ userInfo, err = oidcUserInfo(ctx, idp, request, externalURL)
+ case storepb.IdentityProviderType_LDAP:
+ userInfo, err = s.ldapUserInfo(ctx, idpID, idp, request)
+ default:
+ return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("identity provider type %s not supported", idp.Type.String()))
+ }
+ if err != nil {
+ return nil, err
+ }
+ if userInfo == nil {
+ return nil, connect.NewError(connect.CodeNotFound, errors.Errorf("failed to get user info from identity provider %q", idp.Title))
+ }
+ if userInfo.Identifier == "" {
+ return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("missing identifier in user info from identity provider %q", idp.Title))
+ }
+ // The userinfo's email comes from identity provider, it has to be converted to lower-case.
+ email := strings.ToLower(userInfo.Identifier)
+ if err := common.ValidateEmail(email); err != nil {
+ // If the email is invalid, we will try to use the domain and identifier to construct the email.
+ domain := extractDomain(idp.Domain)
+ if domain != "" {
+ email = strings.ToLower(fmt.Sprintf("%s@%s", email, domain))
+ } else {
+ return nil, connect.NewError(connect.CodeInvalidArgument, errors.Wrapf(err, "invalid email %q", userInfo.Identifier))
+ }
+ }
+
+ user, err := s.store.GetUserByEmail(ctx, email)
+ if err != nil {
+ return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to list users by email %s", email))
+ }
+ // User login through global SSO, then we should auth-resolve the workspace id.
+ if user != nil && workspaceID == "" {
+ wsID, err := s.resolveWorkspaceForLogin(ctx, user, "")
+ if err != nil {
+ slog.Warn("failed to resolve workspace", slog.String("user", user.Email), log.BBError(err))
+ }
+ workspaceID = wsID
+ }
+ // First time login through SSO
+ if user == nil {
+ if workspaceID != "" {
+ if err := validateEmailWithDomains(ctx, s.licenseService, s.store, workspaceID, email, false); err != nil {
+ return nil, err
+ }
+
+ // We will only block new create creation and still allow SSO login from existing users.
+ featurePlan := v1pb.PlanFeature_FEATURE_ENTERPRISE_SSO
+ if idp.Type == storepb.IdentityProviderType_OAUTH2 && googleGitHubDomains[idp.Domain] {
+ featurePlan = v1pb.PlanFeature_FEATURE_GOOGLE_AND_GITHUB_SSO
+ }
+ if err := s.licenseService.IsFeatureEnabled(ctx, workspaceID, featurePlan); err != nil {
+ return nil, connect.NewError(connect.CodePermissionDenied, err)
+ }
+
+ if err := userCountGuard(ctx, s.store, s.licenseService, workspaceID, nil, s.profile.SaaS); err != nil {
+ return nil, err
+ }
+ }
+
+ // Create new user from identity provider.
+ password, err := common.RandomString(20)
+ if err != nil {
+ return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to generate random password"))
+ }
+ passwordHash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
+ if err != nil {
+ return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to generate password hash"))
+ }
+
+ newUser, err := s.store.CreateUser(ctx, &store.UserMessage{
+ Name: userInfo.DisplayName,
+ Email: email,
+ Phone: userInfo.Phone,
+ Type: storepb.PrincipalType_END_USER,
+ PasswordHash: string(passwordHash),
+ })
+ if err != nil {
+ return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to create user"))
+ }
+
+ user = newUser
+ }
+
+ if workspaceID == "" {
+ // Global IDP: create a new workspace for the user (same as Signup flow).
+ wsID, err := common.RandomString(16)
+ if err != nil {
+ return nil, connect.NewError(connect.CodeInternal, errors.Wrap(err, "failed to generate workspace ID"))
+ }
+ ws, err := s.store.CreateWorkspace(ctx, &store.WorkspaceMessage{
+ ResourceID: wsID,
+ Payload: &storepb.WorkspacePayload{Title: "Default Workspace"},
+ AdditionalSettings: s.getAdditionalWorkspaceSettings(),
+ }, email)
+ if err != nil {
+ return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to create workspace"))
+ }
+ workspaceID = ws.ResourceID
+ } else {
+ // Workspace-scoped IDP: add user as member only if not already in the workspace.
+ ws, err := s.store.FindWorkspace(ctx, &store.FindWorkspaceMessage{
+ WorkspaceID: &workspaceID,
+ Email: email,
+ IncludeAllUser: !s.profile.SaaS,
+ })
+ if err != nil {
+ return nil, connect.NewError(connect.CodeInternal, errors.Wrap(err, "failed to check workspace membership"))
+ }
+ if ws == nil {
+ if _, err := s.store.PatchWorkspaceIamPolicy(ctx, &store.PatchIamPolicyMessage{
+ Workspace: workspaceID,
+ Member: common.FormatUserEmail(email),
+ Roles: []string{common.FormatRole(store.WorkspaceMemberRole)},
+ }); err != nil {
+ return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to add user to workspace"))
+ }
+ }
+ }
+
+ if user.MemberDeleted {
+ if err := userCountGuard(ctx, s.store, s.licenseService, workspaceID, nil, s.profile.SaaS); err != nil {
+ return nil, err
+ }
+ // Undelete the user when login via SSO.
+ user, err = s.store.UpdateUser(ctx, user, &store.UpdateUserMessage{Delete: &undeletePatch})
+ if err != nil {
+ return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to undelete user"))
+ }
+ }
+
+ if userInfo.HasGroups {
+ if err := s.syncUserGroups(ctx, user, workspaceID, userInfo.Groups); err != nil {
+ return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to sync user groups"))
+ }
+ }
+ return user, nil
+}
+
+// oauth2UserInfo exchanges the OAuth2 authorization code and fetches the user.
+func oauth2UserInfo(ctx context.Context, idp *store.IdentityProviderMessage, request *v1pb.LoginRequest, externalURL string) (*storepb.IdentityProviderUserInfo, error) {
+ oauth2Context := request.IdpContext.GetOauth2Context()
+ if oauth2Context == nil {
+ return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("missing OAuth2 context"))
+ }
+ oauth2IdentityProvider, err := oauth2.NewIdentityProvider(idp.Config.GetOauth2Config())
+ if err != nil {
+ return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to create new OAuth2 identity provider"))
+ }
+ token, err := oauth2IdentityProvider.ExchangeToken(ctx, fmt.Sprintf("%s/oauth/callback", externalURL), oauth2Context.Code)
+ if err != nil {
+ return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to exchange token"))
+ }
+ userInfo, _, err := oauth2IdentityProvider.UserInfo(token)
+ if err != nil {
+ return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to get user info"))
+ }
+ return userInfo, nil
+}
+
+// oidcUserInfo exchanges the OIDC authorization code and fetches the user.
+func oidcUserInfo(ctx context.Context, idp *store.IdentityProviderMessage, request *v1pb.LoginRequest, externalURL string) (*storepb.IdentityProviderUserInfo, error) {
+ oidcContext := request.IdpContext.GetOidcContext()
+ if oidcContext == nil {
+ return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("missing OIDC context"))
+ }
+ oidcIDP, err := oidc.NewIdentityProvider(ctx, idp.Config.GetOidcConfig())
+ if err != nil {
+ return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to create new OIDC identity provider"))
+ }
+ token, err := oidcIDP.ExchangeToken(ctx, fmt.Sprintf("%s/oidc/callback", externalURL), oidcContext.Code)
+ if err != nil {
+ return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to exchange token"))
+ }
+ userInfo, _, err := oidcIDP.UserInfo(ctx, token, "")
+ if err != nil {
+ return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to get user info"))
+ }
+ return userInfo, nil
+}
+
+// ldapUserInfo binds against the directory as the submitted user. An LDAP bind
+// is a password check: it claims a PASSWORD slot under the provider-scoped
+// identity before the bind and forgets it on success. A rejected credential
+// surfaces as Unauthenticated so edge rate rules counting 401s see failed
+// binds; connectivity and configuration failures stay Internal.
+func (s *AuthService) ldapUserInfo(ctx context.Context, idpID string, idp *store.IdentityProviderMessage, request *v1pb.LoginRequest) (*storepb.IdentityProviderUserInfo, error) {
+ idpConfig := idp.Config.GetLdapConfig()
+ ldapIDP, err := ldap.NewIdentityProvider(
+ ldap.IdentityProviderConfig{
+ Host: idpConfig.Host,
+ Port: int(idpConfig.Port),
+ SkipTLSVerify: idpConfig.SkipTlsVerify,
+ BindDN: idpConfig.BindDn,
+ BindPassword: idpConfig.BindPassword,
+ BaseDN: idpConfig.BaseDn,
+ UserFilter: idpConfig.UserFilter,
+ SecurityProtocol: idpConfig.SecurityProtocol,
+ FieldMapping: idpConfig.FieldMapping,
+ },
+ )
+ if err != nil {
+ return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to create new LDAP identity provider"))
+ }
+
+ identity := ldapLoginIdentity(idpID, request.Email)
+ if err := s.claimLoginAttempt(ctx, identity, storepb.LoginAttemptKind_PASSWORD); err != nil {
+ return nil, err
+ }
+ userInfo, err := ldapIDP.Authenticate(request.Email, request.Password)
+ if err != nil {
+ if errors.Is(err, ldap.ErrInvalidCredentials) {
+ return nil, invalidCredentialsError
+ }
+ return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to get user info"))
+ }
+ s.clearLoginAttempt(ctx, identity, storepb.LoginAttemptKind_PASSWORD)
+ return userInfo, nil
+}
+
+// syncUserGroups syncs the user groups with the given groups.
+// The given groups are the groups that the user belongs to in the identity provider.
+// Supported groups format: ["group1", "group2", ...], ["[email protected]", ...]
+func (s *AuthService) syncUserGroups(ctx context.Context, user *store.UserMessage, workspaceID string, groups []string) error {
+ bbGroups, err := s.store.ListGroups(ctx, &store.FindGroupMessage{Workspace: workspaceID})
+ if err != nil {
+ return connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to list groups"))
+ }
+
+ groupChanged := false
+ for _, bbGroup := range bbGroups {
+ var isMember bool
+ for _, group := range groups {
+ if bbGroup.Email == group || bbGroup.Title == group {
+ isMember = true
+ break
+ }
+ }
+ isBBGroupMember := getMemberInGroup(user, bbGroup) != nil
+ if isMember != isBBGroupMember {
+ if isMember {
+ // Add the user to the group.
+ bbGroup.Payload.Members = append(bbGroup.Payload.Members, &storepb.GroupMember{
+ Role: storepb.GroupMember_MEMBER,
+ Member: common.FormatUserEmail(user.Email),
+ })
+ } else {
+ // Remove the user from the group.
+ bbGroup.Payload.Members = slices.DeleteFunc(bbGroup.Payload.Members, func(member *storepb.GroupMember) bool {
+ return member.Member == common.FormatUserEmail(user.Email)
+ })
+ }
+ if _, err := s.store.UpdateGroup(ctx, &store.UpdateGroupMessage{
+ ID: bbGroup.ID,
+ Workspace: bbGroup.Workspace,
+ Payload: bbGroup.Payload,
+ }); err != nil {
+ return connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to update group %q", bbGroup.Email))
+ }
+ groupChanged = true
+ }
+ }
+
+ // Reload IAM cache if group membership changed.
+ if groupChanged {
+ if err := s.iamManager.ReloadCache(ctx); err != nil {
+ return connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to reload IAM cache"))
+ }
+ }
+
+ return nil
+}
diff --git a/backend/api/v1/auth_service_lockout.go b/backend/api/v1/auth_service_lockout.go
new file mode 100644
index 0000000000..18f73e366e
--- /dev/null
+++ b/backend/api/v1/auth_service_lockout.go
@@ -0,0 +1,103 @@
+package v1
+
+import (
+ "context"
+ "fmt"
+ "log/slog"
+ "time"
+
+ "connectrpc.com/connect"
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/common/log"
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+ "github.com/bytebase/bytebase/backend/store"
+)
+
+// Login-attempt lockout (docs/design/login-attempt-lockout.md): every
+// guessable credential claims a per-identity slot before it is checked, and
+// success forgets the counter. The store owns the atomic mechanism; this file
+// owns the kinds, the shared limit, and the lockout answers.
+
+const (
+ errMsgTooManyPassword = "too many failed login attempts, please try again later"
+ errMsgTooManyMFA = "too many failed MFA attempts, please try again later"
+ errMsgTooManyEmailCode = "too many attempts, please try again later"
+)
+
+// Every credential kind shares one attempt limit
+// (docs/design/login-attempt-lockout.md): loginAttemptMax slots per identity,
+// and a claim more than loginAttemptWindow after the latest restarts the
+// counter — so a lock lasts exactly loginAttemptWindow from the last slot.
+const (
+ loginAttemptMax = 5
+ loginAttemptWindow = 10 * time.Minute
+)
+
+// loginAttemptLockedMsg answers a refused claim, per credential kind.
+var loginAttemptLockedMsg = map[storepb.LoginAttemptKind]string{
+ storepb.LoginAttemptKind_PASSWORD: errMsgTooManyPassword,
+ storepb.LoginAttemptKind_EMAIL_CODE: errMsgTooManyEmailCode,
+ storepb.LoginAttemptKind_MFA: errMsgTooManyMFA,
+}
+
+// claimLoginAttempt claims one attempt slot for the identity under attack,
+// before the credential is checked (docs/design/login-attempt-lockout.md).
+// A locked identity gets ResourceExhausted without any credential comparison.
+// The identity must be server-resolved and globally unique, never optional
+// request context a caller can omit or forge; its size is bounded by the
+// proto field limits, with the store refusing oversized or unkeyed rows.
+func (s *AuthService) claimLoginAttempt(ctx context.Context, identity string, kind storepb.LoginAttemptKind) error {
+ granted, err := s.store.ClaimLoginAttempt(ctx, identity, kind, loginAttemptMax, loginAttemptWindow)
+ if err != nil {
+ return connect.NewError(connect.CodeInternal, err)
+ }
+ if !granted {
+ return connect.NewError(connect.CodeResourceExhausted, errors.New(loginAttemptLockedMsg[kind]))
+ }
+ return nil
+}
+
+// clearLoginAttempt forgets the identity's failed attempts after a successful
+// verification. Success has already consumed a slot, so a swallowed failure
+// here would hold a lock against a proven credential — retry once, then log;
+// a still-standing counter expires on its own within the window.
+func (s *AuthService) clearLoginAttempt(ctx context.Context, identity string, kind storepb.LoginAttemptKind) {
+ err := s.store.ClearLoginAttempt(ctx, identity, kind)
+ if err != nil {
+ err = s.store.ClearLoginAttempt(ctx, identity, kind)
+ }
+ if err != nil {
+ slog.Error("login attempt clear failed", slog.String("kind", kind.String()), log.BBError(err))
+ }
+}
+
+// challengeMFAAndClear verifies the OTP or recovery code (one is present —
+// callers refuse codeless requests before claiming) and forgets the email's
+// MFA failures on success.
+func (s *AuthService) challengeMFAAndClear(ctx context.Context, user *store.UserMessage, email string, otpCode, recoveryCode *string) error {
+ if otpCode != nil {
+ if err := challengeMFACode(user, *otpCode); err != nil {
+ return err
+ }
+ } else if err := s.challengeRecoveryCode(ctx, user, *recoveryCode); err != nil {
+ return err
+ }
+ s.clearLoginAttempt(ctx, email, storepb.LoginAttemptKind_MFA)
+ return nil
+}
+
+// ldapLoginIdentity keys the PASSWORD lockout bucket for an LDAP bind: the
+// identity-provider ID joined with the submitted username, verbatim. The
+// provider must be part of the key — keyed by bare username, an attacker who
+// controls the same username in a directory of their own could clear this
+// directory's counter by logging in there (success deletes the row). The
+// username is not normalized: a case-exact directory attribute can name two
+// accounts differing only by case, and merging them would let either lock —
+// or, on success, clear — the other. One bucket per submitted form is the
+// design's accepted trade. The separator is ":" because it is legal in
+// neither IDP resource IDs ([a-z0-9-]) nor email addresses, so an LDAP
+// bucket can never collide with a plain email account's bucket.
+func ldapLoginIdentity(idpID, username string) string {
+ return fmt.Sprintf("%s:%s", idpID, username)
+}
diff --git a/backend/api/v1/auth_service_lockout_test.go b/backend/api/v1/auth_service_lockout_test.go
new file mode 100644
index 0000000000..fdc9d6b421
--- /dev/null
+++ b/backend/api/v1/auth_service_lockout_test.go
@@ -0,0 +1,471 @@
+package v1
+
+import (
+ "context"
+ "fmt"
+ "testing"
+ "time"
+
+ "connectrpc.com/connect"
+ "github.com/pquerna/otp/totp"
+ "github.com/stretchr/testify/require"
+ "golang.org/x/crypto/bcrypt"
+
+ "github.com/bytebase/bytebase/backend/api/auth"
+ "github.com/bytebase/bytebase/backend/common"
+ "github.com/bytebase/bytebase/backend/common/testcontainer"
+ "github.com/bytebase/bytebase/backend/component/config"
+ "github.com/bytebase/bytebase/backend/enterprise"
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+ v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"
+ "github.com/bytebase/bytebase/backend/migrator"
+ "github.com/bytebase/bytebase/backend/runner/cleaner"
+ "github.com/bytebase/bytebase/backend/store"
+)
+
+// The lockout tests below pin docs/design/login-attempt-lockout.md: every
+// guessable credential claims a login_attempt slot for the identity under
+// attack before the credential is checked, success deletes the row, and locked
+// identities are refused with ResourceExhausted before any bcrypt, TOTP, or
+// hash comparison — independent of audit logs, so identical on Cloud and
+// self-hosted.
+
+func TestPasswordLockoutClaims(t *testing.T) {
+ ctx := context.Background()
+ stores := newAuthTestStore(t)
+ service := &AuthService{store: stores}
+
+ const password = "1024bytebase"
+ createLockoutTestUser(ctx, t, stores, "[email protected]", password)
+
+ t.Run("unknown and known emails lock at the same attempt with the same error", func(t *testing.T) {
+ for _, email := range []string{"[email protected]", "[email protected]"} {
+ for range loginAttemptMax {
+ _, err := service.getAndVerifyUser(ctx, &v1pb.LoginRequest{Email: email, Password: "wrong-password"})
+ require.Equal(t, connect.CodeUnauthenticated, connect.CodeOf(err))
+ require.ErrorContains(t, err, errMsgInvalidCredentials)
+ }
+ _, err := service.getAndVerifyUser(ctx, &v1pb.LoginRequest{Email: email, Password: "wrong-password"})
+ require.Equal(t, connect.CodeResourceExhausted, connect.CodeOf(err))
+ require.ErrorContains(t, err, errMsgTooManyPassword)
+ }
+ })
+
+ t.Run("a locked identity is refused before bcrypt", func(t *testing.T) {
+ _, err := service.getAndVerifyUser(ctx, &v1pb.LoginRequest{Email: "[email protected]", Password: password})
+ require.Equal(t, connect.CodeResourceExhausted, connect.CodeOf(err),
+ "the correct password must not slip through a lock: the slot is claimed before the credential is checked")
+ })
+
+ t.Run("success clears the counter", func(t *testing.T) {
+ const email = "[email protected]"
+ createLockoutTestUser(ctx, t, stores, email, password)
+ for range 3 {
+ _, err := service.getAndVerifyUser(ctx, &v1pb.LoginRequest{Email: email, Password: "wrong-password"})
+ require.Equal(t, connect.CodeUnauthenticated, connect.CodeOf(err))
+ }
+ user, err := service.getAndVerifyUser(ctx, &v1pb.LoginRequest{Email: email, Password: password})
+ require.NoError(t, err)
+ require.Equal(t, email, user.Email)
+
+ // The forgotten failures must not count against the fresh window.
+ for range loginAttemptMax {
+ _, err := service.getAndVerifyUser(ctx, &v1pb.LoginRequest{Email: email, Password: "wrong-password"})
+ require.Equal(t, connect.CodeUnauthenticated, connect.CodeOf(err))
+ }
+ _, err = service.getAndVerifyUser(ctx, &v1pb.LoginRequest{Email: email, Password: "wrong-password"})
+ require.Equal(t, connect.CodeResourceExhausted, connect.CodeOf(err))
+ })
+
+ t.Run("garbage identities never write a row", func(t *testing.T) {
+ // Over-length emails are refused at the proto edge (see
+ // TestAuthEmailFieldsAreLengthBounded); invalid syntax is refused here.
+ for range loginAttemptMax + 1 {
+ _, err := service.getAndVerifyUser(ctx, &v1pb.LoginRequest{Email: "not-an-email", Password: "wrong-password"})
+ require.Equal(t, connect.CodeUnauthenticated, connect.CodeOf(err),
+ "an invalid-syntax email is rejected before the claim, with the same error as a wrong password")
+ }
+ var count int
+ require.NoError(t, stores.GetDB().QueryRowContext(ctx,
+ `SELECT COUNT(*) FROM login_attempt WHERE identity = 'not-an-email'`).Scan(&count))
+ require.Zero(t, count)
+ })
+}
+
+func TestEmailCodeLockoutClaims(t *testing.T) {
+ ctx := context.Background()
+ stores := newAuthTestStore(t)
+ service := &AuthService{store: stores, secret: "test-secret"}
+
+ upsertCode := func(email string, purpose storepb.EmailVerificationCodePurpose, code string) {
+ t.Helper()
+ sent, err := stores.UpsertEmailVerificationCodeIfCooldownExpired(ctx, &store.EmailVerificationCodeMessage{
+ Email: email,
+ Purpose: purpose,
+ CodeHash: service.hashEmailCode(code),
+ ExpiresAt: time.Now().Add(emailCodeExpiry),
+ LastSentAt: time.Now(),
+ }, 0)
+ require.NoError(t, err)
+ require.True(t, sent)
+ }
+
+ t.Run("the lockout precedes the code row", func(t *testing.T) {
+ const email = "[email protected]"
+ for range loginAttemptMax {
+ err := service.verifyEmailCode(ctx, email, storepb.EmailVerificationCodePurpose_LOGIN, "000000")
+ require.Equal(t, connect.CodeUnauthenticated, connect.CodeOf(err))
+ require.ErrorContains(t, err, "invalid or expired code")
+ }
+ err := service.verifyEmailCode(ctx, email, storepb.EmailVerificationCodePurpose_LOGIN, "000000")
+ require.Equal(t, connect.CodeResourceExhausted, connect.CodeOf(err),
+ "guessing must be bounded per identity even when no code is pending")
+ require.ErrorContains(t, err, errMsgTooManyEmailCode)
+ })
+
+ t.Run("resending a code does not reset the counter", func(t *testing.T) {
+ const email = "[email protected]"
+ upsertCode(email, storepb.EmailVerificationCodePurpose_LOGIN, "111111")
+ for range 4 {
+ err := service.verifyEmailCode(ctx, email, storepb.EmailVerificationCodePurpose_LOGIN, "000000")
+ require.Equal(t, connect.CodeUnauthenticated, connect.CodeOf(err))
+ }
+ upsertCode(email, storepb.EmailVerificationCodePurpose_LOGIN, "222222")
+ err := service.verifyEmailCode(ctx, email, storepb.EmailVerificationCodePurpose_LOGIN, "000000")
+ require.Equal(t, connect.CodeUnauthenticated, connect.CodeOf(err))
+
+ err = service.verifyEmailCode(ctx, email, storepb.EmailVerificationCodePurpose_LOGIN, "222222")
+ require.Equal(t, connect.CodeResourceExhausted, connect.CodeOf(err),
+ "the bound must survive code rotation: five wrong guesses lock the email even against a fresh valid code")
+ })
+
+ t.Run("wrong guesses no longer delete the code row", func(t *testing.T) {
+ const email = "[email protected]"
+ upsertCode(email, storepb.EmailVerificationCodePurpose_LOGIN, "111111")
+ for range loginAttemptMax {
+ err := service.verifyEmailCode(ctx, email, storepb.EmailVerificationCodePurpose_LOGIN, "000000")
+ require.Equal(t, connect.CodeUnauthenticated, connect.CodeOf(err))
+ }
+ row, err := stores.GetEmailVerificationCode(ctx, email, storepb.EmailVerificationCodePurpose_LOGIN)
+ require.NoError(t, err)
+ require.NotNil(t, row, "the code row must live until it expires or is consumed")
+
+ sent, err := stores.UpsertEmailVerificationCodeIfCooldownExpired(ctx, &store.EmailVerificationCodeMessage{
+ Email: email,
+ Purpose: storepb.EmailVerificationCodePurpose_LOGIN,
+ CodeHash: service.hashEmailCode("333333"),
+ ExpiresAt: time.Now().Add(emailCodeExpiry),
+ LastSentAt: time.Now(),
+ }, emailCodeResendCooldown)
+ require.NoError(t, err)
+ require.False(t, sent, "the resend cooldown must always have a row to evaluate — the exhaustion bypass is closed")
+ })
+
+ t.Run("a correct code within the limit clears the counter", func(t *testing.T) {
+ const email = "[email protected]"
+ upsertCode(email, storepb.EmailVerificationCodePurpose_LOGIN, "111111")
+ for range 4 {
+ err := service.verifyEmailCode(ctx, email, storepb.EmailVerificationCodePurpose_LOGIN, "000000")
+ require.Equal(t, connect.CodeUnauthenticated, connect.CodeOf(err))
+ }
+ require.NoError(t, service.verifyEmailCode(ctx, email, storepb.EmailVerificationCodePurpose_LOGIN, "111111"))
+
+ row, err := stores.GetEmailVerificationCode(ctx, email, storepb.EmailVerificationCodePurpose_LOGIN)
+ require.NoError(t, err)
+ require.Nil(t, row, "a matched code is single-use")
+
+ for range loginAttemptMax {
+ err := service.verifyEmailCode(ctx, email, storepb.EmailVerificationCodePurpose_LOGIN, "000000")
+ require.Equal(t, connect.CodeUnauthenticated, connect.CodeOf(err))
+ }
+ err = service.verifyEmailCode(ctx, email, storepb.EmailVerificationCodePurpose_LOGIN, "000000")
+ require.Equal(t, connect.CodeResourceExhausted, connect.CodeOf(err))
+ })
+
+ t.Run("login and reset codes share one bucket per email", func(t *testing.T) {
+ const email = "[email protected]"
+ for range 3 {
+ err := service.verifyEmailCode(ctx, email, storepb.EmailVerificationCodePurpose_LOGIN, "000000")
+ require.Equal(t, connect.CodeUnauthenticated, connect.CodeOf(err))
+ }
+ for range 2 {
+ err := service.verifyEmailCode(ctx, email, storepb.EmailVerificationCodePurpose_PASSWORD_RESET, "000000")
+ require.Equal(t, connect.CodeUnauthenticated, connect.CodeOf(err))
+ }
+ err := service.verifyEmailCode(ctx, email, storepb.EmailVerificationCodePurpose_LOGIN, "000000")
+ require.Equal(t, connect.CodeResourceExhausted, connect.CodeOf(err),
+ "the attempt limit is per identity, across codes and purposes")
+ })
+}
+
+func TestResetPasswordClearsPasswordLockout(t *testing.T) {
+ ctx := context.Background()
+ stores := newAuthTestStore(t)
+ t.Setenv("EMAIL_CONFIG", "")
+ service := &AuthService{store: stores, secret: "test-secret", profile: &config.Profile{}}
+
+ const email = "[email protected]"
+ const oldPassword = "old-password-1024"
+ const newPassword = "new-password-1024"
+ createLockoutTestUser(ctx, t, stores, email, oldPassword)
+
+ for range loginAttemptMax {
+ _, err := service.getAndVerifyUser(ctx, &v1pb.LoginRequest{Email: email, Password: "wrong-password"})
+ require.Equal(t, connect.CodeUnauthenticated, connect.CodeOf(err))
+ }
+ _, err := service.getAndVerifyUser(ctx, &v1pb.LoginRequest{Email: email, Password: oldPassword})
+ require.Equal(t, connect.CodeResourceExhausted, connect.CodeOf(err))
+
+ const resetCode = "123456"
+ sent, err := stores.UpsertEmailVerificationCodeIfCooldownExpired(ctx, &store.EmailVerificationCodeMessage{
+ Email: email,
+ Purpose: storepb.EmailVerificationCodePurpose_PASSWORD_RESET,
+ CodeHash: service.hashEmailCode(resetCode),
+ ExpiresAt: time.Now().Add(emailCodeExpiry),
+ LastSentAt: time.Now(),
+ }, 0)
+ require.NoError(t, err)
+ require.True(t, sent)
+
+ _, err = service.ResetPassword(ctx, connect.NewRequest(&v1pb.ResetPasswordRequest{
+ Email: email,
+ Code: resetCode,
+ NewPassword: newPassword,
+ }))
+ require.NoError(t, err)
+
+ user, err := service.getAndVerifyUser(ctx, &v1pb.LoginRequest{Email: email, Password: newPassword})
+ require.NoError(t, err, "a successful password reset must also clear the PASSWORD lock")
+ require.Equal(t, email, user.Email)
+}
+
+func TestMFALockoutClaims(t *testing.T) {
+ ctx := context.Background()
+ stores := newAuthTestStore(t)
+ const secret = "test-secret"
+ service := &AuthService{store: stores, secret: secret}
+
+ attempt := func(email string, code *string) error {
+ t.Helper()
+ token, err := auth.GenerateMFATempTokenWithLoginMethod(email, string(loginAuthMethodPassword), secret, mfaTempTokenDuration)
+ require.NoError(t, err)
+ _, _, err = service.completeMFALogin(ctx, &v1pb.LoginRequest{MfaTempToken: &token, OtpCode: code})
+ return err
+ }
+
+ t.Run("guesses are bounded per identity across temp tokens", func(t *testing.T) {
+ const email = "[email protected]"
+ _, otpSecret := setupMFAUser(ctx, t, stores, email)
+ for i := range loginAttemptMax {
+ // A fresh token per attempt must not buy fresh guesses.
+ err := attempt(email, ptr("not-a-code"))
+ require.Equal(t, connect.CodeUnauthenticated, connect.CodeOf(err), "attempt %d", i+1)
+ require.ErrorContains(t, err, errMsgInvalidMFACode)
+ }
+ err := attempt(email, ptr("not-a-code"))
+ require.Equal(t, connect.CodeResourceExhausted, connect.CodeOf(err))
+ require.ErrorContains(t, err, errMsgTooManyMFA)
+
+ validOTP, err := totp.GenerateCode(otpSecret, time.Now())
+ require.NoError(t, err)
+ err = attempt(email, &validOTP)
+ require.Equal(t, connect.CodeResourceExhausted, connect.CodeOf(err),
+ "a locked identity is refused before the TOTP comparison")
+ })
+
+ t.Run("success clears the counter", func(t *testing.T) {
+ const email = "[email protected]"
+ _, otpSecret := setupMFAUser(ctx, t, stores, email)
+ for range loginAttemptMax - 1 {
+ err := attempt(email, ptr("not-a-code"))
+ require.Equal(t, connect.CodeUnauthenticated, connect.CodeOf(err))
+ }
+ validOTP, err := totp.GenerateCode(otpSecret, time.Now())
+ require.NoError(t, err)
+ require.NoError(t, attempt(email, &validOTP))
+
+ for range loginAttemptMax {
+ err := attempt(email, ptr("not-a-code"))
+ require.Equal(t, connect.CodeUnauthenticated, connect.CodeOf(err))
+ }
+ err = attempt(email, ptr("not-a-code"))
+ require.Equal(t, connect.CodeResourceExhausted, connect.CodeOf(err))
+ })
+
+ t.Run("codeless requests claim nothing", func(t *testing.T) {
+ const email = "[email protected]"
+ setupMFAUser(ctx, t, stores, email)
+ for range loginAttemptMax + 1 {
+ err := attempt(email, nil)
+ require.Equal(t, connect.CodeUnauthenticated, connect.CodeOf(err))
+ require.ErrorContains(t, err, "OTP or recovery code is required")
+ }
+ // The budget is untouched: a real wrong guess still gets the
+ // invalid-code answer, not a lockout.
+ err := attempt(email, ptr("not-a-code"))
+ require.Equal(t, connect.CodeUnauthenticated, connect.CodeOf(err))
+ require.ErrorContains(t, err, errMsgInvalidMFACode)
+ })
+}
+
+func TestSwitchWorkspaceMFAClaims(t *testing.T) {
+ ctx := context.Background()
+ stores := newAuthTestStore(t)
+ const secret = "test-secret"
+ const workspaceID = "switch-mfa-test"
+ const email = "[email protected]"
+
+ _, err := stores.CreateWorkspace(ctx, &store.WorkspaceMessage{
+ ResourceID: workspaceID,
+ Payload: &storepb.WorkspacePayload{Title: "Switch MFA test"},
+ }, email)
+ require.NoError(t, err)
+ licenseService, err := enterprise.NewLicenseService(common.ReleaseModeDev, stores, false, "")
+ require.NoError(t, err)
+ require.NoError(t, licenseService.StoreLicense(ctx, workspaceID, authTestEnterpriseLicense))
+ service := NewAuthService(stores, secret, licenseService, &config.Profile{}, nil)
+
+ user, _ := setupMFAUser(ctx, t, stores, email)
+
+ userCtx := context.WithValue(ctx, common.UserContextKey, user)
+ token, err := auth.GenerateMFATempTokenWithLoginMethod(email, string(loginAuthMethodPassword), secret, mfaTempTokenDuration)
+ require.NoError(t, err)
+
+ // An argument error must not consume attempt budget — the loop below
+ // still needs the full allowance before the lock engages.
+ _, err = service.SwitchWorkspace(userCtx, connect.NewRequest(&v1pb.SwitchWorkspaceRequest{
+ Workspace: common.FormatWorkspace(workspaceID),
+ MfaTempToken: &token,
+ }))
+ require.Equal(t, connect.CodeInvalidArgument, connect.CodeOf(err))
+
+ for range loginAttemptMax {
+ _, err := service.SwitchWorkspace(userCtx, connect.NewRequest(&v1pb.SwitchWorkspaceRequest{
+ Workspace: common.FormatWorkspace(workspaceID),
+ MfaTempToken: &token,
+ OtpCode: ptr("not-a-code"),
+ }))
+ require.Equal(t, connect.CodeUnauthenticated, connect.CodeOf(err))
+ require.ErrorContains(t, err, errMsgInvalidMFACode)
+ }
+ _, err = service.SwitchWorkspace(userCtx, connect.NewRequest(&v1pb.SwitchWorkspaceRequest{
+ Workspace: common.FormatWorkspace(workspaceID),
+ MfaTempToken: &token,
+ OtpCode: ptr("not-a-code"),
+ }))
+ require.Equal(t, connect.CodeResourceExhausted, connect.CodeOf(err),
+ "MFA completion on workspace switch draws from the same per-identity bucket")
+ require.ErrorContains(t, err, errMsgTooManyMFA)
+}
+
+// TestLDAPLoginIdentity pins the provider-scoped lockout key. "/" is legal in
+// an email local part, so a "/" separator would let the literal email account
+// "corpldap/[email protected]" share — lock out, and on success clear — the
+// bucket of LDAP user "[email protected]" on IDP "corpldap". ":" is legal in
+// neither alphabet, so an LDAP identity can never be a valid email.
+func TestLDAPLoginIdentity(t *testing.T) {
+ // The submitted username is kept verbatim: a case-exact directory
+ // attribute can name two accounts differing only by case, and merging
+ // them would let either lock — or clear — the other.
+ require.Equal(t, "corp-ldap:[email protected]", ldapLoginIdentity("corp-ldap", "[email protected]"))
+ require.NotEqual(t, ldapLoginIdentity("corp-ldap", "alice"), ldapLoginIdentity("corp-ldap", "Alice"))
+ require.True(t, common.IsValidEmail("corpldap/[email protected]"))
+ require.False(t, common.IsValidEmail(ldapLoginIdentity("corpldap", "[email protected]")))
+}
+
+func TestLDAPLockoutClaims(t *testing.T) {
+ ctx := context.Background()
+ stores := newAuthTestStore(t)
+ service := &AuthService{store: stores, secret: "test-secret", profile: &config.Profile{ExternalURL: "http://localhost"}}
+
+ const idpID = "ldap-lockout-test"
+ _, err := stores.CreateWorkspace(ctx, &store.WorkspaceMessage{
+ ResourceID: "ldap-lockout-ws",
+ Payload: &storepb.WorkspacePayload{Title: "LDAP lockout test"},
+ require.NoError(t, err)
+ _, err = stores.CreateIdentityProvider(ctx, &store.IdentityProviderMessage{
+ ResourceID: idpID,
+ Workspace: "ldap-lockout-ws",
+ Title: "Unreachable directory",
+ Type: storepb.IdentityProviderType_LDAP,
+ Config: &storepb.IdentityProviderConfig{Config: &storepb.IdentityProviderConfig_LdapConfig{LdapConfig: &storepb.LDAPIdentityProviderConfig{
+ Host: "127.0.0.1",
+ Port: 1,
+ BindDn: "cn=admin,dc=example,dc=com",
+ BindPassword: "unused",
+ BaseDn: "dc=example,dc=com",
+ UserFilter: "(uid=%s)",
+ FieldMapping: &storepb.FieldMapping{Identifier: "uid"},
+ }}},
+ })
+ require.NoError(t, err)
+
+ request := &v1pb.LoginRequest{IdpName: "idps/" + idpID, Email: "Alice", Password: "wrong"}
+ _, err = service.getOrCreateUserWithIDP(ctx, request)
+ require.Error(t, err, "the directory is unreachable")
+
+ // The slot is claimed before the bind, under the provider-scoped key.
+ var identity string
+ require.NoError(t, stores.GetDB().QueryRowContext(ctx,
+ `SELECT identity FROM login_attempt WHERE kind = 'PASSWORD'`).Scan(&identity))
+ require.Equal(t, idpID+":Alice", identity)
+
+ for range loginAttemptMax - 1 {
+ _, err := service.getOrCreateUserWithIDP(ctx, request)
+ require.Error(t, err)
+ require.NotEqual(t, connect.CodeResourceExhausted, connect.CodeOf(err))
+ }
+ _, err = service.getOrCreateUserWithIDP(ctx, request)
+ require.Equal(t, connect.CodeResourceExhausted, connect.CodeOf(err))
+ require.ErrorContains(t, err, errMsgTooManyPassword)
+}
+
+// TestLoginAttemptRetentionOutlivesLockouts ties the cleaner's purge horizon
+// to the lockout window: a retention shorter than the window would delete
+// still-running locks, silently capping every lockout at the retention.
+func TestLoginAttemptRetentionOutlivesLockouts(t *testing.T) {
+ require.Greater(t, cleaner.LoginAttemptRetentionPeriod, loginAttemptWindow,
+ "the hourly purge must never delete a still-running lock")
+}
+
+func newAuthTestStore(t *testing.T) *store.Store {
+ t.Helper()
+ ctx := context.Background()
+ container := testcontainer.GetTestPgContainer(ctx, t)
+ t.Cleanup(func() { container.Close(ctx) })
+ require.NoError(t, migrator.MigrateSchema(ctx, container.GetDB()))
+
+ pgURL := fmt.Sprintf("host=%s port=%s user=postgres password=root-password database=postgres", container.GetHost(), container.GetPort())
+ stores, err := store.New(ctx, pgURL, false)
+ require.NoError(t, err)
+ t.Cleanup(func() { require.NoError(t, stores.Close()) })
+ return stores
+}
+
+func createLockoutTestUser(ctx context.Context, t *testing.T, stores *store.Store, email, password string) *store.UserMessage {
+ t.Helper()
+ passwordHash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.MinCost)
+ require.NoError(t, err)
+ user, err := stores.CreateUser(ctx, &store.UserMessage{
+ Email: email,
+ Name: email,
+ Type: storepb.PrincipalType_END_USER,
+ PasswordHash: string(passwordHash),
+ Profile: &storepb.UserProfile{},
+ })
+ require.NoError(t, err)
+ return user
+}
+
+func setupMFAUser(ctx context.Context, t *testing.T, stores *store.Store, email string) (*store.UserMessage, string) {
+ t.Helper()
+ user := createLockoutTestUser(ctx, t, stores, email, "1024bytebase")
+ key, err := totp.Generate(totp.GenerateOpts{Issuer: "bytebase-test", AccountName: email})
+ require.NoError(t, err)
+ user, err = stores.UpdateUser(ctx, user, &store.UpdateUserMessage{
+ MFAConfig: &storepb.MFAConfig{OtpSecret: key.Secret()},
+ })
+ require.NoError(t, err)
+ return user, key.Secret()
+}
diff --git a/backend/api/v1/auth_service_test.go b/backend/api/v1/auth_service_test.go
index 238edb7e4b..fc68ba3563 100644
--- a/backend/api/v1/auth_service_test.go
+++ b/backend/api/v1/auth_service_test.go
@@ -10,7 +10,6 @@ import (
"connectrpc.com/connect"
"github.com/golang-jwt/jwt/v5"
"github.com/stretchr/testify/require"
- statuspb "google.golang.org/genproto/googleapis/rpc/status"
"github.com/bytebase/bytebase/backend/api/auth"
"github.com/bytebase/bytebase/backend/common"
@@ -19,71 +18,12 @@ import (
"github.com/bytebase/bytebase/backend/enterprise"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"
- "github.com/bytebase/bytebase/backend/generated-go/v1/v1connect"
"github.com/bytebase/bytebase/backend/migrator"
"github.com/bytebase/bytebase/backend/store"
)
const authTestEnterpriseLicense = "eyJhbGciOiJSUzI1NiIsImtpZCI6InYxIiwidHlwIjoiSldUIn0.eyJpbnN0YW5jZUNvdW50Ijo5OTksInRyaWFsaW5nIjpmYWxzZSwicGxhbiI6IkVOVEVSUFJJU0UiLCJvcmdOYW1lIjoiYmIiLCJhdWQiOiJiYi5saWNlbnNlIiwiZXhwIjo3OTc0OTc5MjAwLCJpYXQiOjE2NjM2Njc1NjEsImlzcyI6ImJ5dGViYXNlIiwic3ViIjoiMDAwMDEwMDAuIn0.JjYCMeAAMB9FlVeDFLdN3jvFcqtPsbEzaIm1YEDhUrfekthCbIOeX_DB2Bg2OUji3HSX5uDvG9AkK4Gtrc4gLMPI3D5mk3L-6wUKZ0L4REztS47LT4oxVhpqPQayYa9lKJB1YoHaqeMV4Z5FXeOXwuACoELznlwpT6pXo9xXm_I6QwQiO7-zD83XOTO4PRjByc-q3GKQu_64zJMIKiCW0I8a3GvrdSnO7jUuYU1KPmCuk0ZRq3I91m29LTo478BMST59HqCLj1GGuCKtR3SL_376XsZfUUM0iSAur5scg99zNGWRj-sUo05wbAadYx6V6TKaWrBUi_8_0RnJyP5gbA"
-func TestCountRecentLoginFailures(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))
- _, err := db.ExecContext(ctx, `INSERT INTO workspace (resource_id) VALUES ('ws-test')`)
- require.NoError(t, err)
-
- pgURL := fmt.Sprintf("host=%s port=%s user=postgres password=root-password database=postgres", container.GetHost(), container.GetPort())
- stores, err := store.New(ctx, pgURL, false)
- require.NoError(t, err)
- t.Cleanup(func() { require.NoError(t, stores.Close()) })
- service := &AuthService{store: stores}
-
- const email = "[email protected]"
- createFailure := func(workspace, method, resource, user, message, response string) {
- t.Helper()
- require.NoError(t, stores.CreateAuditLog(ctx, workspace, &storepb.AuditLog{
- Method: method,
- Resource: resource,
- User: user,
- Response: response,
- Status: &statuspb.Status{
- Code: int32(connect.CodeUnauthenticated),
- Message: message,
- },
- }))
- }
-
- createFailure("ws-test", v1connect.AuthServiceLoginProcedure, email, "", errMsgInvalidCredentials, "")
- createFailure("ws-test", v1connect.AuthServiceLoginProcedure, email, "", errMsgInvalidCredentials, "")
- createFailure("ws-test", v1connect.AuthServiceLoginProcedure, email, "", errMsgInvalidCredentials, "old")
- createFailure("ws-test", v1connect.AuthServiceLoginProcedure, email, "", errMsgInvalidMFACode, "")
- createFailure("ws-test", v1connect.AuthServiceLoginProcedure, email, "", errMsgInvalidRecoveryCode, "")
- createFailure("ws-test", v1connect.AuthServiceSwitchWorkspaceProcedure, "workspaces/ws-test", common.FormatUserEmail(email), errMsgInvalidMFACode, "")
- createFailure("ws-test", v1connect.AuthServiceSwitchWorkspaceProcedure, "workspaces/ws-test", common.FormatUserEmail(email), errMsgInvalidRecoveryCode, "")
- require.NoError(t, stores.CreateAuditLog(ctx, "ws-test", &storepb.AuditLog{
- Method: v1connect.AuthServiceLoginProcedure,
- Resource: email,
- Status: &statuspb.Status{},
- }))
-
- result, err := db.ExecContext(ctx, `UPDATE audit_log SET created_at = $1 WHERE payload->>'response' = 'old'`, time.Now().Add(-2*time.Hour))
- require.NoError(t, err)
- rowsAffected, err := result.RowsAffected()
- require.NoError(t, err)
- require.EqualValues(t, 1, rowsAffected)
-
- passwordFailures, err := service.countRecentLoginFailures(ctx, email, time.Hour, errMsgInvalidCredentials)
- require.NoError(t, err)
- require.Equal(t, 2, passwordFailures)
-
- mfaFailures, err := service.countRecentLoginFailures(ctx, email, time.Hour, errMsgInvalidMFACode, errMsgInvalidRecoveryCode)
- require.NoError(t, err)
- require.Equal(t, 2, mfaFailures)
-}
-
func TestLoginAnnouncesPreAuthenticationWorkspace(t *testing.T) {
ctx := context.Background()
container := testcontainer.GetTestPgContainer(ctx, t)
@@ -207,14 +147,7 @@ func TestExtractDomain(t *testing.T) {
func TestPasswordResetEmailSkipsDeletedUser(t *testing.T) {
ctx := context.Background()
- container := testcontainer.GetTestPgContainer(ctx, t)
- t.Cleanup(func() { container.Close(ctx) })
- require.NoError(t, migrator.MigrateSchema(ctx, container.GetDB()))
-
- pgURL := fmt.Sprintf("host=%s port=%s user=postgres password=root-password database=postgres", container.GetHost(), container.GetPort())
- stores, err := store.New(ctx, pgURL, false)
- require.NoError(t, err)
- t.Cleanup(func() { require.NoError(t, stores.Close()) })
+ stores := newAuthTestStore(t)
user, err := stores.CreateUser(ctx, &store.UserMessage{
@@ -247,16 +180,9 @@ func TestLoginEnforcesWorkspaceDomains(t *testing.T) {
)
ctx := context.Background()
- container := testcontainer.GetTestPgContainer(ctx, t)
- t.Cleanup(func() { container.Close(ctx) })
- require.NoError(t, migrator.MigrateSchema(ctx, container.GetDB()))
-
- pgURL := fmt.Sprintf("host=%s port=%s user=postgres password=root-password database=postgres", container.GetHost(), container.GetPort())
- stores, err := store.New(ctx, pgURL, false)
- require.NoError(t, err)
- t.Cleanup(func() { require.NoError(t, stores.Close()) })
+ stores := newAuthTestStore(t)
- _, err = stores.CreateWorkspace(ctx, &store.WorkspaceMessage{
+ _, err := stores.CreateWorkspace(ctx, &store.WorkspaceMessage{
ResourceID: workspaceID,
Payload: &storepb.WorkspacePayload{Title: "Email code domain test"},
@@ -310,14 +236,14 @@ func TestLoginEnforcesWorkspaceDomains(t *testing.T) {
require.NoError(t, err)
t.Run("workspace admin", func(t *testing.T) {
- err := service.validateLoginPermissions(ctx, blockedAdmin, workspaceID, &v1pb.LoginRequest{
+ _, err := service.validateLoginPermissions(ctx, blockedAdmin, workspaceID, &v1pb.LoginRequest{
Email: blockedAdmin.Email,
IdpName: "idps/test",
})
require.Equal(t, connect.CodeInvalidArgument, connect.CodeOf(err))
require.ErrorContains(t, err, "does not belong to allowed domains")
- err = service.validateLoginPermissions(ctx, allowedAdmin, workspaceID, &v1pb.LoginRequest{
+ _, err = service.validateLoginPermissions(ctx, allowedAdmin, workspaceID, &v1pb.LoginRequest{
Email: allowedAdmin.Email,
Password: "password",
})
@@ -355,14 +281,16 @@ func TestLoginEnforcesWorkspaceDomains(t *testing.T) {
CodeHash: service.hashEmailCode(code),
ExpiresAt: time.Now().Add(time.Minute),
LastSentAt: time.Now(),
- Workspace: workspaceID,
}, 0)
require.NoError(t, err)
- _, err = service.authenticateEmailCodeLogin(ctx, &v1pb.LoginRequest{
+ // The domain gate for existing users runs downstream in
+ // validateLoginPermissions against the server-resolved workspace, so
+ // exercise the full Login pipeline.
+ _, err = service.Login(ctx, connect.NewRequest(&v1pb.LoginRequest{
Email: email,
EmailCode: ptr(code),
- })
+ }))
require.Equal(t, connect.CodeInvalidArgument, connect.CodeOf(err))
require.ErrorContains(t, err, "does not belong to allowed domains")
})
@@ -374,14 +302,13 @@ func TestLoginEnforcesWorkspaceDomains(t *testing.T) {
CodeHash: service.hashEmailCode(code),
ExpiresAt: time.Now().Add(time.Minute),
LastSentAt: time.Now(),
- Workspace: workspaceID,
}, 0)
require.NoError(t, err)
- _, err = service.authenticateEmailCodeLogin(ctx, &v1pb.LoginRequest{
+ _, err = service.Login(ctx, connect.NewRequest(&v1pb.LoginRequest{
Email: blockedAdmin.Email,
EmailCode: ptr(code),
- })
+ }))
require.Equal(t, connect.CodeInvalidArgument, connect.CodeOf(err))
require.ErrorContains(t, err, "does not belong to allowed domains")
})
@@ -394,7 +321,6 @@ func TestLoginEnforcesWorkspaceDomains(t *testing.T) {
CodeHash: service.hashEmailCode(code),
ExpiresAt: time.Now().Add(time.Minute),
LastSentAt: time.Now(),
- Workspace: workspaceID,
}, 0)
require.NoError(t, err)
diff --git a/backend/api/v1/user_service.go b/backend/api/v1/user_service.go
index 7056c2b2c8..036959aedd 100644
--- a/backend/api/v1/user_service.go
+++ b/backend/api/v1/user_service.go
@@ -443,7 +443,7 @@ func (s *UserService) UpdateUser(ctx context.Context, request *connect.Request[v
if isMFATempSecretExpired(user.MFAConfig) {
return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("MFA setup has expired, please regenerate the temporary secret"))
}
- isValid := validateWithCodeAndSecret(*request.Msg.OtpCode, user.MFAConfig.TempOtpSecret)
+ isValid := totp.Validate(*request.Msg.OtpCode, user.MFAConfig.TempOtpSecret)
if !isValid {
return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("invalid OTP code"))
}
diff --git a/backend/component/recovery/service.go b/backend/component/recovery/service.go
index cd7f107274..85acab86e8 100644
--- a/backend/component/recovery/service.go
+++ b/backend/component/recovery/service.go
@@ -316,8 +316,10 @@ func (s *Service) AddUserToWorkspace(ctx context.Context, request AddUserToWorks
return result, nil
}
-// ResetUserPassword replaces the password of an existing, active end user
-// without changing any other access state.
+// ResetUserPassword replaces the password of an existing, active end user and
+// clears the user's password-lockout counter so the fresh password works
+// immediately (the API-path ResetPassword does the same); no other access
+// state changes.
func (s *Service) ResetUserPassword(ctx context.Context, request ResetUserPasswordRequest) (*ResetUserPasswordResult, error) {
if err := s.requireWorkspace(ctx, request.WorkspaceID); err != nil {
return nil, err
@@ -367,6 +369,16 @@ func (s *Service) ResetUserPassword(ctx context.Context, request ResetUserPasswo
result.Changed = true
}
+ // A lockout the user guessed themselves into must not outlive the reset:
+ // without this, the operator hands over a password that Login keeps
+ // refusing with ResourceExhausted until the window lapses.
+ if err := s.store.ClearLoginAttempt(ctx, email, storepb.LoginAttemptKind_PASSWORD); err != nil {
+ if result.Changed {
+ return result, errors.Wrap(err, "password was reset, but failed to clear the login attempt counter")
+ }
+ return result, errors.Wrap(err, "failed to clear the login attempt counter")
+ }
+
if err := s.createAuditLog(ctx, request.WorkspaceID, resetUserPasswordAuditMethod, string(auditRequest)); err != nil {
return result, errors.Wrap(err, "user password reset completed, but failed to create the recovery audit log")
}
diff --git a/backend/generated-go/store/auth.pb.go b/backend/generated-go/store/auth.pb.go
index 540a313404..53d2e2c374 100644
--- a/backend/generated-go/store/auth.pb.go
+++ b/backend/generated-go/store/auth.pb.go
@@ -72,6 +72,60 @@ 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.
+type LoginAttemptKind int32
+
+const (
+ LoginAttemptKind_LOGIN_ATTEMPT_KIND_UNSPECIFIED LoginAttemptKind = 0
+ LoginAttemptKind_PASSWORD LoginAttemptKind = 1
+ LoginAttemptKind_EMAIL_CODE LoginAttemptKind = 2
+ LoginAttemptKind_MFA LoginAttemptKind = 3
+)
+
+// Enum value maps for LoginAttemptKind.
+var (
+ LoginAttemptKind_name = map[int32]string{
+ 0: "LOGIN_ATTEMPT_KIND_UNSPECIFIED",
+ 1: "PASSWORD",
+ 2: "EMAIL_CODE",
+ 3: "MFA",
+ }
+ LoginAttemptKind_value = map[string]int32{
+ "LOGIN_ATTEMPT_KIND_UNSPECIFIED": 0,
+ "PASSWORD": 1,
+ "EMAIL_CODE": 2,
+ "MFA": 3,
+ }
+)
+
+func (x LoginAttemptKind) Enum() *LoginAttemptKind {
+ p := new(LoginAttemptKind)
+ *p = x
+ return p
+}
+
+func (x LoginAttemptKind) String() string {
+ return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))
+}
+
+func (LoginAttemptKind) Descriptor() protoreflect.EnumDescriptor {
+ return file_store_auth_proto_enumTypes[1].Descriptor()
+}
+
+func (LoginAttemptKind) Type() protoreflect.EnumType {
+ return &file_store_auth_proto_enumTypes[1]
+}
+
+func (x LoginAttemptKind) Number() protoreflect.EnumNumber {
+ return protoreflect.EnumNumber(x)
+}
+
+// Deprecated: Use LoginAttemptKind.Descriptor instead.
+func (LoginAttemptKind) EnumDescriptor() ([]byte, []int) {
+ return file_store_auth_proto_rawDescGZIP(), []int{1}
+}
+
var File_store_auth_proto protoreflect.FileDescriptor
const file_store_auth_proto_rawDesc = "" +
@@ -80,7 +134,13 @@ const file_store_auth_proto_rawDesc = "" +
"\x1cEmailVerificationCodePurpose\x12/\n" +
"+EMAIL_VERIFICATION_CODE_PURPOSE_UNSPECIFIED\x10\x00\x12\t\n" +
"\x05LOGIN\x10\x01\x12\x12\n" +
- "\x0ePASSWORD_RESET\x10\x02B\x8c\x01\n" +
+ "\x0ePASSWORD_RESET\x10\x02*]\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" +
"\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 (
@@ -95,9 +155,10 @@ func file_store_auth_proto_rawDescGZIP() []byte {
return file_store_auth_proto_rawDescData
}
-var file_store_auth_proto_enumTypes = make([]protoimpl.EnumInfo, 1)
+var file_store_auth_proto_enumTypes = make([]protoimpl.EnumInfo, 2)
var file_store_auth_proto_goTypes = []any{
(EmailVerificationCodePurpose)(0), // 0: bytebase.store.EmailVerificationCodePurpose
+ (LoginAttemptKind)(0), // 1: bytebase.store.LoginAttemptKind
}
var file_store_auth_proto_depIdxs = []int32{
0, // [0:0] is the sub-list for method output_type
@@ -117,7 +178,7 @@ func file_store_auth_proto_init() {
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_store_auth_proto_rawDesc), len(file_store_auth_proto_rawDesc)),
- NumEnums: 1,
+ NumEnums: 2,
NumMessages: 0,
NumExtensions: 0,
NumServices: 0,
diff --git a/backend/generated-go/v1/auth_service.pb.go b/backend/generated-go/v1/auth_service.pb.go
index 59102529fe..781aa3f2f3 100644
--- a/backend/generated-go/v1/auth_service.pb.go
+++ b/backend/generated-go/v1/auth_service.pb.go
@@ -7,6 +7,7 @@
package v1
import (
+ _ "buf.build/gen/go/bufbuild/protovalidate/protocolbuffers/go/buf/validate"
_ "google.golang.org/genproto/googleapis/api/annotations"
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
@@ -211,8 +212,12 @@ func (x *Restriction) GetPasswordResetEnabled() bool {
type LoginRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
// User's email address.
+ // Bounded so an oversized identity is refused at the edge before any
+ // handler runs; the login-attempt lockout keys rows by this value.
Email string `protobuf:"bytes,1,opt,name=email,proto3" json:"email,omitempty"`
- // User's password for authentication.
+ // User's password for authentication. Bounded for abuse only: LDAP
+ // directories may accept passwords beyond bcrypt's 72-byte limit, and the
+ // local-password path rejects longer inputs itself.
Password string `protobuf:"bytes,2,opt,name=password,proto3" json:"password,omitempty"`
// If true, sets access token and refresh token as HTTP-only cookies instead of
// returning the token in the response body. Use for browser-based clients.
@@ -731,6 +736,8 @@ func (x *ExchangeTokenResponse) GetAccessToken() string {
type SignupRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
// The email for the new account.
+ // Bounded so an oversized identity is refused at the edge before any
+ // handler runs; the login-attempt lockout keys rows by this value.
Email string `protobuf:"bytes,1,opt,name=email,proto3" json:"email,omitempty"`
// The password for the new account.
Password string `protobuf:"bytes,2,opt,name=password,proto3" json:"password,omitempty"`
@@ -868,6 +875,8 @@ func (*RefreshResponse) Descriptor() ([]byte, []int) {
type RequestPasswordResetRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
// The email address of the account to reset.
+ // Bounded so an oversized identity is refused at the edge before any
+ // handler runs; the login-attempt lockout keys rows by this value.
Email string `protobuf:"bytes,1,opt,name=email,proto3" json:"email,omitempty"`
// Optional workspace context captured at send time, used to locate the EMAIL setting,
// and later (at verify time) for signup gate checks and workspace assignment.
@@ -925,6 +934,8 @@ func (x *RequestPasswordResetRequest) GetWorkspace() string {
type ResetPasswordRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
// The email address of the account.
+ // Bounded so an oversized identity is refused at the edge before any
+ // handler runs; the login-attempt lockout keys rows by this value.
Email string `protobuf:"bytes,1,opt,name=email,proto3" json:"email,omitempty"`
// The 6-digit code from the reset email.
Code string `protobuf:"bytes,2,opt,name=code,proto3" json:"code,omitempty"`
@@ -988,6 +999,8 @@ func (x *ResetPasswordRequest) GetNewPassword() string {
type SendEmailLoginCodeRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
// The email address to send the code to.
+ // Bounded so an oversized identity is refused at the edge before any
+ // handler runs; the login-attempt lockout keys rows by this value.
Email string `protobuf:"bytes,1,opt,name=email,proto3" json:"email,omitempty"`
// Optional workspace context captured at send time, used to locate the EMAIL setting,
// and later (at verify time) for signup gate checks and workspace assignment.
@@ -1128,7 +1141,7 @@ var File_v1_auth_service_proto protoreflect.FileDescriptor
const file_v1_auth_service_proto_rawDesc = "" +
"\n" +
- "\x15v1/auth_service.proto\x12\vbytebase.v1\x1a\x1cgoogle/api/annotations.proto\x1a\x17google/api/client.proto\x1a\x1fgoogle/api/field_behavior.proto\x1a\x19google/api/resource.proto\x1a\x1bgoogle/protobuf/empty.proto\x1a\x13v1/annotation.proto\x1a\x18v1/setting_service.proto\x1a\x15v1/user_service.proto\"`\n" +
+ "\x15v1/auth_service.proto\x12\vbytebase.v1\x1a\x1bbuf/validate/validate.proto\x1a\x1cgoogle/api/annotations.proto\x1a\x17google/api/client.proto\x1a\x1fgoogle/api/field_behavior.proto\x1a\x19google/api/resource.proto\x1a\x1bgoogle/protobuf/empty.proto\x1a\x13v1/annotation.proto\x1a\x18v1/setting_service.proto\x1a\x15v1/user_service.proto\"`\n" +
"#GetAuthenticationRestrictionRequest\x129\n" +
"\tworkspace\x18\x01 \x01(\tB\x1b\xfaA\x18\n" +
"\x16bytebase.com/WorkspaceR\tworkspace\"x\n" +
@@ -1140,21 +1153,21 @@ const file_v1_auth_service_proto_rawDesc = "" +
"\x18disallow_password_signin\x18\x02 \x01(\bB\x03\xe0A\x03R\x16disallowPasswordSignin\x12p\n" +
"\x14password_restriction\x18\x03 \x01(\v28.bytebase.v1.WorkspaceProfileSetting.PasswordRestrictionB\x03\xe0A\x03R\x13passwordRestriction\x12:\n" +
"\x17allow_email_code_signin\x18\x04 \x01(\bB\x03\xe0A\x03R\x14allowEmailCodeSignin\x129\n" +
- "\x16password_reset_enabled\x18\x05 \x01(\bB\x03\xe0A\x03R\x14passwordResetEnabled\"\xdd\x03\n" +
- "\fLoginRequest\x12\x14\n" +
- "\x05email\x18\x01 \x01(\tR\x05email\x12 \n" +
- "\bpassword\x18\x02 \x01(\tB\x04\xd0\xea0\x01R\bpassword\x12\x10\n" +
- "\x03web\x18\x03 \x01(\bR\x03web\x12\x19\n" +
- "\bidp_name\x18\x04 \x01(\tR\aidpName\x12E\n" +
+ "\x16password_reset_enabled\x18\x05 \x01(\bB\x03\xe0A\x03R\x14passwordResetEnabled\"\xa0\x04\n" +
+ "\fLoginRequest\x12\x1e\n" +
+ "\x05email\x18\x01 \x01(\tB\b\xbaH\x05r\x03\x18\xfe\x01R\x05email\x12(\n" +
+ "\bpassword\x18\x02 \x01(\tB\f\xbaH\x05r\x03(\x80\x04\xd0\xea0\x01R\bpassword\x12\x10\n" +
+ "\x03web\x18\x03 \x01(\bR\x03web\x12#\n" +
+ "\bidp_name\x18\x04 \x01(\tB\b\xbaH\x05r\x03\x18\x80\x02R\aidpName\x12E\n" +
"\vidp_context\x18\x05 \x01(\v2$.bytebase.v1.IdentityProviderContextR\n" +
- "idpContext\x12$\n" +
- "\botp_code\x18\x06 \x01(\tB\x04\xd0\xea0\x01H\x00R\aotpCode\x88\x01\x01\x12.\n" +
- "\rrecovery_code\x18\a \x01(\tB\x04\xd0\xea0\x01H\x01R\frecoveryCode\x88\x01\x01\x12/\n" +
- "\x0emfa_temp_token\x18\b \x01(\tB\x04\xd0\xea0\x01H\x02R\fmfaTempToken\x88\x01\x01\x12(\n" +
+ "idpContext\x12+\n" +
+ "\botp_code\x18\x06 \x01(\tB\v\xbaH\x04r\x02\x18@\xd0\xea0\x01H\x00R\aotpCode\x88\x01\x01\x125\n" +
+ "\rrecovery_code\x18\a \x01(\tB\v\xbaH\x04r\x02\x18@\xd0\xea0\x01H\x01R\frecoveryCode\x88\x01\x01\x127\n" +
+ "\x0emfa_temp_token\x18\b \x01(\tB\f\xbaH\x05r\x03\x18\x80 \xd0\xea0\x01H\x02R\fmfaTempToken\x88\x01\x01\x12/\n" +
"\n" +
- "email_code\x18\t \x01(\tB\x04\xd0\xea0\x01H\x03R\temailCode\x88\x01\x01\x12!\n" +
+ "email_code\x18\t \x01(\tB\v\xbaH\x04r\x02\x18@\xd0\xea0\x01H\x03R\temailCode\x88\x01\x01\x12+\n" +
"\tworkspace\x18\n" +
- " \x01(\tH\x04R\tworkspace\x88\x01\x01B\v\n" +
+ " \x01(\tB\b\xbaH\x05r\x03\x18\x80\x02H\x04R\tworkspace\x88\x01\x01B\v\n" +
"\t_otp_codeB\x10\n" +
"\x0e_recovery_codeB\x11\n" +
"\x0f_mfa_temp_tokenB\r\n" +
@@ -1164,49 +1177,49 @@ const file_v1_auth_service_proto_rawDesc = "" +
"\x17IdentityProviderContext\x12S\n" +
"\x0eoauth2_context\x18\x01 \x01(\v2*.bytebase.v1.OAuth2IdentityProviderContextH\x00R\roauth2Context\x12M\n" +
"\foidc_context\x18\x02 \x01(\v2(.bytebase.v1.OIDCIdentityProviderContextH\x00R\voidcContextB\t\n" +
- "\acontext\"9\n" +
- "\x1dOAuth2IdentityProviderContext\x12\x18\n" +
- "\x04code\x18\x01 \x01(\tB\x04\xd0\xea0\x01R\x04code\"7\n" +
- "\x1bOIDCIdentityProviderContext\x12\x18\n" +
- "\x04code\x18\x01 \x01(\tB\x04\xd0\xea0\x01R\x04code\"\xcc\x01\n" +
+ "\acontext\"A\n" +
+ "\x1dOAuth2IdentityProviderContext\x12 \n" +
+ "\x04code\x18\x01 \x01(\tB\f\xbaH\x05r\x03\x18\x80 \xd0\xea0\x01R\x04code\"?\n" +
+ "\x1bOIDCIdentityProviderContext\x12 \n" +
+ "\x04code\x18\x01 \x01(\tB\f\xbaH\x05r\x03\x18\x80 \xd0\xea0\x01R\x04code\"\xcc\x01\n" +
"\rLoginResponse\x12\x1a\n" +
"\x05token\x18\x01 \x01(\tB\x04\xd0\xea0\x01R\x05token\x12/\n" +
"\x0emfa_temp_token\x18\x02 \x01(\tB\x04\xd0\xea0\x01H\x00R\fmfaTempToken\x88\x01\x01\x124\n" +
"\x16require_reset_password\x18\x03 \x01(\bR\x14requireResetPassword\x12%\n" +
"\x04user\x18\x04 \x01(\v2\x11.bytebase.v1.UserR\x04userB\x11\n" +
"\x0f_mfa_temp_token\"\x0f\n" +
- "\rLogoutRequest\"H\n" +
- "\x14ExchangeTokenRequest\x12\x1a\n" +
- "\x05token\x18\x01 \x01(\tB\x04\xd0\xea0\x01R\x05token\x12\x14\n" +
- "\x05email\x18\x02 \x01(\tR\x05email\"@\n" +
+ "\rLogoutRequest\"[\n" +
+ "\x14ExchangeTokenRequest\x12#\n" +
+ "\x05token\x18\x01 \x01(\tB\r\xbaH\x06r\x04\x18\x80\x80\x04\xd0\xea0\x01R\x05token\x12\x1e\n" +
+ "\x05email\x18\x02 \x01(\tB\b\xbaH\x05r\x03\x18\xfe\x01R\x05email\"@\n" +
"\x15ExchangeTokenResponse\x12'\n" +
- "\faccess_token\x18\x01 \x01(\tB\x04\xd0\xea0\x01R\vaccessToken\"]\n" +
- "\rSignupRequest\x12\x14\n" +
- "\x05email\x18\x01 \x01(\tR\x05email\x12 \n" +
- "\bpassword\x18\x02 \x01(\tB\x04\xd0\xea0\x01R\bpassword\x12\x14\n" +
- "\x05title\x18\x03 \x01(\tR\x05title\"\x10\n" +
+ "\faccess_token\x18\x01 \x01(\tB\x04\xd0\xea0\x01R\vaccessToken\"x\n" +
+ "\rSignupRequest\x12\x1e\n" +
+ "\x05email\x18\x01 \x01(\tB\b\xbaH\x05r\x03\x18\xfe\x01R\x05email\x12'\n" +
+ "\bpassword\x18\x02 \x01(\tB\v\xbaH\x04r\x02(H\xd0\xea0\x01R\bpassword\x12\x1e\n" +
+ "\x05title\x18\x03 \x01(\tB\b\xbaH\x05r\x03\x18\xc8\x01R\x05title\"\x10\n" +
"\x0eRefreshRequest\"\x11\n" +
- "\x0fRefreshResponse\"d\n" +
- "\x1bRequestPasswordResetRequest\x12\x14\n" +
- "\x05email\x18\x01 \x01(\tR\x05email\x12!\n" +
- "\tworkspace\x18\x02 \x01(\tH\x00R\tworkspace\x88\x01\x01B\f\n" +
+ "\x0fRefreshResponse\"x\n" +
+ "\x1bRequestPasswordResetRequest\x12\x1e\n" +
+ "\x05email\x18\x01 \x01(\tB\b\xbaH\x05r\x03\x18\xfe\x01R\x05email\x12+\n" +
+ "\tworkspace\x18\x02 \x01(\tB\b\xbaH\x05r\x03\x18\x80\x02H\x00R\tworkspace\x88\x01\x01B\f\n" +
"\n" +
- "_workspace\"o\n" +
- "\x14ResetPasswordRequest\x12\x14\n" +
- "\x05email\x18\x01 \x01(\tR\x05email\x12\x18\n" +
- "\x04code\x18\x02 \x01(\tB\x04\xd0\xea0\x01R\x04code\x12'\n" +
- "\fnew_password\x18\x03 \x01(\tB\x04\xd0\xea0\x01R\vnewPassword\"b\n" +
- "\x19SendEmailLoginCodeRequest\x12\x14\n" +
- "\x05email\x18\x01 \x01(\tR\x05email\x12!\n" +
- "\tworkspace\x18\x02 \x01(\tH\x00R\tworkspace\x88\x01\x01B\f\n" +
+ "_workspace\"\x87\x01\n" +
+ "\x14ResetPasswordRequest\x12\x1e\n" +
+ "\x05email\x18\x01 \x01(\tB\b\xbaH\x05r\x03\x18\xfe\x01R\x05email\x12\x1f\n" +
+ "\x04code\x18\x02 \x01(\tB\v\xbaH\x04r\x02\x18@\xd0\xea0\x01R\x04code\x12.\n" +
+ "\fnew_password\x18\x03 \x01(\tB\v\xbaH\x04r\x02(H\xd0\xea0\x01R\vnewPassword\"v\n" +
+ "\x19SendEmailLoginCodeRequest\x12\x1e\n" +
+ "\x05email\x18\x01 \x01(\tB\b\xbaH\x05r\x03\x18\xfe\x01R\x05email\x12+\n" +
+ "\tworkspace\x18\x02 \x01(\tB\b\xbaH\x05r\x03\x18\x80\x02H\x00R\tworkspace\x88\x01\x01B\f\n" +
"\n" +
- "_workspace\"\x81\x02\n" +
- "\x16SwitchWorkspaceRequest\x12\x1c\n" +
- "\tworkspace\x18\x01 \x01(\tR\tworkspace\x12\x10\n" +
- "\x03web\x18\x02 \x01(\bR\x03web\x12$\n" +
- "\botp_code\x18\x03 \x01(\tB\x04\xd0\xea0\x01H\x00R\aotpCode\x88\x01\x01\x12.\n" +
- "\rrecovery_code\x18\x04 \x01(\tB\x04\xd0\xea0\x01H\x01R\frecoveryCode\x88\x01\x01\x12/\n" +
- "\x0emfa_temp_token\x18\x05 \x01(\tB\x04\xd0\xea0\x01H\x02R\fmfaTempToken\x88\x01\x01B\v\n" +
+ "_workspace\"\xa1\x02\n" +
+ "\x16SwitchWorkspaceRequest\x12&\n" +
+ "\tworkspace\x18\x01 \x01(\tB\b\xbaH\x05r\x03\x18\x80\x02R\tworkspace\x12\x10\n" +
+ "\x03web\x18\x02 \x01(\bR\x03web\x12+\n" +
+ "\botp_code\x18\x03 \x01(\tB\v\xbaH\x04r\x02\x18@\xd0\xea0\x01H\x00R\aotpCode\x88\x01\x01\x125\n" +
+ "\rrecovery_code\x18\x04 \x01(\tB\v\xbaH\x04r\x02\x18@\xd0\xea0\x01H\x01R\frecoveryCode\x88\x01\x01\x127\n" +
+ "\x0emfa_temp_token\x18\x05 \x01(\tB\f\xbaH\x05r\x03\x18\x80 \xd0\xea0\x01H\x02R\fmfaTempToken\x88\x01\x01B\v\n" +
"\t_otp_codeB\x10\n" +
"\x0e_recovery_codeB\x11\n" +
"\x0f_mfa_temp_token2\xc2\n" +
diff --git a/backend/generated-go/v1/user_service.pb.go b/backend/generated-go/v1/user_service.pb.go
index 4f8fb5efd4..759d27f84d 100644
--- a/backend/generated-go/v1/user_service.pb.go
+++ b/backend/generated-go/v1/user_service.pb.go
@@ -861,17 +861,17 @@ const file_v1_user_service_proto_rawDesc = "" +
"\x11bytebase.com/UserR\x04name\"D\n" +
"\x13UndeleteUserRequest\x12-\n" +
"\x04name\x18\x01 \x01(\tB\x19\xe0A\x02\xfaA\x13\n" +
- "\x11bytebase.com/UserR\x04name\"^\n" +
+ "\x11bytebase.com/UserR\x04name\"f\n" +
"\x12UpdateEmailRequest\x12-\n" +
"\x04name\x18\x01 \x01(\tB\x19\xe0A\x02\xfaA\x13\n" +
- "\x11bytebase.com/UserR\x04name\x12\x19\n" +
- "\x05email\x18\x02 \x01(\tB\x03\xe0A\x02R\x05email\"\x98\x06\n" +
+ "\x11bytebase.com/UserR\x04name\x12!\n" +
+ "\x05email\x18\x02 \x01(\tB\v\xe0A\x02\xbaH\x05r\x03\x18\xfe\x01R\x05email\"\xa9\x06\n" +
"\x04User\x12\x17\n" +
"\x04name\x18\x01 \x01(\tB\x03\xe0A\x03R\x04name\x12(\n" +
- "\x05state\x18\x02 \x01(\x0e2\x12.bytebase.v1.StateR\x05state\x12\x14\n" +
- "\x05email\x18\x03 \x01(\tR\x05email\x12\x1e\n" +
- "\x05title\x18\x04 \x01(\tB\b\xbaH\x05r\x03\x18\xc8\x01R\x05title\x12#\n" +
- "\bpassword\x18\x06 \x01(\tB\a\xe0A\x04\xd0\xea0\x01R\bpassword\x12\x1f\n" +
+ "\x05state\x18\x02 \x01(\x0e2\x12.bytebase.v1.StateR\x05state\x12\x1e\n" +
+ "\x05email\x18\x03 \x01(\tB\b\xbaH\x05r\x03\x18\xfe\x01R\x05email\x12\x1e\n" +
+ "\x05title\x18\x04 \x01(\tB\b\xbaH\x05r\x03\x18\xc8\x01R\x05title\x12*\n" +
+ "\bpassword\x18\x06 \x01(\tB\x0e\xe0A\x04\xbaH\x04r\x02(H\xd0\xea0\x01R\bpassword\x12\x1f\n" +
"\vmfa_enabled\x18\b \x01(\bR\n" +
"mfaEnabled\x12,\n" +
"\x0ftemp_otp_secret\x18\t \x01(\tB\x04\xd0\xea0\x01R\rtempOtpSecret\x124\n" +
diff --git a/backend/migrator/migration/3.22/0012##login_attempt.sql b/backend/migrator/migration/3.22/0012##login_attempt.sql
new file mode 100644
index 0000000000..610e1ecba9
--- /dev/null
+++ b/backend/migrator/migration/3.22/0012##login_attempt.sql
@@ -0,0 +1,27 @@
+-- One table gives every credential — password, emailed code, second factor — an attempt
+-- limit keyed on the identity under attack (docs/design/login-attempt-lockout.md). It
+-- replaces the audit-log lockout counters and the per-code attempts column.
+-- One row per (identity, kind): attempts since the last success, and when the latest was.
+CREATE TABLE login_attempt (
+ -- The identity under attack, server-resolved and globally unique: the normalized
+ -- email, or the identity-provider ID joined with the submitted username for LDAP.
+ -- Not a FK, so unknown identities count too (no existence oracle).
+ identity text NOT NULL,
+ -- Stored as LoginAttemptKind enum name (proto/store/store/auth.proto):
+ -- PASSWORD | EMAIL_CODE | MFA.
+ kind text NOT NULL,
+ attempts int NOT NULL,
+ last_attempt_at timestamptz NOT NULL,
+ PRIMARY KEY (identity, kind)
+);
+
+CREATE INDEX idx_login_attempt_last_attempt_at ON login_attempt (last_attempt_at);
+
+-- The per-code attempt counter is replaced by the EMAIL_CODE lockout above. The code row
+-- now lives until it expires or is consumed, so the resend cooldown always has a row to
+-- evaluate: the delete-on-exhaustion cooldown bypass is closed structurally.
+ALTER TABLE email_verification_code DROP COLUMN attempts;
+
+-- Verify never reads a caller-supplied workspace; the password policy and audit
+-- workspace come from what the server knows about the email at verify time.
+ALTER TABLE email_verification_code DROP COLUMN workspace;
diff --git a/backend/migrator/migration/LATEST.sql b/backend/migrator/migration/LATEST.sql
index 56efa99385..fb178c980d 100644
--- a/backend/migrator/migration/LATEST.sql
+++ b/backend/migrator/migration/LATEST.sql
@@ -723,21 +723,33 @@ CREATE INDEX idx_web_refresh_token_expires_at ON web_refresh_token(expires_at);
CREATE TABLE email_verification_code (
email text NOT NULL,
- -- Stored as EmailVerificationCodePurpose enum name (proto/store/store/email_verification_code.proto)
+ -- Stored as EmailVerificationCodePurpose enum name (proto/store/store/auth.proto)
purpose text NOT NULL,
code_hash text NOT NULL,
- attempts int NOT NULL DEFAULT 0,
expires_at timestamptz NOT NULL,
last_sent_at timestamptz NOT NULL,
- -- Workspace context captured at send time. Used at verify time for gate checks
- -- (disallow_signup, allow_email_code_signin) and for provisionWorkspaceForNewUser.
- -- NULL for SaaS brand-new signup (no workspace exists yet — provision creates one).
- workspace text,
PRIMARY KEY (email, purpose)
);
CREATE INDEX idx_email_verification_code_expires_at ON email_verification_code (expires_at);
+-- Attempt limits for guessable login credentials (docs/design/login-attempt-lockout.md).
+-- One row per (identity, kind): attempts since the last success, and when the latest was.
+CREATE TABLE login_attempt (
+ -- The identity under attack, server-resolved and globally unique: the normalized
+ -- email, or the identity-provider ID joined with the submitted username for LDAP.
+ -- Not a FK, so unknown identities count too (no existence oracle).
+ identity text NOT NULL,
+ -- Stored as LoginAttemptKind enum name (proto/store/store/auth.proto):
+ -- PASSWORD | EMAIL_CODE | MFA.
+ kind text NOT NULL,
+ attempts int NOT NULL,
+ last_attempt_at timestamptz NOT NULL,
+ PRIMARY KEY (identity, kind)
+);
+
+CREATE INDEX idx_login_attempt_last_attempt_at ON login_attempt (last_attempt_at);
+
-----------------------
-- Seed data
-----------------------
diff --git a/backend/migrator/migrator_test.go b/backend/migrator/migrator_test.go
index 15b7aef266..e5f5b588c7 100644
--- a/backend/migrator/migrator_test.go
+++ b/backend/migrator/migrator_test.go
@@ -21,8 +21,8 @@ import (
func TestLatestVersion(t *testing.T) {
files, err := getSortedVersionedFiles()
require.NoError(t, err)
- require.Equal(t, semver.MustParse("3.22.11"), *files[len(files)-1].version)
- require.Equal(t, "migration/3.22/0011##sample_project_instance.sql", files[len(files)-1].path)
+ require.Equal(t, semver.MustParse("3.22.12"), *files[len(files)-1].version)
+ require.Equal(t, "migration/3.22/0012##login_attempt.sql", files[len(files)-1].path)
}
func TestVersionUnique(t *testing.T) {
diff --git a/backend/plugin/idp/ldap/ldap.go b/backend/plugin/idp/ldap/ldap.go
index cffb36a16b..cd5cb627ff 100644
--- a/backend/plugin/idp/ldap/ldap.go
+++ b/backend/plugin/idp/ldap/ldap.go
@@ -15,6 +15,12 @@ import (
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
)
+// ErrInvalidCredentials marks an authentication failure caused by the submitted
+// username or password — the user filter matched no one, or the directory
+// rejected the bind — as opposed to connectivity or configuration failures.
+// Callers surface it as Unauthenticated rather than Internal.
+var ErrInvalidCredentials = errors.New("invalid credentials")
+
// IdentityProvider represents an LDAP Identity Provider.
type IdentityProvider struct {
config IdentityProviderConfig
@@ -188,7 +194,7 @@ func (p *IdentityProvider) searchAndBind(username, password string, attributes [
slog.String("hint", "filter may be too restrictive or user does not exist in the directory"),
)
// Return generic error to prevent information disclosure
- return nil, errors.New("invalid credentials")
+ return nil, ErrInvalidCredentials
} else if len(sr.Entries) > 1 {
// Log detailed information for admin troubleshooting
slog.Error("LDAP authentication failed: user filter matched multiple users",
@@ -206,11 +212,28 @@ func (p *IdentityProvider) searchAndBind(username, password string, attributes [
// Bind as the user to verify their password
err = conn.Bind(entry.DN, password)
if err != nil {
- return nil, errors.Errorf("bind user: %v", err)
+ return nil, bindError(err)
}
return entry, nil
}
+// bindError classifies a failed bind: a credential the directory rejected
+// becomes ErrInvalidCredentials, anything else stays a generic server error.
+// The directory's own diagnostic is logged and kept in the message — AD's
+// result 49 sub-codes distinguish a wrong password (data 52e) from an
+// expired (532), disabled (533), or locked (775) account, which login hides
+// behind a generic 401 but the admin test-sign-in flow and operators need.
+func bindError(err error) error {
+ if ldap.IsErrorWithCode(err, ldap.LDAPResultInvalidCredentials) {
+ slog.Warn("LDAP authentication failed: bind rejected",
+ slog.String("hint", "wrong password, or an expired/disabled/locked directory account — see the result data code"),
+ slog.String("error", err.Error()),
+ )
+ return errors.Wrapf(ErrInvalidCredentials, "bind user: %v", err)
+ }
+ return errors.Errorf("bind user: %v", err)
+}
+
// mappedAttributes returns the attributes to request for the configured field
// mapping, skipping unset mappings: LDAP servers only return explicitly
// requested attributes.
diff --git a/backend/plugin/idp/ldap/ldap_test.go b/backend/plugin/idp/ldap/ldap_test.go
index 76d495027a..0edf14bc0e 100644
--- a/backend/plugin/idp/ldap/ldap_test.go
+++ b/backend/plugin/idp/ldap/ldap_test.go
@@ -8,6 +8,7 @@ import (
goldap "github.com/go-ldap/ldap/v3"
"github.com/lor00x/goldap/message"
+ "github.com/pkg/errors"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/vjeantet/ldapserver"
@@ -340,3 +341,18 @@ func TestEntryAttributes(t *testing.T) {
"jpegPhoto": "<binary>",
}, entryAttributes(entry))
}
+
+// TestBindErrorClassification pins the 401-vs-500 split for failed binds: a
+// credential the directory rejected must surface as ErrInvalidCredentials so
+// login answers Unauthenticated (and edge rate rules counting 401s see it),
+// while connectivity and configuration failures stay generic server errors.
+func TestBindErrorClassification(t *testing.T) {
+ rejected := bindError(goldap.NewError(goldap.LDAPResultInvalidCredentials, errors.New("80090308: LdapErr: DSID-0C09044E, data 532")))
+ require.ErrorIs(t, rejected, ErrInvalidCredentials)
+ require.ErrorContains(t, rejected, "data 532",
+ "the directory's sub-code (expired/disabled/locked vs wrong password) must survive into the admin test-sign-in response")
+
+ unavailable := bindError(goldap.NewError(goldap.LDAPResultUnavailable, errors.New("directory unavailable")))
+ require.NotErrorIs(t, unavailable, ErrInvalidCredentials)
+ require.ErrorContains(t, unavailable, "bind user")
+}
diff --git a/backend/runner/cleaner/data_cleaner.go b/backend/runner/cleaner/data_cleaner.go
index 087c6231f0..c8c48105d6 100644
--- a/backend/runner/cleaner/data_cleaner.go
+++ b/backend/runner/cleaner/data_cleaner.go
@@ -18,6 +18,11 @@ const (
planCheckRunTimeout = 10 * time.Minute
heartbeatRetentionPeriod = 1 * time.Hour
oauth2ClientRetentionPeriod = 30 * 24 * time.Hour // 30 days of inactivity
+ // LoginAttemptRetentionPeriod must exceed every lockout window, or the
+ // purge would delete still-running locks. Exported so the auth service's
+ // TestLoginAttemptRetentionOutlivesLockouts can assert the coupling; the
+ // longest window today is ten minutes, so rows idle for an hour are dead.
+ LoginAttemptRetentionPeriod = 1 * time.Hour
)
// DataCleaner periodically cleans up expired data from the database.
@@ -78,6 +83,7 @@ func (c *DataCleaner) cleanup(ctx context.Context) {
c.cleanupOAuth2Data(ctx)
c.cleanupWebRefreshTokens(ctx)
c.cleanupEmailVerificationCodes(ctx)
+ c.cleanupLoginAttempts(ctx)
c.cleanupStaleHeartbeats(ctx)
c.cleanupExpiredVCSProviderUsers(ctx)
}
@@ -158,6 +164,14 @@ func (c *DataCleaner) cleanupWebRefreshTokens(ctx context.Context) {
}
}
+func (c *DataCleaner) cleanupLoginAttempts(ctx context.Context) {
+ if rowsAffected, err := c.store.DeleteStaleLoginAttempts(ctx, LoginAttemptRetentionPeriod); err != nil {
+ slog.Error("Failed to clean up stale login attempts", log.BBError(err))
+ } else if rowsAffected > 0 {
+ slog.Info("Cleaned up stale login attempts", slog.Int64("count", rowsAffected))
+ }
+}
+
func (c *DataCleaner) cleanupEmailVerificationCodes(ctx context.Context) {
if rowsAffected, err := c.store.DeleteExpiredEmailVerificationCodes(ctx); err != nil {
slog.Error("Failed to clean up expired email verification codes", log.BBError(err))
diff --git a/backend/server/validate_interceptor_test.go b/backend/server/validate_interceptor_test.go
index 90e988bdb1..ee5abc746d 100644
--- a/backend/server/validate_interceptor_test.go
+++ b/backend/server/validate_interceptor_test.go
@@ -1,9 +1,11 @@
package server
import (
+ "strings"
"testing"
"buf.build/go/protovalidate"
+ "google.golang.org/protobuf/proto"
v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"
)
@@ -27,3 +29,82 @@ func TestProtovalidateStandardRules(t *testing.T) {
t.Fatal("expected string.max_len violation for a 201-byte title, got nil")
}
}
+
+// TestAuthEmailFieldsAreLengthBounded pins the edge half of the login-attempt
+// identity bound (docs/design/login-attempt-lockout.md): every auth request
+// field that becomes a lockout identity carries string.max_len = 254, so
+// oversized identities are refused by the validate interceptor before any
+// handler runs. The service still bounds server-composed identities (LDAP,
+// MFA temp token) in claimLoginAttempt.
+func TestAuthEmailFieldsAreLengthBounded(t *testing.T) {
+ v, err := protovalidate.New()
+ if err != nil {
+ t.Fatalf("protovalidate.New: %v", err)
+ }
+ longEmail := strings.Repeat("a", 243) + "@example.com" // 255 chars
+ okEmail := strings.Repeat("a", 242) + "@example.com" // 254 chars
+ for _, msg := range []interface {
+ proto.Message
+ }{
+ &v1pb.LoginRequest{Email: longEmail},
+ &v1pb.SignupRequest{Email: longEmail},
+ &v1pb.RequestPasswordResetRequest{Email: longEmail},
+ &v1pb.ResetPasswordRequest{Email: longEmail},
+ &v1pb.SendEmailLoginCodeRequest{Email: longEmail},
+ } {
+ if err := v.Validate(msg); err == nil {
+ t.Errorf("expected string.max_len violation for 255-char email on %T, got nil", msg)
+ }
+ }
+ if err := v.Validate(&v1pb.LoginRequest{Email: okEmail}); err != nil {
+ t.Errorf("a 254-char email must pass: %v", err)
+ }
+}
+
+// TestAuthRequestFieldsAreSizeBounded pins the size bounds on the remaining
+// auth request strings: passwords at bcrypt's 72-byte hard limit, submitted
+// codes at 64 chars, server-minted and IdP-issued tokens at generous caps, and
+// resource names at 256 — so no unauthenticated request can push an oversized
+// value into hashing, comparison, or lockout bookkeeping.
+func TestAuthRequestFieldsAreSizeBounded(t *testing.T) {
+ v, err := protovalidate.New()
+ if err != nil {
+ t.Fatalf("protovalidate.New: %v", err)
+ }
+ long := func(n int) string { return strings.Repeat("a", n) }
+ for _, tc := range []struct {
+ name string
+ msg proto.Message
+ }{
+ {"login password over the LDAP-tolerant 512 bytes", &v1pb.LoginRequest{Password: long(513)}},
+ {"signup password over bcrypt's 72 bytes", &v1pb.SignupRequest{Password: long(73)}},
+ {"reset new_password over bcrypt's 72 bytes", &v1pb.ResetPasswordRequest{NewPassword: long(73)}},
+ {"signup title over 200", &v1pb.SignupRequest{Title: long(201)}},
+ {"otp code over 64", &v1pb.LoginRequest{OtpCode: ptrOf(long(65))}},
+ {"email code over 64", &v1pb.LoginRequest{EmailCode: ptrOf(long(65))}},
+ {"reset code over 64", &v1pb.ResetPasswordRequest{Code: long(65)}},
+ {"switch recovery code over 64", &v1pb.SwitchWorkspaceRequest{RecoveryCode: ptrOf(long(65))}},
+ {"mfa temp token over 4096", &v1pb.SwitchWorkspaceRequest{MfaTempToken: ptrOf(long(4097))}},
+ {"login workspace over 256", &v1pb.LoginRequest{Workspace: ptrOf(long(257))}},
+ {"idp name over 256", &v1pb.LoginRequest{IdpName: long(257)}},
+ {"exchange token over 64KiB", &v1pb.ExchangeTokenRequest{Token: long(65537)}},
+ {"exchange email over 254", &v1pb.ExchangeTokenRequest{Email: long(255)}},
+ {"user email over 254", &v1pb.User{Email: long(255)}},
+ {"user password over bcrypt's 72 bytes", &v1pb.User{Password: long(73)}},
+ {"update email over 254", &v1pb.UpdateEmailRequest{Email: long(255)}},
+ } {
+ if err := v.Validate(tc.msg); err == nil {
+ t.Errorf("expected size violation for %s, got nil", tc.name)
+ }
+ }
+ // Login tolerates LDAP passwords beyond bcrypt's 72 bytes; the sinks that
+ // bcrypt-hash (signup, reset) cap at exactly 72.
+ if err := v.Validate(&v1pb.LoginRequest{Password: long(512)}); err != nil {
+ t.Errorf("a 512-byte login password must pass: %v", err)
+ }
+ if err := v.Validate(&v1pb.SignupRequest{Password: long(72)}); err != nil {
+ t.Errorf("a 72-byte signup password must pass: %v", err)
+ }
+}
+
+func ptrOf[T any](v T) *T { return &v }
diff --git a/backend/store/email_verification_code.go b/backend/store/email_verification_code.go
index 4068565a2f..c1488b3a2f 100644
--- a/backend/store/email_verification_code.go
+++ b/backend/store/email_verification_code.go
@@ -11,17 +11,16 @@ import (
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
)
-// EmailVerificationCodeMessage represents a row in the email_verification_code table.
+// EmailVerificationCodeMessage represents a row in the email_verification_code table:
+// a code, its expiry, and the resend cooldown. The row lives until it expires or is
+// consumed — wrong guesses are bounded by the per-identity EMAIL_CODE login_attempt
+// lockout, not by per-code state (docs/design/login-attempt-lockout.md).
type EmailVerificationCodeMessage struct {
Email string
Purpose storepb.EmailVerificationCodePurpose
CodeHash string
- Attempts int
ExpiresAt time.Time
LastSentAt time.Time
- // Workspace is the workspace context captured when the code was sent.
- // Empty string means no workspace (SaaS brand-new signup).
- Workspace string
}
// UpsertEmailVerificationCodeIfCooldownExpired inserts or updates the row for (email, purpose),
@@ -34,22 +33,16 @@ type EmailVerificationCodeMessage struct {
// RETURNING is used (not RowsAffected) because Postgres returns unreliable counts
// when the DO UPDATE's WHERE filters out the update.
func (s *Store) UpsertEmailVerificationCodeIfCooldownExpired(ctx context.Context, msg *EmailVerificationCodeMessage, cooldown time.Duration) (bool, error) {
- var workspace sql.NullString
- if msg.Workspace != "" {
- workspace = sql.NullString{String: msg.Workspace, Valid: true}
- }
q := qb.Q().Space(`
- INSERT INTO email_verification_code (email, purpose, code_hash, attempts, expires_at, last_sent_at, workspace)
- VALUES (?, ?, ?, 0, ?, ?, ?)
+ INSERT INTO email_verification_code (email, purpose, code_hash, expires_at, last_sent_at)
+ VALUES (?, ?, ?, ?, ?)
ON CONFLICT (email, purpose) DO UPDATE SET
code_hash = EXCLUDED.code_hash,
- attempts = 0,
expires_at = EXCLUDED.expires_at,
- last_sent_at = EXCLUDED.last_sent_at,
- workspace = EXCLUDED.workspace
+ last_sent_at = EXCLUDED.last_sent_at
WHERE email_verification_code.last_sent_at < EXCLUDED.last_sent_at - make_interval(secs => ?)
RETURNING 1
- `, msg.Email, msg.Purpose.String(), msg.CodeHash, msg.ExpiresAt, msg.LastSentAt, workspace, cooldown.Seconds())
+ `, msg.Email, msg.Purpose.String(), msg.CodeHash, msg.ExpiresAt, msg.LastSentAt, cooldown.Seconds())
query, args, err := q.ToSQL()
if err != nil {
@@ -69,7 +62,7 @@ func (s *Store) UpsertEmailVerificationCodeIfCooldownExpired(ctx context.Context
// or (nil, nil) if no row exists.
func (s *Store) GetEmailVerificationCode(ctx context.Context, email string, purpose storepb.EmailVerificationCodePurpose) (*EmailVerificationCodeMessage, error) {
q := qb.Q().Space(`
- SELECT email, purpose, code_hash, attempts, expires_at, last_sent_at, workspace
+ SELECT email, purpose, code_hash, expires_at, last_sent_at
FROM email_verification_code
WHERE email = ? AND purpose = ?
`, email, purpose.String())
@@ -81,9 +74,8 @@ func (s *Store) GetEmailVerificationCode(ctx context.Context, email string, purp
msg := &EmailVerificationCodeMessage{}
var purposeStr string
- var workspace sql.NullString
if err := s.GetDB().QueryRowContext(ctx, query, args...).Scan(
- &msg.Email, &purposeStr, &msg.CodeHash, &msg.Attempts, &msg.ExpiresAt, &msg.LastSentAt, &workspace,
+ &msg.Email, &purposeStr, &msg.CodeHash, &msg.ExpiresAt, &msg.LastSentAt,
); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, nil
@@ -91,30 +83,9 @@ func (s *Store) GetEmailVerificationCode(ctx context.Context, email string, purp
return nil, errors.Wrap(err, "failed to get email verification code")
}
msg.Purpose = storepb.EmailVerificationCodePurpose(storepb.EmailVerificationCodePurpose_value[purposeStr])
- if workspace.Valid {
- msg.Workspace = workspace.String
- }
return msg, nil
}
-// IncrementEmailVerificationCodeAttempts increments the attempt counter for the given email and purpose.
-func (s *Store) IncrementEmailVerificationCodeAttempts(ctx context.Context, email string, purpose storepb.EmailVerificationCodePurpose) error {
- q := qb.Q().Space(`
- UPDATE email_verification_code
- SET attempts = attempts + 1
- WHERE email = ? AND purpose = ?
- `, email, purpose.String())
-
- query, args, err := q.ToSQL()
- if err != nil {
- return err
- }
- if _, err := s.GetDB().ExecContext(ctx, query, args...); err != nil {
- return errors.Wrap(err, "failed to increment email verification code attempts")
- }
- return nil
-}
-
// DeleteEmailVerificationCodeIfMatch deletes the row only if it still has the given code hash.
// Used to roll back on SMTP failure without wiping a newer code from a concurrent request.
func (s *Store) DeleteEmailVerificationCodeIfMatch(ctx context.Context, email string, purpose storepb.EmailVerificationCodePurpose, codeHash string) error {
diff --git a/backend/store/login_attempt.go b/backend/store/login_attempt.go
new file mode 100644
index 0000000000..6d653f485d
--- /dev/null
+++ b/backend/store/login_attempt.go
@@ -0,0 +1,97 @@
+package store
+
+import (
+ "context"
+ "database/sql"
+ "time"
+
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/common/qb"
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+)
+
+// maxIdentityBytes caps the identity column. The longest legal identity today
+// is an LDAP key: a 63-byte provider ID, ":", and a 254-character
+// proto-bounded username, which is up to 254*4 = 1016 bytes of UTF-8 —
+// 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) {
+ // 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.
+ 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)
+ }
+ q := qb.Q().Space(`
+ INSERT INTO login_attempt (identity, kind, attempts, last_attempt_at)
+ VALUES (?, ?, 1, now())
+ ON CONFLICT (identity, kind) DO UPDATE SET
+ attempts = CASE
+ WHEN login_attempt.last_attempt_at < now() - make_interval(secs => ?) THEN 1
+ ELSE login_attempt.attempts + 1
+ END,
+ last_attempt_at = now()
+ WHERE login_attempt.attempts < ?
+ OR login_attempt.last_attempt_at < now() - make_interval(secs => ?)
+ RETURNING 1
+ `, identity, kind.String(), window.Seconds(), maxAttempts, window.Seconds())
+
+ query, args, err := q.ToSQL()
+ if err != nil {
+ return false, err
+ }
+ var dummy int
+ if 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, errors.Wrap(err, "failed to claim login attempt")
+ }
+ return true, nil
+}
+
+// ClearLoginAttempt forgets the identity's failed attempts after a successful
+// verification by deleting the row. Clearing an unknown identity is a no-op.
+func (s *Store) ClearLoginAttempt(ctx context.Context, identity string, kind storepb.LoginAttemptKind) error {
+ q := qb.Q().Space(`
+ DELETE FROM login_attempt WHERE identity = ? AND kind = ?
+ `, identity, kind.String())
+
+ query, args, err := q.ToSQL()
+ if err != nil {
+ return err
+ }
+ if _, err := s.GetDB().ExecContext(ctx, query, args...); err != nil {
+ return errors.Wrap(err, "failed to clear login attempts")
+ }
+ return nil
+}
+
+// DeleteStaleLoginAttempts deletes rows whose latest attempt is older than
+// retention. Returns the number of deleted rows.
+func (s *Store) DeleteStaleLoginAttempts(ctx context.Context, retention time.Duration) (int64, error) {
+ q := qb.Q().Space(`
+ DELETE FROM login_attempt WHERE last_attempt_at < now() - make_interval(secs => ?)
+ `, retention.Seconds())
+
+ query, args, err := q.ToSQL()
+ if err != nil {
+ return 0, err
+ }
+ result, err := s.GetDB().ExecContext(ctx, query, args...)
+ if err != nil {
+ return 0, errors.Wrap(err, "failed to delete stale login attempts")
+ }
+ return result.RowsAffected()
+}
diff --git a/backend/store/login_attempt_test.go b/backend/store/login_attempt_test.go
new file mode 100644
index 0000000000..add21c446e
--- /dev/null
+++ b/backend/store/login_attempt_test.go
@@ -0,0 +1,206 @@
+package store_test
+
+import (
+ "context"
+ "fmt"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/require"
+
+ "github.com/bytebase/bytebase/backend/common/testcontainer"
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+ "github.com/bytebase/bytebase/backend/migrator"
+ "github.com/bytebase/bytebase/backend/store"
+
+ _ "github.com/bytebase/bytebase/backend/plugin/db/pg"
+)
+
+// TestLoginAttemptClaim verifies the per-identity lockout slots
+// (docs/design/login-attempt-lockout.md): a claim atomically takes one of N
+// attempt slots before the credential is checked, a locked identity claims
+// nothing (so the lock expires exactly D after the Nth attempt), the counter
+// forgets after D of quiet, and success deletes the row.
+func TestLoginAttemptClaim(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 = 10 * time.Minute
+
+ backdate := func(identity string, kind storepb.LoginAttemptKind, by time.Duration) {
+ t.Helper()
+ result, err := db.ExecContext(ctx, `
+ UPDATE login_attempt SET last_attempt_at = last_attempt_at - make_interval(secs => $3)
+ WHERE identity = $1 AND kind = $2
+ `, identity, kind.String(), by.Seconds())
+ require.NoError(t, err)
+ rows, err := result.RowsAffected()
+ require.NoError(t, err)
+ require.EqualValues(t, 1, rows)
+ }
+ lastAttemptAt := func(identity string, kind storepb.LoginAttemptKind) time.Time {
+ t.Helper()
+ var at time.Time
+ require.NoError(t, db.QueryRowContext(ctx, `
+ SELECT last_attempt_at FROM login_attempt WHERE identity = $1 AND kind = $2
+ `, identity, kind.String()).Scan(&at))
+ return at
+ }
+
+ 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)
+ 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)
+ require.NoError(t, err)
+ require.False(t, granted, "claims beyond N must be refused")
+ }
+ })
+
+ 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)
+ 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)
+ require.NoError(t, err)
+ require.False(t, granted)
+ require.Equal(t, lockedAt, lastAttemptAt(identity, storepb.LoginAttemptKind_PASSWORD),
+ "a refused claim must not touch last_attempt_at, so the lock lasts exactly D from the Nth attempt")
+ })
+
+ 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)
+ require.NoError(t, err)
+ require.True(t, granted)
+ }
+ granted, err := s.ClaimLoginAttempt(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)
+ 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)
+ require.NoError(t, err)
+ require.False(t, granted)
+ })
+
+ 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)
+ 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)
+ require.NoError(t, err)
+ require.True(t, granted, "success must forget every prior failure")
+ }
+ })
+
+ t.Run("clear of an unknown identity is a no-op", func(t *testing.T) {
+ require.NoError(t, s.ClearLoginAttempt(ctx, "[email protected]", storepb.LoginAttemptKind_MFA))
+ })
+
+ 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)
+ require.NoError(t, err)
+ require.True(t, granted)
+ }
+ granted, err := s.ClaimLoginAttempt(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)
+ 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)
+ require.NoError(t, err)
+ require.True(t, granted, "another identity must have its own slots")
+ })
+
+ t.Run("concurrent claims grant exactly N slots", func(t *testing.T) {
+ const identity = "[email protected]"
+ const n = 5
+ var wg sync.WaitGroup
+ grants := make(chan bool, 20)
+ for range 20 {
+ wg.Go(func() {
+ granted, err := s.ClaimLoginAttempt(ctx, identity, storepb.LoginAttemptKind_PASSWORD, n, window)
+ require.NoError(t, err)
+ grants <- granted
+ })
+ }
+ wg.Wait()
+ close(grants)
+ grantedCount := 0
+ for granted := range grants {
+ if granted {
+ grantedCount++
+ }
+ }
+ require.Equal(t, n, grantedCount, "the row lock must serialize claims so exactly N slots are granted")
+ })
+
+ t.Run("unkeyed claims are refused outright", func(t *testing.T) {
+ _, err := s.ClaimLoginAttempt(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)
+ 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)
+ require.Error(t, err, "a structurally oversized identity must never write a row")
+ })
+
+ t.Run("purge deletes only stale rows", func(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)
+ require.NoError(t, err)
+ require.True(t, granted)
+ }
+ backdate(staleIdentity, storepb.LoginAttemptKind_PASSWORD, time.Hour+time.Second)
+
+ deleted, err := s.DeleteStaleLoginAttempts(ctx, time.Hour)
+ require.NoError(t, err)
+ require.EqualValues(t, 1, deleted)
+
+ var count int
+ require.NoError(t, db.QueryRowContext(ctx, `
+ SELECT COUNT(*) FROM login_attempt WHERE identity = $1
+ `, freshIdentity).Scan(&count))
+ require.Equal(t, 1, count, "rows attempted within the retention window must survive the purge")
+ })
+}
diff --git a/backend/tests/login_attempt_collision_test.go b/backend/tests/login_attempt_collision_test.go
new file mode 100644
index 0000000000..ebf4c0358b
--- /dev/null
+++ b/backend/tests/login_attempt_collision_test.go
@@ -0,0 +1,92 @@
+package tests
+
+import (
+ "context"
+ "fmt"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/require"
+
+ "github.com/bytebase/bytebase/backend/common/testcontainer"
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+ "github.com/bytebase/bytebase/backend/migrator"
+ "github.com/bytebase/bytebase/backend/store"
+)
+
+// TestCollision_LoginAttempt is the composite-PK collision gate for
+// login_attempt (PRIMARY KEY (identity, kind)) — see AGENTS.md and
+// docs/pre-pr-checklist.md step 3. The table is not project-scoped: identity
+// is itself the scope column, so the shared project fixture does not apply.
+// What collision safety means here is that no store operation may cross
+// buckets: rows sharing an identity (other kind) or sharing a kind (other
+// identity) must be untouched by claims, clears, and purges on a neighbor.
+func TestCollision_LoginAttempt(t *testing.T) {
+ ctx := context.Background()
+ container := testcontainer.GetTestPgContainer(ctx, t)
+ t.Cleanup(func() { container.Close(ctx) })
+ require.NoError(t, migrator.MigrateSchema(ctx, container.GetDB()))
+
+ 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 = 10 * time.Minute
+ const victim = "[email protected]"
+ const neighbor = "[email protected]"
+
+ // 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)
+ require.NoError(t, err)
+ require.True(t, granted)
+ }
+ for _, seed := range []struct {
+ identity string
+ kind storepb.LoginAttemptKind
+ }{
+ {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)
+ require.NoError(t, err)
+ require.True(t, granted)
+ }
+
+ attempts := func(identity string, kind storepb.LoginAttemptKind) int {
+ t.Helper()
+ var count int
+ require.NoError(t, container.GetDB().QueryRowContext(ctx, `
+ SELECT COALESCE((SELECT attempts FROM login_attempt WHERE identity = $1 AND kind = $2), 0)
+ `, identity, kind.String()).Scan(&count))
+ return count
+ }
+
+ // The victim's lock must not leak into either neighbor.
+ granted, err := s.ClaimLoginAttempt(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))
+ require.Equal(t, 1, attempts(neighbor, storepb.LoginAttemptKind_PASSWORD))
+
+ // Clearing the victim must delete exactly the victim's row.
+ require.NoError(t, s.ClearLoginAttempt(ctx, victim, storepb.LoginAttemptKind_PASSWORD))
+ require.Zero(t, attempts(victim, storepb.LoginAttemptKind_PASSWORD))
+ require.Equal(t, 1, attempts(victim, storepb.LoginAttemptKind_MFA))
+ require.Equal(t, 1, attempts(neighbor, storepb.LoginAttemptKind_PASSWORD))
+
+ // 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, `
+ UPDATE login_attempt SET last_attempt_at = last_attempt_at - make_interval(secs => $3)
+ WHERE identity = $1 AND kind = $2
+ `, neighbor, storepb.LoginAttemptKind_PASSWORD.String(), (2 * time.Hour).Seconds())
+ require.NoError(t, err)
+ deleted, err := s.DeleteStaleLoginAttempts(ctx, time.Hour)
+ require.NoError(t, err)
+ require.EqualValues(t, 1, deleted)
+ require.Zero(t, attempts(neighbor, storepb.LoginAttemptKind_PASSWORD))
+ require.Equal(t, 1, attempts(victim, storepb.LoginAttemptKind_MFA))
+}
diff --git a/backend/tests/login_audit_test.go b/backend/tests/login_audit_test.go
index 463864e940..efface2f64 100644
--- a/backend/tests/login_audit_test.go
+++ b/backend/tests/login_audit_test.go
@@ -84,7 +84,7 @@ func TestLoginFailureLockout(t *testing.T) {
a.ErrorContains(err, "too many failed MFA attempts")
for _, email := range []string{" [email protected] ", " [email protected] "} {
- for range 10 {
+ for range 5 {
_, err := ctl.authServiceClient.Login(ctx, connect.NewRequest(&v1pb.LoginRequest{
Email: email,
Password: "wrong-password",
@@ -100,6 +100,26 @@ func TestLoginFailureLockout(t *testing.T) {
a.ErrorContains(err, "too many failed login attempts")
}
+ // Email-code guessing is bounded by the same per-identity claims, taken
+ // before the code row is even loaded — no code needs to be pending and no
+ // audit-log counter is consulted, so the bound holds on Cloud and
+ // self-hosted alike.
+ wrongCode := "000000"
+ for range 5 {
+ _, err := ctl.authServiceClient.Login(ctx, connect.NewRequest(&v1pb.LoginRequest{
+ Email: "[email protected]",
+ EmailCode: &wrongCode,
+ }))
+ a.Equal(connect.CodeUnauthenticated, connect.CodeOf(err))
+ a.ErrorContains(err, "invalid or expired code")
+ }
+ _, err = ctl.authServiceClient.Login(ctx, connect.NewRequest(&v1pb.LoginRequest{
+ Email: "[email protected]",
+ EmailCode: &wrongCode,
+ }))
+ a.Equal(connect.CodeResourceExhausted, connect.CodeOf(err))
+ a.ErrorContains(err, "too many attempts, please try again later")
+
ctl.authInterceptor.token = adminToken
search, err := ctl.auditLogServiceClient.SearchAuditLogs(ctx, connect.NewRequest(&v1pb.SearchAuditLogsRequest{
Parent: workspace,
@@ -113,6 +133,8 @@ func TestLoginFailureLockout(t *testing.T) {
passwordLockoutCount := map[string]int{}
invalidMFACount := 0
mfaLockoutCount := 0
+ invalidEmailCodeCount := 0
+ emailCodeLockoutCount := 0
for _, auditLog := range search.Msg.AuditLogs {
if auditLog.Status == nil {
continue
@@ -123,6 +145,7 @@ func TestLoginFailureLockout(t *testing.T) {
a.Empty(request.Password)
a.Empty(request.GetOtpCode())
a.Empty(request.GetMfaTempToken())
+ a.NotEqual(wrongCode, request.GetEmailCode())
a.NotContains(auditLog.Request, "wrong-password")
a.NotContains(auditLog.Request, invalidOTP)
a.NotContains(auditLog.Request, mfaTempToken)
@@ -136,15 +159,21 @@ func TestLoginFailureLockout(t *testing.T) {
invalidMFACount++
case "too many failed MFA attempts, please try again later":
mfaLockoutCount++
+ case "invalid or expired code":
+ invalidEmailCodeCount++
+ case "too many attempts, please try again later":
+ emailCodeLockoutCount++
default:
}
}
- a.Equal(10, invalidPasswordCount["[email protected]"])
- a.Equal(10, invalidPasswordCount["[email protected]"])
+ a.Equal(5, invalidPasswordCount["[email protected]"])
+ a.Equal(5, invalidPasswordCount["[email protected]"])
a.Equal(1, passwordLockoutCount["[email protected]"])
a.Equal(1, passwordLockoutCount["[email protected]"])
a.Equal(5, invalidMFACount)
a.Equal(1, mfaLockoutCount)
+ a.Equal(5, invalidEmailCodeCount)
+ a.Equal(1, emailCodeLockoutCount)
var misownedRows int
a.NoError(metadataDB.QueryRowContext(ctx, `
@@ -563,21 +592,19 @@ func TestAuditLogFormat(t *testing.T) {
defer metadataDB.Close()
var authSecret string
a.NoError(metadataDB.QueryRowContext(ctx, `SELECT payload->>'authSecret' FROM server_config LIMIT 1`).Scan(&authSecret))
- insertVerificationCode := func(email, purpose, code string, workspaceID sql.NullString) {
+ insertVerificationCode := func(email, purpose, code string) {
mac := hmac.New(sha256.New, []byte(authSecret))
_, err := mac.Write([]byte(code))
a.NoError(err)
_, err = metadataDB.ExecContext(ctx, `
- INSERT INTO email_verification_code (email, purpose, code_hash, expires_at, last_sent_at, workspace)
- VALUES ($1, $2, $3, $4, $5, $6)
- ON CONFLICT (email, purpose) DO UPDATE SET code_hash = EXCLUDED.code_hash, attempts = 0,
- expires_at = EXCLUDED.expires_at, last_sent_at = EXCLUDED.last_sent_at, workspace = EXCLUDED.workspace
- `, email, purpose, hex.EncodeToString(mac.Sum(nil)), time.Now().Add(time.Hour), time.Now(), workspaceID)
+ INSERT INTO email_verification_code (email, purpose, code_hash, expires_at, last_sent_at)
+ VALUES ($1, $2, $3, $4, $5)
+ ON CONFLICT (email, purpose) DO UPDATE SET code_hash = EXCLUDED.code_hash,
+ expires_at = EXCLUDED.expires_at, last_sent_at = EXCLUDED.last_sent_at
+ `, email, purpose, hex.EncodeToString(mac.Sum(nil)), time.Now().Add(time.Hour), time.Now())
a.NoError(err)
}
- workspaceID, err := common.GetWorkspaceID(workspace)
- a.NoError(err)
var invitedUserCount int
_, err = ctl.settingServiceClient.UpdateSetting(ctx, connect.NewRequest(&v1pb.UpdateSettingRequest{
Setting: &v1pb.Setting{
@@ -614,7 +641,7 @@ func TestAuditLogFormat(t *testing.T) {
}))
a.NoError(err)
loginCode := "765432"
- insertVerificationCode(invitedEmail, "LOGIN", loginCode, sql.NullString{String: workspaceID, Valid: true})
+ insertVerificationCode(invitedEmail, "LOGIN", loginCode)
ctl.authInterceptor.token = ""
_, err = ctl.authServiceClient.Login(ctx, connect.NewRequest(&v1pb.LoginRequest{
Email: invitedEmail,
@@ -656,7 +683,7 @@ func TestAuditLogFormat(t *testing.T) {
resetCode := "123456"
newPassword := "new-password-1024"
- insertVerificationCode("[email protected]", "PASSWORD_RESET", resetCode, sql.NullString{String: workspaceID, Valid: true})
+ insertVerificationCode("[email protected]", "PASSWORD_RESET", resetCode)
ctl.authInterceptor.token = ""
_, err = ctl.authServiceClient.ResetPassword(ctx, connect.NewRequest(&v1pb.ResetPasswordRequest{
@@ -683,7 +710,7 @@ func TestAuditLogFormat(t *testing.T) {
failedResetCode := "654321"
failedPassword := "short"
- insertVerificationCode("[email protected]", "PASSWORD_RESET", failedResetCode, sql.NullString{String: workspaceID, Valid: true})
+ insertVerificationCode("[email protected]", "PASSWORD_RESET", failedResetCode)
ctl.authInterceptor.token = ""
_, resetErr := ctl.authServiceClient.ResetPassword(ctx, connect.NewRequest(&v1pb.ResetPasswordRequest{
@@ -710,11 +737,14 @@ func TestAuditLogFormat(t *testing.T) {
a.NotContains(failedResetLog.Request, failedResetCode)
a.NotContains(failedResetLog.Request, failedPassword)
+ // Reset requests carry no workspace context at all: the audit workspace is
+ // resolved from the user's own memberships (here via the allUsers grant), so
+ // these rows land under the workspace even though the caller named none.
noWorkspaceUser, err := ctl.userServiceClient.CreateUser(ctx, connect.NewRequest(&v1pb.CreateUserRequest{
User: &v1pb.User{Email: "[email protected]", Title: "No workspace reset", Password: "1024bytebase"},
}))
a.NoError(err)
- insertVerificationCode(noWorkspaceUser.Msg.Email, "PASSWORD_RESET", resetCode, sql.NullString{})
+ insertVerificationCode(noWorkspaceUser.Msg.Email, "PASSWORD_RESET", resetCode)
ctl.authInterceptor.token = ""
_, err = ctl.authServiceClient.ResetPassword(ctx, connect.NewRequest(&v1pb.ResetPasswordRequest{
Email: noWorkspaceUser.Msg.Email,
@@ -723,7 +753,7 @@ func TestAuditLogFormat(t *testing.T) {
}))
a.NoError(err, "no-workspace reset must preserve existing API behavior")
ctl.authInterceptor.token = adminToken
- insertVerificationCode(noWorkspaceUser.Msg.Email, "PASSWORD_RESET", resetCode, sql.NullString{})
+ insertVerificationCode(noWorkspaceUser.Msg.Email, "PASSWORD_RESET", resetCode)
_, err = ctl.authServiceClient.ResetPassword(ctx, connect.NewRequest(&v1pb.ResetPasswordRequest{
Email: noWorkspaceUser.Msg.Email,
Code: resetCode,
@@ -735,7 +765,7 @@ func TestAuditLogFormat(t *testing.T) {
Filter: `method == "/bytebase.v1.AuthService/ResetPassword"`,
}))
a.NoError(err)
- a.Len(resetLogs.Msg.AuditLogs, 2, "a reset code without workspace context has no valid audit parent")
+ a.Len(resetLogs.Msg.AuditLogs, 4, "resets resolve their audit workspace from the user's membership, not the request")
// --- Part 2.5: Denied Signup is still audited ---
//
diff --git a/docs/design/login-attempt-lockout.md b/docs/design/login-attempt-lockout.md
index 294926b043..f7a93e97c1 100644
--- a/docs/design/login-attempt-lockout.md
+++ b/docs/design/login-attempt-lockout.md
@@ -6,6 +6,10 @@ the two counters that fail today: the audit-log count, which reads zero on Cloud
`attempts` column, which an attacker resets by exhausting it. Closes T9 in
[`v1-api-audit-2026-08.md`](v1-api-audit-2026-08.md).
+**Implemented** in [#21234](https://github.com/bytebase/bytebase/pull/21234) (2026-08-24). Migration
+`3.22/0012##login_attempt.sql`; the store owns the atomic claim, `backend/api/v1/auth_service_lockout.go`
+owns the kinds and limits, and the claim sites live with the credential each verifies.
+
## Background
Guessing is throttled at three points by three mechanisms:
@@ -41,7 +45,8 @@ Guessing is throttled at three points by three mechanisms:
- **G3** No existence oracle: unknown and known emails lock at the same attempt with the same error.
- **G4** Locks expire on their own; no admin unlock.
- **G5** Correct under replicas: state in the metadata database, one atomic statement per attempt.
-- **G6** Password and MFA thresholds, error codes, and messages unchanged.
+- **G6** Lockout error codes and messages unchanged; one shared threshold — five attempts per
+ ten minutes — replaces the three historical ones.
### Non-goals
@@ -75,11 +80,7 @@ belongs to. No `ip` column: the caller IP is forgeable, and per-source throttlin
### Semantics
-| Kind | Attempts `N` | Duration `D` |
-|---|---|---|
-| `PASSWORD` | 10 | 10 min |
-| `EMAIL_CODE` | 5 | 10 min |
-| `MFA` | 5 | 5 min |
+Every kind shares one limit: `N` = 5 attempts, `D` = 10 minutes.
1. **An attempt claims a slot before the credential is checked.** `N` attempts are granted. If
the identity already holds `N` and the latest was under `D` ago, the next gets no slot:
@@ -93,13 +94,18 @@ cannot merge two identities into one bucket or split one across buckets (G1):
- local password and emailed code: the normalized email;
- MFA: the email inside the signed temp token;
-- LDAP: the resolved identity-provider ID joined with the submitted username. The same username in
- another directory is a different person and must be a different row — the point sharpened by
- success deleting the row: keyed by bare username, an attacker who controls that username in a
- directory of their own could clear a victim's counter by logging in there.
-
-Identities over 254 characters — and, where the identity is an email, invalid syntax — are rejected
-before the claim, so garbage never writes a row.
+- LDAP: the resolved identity-provider ID joined with the submitted username, verbatim. The same
+ username in another directory is a different person and must be a different row — the point
+ sharpened by success deleting the row: keyed by bare username, an attacker who controls that
+ username in a directory of their own could clear a victim's counter by logging in there. The
+ username is not normalized either, since a case-exact directory attribute can name two accounts
+ differing only by case, and merging them would let either lock — or clear — the other; one
+ bucket per submitted form is the accepted trade below.
+
+Every request field that becomes an identity is bounded at the proto edge (emails at 254
+characters, `string.max_len` enforced by the validate interceptor), invalid email syntax is
+rejected before the claim, and the store refuses structurally oversized keys — so garbage never
+writes a row.
This is Vault's threshold / duration / counter-reset model with the last two collapsed, as Vault's
own defaults do. It is at least as strict as a sliding window everywhere, and stricter against an
@@ -126,8 +132,9 @@ RETURNING 1;
A row back is a slot; no row is a lockout. The row lock serializes concurrent claims, so the
`N`th slot goes to exactly one of them (G5). `now()` is database time, so replicas cannot
-disagree. A slot spent on a non-credential error (database failure mid-verification) is not
-refunded.
+disagree. A slot spent on a non-credential error (database failure mid-verification, an
+unreachable LDAP directory) is not refunded — during such an outage login fails regardless, and
+the residual lock expires on its own within `D`.
The store exposes exactly three operations: claim an attempt, clear on success, purge stale rows.
@@ -136,9 +143,10 @@ The store exposes exactly three operations: claim an attempt, clear on success,
Password login claims `PASSWORD` once, before the credential is checked — under the email for a
local password, under the provider-scoped identity for an LDAP bind — and clears it on success. Verifying an emailed code claims `EMAIL_CODE` before the code row is even loaded, for
login and password-reset codes alike, and clears it on a match. Completing MFA — during login or
-when switching workspaces — claims `MFA` for the email inside the signed temp token and clears it
-on success. A successful password reset also clears `PASSWORD`, as Grafana and Mattermost do, so
-a user who locked themselves out is not still locked with the new password. The three
+when switching workspaces — claims `MFA` for the email inside the signed temp token, and refuses a
+request carrying no code at all before claiming, since nothing is compared. A successful password
+reset also clears `PASSWORD` — the API path and the recovery CLI alike, as Grafana and Mattermost
+do — so a user who locked themselves out is not still locked with the new password. The three
audit-counting checks they replace are deleted.
### `email_verification_code`
@@ -159,7 +167,8 @@ resend cooldown.
password policy and the audit workspace come from the user's own memberships — the singleton on
self-hosted. Email-code signup: the gates that run before creating a new user check the singleton on
self-hosted, or on SaaS the workspace whose invitation the email holds — the same lookup
- provisioning already uses; a brand-new signup has neither and gets the SaaS defaults, as today.
+ provisioning already uses, preferring the requested workspace when it is one of the email's own
+ invitations, as login does for existing users; a brand-new signup has neither and gets the SaaS defaults, as today.
Existing users are checked after authentication against their resolved workspace, as today.
### Audit log and cleanup
@@ -184,16 +193,18 @@ it.
**Performance: net improvement.** An indexed single-row upsert replaces an audit-log scan per
attempt, locked attempts return before bcrypt, and one identifier's attempts serialize on its own
-row, throttling only that attacker. The one new cost — a small row per distinct identifier
+row, throttling only that attacker. A successful login holds its slot only for the verification's
+duration, so more than `N` concurrent correct-credential logins for one identity can see transient
+refusals until the first completes — accepted; a retry succeeds. The one new cost — a small row per distinct identifier
attempted, an unauthenticated write path Cloud did not have — is bounded by pre-claim validation,
the hourly purge, and edge rate caps.
**Edge rules (configuration, not code).** Cloudflare does nothing for these paths until rules
exist. `Login` / `ResetPassword`: ~30 per 10 min per IP, counting only `401`/`429` responses, so
service accounts and CI logging in successfully from shared IPs never trip it. For that filter to
-catch LDAP spraying, an invalid-credential bind must surface as `Unauthenticated`, not the
-`Internal` (500) it returns today — a small pre-existing fix, without which the edge misses failed
-LDAP binds and the per-username rows they write. The two send paths, which always answer OK to
+catch LDAP spraying, an invalid-credential bind surfaces as `Unauthenticated` rather than the
+`Internal` (500) it used to return (shipped with this change; the directory's own diagnostic is
+logged and kept for the admin test-sign-in flow). The two send paths, which always answer OK to
avoid enumeration: the same limit on all requests — tolerates an office NAT, caps single-IP
mail-bombing. No challenges on auth paths; CLI and CI cannot solve them.
Preconditions: origin locked to Cloudflare's ranges, `CF-Connecting-IP` as the audit caller IP.
diff --git a/docs/design/v1-api-audit-2026-08.md b/docs/design/v1-api-audit-2026-08.md
index 53d2c15313..7085e43563 100644
--- a/docs/design/v1-api-audit-2026-08.md
+++ b/docs/design/v1-api-audit-2026-08.md
@@ -15,7 +15,6 @@ noted. Nothing here is patched yet. Fixed findings are removed and listed at the
| T15 | Rotating a leaked cloud credential can silently do nothing | HIGH |
| T13 | "Waiting for my approval" can show an empty page with a live Load More | HIGH |
| T14 | Paging through issues across projects skips some and repeats others | HIGH |
-| T9 | On Cloud, login codes and 2FA codes can be guessed without limit | HIGH |
| T18a | Test-environment rights can cancel a running production migration | MED |
| T12 | Anonymous callers can enumerate emails, relay mail, and read your LDAP config | MED |
| T16 | Four `BatchGet` RPCs behave four different ways when an item is missing | MED |
@@ -28,40 +27,6 @@ noted. Nothing here is patched yet. Fixed findings are removed and listed at the
## Getting in, and staying in
-### T9 · On Cloud, login codes and 2FA codes can be guessed without limit — HIGH
-
-The password and MFA lockouts count failed-login rows in the audit log, and a failed login's audit
-row needs a workspace to be written under. Self-hosted always has one — the singleton
-(`resolveAuthenticationWorkspaceID`, `auth_service.go:167-190`). On Cloud the only source is the
-request's own `workspace` field, which an attacker omits; with none the interceptor skips the row
-(`audit.go:398-400`), the counter reads zero forever, and the limits never fire. A lockout keyed on
-something the caller controls is not a lockout.
-
-**This does not expose passwords on Cloud.** SaaS forces `DisallowPasswordSignin = true`
-(`auth_service.go:1624-1627`) and Cloud accounts carry a random 32-byte bcrypt hash (`:2049-2056`).
-**What is exposed is the second factor.** `completeMFALogin` gates on `checkMFALockout` (`:1076`) —
-inert on Cloud — and the MFA temp token is a reusable five-minute JWT, so an attacker who has passed
-the email-code step (i.e. holds the inbox, the situation the second factor exists to survive) can
-guess TOTP or recovery codes for the whole window with nothing counting the misses.
-
-Self-hosted is fixed and tested ([#21189](https://github.com/bytebase/bytebase/pull/21189)), but the
-control still reads the audit log. The email-code path, traced for the fix, has its own hole: the
-resend cooldown is a predicate on the code row and the row is deleted on attempt exhaustion, so the
-cooldown can be bypassed and the Cloud primary factor guessed at request rate. That raises the
-finding to HIGH: it is the first factor of every MFA-less Cloud account, not a second factor behind
-a compromised inbox.
-
-**Fix:** [`login-attempt-lockout.md`](login-attempt-lockout.md) — one `login_attempt` table for
-password, email-code, and MFA failures, replacing both the audit-log counter and the per-code
-attempt column. Re-verified 2026-08-23 against `37339d73c8`.
-
-**Accepted, not fixed:** no per-tenant failed-login record on Cloud (a control, not a record, is what
-the fix adds; SIEM consumers are self-hosted, where rows already exist, and attribution is ambiguous
-once a user spans workspaces), and lockout-as-denial-of-service (inherent to per-identity lockout —
-with the fix it covers Cloud's email-code factor too, where the same denial is already reachable by
-burning a victim's codes; bounded by the short window; the remedy is per-IP throttling, scoped out
-with password spraying in BYT-10068).
-
### T10 · A borrowed session becomes permanent account takeover — HIGH
Changing your own password doesn't require the current password, and switching off your own 2FA
@@ -255,16 +220,13 @@ constraints.
## What I'd do, in order
-1. **Bound credential guessing (T9)** per [`login-attempt-lockout.md`](login-attempt-lockout.md):
- one attempt table for password, email-code, and MFA failures on both deployments. It needs no
- stolen session, only a target email, and the design is ready to implement.
-2. **Require re-authentication for password change and 2FA disable (T10).** The one finding that
+1. **Require re-authentication for password change and 2FA disable (T10).** The one finding that
turns a temporary compromise into a permanent one, and it affects both deployments.
-3. **Fix the ACL class, not the instance (T2).** Teach the interceptor to collect every annotated
+2. **Fix the ACL class, not the instance (T2).** Teach the interceptor to collect every annotated
resource field, then annotate `DiffSchema`. Otherwise the next second-resource field reopens it.
-4. **Make credential rotation fail loudly (T15).** A security operation that returns 200 and does
+3. **Make credential rotation fail loudly (T15).** A security operation that returns 200 and does
nothing is worse than one that errors.
-5. **Fail closed on auth annotations, and put api-linter in CI.** Reject
+4. **Fail closed on auth annotations, and put api-linter in CI.** Reject
`AUTH_METHOD_UNSPECIFIED` at startup; make a `permission` on a CUSTOM RPC either enforced or a
build error, since 15 are decorative. None of Tier 5 was visible to `buf lint`'s BASIC profile,
which is why it accumulated.
@@ -283,7 +245,7 @@ constraints.
| 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) |
| 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` |
| 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 |
-| T9 (self-hosted) | [#21189](https://github.com/bytebase/bytebase/pull/21189) — failed logins are audited and the lockout is tested end-to-end (SaaS remainder above) |
+| T9 | [#21189](https://github.com/bytebase/bytebase/pull/21189) (self-hosted audit rows) + [#21234](https://github.com/bytebase/bytebase/pull/21234) — one `login_attempt` table bounds password, email-code, and MFA guessing per identity on both deployments, replacing the audit-log counter and the per-code attempt column (which bypassed the resend cooldown). Accepted with it: no per-tenant failed-login record on Cloud, and lockout-as-denial-of-service — see [`login-attempt-lockout.md`](login-attempt-lockout.md) |
**`AIService.Chat` — accepted, not fixed** (2026-08-18). `Chat` requires an authenticated workspace
principal and touches no database or sheet, so the only exposure is LLM spend. On Cloud the feature
diff --git a/docs/pre-pr-checklist.md b/docs/pre-pr-checklist.md
index 3f10810af8..2e1e25c628 100644
--- a/docs/pre-pr-checklist.md
+++ b/docs/pre-pr-checklist.md
@@ -67,6 +67,12 @@ task run can share a `created_at` microsecond — BYT-10035), but it is equally
project-scoped: every predicate on it must include `project` alongside
`task_run_id`.
+`email_verification_code (email, purpose)` and `login_attempt (identity, kind)`
+are composite-PK but not project-scoped: the email/identity column is itself the
+scope. Their store methods must still predicate on the full PK; collision
+coverage is table-specific (`TestCollision_LoginAttempt` in `backend/tests/`)
+rather than via the shared project fixture.
+
Always verify against LATEST.sql — tables may have been added since this list was
last updated. Cross-reference with the tables your diff touches.
diff --git a/frontend/src/types/proto-es/v1/auth_service_pb.d.ts b/frontend/src/types/proto-es/v1/auth_service_pb.d.ts
index 72328769f8..69fe59106b 100644
--- a/frontend/src/types/proto-es/v1/auth_service_pb.d.ts
+++ b/frontend/src/types/proto-es/v1/auth_service_pb.d.ts
@@ -113,13 +113,17 @@ export declare const RestrictionSchema: GenMessage<Restriction>;
export declare type LoginRequest = Message<"bytebase.v1.LoginRequest"> & {
/**
* User's email address.
+ * Bounded so an oversized identity is refused at the edge before any
+ * handler runs; the login-attempt lockout keys rows by this value.
*
* @generated from field: string email = 1;
*/
email: string;
/**
- * User's password for authentication.
+ * User's password for authentication. Bounded for abuse only: LDAP
+ * directories may accept passwords beyond bcrypt's 72-byte limit, and the
+ * local-password path rejects longer inputs itself.
*
* @generated from field: string password = 2;
*/
@@ -373,6 +377,8 @@ export declare const ExchangeTokenResponseSchema: GenMessage<ExchangeTokenRespon
export declare type SignupRequest = Message<"bytebase.v1.SignupRequest"> & {
/**
* The email for the new account.
+ * Bounded so an oversized identity is refused at the edge before any
+ * handler runs; the login-attempt lockout keys rows by this value.
*
* @generated from field: string email = 1;
*/
@@ -433,6 +439,8 @@ export declare const RefreshResponseSchema: GenMessage<RefreshResponse>;
export declare type RequestPasswordResetRequest = Message<"bytebase.v1.RequestPasswordResetRequest"> & {
/**
* The email address of the account to reset.
+ * Bounded so an oversized identity is refused at the edge before any
+ * handler runs; the login-attempt lockout keys rows by this value.
*
* @generated from field: string email = 1;
*/
@@ -461,6 +469,8 @@ export declare const RequestPasswordResetRequestSchema: GenMessage<RequestPasswo
export declare type ResetPasswordRequest = Message<"bytebase.v1.ResetPasswordRequest"> & {
/**
* The email address of the account.
+ * Bounded so an oversized identity is refused at the edge before any
+ * handler runs; the login-attempt lockout keys rows by this value.
*
* @generated from field: string email = 1;
*/
@@ -493,6 +503,8 @@ export declare const ResetPasswordRequestSchema: GenMessage<ResetPasswordRequest
export declare type SendEmailLoginCodeRequest = Message<"bytebase.v1.SendEmailLoginCodeRequest"> & {
/**
* The email address to send the code to.
+ * Bounded so an oversized identity is refused at the edge before any
+ * handler runs; the login-attempt lockout keys rows by this value.
*
* @generated from field: string email = 1;
*/
diff --git a/frontend/src/types/proto-es/v1/auth_service_pb.js b/frontend/src/types/proto-es/v1/auth_service_pb.js
index 227b9afecd..ff3596203e 100644
--- a/frontend/src/types/proto-es/v1/auth_service_pb.js
+++ b/frontend/src/types/proto-es/v1/auth_service_pb.js
@@ -3,6 +3,7 @@
/* eslint-disable */
import { fileDesc, messageDesc, serviceDesc } from "@bufbuild/protobuf/codegenv2";
+import { file_buf_validate_validate } from "../buf/validate/validate_pb";
import { file_google_api_annotations } from "../google/api/annotations_pb";
import { file_google_api_client } from "../google/api/client_pb";
import { file_google_api_field_behavior } from "../google/api/field_behavior_pb";
@@ -16,7 +17,7 @@ import { file_v1_user_service } from "./user_service_pb";
* Describes the file v1/auth_service.proto.
*/
export const file_v1_auth_service = /*@__PURE__*/
- fileDesc("ChV2MS9hdXRoX3NlcnZpY2UucHJvdG8SC2J5dGViYXNlLnYxIlUKI0dldEF1dGhlbnRpY2F0aW9uUmVzdHJpY3Rpb25SZXF1ZXN0Ei4KCXdvcmtzcGFjZRgBIAEoCUIb+kEYChZieXRlYmFzZS5jb20vV29ya3NwYWNlImAKEkF1dGhlbnRpY2F0aW9uSW5mbxIWCgl3b3Jrc3BhY2UYASABKAlCA+BBAxIyCgtyZXN0cmljdGlvbhgCIAEoCzIYLmJ5dGViYXNlLnYxLlJlc3RyaWN0aW9uQgPgQQMi+gEKC1Jlc3RyaWN0aW9uEhwKD2Rpc2FsbG93X3NpZ251cBgBIAEoCEID4EEDEiUKGGRpc2FsbG93X3Bhc3N3b3JkX3NpZ25pbhgCIAEoCEID4EEDElsKFHBhc3N3b3JkX3Jlc3RyaWN0aW9uGAMgASgLMjguYnl0ZWJhc2UudjEuV29ya3NwYWNlUHJvZmlsZVNldHRpbmcuUGFzc3dvcmRSZXN0cmljdGlvbkID4EEDEiQKF2FsbG93X2VtYWlsX2NvZGVfc2lnbmluGAQgASgIQgPgQQMSIwoWcGFzc3dvcmRfcmVzZXRfZW5hYmxlZBgFIAEoCEID4EEDIvcCCgxMb2dpblJlcXVlc3QSDQoFZW1haWwYASABKAkSFgoIcGFzc3dvcmQYAiABKAlCBNDqMAESCwoDd2ViGAMgASgIEhAKCGlkcF9uYW1lGAQgASgJEjkKC2lkcF9jb250ZXh0GAUgASgLMiQuYnl0ZWJhc2UudjEuSWRlbnRpdHlQcm92aWRlckNvbnRleHQSGwoIb3RwX2NvZGUYBiABKAlCBNDqMAFIAIgBARIgCg1yZWNvdmVyeV9jb2RlGAcgASgJQgTQ6jABSAGIAQESIQoObWZhX3RlbXBfdG9rZW4YCCABKAlCBNDqMAFIAogBARIdCgplbWFpbF9jb2RlGAkgASgJQgTQ6jABSAOIAQESFgoJd29ya3NwYWNlGAogASgJSASIAQFCCwoJX290cF9jb2RlQhAKDl9yZWNvdmVyeV9jb2RlQhEKD19tZmFfdGVtcF90b2tlbkINCgtfZW1haWxfY29kZUIMCgpfd29ya3NwYWNlIqwBChdJZGVudGl0eVByb3ZpZGVyQ29udGV4dBJECg5vYXV0aDJfY29udGV4dBgBIAEoCzIqLmJ5dGViYXNlLnYxLk9BdXRoMklkZW50aXR5UHJvdmlkZXJDb250ZXh0SAASQAoMb2lkY19jb250ZXh0GAIgASgLMiguYnl0ZWJhc2UudjEuT0lEQ0lkZW50aXR5UHJvdmlkZXJDb250ZXh0SABCCQoHY29udGV4dCIzCh1PQXV0aDJJZGVudGl0eVByb3ZpZGVyQ29udGV4dBISCgRjb2RlGAEgASgJQgTQ6jABIjEKG09JRENJZGVudGl0eVByb3ZpZGVyQ29udGV4dBISCgRjb2RlGAEgASgJQgTQ6jABIpsBCg1Mb2dpblJlc3BvbnNlEhMKBXRva2VuGAEgASgJQgTQ6jABEiEKDm1mYV90ZW1wX3Rva2VuGAIgASgJQgTQ6jABSACIAQESHgoWcmVxdWlyZV9yZXNldF9wYXNzd29yZBgDIAEoCBIfCgR1c2VyGAQgASgLMhEuYnl0ZWJhc2UudjEuVXNlckIRCg9fbWZhX3RlbXBfdG9rZW4iDwoNTG9nb3V0UmVxdWVzdCI6ChRFeGNoYW5nZVRva2VuUmVxdWVzdBITCgV0b2tlbhgBIAEoCUIE0OowARINCgVlbWFpbBgCIAEoCSIzChVFeGNoYW5nZVRva2VuUmVzcG9uc2USGgoMYWNjZXNzX3Rva2VuGAEgASgJQgTQ6jABIkUKDVNpZ251cFJlcXVlc3QSDQoFZW1haWwYASABKAkSFgoIcGFzc3dvcmQYAiABKAlCBNDqMAESDQoFdGl0bGUYAyABKAkiEAoOUmVmcmVzaFJlcXVlc3QiEQoPUmVmcmVzaFJlc3BvbnNlIlIKG1JlcXVlc3RQYXNzd29yZFJlc2V0UmVxdWVzdBINCgVlbWFpbBgBIAEoCRIWCgl3b3Jrc3BhY2UYAiABKAlIAIgBAUIMCgpfd29ya3NwYWNlIlUKFFJlc2V0UGFzc3dvcmRSZXF1ZXN0Eg0KBWVtYWlsGAEgASgJEhIKBGNvZGUYAiABKAlCBNDqMAESGgoMbmV3X3Bhc3N3b3JkGAMgASgJQgTQ6jABIlAKGVNlbmRFbWFpbExvZ2luQ29kZVJlcXVlc3QSDQoFZW1haWwYASABKAkSFgoJd29ya3NwYWNlGAIgASgJSACIAQFCDAoKX3dvcmtzcGFjZSLMAQoWU3dpdGNoV29ya3NwYWNlUmVxdWVzdBIRCgl3b3Jrc3BhY2UYASABKAkSCwoDd2ViGAIgASgIEhsKCG90cF9jb2RlGAMgASgJQgTQ6jABSACIAQESIAoNcmVjb3ZlcnlfY29kZRgEIAEoCUIE0OowAUgBiAEBEiEKDm1mYV90ZW1wX3Rva2VuGAUgASgJQgTQ6jABSAKIAQFCCwoJX290cF9jb2RlQhAKDl9yZWNvdmVyeV9jb2RlQhEKD19tZmFfdGVtcF90b2tlbjLCCgoLQXV0aFNlcnZpY2USywEKHEdldEF1dGhlbnRpY2F0aW9uUmVzdHJpY3Rpb24SMC5ieXRlYmFzZS52MS5HZXRBdXRoZW50aWNhdGlvblJlc3RyaWN0aW9uUmVxdWVzdBofLmJ5dGViYXNlLnYxLkF1dGhlbnRpY2F0aW9uSW5mbyJY2kEAgOowAaDqMAGC0+STAkdaLxItL3YxL3t3b3Jrc3BhY2U9d29ya3NwYWNlcy8qfS9hdXRoL3Jlc3RyaWN0aW9uEhQvdjEvYXV0aC9yZXN0cmljdGlvbhJpCgVMb2dpbhIZLmJ5dGViYXNlLnYxLkxvZ2luUmVxdWVzdBoaLmJ5dGViYXNlLnYxLkxvZ2luUmVzcG9uc2UiKYDqMAGY6jABoOowA6jqMAGC0+STAhM6ASoiDi92MS9hdXRoL2xvZ2luEmgKBkxvZ291dBIaLmJ5dGViYXNlLnYxLkxvZ291dFJlcXVlc3QaFi5nb29nbGUucHJvdG9idWYuRW1wdHkiKoDqMAGY6jABoOowA6jqMASC0+STAhQ6ASoiDy92MS9hdXRoL2xvZ291dBKJAQoNRXhjaGFuZ2VUb2tlbhIhLmJ5dGViYXNlLnYxLkV4Y2hhbmdlVG9rZW5SZXF1ZXN0GiIuYnl0ZWJhc2UudjEuRXhjaGFuZ2VUb2tlblJlc3BvbnNlIjGA6jABmOowAaDqMAOo6jABgtPkkwIbOgEqIhYvdjEvYXV0aDpleGNoYW5nZVRva2VuEmwKBlNpZ251cBIaLmJ5dGViYXNlLnYxLlNpZ251cFJlcXVlc3QaGi5ieXRlYmFzZS52MS5Mb2dpblJlc3BvbnNlIiqA6jABmOowAaDqMAOo6jABgtPkkwIUOgEqIg8vdjEvYXV0aC9zaWdudXASbQoHUmVmcmVzaBIbLmJ5dGViYXNlLnYxLlJlZnJlc2hSZXF1ZXN0GhwuYnl0ZWJhc2UudjEuUmVmcmVzaFJlc3BvbnNlIieA6jABoOowA6jqMAGC0+STAhU6ASoiEC92MS9hdXRoL3JlZnJlc2gSgwEKD1N3aXRjaFdvcmtzcGFjZRIjLmJ5dGViYXNlLnYxLlN3aXRjaFdvcmtzcGFjZVJlcXVlc3QaGi5ieXRlYmFzZS52MS5Mb2dpblJlc3BvbnNlIi+Q6jACoOowA6jqMAGC0+STAh06ASoiGC92MS9hdXRoOnN3aXRjaFdvcmtzcGFjZRKSAQoUUmVxdWVzdFBhc3N3b3JkUmVzZXQSKC5ieXRlYmFzZS52MS5SZXF1ZXN0UGFzc3dvcmRSZXNldFJlcXVlc3QaFi5nb29nbGUucHJvdG9idWYuRW1wdHkiOIDqMAGY6jABoOowA6jqMAKC0+STAiI6ASoiHS92MS9hdXRoOnJlcXVlc3RQYXNzd29yZFJlc2V0En0KDVJlc2V0UGFzc3dvcmQSIS5ieXRlYmFzZS52MS5SZXNldFBhc3N3b3JkUmVxdWVzdBoWLmdvb2dsZS5wcm90b2J1Zi5FbXB0eSIxgOowAZjqMAGg6jADqOowAoLT5JMCGzoBKiIWL3YxL2F1dGg6cmVzZXRQYXNzd29yZBKMAQoSU2VuZEVtYWlsTG9naW5Db2RlEiYuYnl0ZWJhc2UudjEuU2VuZEVtYWlsTG9naW5Db2RlUmVxdWVzdBoWLmdvb2dsZS5wcm90b2J1Zi5FbXB0eSI2gOowAZjqMAGg6jADqOowAoLT5JMCIDoBKiIbL3YxL2F1dGg6c2VuZEVtYWlsTG9naW5Db2RlQqYBCg9jb20uYnl0ZWJhc2UudjFCEEF1dGhTZXJ2aWNlUHJvdG9QAVo0Z2l0aHViLmNvbS9ieXRlYmFzZS9ieXRlYmFzZS9iYWNrZW5kL2dlbmVyYXRlZC1nby92MaICA0JYWKoCC0J5dGViYXNlLlYxygILQnl0ZWJhc2VcVjHiAhdCeXRlYmFzZVxWMVxHUEJNZXRhZGF0YeoCDEJ5dGViYXNlOjpWMWIGcHJvdG8z", [file_google_api_annotations, file_google_api_client, file_google_api_field_behavior, file_google_api_resource, file_google_protobuf_empty, file_v1_annotation, file_v1_setting_service, file_v1_user_service]);
+ fileDesc("ChV2MS9hdXRoX3NlcnZpY2UucHJvdG8SC2J5dGViYXNlLnYxIlUKI0dldEF1dGhlbnRpY2F0aW9uUmVzdHJpY3Rpb25SZXF1ZXN0Ei4KCXdvcmtzcGFjZRgBIAEoCUIb+kEYChZieXRlYmFzZS5jb20vV29ya3NwYWNlImAKEkF1dGhlbnRpY2F0aW9uSW5mbxIWCgl3b3Jrc3BhY2UYASABKAlCA+BBAxIyCgtyZXN0cmljdGlvbhgCIAEoCzIYLmJ5dGViYXNlLnYxLlJlc3RyaWN0aW9uQgPgQQMi+gEKC1Jlc3RyaWN0aW9uEhwKD2Rpc2FsbG93X3NpZ251cBgBIAEoCEID4EEDEiUKGGRpc2FsbG93X3Bhc3N3b3JkX3NpZ25pbhgCIAEoCEID4EEDElsKFHBhc3N3b3JkX3Jlc3RyaWN0aW9uGAMgASgLMjguYnl0ZWJhc2UudjEuV29ya3NwYWNlUHJvZmlsZVNldHRpbmcuUGFzc3dvcmRSZXN0cmljdGlvbkID4EEDEiQKF2FsbG93X2VtYWlsX2NvZGVfc2lnbmluGAQgASgIQgPgQQMSIwoWcGFzc3dvcmRfcmVzZXRfZW5hYmxlZBgFIAEoCEID4EEDIroDCgxMb2dpblJlcXVlc3QSFwoFZW1haWwYASABKAlCCLpIBXIDGP4BEh4KCHBhc3N3b3JkGAIgASgJQgy6SAVyAyiABNDqMAESCwoDd2ViGAMgASgIEhoKCGlkcF9uYW1lGAQgASgJQgi6SAVyAxiAAhI5CgtpZHBfY29udGV4dBgFIAEoCzIkLmJ5dGViYXNlLnYxLklkZW50aXR5UHJvdmlkZXJDb250ZXh0EiIKCG90cF9jb2RlGAYgASgJQgu6SARyAhhA0OowAUgAiAEBEicKDXJlY292ZXJ5X2NvZGUYByABKAlCC7pIBHICGEDQ6jABSAGIAQESKQoObWZhX3RlbXBfdG9rZW4YCCABKAlCDLpIBXIDGIAg0OowAUgCiAEBEiQKCmVtYWlsX2NvZGUYCSABKAlCC7pIBHICGEDQ6jABSAOIAQESIAoJd29ya3NwYWNlGAogASgJQgi6SAVyAxiAAkgEiAEBQgsKCV9vdHBfY29kZUIQCg5fcmVjb3ZlcnlfY29kZUIRCg9fbWZhX3RlbXBfdG9rZW5CDQoLX2VtYWlsX2NvZGVCDAoKX3dvcmtzcGFjZSKsAQoXSWRlbnRpdHlQcm92aWRlckNvbnRleHQSRAoOb2F1dGgyX2NvbnRleHQYASABKAsyKi5ieXRlYmFzZS52MS5PQXV0aDJJZGVudGl0eVByb3ZpZGVyQ29udGV4dEgAEkAKDG9pZGNfY29udGV4dBgCIAEoCzIoLmJ5dGViYXNlLnYxLk9JRENJZGVudGl0eVByb3ZpZGVyQ29udGV4dEgAQgkKB2NvbnRleHQiOwodT0F1dGgySWRlbnRpdHlQcm92aWRlckNvbnRleHQSGgoEY29kZRgBIAEoCUIMukgFcgMYgCDQ6jABIjkKG09JRENJZGVudGl0eVByb3ZpZGVyQ29udGV4dBIaCgRjb2RlGAEgASgJQgy6SAVyAxiAINDqMAEimwEKDUxvZ2luUmVzcG9uc2USEwoFdG9rZW4YASABKAlCBNDqMAESIQoObWZhX3RlbXBfdG9rZW4YAiABKAlCBNDqMAFIAIgBARIeChZyZXF1aXJlX3Jlc2V0X3Bhc3N3b3JkGAMgASgIEh8KBHVzZXIYBCABKAsyES5ieXRlYmFzZS52MS5Vc2VyQhEKD19tZmFfdGVtcF90b2tlbiIPCg1Mb2dvdXRSZXF1ZXN0Ik0KFEV4Y2hhbmdlVG9rZW5SZXF1ZXN0EhwKBXRva2VuGAEgASgJQg26SAZyBBiAgATQ6jABEhcKBWVtYWlsGAIgASgJQgi6SAVyAxj+ASIzChVFeGNoYW5nZVRva2VuUmVzcG9uc2USGgoMYWNjZXNzX3Rva2VuGAEgASgJQgTQ6jABImAKDVNpZ251cFJlcXVlc3QSFwoFZW1haWwYASABKAlCCLpIBXIDGP4BEh0KCHBhc3N3b3JkGAIgASgJQgu6SARyAihI0OowARIXCgV0aXRsZRgDIAEoCUIIukgFcgMYyAEiEAoOUmVmcmVzaFJlcXVlc3QiEQoPUmVmcmVzaFJlc3BvbnNlImYKG1JlcXVlc3RQYXNzd29yZFJlc2V0UmVxdWVzdBIXCgVlbWFpbBgBIAEoCUIIukgFcgMY/gESIAoJd29ya3NwYWNlGAIgASgJQgi6SAVyAxiAAkgAiAEBQgwKCl93b3Jrc3BhY2UibQoUUmVzZXRQYXNzd29yZFJlcXVlc3QSFwoFZW1haWwYASABKAlCCLpIBXIDGP4BEhkKBGNvZGUYAiABKAlCC7pIBHICGEDQ6jABEiEKDG5ld19wYXNzd29yZBgDIAEoCUILukgEcgIoSNDqMAEiZAoZU2VuZEVtYWlsTG9naW5Db2RlUmVxdWVzdBIXCgVlbWFpbBgBIAEoCUIIukgFcgMY/gESIAoJd29ya3NwYWNlGAIgASgJQgi6SAVyAxiAAkgAiAEBQgwKCl93b3Jrc3BhY2Ui7AEKFlN3aXRjaFdvcmtzcGFjZVJlcXVlc3QSGwoJd29ya3NwYWNlGAEgASgJQgi6SAVyAxiAAhILCgN3ZWIYAiABKAgSIgoIb3RwX2NvZGUYAyABKAlCC7pIBHICGEDQ6jABSACIAQESJwoNcmVjb3ZlcnlfY29kZRgEIAEoCUILukgEcgIYQNDqMAFIAYgBARIpCg5tZmFfdGVtcF90b2tlbhgFIAEoCUIMukgFcgMYgCDQ6jABSAKIAQFCCwoJX290cF9jb2RlQhAKDl9yZWNvdmVyeV9jb2RlQhEKD19tZmFfdGVtcF90b2tlbjLCCgoLQXV0aFNlcnZpY2USywEKHEdldEF1dGhlbnRpY2F0aW9uUmVzdHJpY3Rpb24SMC5ieXRlYmFzZS52MS5HZXRBdXRoZW50aWNhdGlvblJlc3RyaWN0aW9uUmVxdWVzdBofLmJ5dGViYXNlLnYxLkF1dGhlbnRpY2F0aW9uSW5mbyJY2kEAgOowAaDqMAGC0+STAkdaLxItL3YxL3t3b3Jrc3BhY2U9d29ya3NwYWNlcy8qfS9hdXRoL3Jlc3RyaWN0aW9uEhQvdjEvYXV0aC9yZXN0cmljdGlvbhJpCgVMb2dpbhIZLmJ5dGViYXNlLnYxLkxvZ2luUmVxdWVzdBoaLmJ5dGViYXNlLnYxLkxvZ2luUmVzcG9uc2UiKYDqMAGY6jABoOowA6jqMAGC0+STAhM6ASoiDi92MS9hdXRoL2xvZ2luEmgKBkxvZ291dBIaLmJ5dGViYXNlLnYxLkxvZ291dFJlcXVlc3QaFi5nb29nbGUucHJvdG9idWYuRW1wdHkiKoDqMAGY6jABoOowA6jqMASC0+STAhQ6ASoiDy92MS9hdXRoL2xvZ291dBKJAQoNRXhjaGFuZ2VUb2tlbhIhLmJ5dGViYXNlLnYxLkV4Y2hhbmdlVG9rZW5SZXF1ZXN0GiIuYnl0ZWJhc2UudjEuRXhjaGFuZ2VUb2tlblJlc3BvbnNlIjGA6jABmOowAaDqMAOo6jABgtPkkwIbOgEqIhYvdjEvYXV0aDpleGNoYW5nZVRva2VuEmwKBlNpZ251cBIaLmJ5dGViYXNlLnYxLlNpZ251cFJlcXVlc3QaGi5ieXRlYmFzZS52MS5Mb2dpblJlc3BvbnNlIiqA6jABmOowAaDqMAOo6jABgtPkkwIUOgEqIg8vdjEvYXV0aC9zaWdudXASbQoHUmVmcmVzaBIbLmJ5dGViYXNlLnYxLlJlZnJlc2hSZXF1ZXN0GhwuYnl0ZWJhc2UudjEuUmVmcmVzaFJlc3BvbnNlIieA6jABoOowA6jqMAGC0+STAhU6ASoiEC92MS9hdXRoL3JlZnJlc2gSgwEKD1N3aXRjaFdvcmtzcGFjZRIjLmJ5dGViYXNlLnYxLlN3aXRjaFdvcmtzcGFjZVJlcXVlc3QaGi5ieXRlYmFzZS52MS5Mb2dpblJlc3BvbnNlIi+Q6jACoOowA6jqMAGC0+STAh06ASoiGC92MS9hdXRoOnN3aXRjaFdvcmtzcGFjZRKSAQoUUmVxdWVzdFBhc3N3b3JkUmVzZXQSKC5ieXRlYmFzZS52MS5SZXF1ZXN0UGFzc3dvcmRSZXNldFJlcXVlc3QaFi5nb29nbGUucHJvdG9idWYuRW1wdHkiOIDqMAGY6jABoOowA6jqMAKC0+STAiI6ASoiHS92MS9hdXRoOnJlcXVlc3RQYXNzd29yZFJlc2V0En0KDVJlc2V0UGFzc3dvcmQSIS5ieXRlYmFzZS52MS5SZXNldFBhc3N3b3JkUmVxdWVzdBoWLmdvb2dsZS5wcm90b2J1Zi5FbXB0eSIxgOowAZjqMAGg6jADqOowAoLT5JMCGzoBKiIWL3YxL2F1dGg6cmVzZXRQYXNzd29yZBKMAQoSU2VuZEVtYWlsTG9naW5Db2RlEiYuYnl0ZWJhc2UudjEuU2VuZEVtYWlsTG9naW5Db2RlUmVxdWVzdBoWLmdvb2dsZS5wcm90b2J1Zi5FbXB0eSI2gOowAZjqMAGg6jADqOowAoLT5JMCIDoBKiIbL3YxL2F1dGg6c2VuZEVtYWlsTG9naW5Db2RlQqYBCg9jb20uYnl0ZWJhc2UudjFCEEF1dGhTZXJ2aWNlUHJvdG9QAVo0Z2l0aHViLmNvbS9ieXRlYmFzZS9ieXRlYmFzZS9iYWNrZW5kL2dlbmVyYXRlZC1nby92MaICA0JYWKoCC0J5dGViYXNlLlYxygILQnl0ZWJhc2VcVjHiAhdCeXRlYmFzZVxWMVxHUEJNZXRhZGF0YeoCDEJ5dGViYXNlOjpWMWIGcHJvdG8z", [file_buf_validate_validate, file_google_api_annotations, file_google_api_client, file_google_api_field_behavior, file_google_api_resource, file_google_protobuf_empty, file_v1_annotation, file_v1_setting_service, file_v1_user_service]);
/**
* Describes the message bytebase.v1.GetAuthenticationRestrictionRequest.
diff --git a/frontend/src/types/proto-es/v1/user_service_pb.js b/frontend/src/types/proto-es/v1/user_service_pb.js
index 0a357b8fca..53ea80afa6 100644
--- a/frontend/src/types/proto-es/v1/user_service_pb.js
+++ b/frontend/src/types/proto-es/v1/user_service_pb.js
@@ -16,7 +16,7 @@ import { file_v1_common } from "./common_pb";
* Describes the file v1/user_service.proto.
*/
export const file_v1_user_service = /*@__PURE__*/
- fileDesc("ChV2MS91c2VyX3NlcnZpY2UucHJvdG8SC2J5dGViYXNlLnYxIjkKDkdldFVzZXJSZXF1ZXN0EicKBG5hbWUYASABKAlCGeBBAvpBEwoRYnl0ZWJhc2UuY29tL1VzZXIiQAoUQmF0Y2hHZXRVc2Vyc1JlcXVlc3QSKAoFbmFtZXMYASADKAlCGeBBAvpBEwoRYnl0ZWJhc2UuY29tL1VzZXIiOQoVQmF0Y2hHZXRVc2Vyc1Jlc3BvbnNlEiAKBXVzZXJzGAEgAygLMhEuYnl0ZWJhc2UudjEuVXNlciJfChBMaXN0VXNlcnNSZXF1ZXN0EhEKCXBhZ2Vfc2l6ZRgBIAEoBRISCgpwYWdlX3Rva2VuGAIgASgJEhQKDHNob3dfZGVsZXRlZBgDIAEoCBIOCgZmaWx0ZXIYBCABKAkiTgoRTGlzdFVzZXJzUmVzcG9uc2USIAoFdXNlcnMYASADKAsyES5ieXRlYmFzZS52MS5Vc2VyEhcKD25leHRfcGFnZV90b2tlbhgCIAEoCSI5ChFDcmVhdGVVc2VyUmVxdWVzdBIkCgR1c2VyGAEgASgLMhEuYnl0ZWJhc2UudjEuVXNlckID4EECIvIBChFVcGRhdGVVc2VyUmVxdWVzdBIkCgR1c2VyGAEgASgLMhEuYnl0ZWJhc2UudjEuVXNlckID4EECEi8KC3VwZGF0ZV9tYXNrGAIgASgLMhouZ29vZ2xlLnByb3RvYnVmLkZpZWxkTWFzaxIbCghvdHBfY29kZRgDIAEoCUIE0OowAUgAiAEBEiIKGnJlZ2VuZXJhdGVfdGVtcF9tZmFfc2VjcmV0GAQgASgIEiEKGXJlZ2VuZXJhdGVfcmVjb3ZlcnlfY29kZXMYBSABKAgSFQoNYWxsb3dfbWlzc2luZxgGIAEoCEILCglfb3RwX2NvZGUiPAoRRGVsZXRlVXNlclJlcXVlc3QSJwoEbmFtZRgBIAEoCUIZ4EEC+kETChFieXRlYmFzZS5jb20vVXNlciI+ChNVbmRlbGV0ZVVzZXJSZXF1ZXN0EicKBG5hbWUYASABKAlCGeBBAvpBEwoRYnl0ZWJhc2UuY29tL1VzZXIiUQoSVXBkYXRlRW1haWxSZXF1ZXN0EicKBG5hbWUYASABKAlCGeBBAvpBEwoRYnl0ZWJhc2UuY29tL1VzZXISEgoFZW1haWwYAiABKAlCA+BBAiLZBAoEVXNlchIRCgRuYW1lGAEgASgJQgPgQQMSIQoFc3RhdGUYAiABKA4yEi5ieXRlYmFzZS52MS5TdGF0ZRINCgVlbWFpbBgDIAEoCRIXCgV0aXRsZRgEIAEoCUIIukgFcgMYyAESGQoIcGFzc3dvcmQYBiABKAlCB+BBBNDqMAESEwoLbWZhX2VuYWJsZWQYCCABKAgSHQoPdGVtcF9vdHBfc2VjcmV0GAkgASgJQgTQ6jABEiEKE3RlbXBfcmVjb3ZlcnlfY29kZXMYCiADKAlCBNDqMAESQAocdGVtcF9vdHBfc2VjcmV0X2NyZWF0ZWRfdGltZRgLIAEoCzIaLmdvb2dsZS5wcm90b2J1Zi5UaW1lc3RhbXASEwoFcGhvbmUYDCABKAlCBNDqMAISMAoHcHJvZmlsZRgNIAEoCzIZLmJ5dGViYXNlLnYxLlVzZXIuUHJvZmlsZUIE0OowAhIXCgZncm91cHMYDiADKAlCB+BBA9DqMAISFgoJd29ya3NwYWNlGBAgASgJQgPgQQMajQEKB1Byb2ZpbGUSMwoPbGFzdF9sb2dpbl90aW1lGAEgASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcBI9ChlsYXN0X2NoYW5nZV9wYXNzd29yZF90aW1lGAIgASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcBIOCgZzb3VyY2UYAyABKAk6JepBIgoRYnl0ZWJhc2UuY29tL1VzZXISDXVzZXJzL3tlbWFpbH1KBAgFEAZKBAgHEAhKBAgPEBAyqAkKC1VzZXJTZXJ2aWNlEngKB0dldFVzZXISGy5ieXRlYmFzZS52MS5HZXRVc2VyUmVxdWVzdBoRLmJ5dGViYXNlLnYxLlVzZXIiPdpBBG5hbWWK6jAMYmIudXNlcnMuZ2V0kOowAaDqMASo6jAJgtPkkwIUEhIvdjEve25hbWU9dXNlcnMvKn0SjgEKDUJhdGNoR2V0VXNlcnMSIS5ieXRlYmFzZS52MS5CYXRjaEdldFVzZXJzUmVxdWVzdBoiLmJ5dGViYXNlLnYxLkJhdGNoR2V0VXNlcnNSZXNwb25zZSI2iuowDGJiLnVzZXJzLmdldJDqMAGg6jAEqOowCYLT5JMCFBISL3YxL3VzZXJzOmJhdGNoR2V0El0KDkdldEN1cnJlbnRVc2VyEhYuZ29vZ2xlLnByb3RvYnVmLkVtcHR5GhEuYnl0ZWJhc2UudjEuVXNlciIggOowAZDqMAKg6jABgtPkkwIOEgwvdjEvdXNlcnMvbWUSgwEKCUxpc3RVc2VycxIdLmJ5dGViYXNlLnYxLkxpc3RVc2Vyc1JlcXVlc3QaHi5ieXRlYmFzZS52MS5MaXN0VXNlcnNSZXNwb25zZSI32kEGcGFyZW50iuowDWJiLnVzZXJzLmxpc3SQ6jABoOowBKjqMAmC0+STAgsSCS92MS91c2VycxKCAQoKQ3JlYXRlVXNlchIeLmJ5dGViYXNlLnYxLkNyZWF0ZVVzZXJSZXF1ZXN0GhEuYnl0ZWJhc2UudjEuVXNlciJB2kEEdXNlcorqMA9iYi51c2Vycy5jcmVhdGWQ6jABmOowAaDqMAOo6jAGgtPkkwIROgR1c2VyIgkvdjEvdXNlcnMSiQEKClVwZGF0ZVVzZXISHi5ieXRlYmFzZS52MS5VcGRhdGVVc2VyUmVxdWVzdBoRLmJ5dGViYXNlLnYxLlVzZXIiSNpBEHVzZXIsdXBkYXRlX21hc2uQ6jACmOowAaDqMAOo6jADgtPkkwIfOgR1c2VyMhcvdjEve3VzZXIubmFtZT11c2Vycy8qfRJ3CgpEZWxldGVVc2VyEh4uYnl0ZWJhc2UudjEuRGVsZXRlVXNlclJlcXVlc3QaFi5nb29nbGUucHJvdG9idWYuRW1wdHkiMdpBBG5hbWWQ6jACmOowAaDqMASo6jAJgtPkkwIUKhIvdjEve25hbWU9dXNlcnMvKn0SewoMVW5kZWxldGVVc2VyEiAuYnl0ZWJhc2UudjEuVW5kZWxldGVVc2VyUmVxdWVzdBoRLmJ5dGViYXNlLnYxLlVzZXIiNpDqMAKY6jABoOowBKjqMAmC0+STAiA6ASoiGy92MS97bmFtZT11c2Vycy8qfTp1bmRlbGV0ZRKhAQoLVXBkYXRlRW1haWwSHy5ieXRlYmFzZS52MS5VcGRhdGVFbWFpbFJlcXVlc3QaES5ieXRlYmFzZS52MS5Vc2VyIl7aQQpuYW1lLGVtYWlsiuowFGJiLnVzZXJzLnVwZGF0ZUVtYWlskOowAZjqMAGg6jADqOowBoLT5JMCIzoBKiIeL3YxL3tuYW1lPXVzZXJzLyp9OnVwZGF0ZUVtYWlsQqYBCg9jb20uYnl0ZWJhc2UudjFCEFVzZXJTZXJ2aWNlUHJvdG9QAVo0Z2l0aHViLmNvbS9ieXRlYmFzZS9ieXRlYmFzZS9iYWNrZW5kL2dlbmVyYXRlZC1nby92MaICA0JYWKoCC0J5dGViYXNlLlYxygILQnl0ZWJhc2VcVjHiAhdCeXRlYmFzZVxWMVxHUEJNZXRhZGF0YeoCDEJ5dGViYXNlOjpWMWIGcHJvdG8z", [file_buf_validate_validate, file_google_api_annotations, file_google_api_client, file_google_api_field_behavior, file_google_api_resource, file_google_protobuf_empty, file_google_protobuf_field_mask, file_google_protobuf_timestamp, file_v1_annotation, file_v1_common]);
+ fileDesc("ChV2MS91c2VyX3NlcnZpY2UucHJvdG8SC2J5dGViYXNlLnYxIjkKDkdldFVzZXJSZXF1ZXN0EicKBG5hbWUYASABKAlCGeBBAvpBEwoRYnl0ZWJhc2UuY29tL1VzZXIiQAoUQmF0Y2hHZXRVc2Vyc1JlcXVlc3QSKAoFbmFtZXMYASADKAlCGeBBAvpBEwoRYnl0ZWJhc2UuY29tL1VzZXIiOQoVQmF0Y2hHZXRVc2Vyc1Jlc3BvbnNlEiAKBXVzZXJzGAEgAygLMhEuYnl0ZWJhc2UudjEuVXNlciJfChBMaXN0VXNlcnNSZXF1ZXN0EhEKCXBhZ2Vfc2l6ZRgBIAEoBRISCgpwYWdlX3Rva2VuGAIgASgJEhQKDHNob3dfZGVsZXRlZBgDIAEoCBIOCgZmaWx0ZXIYBCABKAkiTgoRTGlzdFVzZXJzUmVzcG9uc2USIAoFdXNlcnMYASADKAsyES5ieXRlYmFzZS52MS5Vc2VyEhcKD25leHRfcGFnZV90b2tlbhgCIAEoCSI5ChFDcmVhdGVVc2VyUmVxdWVzdBIkCgR1c2VyGAEgASgLMhEuYnl0ZWJhc2UudjEuVXNlckID4EECIvIBChFVcGRhdGVVc2VyUmVxdWVzdBIkCgR1c2VyGAEgASgLMhEuYnl0ZWJhc2UudjEuVXNlckID4EECEi8KC3VwZGF0ZV9tYXNrGAIgASgLMhouZ29vZ2xlLnByb3RvYnVmLkZpZWxkTWFzaxIbCghvdHBfY29kZRgDIAEoCUIE0OowAUgAiAEBEiIKGnJlZ2VuZXJhdGVfdGVtcF9tZmFfc2VjcmV0GAQgASgIEiEKGXJlZ2VuZXJhdGVfcmVjb3ZlcnlfY29kZXMYBSABKAgSFQoNYWxsb3dfbWlzc2luZxgGIAEoCEILCglfb3RwX2NvZGUiPAoRRGVsZXRlVXNlclJlcXVlc3QSJwoEbmFtZRgBIAEoCUIZ4EEC+kETChFieXRlYmFzZS5jb20vVXNlciI+ChNVbmRlbGV0ZVVzZXJSZXF1ZXN0EicKBG5hbWUYASABKAlCGeBBAvpBEwoRYnl0ZWJhc2UuY29tL1VzZXIiWQoSVXBkYXRlRW1haWxSZXF1ZXN0EicKBG5hbWUYASABKAlCGeBBAvpBEwoRYnl0ZWJhc2UuY29tL1VzZXISGgoFZW1haWwYAiABKAlCC+BBArpIBXIDGP4BIuoECgRVc2VyEhEKBG5hbWUYASABKAlCA+BBAxIhCgVzdGF0ZRgCIAEoDjISLmJ5dGViYXNlLnYxLlN0YXRlEhcKBWVtYWlsGAMgASgJQgi6SAVyAxj+ARIXCgV0aXRsZRgEIAEoCUIIukgFcgMYyAESIAoIcGFzc3dvcmQYBiABKAlCDuBBBLpIBHICKEjQ6jABEhMKC21mYV9lbmFibGVkGAggASgIEh0KD3RlbXBfb3RwX3NlY3JldBgJIAEoCUIE0OowARIhChN0ZW1wX3JlY292ZXJ5X2NvZGVzGAogAygJQgTQ6jABEkAKHHRlbXBfb3RwX3NlY3JldF9jcmVhdGVkX3RpbWUYCyABKAsyGi5nb29nbGUucHJvdG9idWYuVGltZXN0YW1wEhMKBXBob25lGAwgASgJQgTQ6jACEjAKB3Byb2ZpbGUYDSABKAsyGS5ieXRlYmFzZS52MS5Vc2VyLlByb2ZpbGVCBNDqMAISFwoGZ3JvdXBzGA4gAygJQgfgQQPQ6jACEhYKCXdvcmtzcGFjZRgQIAEoCUID4EEDGo0BCgdQcm9maWxlEjMKD2xhc3RfbG9naW5fdGltZRgBIAEoCzIaLmdvb2dsZS5wcm90b2J1Zi5UaW1lc3RhbXASPQoZbGFzdF9jaGFuZ2VfcGFzc3dvcmRfdGltZRgCIAEoCzIaLmdvb2dsZS5wcm90b2J1Zi5UaW1lc3RhbXASDgoGc291cmNlGAMgASgJOiXqQSIKEWJ5dGViYXNlLmNvbS9Vc2VyEg11c2Vycy97ZW1haWx9SgQIBRAGSgQIBxAISgQIDxAQMqgJCgtVc2VyU2VydmljZRJ4CgdHZXRVc2VyEhsuYnl0ZWJhc2UudjEuR2V0VXNlclJlcXVlc3QaES5ieXRlYmFzZS52MS5Vc2VyIj3aQQRuYW1liuowDGJiLnVzZXJzLmdldJDqMAGg6jAEqOowCYLT5JMCFBISL3YxL3tuYW1lPXVzZXJzLyp9Eo4BCg1CYXRjaEdldFVzZXJzEiEuYnl0ZWJhc2UudjEuQmF0Y2hHZXRVc2Vyc1JlcXVlc3QaIi5ieXRlYmFzZS52MS5CYXRjaEdldFVzZXJzUmVzcG9uc2UiNorqMAxiYi51c2Vycy5nZXSQ6jABoOowBKjqMAmC0+STAhQSEi92MS91c2VyczpiYXRjaEdldBJdCg5HZXRDdXJyZW50VXNlchIWLmdvb2dsZS5wcm90b2J1Zi5FbXB0eRoRLmJ5dGViYXNlLnYxLlVzZXIiIIDqMAGQ6jACoOowAYLT5JMCDhIML3YxL3VzZXJzL21lEoMBCglMaXN0VXNlcnMSHS5ieXRlYmFzZS52MS5MaXN0VXNlcnNSZXF1ZXN0Gh4uYnl0ZWJhc2UudjEuTGlzdFVzZXJzUmVzcG9uc2UiN9pBBnBhcmVudIrqMA1iYi51c2Vycy5saXN0kOowAaDqMASo6jAJgtPkkwILEgkvdjEvdXNlcnMSggEKCkNyZWF0ZVVzZXISHi5ieXRlYmFzZS52MS5DcmVhdGVVc2VyUmVxdWVzdBoRLmJ5dGViYXNlLnYxLlVzZXIiQdpBBHVzZXKK6jAPYmIudXNlcnMuY3JlYXRlkOowAZjqMAGg6jADqOowBoLT5JMCEToEdXNlciIJL3YxL3VzZXJzEokBCgpVcGRhdGVVc2VyEh4uYnl0ZWJhc2UudjEuVXBkYXRlVXNlclJlcXVlc3QaES5ieXRlYmFzZS52MS5Vc2VyIkjaQRB1c2VyLHVwZGF0ZV9tYXNrkOowApjqMAGg6jADqOowA4LT5JMCHzoEdXNlcjIXL3YxL3t1c2VyLm5hbWU9dXNlcnMvKn0SdwoKRGVsZXRlVXNlchIeLmJ5dGViYXNlLnYxLkRlbGV0ZVVzZXJSZXF1ZXN0GhYuZ29vZ2xlLnByb3RvYnVmLkVtcHR5IjHaQQRuYW1lkOowApjqMAGg6jAEqOowCYLT5JMCFCoSL3YxL3tuYW1lPXVzZXJzLyp9EnsKDFVuZGVsZXRlVXNlchIgLmJ5dGViYXNlLnYxLlVuZGVsZXRlVXNlclJlcXVlc3QaES5ieXRlYmFzZS52MS5Vc2VyIjaQ6jACmOowAaDqMASo6jAJgtPkkwIgOgEqIhsvdjEve25hbWU9dXNlcnMvKn06dW5kZWxldGUSoQEKC1VwZGF0ZUVtYWlsEh8uYnl0ZWJhc2UudjEuVXBkYXRlRW1haWxSZXF1ZXN0GhEuYnl0ZWJhc2UudjEuVXNlciJe2kEKbmFtZSxlbWFpbIrqMBRiYi51c2Vycy51cGRhdGVFbWFpbJDqMAGY6jABoOowA6jqMAaC0+STAiM6ASoiHi92MS97bmFtZT11c2Vycy8qfTp1cGRhdGVFbWFpbEKmAQoPY29tLmJ5dGViYXNlLnYxQhBVc2VyU2VydmljZVByb3RvUAFaNGdpdGh1Yi5jb20vYnl0ZWJhc2UvYnl0ZWJhc2UvYmFja2VuZC9nZW5lcmF0ZWQtZ28vdjGiAgNCWFiqAgtCeXRlYmFzZS5WMcoCC0J5dGViYXNlXFYx4gIXQnl0ZWJhc2VcVjFcR1BCTWV0YWRhdGHqAgxCeXRlYmFzZTo6VjFiBnByb3RvMw", [file_buf_validate_validate, file_google_api_annotations, file_google_api_client, file_google_api_field_behavior, file_google_api_resource, file_google_protobuf_empty, file_google_protobuf_field_mask, file_google_protobuf_timestamp, file_v1_annotation, file_v1_common]);
/**
* Describes the message bytebase.v1.GetUserRequest.
diff --git a/proto/gen/grpc-doc/openapi.yaml b/proto/gen/grpc-doc/openapi.yaml
index b542612aa1..7628c9818e 100644
--- a/proto/gen/grpc-doc/openapi.yaml
+++ b/proto/gen/grpc-doc/openapi.yaml
@@ -17226,6 +17226,7 @@ paths:
email:
type: string
title: email
+ maxLength: 254
description: The new email address.
title: UpdateEmailRequest
required:
@@ -22603,10 +22604,12 @@ components:
token:
type: string
title: token
+ maxLength: 65536
description: External OIDC token (JWT) from CI/CD platform.
email:
type: string
title: email
+ maxLength: 254
description: |-
Workload Identity email for identifying which identity to authenticate as.
Format: {name}@workload.bytebase.com
@@ -25922,11 +25925,19 @@ components:
email:
type: string
title: email
- description: User's email address.
+ maxLength: 254
+ description: |-
+ User's email address.
+ Bounded so an oversized identity is refused at the edge before any
+ handler runs; the login-attempt lockout keys rows by this value.
password:
type: string
title: password
- description: User's password for authentication.
+ description: |
+ User's password for authentication. Bounded for abuse only: LDAP
+ directories may accept passwords beyond bcrypt's 72-byte limit, and the
+ local-password path rejects longer inputs itself.
+ string.max_bytes = 512
web:
type: boolean
title: web
@@ -25936,6 +25947,7 @@ components:
idpName:
type: string
title: idp_name
+ maxLength: 256
description: |-
The name of the identity provider.
Format: idps/{idp}
@@ -25948,24 +25960,28 @@ components:
- string
- "null"
title: otp_code
+ maxLength: 64
description: The otp_code is used to verify the user's identity by MFA.
recoveryCode:
type:
- string
- "null"
title: recovery_code
+ maxLength: 64
description: The recovery_code is used to recovery the user's identity with MFA.
mfaTempToken:
type:
- string
- "null"
title: mfa_temp_token
+ maxLength: 4096
description: The mfa_temp_token is used to verify the user's identity by MFA.
emailCode:
type:
- string
- "null"
title: email_code
+ maxLength: 64
description: |-
6-digit code from email for passwordless login/signup.
Pairs with `email`. Mutually exclusive with `password` and `idp_name`.
@@ -25974,6 +25990,7 @@ components:
- string
- "null"
title: workspace
+ maxLength: 256
description: |-
Preferred workspace to land in after login. If the user is a member of this
workspace, the token is issued for it; otherwise falls back to the default
@@ -26593,6 +26610,7 @@ components:
code:
type: string
title: code
+ maxLength: 4096
description: Authorization code from OAuth2 provider.
title: OAuth2IdentityProviderContext
additionalProperties: false
@@ -26657,6 +26675,7 @@ components:
code:
type: string
title: code
+ maxLength: 4096
description: Authorization code from OIDC provider.
title: OIDCIdentityProviderContext
additionalProperties: false
@@ -28346,12 +28365,17 @@ components:
email:
type: string
title: email
- description: The email address of the account to reset.
+ maxLength: 254
+ description: |-
+ The email address of the account to reset.
+ Bounded so an oversized identity is refused at the edge before any
+ handler runs; the login-attempt lockout keys rows by this value.
workspace:
type:
- string
- "null"
title: workspace
+ maxLength: 256
description: |-
Optional workspace context captured at send time, used to locate the EMAIL setting,
and later (at verify time) for signup gate checks and workspace assignment.
@@ -28365,15 +28389,22 @@ components:
email:
type: string
title: email
- description: The email address of the account.
+ maxLength: 254
+ description: |-
+ The email address of the account.
+ Bounded so an oversized identity is refused at the edge before any
+ handler runs; the login-attempt lockout keys rows by this value.
code:
type: string
title: code
+ maxLength: 64
description: The 6-digit code from the reset email.
newPassword:
type: string
title: new_password
- description: The new password to set.
+ description: |
+ The new password to set.
+ string.max_bytes = 72
title: ResetPasswordRequest
additionalProperties: false
bytebase.v1.Restriction:
@@ -29939,12 +29970,17 @@ components:
email:
type: string
title: email
- description: The email address to send the code to.
+ maxLength: 254
+ description: |-
+ The email address to send the code to.
+ Bounded so an oversized identity is refused at the edge before any
+ handler runs; the login-attempt lockout keys rows by this value.
workspace:
type:
- string
- "null"
title: workspace
+ maxLength: 256
description: |-
Optional workspace context captured at send time, used to locate the EMAIL setting,
and later (at verify time) for signup gate checks and workspace assignment.
@@ -30243,14 +30279,21 @@ components:
email:
type: string
title: email
- description: The email for the new account.
+ maxLength: 254
+ description: |-
+ The email for the new account.
+ Bounded so an oversized identity is refused at the edge before any
+ handler runs; the login-attempt lockout keys rows by this value.
password:
type: string
title: password
- description: The password for the new account.
+ description: |
+ The password for the new account.
+ string.max_bytes = 72
title:
type: string
title: title
+ maxLength: 200
description: The display name of the user.
title: SignupRequest
additionalProperties: false
@@ -30522,6 +30565,7 @@ components:
workspace:
type: string
title: workspace
+ maxLength: 256
description: |-
The target workspace to switch to.
Format: workspaces/{workspace}
@@ -30534,18 +30578,21 @@ components:
- string
- "null"
title: otp_code
+ maxLength: 64
description: OTP code for MFA verification. Required if the target workspace enforces MFA.
recoveryCode:
type:
- string
- "null"
title: recovery_code
+ maxLength: 64
description: Recovery code for MFA verification (alternative to otp_code).
mfaTempToken:
type:
- string
- "null"
title: mfa_temp_token
+ maxLength: 4096
description: Temporary MFA token from a previous SwitchWorkspace call that returned mfa_temp_token.
title: SwitchWorkspaceRequest
additionalProperties: false
@@ -32038,6 +32085,7 @@ components:
email:
type: string
title: email
+ maxLength: 254
description: The new email address.
title: UpdateEmailRequest
required:
@@ -32535,6 +32583,7 @@ components:
email:
type: string
title: email
+ maxLength: 254
description: The email address of the user, used for login and notifications.
title:
type: string
@@ -32544,7 +32593,9 @@ components:
password:
type: string
title: password
- description: The password for authentication. Only used during user creation or password updates.
+ description: |
+ The password for authentication. Only used during user creation or password updates.
+ string.max_bytes = 72
writeOnly: true
mfaEnabled:
type: boolean
diff --git a/proto/gen/grpc-doc/store/README.md b/proto/gen/grpc-doc/store/README.md
index 97e2afa32a..04f5373630 100644
--- a/proto/gen/grpc-doc/store/README.md
+++ b/proto/gen/grpc-doc/store/README.md
@@ -44,6 +44,7 @@
- [store/auth.proto](#store_auth-proto)
- [EmailVerificationCodePurpose](#bytebase-store-EmailVerificationCodePurpose)
+ - [LoginAttemptKind](#bytebase-store-LoginAttemptKind)
- [store/changelog.proto](#store_changelog-proto)
- [ChangelogPayload](#bytebase-store-ChangelogPayload)
@@ -942,6 +943,21 @@ Stored as the enum name string in email_verification_code.purpose column.
| PASSWORD_RESET | 2 | |
+
+<a name="bytebase-store-LoginAttemptKind"></a>
+
+### LoginAttemptKind
+LoginAttemptKind names which credential&#39;s attempt limit a login_attempt row
+tracks. Stored as the enum name string in login_attempt.kind column.
+
+| Name | Number | Description |
+| ---- | ------ | ----------- |
+| LOGIN_ATTEMPT_KIND_UNSPECIFIED | 0 | |
+| PASSWORD | 1 | |
+| EMAIL_CODE | 2 | |
+| MFA | 3 | |
+
+
diff --git a/proto/gen/grpc-doc/store/index.html b/proto/gen/grpc-doc/store/index.html
index df23476d83..78288ff7a4 100644
--- a/proto/gen/grpc-doc/store/index.html
+++ b/proto/gen/grpc-doc/store/index.html
@@ -334,6 +334,10 @@
<a href="#bytebase.store.EmailVerificationCodePurpose"><span class="badge">E</span>EmailVerificationCodePurpose</a>
</li>
+ <li>
+ <a href="#bytebase.store.LoginAttemptKind"><span class="badge">E</span>LoginAttemptKind</a>
+ </li>
+
</ul>
@@ -3143,6 +3147,41 @@ This information is not authenticated and should be treated accordingly. </p></t
</tbody>
</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>
+ <table class="enum-table">
+ <thead>
+ <tr><td>Name</td><td>Number</td><td>Description</td></tr>
+ </thead>
+ <tbody>
+
+ <tr>
+ <td>LOGIN_ATTEMPT_KIND_UNSPECIFIED</td>
+ <td>0</td>
+ <td><p></p></td>
+ </tr>
+
+ <tr>
+ <td>PASSWORD</td>
+ <td>1</td>
+ <td><p></p></td>
+ </tr>
+
+ <tr>
+ <td>EMAIL_CODE</td>
+ <td>2</td>
+ <td><p></p></td>
+ </tr>
+
+ <tr>
+ <td>MFA</td>
+ <td>3</td>
+ <td><p></p></td>
+ </tr>
+
+ </tbody>
+ </table>
+
diff --git a/proto/gen/grpc-doc/v1/README.md b/proto/gen/grpc-doc/v1/README.md
index 0266519f83..a90508415e 100644
--- a/proto/gen/grpc-doc/v1/README.md
+++ b/proto/gen/grpc-doc/v1/README.md
@@ -5716,8 +5716,8 @@ Context for identity provider authentication.
| Field | Type | Label | Description |
| ----- | ---- | ----- | ----------- |
-| email | [string](#string) | | User&#39;s email address. |
-| password | [string](#string) | | User&#39;s password for authentication. |
+| email | [string](#string) | | User&#39;s email address. Bounded so an oversized identity is refused at the edge before any handler runs; the login-attempt lockout keys rows by this value. |
+| password | [string](#string) | | User&#39;s password for authentication. Bounded for abuse only: LDAP directories may accept passwords beyond bcrypt&#39;s 72-byte limit, and the local-password path rejects longer inputs itself. |
| web | [bool](#bool) | | If true, sets access token and refresh token as HTTP-only cookies instead of returning the token in the response body. Use for browser-based clients. |
| idp_name | [string](#string) | | The name of the identity provider. Format: idps/{idp} |
| idp_context | [IdentityProviderContext](#bytebase-v1-IdentityProviderContext) | | The idp_context is used to get the user information from identity provider. |
@@ -5818,7 +5818,7 @@ Response from refreshing the access token.
| Field | Type | Label | Description |
| ----- | ---- | ----- | ----------- |
-| email | [string](#string) | | The email address of the account to reset. |
+| email | [string](#string) | | The email address of the account to reset. Bounded so an oversized identity is refused at the edge before any handler runs; the login-attempt lockout keys rows by this value. |
| workspace | [string](#string) | optional | Optional workspace context captured at send time, used to locate the EMAIL setting, and later (at verify time) for signup gate checks and workspace assignment. Unset for SaaS brand-new signup (no workspace exists yet). Format: workspaces/{workspace} |
@@ -5834,7 +5834,7 @@ Response from refreshing the access token.
| Field | Type | Label | Description |
| ----- | ---- | ----- | ----------- |
-| email | [string](#string) | | The email address of the account. |
+| email | [string](#string) | | The email address of the account. Bounded so an oversized identity is refused at the edge before any handler runs; the login-attempt lockout keys rows by this value. |
| code | [string](#string) | | The 6-digit code from the reset email. |
| new_password | [string](#string) | | The new password to set. |
@@ -5870,7 +5870,7 @@ Response from refreshing the access token.
| Field | Type | Label | Description |
| ----- | ---- | ----- | ----------- |
-| email | [string](#string) | | The email address to send the code to. |
+| email | [string](#string) | | The email address to send the code to. Bounded so an oversized identity is refused at the edge before any handler runs; the login-attempt lockout keys rows by this value. |
| workspace | [string](#string) | optional | Optional workspace context captured at send time, used to locate the EMAIL setting, and later (at verify time) for signup gate checks and workspace assignment. Unset for SaaS brand-new signup (no workspace exists yet). Format: workspaces/{workspace} |
@@ -5886,7 +5886,7 @@ Response from refreshing the access token.
| Field | Type | Label | Description |
| ----- | ---- | ----- | ----------- |
-| email | [string](#string) | | The email for the new account. |
+| email | [string](#string) | | The email for the new account. Bounded so an oversized identity is refused at the edge before any handler runs; the login-attempt lockout keys rows by this value. |
| password | [string](#string) | | The password for the new account. |
| title | [string](#string) | | The display name of the user. |
diff --git a/proto/gen/grpc-doc/v1/index.html b/proto/gen/grpc-doc/v1/index.html
index 432dd4f0d6..ec0c545d05 100644
--- a/proto/gen/grpc-doc/v1/index.html
+++ b/proto/gen/grpc-doc/v1/index.html
@@ -16359,14 +16359,18 @@ the deployment-level defaults. </p></td>
<td>email</td>
<td><a href="#string">string</a></td>
<td></td>
- <td><p>User&#39;s email address. </p></td>
+ <td><p>User&#39;s email address.
+Bounded so an oversized identity is refused at the edge before any
+handler runs; the login-attempt lockout keys rows by this value. </p></td>
</tr>
<tr>
<td>password</td>
<td><a href="#string">string</a></td>
<td></td>
- <td><p>User&#39;s password for authentication. </p></td>
+ <td><p>User&#39;s password for authentication. Bounded for abuse only: LDAP
+directories may accept passwords beyond bcrypt&#39;s 72-byte limit, and the
+local-password path rejects longer inputs itself. </p></td>
</tr>
<tr>
@@ -16568,7 +16572,9 @@ Only returned when web=false. For web=true, the token is set as an HTTP-only coo
<td>email</td>
<td><a href="#string">string</a></td>
<td></td>
- <td><p>The email address of the account to reset. </p></td>
+ <td><p>The email address of the account to reset.
+Bounded so an oversized identity is refused at the edge before any
+handler runs; the login-attempt lockout keys rows by this value. </p></td>
</tr>
<tr>
@@ -16602,7 +16608,9 @@ Format: workspaces/{workspace} </p></td>
<td>email</td>
<td><a href="#string">string</a></td>
<td></td>
- <td><p>The email address of the account. </p></td>
+ <td><p>The email address of the account.
+Bounded so an oversized identity is refused at the edge before any
+handler runs; the login-attempt lockout keys rows by this value. </p></td>
</tr>
<tr>
@@ -16693,7 +16701,9 @@ True when the workspace (or deployment) has an email setting configured. </p></t
<td>email</td>
<td><a href="#string">string</a></td>
<td></td>
- <td><p>The email address to send the code to. </p></td>
+ <td><p>The email address to send the code to.
+Bounded so an oversized identity is refused at the edge before any
+handler runs; the login-attempt lockout keys rows by this value. </p></td>
</tr>
<tr>
@@ -16727,7 +16737,9 @@ Format: workspaces/{workspace} </p></td>
<td>email</td>
<td><a href="#string">string</a></td>
<td></td>
- <td><p>The email for the new account. </p></td>
+ <td><p>The email for the new account.
+Bounded so an oversized identity is refused at the edge before any
+handler runs; the login-attempt lockout keys rows by this value. </p></td>
</tr>
<tr>
diff --git a/proto/store/store/auth.proto b/proto/store/store/auth.proto
index e8b354a5fa..3acff6fc75 100644
--- a/proto/store/store/auth.proto
+++ b/proto/store/store/auth.proto
@@ -11,3 +11,12 @@ enum EmailVerificationCodePurpose {
LOGIN = 1;
PASSWORD_RESET = 2;
}
+
+// LoginAttemptKind names which credential's attempt limit a login_attempt row
+// tracks. Stored as the enum name string in login_attempt.kind column.
+enum LoginAttemptKind {
+ LOGIN_ATTEMPT_KIND_UNSPECIFIED = 0;
+ PASSWORD = 1;
+ EMAIL_CODE = 2;
+ MFA = 3;
+}
diff --git a/proto/v1/v1/auth_service.proto b/proto/v1/v1/auth_service.proto
index 4d08de0b32..5e8d423a29 100644
--- a/proto/v1/v1/auth_service.proto
+++ b/proto/v1/v1/auth_service.proto
@@ -2,6 +2,7 @@ syntax = "proto3";
package bytebase.v1;
+import "buf/validate/validate.proto";
import "google/api/annotations.proto";
import "google/api/client.proto";
import "google/api/field_behavior.proto";
@@ -189,10 +190,17 @@ message Restriction {
message LoginRequest {
// User's email address.
- string email = 1;
-
- // User's password for authentication.
- string password = 2 [(bytebase.v1.audit_behavior) = SENSITIVE];
+ // Bounded so an oversized identity is refused at the edge before any
+ // handler runs; the login-attempt lockout keys rows by this value.
+ string email = 1 [(buf.validate.field).string.max_len = 254];
+
+ // User's password for authentication. Bounded for abuse only: LDAP
+ // directories may accept passwords beyond bcrypt's 72-byte limit, and the
+ // local-password path rejects longer inputs itself.
+ string password = 2 [
+ (bytebase.v1.audit_behavior) = SENSITIVE,
+ (buf.validate.field).string.max_bytes = 512
+ ];
// If true, sets access token and refresh token as HTTP-only cookies instead of
// returning the token in the response body. Use for browser-based clients.
@@ -200,30 +208,42 @@ message LoginRequest {
// The name of the identity provider.
// Format: idps/{idp}
- string idp_name = 4;
+ string idp_name = 4 [(buf.validate.field).string.max_len = 256];
// The idp_context is used to get the user information from identity provider.
IdentityProviderContext idp_context = 5;
// The otp_code is used to verify the user's identity by MFA.
- optional string otp_code = 6 [(bytebase.v1.audit_behavior) = SENSITIVE];
+ optional string otp_code = 6 [
+ (bytebase.v1.audit_behavior) = SENSITIVE,
+ (buf.validate.field).string.max_len = 64
+ ];
// The recovery_code is used to recovery the user's identity with MFA.
- optional string recovery_code = 7 [(bytebase.v1.audit_behavior) = SENSITIVE];
+ optional string recovery_code = 7 [
+ (bytebase.v1.audit_behavior) = SENSITIVE,
+ (buf.validate.field).string.max_len = 64
+ ];
// The mfa_temp_token is used to verify the user's identity by MFA.
- optional string mfa_temp_token = 8 [(bytebase.v1.audit_behavior) = SENSITIVE];
+ optional string mfa_temp_token = 8 [
+ (bytebase.v1.audit_behavior) = SENSITIVE,
+ (buf.validate.field).string.max_len = 4096
+ ];
// 6-digit code from email for passwordless login/signup.
// Pairs with `email`. Mutually exclusive with `password` and `idp_name`.
- optional string email_code = 9 [(bytebase.v1.audit_behavior) = SENSITIVE];
+ optional string email_code = 9 [
+ (bytebase.v1.audit_behavior) = SENSITIVE,
+ (buf.validate.field).string.max_len = 64
+ ];
// Preferred workspace to land in after login. If the user is a member of this
// workspace, the token is issued for it; otherwise falls back to the default
// resolution (last login workspace → first membership). Typically populated
// from the ?workspace= query parameter in invite links.
// Format: workspaces/{workspace}
- optional string workspace = 10;
+ optional string workspace = 10 [(buf.validate.field).string.max_len = 256];
}
// Context for identity provider authentication.
@@ -239,13 +259,19 @@ message IdentityProviderContext {
// OAuth2 authentication context.
message OAuth2IdentityProviderContext {
// Authorization code from OAuth2 provider.
- string code = 1 [(bytebase.v1.audit_behavior) = SENSITIVE];
+ string code = 1 [
+ (bytebase.v1.audit_behavior) = SENSITIVE,
+ (buf.validate.field).string.max_len = 4096
+ ];
}
// OpenID Connect authentication context.
message OIDCIdentityProviderContext {
// Authorization code from OIDC provider.
- string code = 1 [(bytebase.v1.audit_behavior) = SENSITIVE];
+ string code = 1 [
+ (bytebase.v1.audit_behavior) = SENSITIVE,
+ (buf.validate.field).string.max_len = 4096
+ ];
}
message LoginResponse {
@@ -268,11 +294,14 @@ message LogoutRequest {}
message ExchangeTokenRequest {
// External OIDC token (JWT) from CI/CD platform.
- string token = 1 [(bytebase.v1.audit_behavior) = SENSITIVE];
+ string token = 1 [
+ (bytebase.v1.audit_behavior) = SENSITIVE,
+ (buf.validate.field).string.max_len = 65536
+ ];
// Workload Identity email for identifying which identity to authenticate as.
// Format: {name}@workload.bytebase.com
- string email = 2;
+ string email = 2 [(buf.validate.field).string.max_len = 254];
}
message ExchangeTokenResponse {
@@ -282,13 +311,18 @@ message ExchangeTokenResponse {
message SignupRequest {
// The email for the new account.
- string email = 1;
+ // Bounded so an oversized identity is refused at the edge before any
+ // handler runs; the login-attempt lockout keys rows by this value.
+ string email = 1 [(buf.validate.field).string.max_len = 254];
// The password for the new account.
- string password = 2 [(bytebase.v1.audit_behavior) = SENSITIVE];
+ string password = 2 [
+ (bytebase.v1.audit_behavior) = SENSITIVE,
+ (buf.validate.field).string.max_bytes = 72
+ ];
// The display name of the user.
- string title = 3;
+ string title = 3 [(buf.validate.field).string.max_len = 200];
}
// Request to refresh the access token.
@@ -299,47 +333,68 @@ message RefreshResponse {}
message RequestPasswordResetRequest {
// The email address of the account to reset.
- string email = 1;
+ // Bounded so an oversized identity is refused at the edge before any
+ // handler runs; the login-attempt lockout keys rows by this value.
+ string email = 1 [(buf.validate.field).string.max_len = 254];
// Optional workspace context captured at send time, used to locate the EMAIL setting,
// and later (at verify time) for signup gate checks and workspace assignment.
// Unset for SaaS brand-new signup (no workspace exists yet).
// Format: workspaces/{workspace}
- optional string workspace = 2;
+ optional string workspace = 2 [(buf.validate.field).string.max_len = 256];
}
message ResetPasswordRequest {
// The email address of the account.
- string email = 1;
+ // Bounded so an oversized identity is refused at the edge before any
+ // handler runs; the login-attempt lockout keys rows by this value.
+ string email = 1 [(buf.validate.field).string.max_len = 254];
// The 6-digit code from the reset email.
- string code = 2 [(bytebase.v1.audit_behavior) = SENSITIVE];
+ string code = 2 [
+ (bytebase.v1.audit_behavior) = SENSITIVE,
+ (buf.validate.field).string.max_len = 64
+ ];
// The new password to set.
- string new_password = 3 [(bytebase.v1.audit_behavior) = SENSITIVE];
+ string new_password = 3 [
+ (bytebase.v1.audit_behavior) = SENSITIVE,
+ (buf.validate.field).string.max_bytes = 72
+ ];
}
message SendEmailLoginCodeRequest {
// The email address to send the code to.
- string email = 1;
+ // Bounded so an oversized identity is refused at the edge before any
+ // handler runs; the login-attempt lockout keys rows by this value.
+ string email = 1 [(buf.validate.field).string.max_len = 254];
// Optional workspace context captured at send time, used to locate the EMAIL setting,
// and later (at verify time) for signup gate checks and workspace assignment.
// Unset for SaaS brand-new signup (no workspace exists yet).
// Format: workspaces/{workspace}
- optional string workspace = 2;
+ optional string workspace = 2 [(buf.validate.field).string.max_len = 256];
}
message SwitchWorkspaceRequest {
// The target workspace to switch to.
// Format: workspaces/{workspace}
- string workspace = 1;
+ string workspace = 1 [(buf.validate.field).string.max_len = 256];
// If true, sets tokens as HTTP-only cookies (browser clients).
bool web = 2;
// OTP code for MFA verification. Required if the target workspace enforces MFA.
- optional string otp_code = 3 [(bytebase.v1.audit_behavior) = SENSITIVE];
+ optional string otp_code = 3 [
+ (bytebase.v1.audit_behavior) = SENSITIVE,
+ (buf.validate.field).string.max_len = 64
+ ];
// Recovery code for MFA verification (alternative to otp_code).
- optional string recovery_code = 4 [(bytebase.v1.audit_behavior) = SENSITIVE];
+ optional string recovery_code = 4 [
+ (bytebase.v1.audit_behavior) = SENSITIVE,
+ (buf.validate.field).string.max_len = 64
+ ];
// Temporary MFA token from a previous SwitchWorkspace call that returned mfa_temp_token.
- optional string mfa_temp_token = 5 [(bytebase.v1.audit_behavior) = SENSITIVE];
+ optional string mfa_temp_token = 5 [
+ (bytebase.v1.audit_behavior) = SENSITIVE,
+ (buf.validate.field).string.max_len = 4096
+ ];
}
diff --git a/proto/v1/v1/user_service.proto b/proto/v1/v1/user_service.proto
index a2b4d37282..3ed1226472 100644
--- a/proto/v1/v1/user_service.proto
+++ b/proto/v1/v1/user_service.proto
@@ -261,7 +261,10 @@ message UpdateEmailRequest {
];
// The new email address.
- string email = 2 [(google.api.field_behavior) = REQUIRED];
+ string email = 2 [
+ (google.api.field_behavior) = REQUIRED,
+ (buf.validate.field).string.max_len = 254
+ ];
}
message User {
@@ -280,7 +283,7 @@ message User {
State state = 2;
// The email address of the user, used for login and notifications.
- string email = 3;
+ string email = 3 [(buf.validate.field).string.max_len = 254];
// The display title or full name of the user.
string title = 4 [(buf.validate.field).string.max_len = 200];
@@ -288,7 +291,8 @@ message User {
// The password for authentication. Only used during user creation or password updates.
string password = 6 [
(google.api.field_behavior) = INPUT_ONLY,
- (bytebase.v1.audit_behavior) = SENSITIVE
+ (bytebase.v1.audit_behavior) = SENSITIVE,
+ (buf.validate.field).string.max_bytes = 72
];
// The mfa_enabled flag means if the user has enabled MFA.