Skip to content

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

feat(api): require re-authentication to change your own credentials (#21258)

Danny Xu9e117d42e20f
diff --git a/.github/workflows/frontend-tests.yml b/.github/workflows/frontend-tests.yml
index 50181e1bcf..3aefd8d9ba 100644
--- a/.github/workflows/frontend-tests.yml
+++ b/.github/workflows/frontend-tests.yml
@@ -17,17 +17,25 @@ concurrency:
jobs:
static-checks:
- runs-on: ubuntu-latest
+ runs-on: self-hosted
+ timeout-minutes: 30
steps:
- uses: actions/checkout@v7
- - uses: pnpm/action-setup@v6
- with:
- version: '11.17.0'
- uses: actions/setup-node@v7
with:
node-version: '24.18.1'
- cache: pnpm
- cache-dependency-path: "frontend/pnpm-lock.yaml"
+ # The runner's pnpm store persists between runs, so the Actions
+ # cache adds nothing and downloading it is slow.
+ cache: ''
+ - uses: pnpm/action-setup@v6
+ with:
+ version: '11.17.0'
+ # Fetch the pnpm binary instead of running the npm-based
+ # self-installer: the self-hosted runner's bundled npm
+ # (externals/node24) is missing lib/cli.js, so the installer dies
+ # before pnpm exists. Ordering setup-node first also keeps this off
+ # the runner's bundled toolchain.
+ standalone: true
- name: Install dependencies
run: pnpm install --frozen-lockfile
working-directory: frontend
@@ -39,17 +47,25 @@ jobs:
working-directory: frontend
frontend-tests:
- runs-on: ubuntu-latest
+ runs-on: self-hosted
+ timeout-minutes: 30
steps:
- uses: actions/checkout@v7
- - uses: pnpm/action-setup@v6
- with:
- version: '11.17.0'
- uses: actions/setup-node@v7
with:
node-version: '24.18.1'
- cache: pnpm
- cache-dependency-path: "frontend/pnpm-lock.yaml"
+ # The runner's pnpm store persists between runs, so the Actions
+ # cache adds nothing and downloading it is slow.
+ cache: ''
+ - uses: pnpm/action-setup@v6
+ with:
+ version: '11.17.0'
+ # Fetch the pnpm binary instead of running the npm-based
+ # self-installer: the self-hosted runner's bundled npm
+ # (externals/node24) is missing lib/cli.js, so the installer dies
+ # before pnpm exists. Ordering setup-node first also keeps this off
+ # the runner's bundled toolchain.
+ standalone: true
- name: Install dependencies
run: pnpm install --frozen-lockfile
working-directory: frontend
diff --git a/.github/workflows/start-runner-vm.yml b/.github/workflows/start-runner-vm.yml
index 4f94121a15..7bd1ce69ff 100644
--- a/.github/workflows/start-runner-vm.yml
+++ b/.github/workflows/start-runner-vm.yml
@@ -1,6 +1,6 @@
# Starts the github-runner GCE VM, which hosts this repo's self-hosted Actions
# runner (used by jobs with `runs-on: self-hosted`, e.g. backend-tests,
-# golangci-lint, test_link).
+# frontend-tests, golangci-lint, test_link).
name: Start github-runner VM
on:
diff --git a/backend/api/mcp/gen/openapi.yaml b/backend/api/mcp/gen/openapi.yaml
index 974f250140..55e6c519b8 100644
--- a/backend/api/mcp/gen/openapi.yaml
+++ b/backend/api/mcp/gen/openapi.yaml
@@ -569,6 +569,8 @@ paths:
description: |-
Requests a password reset email for the given email address.
Always returns success to avoid leaking whether the email exists.
+ Requires the workspace's SMTP mail delivery setting; without it the
+ recovery route is an admin password reset.
Permissions required: None
operationId: bytebase.v1.AuthService.RequestPasswordReset
parameters:
@@ -646,6 +648,8 @@ paths:
description: |-
Sends a 6-digit verification code to the email for login/signup.
Always returns success (no email enumeration). Enforces 60-sec resend cooldown.
+ The signed-in counterpart is UserService.RequestReauthCode; LOGIN and
+ REAUTH codes are not interchangeable.
Permissions required: None
operationId: bytebase.v1.AuthService.SendEmailLoginCode
parameters:
@@ -7512,6 +7516,47 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/bytebase.v1.RegenerateRecoveryCodesResponse'
+ /bytebase.v1.UserService/RequestReauthCode:
+ post:
+ tags:
+ - bytebase.v1.UserService
+ summary: RequestReauthCode
+ description: |-
+ Sends a one-time code to the caller's own email, usable as
+ CredentialProof.email_code. Bytebase Cloud only, and only while the
+ account has no live MFA factor. Not AuthService.SendEmailLoginCode: that
+ one starts a session, this one proves an existing one.
+ Permissions required: None beyond being signed in as `name`.
+ operationId: bytebase.v1.UserService.RequestReauthCode
+ parameters:
+ - name: Connect-Protocol-Version
+ in: header
+ required: true
+ schema:
+ $ref: '#/components/schemas/connect-protocol-version'
+ - name: Connect-Timeout-Ms
+ in: header
+ schema:
+ $ref: '#/components/schemas/connect-timeout-header'
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/bytebase.v1.RequestReauthCodeRequest'
+ required: true
+ responses:
+ default:
+ description: Error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/connect.error'
+ "200":
+ description: Success
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/google.protobuf.Empty'
/bytebase.v1.UserService/StartMFAEnrollment:
post:
tags:
@@ -9874,7 +9919,12 @@ components:
title: new_password
description: |
string.max_bytes = 72
+ credential:
+ title: credential
+ $ref: '#/components/schemas/bytebase.v1.CredentialProof'
title: ChangePasswordRequest
+ required:
+ - credential
additionalProperties: false
bytebase.v1.Changelog:
type: object
@@ -10258,9 +10308,20 @@ components:
The pending_version of the codes being confirmed. Confirming promotes
exactly the set this version identifies, or nothing.
$ref: '#/components/schemas/google.protobuf.Timestamp'
+ credential:
+ title: credential
+ $ref: '#/components/schemas/bytebase.v1.CredentialProof'
+ otpCode:
+ type: string
+ title: otp_code
+ maxLength: 64
+ description: |-
+ Required for first-time enrollment, rejected otherwise. A *fresh* code,
+ not the one EnableMFA took.
title: ConfirmRecoveryCodesRequest
required:
- pendingVersion
+ - credential
additionalProperties: false
bytebase.v1.CreateAccessGrantRequest:
type: object
@@ -10647,6 +10708,58 @@ components:
title: CreateWorkloadIdentityRequest
additionalProperties: false
description: Request message for creating a workload identity.
+ bytebase.v1.CredentialProof:
+ type: object
+ oneOf:
+ - type: object
+ properties:
+ currentPassword:
+ type: string
+ title: current_password
+ description: |
+ The account's current password. Refused by a factor-touching method
+ while a live MFA factor exists.
+ string.max_bytes = 72
+ title: current_password
+ required:
+ - currentPassword
+ - type: object
+ properties:
+ emailCode:
+ type: string
+ title: email_code
+ maxLength: 64
+ description: |-
+ A one-time code from RequestReauthCode. Bytebase Cloud only, and only
+ while the account has no live MFA factor.
+ title: email_code
+ required:
+ - emailCode
+ - type: object
+ properties:
+ otpCode:
+ type: string
+ title: otp_code
+ maxLength: 64
+ description: A live code from the account's enrolled TOTP authenticator.
+ title: otp_code
+ required:
+ - otpCode
+ - type: object
+ properties:
+ recoveryCode:
+ type: string
+ title: recovery_code
+ maxLength: 64
+ description: A single-use MFA recovery code.
+ title: recovery_code
+ required:
+ - recoveryCode
+ title: CredentialProof
+ additionalProperties: false
+ description: |-
+ One proof that the caller currently controls a credential on the account.
+ Exactly one field must be set; enforced in the handler.
bytebase.v1.DataClassificationSetting:
type: object
properties:
@@ -11805,6 +11918,12 @@ components:
description: |-
Format: users/{email}. The caller's own, or another user's with
bb.users.update.
+ credential:
+ title: credential
+ description: |-
+ Required for a self-service call against a live factor, and then only
+ otp_code or recovery_code. Unused on an admin-assisted call.
+ $ref: '#/components/schemas/bytebase.v1.CredentialProof'
title: DisableMFARequest
additionalProperties: false
bytebase.v1.EmailSetting:
@@ -11895,6 +12014,12 @@ components:
title: pending_version
description: The pending_version this enrollment was minted with.
$ref: '#/components/schemas/google.protobuf.Timestamp'
+ credential:
+ title: credential
+ description: |-
+ Proof of the *existing* factor, not the new device above. Required for a
+ rotation, and for first-time enrollment on an account with a password.
+ $ref: '#/components/schemas/bytebase.v1.CredentialProof'
title: EnableMFARequest
required:
- pendingVersion
@@ -17700,6 +17825,16 @@ components:
Format: workspaces/{workspace}
title: RequestPasswordResetRequest
additionalProperties: false
+ bytebase.v1.RequestReauthCodeRequest:
+ type: object
+ properties:
+ name:
+ type: string
+ title: name
+ maxLength: 260
+ description: 'Format: users/{email}. Must be the caller''s own name.'
+ title: RequestReauthCodeRequest
+ additionalProperties: false
bytebase.v1.ResetPasswordRequest:
type: object
properties:
diff --git a/backend/api/v1/audit_redact_inventory_test.go b/backend/api/v1/audit_redact_inventory_test.go
index 73e437fd37..1a189470ea 100644
--- a/backend/api/v1/audit_redact_inventory_test.go
+++ b/backend/api/v1/audit_redact_inventory_test.go
@@ -810,6 +810,7 @@ var auditRecordedFields = []string{
"bytebase.v1.RequestMetadata.caller_supplied_user_agent",
"bytebase.v1.RequestPasswordResetRequest.email",
"bytebase.v1.RequestPasswordResetRequest.workspace",
+ "bytebase.v1.RequestReauthCodeRequest.name",
"bytebase.v1.ResetPasswordRequest.email",
"bytebase.v1.RetryIssueApprovalRequest.name",
"bytebase.v1.ReviewConfig.name",
diff --git a/backend/api/v1/audit_redact_test.go b/backend/api/v1/audit_redact_test.go
index 79573d4f72..bfccc77c64 100644
--- a/backend/api/v1/audit_redact_test.go
+++ b/backend/api/v1/audit_redact_test.go
@@ -180,15 +180,24 @@ func TestAuditRowKeepsItsSubstance(t *testing.T) {
},
{
// A failed validation neither consumes the code nor suppresses the
- // row, so an intact OTP here used to be a still-live one.
- name: "enable MFA retains who enrolled but not the code",
- value: &v1pb.EnableMFARequest{Name: "users/[email protected]", OtpCode: otpCode},
- want: []string{"users/[email protected]"},
+ // row, so an intact OTP here used to be a still-live one — and the
+ // proof beside it carries the current password.
+ name: "enable MFA retains who enrolled but neither the code nor the proof",
+ value: &v1pb.EnableMFARequest{
+ Name: "users/[email protected]",
+ OtpCode: otpCode,
+ Credential: &v1pb.CredentialProof{Proof: &v1pb.CredentialProof_CurrentPassword{CurrentPassword: secretSentinel}},
+ },
+ want: []string{"users/[email protected]"},
},
{
- name: "change password retains who changed it but not the password",
- value: &v1pb.ChangePasswordRequest{Name: "users/[email protected]", NewPassword: secretSentinel},
- want: []string{"users/[email protected]"},
+ name: "change password retains who changed it but neither password",
+ value: &v1pb.ChangePasswordRequest{
+ Name: "users/[email protected]",
+ NewPassword: secretSentinel,
+ Credential: &v1pb.CredentialProof{Proof: &v1pb.CredentialProof_CurrentPassword{CurrentPassword: secretSentinel}},
+ },
+ want: []string{"users/[email protected]"},
},
{
name: "user update retains who was updated",
diff --git a/backend/api/v1/auth_service_email_code.go b/backend/api/v1/auth_service_email_code.go
index 2cec737244..35197df15c 100644
--- a/backend/api/v1/auth_service_email_code.go
+++ b/backend/api/v1/auth_service_email_code.go
@@ -349,12 +349,26 @@ func resolvePreLoginEmailSetting(
// 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.
+// the account exists.
func (s *AuthService) sendEmailVerificationCode(ctx context.Context, workspaceID, email string, purpose storepb.EmailVerificationCodePurpose, subject, bodyFmt string) error {
+ return sendEmailVerificationCode(ctx, s.store, s.secret, workspaceID, email, purpose, emailCodeTemplate{Subject: subject, BodyFmt: bodyFmt})
+}
+
+// emailCodeTemplate is the message a verification code is delivered in.
+// BodyFmt must contain one %s for the 6-digit code.
+type emailCodeTemplate struct {
+ Subject string
+ BodyFmt string
+}
+
+// sendEmailVerificationCode is package-level because both AuthService (login
+// and password-reset codes) and UserService (the re-authentication code) send
+// them; the deps it needs are passed rather than reached through a receiver.
+func sendEmailVerificationCode(ctx context.Context, stores *store.Store, secret, workspaceID, email string, purpose storepb.EmailVerificationCodePurpose, mail emailCodeTemplate) error {
// 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)
+ account, err := stores.GetAccountByEmail(ctx, email)
if err != nil {
return errors.Wrap(err, "failed to look up account for password reset")
}
@@ -365,7 +379,7 @@ func (s *AuthService) sendEmailVerificationCode(ctx context.Context, workspaceID
// 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)
+ emailSetting, err := resolvePreLoginEmailSetting(ctx, stores, workspaceID)
if err != nil {
return err
}
@@ -379,10 +393,10 @@ func (s *AuthService) sendEmailVerificationCode(ctx context.Context, workspaceID
}
now := time.Now()
- sent, err := s.store.UpsertEmailVerificationCodeIfCooldownExpired(ctx, &store.EmailVerificationCodeMessage{
+ sent, err := stores.UpsertEmailVerificationCodeIfCooldownExpired(ctx, &store.EmailVerificationCodeMessage{
Email: email,
Purpose: purpose,
- CodeHash: s.hashEmailCode(code),
+ CodeHash: hashEmailCode(secret, code),
ExpiresAt: now.Add(emailCodeExpiry),
LastSentAt: now,
}, emailCodeResendCooldown)
@@ -398,15 +412,15 @@ func (s *AuthService) sendEmailVerificationCode(ctx context.Context, workspaceID
return errors.Wrap(err, "failed to create mail sender")
}
- body := fmt.Sprintf(bodyFmt, code, int(emailCodeExpiry.Minutes()))
+ body := fmt.Sprintf(mail.BodyFmt, code, int(emailCodeExpiry.Minutes()))
if err := sender.Send(ctx, &mailer.SendRequest{
To: []string{email},
- Subject: subject,
+ Subject: mail.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))
+ _ = stores.DeleteEmailVerificationCodeIfMatch(ctx, email, purpose, hashEmailCode(secret, code))
return errors.Wrap(err, "failed to send email")
}
return nil
@@ -437,7 +451,7 @@ func (s *AuthService) verifyEmailCode(ctx context.Context, email string, purpose
_ = 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 {
+ if subtle.ConstantTimeCompare([]byte(hashEmailCode(s.secret, submittedCode)), []byte(row.CodeHash)) != 1 {
return connect.NewError(connect.CodeUnauthenticated, errors.New(errMsgInvalidEmailCode))
}
_ = s.store.DeleteEmailVerificationCodeIfMatch(ctx, email, purpose, row.CodeHash)
@@ -462,8 +476,8 @@ func generateEmailCode() (string, error) {
// 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))
+func hashEmailCode(secret, code string) string {
+ mac := hmac.New(sha256.New, []byte(secret))
mac.Write([]byte(code))
return hex.EncodeToString(mac.Sum(nil))
}
diff --git a/backend/api/v1/auth_service_lockout.go b/backend/api/v1/auth_service_lockout.go
index 18f73e366e..234a225e6c 100644
--- a/backend/api/v1/auth_service_lockout.go
+++ b/backend/api/v1/auth_service_lockout.go
@@ -48,7 +48,14 @@ var loginAttemptLockedMsg = map[storepb.LoginAttemptKind]string{
// 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)
+ return claimLoginAttempt(ctx, s.store, identity, kind)
+}
+
+// claimLoginAttempt is package-level so UserService can claim the same buckets
+// when it verifies a CredentialProof: a proof channel without that bound is a
+// guessing oracle.
+func claimLoginAttempt(ctx context.Context, stores *store.Store, identity string, kind storepb.LoginAttemptKind) error {
+ granted, err := stores.ClaimLoginAttempt(ctx, identity, kind, loginAttemptMax, loginAttemptWindow)
if err != nil {
return connect.NewError(connect.CodeInternal, err)
}
@@ -63,9 +70,13 @@ func (s *AuthService) claimLoginAttempt(ctx context.Context, identity string, ki
// 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)
+ clearLoginAttempt(ctx, s.store, identity, kind)
+}
+
+func clearLoginAttempt(ctx context.Context, stores *store.Store, identity string, kind storepb.LoginAttemptKind) {
+ err := stores.ClearLoginAttempt(ctx, identity, kind)
if err != nil {
- err = s.store.ClearLoginAttempt(ctx, identity, kind)
+ err = stores.ClearLoginAttempt(ctx, identity, kind)
}
if err != nil {
slog.Error("login attempt clear failed", slog.String("kind", kind.String()), log.BBError(err))
diff --git a/backend/api/v1/auth_service_lockout_test.go b/backend/api/v1/auth_service_lockout_test.go
index fdc9d6b421..35b4e764d0 100644
--- a/backend/api/v1/auth_service_lockout_test.go
+++ b/backend/api/v1/auth_service_lockout_test.go
@@ -102,7 +102,7 @@ func TestEmailCodeLockoutClaims(t *testing.T) {
sent, err := stores.UpsertEmailVerificationCodeIfCooldownExpired(ctx, &store.EmailVerificationCodeMessage{
Email: email,
Purpose: purpose,
- CodeHash: service.hashEmailCode(code),
+ CodeHash: hashEmailCode(service.secret, code),
ExpiresAt: time.Now().Add(emailCodeExpiry),
LastSentAt: time.Now(),
}, 0)
@@ -153,7 +153,7 @@ func TestEmailCodeLockoutClaims(t *testing.T) {
sent, err := stores.UpsertEmailVerificationCodeIfCooldownExpired(ctx, &store.EmailVerificationCodeMessage{
Email: email,
Purpose: storepb.EmailVerificationCodePurpose_LOGIN,
- CodeHash: service.hashEmailCode("333333"),
+ CodeHash: hashEmailCode(service.secret, "333333"),
ExpiresAt: time.Now().Add(emailCodeExpiry),
LastSentAt: time.Now(),
}, emailCodeResendCooldown)
@@ -220,7 +220,7 @@ func TestResetPasswordClearsPasswordLockout(t *testing.T) {
sent, err := stores.UpsertEmailVerificationCodeIfCooldownExpired(ctx, &store.EmailVerificationCodeMessage{
Email: email,
Purpose: storepb.EmailVerificationCodePurpose_PASSWORD_RESET,
- CodeHash: service.hashEmailCode(resetCode),
+ CodeHash: hashEmailCode(service.secret, resetCode),
ExpiresAt: time.Now().Add(emailCodeExpiry),
LastSentAt: time.Now(),
}, 0)
diff --git a/backend/api/v1/auth_service_test.go b/backend/api/v1/auth_service_test.go
index fc68ba3563..92fafb3cd1 100644
--- a/backend/api/v1/auth_service_test.go
+++ b/backend/api/v1/auth_service_test.go
@@ -278,7 +278,7 @@ func TestLoginEnforcesWorkspaceDomains(t *testing.T) {
_, err = stores.UpsertEmailVerificationCodeIfCooldownExpired(ctx, &store.EmailVerificationCodeMessage{
Email: email,
Purpose: storepb.EmailVerificationCodePurpose_LOGIN,
- CodeHash: service.hashEmailCode(code),
+ CodeHash: hashEmailCode(service.secret, code),
ExpiresAt: time.Now().Add(time.Minute),
LastSentAt: time.Now(),
}, 0)
@@ -299,7 +299,7 @@ func TestLoginEnforcesWorkspaceDomains(t *testing.T) {
_, err := stores.UpsertEmailVerificationCodeIfCooldownExpired(ctx, &store.EmailVerificationCodeMessage{
Email: blockedAdmin.Email,
Purpose: storepb.EmailVerificationCodePurpose_LOGIN,
- CodeHash: service.hashEmailCode(code),
+ CodeHash: hashEmailCode(service.secret, code),
ExpiresAt: time.Now().Add(time.Minute),
LastSentAt: time.Now(),
}, 0)
@@ -318,7 +318,7 @@ func TestLoginEnforcesWorkspaceDomains(t *testing.T) {
_, err := stores.UpsertEmailVerificationCodeIfCooldownExpired(ctx, &store.EmailVerificationCodeMessage{
Email: email,
Purpose: storepb.EmailVerificationCodePurpose_LOGIN,
- CodeHash: service.hashEmailCode(code),
+ CodeHash: hashEmailCode(service.secret, code),
ExpiresAt: time.Now().Add(time.Minute),
LastSentAt: time.Now(),
}, 0)
diff --git a/backend/api/v1/mcp_gate_test.go b/backend/api/v1/mcp_gate_test.go
index b035208d0e..24931ec0ee 100644
--- a/backend/api/v1/mcp_gate_test.go
+++ b/backend/api/v1/mcp_gate_test.go
@@ -133,6 +133,7 @@ func TestForbiddenClassMembership(t *testing.T) {
v1connect.UserServiceDisableMFAProcedure,
v1connect.UserServiceRegenerateRecoveryCodesProcedure,
v1connect.UserServiceConfirmRecoveryCodesProcedure,
+ v1connect.UserServiceRequestReauthCodeProcedure,
}
got := forbiddenProceduresFromDescriptors(t)
@@ -172,6 +173,7 @@ func TestForbiddenClassMembership(t *testing.T) {
v1connect.UserServiceDisableMFAProcedure: v1pb.MCPDenialReason_TAKES_OVER_ACCOUNT,
v1connect.UserServiceRegenerateRecoveryCodesProcedure: v1pb.MCPDenialReason_MINTS_CREDENTIAL,
v1connect.UserServiceConfirmRecoveryCodesProcedure: v1pb.MCPDenialReason_TAKES_OVER_ACCOUNT,
+ v1connect.UserServiceRequestReauthCodeProcedure: v1pb.MCPDenialReason_RESETS_CREDENTIAL,
v1connect.IdentityProviderServiceCreateIdentityProviderProcedure: v1pb.MCPDenialReason_MINTS_CREDENTIAL_FOR_OTHERS,
v1connect.IdentityProviderServiceUpdateIdentityProviderProcedure: v1pb.MCPDenialReason_MINTS_CREDENTIAL_FOR_OTHERS,
v1connect.IdentityProviderServiceTestIdentityProviderProcedure: v1pb.MCPDenialReason_MINTS_CREDENTIAL_FOR_OTHERS,
diff --git a/backend/api/v1/testdata/mcp_method_classification.md b/backend/api/v1/testdata/mcp_method_classification.md
index cb0a955286..493493f335 100644
--- a/backend/api/v1/testdata/mcp_method_classification.md
+++ b/backend/api/v1/testdata/mcp_method_classification.md
@@ -19,9 +19,9 @@ served by no ceiling.
| READ | 57 | served to a read-only session and above |
| WRITE | 40 | served to a read-write session only |
| EXCLUDED | 85 | served by no ceiling this phase ships |
-| FORBIDDEN | 34 | never served, whatever the ceiling |
+| FORBIDDEN | 35 | never served, whatever the ceiling |
| MCP_METHOD_CLASS_UNSPECIFIED | 0 | unclassified — CI rejects this, and the gate refuses it |
-| **total** | **216** | |
+| **total** | **217** | |
| Method | Class | Reason | Permission |
|---|---|---|---|
@@ -222,6 +222,7 @@ served by no ceiling.
| UserService/GetUser | EXCLUDED | ADMINISTERS_THE_WORKSPACE | bb.users.get |
| UserService/ListUsers | EXCLUDED | ADMINISTERS_THE_WORKSPACE | bb.users.list |
| UserService/RegenerateRecoveryCodes | FORBIDDEN | MINTS_CREDENTIAL | — |
+| UserService/RequestReauthCode | FORBIDDEN | RESETS_CREDENTIAL | — |
| UserService/StartMFAEnrollment | FORBIDDEN | MINTS_CREDENTIAL | — |
| UserService/UndeleteUser | EXCLUDED | ADMINISTERS_THE_WORKSPACE | — |
| UserService/UpdateEmail | FORBIDDEN | MINTS_CREDENTIAL_FOR_OTHERS | bb.users.updateEmail |
diff --git a/backend/api/v1/user_service.go b/backend/api/v1/user_service.go
index 54c754dfac..ed39f21c3d 100644
--- a/backend/api/v1/user_service.go
+++ b/backend/api/v1/user_service.go
@@ -34,15 +34,17 @@ import (
type UserService struct {
v1connect.UnimplementedUserServiceHandler
store *store.Store
+ secret string
licenseService *enterprise.LicenseService
profile *config.Profile
iamManager *iam.Manager
}
// NewUserService creates a new UserService.
-func NewUserService(store *store.Store, licenseService *enterprise.LicenseService, profile *config.Profile, iamManager *iam.Manager) *UserService {
+func NewUserService(store *store.Store, secret string, licenseService *enterprise.LicenseService, profile *config.Profile, iamManager *iam.Manager) *UserService {
return &UserService{
store: store,
+ secret: secret,
licenseService: licenseService,
profile: profile,
iamManager: iamManager,
@@ -359,7 +361,7 @@ func (s *UserService) UpdateUser(ctx context.Context, request *connect.Request[v
}
}
- var passwordPatch *string
+ var newPassword *string
patch := &store.UpdateUserMessage{}
for _, path := range request.Msg.UpdateMask.Paths {
switch path {
@@ -369,22 +371,22 @@ func (s *UserService) UpdateUser(ctx context.Context, request *connect.Request[v
case "title":
patch.Name = &request.Msg.User.Title
case "password":
- if user.Type != storepb.PrincipalType_END_USER {
- return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("password can be mutated for end users only"))
- }
+ // Admin-assisted reset only: an admin recovering a locked-out user
+ // cannot know the credential being replaced, and bb.users.update
+ // plus the audit log are the control there. A caller changing
+ // their own password must prove the current one via ChangePassword.
if callerUser.ID == user.ID {
- // Changing your own password is ChangePassword's job: it is the
- // method that knows the old one mattered.
return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("use ChangePassword to change your own password"))
}
+ if user.Type != storepb.PrincipalType_END_USER {
+ return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("password can be mutated for end users only"))
+ }
if err := s.validatePassword(ctx, common.GetWorkspaceIDFromContext(ctx), request.Msg.User.Password); err != nil {
return nil, err
}
- passwordPatch = &request.Msg.User.Password
+ newPassword = &request.Msg.User.Password
case "mfa_enabled":
- // MFA is enrolled and disabled through its own methods, which can
- // state what they write; a boolean on an update mask cannot.
- return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("use EnableMFA, ConfirmRecoveryCodes or DisableMFA to change MFA"))
+ return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("mfa_enabled is output only, use EnableMFA or DisableMFA instead"))
case "phone":
if request.Msg.User.Phone != "" {
if err := common.ValidatePhone(request.Msg.User.Phone); err != nil {
@@ -395,16 +397,16 @@ func (s *UserService) UpdateUser(ctx context.Context, request *connect.Request[v
default:
}
}
- if passwordPatch != nil {
- if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(*passwordPatch)); err == nil {
+ if newPassword != nil {
+ if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(*newPassword)); err == nil {
// return bad request if the passwords match
return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("password cannot be the same"))
}
-
- passwordHash, err := bcrypt.GenerateFromPassword([]byte((*passwordPatch)), bcrypt.DefaultCost)
+ passwordHash, err := bcrypt.GenerateFromPassword([]byte(*newPassword), bcrypt.DefaultCost)
if err != nil {
return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to generate password hash"))
}
+
patch.PasswordHash = new(string(passwordHash))
// Revoke all refresh tokens for this user (including current session)
@@ -413,6 +415,7 @@ func (s *UserService) UpdateUser(ctx context.Context, request *connect.Request[v
slog.Error("failed to revoke refresh tokens on password change", log.BBError(err), slog.String("user", user.Email))
}
}
+
user, err = s.store.UpdateUser(ctx, user, patch)
if err != nil {
return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to update user"))
@@ -631,45 +634,126 @@ func (s *UserService) UpdateEmail(ctx context.Context, request *connect.Request[
return connect.NewResponse(v1User), nil
}
-// convertToUser converts a stored user for a read. The MFA enrollment secrets
-// stay out: temp_otp_secret is the TOTP seed and temp_recovery_codes are the
-// codes that get past the second factor, and a response that carries either
-// hands a reader the account's second factor. Every caller but one is a read,
-// so this is the default and the exception has to be asked for by name.
-var errSupersededPendingMFAState = connect.NewError(connect.CodeFailedPrecondition,
- errors.New("the pending MFA state has been superseded; restart from the mint step"))
-
-// Self-service credential methods. These replace the UpdateUser field masks
-// and flags that used to drive password changes and MFA enrollment — same
-// operations, addressed as methods rather than as a mask plus three booleans,
-// so each one states who may call it and what it writes.
+// Self-service credential changes (docs/design/reauthenticate-credential-changes.md).
//
-// They are auth_method=CUSTOM: the ACL interceptor enforces nothing for them,
-// so every handler checks the caller itself. DisableMFA is the one method with
-// an administrator path.
+// Every mutation that rewrites live authentication material — password hash,
+// permanent TOTP secret, permanent recovery codes — requires a CredentialProof
+// that the caller currently holds a credential on the account. A password
+// change additionally ends the account's other web sessions.
+//
+// These methods are auth_method=CUSTOM: the ACL interceptor enforces nothing
+// for them, so each handler independently rejects any name other than the
+// caller's own. DisableMFA is the one method with a real admin path.
+
+// errFirstTimeEnrollmentNeedsPassword is the refusal a self-hosted first-time
+// enrollment gets when it carries no proof. It names both ways out, because
+// the server cannot tell which applies: an account whose owner chose a
+// password proves it directly, while an SSO-provisioned one holds a random
+// password nobody was ever told and needs an administrator to reset it first.
+var errFirstTimeEnrollmentNeedsPassword = connect.NewError(connect.CodeFailedPrecondition,
+ errors.New("enrolling MFA requires your current password; if you sign in through SSO and never chose one, ask a workspace admin to reset your password, then enroll with it"))
+
+// RequestReauthCode sends a one-time REAUTH code to the caller's own email,
+// usable as CredentialProof.email_code. Bytebase Cloud only: self-hosted
+// deployments cannot send email, so the eligibility check below refuses them
+// before any mail machinery runs.
+//
+// The signed-in half of the pair AuthService.SendEmailLoginCode completes:
+// that one gets a caller into an account and is unauthenticated, this one
+// proves the caller already holds the account. Same mail machinery, different
+// purpose row — a LOGIN code is not spendable here, and vice versa.
+func (s *UserService) RequestReauthCode(ctx context.Context, request *connect.Request[v1pb.RequestReauthCodeRequest]) (*connect.Response[emptypb.Empty], error) {
+ caller, err := s.resolveSelfUser(ctx, request.Msg.Name)
+ if err != nil {
+ return nil, err
+ }
+ // Eligibility is enforced again at redemption — verifyCredentialProof's
+ // email_code branch calls checkEmailCodeEligible — so this check is not
+ // the gate. It is here to refuse ineligible callers outright rather than
+ // mailing them a code they could never spend.
+ if err := s.checkEmailCodeEligible(caller); err != nil {
+ return nil, err
+ }
+
+ // Unlike RequestPasswordReset, a send failure is surfaced: the caller is
+ // already authenticated as the only account this could be about, so there
+ // is no existence oracle to protect — only a dead end to diagnose.
+ if err := sendEmailVerificationCode(
+ ctx,
+ s.store,
+ s.secret,
+ common.GetWorkspaceIDFromContext(ctx),
+ caller.Email,
+ storepb.EmailVerificationCodePurpose_REAUTH,
+ emailCodeTemplate{
+ Subject: "[Bytebase] Confirm your identity",
+ BodyFmt: "Hi,\n\nYour verification code is: %s\n\nThis code expires in %d minutes. If you didn't request this, you can safely ignore this email.\n\n— Bytebase",
+ },
+ ); err != nil {
+ return nil, connect.NewError(connect.CodeInternal, err)
+ }
+ return connect.NewResponse(&emptypb.Empty{}), nil
+}
-// ChangePassword changes the caller's own password.
+// ChangePassword changes the caller's own password after verifying a
+// CredentialProof, and ends the account's web sessions — the caller's own
+// included. OAuth grants deliberately survive: widening revocation to MCP
+// grants is a separate change with its own blast radius.
func (s *UserService) ChangePassword(ctx context.Context, request *connect.Request[v1pb.ChangePasswordRequest]) (*connect.Response[v1pb.User], error) {
caller, err := s.resolveSelfUser(ctx, request.Msg.Name)
if err != nil {
return nil, err
}
- if caller.Type != storepb.PrincipalType_END_USER {
- return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("password can be mutated for end users only"))
+ restriction, err := getAccountRestriction(ctx, s.store, s.licenseService, s.profile.SaaS, common.GetWorkspaceIDFromContext(ctx))
+ if err != nil {
+ return nil, err
+ }
+ if restriction.DisallowPasswordSignin {
+ return nil, connect.NewError(connect.CodeFailedPrecondition, errors.Errorf("password sign-in is disabled for this workspace"))
}
if err := s.validatePassword(ctx, common.GetWorkspaceIDFromContext(ctx), request.Msg.NewPassword); err != nil {
return nil, err
}
- if bcrypt.CompareHashAndPassword([]byte(caller.PasswordHash), []byte(request.Msg.NewPassword)) == nil {
- return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("password cannot be the same"))
- }
- passwordHash, err := bcrypt.GenerateFromPassword([]byte(request.Msg.NewPassword), bcrypt.DefaultCost)
+ newPasswordHash, err := bcrypt.GenerateFromPassword([]byte(request.Msg.NewPassword), bcrypt.DefaultCost)
if err != nil {
return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to generate password hash"))
}
- hash := string(passwordHash)
- user, err := s.store.UpdateUser(ctx, caller, &store.UpdateUserMessage{PasswordHash: &hash})
+ claimed, err := s.claimCredentialProof(ctx, caller.Email, request.Msg.Credential, false)
+ if err != nil {
+ return nil, err
+ }
+ // Changing the password is not touching the MFA factor, so
+ // current_password is acceptable with or without live MFA. A recovery-code
+ // proof is spent by the verify itself, so nothing about mfa_config is
+ // rewritten here from a read taken before it.
+ if err := s.verifyCredentialProof(ctx, caller, request.Msg.Credential, false); err != nil {
+ return nil, err
+ }
+ // Proven, so its bucket has done its job. Every refusal below this line is
+ // about the request, not the credential, and must not count against the
+ // bucket an ordinary login draws from.
+ s.clearCredentialProofClaims(ctx, caller.Email, claimed)
+ claimed = nil
+
+ if bcrypt.CompareHashAndPassword([]byte(caller.PasswordHash), []byte(request.Msg.NewPassword)) == nil {
+ // Not just UX: any PasswordHash write moves the password-rotation
+ // deadline, which a same-password "change" must not reset.
+ //
+ // This comparison answers "is this the current password?", so it stays
+ // behind the proof. Reached without one it is an unbounded password
+ // oracle: a stolen session exhausts the lockout bucket, then reads the
+ // answer off which error comes back for each candidate new_password.
+ //
+ return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("password cannot be the same"))
+ }
+
+ profile := caller.Profile
+ profile.LastChangePasswordTime = timestamppb.Now()
+ user, err := s.store.UpdateUser(ctx, caller, &store.UpdateUserMessage{
+ PasswordHash: new(string(newPasswordHash)),
+ Profile: profile,
+ })
if err != nil {
return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to update user"))
}
@@ -678,12 +762,16 @@ func (s *UserService) ChangePassword(ctx context.Context, request *connect.Reque
if err := s.store.DeleteWebRefreshTokensByUser(ctx, user.Email); err != nil {
slog.Error("failed to revoke refresh tokens on password change", log.BBError(err), slog.String("user", user.Email))
}
+ s.clearCredentialProofClaims(ctx, caller.Email, claimed)
return s.convertUserResponse(ctx, user)
}
-// StartMFAEnrollment mints a pending TOTP secret and recovery codes and hands
-// them back. Any live factor is preserved: an enrollment that is abandoned, or
-// superseded by a later one, changes nothing about how the account signs in.
+// StartMFAEnrollment mints a pending TOTP secret and recovery codes. Nothing
+// goes live, so no proof is required. The write goes through
+// SetPendingMFAState, which sets the three pending fields on the row itself
+// rather than writing back a whole config assembled from this read — a
+// read-modify-write here would resurrect codes a concurrent confirmation
+// rotated away.
func (s *UserService) StartMFAEnrollment(ctx context.Context, request *connect.Request[v1pb.StartMFAEnrollmentRequest]) (*connect.Response[v1pb.StartMFAEnrollmentResponse], error) {
caller, err := s.resolveSelfUser(ctx, request.Msg.Name)
if err != nil {
@@ -697,49 +785,93 @@ func (s *UserService) StartMFAEnrollment(ctx context.Context, request *connect.R
if err != nil {
return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to generate recovery codes"))
}
- // Truncated to the microsecond the database stores, so the version the
- // caller echoes back matches the stored one exactly.
- createdTime := timestamppb.New(time.Now().UTC().Truncate(time.Microsecond))
+ // Microseconds, not nanoseconds: this value is handed to the caller,
+ // stored, and later matched as a Postgres timestamptz, which cannot hold
+ // a finer instant. Minting one the store cannot represent would make the
+ // confirmation reject the enrollment it just created.
+ version := timestamppb.New(time.Now().Truncate(time.Microsecond))
- // Writes only the pending fields: copying the live factor forward from the
- // read above would resurrect it if an administrator disabled MFA while
- // this mint was in flight.
- if err := s.store.SetPendingMFAState(ctx, caller.ID, tempSecret, tempRecoveryCodes, createdTime.AsTime()); err != nil {
+ // The live factor is carried forward untouched: minting an enrollment
+ // changes nothing about how the account signs in today.
+ if err := s.store.SetPendingMFAState(ctx, caller.ID, tempSecret, tempRecoveryCodes, version.AsTime()); err != nil {
return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to update user"))
}
return connect.NewResponse(&v1pb.StartMFAEnrollmentResponse{
OtpSecret: tempSecret,
RecoveryCodes: tempRecoveryCodes,
- ExpireTime: timestamppb.New(createdTime.AsTime().Add(mfaTempSecretExpiration)),
- PendingVersion: createdTime,
+ ExpireTime: timestamppb.New(version.AsTime().Add(mfaTempSecretExpiration)),
+ PendingVersion: version,
}), nil
}
-// EnableMFA verifies an otp_code against the pending enrollment and writes
-// nothing. It exists to catch a mistyped authenticator before the caller is
-// handed recovery codes; ConfirmRecoveryCodes is what makes the factor live.
+// EnableMFA verifies the pending enrollment's otp_code and writes nothing —
+// for a rotation as much as for a first enrollment. ConfirmRecoveryCodes owns
+// promotion in both flows, where the secret goes live in the same write as the
+// codes that recover it, so an account is never MFA-required with none saved
+// and a rotation is not half-applied if the user abandons the download step.
+// Nothing is revoked either: MFA gates minting a session, not using one.
func (s *UserService) EnableMFA(ctx context.Context, request *connect.Request[v1pb.EnableMFARequest]) (*connect.Response[v1pb.User], error) {
caller, err := s.resolveSelfUser(ctx, request.Msg.Name)
if err != nil {
return nil, err
}
- // Verification only, so a read is enough: this writes nothing, and the
- // promotion re-checks the version against the row it updates.
- if err := checkPendingMFAState(caller, request.Msg.PendingVersion); err != nil {
+ if request.Msg.PendingVersion == nil {
+ return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("pending_version is required"))
+ }
+ // Non-guess refusals run before the lockout claim: an argument or state
+ // error is not a guess (the SwitchWorkspace MFA step states the same
+ // rule), and a stale-tab retry against an expired enrollment must not
+ // consume slots from the bucket real MFA logins draw from.
+ if err := checkEnableMFAConfirmable(caller, request.Msg.PendingVersion); err != nil {
+ return nil, err
+ }
+ if err := s.checkEnableMFACredentialShape(caller, request.Msg.Credential); err != nil {
+ return nil, err
+ }
+
+ // The enrollment otp_code claims the MFA bucket even when no
+ // CredentialProof is present at all, so verifying against the pending
+ // TOTP seed is never an unbounded guessing oracle.
+ claimed, err := s.claimCredentialProof(ctx, caller.Email, request.Msg.Credential, true)
+ if err != nil {
return nil, err
}
- if isMFATempSecretExpired(caller.MFAConfig) {
- return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("MFA setup has expired, please restart the enrollment"))
+
+ // The shape check above admits a credential exactly when one is required:
+ // replacing a live factor is proven with the factor, and a first-time
+ // enrollment on self-hosted with the password.
+ if request.Msg.Credential != nil {
+ rotation := caller.MFAConfig.GetOtpSecret() != ""
+ if err := s.verifyCredentialProof(ctx, caller, request.Msg.Credential, true); err != nil {
+ return nil, firstTimeEnrollmentProofError(err, rotation, request.Msg.Credential)
+ }
+ // Proven, so its bucket has done its job. Releasing it here rather
+ // than at the end keeps a mistyped new-device code below from
+ // draining the bucket an ordinary login draws from.
+ s.clearCredentialProofClaims(ctx, caller.Email, claimed)
+ claimed = nil
}
+
+ // The enrollment code proves the caller configured the new device
+ // correctly; skipping it would leave a typo'd authenticator undetected
+ // until the user is locked out at their next login.
if !totp.Validate(request.Msg.OtpCode, caller.MFAConfig.GetTempOtpSecret()) {
return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("invalid OTP code"))
}
+
+ // Verification only, so this writes nothing: promotion belongs to
+ // ConfirmRecoveryCodes, atomically with the codes and under the version
+ // predicate, so the account is never MFA-required with none saved.
+ s.clearCredentialProofClaims(ctx, caller.Email, claimed)
return s.convertUserResponse(ctx, caller)
}
-// DisableMFA clears the account's entire MFA config, live and pending alike, so
-// a confirmation left open cannot silently re-enable it.
+// DisableMFA turns MFA off by clearing the entire MFAConfig — live and
+// pending state alike, so a stale confirmation cannot silently re-enable it.
+// Self-service requires proof by the factor itself; the admin path
+// (self-hosted only) requires bb.users.update and no proof, since an admin
+// recovering a locked-out user cannot know the factor being removed.
func (s *UserService) DisableMFA(ctx context.Context, request *connect.Request[v1pb.DisableMFARequest]) (*connect.Response[v1pb.User], error) {
callerUser, ok := GetUserFromContext(ctx)
if !ok {
@@ -760,7 +892,8 @@ func (s *UserService) DisableMFA(ctx context.Context, request *connect.Request[v
return nil, connect.NewError(connect.CodeNotFound, errors.Errorf("user %q not found", email))
}
- if callerUser.ID != user.ID {
+ selfService := callerUser.ID == user.ID
+ if !selfService {
// Same cross-user gate as UpdateUser: the principal is global, so a
// SaaS workspace admin gets no cross-user reach here either.
if s.profile.SaaS {
@@ -791,32 +924,69 @@ func (s *UserService) DisableMFA(ctx context.Context, request *connect.Request[v
}
}
- updatedUser, err := s.store.UpdateUser(ctx, user, &store.UpdateUserMessage{MFAConfig: &storepb.MFAConfig{}})
+ // Only a live factor has to be proven. With none, this call is cancelling
+ // a pending enrollment or is a no-op, and there is nothing to prove with:
+ // requiring a factor here would strand a user who abandoned an enrollment.
+ var claimed []storepb.LoginAttemptKind
+ if selfService && user.MFAConfig.GetOtpSecret() != "" {
+ if request.Msg.Credential == nil {
+ return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("credential is required"))
+ }
+ if err := s.checkFactorProofShape(user, request.Msg.Credential); err != nil {
+ return nil, err
+ }
+ claimed, err = s.claimCredentialProof(ctx, user.Email, request.Msg.Credential, false)
+ if err != nil {
+ return nil, err
+ }
+ // Turning the factor off must be proven with the factor: a password
+ // can be minted from mailbox possession alone (ResetPassword), so
+ // accepting one here would let a stolen session plus a mailbox strip
+ // the second factor.
+ if err := s.verifyCredentialProof(ctx, user, request.Msg.Credential, true); err != nil {
+ return nil, err
+ }
+ // See ChangePassword: released the moment it is proven, so a failed
+ // write below cannot charge the caller for a correct proof.
+ s.clearCredentialProofClaims(ctx, user.Email, claimed)
+ claimed = nil
+ }
+ // The admin path stays idempotent: a retry, or a second admin racing the
+ // first, finds MFA already off and still reaches the desired state —
+ // erroring would report failure for a satisfied intent. The wipe clears
+ // any pending enrollment either way.
+ updatedUser, err := s.store.UpdateUser(ctx, user, &store.UpdateUserMessage{
+ MFAConfig: &storepb.MFAConfig{},
+ })
if err != nil {
return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to update user"))
}
+ s.clearCredentialProofClaims(ctx, user.Email, claimed)
return s.convertUserResponse(ctx, updatedUser)
}
-// RegenerateRecoveryCodes mints a pending recovery-code set beside the live
-// one. The old codes keep working until ConfirmRecoveryCodes promotes these.
+// RegenerateRecoveryCodes mints a pending recovery-code set alongside the
+// still-live old one. Nothing goes live, so no proof — same as
+// StartMFAEnrollment, and locked for the same reason.
func (s *UserService) RegenerateRecoveryCodes(ctx context.Context, request *connect.Request[v1pb.RegenerateRecoveryCodesRequest]) (*connect.Response[v1pb.RegenerateRecoveryCodesResponse], error) {
caller, err := s.resolveSelfUser(ctx, request.Msg.Name)
if err != nil {
return nil, err
}
- if caller.MFAConfig.GetOtpSecret() == "" {
- return nil, connect.NewError(connect.CodeFailedPrecondition, errors.Errorf("MFA is not enabled"))
- }
tempRecoveryCodes, err := generateRecoveryCodes(10)
if err != nil {
return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to generate recovery codes"))
}
- version := timestamppb.New(time.Now().UTC().Truncate(time.Microsecond))
+ version := timestamppb.New(time.Now().Truncate(time.Microsecond))
- // Same targeted write, and the empty pending secret is deliberate: these
- // codes belong to the live factor, so confirming them must not also
- // promote a secret left behind by an abandoned enrollment.
+ if caller.MFAConfig.GetOtpSecret() == "" {
+ return nil, connect.NewError(connect.CodeFailedPrecondition, errors.Errorf("MFA is not enabled"))
+ }
+ // Minting into the shared temp state supersedes any in-flight TOTP
+ // rotation; its EnableMFA fails the pending_version check rather than
+ // promoting against a half-overwritten set. The empty pending secret is
+ // deliberate: these codes belong to the live factor, so confirming them
+ // must not also promote a secret an abandoned enrollment left behind.
if err := s.store.SetPendingMFAState(ctx, caller.ID, "", tempRecoveryCodes, version.AsTime()); err != nil {
return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to update user"))
}
@@ -827,16 +997,26 @@ func (s *UserService) RegenerateRecoveryCodes(ctx context.Context, request *conn
}), nil
}
-// ConfirmRecoveryCodes promotes the pending recovery codes. On a first-time
-// enrollment the pending TOTP secret goes live in the same write, so the factor
-// and the codes that recover it start existing together.
+// ConfirmRecoveryCodes promotes the exact pending set named by
+// pending_version. For a rotation it replaces the live recovery codes; for
+// first-time enrollment it promotes the TOTP secret and recovery codes
+// together, gated on a fresh otp_code. Both branches change live credential
+// material, so both revoke sessions.
func (s *UserService) ConfirmRecoveryCodes(ctx context.Context, request *connect.Request[v1pb.ConfirmRecoveryCodesRequest]) (*connect.Response[v1pb.User], error) {
caller, err := s.resolveSelfUser(ctx, request.Msg.Name)
if err != nil {
return nil, err
}
- if len(caller.MFAConfig.GetTempRecoveryCodes()) == 0 {
- return nil, connect.NewError(connect.CodeFailedPrecondition, errors.Errorf("no pending recovery codes to confirm"))
+ if request.Msg.Credential == nil {
+ return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("credential is required"))
+ }
+ if request.Msg.PendingVersion == nil {
+ return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("pending_version is required"))
+ }
+ // Non-guess refusals before the claim, same rule as EnableMFA.
+ firstTime := caller.MFAConfig.GetOtpSecret() == ""
+ if err := checkRecoveryCodesConfirmable(caller, request.Msg.PendingVersion, request.Msg.OtpCode, firstTime); err != nil {
+ return nil, err
}
mfaConfig := &storepb.MFAConfig{
@@ -857,12 +1037,49 @@ func (s *UserService) ConfirmRecoveryCodes(ctx context.Context, request *connect
return nil, connect.NewError(connect.CodeFailedPrecondition, errors.Errorf("no MFA enrollment in progress, call StartMFAEnrollment first"))
}
+ if err := s.checkFactorProofShape(caller, request.Msg.Credential); err != nil {
+ return nil, err
+ }
+ claimed, err := s.claimCredentialProof(ctx, caller.Email, request.Msg.Credential, request.Msg.OtpCode != "")
+ if err != nil {
+ return nil, err
+ }
+
+ if firstTime {
+ // First-time enrollment: this is where the secret and the codes go
+ // live, so this is where the proof binds. A fresh otp_code, not a
+ // replay of EnableMFA's — promotion is the moment MFA starts gating
+ // logins.
+ if err := s.verifyCredentialProof(ctx, caller, request.Msg.Credential, true); err != nil {
+ return nil, firstTimeEnrollmentProofError(err, false, request.Msg.Credential)
+ }
+ // Released once proven, so a mistyped new-device code costs the user
+ // nothing but a retry. See EnableMFA.
+ s.clearCredentialProofClaims(ctx, caller.Email, claimed)
+ claimed = nil
+ if !totp.Validate(request.Msg.OtpCode, caller.MFAConfig.GetTempOtpSecret()) {
+ return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("invalid OTP code"))
+ }
+ } else {
+ if err := s.verifyCredentialProof(ctx, caller, request.Msg.Credential, true); err != nil {
+ return nil, err
+ }
+ // Same release as the first-time branch above: the compare-and-set
+ // below can lose to another tab's mint or an administrator's
+ // DisableMFA, and losing that race is not a failed proof.
+ s.clearCredentialProofClaims(ctx, caller.Email, claimed)
+ claimed = nil
+ }
+
// The pending state is one shared slot, so two flows can race for it, and
// the version predicate rides on the write rather than sitting in front of
// it: a mint from another tab, or an administrator's DisableMFA, can land
- // between a check and an unconditional write, and this request would then
- // promote a secret the caller never saw or revive a factor that
+ // between the check above and an unconditional write, and this request
+ // would then promote a secret the caller never saw or revive a factor that
// administrator just cleared.
+ //
+ // Turning MFA on, or rotating the codes, is not a reason to sign the
+ // account out of its other devices.
user, err := s.store.UpdateUserMFAConfigIfPending(ctx, caller.ID, request.Msg.PendingVersion.AsTime(), mfaConfig)
if err != nil {
return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to update user"))
@@ -870,23 +1087,13 @@ func (s *UserService) ConfirmRecoveryCodes(ctx context.Context, request *connect
if user == nil {
return nil, errSupersededPendingMFAState
}
+ s.clearCredentialProofClaims(ctx, caller.Email, claimed)
return s.convertUserResponse(ctx, user)
}
-// checkPendingMFAState rejects a confirmation whose pending_version is no
-// longer the account's pending state — a later mint superseded the enrollment
-// or code set this request thinks it is confirming, or a DisableMFA cleared it.
-func checkPendingMFAState(user *store.UserMessage, pendingVersion *timestamppb.Timestamp) error {
- stored := user.MFAConfig.GetTempOtpSecretCreatedTime()
- if stored == nil || !stored.AsTime().Equal(pendingVersion.AsTime()) {
- return errSupersededPendingMFAState
- }
- return nil
-}
-
// resolveSelfUser parses name and requires it to be the caller's own account.
// Nothing upstream enforces this for CUSTOM methods, so every self-service
-// method goes through here.
+// credential method goes through here.
func (*UserService) resolveSelfUser(ctx context.Context, name string) (*store.UserMessage, error) {
caller, ok := GetUserFromContext(ctx)
if !ok {
@@ -905,6 +1112,280 @@ func (*UserService) resolveSelfUser(ctx context.Context, name string) (*store.Us
return caller, nil
}
+// claimCredentialProof claims the T9 lockout slot for the credential this
+// request will verify, before any verification runs — a proof channel that
+// verified first and counted afterwards would let a caller abandon the request
+// on failure and guess without bound.
+//
+// Exactly one slot, never two. An enrollment otp_code is checked against a
+// secret StartMFAEnrollment just handed this same caller, so it is not a
+// secret to guess; it needs the bound only when it is the one thing being
+// verified, which is Cloud first-time enrollment. Claiming a second bucket
+// alongside a real proof would also mean a refusal on that second claim leaves
+// the first one counted against a request that verified nothing, draining an
+// unrelated bucket on every retry.
+func (s *UserService) claimCredentialProof(ctx context.Context, email string, credential *v1pb.CredentialProof, verifiesEnrollmentOtp bool) ([]storepb.LoginAttemptKind, error) {
+ var kinds []storepb.LoginAttemptKind
+ if credential != nil {
+ kind, err := credentialProofKind(credential)
+ if err != nil {
+ return nil, err
+ }
+ kinds = append(kinds, kind)
+ } else if verifiesEnrollmentOtp {
+ kinds = append(kinds, storepb.LoginAttemptKind_MFA)
+ }
+ for _, kind := range kinds {
+ if err := claimLoginAttempt(ctx, s.store, email, kind); err != nil {
+ return nil, err
+ }
+ }
+ return kinds, nil
+}
+
+// clearCredentialProofClaims forgets the request's claims after every
+// verification in it succeeded.
+func (s *UserService) clearCredentialProofClaims(ctx context.Context, email string, kinds []storepb.LoginAttemptKind) {
+ for _, kind := range kinds {
+ clearLoginAttempt(ctx, s.store, email, kind)
+ }
+}
+
+func credentialProofKind(credential *v1pb.CredentialProof) (storepb.LoginAttemptKind, error) {
+ switch credential.GetProof().(type) {
+ case *v1pb.CredentialProof_CurrentPassword:
+ return storepb.LoginAttemptKind_PASSWORD, nil
+ case *v1pb.CredentialProof_OtpCode, *v1pb.CredentialProof_RecoveryCode:
+ return storepb.LoginAttemptKind_MFA, nil
+ case *v1pb.CredentialProof_EmailCode:
+ return storepb.LoginAttemptKind_EMAIL_CODE, nil
+ default:
+ return storepb.LoginAttemptKind_LOGIN_ATTEMPT_KIND_UNSPECIFIED, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("credential must set exactly one proof"))
+ }
+}
+
+// verifyCredentialProof verifies one CredentialProof against the account. touchesFactor marks methods that
+// rewrite the MFA factor itself: while a live factor exists they accept only
+// otp_code or recovery_code — current_password is not independent (a
+// ResetPassword mints one from mailbox possession alone) and email_code is
+// strictly weaker than the factor.
+//
+// Single-use proofs are spent here, in the same step that accepts them, the
+// way the login path spends a recovery code: `user` is the pointer the store's
+// user cache handed out, so consuming one by editing it in place and leaving
+// the write to a caller would desynchronize that cache from the row on every
+// path that then writes nothing, or whose write fails.
+func (s *UserService) verifyCredentialProof(ctx context.Context, user *store.UserMessage, credential *v1pb.CredentialProof, touchesFactor bool) error {
+ liveMFA := user.MFAConfig.GetOtpSecret() != ""
+ // GetProof, not the field: a nil credential must land in the default
+ // case, never dereference.
+ switch proof := credential.GetProof().(type) {
+ case *v1pb.CredentialProof_CurrentPassword:
+ if touchesFactor && liveMFA {
+ return connect.NewError(connect.CodeInvalidArgument, errors.Errorf("changing the MFA factor requires an OTP or recovery code, not the password"))
+ }
+ if bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(proof.CurrentPassword)) != nil {
+ return connect.NewError(connect.CodeUnauthenticated, errors.Errorf("invalid password"))
+ }
+ return nil
+ case *v1pb.CredentialProof_OtpCode:
+ if !liveMFA {
+ return connect.NewError(connect.CodeInvalidArgument, errors.Errorf("MFA is not enabled"))
+ }
+ if !totp.Validate(proof.OtpCode, user.MFAConfig.GetOtpSecret()) {
+ return connect.NewError(connect.CodeUnauthenticated, errors.Errorf(errMsgInvalidMFACode))
+ }
+ return nil
+ case *v1pb.CredentialProof_RecoveryCode:
+ if !liveMFA {
+ return connect.NewError(connect.CodeInvalidArgument, errors.Errorf("MFA is not enabled"))
+ }
+ // The row decides, not the list read into memory: the spend is the
+ // predicate on the UPDATE, so a code cannot be accepted twice.
+ consumed, err := s.store.ConsumeRecoveryCode(ctx, user.ID, proof.RecoveryCode)
+ if err != nil {
+ return connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to verify recovery code"))
+ }
+ if !consumed {
+ return connect.NewError(connect.CodeUnauthenticated, errors.Errorf(errMsgInvalidRecoveryCode))
+ }
+ return nil
+ case *v1pb.CredentialProof_EmailCode:
+ if err := s.checkEmailCodeEligible(user); err != nil {
+ return err
+ }
+ // A REAUTH code is single-use, and the spend is the same statement
+ // that matches it: validating a row that was read first would let two
+ // concurrent requests both accept one code, each deleting a row the
+ // other had already used to authorize a credential change.
+ consumed, err := s.store.ConsumeEmailVerificationCode(ctx, user.Email, storepb.EmailVerificationCodePurpose_REAUTH, hashEmailCode(s.secret, proof.EmailCode))
+ if err != nil {
+ return connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to verify code"))
+ }
+ if !consumed {
+ // Wrong, already spent, or expired — indistinguishable on purpose.
+ return connect.NewError(connect.CodeUnauthenticated, errors.Errorf(errMsgInvalidEmailCode))
+ }
+ return nil
+ default:
+ return connect.NewError(connect.CodeInvalidArgument, errors.Errorf("credential must set exactly one proof"))
+ }
+}
+
+// checkEmailCodeEligible enforces email_code's server-side eligibility rule:
+// Bytebase Cloud only, and never against a live MFA factor. A mailbox code is
+// bootstrap proof for an account that has nothing else to prove — on Cloud,
+// where no caller-chosen password can exist, that is every account without
+// MFA — and never a substitute for a credential that does exist.
+//
+// The Cloud restriction is scope, not capability: a self-hosted workspace with
+// its mail delivery setting configured sends password-reset codes today and
+// could send these. It is withheld there because self-hosted keeps an
+// administrator who can reset a password, which is the recovery route
+// errFirstTimeEnrollmentNeedsPassword names.
+func (s *UserService) checkEmailCodeEligible(user *store.UserMessage) error {
+ if !s.profile.SaaS {
+ return connect.NewError(connect.CodeFailedPrecondition, errors.Errorf("email verification codes are only available on Bytebase Cloud"))
+ }
+ if user.MFAConfig.GetOtpSecret() != "" {
+ return connect.NewError(connect.CodeInvalidArgument, errors.Errorf("this account has MFA enabled; prove it with an OTP or recovery code"))
+ }
+ return nil
+}
+
+// checkPendingMFAState rejects a confirmation whose pending_version no longer
+// matches the account's pending MFA state — a later mint superseded the set
+// this request thinks it is confirming, or a DisableMFA wiped it.
+var errSupersededPendingMFAState = connect.NewError(connect.CodeFailedPrecondition,
+ errors.New("the pending MFA state has been superseded; restart from the mint step"))
+
+func checkPendingMFAState(user *store.UserMessage, pendingVersion *timestamppb.Timestamp) error {
+ stored := user.MFAConfig.GetTempOtpSecretCreatedTime()
+ if stored == nil || !stored.AsTime().Equal(pendingVersion.AsTime()) {
+ return errSupersededPendingMFAState
+ }
+ return nil
+}
+
+// checkEnableMFAConfirmable refuses the stale-enrollment states EnableMFA
+// cannot act on: a superseded pending version, no enrollment in progress, or
+// an expired one.
+func checkEnableMFAConfirmable(user *store.UserMessage, pendingVersion *timestamppb.Timestamp) error {
+ if err := checkPendingMFAState(user, pendingVersion); err != nil {
+ return err
+ }
+ if user.MFAConfig.GetTempOtpSecret() == "" {
+ return connect.NewError(connect.CodeFailedPrecondition, errors.Errorf("no MFA enrollment in progress, call StartMFAEnrollment first"))
+ }
+ if isMFATempSecretExpired(user.MFAConfig) {
+ return connect.NewError(connect.CodeInvalidArgument, errors.Errorf("MFA setup has expired, please restart the enrollment"))
+ }
+ return nil
+}
+
+// checkEnableMFACredentialShape refuses an EnableMFA whose credential does not
+// fit the account's shape. Replacing a live factor must be proven with the
+// factor; a first-time enrollment on self-hosted must be proven with the
+// password, which is also the only proof channel there.
+//
+// Whether the caller has a password is answered by whether they can supply
+// one, not by a stored timestamp. Inferring it from lastChangePasswordTime
+// meant an SSO account — whose password is a random string nobody was ever
+// told — read as "has a password" and was asked to prove it, which is a dead
+// end rather than an answer. The refusal below names the route out instead.
+func (s *UserService) checkEnableMFACredentialShape(user *store.UserMessage, credential *v1pb.CredentialProof) error {
+ if user.MFAConfig.GetOtpSecret() != "" || !s.profile.SaaS {
+ if credential == nil {
+ return errFirstTimeEnrollmentNeedsPassword
+ }
+ return s.checkFactorProofShape(user, credential)
+ }
+ if credential != nil {
+ // Cloud passwordless enrollment: email_code would be the only
+ // possible proof, and it is single-use — consumed once, at
+ // ConfirmRecoveryCodes, where the mutation actually happens. This
+ // call writes nothing for this account shape, so it needs no proof
+ // at all.
+ return connect.NewError(connect.CodeInvalidArgument, errors.Errorf("credential must be omitted for first-time enrollment on an account without a password"))
+ }
+ return nil
+}
+
+// checkFactorProofShape refuses, before any slot is claimed, a proof channel
+// that a live factor could never accept. verifyCredentialProof rejects these
+// too, but it does so after the claim — and a request naming a channel this
+// account cannot use has guessed at nothing, so five of them must not lock the
+// bucket ordinary password or email-code logins draw from.
+func (s *UserService) checkFactorProofShape(user *store.UserMessage, credential *v1pb.CredentialProof) error {
+ if credential == nil {
+ return nil
+ }
+ if user.MFAConfig.GetOtpSecret() != "" {
+ switch credential.GetProof().(type) {
+ case *v1pb.CredentialProof_OtpCode, *v1pb.CredentialProof_RecoveryCode:
+ return nil
+ default:
+ return connect.NewError(connect.CodeInvalidArgument, errors.Errorf("changing the MFA factor requires an OTP or recovery code, not the password"))
+ }
+ }
+ // No live factor, so exactly one channel can succeed and it is decided by
+ // the deployment: self-hosted accounts prove the password they have, Cloud
+ // accounts an emailed code because they never have a caller-chosen one.
+ if !s.profile.SaaS {
+ if _, ok := credential.GetProof().(*v1pb.CredentialProof_CurrentPassword); !ok {
+ return connect.NewError(connect.CodeInvalidArgument, errors.Errorf("this account has no MFA factor; prove it with your current password"))
+ }
+ return nil
+ }
+ if _, ok := credential.GetProof().(*v1pb.CredentialProof_EmailCode); !ok {
+ return connect.NewError(connect.CodeInvalidArgument, errors.Errorf("this account has no MFA factor or password; prove it with an emailed code"))
+ }
+ return nil
+}
+
+// checkRecoveryCodesConfirmable refuses the state and argument shapes
+// ConfirmRecoveryCodes cannot act on, for both branches.
+func checkRecoveryCodesConfirmable(user *store.UserMessage, pendingVersion *timestamppb.Timestamp, otpCode string, firstTime bool) error {
+ if err := checkPendingMFAState(user, pendingVersion); err != nil {
+ return err
+ }
+ if len(user.MFAConfig.GetTempRecoveryCodes()) == 0 {
+ return connect.NewError(connect.CodeFailedPrecondition, errors.Errorf("no pending recovery codes to confirm"))
+ }
+ if !firstTime {
+ // The live factor is the proof for a rotation or a replacement; the
+ // new device was already validated by EnableMFA.
+ if otpCode != "" {
+ return connect.NewError(connect.CodeInvalidArgument, errors.Errorf("otp_code is only for first-time enrollment; use credential to prove the existing factor"))
+ }
+ return nil
+ }
+ // A fresh code, not a replay of EnableMFA's: TOTP codes outlive one ~30s
+ // window and the download screen in between routinely takes longer — and
+ // promotion is exactly the moment MFA goes live.
+ if otpCode == "" {
+ return connect.NewError(connect.CodeInvalidArgument, errors.Errorf("otp_code is required to complete first-time enrollment"))
+ }
+ return nil
+}
+
+// firstTimeEnrollmentProofError makes a failed first-time-enrollment password
+// proof actionable. The 3.22 backfill stamps every pre-existing account as
+// having a chosen password — including SSO-provisioned ones whose password is
+// a random hash nobody knows — so a failed compare here may mean "no password
+// exists to know", and the recovery route is the same admin reset an
+// unstamped account is pointed at. Rotation keeps the bare refusal: a live
+// factor means the password was never the required proof.
+func firstTimeEnrollmentProofError(err error, rotation bool, credential *v1pb.CredentialProof) error {
+ if rotation || connect.CodeOf(err) != connect.CodeUnauthenticated {
+ return err
+ }
+ if _, ok := credential.GetProof().(*v1pb.CredentialProof_CurrentPassword); !ok {
+ return err
+ }
+ return connect.NewError(connect.CodeUnauthenticated, errors.Errorf("invalid password; if you sign in through SSO and never chose a password, ask a workspace admin to reset your password, then enroll with it"))
+}
+
func (s *UserService) convertUserResponse(ctx context.Context, user *store.UserMessage) (*connect.Response[v1pb.User], error) {
v1User, err := convertToUser(ctx, s.iamManager, user)
if err != nil {
@@ -913,6 +1394,10 @@ func (s *UserService) convertUserResponse(ctx context.Context, user *store.UserM
return connect.NewResponse(v1User), nil
}
+// convertToUser converts a stored user for a read. MFA enrollment state never
+// appears here: the pending TOTP seed and recovery codes are returned exactly
+// once, by StartMFAEnrollment, and a read that carried either would hand a
+// reader the account's second factor.
func convertToUser(ctx context.Context, iamManager *iam.Manager, user *store.UserMessage) (*v1pb.User, error) {
groups, err := iamManager.GetUserGroups(ctx, common.GetWorkspaceIDFromContext(ctx), user.Email)
if err != nil {
@@ -1023,7 +1508,8 @@ func isMFATempSecretExpired(mfaConfig *storepb.MFAConfig) bool {
return time.Since(createdAt) > mfaTempSecretExpiration
}
-// generateRandSecret generates a random secret for the given account name.
+// generateRandSecret generates a random TOTP secret for the given account
+// name, returning the secret and its otpauth:// provisioning URI.
func generateRandSecret(accountName string) (string, error) {
key, err := totp.Generate(totp.GenerateOpts{
Issuer: issuerName,
diff --git a/backend/api/v1/user_service_credential_test.go b/backend/api/v1/user_service_credential_test.go
new file mode 100644
index 0000000000..1538747e4f
--- /dev/null
+++ b/backend/api/v1/user_service_credential_test.go
@@ -0,0 +1,90 @@
+package v1
+
+import (
+ "testing"
+
+ "connectrpc.com/connect"
+ "github.com/stretchr/testify/require"
+ "google.golang.org/protobuf/types/known/timestamppb"
+
+ "github.com/bytebase/bytebase/backend/component/config"
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+ v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"
+ "github.com/bytebase/bytebase/backend/store"
+)
+
+// TestEmailCodeEligibility pins the deployment split for the email_code proof
+// channel: Cloud only — self-hosted keeps an administrator who can reset a
+// password instead — and never against a live MFA factor. The SaaS side has
+// no e2e harness, so the rule is pinned here.
+func TestEmailCodeEligibility(t *testing.T) {
+ userWith := func(otpSecret string, lastChangePassword bool) *store.UserMessage {
+ profile := &storepb.UserProfile{}
+ if lastChangePassword {
+ profile.LastChangePasswordTime = timestamppb.Now()
+ }
+ return &store.UserMessage{
+ MFAConfig: &storepb.MFAConfig{OtpSecret: otpSecret},
+ Profile: profile,
+ }
+ }
+
+ saas := &UserService{profile: &config.Profile{SaaS: true}}
+ selfHosted := &UserService{profile: &config.Profile{SaaS: false}}
+
+ require.NoError(t, saas.checkEmailCodeEligible(userWith("", false)),
+ "a Cloud account without MFA is exactly who the channel exists for")
+ err := saas.checkEmailCodeEligible(userWith("live-secret", false))
+ require.Equal(t, connect.CodeInvalidArgument, connect.CodeOf(err),
+ "a mailbox code must never stand in for a live factor")
+
+ for _, user := range []*store.UserMessage{
+ userWith("", false),
+ userWith("", true),
+ userWith("live-secret", false),
+ } {
+ err := selfHosted.checkEmailCodeEligible(user)
+ require.Equal(t, connect.CodeFailedPrecondition, connect.CodeOf(err),
+ "self-hosted has no email capability, so the channel does not exist there for any account")
+ require.ErrorContains(t, err, "Cloud")
+ }
+}
+
+// TestFirstTimeEnrollmentCredentialShape pins which first-time enrollments
+// must carry a password proof, now that the answer comes from the deployment
+// rather than from a stored timestamp: self-hosted always, because the
+// password is the only proof channel there, and Cloud never, because no
+// account has a caller-chosen password and the emailed code is spent at
+// promotion instead.
+//
+// The self-hosted refusal has to name the administrator-reset route: an
+// SSO-provisioned account holds a random password nobody was told, and the
+// server cannot tell it apart from one whose owner simply did not type it.
+func TestFirstTimeEnrollmentCredentialShape(t *testing.T) {
+ saas := &UserService{profile: &config.Profile{SaaS: true}}
+ selfHosted := &UserService{profile: &config.Profile{SaaS: false}}
+ enrolling := &store.UserMessage{
+ MFAConfig: &storepb.MFAConfig{TempOtpSecret: "pending"},
+ Profile: &storepb.UserProfile{},
+ }
+ password := &v1pb.CredentialProof{
+ Proof: &v1pb.CredentialProof_CurrentPassword{CurrentPassword: "hunter2"},
+ }
+
+ err := selfHosted.checkEnableMFACredentialShape(enrolling, nil)
+ require.Equal(t, connect.CodeFailedPrecondition, connect.CodeOf(err))
+ require.ErrorContains(t, err, "ask a workspace admin")
+ require.NoError(t, selfHosted.checkEnableMFACredentialShape(enrolling, password))
+
+ require.NoError(t, saas.checkEnableMFACredentialShape(enrolling, nil),
+ "Cloud proves a first-time enrollment with the emailed code at promotion")
+
+ // A live factor is proven with the factor on either deployment.
+ rotating := &store.UserMessage{
+ MFAConfig: &storepb.MFAConfig{OtpSecret: "live", TempOtpSecret: "pending"},
+ Profile: &storepb.UserProfile{},
+ }
+ for _, s := range []*UserService{saas, selfHosted} {
+ require.Error(t, s.checkEnableMFACredentialShape(rotating, nil))
+ }
+}
diff --git a/backend/generated-go/store/auth.pb.go b/backend/generated-go/store/auth.pb.go
index 53d2e2c374..39f8867993 100644
--- a/backend/generated-go/store/auth.pb.go
+++ b/backend/generated-go/store/auth.pb.go
@@ -29,6 +29,9 @@ const (
EmailVerificationCodePurpose_EMAIL_VERIFICATION_CODE_PURPOSE_UNSPECIFIED EmailVerificationCodePurpose = 0
EmailVerificationCodePurpose_LOGIN EmailVerificationCodePurpose = 1
EmailVerificationCodePurpose_PASSWORD_RESET EmailVerificationCodePurpose = 2
+ // Re-authentication proof for a credential change
+ // (CredentialProof.email_code). Never accepted by Login.
+ EmailVerificationCodePurpose_REAUTH EmailVerificationCodePurpose = 3
)
// Enum value maps for EmailVerificationCodePurpose.
@@ -37,11 +40,13 @@ var (
0: "EMAIL_VERIFICATION_CODE_PURPOSE_UNSPECIFIED",
1: "LOGIN",
2: "PASSWORD_RESET",
+ 3: "REAUTH",
}
EmailVerificationCodePurpose_value = map[string]int32{
"EMAIL_VERIFICATION_CODE_PURPOSE_UNSPECIFIED": 0,
"LOGIN": 1,
"PASSWORD_RESET": 2,
+ "REAUTH": 3,
}
)
@@ -130,11 +135,13 @@ var File_store_auth_proto protoreflect.FileDescriptor
const file_store_auth_proto_rawDesc = "" +
"\n" +
- "\x10store/auth.proto\x12\x0ebytebase.store*n\n" +
+ "\x10store/auth.proto\x12\x0ebytebase.store*z\n" +
"\x1cEmailVerificationCodePurpose\x12/\n" +
"+EMAIL_VERIFICATION_CODE_PURPOSE_UNSPECIFIED\x10\x00\x12\t\n" +
"\x05LOGIN\x10\x01\x12\x12\n" +
- "\x0ePASSWORD_RESET\x10\x02*]\n" +
+ "\x0ePASSWORD_RESET\x10\x02\x12\n" +
+ "\n" +
+ "\x06REAUTH\x10\x03*]\n" +
"\x10LoginAttemptKind\x12\"\n" +
"\x1eLOGIN_ATTEMPT_KIND_UNSPECIFIED\x10\x00\x12\f\n" +
"\bPASSWORD\x10\x01\x12\x0e\n" +
diff --git a/backend/generated-go/v1/annotation.pb.go b/backend/generated-go/v1/annotation.pb.go
index 9ccc47b3d2..d5ca7d103f 100644
--- a/backend/generated-go/v1/annotation.pb.go
+++ b/backend/generated-go/v1/annotation.pb.go
@@ -248,7 +248,7 @@ const (
// Puts a token for the caller's own principal in the response body.
MCPDenialReason_MINTS_CREDENTIAL MCPDenialReason = 1
// Drives the out-of-band reset flow that sets or delivers the secret a
- // login accepts.
+ // login or a credential change accepts.
MCPDenialReason_RESETS_CREDENTIAL MCPDenialReason = 2
// Rewrites an account's own credentials, which would let the session log in
// as that account.
diff --git a/backend/generated-go/v1/auth_service_grpc.pb.go b/backend/generated-go/v1/auth_service_grpc.pb.go
index 4dddf194bf..a3dd328bfb 100644
--- a/backend/generated-go/v1/auth_service_grpc.pb.go
+++ b/backend/generated-go/v1/auth_service_grpc.pb.go
@@ -64,6 +64,8 @@ type AuthServiceClient interface {
SwitchWorkspace(ctx context.Context, in *SwitchWorkspaceRequest, opts ...grpc.CallOption) (*LoginResponse, error)
// Requests a password reset email for the given email address.
// Always returns success to avoid leaking whether the email exists.
+ // Requires the workspace's SMTP mail delivery setting; without it the
+ // recovery route is an admin password reset.
// Permissions required: None
RequestPasswordReset(ctx context.Context, in *RequestPasswordResetRequest, opts ...grpc.CallOption) (*emptypb.Empty, error)
// Resets the user's password using a password reset token from email.
@@ -71,6 +73,8 @@ type AuthServiceClient interface {
ResetPassword(ctx context.Context, in *ResetPasswordRequest, opts ...grpc.CallOption) (*emptypb.Empty, error)
// Sends a 6-digit verification code to the email for login/signup.
// Always returns success (no email enumeration). Enforces 60-sec resend cooldown.
+ // The signed-in counterpart is UserService.RequestReauthCode; LOGIN and
+ // REAUTH codes are not interchangeable.
// Permissions required: None
SendEmailLoginCode(ctx context.Context, in *SendEmailLoginCodeRequest, opts ...grpc.CallOption) (*emptypb.Empty, error)
}
@@ -215,6 +219,8 @@ type AuthServiceServer interface {
SwitchWorkspace(context.Context, *SwitchWorkspaceRequest) (*LoginResponse, error)
// Requests a password reset email for the given email address.
// Always returns success to avoid leaking whether the email exists.
+ // Requires the workspace's SMTP mail delivery setting; without it the
+ // recovery route is an admin password reset.
// Permissions required: None
RequestPasswordReset(context.Context, *RequestPasswordResetRequest) (*emptypb.Empty, error)
// Resets the user's password using a password reset token from email.
@@ -222,6 +228,8 @@ type AuthServiceServer interface {
ResetPassword(context.Context, *ResetPasswordRequest) (*emptypb.Empty, error)
// Sends a 6-digit verification code to the email for login/signup.
// Always returns success (no email enumeration). Enforces 60-sec resend cooldown.
+ // The signed-in counterpart is UserService.RequestReauthCode; LOGIN and
+ // REAUTH codes are not interchangeable.
// Permissions required: None
SendEmailLoginCode(context.Context, *SendEmailLoginCodeRequest) (*emptypb.Empty, error)
mustEmbedUnimplementedAuthServiceServer()
diff --git a/backend/generated-go/v1/user_service.pb.go b/backend/generated-go/v1/user_service.pb.go
index c6ac0f371f..f86efe964e 100644
--- a/backend/generated-go/v1/user_service.pb.go
+++ b/backend/generated-go/v1/user_service.pb.go
@@ -575,18 +575,186 @@ func (x *UpdateEmailRequest) GetEmail() string {
return ""
}
-type ChangePasswordRequest struct {
+// One proof that the caller currently controls a credential on the account.
+// Exactly one field must be set; enforced in the handler.
+type CredentialProof struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ // Types that are valid to be assigned to Proof:
+ //
+ // *CredentialProof_CurrentPassword
+ // *CredentialProof_OtpCode
+ // *CredentialProof_RecoveryCode
+ // *CredentialProof_EmailCode
+ Proof isCredentialProof_Proof `protobuf_oneof:"proof"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *CredentialProof) Reset() {
+ *x = CredentialProof{}
+ mi := &file_v1_user_service_proto_msgTypes[10]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *CredentialProof) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*CredentialProof) ProtoMessage() {}
+
+func (x *CredentialProof) ProtoReflect() protoreflect.Message {
+ mi := &file_v1_user_service_proto_msgTypes[10]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use CredentialProof.ProtoReflect.Descriptor instead.
+func (*CredentialProof) Descriptor() ([]byte, []int) {
+ return file_v1_user_service_proto_rawDescGZIP(), []int{10}
+}
+
+func (x *CredentialProof) GetProof() isCredentialProof_Proof {
+ if x != nil {
+ return x.Proof
+ }
+ return nil
+}
+
+func (x *CredentialProof) GetCurrentPassword() string {
+ if x != nil {
+ if x, ok := x.Proof.(*CredentialProof_CurrentPassword); ok {
+ return x.CurrentPassword
+ }
+ }
+ return ""
+}
+
+func (x *CredentialProof) GetOtpCode() string {
+ if x != nil {
+ if x, ok := x.Proof.(*CredentialProof_OtpCode); ok {
+ return x.OtpCode
+ }
+ }
+ return ""
+}
+
+func (x *CredentialProof) GetRecoveryCode() string {
+ if x != nil {
+ if x, ok := x.Proof.(*CredentialProof_RecoveryCode); ok {
+ return x.RecoveryCode
+ }
+ }
+ return ""
+}
+
+func (x *CredentialProof) GetEmailCode() string {
+ if x != nil {
+ if x, ok := x.Proof.(*CredentialProof_EmailCode); ok {
+ return x.EmailCode
+ }
+ }
+ return ""
+}
+
+type isCredentialProof_Proof interface {
+ isCredentialProof_Proof()
+}
+
+type CredentialProof_CurrentPassword struct {
+ // The account's current password. Refused by a factor-touching method
+ // while a live MFA factor exists.
+ CurrentPassword string `protobuf:"bytes,1,opt,name=current_password,json=currentPassword,proto3,oneof"`
+}
+
+type CredentialProof_OtpCode struct {
+ // A live code from the account's enrolled TOTP authenticator.
+ OtpCode string `protobuf:"bytes,2,opt,name=otp_code,json=otpCode,proto3,oneof"`
+}
+
+type CredentialProof_RecoveryCode struct {
+ // A single-use MFA recovery code.
+ RecoveryCode string `protobuf:"bytes,3,opt,name=recovery_code,json=recoveryCode,proto3,oneof"`
+}
+
+type CredentialProof_EmailCode struct {
+ // A one-time code from RequestReauthCode. Bytebase Cloud only, and only
+ // while the account has no live MFA factor.
+ EmailCode string `protobuf:"bytes,4,opt,name=email_code,json=emailCode,proto3,oneof"`
+}
+
+func (*CredentialProof_CurrentPassword) isCredentialProof_Proof() {}
+
+func (*CredentialProof_OtpCode) isCredentialProof_Proof() {}
+
+func (*CredentialProof_RecoveryCode) isCredentialProof_Proof() {}
+
+func (*CredentialProof_EmailCode) isCredentialProof_Proof() {}
+
+type RequestReauthCodeRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
// Format: users/{email}. Must be the caller's own name.
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
- NewPassword string `protobuf:"bytes,2,opt,name=new_password,json=newPassword,proto3" json:"new_password,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *RequestReauthCodeRequest) Reset() {
+ *x = RequestReauthCodeRequest{}
+ mi := &file_v1_user_service_proto_msgTypes[11]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *RequestReauthCodeRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*RequestReauthCodeRequest) ProtoMessage() {}
+
+func (x *RequestReauthCodeRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_v1_user_service_proto_msgTypes[11]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use RequestReauthCodeRequest.ProtoReflect.Descriptor instead.
+func (*RequestReauthCodeRequest) Descriptor() ([]byte, []int) {
+ return file_v1_user_service_proto_rawDescGZIP(), []int{11}
+}
+
+func (x *RequestReauthCodeRequest) GetName() string {
+ if x != nil {
+ return x.Name
+ }
+ return ""
+}
+
+type ChangePasswordRequest struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ // Format: users/{email}. Must be the caller's own name.
+ Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
+ NewPassword string `protobuf:"bytes,2,opt,name=new_password,json=newPassword,proto3" json:"new_password,omitempty"`
+ Credential *CredentialProof `protobuf:"bytes,3,opt,name=credential,proto3" json:"credential,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *ChangePasswordRequest) Reset() {
*x = ChangePasswordRequest{}
- mi := &file_v1_user_service_proto_msgTypes[10]
+ mi := &file_v1_user_service_proto_msgTypes[12]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -598,7 +766,7 @@ func (x *ChangePasswordRequest) String() string {
func (*ChangePasswordRequest) ProtoMessage() {}
func (x *ChangePasswordRequest) ProtoReflect() protoreflect.Message {
- mi := &file_v1_user_service_proto_msgTypes[10]
+ mi := &file_v1_user_service_proto_msgTypes[12]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -611,7 +779,7 @@ func (x *ChangePasswordRequest) ProtoReflect() protoreflect.Message {
// Deprecated: Use ChangePasswordRequest.ProtoReflect.Descriptor instead.
func (*ChangePasswordRequest) Descriptor() ([]byte, []int) {
- return file_v1_user_service_proto_rawDescGZIP(), []int{10}
+ return file_v1_user_service_proto_rawDescGZIP(), []int{12}
}
func (x *ChangePasswordRequest) GetName() string {
@@ -628,6 +796,13 @@ func (x *ChangePasswordRequest) GetNewPassword() string {
return ""
}
+func (x *ChangePasswordRequest) GetCredential() *CredentialProof {
+ if x != nil {
+ return x.Credential
+ }
+ return nil
+}
+
type StartMFAEnrollmentRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
// Format: users/{email}. Must be the caller's own name.
@@ -638,7 +813,7 @@ type StartMFAEnrollmentRequest struct {
func (x *StartMFAEnrollmentRequest) Reset() {
*x = StartMFAEnrollmentRequest{}
- mi := &file_v1_user_service_proto_msgTypes[11]
+ mi := &file_v1_user_service_proto_msgTypes[13]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -650,7 +825,7 @@ func (x *StartMFAEnrollmentRequest) String() string {
func (*StartMFAEnrollmentRequest) ProtoMessage() {}
func (x *StartMFAEnrollmentRequest) ProtoReflect() protoreflect.Message {
- mi := &file_v1_user_service_proto_msgTypes[11]
+ mi := &file_v1_user_service_proto_msgTypes[13]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -663,7 +838,7 @@ func (x *StartMFAEnrollmentRequest) ProtoReflect() protoreflect.Message {
// Deprecated: Use StartMFAEnrollmentRequest.ProtoReflect.Descriptor instead.
func (*StartMFAEnrollmentRequest) Descriptor() ([]byte, []int) {
- return file_v1_user_service_proto_rawDescGZIP(), []int{11}
+ return file_v1_user_service_proto_rawDescGZIP(), []int{13}
}
func (x *StartMFAEnrollmentRequest) GetName() string {
@@ -693,7 +868,7 @@ type StartMFAEnrollmentResponse struct {
func (x *StartMFAEnrollmentResponse) Reset() {
*x = StartMFAEnrollmentResponse{}
- mi := &file_v1_user_service_proto_msgTypes[12]
+ mi := &file_v1_user_service_proto_msgTypes[14]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -705,7 +880,7 @@ func (x *StartMFAEnrollmentResponse) String() string {
func (*StartMFAEnrollmentResponse) ProtoMessage() {}
func (x *StartMFAEnrollmentResponse) ProtoReflect() protoreflect.Message {
- mi := &file_v1_user_service_proto_msgTypes[12]
+ mi := &file_v1_user_service_proto_msgTypes[14]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -718,7 +893,7 @@ func (x *StartMFAEnrollmentResponse) ProtoReflect() protoreflect.Message {
// Deprecated: Use StartMFAEnrollmentResponse.ProtoReflect.Descriptor instead.
func (*StartMFAEnrollmentResponse) Descriptor() ([]byte, []int) {
- return file_v1_user_service_proto_rawDescGZIP(), []int{12}
+ return file_v1_user_service_proto_rawDescGZIP(), []int{14}
}
func (x *StartMFAEnrollmentResponse) GetOtpSecret() string {
@@ -757,13 +932,16 @@ type EnableMFARequest struct {
OtpCode string `protobuf:"bytes,2,opt,name=otp_code,json=otpCode,proto3" json:"otp_code,omitempty"`
// The pending_version this enrollment was minted with.
PendingVersion *timestamppb.Timestamp `protobuf:"bytes,3,opt,name=pending_version,json=pendingVersion,proto3" json:"pending_version,omitempty"`
- unknownFields protoimpl.UnknownFields
- sizeCache protoimpl.SizeCache
+ // Proof of the *existing* factor, not the new device above. Required for a
+ // rotation, and for first-time enrollment on an account with a password.
+ Credential *CredentialProof `protobuf:"bytes,4,opt,name=credential,proto3" json:"credential,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
}
func (x *EnableMFARequest) Reset() {
*x = EnableMFARequest{}
- mi := &file_v1_user_service_proto_msgTypes[13]
+ mi := &file_v1_user_service_proto_msgTypes[15]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -775,7 +953,7 @@ func (x *EnableMFARequest) String() string {
func (*EnableMFARequest) ProtoMessage() {}
func (x *EnableMFARequest) ProtoReflect() protoreflect.Message {
- mi := &file_v1_user_service_proto_msgTypes[13]
+ mi := &file_v1_user_service_proto_msgTypes[15]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -788,7 +966,7 @@ func (x *EnableMFARequest) ProtoReflect() protoreflect.Message {
// Deprecated: Use EnableMFARequest.ProtoReflect.Descriptor instead.
func (*EnableMFARequest) Descriptor() ([]byte, []int) {
- return file_v1_user_service_proto_rawDescGZIP(), []int{13}
+ return file_v1_user_service_proto_rawDescGZIP(), []int{15}
}
func (x *EnableMFARequest) GetName() string {
@@ -812,18 +990,28 @@ func (x *EnableMFARequest) GetPendingVersion() *timestamppb.Timestamp {
return nil
}
+func (x *EnableMFARequest) GetCredential() *CredentialProof {
+ if x != nil {
+ return x.Credential
+ }
+ return nil
+}
+
type DisableMFARequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
// Format: users/{email}. The caller's own, or another user's with
// bb.users.update.
- Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
+ Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
+ // Required for a self-service call against a live factor, and then only
+ // otp_code or recovery_code. Unused on an admin-assisted call.
+ Credential *CredentialProof `protobuf:"bytes,2,opt,name=credential,proto3" json:"credential,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *DisableMFARequest) Reset() {
*x = DisableMFARequest{}
- mi := &file_v1_user_service_proto_msgTypes[14]
+ mi := &file_v1_user_service_proto_msgTypes[16]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -835,7 +1023,7 @@ func (x *DisableMFARequest) String() string {
func (*DisableMFARequest) ProtoMessage() {}
func (x *DisableMFARequest) ProtoReflect() protoreflect.Message {
- mi := &file_v1_user_service_proto_msgTypes[14]
+ mi := &file_v1_user_service_proto_msgTypes[16]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -848,7 +1036,7 @@ func (x *DisableMFARequest) ProtoReflect() protoreflect.Message {
// Deprecated: Use DisableMFARequest.ProtoReflect.Descriptor instead.
func (*DisableMFARequest) Descriptor() ([]byte, []int) {
- return file_v1_user_service_proto_rawDescGZIP(), []int{14}
+ return file_v1_user_service_proto_rawDescGZIP(), []int{16}
}
func (x *DisableMFARequest) GetName() string {
@@ -858,6 +1046,13 @@ func (x *DisableMFARequest) GetName() string {
return ""
}
+func (x *DisableMFARequest) GetCredential() *CredentialProof {
+ if x != nil {
+ return x.Credential
+ }
+ return nil
+}
+
type RegenerateRecoveryCodesRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
// Format: users/{email}. Must be the caller's own name.
@@ -868,7 +1063,7 @@ type RegenerateRecoveryCodesRequest struct {
func (x *RegenerateRecoveryCodesRequest) Reset() {
*x = RegenerateRecoveryCodesRequest{}
- mi := &file_v1_user_service_proto_msgTypes[15]
+ mi := &file_v1_user_service_proto_msgTypes[17]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -880,7 +1075,7 @@ func (x *RegenerateRecoveryCodesRequest) String() string {
func (*RegenerateRecoveryCodesRequest) ProtoMessage() {}
func (x *RegenerateRecoveryCodesRequest) ProtoReflect() protoreflect.Message {
- mi := &file_v1_user_service_proto_msgTypes[15]
+ mi := &file_v1_user_service_proto_msgTypes[17]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -893,7 +1088,7 @@ func (x *RegenerateRecoveryCodesRequest) ProtoReflect() protoreflect.Message {
// Deprecated: Use RegenerateRecoveryCodesRequest.ProtoReflect.Descriptor instead.
func (*RegenerateRecoveryCodesRequest) Descriptor() ([]byte, []int) {
- return file_v1_user_service_proto_rawDescGZIP(), []int{15}
+ return file_v1_user_service_proto_rawDescGZIP(), []int{17}
}
func (x *RegenerateRecoveryCodesRequest) GetName() string {
@@ -915,7 +1110,7 @@ type RegenerateRecoveryCodesResponse struct {
func (x *RegenerateRecoveryCodesResponse) Reset() {
*x = RegenerateRecoveryCodesResponse{}
- mi := &file_v1_user_service_proto_msgTypes[16]
+ mi := &file_v1_user_service_proto_msgTypes[18]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -927,7 +1122,7 @@ func (x *RegenerateRecoveryCodesResponse) String() string {
func (*RegenerateRecoveryCodesResponse) ProtoMessage() {}
func (x *RegenerateRecoveryCodesResponse) ProtoReflect() protoreflect.Message {
- mi := &file_v1_user_service_proto_msgTypes[16]
+ mi := &file_v1_user_service_proto_msgTypes[18]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -940,7 +1135,7 @@ func (x *RegenerateRecoveryCodesResponse) ProtoReflect() protoreflect.Message {
// Deprecated: Use RegenerateRecoveryCodesResponse.ProtoReflect.Descriptor instead.
func (*RegenerateRecoveryCodesResponse) Descriptor() ([]byte, []int) {
- return file_v1_user_service_proto_rawDescGZIP(), []int{16}
+ return file_v1_user_service_proto_rawDescGZIP(), []int{18}
}
func (x *RegenerateRecoveryCodesResponse) GetRecoveryCodes() []string {
@@ -964,13 +1159,17 @@ type ConfirmRecoveryCodesRequest struct {
// The pending_version of the codes being confirmed. Confirming promotes
// exactly the set this version identifies, or nothing.
PendingVersion *timestamppb.Timestamp `protobuf:"bytes,2,opt,name=pending_version,json=pendingVersion,proto3" json:"pending_version,omitempty"`
- unknownFields protoimpl.UnknownFields
- sizeCache protoimpl.SizeCache
+ Credential *CredentialProof `protobuf:"bytes,3,opt,name=credential,proto3" json:"credential,omitempty"`
+ // Required for first-time enrollment, rejected otherwise. A *fresh* code,
+ // not the one EnableMFA took.
+ OtpCode string `protobuf:"bytes,4,opt,name=otp_code,json=otpCode,proto3" json:"otp_code,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
}
func (x *ConfirmRecoveryCodesRequest) Reset() {
*x = ConfirmRecoveryCodesRequest{}
- mi := &file_v1_user_service_proto_msgTypes[17]
+ mi := &file_v1_user_service_proto_msgTypes[19]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -982,7 +1181,7 @@ func (x *ConfirmRecoveryCodesRequest) String() string {
func (*ConfirmRecoveryCodesRequest) ProtoMessage() {}
func (x *ConfirmRecoveryCodesRequest) ProtoReflect() protoreflect.Message {
- mi := &file_v1_user_service_proto_msgTypes[17]
+ mi := &file_v1_user_service_proto_msgTypes[19]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -995,7 +1194,7 @@ func (x *ConfirmRecoveryCodesRequest) ProtoReflect() protoreflect.Message {
// Deprecated: Use ConfirmRecoveryCodesRequest.ProtoReflect.Descriptor instead.
func (*ConfirmRecoveryCodesRequest) Descriptor() ([]byte, []int) {
- return file_v1_user_service_proto_rawDescGZIP(), []int{17}
+ return file_v1_user_service_proto_rawDescGZIP(), []int{19}
}
func (x *ConfirmRecoveryCodesRequest) GetName() string {
@@ -1012,6 +1211,20 @@ func (x *ConfirmRecoveryCodesRequest) GetPendingVersion() *timestamppb.Timestamp
return nil
}
+func (x *ConfirmRecoveryCodesRequest) GetCredential() *CredentialProof {
+ if x != nil {
+ return x.Credential
+ }
+ return nil
+}
+
+func (x *ConfirmRecoveryCodesRequest) GetOtpCode() string {
+ if x != nil {
+ return x.OtpCode
+ }
+ return ""
+}
+
type User struct {
state protoimpl.MessageState `protogen:"open.v1"`
// The name of the user.
@@ -1045,7 +1258,7 @@ type User struct {
func (x *User) Reset() {
*x = User{}
- mi := &file_v1_user_service_proto_msgTypes[18]
+ mi := &file_v1_user_service_proto_msgTypes[20]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -1057,7 +1270,7 @@ func (x *User) String() string {
func (*User) ProtoMessage() {}
func (x *User) ProtoReflect() protoreflect.Message {
- mi := &file_v1_user_service_proto_msgTypes[18]
+ mi := &file_v1_user_service_proto_msgTypes[20]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -1070,7 +1283,7 @@ func (x *User) ProtoReflect() protoreflect.Message {
// Deprecated: Use User.ProtoReflect.Descriptor instead.
func (*User) Descriptor() ([]byte, []int) {
- return file_v1_user_service_proto_rawDescGZIP(), []int{18}
+ return file_v1_user_service_proto_rawDescGZIP(), []int{20}
}
func (x *User) GetName() string {
@@ -1157,7 +1370,7 @@ type User_Profile struct {
func (x *User_Profile) Reset() {
*x = User_Profile{}
- mi := &file_v1_user_service_proto_msgTypes[19]
+ mi := &file_v1_user_service_proto_msgTypes[21]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -1169,7 +1382,7 @@ func (x *User_Profile) String() string {
func (*User_Profile) ProtoMessage() {}
func (x *User_Profile) ProtoReflect() protoreflect.Message {
- mi := &file_v1_user_service_proto_msgTypes[19]
+ mi := &file_v1_user_service_proto_msgTypes[21]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -1182,7 +1395,7 @@ func (x *User_Profile) ProtoReflect() protoreflect.Message {
// Deprecated: Use User_Profile.ProtoReflect.Descriptor instead.
func (*User_Profile) Descriptor() ([]byte, []int) {
- return file_v1_user_service_proto_rawDescGZIP(), []int{18, 0}
+ return file_v1_user_service_proto_rawDescGZIP(), []int{20, 0}
}
func (x *User_Profile) GetLastLoginTime() *timestamppb.Timestamp {
@@ -1244,11 +1457,24 @@ const file_v1_user_service_proto_rawDesc = "" +
"\x12UpdateEmailRequest\x12-\n" +
"\x04name\x18\x01 \x01(\tB\x19\xe0A\x02\xfaA\x13\n" +
"\x11bytebase.com/UserR\x04name\x12!\n" +
- "\x05email\x18\x02 \x01(\tB\v\xe0A\x02\xbaH\x05r\x03\x18\xfe\x01R\x05email\"\x81\x01\n" +
+ "\x05email\x18\x02 \x01(\tB\v\xe0A\x02\xbaH\x05r\x03\x18\xfe\x01R\x05email\"\xe0\x01\n" +
+ "\x0fCredentialProof\x128\n" +
+ "\x10current_password\x18\x01 \x01(\tB\v\xbaH\x04r\x02(H\xd0\xea0\x01H\x00R\x0fcurrentPassword\x12(\n" +
+ "\botp_code\x18\x02 \x01(\tB\v\xbaH\x04r\x02\x18@\xd0\xea0\x01H\x00R\aotpCode\x122\n" +
+ "\rrecovery_code\x18\x03 \x01(\tB\v\xbaH\x04r\x02\x18@\xd0\xea0\x01H\x00R\frecoveryCode\x12,\n" +
+ "\n" +
+ "email_code\x18\x04 \x01(\tB\v\xbaH\x04r\x02\x18@\xd0\xea0\x01H\x00R\temailCodeB\a\n" +
+ "\x05proof\"Q\n" +
+ "\x18RequestReauthCodeRequest\x125\n" +
+ "\x04name\x18\x01 \x01(\tB!\xe0A\x02\xfaA\x13\n" +
+ "\x11bytebase.com/User\xbaH\x05r\x03\x18\x84\x02R\x04name\"\xca\x01\n" +
"\x15ChangePasswordRequest\x125\n" +
"\x04name\x18\x01 \x01(\tB!\xe0A\x02\xfaA\x13\n" +
"\x11bytebase.com/User\xbaH\x05r\x03\x18\x84\x02R\x04name\x121\n" +
- "\fnew_password\x18\x02 \x01(\tB\x0e\xe0A\x02\xbaH\x04r\x02(H\xd0\xea0\x01R\vnewPassword\"R\n" +
+ "\fnew_password\x18\x02 \x01(\tB\x0e\xe0A\x02\xbaH\x04r\x02(H\xd0\xea0\x01R\vnewPassword\x12G\n" +
+ "\n" +
+ "credential\x18\x03 \x01(\v2\x1c.bytebase.v1.CredentialProofB\t\xe0A\x02\xbaH\x03\xc8\x01\x01R\n" +
+ "credential\"R\n" +
"\x19StartMFAEnrollmentRequest\x125\n" +
"\x04name\x18\x01 \x01(\tB!\xe0A\x02\xfaA\x13\n" +
"\x11bytebase.com/User\xbaH\x05r\x03\x18\x84\x02R\x04name\"\xf0\x01\n" +
@@ -1258,25 +1484,35 @@ const file_v1_user_service_proto_rawDesc = "" +
"\x0erecovery_codes\x18\x02 \x03(\tB\x04\xd0\xea0\x01R\rrecoveryCodes\x12;\n" +
"\vexpire_time\x18\x03 \x01(\v2\x1a.google.protobuf.TimestampR\n" +
"expireTime\x12C\n" +
- "\x0fpending_version\x18\x04 \x01(\v2\x1a.google.protobuf.TimestampR\x0ependingVersion\"\xc4\x01\n" +
+ "\x0fpending_version\x18\x04 \x01(\v2\x1a.google.protobuf.TimestampR\x0ependingVersion\"\x87\x02\n" +
"\x10EnableMFARequest\x125\n" +
"\x04name\x18\x01 \x01(\tB!\xe0A\x02\xfaA\x13\n" +
"\x11bytebase.com/User\xbaH\x05r\x03\x18\x84\x02R\x04name\x12)\n" +
"\botp_code\x18\x02 \x01(\tB\x0e\xe0A\x02\xbaH\x04r\x02\x18@\xd0\xea0\x01R\aotpCode\x12N\n" +
- "\x0fpending_version\x18\x03 \x01(\v2\x1a.google.protobuf.TimestampB\t\xe0A\x02\xbaH\x03\xc8\x01\x01R\x0ependingVersion\"J\n" +
+ "\x0fpending_version\x18\x03 \x01(\v2\x1a.google.protobuf.TimestampB\t\xe0A\x02\xbaH\x03\xc8\x01\x01R\x0ependingVersion\x12A\n" +
+ "\n" +
+ "credential\x18\x04 \x01(\v2\x1c.bytebase.v1.CredentialProofB\x03\xe0A\x01R\n" +
+ "credential\"\x8d\x01\n" +
"\x11DisableMFARequest\x125\n" +
"\x04name\x18\x01 \x01(\tB!\xe0A\x02\xfaA\x13\n" +
- "\x11bytebase.com/User\xbaH\x05r\x03\x18\x84\x02R\x04name\"W\n" +
+ "\x11bytebase.com/User\xbaH\x05r\x03\x18\x84\x02R\x04name\x12A\n" +
+ "\n" +
+ "credential\x18\x02 \x01(\v2\x1c.bytebase.v1.CredentialProofB\x03\xe0A\x01R\n" +
+ "credential\"W\n" +
"\x1eRegenerateRecoveryCodesRequest\x125\n" +
"\x04name\x18\x01 \x01(\tB!\xe0A\x02\xfaA\x13\n" +
"\x11bytebase.com/User\xbaH\x05r\x03\x18\x84\x02R\x04name\"\x93\x01\n" +
"\x1fRegenerateRecoveryCodesResponse\x12+\n" +
"\x0erecovery_codes\x18\x01 \x03(\tB\x04\xd0\xea0\x01R\rrecoveryCodes\x12C\n" +
- "\x0fpending_version\x18\x02 \x01(\v2\x1a.google.protobuf.TimestampR\x0ependingVersion\"\xa4\x01\n" +
+ "\x0fpending_version\x18\x02 \x01(\v2\x1a.google.protobuf.TimestampR\x0ependingVersion\"\x98\x02\n" +
"\x1bConfirmRecoveryCodesRequest\x125\n" +
"\x04name\x18\x01 \x01(\tB!\xe0A\x02\xfaA\x13\n" +
"\x11bytebase.com/User\xbaH\x05r\x03\x18\x84\x02R\x04name\x12N\n" +
- "\x0fpending_version\x18\x02 \x01(\v2\x1a.google.protobuf.TimestampB\t\xe0A\x02\xbaH\x03\xc8\x01\x01R\x0ependingVersion\"\xc4\x05\n" +
+ "\x0fpending_version\x18\x02 \x01(\v2\x1a.google.protobuf.TimestampB\t\xe0A\x02\xbaH\x03\xc8\x01\x01R\x0ependingVersion\x12G\n" +
+ "\n" +
+ "credential\x18\x03 \x01(\v2\x1c.bytebase.v1.CredentialProofB\t\xe0A\x02\xbaH\x03\xc8\x01\x01R\n" +
+ "credential\x12)\n" +
+ "\botp_code\x18\x04 \x01(\tB\x0e\xe0A\x01\xbaH\x04r\x02\x18@\xd0\xea0\x01R\aotpCode\"\xc4\x05\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\x1e\n" +
@@ -1295,7 +1531,7 @@ const file_v1_user_service_proto_rawDesc = "" +
"\x06source\x18\x03 \x01(\tR\x06source:%\xeaA\"\n" +
"\x11bytebase.com/User\x12\rusers/{email}J\x04\b\x05\x10\x06J\x04\b\a\x10\bJ\x04\b\x0f\x10\x10J\x04\b\t\x10\n" +
"J\x04\b\n" +
- "\x10\vJ\x04\b\v\x10\fR\x0ftemp_otp_secretR\x13temp_recovery_codesR\x1ctemp_otp_secret_created_time2\xe7\x10\n" +
+ "\x10\vJ\x04\b\v\x10\fR\x0ftemp_otp_secretR\x13temp_recovery_codesR\x1ctemp_otp_secret_created_time2\x84\x12\n" +
"\vUserService\x12x\n" +
"\aGetUser\x12\x1b.bytebase.v1.GetUserRequest\x1a\x11.bytebase.v1.User\"=\xdaA\x04name\x8a\xea0\fbb.users.get\x90\xea0\x01\xa0\xea0\x04\xa8\xea0\t\x82\xd3\xe4\x93\x02\x14\x12\x12/v1/{name=users/*}\x12\x8e\x01\n" +
"\rBatchGetUsers\x12!.bytebase.v1.BatchGetUsersRequest\x1a\".bytebase.v1.BatchGetUsersResponse\"6\x8a\xea0\fbb.users.get\x90\xea0\x01\xa0\xea0\x04\xa8\xea0\t\x82\xd3\xe4\x93\x02\x14\x12\x12/v1/users:batchGet\x12]\n" +
@@ -1309,7 +1545,8 @@ const file_v1_user_service_proto_rawDesc = "" +
"DeleteUser\x12\x1e.bytebase.v1.DeleteUserRequest\x1a\x16.google.protobuf.Empty\"1\xdaA\x04name\x90\xea0\x02\x98\xea0\x01\xa0\xea0\x04\xa8\xea0\t\x82\xd3\xe4\x93\x02\x14*\x12/v1/{name=users/*}\x12{\n" +
"\fUndeleteUser\x12 .bytebase.v1.UndeleteUserRequest\x1a\x11.bytebase.v1.User\"6\x90\xea0\x02\x98\xea0\x01\xa0\xea0\x04\xa8\xea0\t\x82\xd3\xe4\x93\x02 :\x01*\"\x1b/v1/{name=users/*}:undelete\x12\xa1\x01\n" +
"\vUpdateEmail\x12\x1f.bytebase.v1.UpdateEmailRequest\x1a\x11.bytebase.v1.User\"^\xdaA\n" +
- "name,email\x8a\xea0\x14bb.users.updateEmail\x90\xea0\x01\x98\xea0\x01\xa0\xea0\x03\xa8\xea0\x06\x82\xd3\xe4\x93\x02#:\x01*\"\x1e/v1/{name=users/*}:updateEmail\x12\x99\x01\n" +
+ "name,email\x8a\xea0\x14bb.users.updateEmail\x90\xea0\x01\x98\xea0\x01\xa0\xea0\x03\xa8\xea0\x06\x82\xd3\xe4\x93\x02#:\x01*\"\x1e/v1/{name=users/*}:updateEmail\x12\x9a\x01\n" +
+ "\x11RequestReauthCode\x12%.bytebase.v1.RequestReauthCodeRequest\x1a\x16.google.protobuf.Empty\"F\xdaA\x04name\x90\xea0\x02\x98\xea0\x01\xa0\xea0\x03\xa8\xea0\x02\x82\xd3\xe4\x93\x02):\x01*\"$/v1/{name=users/*}:requestReauthCode\x12\x99\x01\n" +
"\x0eChangePassword\x12\".bytebase.v1.ChangePasswordRequest\x1a\x11.bytebase.v1.User\"P\xdaA\x11name,new_password\x90\xea0\x02\x98\xea0\x01\xa0\xea0\x03\xa8\xea0\x03\x82\xd3\xe4\x93\x02&:\x01*\"!/v1/{name=users/*}:changePassword\x12\xae\x01\n" +
"\x12StartMFAEnrollment\x12&.bytebase.v1.StartMFAEnrollmentRequest\x1a'.bytebase.v1.StartMFAEnrollmentResponse\"G\xdaA\x04name\x90\xea0\x02\x98\xea0\x01\xa0\xea0\x03\xa8\xea0\x01\x82\xd3\xe4\x93\x02*:\x01*\"%/v1/{name=users/*}:startMFAEnrollment\x12\x86\x01\n" +
"\tEnableMFA\x12\x1d.bytebase.v1.EnableMFARequest\x1a\x11.bytebase.v1.User\"G\xdaA\rname,otp_code\x90\xea0\x02\x98\xea0\x01\xa0\xea0\x03\xa8\xea0\x03\x82\xd3\xe4\x93\x02!:\x01*\"\x1c/v1/{name=users/*}:enableMFA\x12\x80\x01\n" +
@@ -1331,7 +1568,7 @@ func file_v1_user_service_proto_rawDescGZIP() []byte {
return file_v1_user_service_proto_rawDescData
}
-var file_v1_user_service_proto_msgTypes = make([]protoimpl.MessageInfo, 20)
+var file_v1_user_service_proto_msgTypes = make([]protoimpl.MessageInfo, 22)
var file_v1_user_service_proto_goTypes = []any{
(*GetUserRequest)(nil), // 0: bytebase.v1.GetUserRequest
(*BatchGetUsersRequest)(nil), // 1: bytebase.v1.BatchGetUsersRequest
@@ -1343,71 +1580,79 @@ var file_v1_user_service_proto_goTypes = []any{
(*DeleteUserRequest)(nil), // 7: bytebase.v1.DeleteUserRequest
(*UndeleteUserRequest)(nil), // 8: bytebase.v1.UndeleteUserRequest
(*UpdateEmailRequest)(nil), // 9: bytebase.v1.UpdateEmailRequest
- (*ChangePasswordRequest)(nil), // 10: bytebase.v1.ChangePasswordRequest
- (*StartMFAEnrollmentRequest)(nil), // 11: bytebase.v1.StartMFAEnrollmentRequest
- (*StartMFAEnrollmentResponse)(nil), // 12: bytebase.v1.StartMFAEnrollmentResponse
- (*EnableMFARequest)(nil), // 13: bytebase.v1.EnableMFARequest
- (*DisableMFARequest)(nil), // 14: bytebase.v1.DisableMFARequest
- (*RegenerateRecoveryCodesRequest)(nil), // 15: bytebase.v1.RegenerateRecoveryCodesRequest
- (*RegenerateRecoveryCodesResponse)(nil), // 16: bytebase.v1.RegenerateRecoveryCodesResponse
- (*ConfirmRecoveryCodesRequest)(nil), // 17: bytebase.v1.ConfirmRecoveryCodesRequest
- (*User)(nil), // 18: bytebase.v1.User
- (*User_Profile)(nil), // 19: bytebase.v1.User.Profile
- (*fieldmaskpb.FieldMask)(nil), // 20: google.protobuf.FieldMask
- (*timestamppb.Timestamp)(nil), // 21: google.protobuf.Timestamp
- (State)(0), // 22: bytebase.v1.State
- (*emptypb.Empty)(nil), // 23: google.protobuf.Empty
+ (*CredentialProof)(nil), // 10: bytebase.v1.CredentialProof
+ (*RequestReauthCodeRequest)(nil), // 11: bytebase.v1.RequestReauthCodeRequest
+ (*ChangePasswordRequest)(nil), // 12: bytebase.v1.ChangePasswordRequest
+ (*StartMFAEnrollmentRequest)(nil), // 13: bytebase.v1.StartMFAEnrollmentRequest
+ (*StartMFAEnrollmentResponse)(nil), // 14: bytebase.v1.StartMFAEnrollmentResponse
+ (*EnableMFARequest)(nil), // 15: bytebase.v1.EnableMFARequest
+ (*DisableMFARequest)(nil), // 16: bytebase.v1.DisableMFARequest
+ (*RegenerateRecoveryCodesRequest)(nil), // 17: bytebase.v1.RegenerateRecoveryCodesRequest
+ (*RegenerateRecoveryCodesResponse)(nil), // 18: bytebase.v1.RegenerateRecoveryCodesResponse
+ (*ConfirmRecoveryCodesRequest)(nil), // 19: bytebase.v1.ConfirmRecoveryCodesRequest
+ (*User)(nil), // 20: bytebase.v1.User
+ (*User_Profile)(nil), // 21: bytebase.v1.User.Profile
+ (*fieldmaskpb.FieldMask)(nil), // 22: google.protobuf.FieldMask
+ (*timestamppb.Timestamp)(nil), // 23: google.protobuf.Timestamp
+ (State)(0), // 24: bytebase.v1.State
+ (*emptypb.Empty)(nil), // 25: google.protobuf.Empty
}
var file_v1_user_service_proto_depIdxs = []int32{
- 18, // 0: bytebase.v1.BatchGetUsersResponse.users:type_name -> bytebase.v1.User
- 18, // 1: bytebase.v1.ListUsersResponse.users:type_name -> bytebase.v1.User
- 18, // 2: bytebase.v1.CreateUserRequest.user:type_name -> bytebase.v1.User
- 18, // 3: bytebase.v1.UpdateUserRequest.user:type_name -> bytebase.v1.User
- 20, // 4: bytebase.v1.UpdateUserRequest.update_mask:type_name -> google.protobuf.FieldMask
- 21, // 5: bytebase.v1.StartMFAEnrollmentResponse.expire_time:type_name -> google.protobuf.Timestamp
- 21, // 6: bytebase.v1.StartMFAEnrollmentResponse.pending_version:type_name -> google.protobuf.Timestamp
- 21, // 7: bytebase.v1.EnableMFARequest.pending_version:type_name -> google.protobuf.Timestamp
- 21, // 8: bytebase.v1.RegenerateRecoveryCodesResponse.pending_version:type_name -> google.protobuf.Timestamp
- 21, // 9: bytebase.v1.ConfirmRecoveryCodesRequest.pending_version:type_name -> google.protobuf.Timestamp
- 22, // 10: bytebase.v1.User.state:type_name -> bytebase.v1.State
- 19, // 11: bytebase.v1.User.profile:type_name -> bytebase.v1.User.Profile
- 21, // 12: bytebase.v1.User.Profile.last_login_time:type_name -> google.protobuf.Timestamp
- 21, // 13: bytebase.v1.User.Profile.last_change_password_time:type_name -> google.protobuf.Timestamp
- 0, // 14: bytebase.v1.UserService.GetUser:input_type -> bytebase.v1.GetUserRequest
- 1, // 15: bytebase.v1.UserService.BatchGetUsers:input_type -> bytebase.v1.BatchGetUsersRequest
- 23, // 16: bytebase.v1.UserService.GetCurrentUser:input_type -> google.protobuf.Empty
- 3, // 17: bytebase.v1.UserService.ListUsers:input_type -> bytebase.v1.ListUsersRequest
- 5, // 18: bytebase.v1.UserService.CreateUser:input_type -> bytebase.v1.CreateUserRequest
- 6, // 19: bytebase.v1.UserService.UpdateUser:input_type -> bytebase.v1.UpdateUserRequest
- 7, // 20: bytebase.v1.UserService.DeleteUser:input_type -> bytebase.v1.DeleteUserRequest
- 8, // 21: bytebase.v1.UserService.UndeleteUser:input_type -> bytebase.v1.UndeleteUserRequest
- 9, // 22: bytebase.v1.UserService.UpdateEmail:input_type -> bytebase.v1.UpdateEmailRequest
- 10, // 23: bytebase.v1.UserService.ChangePassword:input_type -> bytebase.v1.ChangePasswordRequest
- 11, // 24: bytebase.v1.UserService.StartMFAEnrollment:input_type -> bytebase.v1.StartMFAEnrollmentRequest
- 13, // 25: bytebase.v1.UserService.EnableMFA:input_type -> bytebase.v1.EnableMFARequest
- 14, // 26: bytebase.v1.UserService.DisableMFA:input_type -> bytebase.v1.DisableMFARequest
- 15, // 27: bytebase.v1.UserService.RegenerateRecoveryCodes:input_type -> bytebase.v1.RegenerateRecoveryCodesRequest
- 17, // 28: bytebase.v1.UserService.ConfirmRecoveryCodes:input_type -> bytebase.v1.ConfirmRecoveryCodesRequest
- 18, // 29: bytebase.v1.UserService.GetUser:output_type -> bytebase.v1.User
- 2, // 30: bytebase.v1.UserService.BatchGetUsers:output_type -> bytebase.v1.BatchGetUsersResponse
- 18, // 31: bytebase.v1.UserService.GetCurrentUser:output_type -> bytebase.v1.User
- 4, // 32: bytebase.v1.UserService.ListUsers:output_type -> bytebase.v1.ListUsersResponse
- 18, // 33: bytebase.v1.UserService.CreateUser:output_type -> bytebase.v1.User
- 18, // 34: bytebase.v1.UserService.UpdateUser:output_type -> bytebase.v1.User
- 23, // 35: bytebase.v1.UserService.DeleteUser:output_type -> google.protobuf.Empty
- 18, // 36: bytebase.v1.UserService.UndeleteUser:output_type -> bytebase.v1.User
- 18, // 37: bytebase.v1.UserService.UpdateEmail:output_type -> bytebase.v1.User
- 18, // 38: bytebase.v1.UserService.ChangePassword:output_type -> bytebase.v1.User
- 12, // 39: bytebase.v1.UserService.StartMFAEnrollment:output_type -> bytebase.v1.StartMFAEnrollmentResponse
- 18, // 40: bytebase.v1.UserService.EnableMFA:output_type -> bytebase.v1.User
- 18, // 41: bytebase.v1.UserService.DisableMFA:output_type -> bytebase.v1.User
- 16, // 42: bytebase.v1.UserService.RegenerateRecoveryCodes:output_type -> bytebase.v1.RegenerateRecoveryCodesResponse
- 18, // 43: bytebase.v1.UserService.ConfirmRecoveryCodes:output_type -> bytebase.v1.User
- 29, // [29:44] is the sub-list for method output_type
- 14, // [14:29] is the sub-list for method input_type
- 14, // [14:14] is the sub-list for extension type_name
- 14, // [14:14] is the sub-list for extension extendee
- 0, // [0:14] is the sub-list for field type_name
+ 20, // 0: bytebase.v1.BatchGetUsersResponse.users:type_name -> bytebase.v1.User
+ 20, // 1: bytebase.v1.ListUsersResponse.users:type_name -> bytebase.v1.User
+ 20, // 2: bytebase.v1.CreateUserRequest.user:type_name -> bytebase.v1.User
+ 20, // 3: bytebase.v1.UpdateUserRequest.user:type_name -> bytebase.v1.User
+ 22, // 4: bytebase.v1.UpdateUserRequest.update_mask:type_name -> google.protobuf.FieldMask
+ 10, // 5: bytebase.v1.ChangePasswordRequest.credential:type_name -> bytebase.v1.CredentialProof
+ 23, // 6: bytebase.v1.StartMFAEnrollmentResponse.expire_time:type_name -> google.protobuf.Timestamp
+ 23, // 7: bytebase.v1.StartMFAEnrollmentResponse.pending_version:type_name -> google.protobuf.Timestamp
+ 23, // 8: bytebase.v1.EnableMFARequest.pending_version:type_name -> google.protobuf.Timestamp
+ 10, // 9: bytebase.v1.EnableMFARequest.credential:type_name -> bytebase.v1.CredentialProof
+ 10, // 10: bytebase.v1.DisableMFARequest.credential:type_name -> bytebase.v1.CredentialProof
+ 23, // 11: bytebase.v1.RegenerateRecoveryCodesResponse.pending_version:type_name -> google.protobuf.Timestamp
+ 23, // 12: bytebase.v1.ConfirmRecoveryCodesRequest.pending_version:type_name -> google.protobuf.Timestamp
+ 10, // 13: bytebase.v1.ConfirmRecoveryCodesRequest.credential:type_name -> bytebase.v1.CredentialProof
+ 24, // 14: bytebase.v1.User.state:type_name -> bytebase.v1.State
+ 21, // 15: bytebase.v1.User.profile:type_name -> bytebase.v1.User.Profile
+ 23, // 16: bytebase.v1.User.Profile.last_login_time:type_name -> google.protobuf.Timestamp
+ 23, // 17: bytebase.v1.User.Profile.last_change_password_time:type_name -> google.protobuf.Timestamp
+ 0, // 18: bytebase.v1.UserService.GetUser:input_type -> bytebase.v1.GetUserRequest
+ 1, // 19: bytebase.v1.UserService.BatchGetUsers:input_type -> bytebase.v1.BatchGetUsersRequest
+ 25, // 20: bytebase.v1.UserService.GetCurrentUser:input_type -> google.protobuf.Empty
+ 3, // 21: bytebase.v1.UserService.ListUsers:input_type -> bytebase.v1.ListUsersRequest
+ 5, // 22: bytebase.v1.UserService.CreateUser:input_type -> bytebase.v1.CreateUserRequest
+ 6, // 23: bytebase.v1.UserService.UpdateUser:input_type -> bytebase.v1.UpdateUserRequest
+ 7, // 24: bytebase.v1.UserService.DeleteUser:input_type -> bytebase.v1.DeleteUserRequest
+ 8, // 25: bytebase.v1.UserService.UndeleteUser:input_type -> bytebase.v1.UndeleteUserRequest
+ 9, // 26: bytebase.v1.UserService.UpdateEmail:input_type -> bytebase.v1.UpdateEmailRequest
+ 11, // 27: bytebase.v1.UserService.RequestReauthCode:input_type -> bytebase.v1.RequestReauthCodeRequest
+ 12, // 28: bytebase.v1.UserService.ChangePassword:input_type -> bytebase.v1.ChangePasswordRequest
+ 13, // 29: bytebase.v1.UserService.StartMFAEnrollment:input_type -> bytebase.v1.StartMFAEnrollmentRequest
+ 15, // 30: bytebase.v1.UserService.EnableMFA:input_type -> bytebase.v1.EnableMFARequest
+ 16, // 31: bytebase.v1.UserService.DisableMFA:input_type -> bytebase.v1.DisableMFARequest
+ 17, // 32: bytebase.v1.UserService.RegenerateRecoveryCodes:input_type -> bytebase.v1.RegenerateRecoveryCodesRequest
+ 19, // 33: bytebase.v1.UserService.ConfirmRecoveryCodes:input_type -> bytebase.v1.ConfirmRecoveryCodesRequest
+ 20, // 34: bytebase.v1.UserService.GetUser:output_type -> bytebase.v1.User
+ 2, // 35: bytebase.v1.UserService.BatchGetUsers:output_type -> bytebase.v1.BatchGetUsersResponse
+ 20, // 36: bytebase.v1.UserService.GetCurrentUser:output_type -> bytebase.v1.User
+ 4, // 37: bytebase.v1.UserService.ListUsers:output_type -> bytebase.v1.ListUsersResponse
+ 20, // 38: bytebase.v1.UserService.CreateUser:output_type -> bytebase.v1.User
+ 20, // 39: bytebase.v1.UserService.UpdateUser:output_type -> bytebase.v1.User
+ 25, // 40: bytebase.v1.UserService.DeleteUser:output_type -> google.protobuf.Empty
+ 20, // 41: bytebase.v1.UserService.UndeleteUser:output_type -> bytebase.v1.User
+ 20, // 42: bytebase.v1.UserService.UpdateEmail:output_type -> bytebase.v1.User
+ 25, // 43: bytebase.v1.UserService.RequestReauthCode:output_type -> google.protobuf.Empty
+ 20, // 44: bytebase.v1.UserService.ChangePassword:output_type -> bytebase.v1.User
+ 14, // 45: bytebase.v1.UserService.StartMFAEnrollment:output_type -> bytebase.v1.StartMFAEnrollmentResponse
+ 20, // 46: bytebase.v1.UserService.EnableMFA:output_type -> bytebase.v1.User
+ 20, // 47: bytebase.v1.UserService.DisableMFA:output_type -> bytebase.v1.User
+ 18, // 48: bytebase.v1.UserService.RegenerateRecoveryCodes:output_type -> bytebase.v1.RegenerateRecoveryCodesResponse
+ 20, // 49: bytebase.v1.UserService.ConfirmRecoveryCodes:output_type -> bytebase.v1.User
+ 34, // [34:50] is the sub-list for method output_type
+ 18, // [18:34] is the sub-list for method input_type
+ 18, // [18:18] is the sub-list for extension type_name
+ 18, // [18:18] is the sub-list for extension extendee
+ 0, // [0:18] is the sub-list for field type_name
}
func init() { file_v1_user_service_proto_init() }
@@ -1417,13 +1662,19 @@ func file_v1_user_service_proto_init() {
}
file_v1_annotation_proto_init()
file_v1_common_proto_init()
+ file_v1_user_service_proto_msgTypes[10].OneofWrappers = []any{
+ (*CredentialProof_CurrentPassword)(nil),
+ (*CredentialProof_OtpCode)(nil),
+ (*CredentialProof_RecoveryCode)(nil),
+ (*CredentialProof_EmailCode)(nil),
+ }
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_v1_user_service_proto_rawDesc), len(file_v1_user_service_proto_rawDesc)),
NumEnums: 0,
- NumMessages: 20,
+ NumMessages: 22,
NumExtensions: 0,
NumServices: 1,
},
diff --git a/backend/generated-go/v1/user_service.pb.gw.go b/backend/generated-go/v1/user_service.pb.gw.go
index 328ba73806..762d00096e 100644
--- a/backend/generated-go/v1/user_service.pb.gw.go
+++ b/backend/generated-go/v1/user_service.pb.gw.go
@@ -403,6 +403,51 @@ func local_request_UserService_UpdateEmail_0(ctx context.Context, marshaler runt
return msg, metadata, err
}
+func request_UserService_RequestReauthCode_0(ctx context.Context, marshaler runtime.Marshaler, client UserServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
+ var (
+ protoReq RequestReauthCodeRequest
+ metadata runtime.ServerMetadata
+ err error
+ )
+ if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) {
+ return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
+ }
+ val, ok := pathParams["name"]
+ if !ok {
+ return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "name")
+ }
+ protoReq.Name, err = runtime.String(val)
+ if err != nil {
+ return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "name", err)
+ }
+ if req.Body != nil {
+ _, _ = io.Copy(io.Discard, req.Body)
+ }
+ msg, err := client.RequestReauthCode(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
+ return msg, metadata, err
+}
+
+func local_request_UserService_RequestReauthCode_0(ctx context.Context, marshaler runtime.Marshaler, server UserServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
+ var (
+ protoReq RequestReauthCodeRequest
+ metadata runtime.ServerMetadata
+ err error
+ )
+ if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) {
+ return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
+ }
+ val, ok := pathParams["name"]
+ if !ok {
+ return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "name")
+ }
+ protoReq.Name, err = runtime.String(val)
+ if err != nil {
+ return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "name", err)
+ }
+ msg, err := server.RequestReauthCode(ctx, &protoReq)
+ return msg, metadata, err
+}
+
func request_UserService_ChangePassword_0(ctx context.Context, marshaler runtime.Marshaler, client UserServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var (
protoReq ChangePasswordRequest
@@ -859,6 +904,26 @@ func RegisterUserServiceHandlerServer(ctx context.Context, mux *runtime.ServeMux
}
forward_UserService_UpdateEmail_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
+ mux.Handle(http.MethodPost, pattern_UserService_RequestReauthCode_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
+ ctx, cancel := context.WithCancel(req.Context())
+ defer cancel()
+ var stream runtime.ServerTransportStream
+ ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)
+ inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
+ annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/bytebase.v1.UserService/RequestReauthCode", runtime.WithHTTPPathPattern("/v1/{name=users/*}:requestReauthCode"))
+ if err != nil {
+ runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
+ return
+ }
+ resp, md, err := local_request_UserService_RequestReauthCode_0(annotatedContext, inboundMarshaler, server, req, pathParams)
+ md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())
+ annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)
+ if err != nil {
+ runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)
+ return
+ }
+ forward_UserService_RequestReauthCode_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
+ })
mux.Handle(http.MethodPost, pattern_UserService_ChangePassword_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
@@ -1172,6 +1237,23 @@ func RegisterUserServiceHandlerClient(ctx context.Context, mux *runtime.ServeMux
}
forward_UserService_UpdateEmail_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
+ mux.Handle(http.MethodPost, pattern_UserService_RequestReauthCode_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
+ ctx, cancel := context.WithCancel(req.Context())
+ defer cancel()
+ inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
+ annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/bytebase.v1.UserService/RequestReauthCode", runtime.WithHTTPPathPattern("/v1/{name=users/*}:requestReauthCode"))
+ if err != nil {
+ runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
+ return
+ }
+ resp, md, err := request_UserService_RequestReauthCode_0(annotatedContext, inboundMarshaler, client, req, pathParams)
+ annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)
+ if err != nil {
+ runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)
+ return
+ }
+ forward_UserService_RequestReauthCode_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
+ })
mux.Handle(http.MethodPost, pattern_UserService_ChangePassword_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
@@ -1287,6 +1369,7 @@ var (
pattern_UserService_DeleteUser_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 2, 5, 2}, []string{"v1", "users", "name"}, ""))
pattern_UserService_UndeleteUser_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 2, 5, 2}, []string{"v1", "users", "name"}, "undelete"))
pattern_UserService_UpdateEmail_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 2, 5, 2}, []string{"v1", "users", "name"}, "updateEmail"))
+ pattern_UserService_RequestReauthCode_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 2, 5, 2}, []string{"v1", "users", "name"}, "requestReauthCode"))
pattern_UserService_ChangePassword_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 2, 5, 2}, []string{"v1", "users", "name"}, "changePassword"))
pattern_UserService_StartMFAEnrollment_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 2, 5, 2}, []string{"v1", "users", "name"}, "startMFAEnrollment"))
pattern_UserService_EnableMFA_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 2, 5, 2}, []string{"v1", "users", "name"}, "enableMFA"))
@@ -1305,6 +1388,7 @@ var (
forward_UserService_DeleteUser_0 = runtime.ForwardResponseMessage
forward_UserService_UndeleteUser_0 = runtime.ForwardResponseMessage
forward_UserService_UpdateEmail_0 = runtime.ForwardResponseMessage
+ forward_UserService_RequestReauthCode_0 = runtime.ForwardResponseMessage
forward_UserService_ChangePassword_0 = runtime.ForwardResponseMessage
forward_UserService_StartMFAEnrollment_0 = runtime.ForwardResponseMessage
forward_UserService_EnableMFA_0 = runtime.ForwardResponseMessage
diff --git a/backend/generated-go/v1/user_service_equal.pb.go b/backend/generated-go/v1/user_service_equal.pb.go
index 1efbce081c..4b0b95689e 100644
--- a/backend/generated-go/v1/user_service_equal.pb.go
+++ b/backend/generated-go/v1/user_service_equal.pb.go
@@ -178,6 +178,41 @@ func (x *UpdateEmailRequest) Equal(y *UpdateEmailRequest) bool {
return true
}
+func (x *CredentialProof) Equal(y *CredentialProof) bool {
+ if x == y {
+ return true
+ }
+ if x == nil || y == nil {
+ return x == nil && y == nil
+ }
+ if x.GetCurrentPassword() != y.GetCurrentPassword() {
+ return false
+ }
+ if x.GetOtpCode() != y.GetOtpCode() {
+ return false
+ }
+ if x.GetRecoveryCode() != y.GetRecoveryCode() {
+ return false
+ }
+ if x.GetEmailCode() != y.GetEmailCode() {
+ return false
+ }
+ return true
+}
+
+func (x *RequestReauthCodeRequest) Equal(y *RequestReauthCodeRequest) bool {
+ if x == y {
+ return true
+ }
+ if x == nil || y == nil {
+ return x == nil && y == nil
+ }
+ if x.Name != y.Name {
+ return false
+ }
+ return true
+}
+
func (x *ChangePasswordRequest) Equal(y *ChangePasswordRequest) bool {
if x == y {
return true
@@ -191,6 +226,9 @@ func (x *ChangePasswordRequest) Equal(y *ChangePasswordRequest) bool {
if x.NewPassword != y.NewPassword {
return false
}
+ if !x.Credential.Equal(y.Credential) {
+ return false
+ }
return true
}
@@ -250,6 +288,9 @@ func (x *EnableMFARequest) Equal(y *EnableMFARequest) bool {
if p, q := x.PendingVersion, y.PendingVersion; (p == nil && q != nil) || (p != nil && (q == nil || p.Seconds != q.Seconds || p.Nanos != q.Nanos)) {
return false
}
+ if !x.Credential.Equal(y.Credential) {
+ return false
+ }
return true
}
@@ -263,6 +304,9 @@ func (x *DisableMFARequest) Equal(y *DisableMFARequest) bool {
if x.Name != y.Name {
return false
}
+ if !x.Credential.Equal(y.Credential) {
+ return false
+ }
return true
}
@@ -313,6 +357,12 @@ func (x *ConfirmRecoveryCodesRequest) Equal(y *ConfirmRecoveryCodesRequest) bool
if p, q := x.PendingVersion, y.PendingVersion; (p == nil && q != nil) || (p != nil && (q == nil || p.Seconds != q.Seconds || p.Nanos != q.Nanos)) {
return false
}
+ if !x.Credential.Equal(y.Credential) {
+ return false
+ }
+ if x.OtpCode != y.OtpCode {
+ return false
+ }
return true
}
diff --git a/backend/generated-go/v1/user_service_grpc.pb.go b/backend/generated-go/v1/user_service_grpc.pb.go
index a019ab5995..e9c66e7063 100644
--- a/backend/generated-go/v1/user_service_grpc.pb.go
+++ b/backend/generated-go/v1/user_service_grpc.pb.go
@@ -29,6 +29,7 @@ const (
UserService_DeleteUser_FullMethodName = "/bytebase.v1.UserService/DeleteUser"
UserService_UndeleteUser_FullMethodName = "/bytebase.v1.UserService/UndeleteUser"
UserService_UpdateEmail_FullMethodName = "/bytebase.v1.UserService/UpdateEmail"
+ UserService_RequestReauthCode_FullMethodName = "/bytebase.v1.UserService/RequestReauthCode"
UserService_ChangePassword_FullMethodName = "/bytebase.v1.UserService/ChangePassword"
UserService_StartMFAEnrollment_FullMethodName = "/bytebase.v1.UserService/StartMFAEnrollment"
UserService_EnableMFA_FullMethodName = "/bytebase.v1.UserService/EnableMFA"
@@ -75,6 +76,12 @@ type UserServiceClient interface {
// Updates a user's email address.
// Permissions required: bb.users.updateEmail
UpdateEmail(ctx context.Context, in *UpdateEmailRequest, opts ...grpc.CallOption) (*User, error)
+ // Sends a one-time code to the caller's own email, usable as
+ // CredentialProof.email_code. Bytebase Cloud only, and only while the
+ // account has no live MFA factor. Not AuthService.SendEmailLoginCode: that
+ // one starts a session, this one proves an existing one.
+ // Permissions required: None beyond being signed in as `name`.
+ RequestReauthCode(ctx context.Context, in *RequestReauthCodeRequest, opts ...grpc.CallOption) (*emptypb.Empty, error)
// Changes the caller's own password. An administrator resetting someone
// else's password uses UpdateUser with the `password` mask instead — that
// is a different operation with a different audit story, even though both
@@ -211,6 +218,16 @@ func (c *userServiceClient) UpdateEmail(ctx context.Context, in *UpdateEmailRequ
return out, nil
}
+func (c *userServiceClient) RequestReauthCode(ctx context.Context, in *RequestReauthCodeRequest, opts ...grpc.CallOption) (*emptypb.Empty, error) {
+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
+ out := new(emptypb.Empty)
+ err := c.cc.Invoke(ctx, UserService_RequestReauthCode_FullMethodName, in, out, cOpts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
func (c *userServiceClient) ChangePassword(ctx context.Context, in *ChangePasswordRequest, opts ...grpc.CallOption) (*User, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(User)
@@ -309,6 +326,12 @@ type UserServiceServer interface {
// Updates a user's email address.
// Permissions required: bb.users.updateEmail
UpdateEmail(context.Context, *UpdateEmailRequest) (*User, error)
+ // Sends a one-time code to the caller's own email, usable as
+ // CredentialProof.email_code. Bytebase Cloud only, and only while the
+ // account has no live MFA factor. Not AuthService.SendEmailLoginCode: that
+ // one starts a session, this one proves an existing one.
+ // Permissions required: None beyond being signed in as `name`.
+ RequestReauthCode(context.Context, *RequestReauthCodeRequest) (*emptypb.Empty, error)
// Changes the caller's own password. An administrator resetting someone
// else's password uses UpdateUser with the `password` mask instead — that
// is a different operation with a different audit story, even though both
@@ -382,6 +405,9 @@ func (UnimplementedUserServiceServer) UndeleteUser(context.Context, *UndeleteUse
func (UnimplementedUserServiceServer) UpdateEmail(context.Context, *UpdateEmailRequest) (*User, error) {
return nil, status.Error(codes.Unimplemented, "method UpdateEmail not implemented")
}
+func (UnimplementedUserServiceServer) RequestReauthCode(context.Context, *RequestReauthCodeRequest) (*emptypb.Empty, error) {
+ return nil, status.Error(codes.Unimplemented, "method RequestReauthCode not implemented")
+}
func (UnimplementedUserServiceServer) ChangePassword(context.Context, *ChangePasswordRequest) (*User, error) {
return nil, status.Error(codes.Unimplemented, "method ChangePassword not implemented")
}
@@ -583,6 +609,24 @@ func _UserService_UpdateEmail_Handler(srv interface{}, ctx context.Context, dec
return interceptor(ctx, in, info, handler)
}
+func _UserService_RequestReauthCode_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(RequestReauthCodeRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(UserServiceServer).RequestReauthCode(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: UserService_RequestReauthCode_FullMethodName,
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(UserServiceServer).RequestReauthCode(ctx, req.(*RequestReauthCodeRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
func _UserService_ChangePassword_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(ChangePasswordRequest)
if err := dec(in); err != nil {
@@ -734,6 +778,10 @@ var UserService_ServiceDesc = grpc.ServiceDesc{
MethodName: "UpdateEmail",
Handler: _UserService_UpdateEmail_Handler,
},
+ {
+ MethodName: "RequestReauthCode",
+ Handler: _UserService_RequestReauthCode_Handler,
+ },
{
MethodName: "ChangePassword",
Handler: _UserService_ChangePassword_Handler,
diff --git a/backend/generated-go/v1/v1connect/auth_service.connect.go b/backend/generated-go/v1/v1connect/auth_service.connect.go
index 3d6a97b617..0d78c2eafc 100644
--- a/backend/generated-go/v1/v1connect/auth_service.connect.go
+++ b/backend/generated-go/v1/v1connect/auth_service.connect.go
@@ -90,6 +90,8 @@ type AuthServiceClient interface {
SwitchWorkspace(context.Context, *connect.Request[v1.SwitchWorkspaceRequest]) (*connect.Response[v1.LoginResponse], error)
// Requests a password reset email for the given email address.
// Always returns success to avoid leaking whether the email exists.
+ // Requires the workspace's SMTP mail delivery setting; without it the
+ // recovery route is an admin password reset.
// Permissions required: None
RequestPasswordReset(context.Context, *connect.Request[v1.RequestPasswordResetRequest]) (*connect.Response[emptypb.Empty], error)
// Resets the user's password using a password reset token from email.
@@ -97,6 +99,8 @@ type AuthServiceClient interface {
ResetPassword(context.Context, *connect.Request[v1.ResetPasswordRequest]) (*connect.Response[emptypb.Empty], error)
// Sends a 6-digit verification code to the email for login/signup.
// Always returns success (no email enumeration). Enforces 60-sec resend cooldown.
+ // The signed-in counterpart is UserService.RequestReauthCode; LOGIN and
+ // REAUTH codes are not interchangeable.
// Permissions required: None
SendEmailLoginCode(context.Context, *connect.Request[v1.SendEmailLoginCodeRequest]) (*connect.Response[emptypb.Empty], error)
}
@@ -267,6 +271,8 @@ type AuthServiceHandler interface {
SwitchWorkspace(context.Context, *connect.Request[v1.SwitchWorkspaceRequest]) (*connect.Response[v1.LoginResponse], error)
// Requests a password reset email for the given email address.
// Always returns success to avoid leaking whether the email exists.
+ // Requires the workspace's SMTP mail delivery setting; without it the
+ // recovery route is an admin password reset.
// Permissions required: None
RequestPasswordReset(context.Context, *connect.Request[v1.RequestPasswordResetRequest]) (*connect.Response[emptypb.Empty], error)
// Resets the user's password using a password reset token from email.
@@ -274,6 +280,8 @@ type AuthServiceHandler interface {
ResetPassword(context.Context, *connect.Request[v1.ResetPasswordRequest]) (*connect.Response[emptypb.Empty], error)
// Sends a 6-digit verification code to the email for login/signup.
// Always returns success (no email enumeration). Enforces 60-sec resend cooldown.
+ // The signed-in counterpart is UserService.RequestReauthCode; LOGIN and
+ // REAUTH codes are not interchangeable.
// Permissions required: None
SendEmailLoginCode(context.Context, *connect.Request[v1.SendEmailLoginCodeRequest]) (*connect.Response[emptypb.Empty], error)
}
diff --git a/backend/generated-go/v1/v1connect/user_service.connect.go b/backend/generated-go/v1/v1connect/user_service.connect.go
index c99995a44f..220369646d 100644
--- a/backend/generated-go/v1/v1connect/user_service.connect.go
+++ b/backend/generated-go/v1/v1connect/user_service.connect.go
@@ -55,6 +55,9 @@ const (
UserServiceUndeleteUserProcedure = "/bytebase.v1.UserService/UndeleteUser"
// UserServiceUpdateEmailProcedure is the fully-qualified name of the UserService's UpdateEmail RPC.
UserServiceUpdateEmailProcedure = "/bytebase.v1.UserService/UpdateEmail"
+ // UserServiceRequestReauthCodeProcedure is the fully-qualified name of the UserService's
+ // RequestReauthCode RPC.
+ UserServiceRequestReauthCodeProcedure = "/bytebase.v1.UserService/RequestReauthCode"
// UserServiceChangePasswordProcedure is the fully-qualified name of the UserService's
// ChangePassword RPC.
UserServiceChangePasswordProcedure = "/bytebase.v1.UserService/ChangePassword"
@@ -107,6 +110,12 @@ type UserServiceClient interface {
// Updates a user's email address.
// Permissions required: bb.users.updateEmail
UpdateEmail(context.Context, *connect.Request[v1.UpdateEmailRequest]) (*connect.Response[v1.User], error)
+ // Sends a one-time code to the caller's own email, usable as
+ // CredentialProof.email_code. Bytebase Cloud only, and only while the
+ // account has no live MFA factor. Not AuthService.SendEmailLoginCode: that
+ // one starts a session, this one proves an existing one.
+ // Permissions required: None beyond being signed in as `name`.
+ RequestReauthCode(context.Context, *connect.Request[v1.RequestReauthCodeRequest]) (*connect.Response[emptypb.Empty], error)
// Changes the caller's own password. An administrator resetting someone
// else's password uses UpdateUser with the `password` mask instead — that
// is a different operation with a different audit story, even though both
@@ -210,6 +219,12 @@ func NewUserServiceClient(httpClient connect.HTTPClient, baseURL string, opts ..
connect.WithSchema(userServiceMethods.ByName("UpdateEmail")),
connect.WithClientOptions(opts...),
),
+ requestReauthCode: connect.NewClient[v1.RequestReauthCodeRequest, emptypb.Empty](
+ httpClient,
+ baseURL+UserServiceRequestReauthCodeProcedure,
+ connect.WithSchema(userServiceMethods.ByName("RequestReauthCode")),
+ connect.WithClientOptions(opts...),
+ ),
changePassword: connect.NewClient[v1.ChangePasswordRequest, v1.User](
httpClient,
baseURL+UserServiceChangePasswordProcedure,
@@ -260,6 +275,7 @@ type userServiceClient struct {
deleteUser *connect.Client[v1.DeleteUserRequest, emptypb.Empty]
undeleteUser *connect.Client[v1.UndeleteUserRequest, v1.User]
updateEmail *connect.Client[v1.UpdateEmailRequest, v1.User]
+ requestReauthCode *connect.Client[v1.RequestReauthCodeRequest, emptypb.Empty]
changePassword *connect.Client[v1.ChangePasswordRequest, v1.User]
startMFAEnrollment *connect.Client[v1.StartMFAEnrollmentRequest, v1.StartMFAEnrollmentResponse]
enableMFA *connect.Client[v1.EnableMFARequest, v1.User]
@@ -313,6 +329,11 @@ func (c *userServiceClient) UpdateEmail(ctx context.Context, req *connect.Reques
return c.updateEmail.CallUnary(ctx, req)
}
+// RequestReauthCode calls bytebase.v1.UserService.RequestReauthCode.
+func (c *userServiceClient) RequestReauthCode(ctx context.Context, req *connect.Request[v1.RequestReauthCodeRequest]) (*connect.Response[emptypb.Empty], error) {
+ return c.requestReauthCode.CallUnary(ctx, req)
+}
+
// ChangePassword calls bytebase.v1.UserService.ChangePassword.
func (c *userServiceClient) ChangePassword(ctx context.Context, req *connect.Request[v1.ChangePasswordRequest]) (*connect.Response[v1.User], error) {
return c.changePassword.CallUnary(ctx, req)
@@ -377,6 +398,12 @@ type UserServiceHandler interface {
// Updates a user's email address.
// Permissions required: bb.users.updateEmail
UpdateEmail(context.Context, *connect.Request[v1.UpdateEmailRequest]) (*connect.Response[v1.User], error)
+ // Sends a one-time code to the caller's own email, usable as
+ // CredentialProof.email_code. Bytebase Cloud only, and only while the
+ // account has no live MFA factor. Not AuthService.SendEmailLoginCode: that
+ // one starts a session, this one proves an existing one.
+ // Permissions required: None beyond being signed in as `name`.
+ RequestReauthCode(context.Context, *connect.Request[v1.RequestReauthCodeRequest]) (*connect.Response[emptypb.Empty], error)
// Changes the caller's own password. An administrator resetting someone
// else's password uses UpdateUser with the `password` mask instead — that
// is a different operation with a different audit story, even though both
@@ -476,6 +503,12 @@ func NewUserServiceHandler(svc UserServiceHandler, opts ...connect.HandlerOption
connect.WithSchema(userServiceMethods.ByName("UpdateEmail")),
connect.WithHandlerOptions(opts...),
)
+ userServiceRequestReauthCodeHandler := connect.NewUnaryHandler(
+ UserServiceRequestReauthCodeProcedure,
+ svc.RequestReauthCode,
+ connect.WithSchema(userServiceMethods.ByName("RequestReauthCode")),
+ connect.WithHandlerOptions(opts...),
+ )
userServiceChangePasswordHandler := connect.NewUnaryHandler(
UserServiceChangePasswordProcedure,
svc.ChangePassword,
@@ -532,6 +565,8 @@ func NewUserServiceHandler(svc UserServiceHandler, opts ...connect.HandlerOption
userServiceUndeleteUserHandler.ServeHTTP(w, r)
case UserServiceUpdateEmailProcedure:
userServiceUpdateEmailHandler.ServeHTTP(w, r)
+ case UserServiceRequestReauthCodeProcedure:
+ userServiceRequestReauthCodeHandler.ServeHTTP(w, r)
case UserServiceChangePasswordProcedure:
userServiceChangePasswordHandler.ServeHTTP(w, r)
case UserServiceStartMFAEnrollmentProcedure:
@@ -589,6 +624,10 @@ func (UnimplementedUserServiceHandler) UpdateEmail(context.Context, *connect.Req
return nil, connect.NewError(connect.CodeUnimplemented, errors.New("bytebase.v1.UserService.UpdateEmail is not implemented"))
}
+func (UnimplementedUserServiceHandler) RequestReauthCode(context.Context, *connect.Request[v1.RequestReauthCodeRequest]) (*connect.Response[emptypb.Empty], error) {
+ return nil, connect.NewError(connect.CodeUnimplemented, errors.New("bytebase.v1.UserService.RequestReauthCode is not implemented"))
+}
+
func (UnimplementedUserServiceHandler) ChangePassword(context.Context, *connect.Request[v1.ChangePasswordRequest]) (*connect.Response[v1.User], error) {
return nil, connect.NewError(connect.CodeUnimplemented, errors.New("bytebase.v1.UserService.ChangePassword is not implemented"))
}
diff --git a/backend/server/grpc_routes.go b/backend/server/grpc_routes.go
index c9e594e7b0..b452b41915 100644
--- a/backend/server/grpc_routes.go
+++ b/backend/server/grpc_routes.go
@@ -118,7 +118,7 @@ func configureGrpcRouters(
sheetService := apiv1.NewSheetService(stores)
sqlService := apiv1.NewSQLService(stores, schemaSyncer, dbFactory, licenseService, iamManager, queryHistoryService)
subscriptionService := apiv1.NewSubscriptionService(profile, stores, licenseService)
- userService := apiv1.NewUserService(stores, licenseService, profile, iamManager)
+ userService := apiv1.NewUserService(stores, secret, licenseService, profile, iamManager)
serviceAccountService := apiv1.NewServiceAccountService(stores, profile, iamManager)
workloadIdentityService := apiv1.NewWorkloadIdentityService(stores, profile, iamManager)
savedQueryService := apiv1.NewSavedQueryService(stores, iamManager)
diff --git a/backend/server/validate_interceptor_test.go b/backend/server/validate_interceptor_test.go
index ee5abc746d..dd51744599 100644
--- a/backend/server/validate_interceptor_test.go
+++ b/backend/server/validate_interceptor_test.go
@@ -92,6 +92,23 @@ func TestAuthRequestFieldsAreSizeBounded(t *testing.T) {
{"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)}},
+ // The credential-change methods turn name into a T9 lockout identity,
+ // so the interceptor must refuse an oversized one before any handler
+ // claims a slot. 260 = "users/" + a 254-char email.
+ {"reauth code name over 260", &v1pb.RequestReauthCodeRequest{Name: long(261)}},
+ {"change password name over 260", &v1pb.ChangePasswordRequest{Name: long(261)}},
+ {"start mfa enrollment name over 260", &v1pb.StartMFAEnrollmentRequest{Name: long(261)}},
+ {"enable mfa name over 260", &v1pb.EnableMFARequest{Name: long(261)}},
+ {"disable mfa name over 260", &v1pb.DisableMFARequest{Name: long(261)}},
+ {"regenerate recovery codes name over 260", &v1pb.RegenerateRecoveryCodesRequest{Name: long(261)}},
+ {"confirm recovery codes name over 260", &v1pb.ConfirmRecoveryCodesRequest{Name: long(261)}},
+ {"change password new_password over bcrypt's 72 bytes", &v1pb.ChangePasswordRequest{NewPassword: long(73)}},
+ {"proof current_password over bcrypt's 72 bytes", &v1pb.CredentialProof{Proof: &v1pb.CredentialProof_CurrentPassword{CurrentPassword: long(73)}}},
+ {"proof otp code over 64", &v1pb.CredentialProof{Proof: &v1pb.CredentialProof_OtpCode{OtpCode: long(65)}}},
+ {"proof recovery code over 64", &v1pb.CredentialProof{Proof: &v1pb.CredentialProof_RecoveryCode{RecoveryCode: long(65)}}},
+ {"proof email code over 64", &v1pb.CredentialProof{Proof: &v1pb.CredentialProof_EmailCode{EmailCode: long(65)}}},
+ {"enable mfa otp code over 64", &v1pb.EnableMFARequest{OtpCode: long(65)}},
+ {"confirm recovery codes otp code over 64", &v1pb.ConfirmRecoveryCodesRequest{OtpCode: long(65)}},
} {
if err := v.Validate(tc.msg); err == nil {
t.Errorf("expected size violation for %s, got nil", tc.name)
@@ -107,4 +124,26 @@ func TestAuthRequestFieldsAreSizeBounded(t *testing.T) {
}
}
+// TestCredentialProofIsRequired pins the proof-carrying requests that must
+// never reach a handler without a CredentialProof. The handler dereferences
+// the proof to pick a verification path, so a missing one has to be an
+// interceptor-level invalid_argument rather than a nil dereference deeper in
+// (docs/design/reauthenticate-credential-changes.md).
+func TestCredentialProofIsRequired(t *testing.T) {
+ v, err := protovalidate.New()
+ if err != nil {
+ t.Fatalf("protovalidate.New: %v", err)
+ }
+ if err := v.Validate(&v1pb.ChangePasswordRequest{Name: "users/[email protected]", NewPassword: "new-password"}); err == nil {
+ t.Error("expected a required violation for ChangePasswordRequest without a credential, got nil")
+ }
+ if err := v.Validate(&v1pb.ChangePasswordRequest{
+ Name: "users/[email protected]",
+ NewPassword: "new-password",
+ Credential: &v1pb.CredentialProof{Proof: &v1pb.CredentialProof_CurrentPassword{CurrentPassword: "old-password"}},
+ }); err != nil {
+ t.Errorf("a ChangePasswordRequest carrying a credential 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 c1488b3a2f..20e66460db 100644
--- a/backend/store/email_verification_code.go
+++ b/backend/store/email_verification_code.go
@@ -86,6 +86,38 @@ func (s *Store) GetEmailVerificationCode(ctx context.Context, email string, purp
return msg, nil
}
+// ConsumeEmailVerificationCode deletes the account's unexpired code for a
+// purpose, but only if it is the one whose hash was submitted, and reports
+// whether this call is the one that claimed it. Every condition rides on the
+// DELETE rather than on a preceding read: two requests submitting the same
+// valid code race here and exactly one observes consumed=true, so a code that
+// authorizes a credential change really is spendable once.
+//
+// RETURNING (not RowsAffected) for the same reason ConsumeOAuth2RefreshToken
+// gives. A false return means the code was wrong, already spent, or expired —
+// callers must not distinguish those to the caller.
+func (s *Store) ConsumeEmailVerificationCode(ctx context.Context, email string, purpose storepb.EmailVerificationCodePurpose, codeHash string) (bool, error) {
+ q := qb.Q().Space(`
+ DELETE FROM email_verification_code
+ WHERE email = ? AND purpose = ? AND code_hash = ? AND expires_at > NOW()
+ RETURNING email
+ `, email, purpose.String(), codeHash)
+
+ query, args, err := q.ToSQL()
+ if err != nil {
+ return false, err
+ }
+
+ var consumedEmail string
+ if err := s.GetDB().QueryRowContext(ctx, query, args...).Scan(&consumedEmail); err != nil { // NOSONAR: query is parameterized via qb.Query
+ if errors.Is(err, sql.ErrNoRows) {
+ return false, nil
+ }
+ return false, errors.Wrap(err, "failed to consume email verification code")
+ }
+ return true, 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/mfa_pending_version_test.go b/backend/store/mfa_pending_version_test.go
index 474abfe471..a4bca4a76c 100644
--- a/backend/store/mfa_pending_version_test.go
+++ b/backend/store/mfa_pending_version_test.go
@@ -1,127 +1,61 @@
package store_test
import (
- "context"
- "fmt"
"testing"
"time"
"github.com/stretchr/testify/require"
- "google.golang.org/protobuf/types/known/timestamppb"
- "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"
)
-func newMFAPendingTestStore(t *testing.T) *store.Store {
- t.Helper()
- 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()) })
- return s
-}
-
-// TestUpdateUserMFAConfigIfPending pins the compare-and-swap the confirming
-// methods promote through. The version has to be part of the write: a caller
-// that checked a user it read moments ago would otherwise still commit, and
-// the two states worth protecting are a newer enrollment from another tab and
-// an administrator's disable — reviving a factor that was just cleared.
-func TestUpdateUserMFAConfigIfPending(t *testing.T) {
- ctx := context.Background()
- s := newMFAPendingTestStore(t)
+// TestPendingMFAVersionSurvivesNanosecondClocks pins the precision contract
+// between the pending version and the predicate that matches it.
+//
+// UpdateUserMFAConfigIfPending compares the stored value as a timestamptz, and
+// that type holds microseconds. The cast rounds a nanosecond tail while the
+// bound parameter does not, so an instant whose sub-microsecond remainder
+// rounds up used to match nothing and the confirmation reported that its own
+// enrollment had been superseded.
+//
+// It never reproduced on macOS, whose clock is microsecond-granular: every
+// value it produces is already exact. On Linux, which is nanosecond-granular,
+// it struck roughly half of all enrollments — so the instants here are chosen
+// rather than sampled from time.Now().
+func TestPendingMFAVersionSurvivesNanosecondClocks(t *testing.T) {
+ ctx, _, s := newSettingAtomicFixture(t)
+ a := require.New(t)
user, err := s.CreateUser(ctx, &store.UserMessage{
- Email: "[email protected]",
- Name: "Pending",
- PasswordHash: "unused",
+ Email: "[email protected]",
+ Name: "enroller",
+ Type: storepb.PrincipalType_END_USER,
})
- require.NoError(t, err)
-
- version := timestamppb.New(time.Now().UTC().Truncate(time.Microsecond))
- _, err = s.UpdateUser(ctx, user, &store.UpdateUserMessage{
- MFAConfig: &storepb.MFAConfig{
- TempOtpSecret: "pending-secret",
- TempRecoveryCodes: []string{"code-a"},
- TempOtpSecretCreatedTime: version,
- },
- })
- require.NoError(t, err)
-
- promoted := &storepb.MFAConfig{OtpSecret: "pending-secret", RecoveryCodes: []string{"code-a"}}
-
- stale := version.AsTime().Add(-time.Second)
- refused, err := s.UpdateUserMFAConfigIfPending(ctx, user.ID, stale, promoted)
- require.NoError(t, err)
- require.Nil(t, refused, "a version that is not the pending one must not commit")
- unchanged, err := s.GetUserByEmail(ctx, user.Email)
- require.NoError(t, err)
- require.Empty(t, unchanged.MFAConfig.GetOtpSecret(), "the refused write must leave the account alone")
-
- updated, err := s.UpdateUserMFAConfigIfPending(ctx, user.ID, version.AsTime(), promoted)
- require.NoError(t, err)
- require.NotNil(t, updated)
- require.Equal(t, "pending-secret", updated.MFAConfig.GetOtpSecret())
-
- // Promotion clears the pending slot, so replaying the same confirmation —
- // a double-submit, or a tab that never learned it already went through —
- // finds nothing to promote rather than rewriting the factor.
- replayed, err := s.UpdateUserMFAConfigIfPending(ctx, user.ID, version.AsTime(), promoted)
- require.NoError(t, err)
- require.Nil(t, replayed, "a consumed pending version must not promote twice")
-}
-
-// TestSetPendingMFAStateLeavesTheLiveFactor pins that minting pending state
-// never writes the live factor. The mint reads the account, generates secrets,
-// then writes — and an administrator disabling MFA in that window used to be
-// undone by the write, silently re-enabling the factor they had cleared for a
-// locked-out user.
-func TestSetPendingMFAStateLeavesTheLiveFactor(t *testing.T) {
- ctx := context.Background()
- s := newMFAPendingTestStore(t)
-
- user, err := s.CreateUser(ctx, &store.UserMessage{
- Email: "[email protected]",
- Name: "Mint",
- PasswordHash: "unused",
- })
- require.NoError(t, err)
- live, err := s.UpdateUser(ctx, user, &store.UpdateUserMessage{
- MFAConfig: &storepb.MFAConfig{
- OtpSecret: "live-secret",
- RecoveryCodes: []string{"live-a", "live-b"},
- },
- })
- require.NoError(t, err)
-
- // What a mint holds: the account as it was before the concurrent change.
- stale := live
-
- _, err = s.UpdateUser(ctx, stale, &store.UpdateUserMessage{MFAConfig: &storepb.MFAConfig{}})
- require.NoError(t, err)
-
- // The mint lands afterwards, still holding the stale read.
- require.NoError(t, s.SetPendingMFAState(ctx, stale.ID, "pending-secret", []string{"code-a"}, time.Now()))
-
- after, err := s.GetUserByEmail(ctx, user.Email)
- require.NoError(t, err)
- require.Empty(t, after.MFAConfig.GetOtpSecret(), "a mint must not bring back a disabled factor")
- require.Empty(t, after.MFAConfig.GetRecoveryCodes(), "nor the codes that went with it")
- require.Equal(t, "pending-secret", after.MFAConfig.GetTempOtpSecret())
- require.Equal(t, []string{"code-a"}, after.MFAConfig.GetTempRecoveryCodes())
- require.NotNil(t, after.MFAConfig.GetTempOtpSecretCreatedTime(), "the version must round-trip through protojson")
+ a.NoError(err)
+
+ base := time.Date(2026, 8, 27, 5, 10, 43, 0, time.UTC)
+ for _, nanos := range []int{0, 1, 499, 500, 501, 999, 123456000, 123456789, 999999999} {
+ // Handed in with the nanosecond tail a Linux clock produces, not
+ // pre-rounded: the store owns this contract, so it has to hold for a
+ // caller that passes time.Now() straight through.
+ raw := base.Add(time.Duration(nanos))
+ a.NoError(s.SetPendingMFAState(ctx, user.ID, "PENDINGSECRET", []string{"code-1", "code-2"}, raw))
+
+ promoted, err := s.UpdateUserMFAConfigIfPending(ctx, user.ID, raw, &storepb.MFAConfig{
+ OtpSecret: "PENDINGSECRET",
+ RecoveryCodes: []string{"code-1", "code-2"},
+ })
+ a.NoError(err)
+ a.NotNil(promoted, "a confirmation carrying the version it was minted with must promote, nanos=%d", nanos)
+ a.Equal("PENDINGSECRET", promoted.MFAConfig.GetOtpSecret(), "nanos=%d", nanos)
+
+ // The row reports the instant it can actually hold, so a handler that
+ // mints the same way compares equal to it.
+ a.NoError(s.SetPendingMFAState(ctx, user.ID, "AGAIN", []string{"code-3"}, raw))
+ reread, err := s.GetUserByID(ctx, user.ID)
+ a.NoError(err)
+ stored := reread.MFAConfig.GetTempOtpSecretCreatedTime().AsTime()
+ a.True(stored.Equal(raw.Truncate(time.Microsecond)), "stored %v, minted %v", stored, raw)
+ }
}
diff --git a/backend/store/principal.go b/backend/store/principal.go
index 735be66e5e..96f3365b02 100644
--- a/backend/store/principal.go
+++ b/backend/store/principal.go
@@ -331,6 +331,45 @@ func listUserImpl(ctx context.Context, txn *sql.Tx, find *FindUserMessage) ([]*U
return userMessages, nil
}
+// ConsumeRecoveryCode removes one live recovery code from the account, and
+// reports whether this call is the one that removed it. The removal is a
+// predicate on the row rather than a read-modify-write: two requests spending
+// the same code race here and exactly one sees consumed=true, and the other
+// live fields are never rewritten from whatever the caller happened to read.
+//
+// Callers must treat consumed=false as an invalid code. Verifying against a
+// list read earlier is not enough — that list can be a spend behind.
+func (s *Store) ConsumeRecoveryCode(ctx context.Context, userID int, code string) (bool, error) {
+ // protojson's spelling for MFAConfig.recovery_codes; this JSON is read
+ // back through protojson.Unmarshal.
+ q := qb.Q().Space(`
+ UPDATE principal
+ SET mfa_config = jsonb_set(
+ mfa_config,
+ '{recoveryCodes}',
+ COALESCE((
+ SELECT jsonb_agg(remaining)
+ FROM jsonb_array_elements(mfa_config->'recoveryCodes') AS remaining
+ WHERE remaining <> to_jsonb(?::text)
+ ), '[]'::jsonb))
+ WHERE id = ? AND COALESCE(mfa_config->'recoveryCodes', '[]'::jsonb) @> to_jsonb(?::text)
+ RETURNING email
+ `, code, userID, code)
+ query, args, err := q.ToSQL()
+ if err != nil {
+ return false, errors.Wrapf(err, "failed to build sql")
+ }
+ var email string
+ if err := s.GetDB().QueryRowContext(ctx, query, args...).Scan(&email); err != nil {
+ if errors.Is(err, sql.ErrNoRows) {
+ return false, nil
+ }
+ return false, errors.Wrapf(err, "failed to consume recovery code")
+ }
+ s.userEmailCache.Remove(email)
+ return true, nil
+}
+
// SetPendingMFAState writes the three pending enrollment fields and nothing
// else. The live factor is left exactly as the row has it rather than copied
// forward from whatever the caller read: a mint that rewrites the whole config
@@ -342,6 +381,11 @@ func listUserImpl(ctx context.Context, txn *sql.Tx, find *FindUserMessage) ([]*U
// abandoned enrollment left behind — otherwise confirming those codes would
// promote a secret nobody is holding.
func (s *Store) SetPendingMFAState(ctx context.Context, userID int, tempOtpSecret string, tempRecoveryCodes []string, createdTime time.Time) error {
+ // Truncated because UpdateUserMFAConfigIfPending matches this value as a
+ // timestamptz, and that type is microsecond-resolution: a nanosecond tail
+ // stored here would be rounded by the cast in that predicate and never
+ // match the value handed back to the caller.
+ createdTime = createdTime.Truncate(time.Microsecond)
codesJSON, err := json.Marshal(tempRecoveryCodes)
if err != nil {
return err
@@ -388,11 +432,19 @@ func (s *Store) UpdateUserMFAConfigIfPending(ctx context.Context, userID int, ex
// as timestamptz rather than text keeps the match independent of how many
// fractional digits the value was serialized with. A cleared config has no
// such key, so the NULL comparison fails and the write is refused.
+ //
+ // timestamptz is microsecond-resolution, so both sides are truncated to
+ // microseconds: the cast rounds a nanosecond tail while the bound
+ // parameter does not, and the two then disagree for any instant whose
+ // sub-microsecond remainder is large enough to round up. Go's clock is
+ // microsecond-granular on macOS and nanosecond-granular on Linux, so
+ // without this the mismatch appears only on Linux — and there, for roughly
+ // half of all enrollments.
q := qb.Q().Space(`
UPDATE principal SET mfa_config = ?
WHERE id = ? AND (mfa_config->>'tempOtpSecretCreatedTime')::timestamptz = ?
RETURNING id, deleted, email, name, password_hash, mfa_config, phone, profile, created_at
- `, mfaConfigBytes, userID, expectedPendingVersion)
+ `, mfaConfigBytes, userID, expectedPendingVersion.Truncate(time.Microsecond))
sqlStr, args, err := q.ToSQL()
if err != nil {
return nil, errors.Wrapf(err, "failed to build sql")
diff --git a/backend/tests/credential_change_test.go b/backend/tests/credential_change_test.go
new file mode 100644
index 0000000000..454476cdf3
--- /dev/null
+++ b/backend/tests/credential_change_test.go
@@ -0,0 +1,466 @@
+package tests
+
+import (
+ "context"
+ "crypto/hmac"
+ "crypto/sha256"
+ "database/sql"
+ "encoding/hex"
+ "strings"
+ "testing"
+ "time"
+
+ "connectrpc.com/connect"
+ "github.com/pquerna/otp/totp"
+ "github.com/stretchr/testify/require"
+ "golang.org/x/crypto/bcrypt"
+ "google.golang.org/protobuf/types/known/fieldmaskpb"
+
+ "github.com/bytebase/bytebase/backend/common"
+ v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"
+)
+
+// Regression tests for docs/design/reauthenticate-credential-changes.md:
+// every mutation of live authentication material demands a CredentialProof,
+// and a password change revokes the account's sessions and OAuth grants
+// atomically with the write.
+
+func passwordProofOf(password string) *v1pb.CredentialProof {
+ return &v1pb.CredentialProof{Proof: &v1pb.CredentialProof_CurrentPassword{CurrentPassword: password}}
+}
+
+func otpProofOf(t *testing.T, otpSecret string) *v1pb.CredentialProof {
+ t.Helper()
+ code, err := totp.GenerateCode(otpSecret, time.Now())
+ require.NoError(t, err)
+ return &v1pb.CredentialProof{Proof: &v1pb.CredentialProof_OtpCode{OtpCode: code}}
+}
+
+func TestChangePasswordProofAndRevocation(t *testing.T) {
+ t.Parallel()
+ a := require.New(t)
+ ctx := context.Background()
+ ctl := &controller{}
+ ctx, err := ctl.StartServerWithExternalPg(ctx)
+ a.NoError(err)
+ defer ctl.Close(ctx)
+
+ metadataDB, err := sql.Open("pgx", ctl.profile.PgURL)
+ a.NoError(err)
+ defer metadataDB.Close()
+
+ const email = "[email protected]"
+ const oldPassword = "1024bytebase"
+ const newPassword = "rotated-password-1"
+ userName := common.FormatUserEmail(email)
+
+ // Seed one row per token table so the revocation's coverage is observable:
+ // a web session, an OAuth authorization code, and an OAuth refresh grant.
+ for _, stmt := range []string{
+ `INSERT INTO web_refresh_token (token_hash, user_email, expires_at) VALUES ('cred-web-token', $1, now() + interval '1 hour')`,
+ `INSERT INTO oauth2_client (client_id, client_secret_hash, config) VALUES ('cred-client', 'unused', '{}')`,
+ `INSERT INTO oauth2_authorization_code (code, client_id, user_email, config, expires_at) VALUES ('cred-code', 'cred-client', $1, '{}', now() + interval '1 hour')`,
+ `INSERT INTO oauth2_refresh_token (token_hash, client_id, user_email, config, expires_at) VALUES ('cred-grant', 'cred-client', $1, '{}', now() + interval '30 days')`,
+ } {
+ if strings.Contains(stmt, "$1") {
+ _, err = metadataDB.ExecContext(ctx, stmt, email)
+ } else {
+ _, err = metadataDB.ExecContext(ctx, stmt)
+ }
+ a.NoError(err)
+ }
+
+ // Self-service password change no longer rides on UpdateUser.
+ _, err = ctl.userServiceClient.UpdateUser(ctx, connect.NewRequest(&v1pb.UpdateUserRequest{
+ User: &v1pb.User{Name: userName, Password: newPassword},
+ UpdateMask: &fieldmaskpb.FieldMask{Paths: []string{"password"}},
+ }))
+ a.Equal(connect.CodeInvalidArgument, connect.CodeOf(err))
+ a.ErrorContains(err, "ChangePassword")
+
+ // A wrong current password is refused without touching anything.
+ _, err = ctl.userServiceClient.ChangePassword(ctx, connect.NewRequest(&v1pb.ChangePasswordRequest{
+ Name: userName,
+ NewPassword: newPassword,
+ Credential: passwordProofOf("not-the-password"),
+ }))
+ a.Equal(connect.CodeUnauthenticated, connect.CodeOf(err))
+
+ // A valid emailed code is refused on self-hosted, where the channel does
+ // not exist at all — mailbox possession never stands in for a credential
+ // here, even with a code planted directly in the store.
+ insertReauthCode(ctx, t, metadataDB, email, "554433")
+ _, err = ctl.userServiceClient.ChangePassword(ctx, connect.NewRequest(&v1pb.ChangePasswordRequest{
+ Name: userName,
+ NewPassword: newPassword,
+ Credential: &v1pb.CredentialProof{Proof: &v1pb.CredentialProof_EmailCode{EmailCode: "554433"}},
+ }))
+ a.Equal(connect.CodeFailedPrecondition, connect.CodeOf(err))
+ a.ErrorContains(err, "Cloud")
+
+ // The real change: proof verified, web sessions revoked, and the
+ // same-password refusal enforced against the new value.
+ _, err = ctl.userServiceClient.ChangePassword(ctx, connect.NewRequest(&v1pb.ChangePasswordRequest{
+ Name: userName,
+ NewPassword: newPassword,
+ Credential: passwordProofOf(oldPassword),
+ }))
+ a.NoError(err)
+
+ var sessions int
+ a.NoError(metadataDB.QueryRowContext(ctx,
+ `SELECT COUNT(*) FROM web_refresh_token WHERE user_email = $1`, email).Scan(&sessions))
+ a.Zero(sessions, "a password change ends the account's web sessions")
+
+ // OAuth grants are deliberately not swept here: this method revokes what
+ // the password mask on UpdateUser already revoked, and widening that to
+ // MCP grants is a separate change with its own blast radius.
+ var grants int
+ a.NoError(metadataDB.QueryRowContext(ctx,
+ `SELECT COUNT(*) FROM oauth2_refresh_token WHERE user_email = $1`, email).Scan(&grants))
+ a.Positive(grants, "the seeded grant is still here, which is today's behavior")
+
+ _, err = ctl.userServiceClient.ChangePassword(ctx, connect.NewRequest(&v1pb.ChangePasswordRequest{
+ Name: userName,
+ NewPassword: newPassword,
+ Credential: passwordProofOf(newPassword),
+ }))
+ a.Equal(connect.CodeInvalidArgument, connect.CodeOf(err), "changing to the same password must not reset the rotation deadline")
+
+ // The old password is dead and the new one works.
+ adminToken := ctl.authInterceptor.token
+ ctl.authInterceptor.token = ""
+ _, err = ctl.authServiceClient.Login(ctx, connect.NewRequest(&v1pb.LoginRequest{Email: email, Password: oldPassword}))
+ a.Equal(connect.CodeUnauthenticated, connect.CodeOf(err))
+ _, err = ctl.authServiceClient.Login(ctx, connect.NewRequest(&v1pb.LoginRequest{Email: email, Password: newPassword}))
+ a.NoError(err)
+ ctl.authInterceptor.token = adminToken
+}
+
+func TestCredentialProofSharesLoginLockout(t *testing.T) {
+ t.Parallel()
+ a := require.New(t)
+ ctx := context.Background()
+ ctl := &controller{}
+ ctx, err := ctl.StartServerWithExternalPg(ctx)
+ a.NoError(err)
+ defer ctl.Close(ctx)
+
+ const email = "[email protected]"
+ const password = "victim-password-1"
+ adminToken := ctl.authInterceptor.token
+ ctl.authInterceptor.token = ""
+ _, err = ctl.authServiceClient.Signup(ctx, connect.NewRequest(&v1pb.SignupRequest{
+ Email: email,
+ Title: "Lockout Victim",
+ Password: password,
+ }))
+ a.NoError(err)
+ login, err := ctl.authServiceClient.Login(ctx, connect.NewRequest(&v1pb.LoginRequest{Email: email, Password: password}))
+ a.NoError(err)
+ ctl.authInterceptor.token = login.Msg.Token
+
+ // Five wrong proofs exhaust the shared PASSWORD bucket; the sixth is
+ // refused before any comparison, and login itself is locked out too — the
+ // proof is not a fresh guessing oracle beside T9's.
+ for range 5 {
+ _, err := ctl.userServiceClient.ChangePassword(ctx, connect.NewRequest(&v1pb.ChangePasswordRequest{
+ Name: common.FormatUserEmail(email),
+ NewPassword: "does-not-matter-1",
+ Credential: passwordProofOf("wrong-password"),
+ }))
+ a.Equal(connect.CodeUnauthenticated, connect.CodeOf(err))
+ }
+ _, err = ctl.userServiceClient.ChangePassword(ctx, connect.NewRequest(&v1pb.ChangePasswordRequest{
+ Name: common.FormatUserEmail(email),
+ NewPassword: "does-not-matter-1",
+ Credential: passwordProofOf(password),
+ }))
+ a.Equal(connect.CodeResourceExhausted, connect.CodeOf(err))
+
+ ctl.authInterceptor.token = ""
+ _, err = ctl.authServiceClient.Login(ctx, connect.NewRequest(&v1pb.LoginRequest{Email: email, Password: password}))
+ a.Equal(connect.CodeResourceExhausted, connect.CodeOf(err),
+ "credential-proof guesses and login guesses must drain the same per-identity budget")
+ ctl.authInterceptor.token = adminToken
+}
+
+func TestMFALifecycleFactorBoundProofs(t *testing.T) {
+ t.Parallel()
+ a := require.New(t)
+ ctx := context.Background()
+ ctl := &controller{}
+ ctx, err := ctl.StartServerWithExternalPg(ctx)
+ a.NoError(err)
+ defer ctl.Close(ctx)
+
+ const email = "[email protected]"
+ const password = "1024bytebase"
+ userName := common.FormatUserEmail(email)
+ otpSecret := enrollMFA(ctx, t, ctl, userName, password)
+
+ // While a live factor exists, factor-touching methods refuse the password:
+ // ResetPassword mints one from mailbox possession alone, so accepting it
+ // here would let a stolen session plus mailbox strip the second factor.
+ _, err = ctl.userServiceClient.DisableMFA(ctx, connect.NewRequest(&v1pb.DisableMFARequest{
+ Name: userName,
+ Credential: passwordProofOf(password),
+ }))
+ a.Equal(connect.CodeInvalidArgument, connect.CodeOf(err))
+
+ // Recovery-code rotation: a stale pending_version is rejected rather than
+ // silently promoting whatever is currently pending.
+ first, err := ctl.userServiceClient.RegenerateRecoveryCodes(ctx, connect.NewRequest(&v1pb.RegenerateRecoveryCodesRequest{Name: userName}))
+ a.NoError(err)
+ second, err := ctl.userServiceClient.RegenerateRecoveryCodes(ctx, connect.NewRequest(&v1pb.RegenerateRecoveryCodesRequest{Name: userName}))
+ a.NoError(err)
+ _, err = ctl.userServiceClient.ConfirmRecoveryCodes(ctx, connect.NewRequest(&v1pb.ConfirmRecoveryCodesRequest{
+ Name: userName,
+ Credential: otpProofOf(t, otpSecret),
+ PendingVersion: first.Msg.PendingVersion,
+ }))
+ a.Equal(connect.CodeFailedPrecondition, connect.CodeOf(err))
+
+ // The rotation's own confirmation is factor-bound too.
+ _, err = ctl.userServiceClient.ConfirmRecoveryCodes(ctx, connect.NewRequest(&v1pb.ConfirmRecoveryCodesRequest{
+ Name: userName,
+ Credential: passwordProofOf(password),
+ PendingVersion: second.Msg.PendingVersion,
+ }))
+ a.Equal(connect.CodeInvalidArgument, connect.CodeOf(err))
+
+ _, err = ctl.userServiceClient.ConfirmRecoveryCodes(ctx, connect.NewRequest(&v1pb.ConfirmRecoveryCodesRequest{
+ Name: userName,
+ Credential: otpProofOf(t, otpSecret),
+ PendingVersion: second.Msg.PendingVersion,
+ }))
+ a.NoError(err)
+
+ // Confirming promoted the second set, and DisableMFA takes a recovery code
+ // in place of an OTP — either proves the factor it is turning off.
+ recoveryProof := &v1pb.CredentialProof{Proof: &v1pb.CredentialProof_RecoveryCode{RecoveryCode: second.Msg.RecoveryCodes[0]}}
+ disabled, err := ctl.userServiceClient.DisableMFA(ctx, connect.NewRequest(&v1pb.DisableMFARequest{
+ Name: userName,
+ Credential: recoveryProof,
+ }))
+ a.NoError(err)
+ a.False(disabled.Msg.MfaEnabled)
+
+ // Disabling wiped the config, so there is no longer a factor to prove:
+ // a repeat reaches the same desired state rather than reporting failure
+ // for a satisfied intent, and needs no credential to do it. That is what
+ // lets a user abandon an enrollment they can no longer complete.
+ repeat, err := ctl.userServiceClient.DisableMFA(ctx, connect.NewRequest(&v1pb.DisableMFARequest{
+ Name: userName,
+ }))
+ a.NoError(err)
+ a.False(repeat.Msg.MfaEnabled)
+}
+
+// TestEmailCodeProofIsCloudOnly pins the deployment split: only Cloud can
+// send email, so on self-hosted the email_code channel does not exist at all —
+// even a valid code planted directly in the store is refused — and a
+// passwordless account is pointed at the admin-password-reset route instead of
+// dying on an unusable verification error.
+func TestEmailCodeProofIsCloudOnly(t *testing.T) {
+ t.Parallel()
+ a := require.New(t)
+ ctx := context.Background()
+ ctl := &controller{}
+ ctx, err := ctl.StartServerWithExternalPg(ctx)
+ a.NoError(err)
+ defer ctl.Close(ctx)
+
+ metadataDB, err := sql.Open("pgx", ctl.profile.PgURL)
+ a.NoError(err)
+ defer metadataDB.Close()
+
+ // The send side refuses on self-hosted before any mail machinery runs.
+ _, err = ctl.userServiceClient.RequestReauthCode(ctx, connect.NewRequest(&v1pb.RequestReauthCodeRequest{
+ Name: common.FormatUserEmail("[email protected]"),
+ }))
+ a.Equal(connect.CodeFailedPrecondition, connect.CodeOf(err))
+ a.ErrorContains(err, "Cloud")
+
+ // A passwordless account — the SSO shape: a hash its owner never chose,
+ // lastChangePasswordTime unset. Seeded directly because this suite has no
+ // IdP; the test still knows the hash's preimage so it can hold a session
+ // as the user.
+ const email = "[email protected]"
+ const bridgePassword = "sso-bridge-pass-1"
+ bridgeHash, err := bcrypt.GenerateFromPassword([]byte(bridgePassword), bcrypt.MinCost)
+ a.NoError(err)
+ _, err = metadataDB.ExecContext(ctx, `
+ INSERT INTO principal (name, email, password_hash, profile)
+ VALUES ('SSO User', $1, $2, '{}')
+ `, email, string(bridgeHash))
+ a.NoError(err)
+
+ adminToken := ctl.authInterceptor.token
+ ctl.authInterceptor.token = ""
+ login, err := ctl.authServiceClient.Login(ctx, connect.NewRequest(&v1pb.LoginRequest{Email: email, Password: bridgePassword}))
+ a.NoError(err)
+ ctl.authInterceptor.token = login.Msg.Token
+
+ // Even a valid REAUTH code sitting in the store cannot be spent here.
+ insertReauthCode(ctx, t, metadataDB, email, "665544")
+ _, err = ctl.userServiceClient.ChangePassword(ctx, connect.NewRequest(&v1pb.ChangePasswordRequest{
+ Name: common.FormatUserEmail(email),
+ NewPassword: "chosen-at-last-1",
+ Credential: &v1pb.CredentialProof{Proof: &v1pb.CredentialProof_EmailCode{EmailCode: "665544"}},
+ }))
+ a.Equal(connect.CodeFailedPrecondition, connect.CodeOf(err))
+ a.ErrorContains(err, "Cloud")
+
+ // First-time enrollment on a passwordless self-hosted account fails at
+ // step one with the actionable route, not after saving recovery codes.
+ minted, err := ctl.userServiceClient.StartMFAEnrollment(ctx, connect.NewRequest(&v1pb.StartMFAEnrollmentRequest{
+ Name: common.FormatUserEmail(email),
+ }))
+ a.NoError(err)
+ otp, err := totp.GenerateCode(minted.Msg.OtpSecret, time.Now())
+ a.NoError(err)
+ _, err = ctl.userServiceClient.EnableMFA(ctx, connect.NewRequest(&v1pb.EnableMFARequest{
+ Name: common.FormatUserEmail(email),
+ OtpCode: otp,
+ PendingVersion: minted.Msg.PendingVersion,
+ }))
+ a.Equal(connect.CodeFailedPrecondition, connect.CodeOf(err))
+ a.ErrorContains(err, "ask a workspace admin")
+
+ // The admin-reset route works: once an admin sets a password, the account
+ // has a caller-chosen password and enrolls with it as proof.
+ ctl.authInterceptor.token = adminToken
+ _, err = ctl.userServiceClient.UpdateUser(ctx, connect.NewRequest(&v1pb.UpdateUserRequest{
+ User: &v1pb.User{Name: common.FormatUserEmail(email), Password: "admin-issued-pass-1"},
+ UpdateMask: &fieldmaskpb.FieldMask{Paths: []string{"password"}},
+ }))
+ a.NoError(err)
+ ctl.authInterceptor.token = ""
+ login, err = ctl.authServiceClient.Login(ctx, connect.NewRequest(&v1pb.LoginRequest{Email: email, Password: "admin-issued-pass-1"}))
+ a.NoError(err)
+ ctl.authInterceptor.token = login.Msg.Token
+ enrollMFA(ctx, t, ctl, common.FormatUserEmail(email), "admin-issued-pass-1")
+ ctl.authInterceptor.token = adminToken
+}
+
+// TestRecoveryCodeProofIsSpentOnce covers the one proof channel that spends
+// what it proves. EnableMFA writes nothing of its own, so a recovery code
+// accepted there is single-use only if the verification records the spend on
+// the row itself: an in-memory edit would leave the code live in the database
+// while the replica that served the request believed otherwise, and every
+// other replica kept accepting it.
+func TestRecoveryCodeProofIsSpentOnce(t *testing.T) {
+ t.Parallel()
+ a := require.New(t)
+ ctx := context.Background()
+ ctl := &controller{}
+ ctx, err := ctl.StartServerWithExternalPg(ctx)
+ a.NoError(err)
+ defer ctl.Close(ctx)
+
+ const email = "[email protected]"
+ const password = "1024bytebase"
+ userName := common.FormatUserEmail(email)
+
+ minted, err := ctl.userServiceClient.StartMFAEnrollment(ctx, connect.NewRequest(&v1pb.StartMFAEnrollmentRequest{Name: userName}))
+ a.NoError(err)
+ otp, err := totp.GenerateCode(minted.Msg.OtpSecret, time.Now())
+ a.NoError(err)
+ _, err = ctl.userServiceClient.EnableMFA(ctx, connect.NewRequest(&v1pb.EnableMFARequest{
+ Name: userName,
+ OtpCode: otp,
+ Credential: passwordProofOf(password),
+ PendingVersion: minted.Msg.PendingVersion,
+ }))
+ a.NoError(err)
+ _, err = ctl.userServiceClient.ConfirmRecoveryCodes(ctx, connect.NewRequest(&v1pb.ConfirmRecoveryCodesRequest{
+ Name: userName,
+ Credential: passwordProofOf(password),
+ PendingVersion: minted.Msg.PendingVersion,
+ OtpCode: otp,
+ }))
+ a.NoError(err)
+ liveCodes := minted.Msg.RecoveryCodes
+ a.GreaterOrEqual(len(liveCodes), 2)
+
+ recoveryProofOf := func(code string) *v1pb.CredentialProof {
+ return &v1pb.CredentialProof{Proof: &v1pb.CredentialProof_RecoveryCode{RecoveryCode: code}}
+ }
+ // Replacing the authenticator is a factor-touching call, so the proof has
+ // to be the factor — an OTP, or one of these recovery codes.
+ rotateWith := func(credential *v1pb.CredentialProof) error {
+ t.Helper()
+ next, err := ctl.userServiceClient.StartMFAEnrollment(ctx, connect.NewRequest(&v1pb.StartMFAEnrollmentRequest{Name: userName}))
+ a.NoError(err)
+ nextOTP, err := totp.GenerateCode(next.Msg.OtpSecret, time.Now())
+ a.NoError(err)
+ _, err = ctl.userServiceClient.EnableMFA(ctx, connect.NewRequest(&v1pb.EnableMFARequest{
+ Name: userName,
+ OtpCode: nextOTP,
+ Credential: credential,
+ PendingVersion: next.Msg.PendingVersion,
+ }))
+ return err
+ }
+
+ a.NoError(rotateWith(recoveryProofOf(liveCodes[0])))
+
+ // EnableMFA promoted nothing, so the live factor and its codes are the
+ // same set as before — minus the one just spent, which the row no longer
+ // holds. This is the assertion an in-place edit cannot satisfy.
+ a.Equal(connect.CodeUnauthenticated, connect.CodeOf(rotateWith(recoveryProofOf(liveCodes[0]))),
+ "a recovery code accepted once must not be accepted again")
+
+ // A different code from the same set still works, so exactly one was
+ // spent rather than the list being rewritten wholesale.
+ a.NoError(rotateWith(recoveryProofOf(liveCodes[1])))
+}
+
+// enrollMFA walks the split enrollment for an account that proves itself with
+// a password, and returns the live TOTP secret.
+func enrollMFA(ctx context.Context, t *testing.T, ctl *controller, userName, password string) string {
+ t.Helper()
+ a := require.New(t)
+ minted, err := ctl.userServiceClient.StartMFAEnrollment(ctx, connect.NewRequest(&v1pb.StartMFAEnrollmentRequest{Name: userName}))
+ a.NoError(err)
+ otp, err := totp.GenerateCode(minted.Msg.OtpSecret, time.Now())
+ a.NoError(err)
+ _, err = ctl.userServiceClient.EnableMFA(ctx, connect.NewRequest(&v1pb.EnableMFARequest{
+ Name: userName,
+ OtpCode: otp,
+ Credential: passwordProofOf(password),
+ PendingVersion: minted.Msg.PendingVersion,
+ }))
+ a.NoError(err)
+ confirmed, err := ctl.userServiceClient.ConfirmRecoveryCodes(ctx, connect.NewRequest(&v1pb.ConfirmRecoveryCodesRequest{
+ Name: userName,
+ Credential: passwordProofOf(password),
+ PendingVersion: minted.Msg.PendingVersion,
+ OtpCode: otp,
+ }))
+ a.NoError(err)
+ a.True(confirmed.Msg.MfaEnabled)
+ return minted.Msg.OtpSecret
+}
+
+// insertReauthCode plants a REAUTH verification code directly, hashed the way
+// the server hashes it (HMAC with the deployment's auth secret). The suite
+// runs self-hosted, where no such row is ever legitimately written — planting
+// one is exactly the point: even a valid code must be refused off Cloud.
+func insertReauthCode(ctx context.Context, t *testing.T, metadataDB *sql.DB, email, code string) {
+ t.Helper()
+ a := require.New(t)
+ var authSecret string
+ a.NoError(metadataDB.QueryRowContext(ctx, `SELECT payload->>'authSecret' FROM server_config`).Scan(&authSecret))
+ 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)
+ VALUES ($1, 'REAUTH', $2, now() + interval '10 minutes', now())
+ 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, hex.EncodeToString(mac.Sum(nil)))
+ a.NoError(err)
+}
diff --git a/backend/tests/login_audit_test.go b/backend/tests/login_audit_test.go
index cbdd62eba3..164ca40583 100644
--- a/backend/tests/login_audit_test.go
+++ b/backend/tests/login_audit_test.go
@@ -48,15 +48,21 @@ func TestLoginFailureLockout(t *testing.T) {
a.NoError(err)
validOTP, err := totp.GenerateCode(mfaSetup.Msg.OtpSecret, time.Now())
a.NoError(err)
+ passwordProof := &v1pb.CredentialProof{Proof: &v1pb.CredentialProof_CurrentPassword{CurrentPassword: "1024bytebase"}}
_, err = ctl.userServiceClient.EnableMFA(ctx, connect.NewRequest(&v1pb.EnableMFARequest{
Name: userName,
OtpCode: validOTP,
+ Credential: passwordProof,
PendingVersion: mfaSetup.Msg.PendingVersion,
}))
a.NoError(err)
+ confirmOTP, err := totp.GenerateCode(mfaSetup.Msg.OtpSecret, time.Now())
+ a.NoError(err)
_, err = ctl.userServiceClient.ConfirmRecoveryCodes(ctx, connect.NewRequest(&v1pb.ConfirmRecoveryCodesRequest{
Name: userName,
+ Credential: passwordProof,
PendingVersion: mfaSetup.Msg.PendingVersion,
+ OtpCode: confirmOTP,
}))
a.NoError(err)
diff --git a/backend/tests/mcp_forbidden_class_test.go b/backend/tests/mcp_forbidden_class_test.go
index cb1af09d6a..2f912192e7 100644
--- a/backend/tests/mcp_forbidden_class_test.go
+++ b/backend/tests/mcp_forbidden_class_test.go
@@ -189,12 +189,16 @@ func TestWebUserStillChangesPasswordAndLogsIn(t *testing.T) {
a.NoError(err)
// The user's own session changes their own password, exactly as the
- // console does.
+ // console does — proving the current one, per
+ // docs/design/reauthenticate-credential-changes.md.
admin := ctl.authInterceptor.token
ctl.authInterceptor.token = login.Msg.Token
_, err = ctl.userServiceClient.ChangePassword(ctx, connect.NewRequest(&v1pb.ChangePasswordRequest{
Name: "users/" + webEmail,
NewPassword: newPassword,
+ Credential: &v1pb.CredentialProof{
+ Proof: &v1pb.CredentialProof_CurrentPassword{CurrentPassword: oldPassword},
+ },
}))
ctl.authInterceptor.token = admin
a.NoError(err, "a normal session must still be able to change its own password")
diff --git a/backend/tests/read_path_secret_test.go b/backend/tests/read_path_secret_test.go
index 7b7083e4dc..9344486f5c 100644
--- a/backend/tests/read_path_secret_test.go
+++ b/backend/tests/read_path_secret_test.go
@@ -132,12 +132,20 @@ func TestEnrollmentSecretsLiveOnlyInTheMintingResponses(t *testing.T) {
_, err = ctl.userServiceClient.EnableMFA(ctx, connect.NewRequest(&v1pb.EnableMFARequest{
Name: userName,
OtpCode: otp,
+ Credential: &v1pb.CredentialProof{Proof: &v1pb.CredentialProof_CurrentPassword{CurrentPassword: "1024bytebase"}},
PendingVersion: minted.Msg.PendingVersion,
}))
a.NoError(err)
+ // A fresh code, not a replay of EnableMFA's: promotion is the moment MFA
+ // starts gating logins, and the download screen in between outlives one
+ // ~30s TOTP window.
+ confirmOTP, err := totp.GenerateCode(minted.Msg.OtpSecret, time.Now())
+ a.NoError(err)
confirmed, err := ctl.userServiceClient.ConfirmRecoveryCodes(ctx, connect.NewRequest(&v1pb.ConfirmRecoveryCodesRequest{
Name: userName,
+ OtpCode: confirmOTP,
+ Credential: &v1pb.CredentialProof{Proof: &v1pb.CredentialProof_CurrentPassword{CurrentPassword: "1024bytebase"}},
PendingVersion: minted.Msg.PendingVersion,
}))
a.NoError(err)
@@ -286,8 +294,21 @@ func TestMFAReplacementPromotesTheNewAuthenticator(t *testing.T) {
defer ctl.Close(ctx)
userName := common.FormatUserEmail("[email protected]")
- enroll := func() string {
+ // liveSecret is empty for the account's first factor and holds the live
+ // one for the replacement: a factor-touching call on an account that has a
+ // factor must be proven with that factor, never with the password, since a
+ // password can be minted from mailbox possession alone.
+ enroll := func(liveSecret string) string {
t.Helper()
+ proof := func() *v1pb.CredentialProof {
+ t.Helper()
+ if liveSecret == "" {
+ return &v1pb.CredentialProof{Proof: &v1pb.CredentialProof_CurrentPassword{CurrentPassword: "1024bytebase"}}
+ }
+ live, err := totp.GenerateCode(liveSecret, time.Now())
+ a.NoError(err)
+ return &v1pb.CredentialProof{Proof: &v1pb.CredentialProof_OtpCode{OtpCode: live}}
+ }
minted, err := ctl.userServiceClient.StartMFAEnrollment(ctx, connect.NewRequest(&v1pb.StartMFAEnrollmentRequest{
Name: userName,
}))
@@ -297,19 +318,29 @@ func TestMFAReplacementPromotesTheNewAuthenticator(t *testing.T) {
_, err = ctl.userServiceClient.EnableMFA(ctx, connect.NewRequest(&v1pb.EnableMFARequest{
Name: userName,
OtpCode: otp,
+ Credential: proof(),
PendingVersion: minted.Msg.PendingVersion,
}))
a.NoError(err)
- _, err = ctl.userServiceClient.ConfirmRecoveryCodes(ctx, connect.NewRequest(&v1pb.ConfirmRecoveryCodesRequest{
+ confirm := &v1pb.ConfirmRecoveryCodesRequest{
Name: userName,
+ Credential: proof(),
PendingVersion: minted.Msg.PendingVersion,
- }))
+ }
+ if liveSecret == "" {
+ // Only a first-time enrollment re-proves the new device here; a
+ // replacement is proven with the factor it is replacing.
+ confirmOTP, err := totp.GenerateCode(minted.Msg.OtpSecret, time.Now())
+ a.NoError(err)
+ confirm.OtpCode = confirmOTP
+ }
+ _, err = ctl.userServiceClient.ConfirmRecoveryCodes(ctx, connect.NewRequest(confirm))
a.NoError(err)
return minted.Msg.OtpSecret
}
- firstSecret := enroll()
- replacementSecret := enroll()
+ firstSecret := enroll("")
+ replacementSecret := enroll(firstSecret)
a.NotEqual(firstSecret, replacementSecret)
// Sign in with the replacement authenticator. This is the assertion that
@@ -362,11 +393,16 @@ func TestSupersededPendingStateIsRefused(t *testing.T) {
_, err = ctl.userServiceClient.EnableMFA(ctx, connect.NewRequest(&v1pb.EnableMFARequest{
Name: userName,
OtpCode: otp,
+ Credential: &v1pb.CredentialProof{Proof: &v1pb.CredentialProof_CurrentPassword{CurrentPassword: "1024bytebase"}},
PendingVersion: enrolled.Msg.PendingVersion,
}))
a.NoError(err)
+ confirmOTP, err := totp.GenerateCode(enrolled.Msg.OtpSecret, time.Now())
+ a.NoError(err)
_, err = ctl.userServiceClient.ConfirmRecoveryCodes(ctx, connect.NewRequest(&v1pb.ConfirmRecoveryCodesRequest{
Name: userName,
+ OtpCode: confirmOTP,
+ Credential: &v1pb.CredentialProof{Proof: &v1pb.CredentialProof_CurrentPassword{CurrentPassword: "1024bytebase"}},
PendingVersion: enrolled.Msg.PendingVersion,
}))
a.NoError(err)
@@ -385,9 +421,12 @@ func TestSupersededPendingStateIsRefused(t *testing.T) {
a.NoError(err)
a.NotEqual(enrolled.Msg.OtpSecret, replacement.Msg.OtpSecret)
- // Tab one saves its codes and confirms.
+ // Tab one saves its codes and confirms, proving the live factor it has.
+ liveOTPForConfirm, err := totp.GenerateCode(enrolled.Msg.OtpSecret, time.Now())
+ a.NoError(err)
_, err = ctl.userServiceClient.ConfirmRecoveryCodes(ctx, connect.NewRequest(&v1pb.ConfirmRecoveryCodesRequest{
Name: userName,
+ Credential: &v1pb.CredentialProof{Proof: &v1pb.CredentialProof_OtpCode{OtpCode: liveOTPForConfirm}},
PendingVersion: regenerated.Msg.PendingVersion,
}))
a.Equal(connect.CodeFailedPrecondition, connect.CodeOf(err),
@@ -441,20 +480,26 @@ func TestConfirmationCannotRevivePendingStateItRaced(t *testing.T) {
_, err = ctl.userServiceClient.EnableMFA(ctx, connect.NewRequest(&v1pb.EnableMFARequest{
Name: userName,
OtpCode: otp,
+ Credential: &v1pb.CredentialProof{Proof: &v1pb.CredentialProof_CurrentPassword{CurrentPassword: "1024bytebase"}},
PendingVersion: minted.Msg.PendingVersion,
}))
a.NoError(err)
// The pending state is cleared out from under the open enrollment, the way
- // DisableMFA clears it for an account being recovered.
+ // DisableMFA clears it for an account being recovered. No CredentialProof:
+ // nothing was ever promoted, so there is no factor to prove.
_, err = ctl.userServiceClient.DisableMFA(ctx, connect.NewRequest(&v1pb.DisableMFARequest{
Name: userName,
}))
a.NoError(err)
// The stale tab confirms with the version it was handed.
+ staleOTP, err := totp.GenerateCode(minted.Msg.OtpSecret, time.Now())
+ a.NoError(err)
_, err = ctl.userServiceClient.ConfirmRecoveryCodes(ctx, connect.NewRequest(&v1pb.ConfirmRecoveryCodesRequest{
Name: userName,
+ OtpCode: staleOTP,
+ Credential: &v1pb.CredentialProof{Proof: &v1pb.CredentialProof_CurrentPassword{CurrentPassword: "1024bytebase"}},
PendingVersion: minted.Msg.PendingVersion,
}))
a.Equal(connect.CodeFailedPrecondition, connect.CodeOf(err),
diff --git a/docs/design/reauthenticate-credential-changes.md b/docs/design/reauthenticate-credential-changes.md
index af3ce3e000..b2ee98d2d5 100644
--- a/docs/design/reauthenticate-credential-changes.md
+++ b/docs/design/reauthenticate-credential-changes.md
@@ -7,9 +7,50 @@ codes without proving they still control the credential being replaced. Closes T
[`v1-api-audit-2026-08.md`](v1-api-audit-2026-08.md) for every path `UpdateUser` and its neighbors
expose today: password and MFA lifecycle both move off `UpdateUser` onto their own methods, not just a
field addition — see [Resource design](#resource-design). A stolen access token may keep answering
-requests until it expires (≤1h), but this design also stops it being *spent* on a replacement: every
-path that mints a new token from an existing one is bound to the account's credential generation. See
-G7 and Verification → Token-minting paths.
+requests until it expires (≤1h); this design stops it being *spent* on a replacement credential.
+
+> **What shipped differs from this document.** The change that landed is the
+> credential-proof surface only; several mechanisms below were cut or deferred,
+> and the text still describes them as designed.
+>
+> **Shipped.** `CredentialProof` — current password, OTP, recovery code, or an
+> emailed `RequestReauthCode` code — required by `ChangePassword`,
+> `EnableMFA`, `DisableMFA` (self-service), and `ConfirmRecoveryCodes`. Every
+> proof claims a T9 login-attempt slot, so no channel is an unbounded guessing
+> oracle. Factor-touching methods refuse the password while a live factor
+> exists. `email_code` is Bytebase Cloud only and only when no factor exists —
+> bootstrap proof for a Cloud account that has nothing else.
+>
+> **Cut.**
+>
+> - **Credential generation.** `Profile.last_credential_change_time`, the
+> `cred_gen` JWT claim, and the consume-time checks are gone. Service
+> accounts and SSO accounts stop being exceptions to a rule that only ever
+> fit password users.
+> - **The enrollment stamp.** Whether a caller can prove a password is answered
+> by whether they can supply one. With the stamp went the migration: this
+> change needs none.
+> - **MFA revocation.** Enrolling, rotating, or disabling a factor no longer
+> ends other sessions — MFA gates minting a session, not using one, so a new
+> phone must not sign the owner out everywhere. Only a password change
+> revokes, and only the account's web sessions; OAuth grants are untouched,
+> which is a separate change with its own blast radius.
+>
+> **Deferred.** The fenced credential transaction (`store.RunUserCredentialTx`)
+> and the issuance guard are not here; they are a store-concurrency change of
+> their own. Handlers verify against a read and write through the ordinary
+> store methods, so read `Design → the fenced transaction` as intent, not as
+> shipped code.
+>
+> **Kept from the existing implementation.** Promotion stays in
+> `ConfirmRecoveryCodes` for every flow, under the `pending_version`
+> compare-and-set, so a first factor is never live with no saved recovery
+> codes and a replacement promotes the authenticator the user just scanned.
+> `EnableMFA` verifies and writes nothing. First-time enrollment therefore
+> submits a second, fresh `otp_code` at confirmation, since promotion — not
+> verification — is the moment MFA starts gating logins. `DisableMFA` asks for
+> a proof only when there is a live factor to prove, so an abandoned
+> enrollment can still be cancelled.
## Background
diff --git a/frontend/scripts/ui-guideline-legacy-debt.json b/frontend/scripts/ui-guideline-legacy-debt.json
index 488e8662e6..4ccb614f84 100644
--- a/frontend/scripts/ui-guideline-legacy-debt.json
+++ b/frontend/scripts/ui-guideline-legacy-debt.json
@@ -3186,18 +3186,6 @@
"token": "bg-gray-50",
"count": 1
},
- {
- "path": "src/routes/workspace/two-factor/TwoFactorSetupPage.tsx",
- "rule": "no-native-control",
- "token": "button",
- "count": 1
- },
- {
- "path": "src/routes/workspace/two-factor/TwoFactorSetupPage.tsx",
- "rule": "no-raw-color",
- "token": "bg-blue-600",
- "count": 1
- },
{
"path": "src/routes/workspace/two-factor/TwoFactorSetupPage.tsx",
"rule": "no-raw-color",
@@ -3222,12 +3210,6 @@
"token": "border-yellow-200",
"count": 1
},
- {
- "path": "src/routes/workspace/two-factor/TwoFactorSetupPage.tsx",
- "rule": "no-raw-color",
- "token": "hover:bg-blue-700",
- "count": 1
- },
{
"path": "src/routes/workspace/two-factor/TwoFactorSetupPage.tsx",
"rule": "no-raw-color",
@@ -3246,12 +3228,6 @@
"token": "text-red-800",
"count": 1
},
- {
- "path": "src/routes/workspace/two-factor/TwoFactorSetupPage.tsx",
- "rule": "no-raw-color",
- "token": "text-white",
- "count": 1
- },
{
"path": "src/routes/workspace/two-factor/TwoFactorSetupPage.tsx",
"rule": "no-raw-color",
diff --git a/frontend/src/components/CredentialProofInput.test.tsx b/frontend/src/components/CredentialProofInput.test.tsx
new file mode 100644
index 0000000000..30323111a9
--- /dev/null
+++ b/frontend/src/components/CredentialProofInput.test.tsx
@@ -0,0 +1,151 @@
+import type { ReactElement } from "react";
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+const mocks = vi.hoisted(() => ({
+ currentUser: {
+ name: "users/[email protected]",
+ email: "[email protected]",
+ mfaEnabled: false,
+ },
+ saas: false,
+ requestReauthCode: vi.fn(async () => ({})),
+ pushNotification: vi.fn(),
+}));
+
+vi.mock("@/hooks/useAppState", () => ({
+ useCurrentUser: () => mocks.currentUser,
+}));
+
+vi.mock("@/stores", () => ({
+ pushNotification: mocks.pushNotification,
+}));
+
+vi.mock("@/stores/app", () => {
+ const getState = () => ({ serverInfo: { saas: mocks.saas } });
+ return {
+ useAppStore: Object.assign(
+ (selector?: (state: ReturnType<typeof getState>) => unknown) =>
+ selector ? selector(getState()) : getState(),
+ { getState }
+ ),
+ };
+});
+
+vi.mock("@/api", () => ({
+ userServiceClientConnect: { requestReauthCode: mocks.requestReauthCode },
+}));
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({
+ t: (key: string, vars?: Record<string, unknown>) =>
+ vars ? `${key}:${JSON.stringify(vars)}` : key,
+ }),
+ initReactI18next: { type: "3rdParty", init: () => {} },
+}));
+
+let CredentialProofInput: typeof import(
+ "./CredentialProofInput"
+).CredentialProofInput;
+
+const renderIntoContainer = (element: ReactElement) => {
+ const container = document.createElement("div");
+ document.body.appendChild(container);
+ const root = createRoot(container);
+ return {
+ container,
+ render: () => {
+ act(() => {
+ root.render(element);
+ });
+ },
+ unmount: () => {
+ act(() => {
+ root.unmount();
+ });
+ container.remove();
+ },
+ };
+};
+
+// The proof input is the only control in a re-authentication dialog, so a
+// screen reader that cannot name it leaves the account with no way to tell
+// which secret is being asked for.
+const expectLabelledInput = (container: HTMLElement, labelKey: string) => {
+ const label = container.querySelector("label");
+ expect(label?.textContent).toBe(`${labelKey}*`);
+ expect(label?.htmlFor).toBeTruthy();
+ const input = container.querySelector<HTMLInputElement>(
+ `#${CSS.escape(label?.htmlFor ?? "")}`
+ );
+ expect(input?.tagName).toBe("INPUT");
+ return input as HTMLInputElement;
+};
+
+beforeEach(async () => {
+ vi.clearAllMocks();
+ mocks.currentUser = {
+ name: "users/[email protected]",
+ email: "[email protected]",
+ mfaEnabled: false,
+ };
+ mocks.saas = false;
+ ({ CredentialProofInput } = await import("./CredentialProofInput"));
+});
+
+describe("CredentialProofInput", () => {
+ test("password mode labels its input", () => {
+ const { container, render, unmount } = renderIntoContainer(
+ <CredentialProofInput value="" onChange={() => {}} />
+ );
+ render();
+
+ const input = expectLabelledInput(
+ container,
+ "credential-proof.password-label"
+ );
+ expect(input.type).toBe("password");
+ expect(input.autocomplete).toBe("current-password");
+
+ unmount();
+ });
+
+ test("factor mode labels its input", () => {
+ mocks.currentUser = { ...mocks.currentUser, mfaEnabled: true };
+ const { container, render, unmount } = renderIntoContainer(
+ <CredentialProofInput value="" onChange={() => {}} />
+ );
+ render();
+
+ const input = expectLabelledInput(
+ container,
+ "credential-proof.factor-label"
+ );
+ expect(input.placeholder).toBe("credential-proof.factor-placeholder");
+ expect(input.autocomplete).toBe("one-time-code");
+
+ unmount();
+ });
+
+ test("email mode labels the input it pairs with the send button", () => {
+ mocks.saas = true;
+ const { container, render, unmount } = renderIntoContainer(
+ <CredentialProofInput value="" onChange={() => {}} />
+ );
+ render();
+
+ const input = expectLabelledInput(container, "credential-proof.email-label");
+ expect(input.placeholder).toBe("credential-proof.email-placeholder");
+ // The button shares the field's row, so the label must point at the input
+ // rather than wrapping both controls.
+ const button = container.querySelector("button");
+ expect(button?.textContent).toBe("credential-proof.email-me-a-code");
+
+ unmount();
+ });
+});
diff --git a/frontend/src/components/CredentialProofInput.tsx b/frontend/src/components/CredentialProofInput.tsx
new file mode 100644
index 0000000000..342dd0c16c
--- /dev/null
+++ b/frontend/src/components/CredentialProofInput.tsx
@@ -0,0 +1,220 @@
+import { create } from "@bufbuild/protobuf";
+import { Code, createContextValues } from "@connectrpc/connect";
+import {
+ useCallback,
+ useEffect,
+ useId,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
+import { useTranslation } from "react-i18next";
+import { userServiceClientConnect } from "@/api";
+import { ignoredCodesContextKey } from "@/api/context-key";
+import { Button } from "@/components/ui/button";
+import { FormControlRow, FormField, FormLabel } from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import { useCurrentUser } from "@/hooks/useAppState";
+import { pushNotification } from "@/stores";
+import { useAppStore } from "@/stores/app";
+import type { CredentialProof } from "@/types/proto-es/v1/user_service_pb";
+import {
+ CredentialProofSchema,
+ RequestReauthCodeRequestSchema,
+} from "@/types/proto-es/v1/user_service_pb";
+
+// How the signed-in account can prove it still holds a credential
+// (CredentialProof in user_service.proto). The server enforces the same rule;
+// this only picks which input to render:
+// - a live MFA factor is proven with the factor (an OTP or a recovery code),
+// - else on Cloud, a one-time emailed code (Cloud accounts never have a
+// caller-chosen password, and only Cloud can send email),
+// - else the password — self-hosted has no email capability, so an account
+// that never had a password needs an admin reset before it can prove
+// anything (the server says so).
+export type CredentialProofMode = "factor" | "password" | "email";
+
+export function useCredentialProofMode(): CredentialProofMode {
+ const currentUser = useCurrentUser();
+ const saas = useAppStore((state) => state.serverInfo?.saas ?? false);
+ if (currentUser.mfaEnabled) return "factor";
+ if (saas) return "email";
+ return "password";
+}
+
+// A recovery code is longer than a 6-digit OTP and never purely numeric.
+function factorProofOf(value: string): CredentialProof {
+ if (/^\d{6}$/.test(value)) {
+ return create(CredentialProofSchema, {
+ proof: { case: "otpCode", value },
+ });
+ }
+ return create(CredentialProofSchema, {
+ proof: { case: "recoveryCode", value },
+ });
+}
+
+interface CredentialProofInputProps {
+ value: string;
+ onChange: (value: string) => void;
+}
+
+// credentialProofCallOptions marks a call that carries a CredentialProof: a
+// wrong proof answers Unauthenticated, which must reach the caller as a plain
+// error — not trigger the interceptor's refresh-and-retry, which would
+// re-submit the same wrong proof (burning a second lockout slot) and then
+// declare the whole session expired.
+export function credentialProofCallOptions() {
+ return {
+ contextValues: createContextValues().set(ignoredCodesContextKey, [
+ Code.Unauthenticated,
+ ]),
+ };
+}
+
+// isCredentialProofReady reports whether the input holds enough to submit.
+// A password is whatever the user typed, whitespace included — login compares
+// it verbatim, so an account whose password is spaces must still be able to
+// change it. The codes are transcribed, so their surrounding whitespace is a
+// paste artifact rather than content.
+export function isCredentialProofReady(
+ mode: CredentialProofMode,
+ value: string
+): boolean {
+ return mode === "password" ? value.length > 0 : value.trim().length > 0;
+}
+
+// buildCredentialProof turns the raw input value into the proof message for
+// the mode the account is in, or undefined while the input is empty.
+export function buildCredentialProof(
+ mode: CredentialProofMode,
+ value: string
+): CredentialProof | undefined {
+ if (!isCredentialProofReady(mode, value)) return undefined;
+ const trimmed = value.trim();
+ switch (mode) {
+ case "factor":
+ return factorProofOf(trimmed);
+ case "password":
+ return create(CredentialProofSchema, {
+ proof: { case: "currentPassword", value },
+ });
+ case "email":
+ return create(CredentialProofSchema, {
+ proof: { case: "emailCode", value: trimmed },
+ });
+ }
+}
+
+// CredentialProofInput renders the one input the account can answer with. The
+// email mode carries its own "email me a code" sender with a resend cooldown
+// matching the server's.
+export function CredentialProofInput({
+ value,
+ onChange,
+}: Readonly<CredentialProofInputProps>) {
+ const { t } = useTranslation();
+ // Only one mode's Input renders at a time, so a single id serves them all.
+ const inputId = useId();
+ const mode = useCredentialProofMode();
+ const currentUser = useCurrentUser();
+ const [sending, setSending] = useState(false);
+ const [resendCountdown, setResendCountdown] = useState(0);
+ const countdownRef = useRef<ReturnType<typeof setInterval> | null>(null);
+
+ useEffect(() => {
+ return () => {
+ if (countdownRef.current) clearInterval(countdownRef.current);
+ };
+ }, []);
+
+ const requestCode = useCallback(async () => {
+ setSending(true);
+ try {
+ await userServiceClientConnect.requestReauthCode(
+ create(RequestReauthCodeRequestSchema, { name: currentUser.name })
+ );
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t("credential-proof.code-sent"),
+ });
+ setResendCountdown(60);
+ countdownRef.current = setInterval(() => {
+ setResendCountdown((remaining) => {
+ if (remaining <= 1 && countdownRef.current) {
+ clearInterval(countdownRef.current);
+ countdownRef.current = null;
+ }
+ return Math.max(0, remaining - 1);
+ });
+ }, 1000);
+ } catch (error) {
+ pushNotification({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: (error as Error).message,
+ });
+ } finally {
+ setSending(false);
+ }
+ }, [currentUser.name, t]);
+
+ const label = useMemo(() => {
+ switch (mode) {
+ case "factor":
+ return t("credential-proof.factor-label");
+ case "password":
+ return t("credential-proof.password-label");
+ case "email":
+ return t("credential-proof.email-label");
+ }
+ }, [mode, t]);
+
+ return (
+ <FormField>
+ <FormLabel htmlFor={inputId}>
+ {label}
+ <span className="text-error">*</span>
+ </FormLabel>
+ {mode === "factor" && (
+ <Input
+ id={inputId}
+ value={value}
+ placeholder={t("credential-proof.factor-placeholder")}
+ autoComplete="one-time-code"
+ onChange={(e) => onChange(e.target.value)}
+ />
+ )}
+ {mode === "password" && (
+ <Input
+ id={inputId}
+ type="password"
+ value={value}
+ autoComplete="current-password"
+ onChange={(e) => onChange(e.target.value)}
+ />
+ )}
+ {mode === "email" && (
+ <FormControlRow>
+ <Input
+ id={inputId}
+ value={value}
+ placeholder={t("credential-proof.email-placeholder")}
+ autoComplete="one-time-code"
+ onChange={(e) => onChange(e.target.value)}
+ />
+ <Button
+ appearance="outline"
+ disabled={sending || resendCountdown > 0}
+ onClick={requestCode}
+ >
+ {resendCountdown > 0
+ ? t("credential-proof.resend-in", { seconds: resendCountdown })
+ : t("credential-proof.email-me-a-code")}
+ </Button>
+ </FormControlRow>
+ )}
+ </FormField>
+ );
+}
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index 17849c2cd9..7fac28f4a2 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -511,6 +511,16 @@
"new-database-name": "New database name",
"reserved-db-error": "{{databaseName}} is a reserved name"
},
+ "credential-proof": {
+ "code-sent": "Code sent — check your email",
+ "email-label": "Email verification code",
+ "email-me-a-code": "Email me a code",
+ "email-placeholder": "6-digit code",
+ "factor-label": "Verification code",
+ "factor-placeholder": "Authenticator code or recovery code",
+ "password-label": "Current password",
+ "resend-in": "Resend in {{seconds}}s"
+ },
"custom-approval": {
"approval-flow": {
"fallback-rules": "Fallback Rules",
@@ -3488,6 +3498,7 @@
},
"self": "Two-factor authentication",
"setup-steps": {
+ "confirm-code": "Enter a fresh code from your authenticator to finish",
"download-recovery-codes": {
"keep-safe": {
"description": "These codes are the last resort for accessing your account in case you lose your two-factor authentication code. If you cannot find these codes, you will lose access to your account.",
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index 2246559eec..453d3ed4e8 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -511,6 +511,16 @@
"new-database-name": "Nuevo nombre de la base de datos",
"reserved-db-error": "{{databaseName}} es un nombre reservado"
},
+ "credential-proof": {
+ "code-sent": "Código enviado; revisa tu correo",
+ "email-label": "Código de verificación por correo",
+ "email-me-a-code": "Enviarme un código por correo",
+ "email-placeholder": "Código de 6 dígitos",
+ "factor-label": "Código de verificación",
+ "factor-placeholder": "Código del autenticador o código de recuperación",
+ "password-label": "Contraseña actual",
+ "resend-in": "Reenviar en {{seconds}}s"
+ },
"custom-approval": {
"approval-flow": {
"fallback-rules": "Reglas de respaldo",
@@ -3488,6 +3498,7 @@
},
"self": "Autenticación de dos factores",
"setup-steps": {
+ "confirm-code": "Introduce un código nuevo de tu autenticador para finalizar",
"download-recovery-codes": {
"keep-safe": {
"description": "Estos códigos son el último recurso para acceder a su cuenta en caso de que pierda su código de autenticación de dos factores. Si no puede encontrar estos códigos, perderá el acceso a su cuenta.",
diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.json
index a4e0d4c6dc..855c4904b3 100644
--- a/frontend/src/locales/ja-JP.json
+++ b/frontend/src/locales/ja-JP.json
@@ -511,6 +511,16 @@
"new-database-name": "新しいデータベース名",
"reserved-db-error": "{{databaseName}} は予約された名前です"
},
+ "credential-proof": {
+ "code-sent": "コードを送信しました。メールをご確認ください",
+ "email-label": "メール確認コード",
+ "email-me-a-code": "コードをメールで送信",
+ "email-placeholder": "6 桁のコード",
+ "factor-label": "確認コード",
+ "factor-placeholder": "認証アプリのコードまたはリカバリーコード",
+ "password-label": "現在のパスワード",
+ "resend-in": "{{seconds}} 秒後に再送信できます"
+ },
"custom-approval": {
"approval-flow": {
"fallback-rules": "フォールバックルール",
@@ -3488,6 +3498,7 @@
},
"self": "二要素認証",
"setup-steps": {
+ "confirm-code": "認証アプリの最新のコードを入力して完了します",
"download-recovery-codes": {
"keep-safe": {
"description": "これらのコードは、2 要素認証コードを受信できない場合にアカウントにアクセスするために使用されます。これらのコードが見つからない場合は、アカウントにアクセスできなくなります。",
diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.json
index 718a1325c2..d7376ff3cf 100644
--- a/frontend/src/locales/vi-VN.json
+++ b/frontend/src/locales/vi-VN.json
@@ -511,6 +511,16 @@
"new-database-name": "Tên cơ sở dữ liệu mới",
"reserved-db-error": "{{databaseName}} là một tên dành riêng"
},
+ "credential-proof": {
+ "code-sent": "Đã gửi mã — kiểm tra email của bạn",
+ "email-label": "Mã xác minh qua email",
+ "email-me-a-code": "Gửi mã qua email",
+ "email-placeholder": "Mã 6 chữ số",
+ "factor-label": "Mã xác minh",
+ "factor-placeholder": "Mã ứng dụng xác thực hoặc mã khôi phục",
+ "password-label": "Mật khẩu hiện tại",
+ "resend-in": "Gửi lại sau {{seconds}} giây"
+ },
"custom-approval": {
"approval-flow": {
"fallback-rules": "Quy tắc dự phòng",
@@ -3488,6 +3498,7 @@
},
"self": "Xác thực hai yếu tố",
"setup-steps": {
+ "confirm-code": "Nhập mã mới từ ứng dụng xác thực để hoàn tất",
"download-recovery-codes": {
"keep-safe": {
"description": "Các mã này là phương sách cuối cùng để truy cập tài khoản của bạn trong trường hợp bạn mất mã xác thực hai yếu tố. Nếu bạn không thể tìm thấy các mã này, bạn sẽ mất quyền truy cập vào tài khoản của mình.",
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index 4fd75c9242..b510d5b153 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -511,6 +511,16 @@
"new-database-name": "新数据库名称",
"reserved-db-error": "{{databaseName}} 是一个预留名称"
},
+ "credential-proof": {
+ "code-sent": "验证码已发送,请查收邮件",
+ "email-label": "邮箱验证码",
+ "email-me-a-code": "发送验证码到邮箱",
+ "email-placeholder": "6 位数字验证码",
+ "factor-label": "验证码",
+ "factor-placeholder": "身份验证器代码或恢复代码",
+ "password-label": "当前密码",
+ "resend-in": "{{seconds}} 秒后可重新发送"
+ },
"custom-approval": {
"approval-flow": {
"fallback-rules": "兜底规则",
@@ -3488,6 +3498,7 @@
},
"self": "双重认证",
"setup-steps": {
+ "confirm-code": "输入身份验证器中的最新代码以完成设置",
"download-recovery-codes": {
"keep-safe": {
"description": "这些代码是在您无法收到双重认证代码的情况下访问您的账户。如果您找不到这些代码,您将失去对您账户的访问。",
diff --git a/frontend/src/routes/auth/PasswordResetPage.test.tsx b/frontend/src/routes/auth/PasswordResetPage.test.tsx
index da3c81eaee..b37dd8dbaa 100644
--- a/frontend/src/routes/auth/PasswordResetPage.test.tsx
+++ b/frontend/src/routes/auth/PasswordResetPage.test.tsx
@@ -238,8 +238,12 @@ describe("PasswordResetPage", () => {
const passwordInputs = container.querySelectorAll<HTMLInputElement>(
'input[type="password"]'
);
- setInputValue(passwordInputs[0], "Passw0rd!");
+ // A matching new password is not enough on its own: the forced reset is a
+ // credential change, so it proves the current password too.
setInputValue(passwordInputs[1], "Passw0rd!");
+ setInputValue(passwordInputs[2], "Passw0rd!");
+ expect(confirmBtn?.disabled).toBe(true);
+ setInputValue(passwordInputs[0], "0ldPassw0rd!");
expect(confirmBtn?.disabled).toBe(false);
unmount();
});
@@ -257,8 +261,9 @@ describe("PasswordResetPage", () => {
const passwordInputs = container.querySelectorAll<HTMLInputElement>(
'input[type="password"]'
);
- setInputValue(passwordInputs[0], "Passw0rd!");
+ setInputValue(passwordInputs[0], "0ldPassw0rd!");
setInputValue(passwordInputs[1], "Passw0rd!");
+ setInputValue(passwordInputs[2], "Passw0rd!");
const confirmBtn = Array.from(
container.querySelectorAll<HTMLButtonElement>("button")
).find((b) => b.textContent === "common.confirm")!;
@@ -268,7 +273,15 @@ describe("PasswordResetPage", () => {
await flushPromises();
expect(mocks.changePassword).toHaveBeenCalledWith(
- expect.objectContaining({ name: "users/1", newPassword: "Passw0rd!" })
+ expect.objectContaining({
+ name: "users/1",
+ newPassword: "Passw0rd!",
+ // The proof travels with the change; without it the server refuses.
+ credential: expect.objectContaining({
+ proof: { case: "currentPassword", value: "0ldPassw0rd!" },
+ }),
+ }),
+ expect.anything()
);
expect(mocks.updateUser).not.toHaveBeenCalled();
// The response is adopted rather than refetched, so the shared user the
diff --git a/frontend/src/routes/auth/PasswordResetPage.tsx b/frontend/src/routes/auth/PasswordResetPage.tsx
index d9cdee2b52..eba8d70ee4 100644
--- a/frontend/src/routes/auth/PasswordResetPage.tsx
+++ b/frontend/src/routes/auth/PasswordResetPage.tsx
@@ -1,5 +1,6 @@
import { create } from "@bufbuild/protobuf";
-import { useEffect, useRef, useState } from "react";
+import type { ConnectError } from "@connectrpc/connect";
+import { useEffect, useId, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { authServiceClientConnect, userServiceClientConnect } from "@/api";
import { router } from "@/app/router";
@@ -8,6 +9,7 @@ import logoFull from "@/assets/logo-full.svg";
import { AuthDivider } from "@/components/auth/AuthDivider";
import { UserPasswordFields } from "@/components/auth/UserPasswordFields";
import { computePasswordValidation } from "@/components/auth/userPasswordValidation";
+import { credentialProofCallOptions } from "@/components/CredentialProofInput";
import { RouterLink } from "@/components/RouterLink";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
@@ -20,12 +22,17 @@ import {
LoginRequestSchema,
ResetPasswordRequestSchema,
} from "@/types/proto-es/v1/auth_service_pb";
-import { ChangePasswordRequestSchema } from "@/types/proto-es/v1/user_service_pb";
+import {
+ ChangePasswordRequestSchema,
+ CredentialProofSchema,
+} from "@/types/proto-es/v1/user_service_pb";
export function PasswordResetPage() {
const { t } = useTranslation();
const [email, setEmail] = useState("");
const [codeParts, setCodeParts] = useState<string[]>([]);
+ const [currentPassword, setCurrentPassword] = useState("");
+ const currentPasswordId = useId();
const [password, setPassword] = useState("");
const [passwordConfirm, setPasswordConfirm] = useState("");
const [resendCountdown, setResendCountdown] = useState(60);
@@ -98,6 +105,7 @@ export function PasswordResetPage() {
const allowConfirm = (() => {
if (!password) return false;
if (codeMode && (!email || codeParts.join("").length !== 6)) return false;
+ if (!codeMode && !currentPassword) return false;
return !validation.hint && !validation.mismatch;
})();
@@ -150,15 +158,31 @@ export function PasswordResetPage() {
return;
}
- // Forced-reset mode
+ // Forced-reset mode: the caller just signed in with their password, so
+ // the current password is the proof ChangePassword requires.
if (!currentUser) return;
- const updated = await userServiceClientConnect.changePassword(
- create(ChangePasswordRequestSchema, {
- name: currentUser.name,
- newPassword: password,
- })
- );
- useAppStore.getState().setCurrentUser(updated);
+ try {
+ const updated = await userServiceClientConnect.changePassword(
+ create(ChangePasswordRequestSchema, {
+ name: currentUser.name,
+ newPassword: password,
+ credential: create(CredentialProofSchema, {
+ proof: { case: "currentPassword", value: currentPassword },
+ }),
+ }),
+ credentialProofCallOptions()
+ );
+ // Adopt what the mutation answered with rather than refetching: the
+ // guard that stranded this user on this page reads the shared store.
+ useAppStore.getState().setCurrentUser(updated);
+ } catch (error) {
+ pushNotification({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: (error as ConnectError).message,
+ });
+ return;
+ }
pushNotification({
module: "bytebase",
style: "SUCCESS",
@@ -224,6 +248,27 @@ export function PasswordResetPage() {
</>
)}
+ {!codeMode && (
+ <div>
+ <label
+ htmlFor={currentPasswordId}
+ className="block text-sm font-medium leading-5 text-control"
+ >
+ {t("credential-proof.password-label")}
+ <span className="text-error ml-0.5">*</span>
+ </label>
+ <Input
+ id={currentPasswordId}
+ className="mt-1"
+ type="password"
+ autoComplete="current-password"
+ value={currentPassword}
+ required
+ onChange={(e) => setCurrentPassword(e.target.value)}
+ />
+ </div>
+ )}
+
<UserPasswordFields
password={password}
passwordConfirm={passwordConfirm}
diff --git a/frontend/src/routes/workspace/profile/AccountSettingsPage.tsx b/frontend/src/routes/workspace/profile/AccountSettingsPage.tsx
index 28f6e66fd1..2df24a4425 100644
--- a/frontend/src/routes/workspace/profile/AccountSettingsPage.tsx
+++ b/frontend/src/routes/workspace/profile/AccountSettingsPage.tsx
@@ -7,6 +7,13 @@ import { useTranslation } from "react-i18next";
import { userServiceClientConnect } from "@/api";
import { router } from "@/app/router";
import { ACCOUNT_ROUTE_TWO_FACTOR } from "@/app/router/handles";
+import {
+ buildCredentialProof,
+ CredentialProofInput,
+ credentialProofCallOptions,
+ isCredentialProofReady,
+ useCredentialProofMode,
+} from "@/components/CredentialProofInput";
import { FeatureBadge } from "@/components/FeatureBadge";
import { LearnMoreLink } from "@/components/LearnMoreLink";
import { getAvatarColor, getInitials } from "@/components/UserAvatar";
@@ -61,6 +68,14 @@ export function AccountSettingsPage() {
(s) => s.getWorkspaceProfile().passwordRestriction
);
const requireMfa = useAppStore((s) => s.getWorkspaceProfile().requireMfa);
+ // ChangePassword refuses when password sign-in is disallowed, and SaaS
+ // forces that on regardless of the stored setting (getAccountRestriction),
+ // so both are consulted — otherwise Cloud shows a button that always fails.
+ const passwordSigninAvailable = useAppStore(
+ (s) =>
+ !(s.serverInfo?.saas ?? false) &&
+ !s.getWorkspaceProfile().disallowPasswordSignin
+ );
const has2FAFeature = useAppStore((s) =>
s.hasFeature(PlanFeature.FEATURE_TWO_FA)
);
@@ -79,13 +94,16 @@ export function AccountSettingsPage() {
// --- Password section ---
const [password, setPassword] = useState("");
const [passwordConfirm, setPasswordConfirm] = useState("");
+ const [passwordProofValue, setPasswordProofValue] = useState("");
const [savingPassword, setSavingPassword] = useState(false);
+ const proofMode = useCredentialProofMode();
// --- Password + 2FA dialogs ---
const [showChangePassword, setShowChangePassword] = useState(false);
const [showFeatureModal, setShowFeatureModal] = useState(false);
const [showDisable2FAConfirm, setShowDisable2FAConfirm] = useState(false);
const [showRegenerateView, setShowRegenerateView] = useState(false);
+ const [disable2FAProofValue, setDisable2FAProofValue] = useState("");
const [disabling2FA, setDisabling2FA] = useState(false);
useEffect(() => {
@@ -111,6 +129,7 @@ export function AccountSettingsPage() {
);
const allowSavePassword =
password.length > 0 &&
+ isCredentialProofReady(proofMode, passwordProofValue) &&
!passwordErrors.hasHint &&
!passwordErrors.hasMismatch;
@@ -170,11 +189,14 @@ export function AccountSettingsPage() {
create(ChangePasswordRequestSchema, {
name: user.name,
newPassword: password,
- })
+ credential: buildCredentialProof(proofMode, passwordProofValue),
+ }),
+ credentialProofCallOptions()
);
setCurrentUser(updated);
setPassword("");
setPasswordConfirm("");
+ setPasswordProofValue("");
setShowChangePassword(false);
notifyUpdated();
} catch (error) {
@@ -182,7 +204,15 @@ export function AccountSettingsPage() {
} finally {
setSavingPassword(false);
}
- }, [allowSavePassword, password, user.name, notifyUpdated, notifyError]);
+ }, [
+ allowSavePassword,
+ password,
+ passwordProofValue,
+ proofMode,
+ user.name,
+ notifyUpdated,
+ notifyError,
+ ]);
const handleEnable2FA = useCallback(() => {
if (!has2FAFeature) {
@@ -210,8 +240,15 @@ export function AccountSettingsPage() {
if (disabling2FA) return;
setDisabling2FA(true);
try {
+ // Turning the factor off is proven with the factor itself — an OTP or
+ // a recovery code — never the password, which a mailbox reset could
+ // have minted (docs/design/reauthenticate-credential-changes.md).
const updated = await userServiceClientConnect.disableMFA(
- create(DisableMFARequestSchema, { name: user.name })
+ create(DisableMFARequestSchema, {
+ name: user.name,
+ credential: buildCredentialProof("factor", disable2FAProofValue),
+ }),
+ credentialProofCallOptions()
);
setCurrentUser(updated);
// The router guard reads mfa_enabled off the shared store, not this
@@ -221,6 +258,7 @@ export function AccountSettingsPage() {
useAppStore.getState().setCurrentUser(updated);
setShowDisable2FAConfirm(false);
setShowRegenerateView(false);
+ setDisable2FAProofValue("");
pushNotification({
module: "bytebase",
style: "SUCCESS",
@@ -231,7 +269,7 @@ export function AccountSettingsPage() {
} finally {
setDisabling2FA(false);
}
- }, [disabling2FA, user.name, notifyError, t]);
+ }, [disabling2FA, user.name, disable2FAProofValue, notifyError, t]);
return (
<WorkspacePageLayout>
@@ -314,17 +352,19 @@ export function AccountSettingsPage() {
{t("settings.account.security")}
</h2>
<SettingsCard>
- <SettingsRow
- label={t("settings.profile.password")}
- description={t("settings.account.password-notice")}
- >
- <Button
- appearance="outline"
- onClick={() => setShowChangePassword(true)}
+ {passwordSigninAvailable && (
+ <SettingsRow
+ label={t("settings.profile.password")}
+ description={t("settings.account.password-notice")}
>
- {t("settings.account.update-password")}
- </Button>
- </SettingsRow>
+ <Button
+ appearance="outline"
+ onClick={() => setShowChangePassword(true)}
+ >
+ {t("settings.account.update-password")}
+ </Button>
+ </SettingsRow>
+ )}
<SettingsRow
align="start"
@@ -413,6 +453,7 @@ export function AccountSettingsPage() {
if (!next) {
setPassword("");
setPasswordConfirm("");
+ setPasswordProofValue("");
}
}}
>
@@ -421,7 +462,11 @@ export function AccountSettingsPage() {
<DialogDescription>
{t("settings.account.password-notice")}
</DialogDescription>
- <div className="mt-4">
+ <div className="mt-4 flex flex-col gap-y-4">
+ <CredentialProofInput
+ value={passwordProofValue}
+ onChange={setPasswordProofValue}
+ />
<UserPasswordSection
password={password}
passwordConfirm={passwordConfirm}
@@ -459,6 +504,12 @@ export function AccountSettingsPage() {
<DialogDescription>
{t("two-factor.disable.description")}
</DialogDescription>
+ <div className="mt-4">
+ <CredentialProofInput
+ value={disable2FAProofValue}
+ onChange={setDisable2FAProofValue}
+ />
+ </div>
<div className="mt-4 flex justify-end gap-x-2">
<Button
appearance="outline"
@@ -468,7 +519,10 @@ export function AccountSettingsPage() {
</Button>
<Button
variant="destructive"
- disabled={disabling2FA}
+ disabled={
+ disabling2FA ||
+ !isCredentialProofReady("factor", disable2FAProofValue)
+ }
onClick={handleDisable2FA}
>
{t("common.disable")}
diff --git a/frontend/src/routes/workspace/two-factor/RegenerateRecoveryCodesView.tsx b/frontend/src/routes/workspace/two-factor/RegenerateRecoveryCodesView.tsx
index 152244c084..5fe01ba260 100644
--- a/frontend/src/routes/workspace/two-factor/RegenerateRecoveryCodesView.tsx
+++ b/frontend/src/routes/workspace/two-factor/RegenerateRecoveryCodesView.tsx
@@ -1,11 +1,18 @@
import { create } from "@bufbuild/protobuf";
-import type { Timestamp } from "@bufbuild/protobuf/wkt";
+import type { ConnectError } from "@connectrpc/connect";
import { useCallback, useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { userServiceClientConnect } from "@/api";
+import {
+ buildCredentialProof,
+ CredentialProofInput,
+ credentialProofCallOptions,
+ isCredentialProofReady,
+} from "@/components/CredentialProofInput";
import { Button } from "@/components/ui/button";
import { useCurrentUser } from "@/hooks/useAppState";
import { pushNotification } from "@/stores";
+import type { RegenerateRecoveryCodesResponse } from "@/types/proto-es/v1/user_service_pb";
import {
ConfirmRecoveryCodesRequestSchema,
RegenerateRecoveryCodesRequestSchema,
@@ -16,14 +23,21 @@ interface RegenerateRecoveryCodesViewProps {
onClose: () => void;
}
+// Mint-then-confirm: RegenerateRecoveryCodes returns a pending set (the old
+// codes keep working), and ConfirmRecoveryCodes promotes exactly that set —
+// proven with the live factor, since promotion is the moment the old codes
+// stop working (docs/design/reauthenticate-credential-changes.md).
export function RegenerateRecoveryCodesView({
onClose,
}: RegenerateRecoveryCodesViewProps) {
const { t } = useTranslation();
const currentUser = useCurrentUser();
- const [recoveryCodes, setRecoveryCodes] = useState<string[]>([]);
- const [pendingVersion, setPendingVersion] = useState<Timestamp | undefined>();
+ const [pending, setPending] = useState<
+ RegenerateRecoveryCodesResponse | undefined
+ >(undefined);
const [recoveryCodesDownloaded, setRecoveryCodesDownloaded] = useState(false);
+ const [proofValue, setProofValue] = useState("");
+ const [submitting, setSubmitting] = useState(false);
// The codes exist only in the minting response, so this view fetches its own
// rather than reading them off the user. The live set keeps working until
@@ -33,42 +47,68 @@ export function RegenerateRecoveryCodesView({
.regenerateRecoveryCodes(
create(RegenerateRecoveryCodesRequestSchema, { name: currentUser.name })
)
- .then((response) => {
- setRecoveryCodes([...response.recoveryCodes]);
- setPendingVersion(response.pendingVersion);
+ .then(setPending)
+ .catch((error) => {
+ pushNotification({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: (error as ConnectError).message,
+ });
});
}, [currentUser.name]);
const confirmRecoveryCodes = useCallback(async () => {
+ if (!pending || submitting) return;
+ setSubmitting(true);
// Confirm the set this view minted and displayed, never whatever is
// pending now: an enrollment started in another tab would otherwise be
// promoted here, swapping the factor along with it.
- await userServiceClientConnect.confirmRecoveryCodes(
- create(ConfirmRecoveryCodesRequestSchema, {
- name: currentUser.name,
- pendingVersion,
- })
- );
+ try {
+ await userServiceClientConnect.confirmRecoveryCodes(
+ create(ConfirmRecoveryCodesRequestSchema, {
+ name: currentUser.name,
+ credential: buildCredentialProof("factor", proofValue),
+ pendingVersion: pending.pendingVersion,
+ }),
+ credentialProofCallOptions()
+ );
+ } catch (error) {
+ pushNotification({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: (error as ConnectError).message,
+ });
+ setSubmitting(false);
+ return;
+ }
pushNotification({
module: "bytebase",
style: "SUCCESS",
title: t("two-factor.messages.recovery-codes-regenerated"),
});
onClose();
- }, [currentUser.name, onClose, pendingVersion, t]);
+ }, [pending, submitting, currentUser.name, proofValue, onClose, t]);
return (
<>
<RecoveryCodesView
- recoveryCodes={recoveryCodes}
+ recoveryCodes={pending ? [...pending.recoveryCodes] : []}
onDownload={() => setRecoveryCodesDownloaded(true)}
/>
+ <div className="max-w-sm mb-4">
+ <CredentialProofInput value={proofValue} onChange={setProofValue} />
+ </div>
<div className="flex flex-row justify-between items-center mb-8">
<Button appearance="outline" onClick={onClose}>
{t("common.cancel")}
</Button>
<Button
- disabled={!recoveryCodesDownloaded}
+ disabled={
+ !recoveryCodesDownloaded ||
+ !isCredentialProofReady("factor", proofValue) ||
+ !pending ||
+ submitting
+ }
onClick={confirmRecoveryCodes}
>
{t("two-factor.setup-steps.recovery-codes-saved")}
diff --git a/frontend/src/routes/workspace/two-factor/TwoFactorSetupPage.test.tsx b/frontend/src/routes/workspace/two-factor/TwoFactorSetupPage.test.tsx
index 69d35e94bc..33ef5f5e23 100644
--- a/frontend/src/routes/workspace/two-factor/TwoFactorSetupPage.test.tsx
+++ b/frontend/src/routes/workspace/two-factor/TwoFactorSetupPage.test.tsx
@@ -7,20 +7,26 @@ import { beforeEach, describe, expect, test, vi } from "vitest";
globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
).IS_REACT_ACT_ENVIRONMENT = true;
-const expireTimestamp = () => ({
- seconds: BigInt(Math.floor(Date.now() / 1000) + 300),
+const currentTimestamp = () => ({
+ seconds: BigInt(Math.floor(Date.now() / 1000)),
nanos: 0,
});
const currentUser = {
name: "users/[email protected]",
+ mfaEnabled: false,
+ profile: { lastChangePasswordTime: currentTimestamp() },
};
const mintedEnrollment = {
otpSecret: "new-secret",
recoveryCodes: ["code-1", "code-2"],
- expireTime: expireTimestamp(),
+ expireTime: {
+ seconds: BigInt(Math.floor(Date.now() / 1000) + 300),
+ nanos: 0,
+ },
+ pendingVersion: currentTimestamp(),
};
const mocks = vi.hoisted(() => ({
@@ -38,19 +44,22 @@ vi.mock("@/hooks/useAppState", () => ({
useCurrentUser: mocks.useCurrentUser,
}));
+vi.mock("@/api", () => ({
+ userServiceClientConnect: {
+ startMFAEnrollment: mocks.startMFAEnrollment,
+ enableMFA: vi.fn(),
+ confirmRecoveryCodes: vi.fn(),
+ },
+}));
+
vi.mock("@/stores/app", () => ({
useAppStore: (selector: (state: unknown) => unknown) =>
selector({
setCurrentUser: mocks.setCurrentUser,
+ serverInfo: { saas: false },
}),
}));
-vi.mock("@/api", () => ({
- userServiceClientConnect: {
- startMFAEnrollment: mocks.startMFAEnrollment,
- },
-}));
-
vi.mock("@/stores", () => ({
pushNotification: mocks.pushNotification,
}));
@@ -81,6 +90,7 @@ vi.mock("@/types/proto-es/v1/user_service_pb", async (importOriginal) => {
StartMFAEnrollmentRequestSchema: {},
EnableMFARequestSchema: {},
ConfirmRecoveryCodesRequestSchema: {},
+ CredentialProofSchema: {},
};
});
@@ -116,6 +126,14 @@ vi.mock("@/components/ui/otp-input", () => ({
OtpInput: () => <div data-testid="otp-input" />,
}));
+vi.mock("@/components/CredentialProofInput", async (importOriginal) => ({
+ ...(await importOriginal<
+ typeof import("@/components/CredentialProofInput")
+ >()),
+ CredentialProofInput: () => <div data-testid="credential-proof" />,
+ useCredentialProofMode: () => "password" as const,
+}));
+
vi.mock("./RecoveryCodesView", () => ({
RecoveryCodesView: () => <div data-testid="recovery-codes" />,
}));
@@ -172,6 +190,10 @@ describe("TwoFactorSetupPage", () => {
.querySelector('[data-testid="secret-modal"]')
?.getAttribute("data-secret")
).toBe("new-secret");
+ // An account with a password proves it before the swap.
+ expect(
+ container.querySelector('[data-testid="credential-proof"]')
+ ).not.toBeNull();
unmount();
});
diff --git a/frontend/src/routes/workspace/two-factor/TwoFactorSetupPage.tsx b/frontend/src/routes/workspace/two-factor/TwoFactorSetupPage.tsx
index bd9bbac7b5..dfed404509 100644
--- a/frontend/src/routes/workspace/two-factor/TwoFactorSetupPage.tsx
+++ b/frontend/src/routes/workspace/two-factor/TwoFactorSetupPage.tsx
@@ -1,5 +1,4 @@
import { create } from "@bufbuild/protobuf";
-import type { Timestamp } from "@bufbuild/protobuf/wkt";
import type { ConnectError } from "@connectrpc/connect";
import { QRCodeSVG } from "qrcode.react";
import { useCallback, useEffect, useRef, useState } from "react";
@@ -7,6 +6,13 @@ import { useTranslation } from "react-i18next";
import { userServiceClientConnect } from "@/api";
import { router } from "@/app/router";
import { ACCOUNT_ROUTE, AUTH_2FA_SETUP_MODULE } from "@/app/router/handles";
+import {
+ buildCredentialProof,
+ CredentialProofInput,
+ credentialProofCallOptions,
+ isCredentialProofReady,
+ useCredentialProofMode,
+} from "@/components/CredentialProofInput";
import { LearnMoreLink } from "@/components/LearnMoreLink";
import { Button } from "@/components/ui/button";
import { OtpInput } from "@/components/ui/otp-input";
@@ -14,6 +20,10 @@ import { StepIndicator } from "@/components/ui/step-indicator";
import { useCurrentUser } from "@/hooks/useAppState";
import { pushNotification } from "@/stores";
import { useAppStore } from "@/stores/app";
+import type {
+ StartMFAEnrollmentResponse,
+ User,
+} from "@/types/proto-es/v1/user_service_pb";
import {
ConfirmRecoveryCodesRequestSchema,
EnableMFARequestSchema,
@@ -25,18 +35,6 @@ import { TwoFactorSecretModal } from "./TwoFactorSecretModal";
const ISSUER_NAME = "Bytebase";
const DIGITS = 6;
-// What StartMFAEnrollment handed back. Nothing here is on the User resource:
-// the secret and the codes exist only in that response, and the expiry is the
-// server's, not a duration this page assumes.
-interface Enrollment {
- otpSecret: string;
- recoveryCodes: string[];
- expireTime: Timestamp | undefined;
- // Identifies this mint. Confirming with it is what keeps a mint from
- // another tab from being promoted in place of the one on screen.
- pendingVersion: Timestamp | undefined;
-}
-
const SETUP_AUTH_APP_STEP = 0;
const DOWNLOAD_RECOVERY_CODES_STEP = 1;
type Step = typeof SETUP_AUTH_APP_STEP | typeof DOWNLOAD_RECOVERY_CODES_STEP;
@@ -45,16 +43,32 @@ interface TwoFactorSetupPageProps {
cancelAction?: () => void;
}
+// The split enrollment (docs/design/reauthenticate-credential-changes.md):
+// StartMFAEnrollment mints the pending secret and recovery codes — the only
+// response that ever carries them — EnableMFA verifies the new device (and,
+// for a rotation, promotes the secret), and ConfirmRecoveryCodes promotes the
+// rest once the user confirms they saved the codes. Every step that changes
+// live credential material carries a CredentialProof.
export function TwoFactorSetupPage({ cancelAction }: TwoFactorSetupPageProps) {
const { t } = useTranslation();
const currentUser = useCurrentUser();
const setCurrentUser = useAppStore((state) => state.setCurrentUser);
- const [enrollment, setEnrollment] = useState<Enrollment | undefined>();
+ const proofMode = useCredentialProofMode();
+ // Captured at mount: EnableMFA flips mfaEnabled mid-flow on a rotation, and
+ // the confirm step's request shape depends on which flow this is.
+ const [rotation] = useState(currentUser.mfaEnabled);
+ const [enrollment, setEnrollment] = useState<
+ StartMFAEnrollmentResponse | undefined
+ >(undefined);
const [currentStep, setCurrentStep] = useState<Step>(SETUP_AUTH_APP_STEP);
const [showSecretModal, setShowSecretModal] = useState(false);
const [otpCodes, setOtpCodes] = useState<string[]>([]);
+ const [proofValue, setProofValue] = useState("");
+ const [confirmOtpCodes, setConfirmOtpCodes] = useState<string[]>([]);
+ const [confirmProofValue, setConfirmProofValue] = useState("");
const [recoveryCodesDownloaded, setRecoveryCodesDownloaded] = useState(false);
+ const [submitting, setSubmitting] = useState(false);
const [timeRemaining, setTimeRemaining] = useState("5:00");
const [isExpired, setIsExpired] = useState(false);
const [isExpiringSoon, setIsExpiringSoon] = useState(false);
@@ -64,6 +78,11 @@ export function TwoFactorSetupPage({ cancelAction }: TwoFactorSetupPageProps) {
const enrollmentRef = useRef(enrollment);
enrollmentRef.current = enrollment;
+ // EnableMFA needs no proof at all for a first-time enrollment on an account
+ // whose only possible proof is a single-use emailed code — that code is
+ // spent once, at the confirm step, where the mutation actually happens.
+ const needProofAtEnable = proofMode !== "email";
+
const stopCountdown = useCallback(() => {
if (countdownRef.current) {
clearInterval(countdownRef.current);
@@ -105,12 +124,7 @@ export function TwoFactorSetupPage({ cancelAction }: TwoFactorSetupPageProps) {
const response = await userServiceClientConnect.startMFAEnrollment(
create(StartMFAEnrollmentRequestSchema, { name: currentUser.name })
);
- setEnrollment({
- otpSecret: response.otpSecret,
- recoveryCodes: [...response.recoveryCodes],
- expireTime: response.expireTime,
- pendingVersion: response.pendingVersion,
- });
+ setEnrollment(response);
}, [currentUser.name]);
// On mount: mint an enrollment and start counting down to its expiry
@@ -123,46 +137,64 @@ export function TwoFactorSetupPage({ cancelAction }: TwoFactorSetupPageProps) {
const otpauthUrl = `otpauth://totp/${ISSUER_NAME}:${currentUser.email}?algorithm=SHA1&digits=${DIGITS}&issuer=${ISSUER_NAME}&period=30&secret=${enrollment?.otpSecret ?? ""}`;
- const verifyOTPCode = useCallback(
+ const notifyError = useCallback((error: unknown) => {
+ pushNotification({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: (error as ConnectError).message,
+ });
+ }, []);
+
+ const verifyNewDevice = useCallback(
async (codes: string[]) => {
+ if (!enrollment) return false;
try {
await userServiceClientConnect.enableMFA(
create(EnableMFARequestSchema, {
name: currentUser.name,
otpCode: codes.join(""),
- pendingVersion: enrollment?.pendingVersion,
- })
+ credential: needProofAtEnable
+ ? buildCredentialProof(proofMode, proofValue)
+ : undefined,
+ pendingVersion: enrollment.pendingVersion,
+ }),
+ credentialProofCallOptions()
);
} catch (error) {
- pushNotification({
- module: "bytebase",
- style: "CRITICAL",
- title: (error as ConnectError).message,
- });
+ notifyError(error);
return false;
}
return true;
},
- [currentUser.name, enrollment?.pendingVersion]
+ [
+ enrollment,
+ currentUser.name,
+ needProofAtEnable,
+ proofMode,
+ proofValue,
+ notifyError,
+ ]
);
const handleOtpFinish = useCallback(
async (value: string[]) => {
setOtpCodes(value);
- const result = await verifyOTPCode(value);
+ if (needProofAtEnable && !isCredentialProofReady(proofMode, proofValue))
+ return;
+ const result = await verifyNewDevice(value);
if (result && currentStep === SETUP_AUTH_APP_STEP) {
setCurrentStep(DOWNLOAD_RECOVERY_CODES_STEP);
}
},
- [verifyOTPCode, currentStep]
+ [verifyNewDevice, currentStep, needProofAtEnable, proofValue]
);
const handleNext = useCallback(async () => {
- const result = await verifyOTPCode(otpCodes);
+ const result = await verifyNewDevice(otpCodes);
if (result) {
setCurrentStep(DOWNLOAD_RECOVERY_CODES_STEP);
}
- }, [verifyOTPCode, otpCodes]);
+ }, [verifyNewDevice, otpCodes]);
const handleBack = useCallback(() => {
setOtpCodes([]);
@@ -186,14 +218,46 @@ export function TwoFactorSetupPage({ cancelAction }: TwoFactorSetupPageProps) {
}, [cancelAction]);
const tryFinishSetup = useCallback(async () => {
- // Confirming the codes is what makes the factor live: the secret and the
- // codes that recover it start existing in the same write.
- const enabled = await userServiceClientConnect.confirmRecoveryCodes(
- create(ConfirmRecoveryCodesRequestSchema, {
- name: currentUser.name,
- pendingVersion: enrollment?.pendingVersion,
- })
- );
+ if (!enrollment || submitting) return;
+ setSubmitting(true);
+ let enabled: User;
+ try {
+ const freshOtp = confirmOtpCodes.join("");
+ if (rotation) {
+ // Promotion happens here, so the proof binds here — and it is the
+ // factor being replaced, which is still the live one: EnableMFA
+ // verified the new device without promoting it. A fresh code, since
+ // the one spent at the previous step has aged out of its window.
+ enabled = await userServiceClientConnect.confirmRecoveryCodes(
+ create(ConfirmRecoveryCodesRequestSchema, {
+ name: currentUser.name,
+ credential: buildCredentialProof("factor", confirmProofValue),
+ pendingVersion: enrollment.pendingVersion,
+ }),
+ credentialProofCallOptions()
+ );
+ } else {
+ // First-time enrollment: nothing is live until here. The fresh code
+ // proves the device once more, and the credential proves the account
+ // — the password held from the previous step, or the emailed code.
+ enabled = await userServiceClientConnect.confirmRecoveryCodes(
+ create(ConfirmRecoveryCodesRequestSchema, {
+ name: currentUser.name,
+ otpCode: freshOtp,
+ credential: buildCredentialProof(
+ proofMode,
+ proofMode === "email" ? confirmProofValue : proofValue
+ ),
+ pendingVersion: enrollment.pendingVersion,
+ }),
+ credentialProofCallOptions()
+ );
+ }
+ } catch (error) {
+ notifyError(error);
+ setSubmitting(false);
+ return;
+ }
// Adopt the response rather than refetching. The navigation below runs
// through the router guard, which sends an account without a live factor
// back here; a refetch that failed would leave the store saying exactly
@@ -210,12 +274,35 @@ export function TwoFactorSetupPage({ cancelAction }: TwoFactorSetupPageProps) {
} else {
router.replace({ name: ACCOUNT_ROUTE });
}
- }, [currentUser.name, enrollment?.pendingVersion, setCurrentUser, t]);
+ }, [
+ enrollment,
+ submitting,
+ rotation,
+ currentUser.name,
+ proofMode,
+ proofValue,
+ confirmProofValue,
+ confirmOtpCodes,
+ setCurrentUser,
+ notifyError,
+ t,
+ ]);
+ // Rotation proves the live factor here; a first-time enrollment re-proves
+ // the new device with a fresh code, plus the emailed code when that is the
+ // only proof the account has.
+ const confirmNeedsEmailProof = !rotation && proofMode === "email";
+ const confirmStepReady = rotation
+ ? isCredentialProofReady("factor", confirmProofValue)
+ : confirmOtpCodes.filter(Boolean).length === DIGITS &&
+ (!confirmNeedsEmailProof ||
+ isCredentialProofReady("email", confirmProofValue));
const allowNext =
currentStep === SETUP_AUTH_APP_STEP
- ? otpCodes.filter((v) => v).length === DIGITS && !isExpired
- : recoveryCodesDownloaded;
+ ? otpCodes.filter(Boolean).length === DIGITS &&
+ !isExpired &&
+ (!needProofAtEnable || isCredentialProofReady(proofMode, proofValue))
+ : recoveryCodesDownloaded && confirmStepReady;
const steps = [
{ title: t("two-factor.setup-steps.setup-auth-app.self") },
@@ -265,13 +352,9 @@ export function TwoFactorSetupPage({ cancelAction }: TwoFactorSetupPageProps) {
})}
</p>
{isExpired && (
- <button
- type="button"
- className="ml-3 px-3 py-1 text-sm font-medium text-white bg-blue-600 rounded-sm hover:bg-blue-700"
- onClick={handleRegenerateSecret}
- >
+ <Button size="sm" onClick={handleRegenerateSecret}>
{t("two-factor.setup-steps.setup-auth-app.regenerate")}
- </button>
+ </Button>
)}
</div>
</div>
@@ -306,7 +389,7 @@ export function TwoFactorSetupPage({ cancelAction }: TwoFactorSetupPageProps) {
);
})()}
</p>
- <div className="w-full flex flex-col justify-center items-center pb-8">
+ <div className="w-full flex flex-col justify-center items-center pb-4">
<QRCodeSVG value={otpauthUrl} size={150} />
<span className="mt-4 mb-2 text-sm font-medium">
{t("two-factor.setup-steps.setup-auth-app.verify-code")}
@@ -318,15 +401,50 @@ export function TwoFactorSetupPage({ cancelAction }: TwoFactorSetupPageProps) {
length={DIGITS}
/>
</div>
+ {needProofAtEnable && (
+ <div className="w-full max-w-sm mx-auto">
+ <CredentialProofInput
+ value={proofValue}
+ onChange={setProofValue}
+ />
+ </div>
+ )}
</div>
)}
{currentStep === DOWNLOAD_RECOVERY_CODES_STEP && (
- <div className="w-full max-w-2xl mx-auto">
+ <div className="w-full max-w-2xl mx-auto flex flex-col gap-y-6">
<RecoveryCodesView
- recoveryCodes={enrollment?.recoveryCodes ?? []}
+ recoveryCodes={enrollment ? [...enrollment.recoveryCodes] : []}
onDownload={() => setRecoveryCodesDownloaded(true)}
/>
+ {rotation ? (
+ <div className="w-full max-w-sm mx-auto">
+ <CredentialProofInput
+ value={confirmProofValue}
+ onChange={setConfirmProofValue}
+ />
+ </div>
+ ) : (
+ <div className="w-full flex flex-col justify-center items-center gap-y-2">
+ <span className="text-sm font-medium">
+ {t("two-factor.setup-steps.confirm-code")}
+ </span>
+ <OtpInput
+ value={confirmOtpCodes}
+ onChange={setConfirmOtpCodes}
+ length={DIGITS}
+ />
+ </div>
+ )}
+ {confirmNeedsEmailProof && (
+ <div className="w-full max-w-sm mx-auto">
+ <CredentialProofInput
+ value={confirmProofValue}
+ onChange={setConfirmProofValue}
+ />
+ </div>
+ )}
</div>
)}
@@ -347,7 +465,10 @@ export function TwoFactorSetupPage({ cancelAction }: TwoFactorSetupPageProps) {
</Button>
)}
{currentStep === DOWNLOAD_RECOVERY_CODES_STEP && (
- <Button disabled={!allowNext} onClick={tryFinishSetup}>
+ <Button
+ disabled={!allowNext || submitting}
+ onClick={tryFinishSetup}
+ >
{t("two-factor.setup-steps.recovery-codes-saved")}
</Button>
)}
diff --git a/frontend/src/stores/app/utils.ts b/frontend/src/stores/app/utils.ts
index 9616ff3d64..8783b28f3d 100644
--- a/frontend/src/stores/app/utils.ts
+++ b/frontend/src/stores/app/utils.ts
@@ -286,21 +286,3 @@ export function projectResourceNameFromId(projectId: string | undefined) {
export function getProjectResourceId(project: Project) {
return getProjectName(project.name);
}
-
-// The MFA enrollment secrets come back only from the two UpdateUser requests
-// that drive the enrollment. A GetCurrentUser read no longer carries them,
-// because a TOTP seed in a read response is a stored secret handed to whoever
-// can read the profile, and neither does an UpdateUser that mints nothing.
-//
-// Both of those overwrite the store's current user, and the enrollment window
-// is five minutes: AuthGate revalidates the session on that same interval, and
-// the account page saves a title or a phone number from the panel showing the
-// recovery codes. A plain overwrite would blank what the user is halfway
-// through saving, so both merges go through here.
-//
-// Carry them across while the response still describes the enrollment we hold.
-// temp_otp_secret_created_time is not a secret and reads keep it, so it
-// identifies the enrollment: it is nil once the enrollment commits, moves when
-// a new seed is minted, and is withheld once the window expires. Any of the
-// three stops what we hold from being carried, which is why there is no copy of
-// the five-minute rule here — the server does not report an expired enrollment
diff --git a/frontend/src/types/proto-es/v1/annotation_pb.d.ts b/frontend/src/types/proto-es/v1/annotation_pb.d.ts
index 6a882b0d03..191e4bf0eb 100644
--- a/frontend/src/types/proto-es/v1/annotation_pb.d.ts
+++ b/frontend/src/types/proto-es/v1/annotation_pb.d.ts
@@ -195,7 +195,7 @@ export enum MCPDenialReason {
/**
* Drives the out-of-band reset flow that sets or delivers the secret a
- * login accepts.
+ * login or a credential change accepts.
*
* @generated from enum value: RESETS_CREDENTIAL = 2;
*/
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 69fe59106b..7e7881ed63 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
@@ -663,6 +663,8 @@ export declare const AuthService: GenService<{
/**
* Requests a password reset email for the given email address.
* Always returns success to avoid leaking whether the email exists.
+ * Requires the workspace's SMTP mail delivery setting; without it the
+ * recovery route is an admin password reset.
* Permissions required: None
*
* @generated from rpc bytebase.v1.AuthService.RequestPasswordReset
@@ -686,6 +688,8 @@ export declare const AuthService: GenService<{
/**
* Sends a 6-digit verification code to the email for login/signup.
* Always returns success (no email enumeration). Enforces 60-sec resend cooldown.
+ * The signed-in counterpart is UserService.RequestReauthCode; LOGIN and
+ * REAUTH codes are not interchangeable.
* Permissions required: None
*
* @generated from rpc bytebase.v1.AuthService.SendEmailLoginCode
diff --git a/frontend/src/types/proto-es/v1/user_service_pb.d.ts b/frontend/src/types/proto-es/v1/user_service_pb.d.ts
index 1c8369ffbb..2c80794e89 100644
--- a/frontend/src/types/proto-es/v1/user_service_pb.d.ts
+++ b/frontend/src/types/proto-es/v1/user_service_pb.d.ts
@@ -277,6 +277,77 @@ export declare type UpdateEmailRequest = Message<"bytebase.v1.UpdateEmailRequest
*/
export declare const UpdateEmailRequestSchema: GenMessage<UpdateEmailRequest>;
+/**
+ * One proof that the caller currently controls a credential on the account.
+ * Exactly one field must be set; enforced in the handler.
+ *
+ * @generated from message bytebase.v1.CredentialProof
+ */
+export declare type CredentialProof = Message<"bytebase.v1.CredentialProof"> & {
+ /**
+ * @generated from oneof bytebase.v1.CredentialProof.proof
+ */
+ proof: {
+ /**
+ * The account's current password. Refused by a factor-touching method
+ * while a live MFA factor exists.
+ *
+ * @generated from field: string current_password = 1;
+ */
+ value: string;
+ case: "currentPassword";
+ } | {
+ /**
+ * A live code from the account's enrolled TOTP authenticator.
+ *
+ * @generated from field: string otp_code = 2;
+ */
+ value: string;
+ case: "otpCode";
+ } | {
+ /**
+ * A single-use MFA recovery code.
+ *
+ * @generated from field: string recovery_code = 3;
+ */
+ value: string;
+ case: "recoveryCode";
+ } | {
+ /**
+ * A one-time code from RequestReauthCode. Bytebase Cloud only, and only
+ * while the account has no live MFA factor.
+ *
+ * @generated from field: string email_code = 4;
+ */
+ value: string;
+ case: "emailCode";
+ } | { case: undefined; value?: undefined };
+};
+
+/**
+ * Describes the message bytebase.v1.CredentialProof.
+ * Use `create(CredentialProofSchema)` to create a new message.
+ */
+export declare const CredentialProofSchema: GenMessage<CredentialProof>;
+
+/**
+ * @generated from message bytebase.v1.RequestReauthCodeRequest
+ */
+export declare type RequestReauthCodeRequest = Message<"bytebase.v1.RequestReauthCodeRequest"> & {
+ /**
+ * Format: users/{email}. Must be the caller's own name.
+ *
+ * @generated from field: string name = 1;
+ */
+ name: string;
+};
+
+/**
+ * Describes the message bytebase.v1.RequestReauthCodeRequest.
+ * Use `create(RequestReauthCodeRequestSchema)` to create a new message.
+ */
+export declare const RequestReauthCodeRequestSchema: GenMessage<RequestReauthCodeRequest>;
+
/**
* @generated from message bytebase.v1.ChangePasswordRequest
*/
@@ -292,6 +363,11 @@ export declare type ChangePasswordRequest = Message<"bytebase.v1.ChangePasswordR
* @generated from field: string new_password = 2;
*/
newPassword: string;
+
+ /**
+ * @generated from field: bytebase.v1.CredentialProof credential = 3;
+ */
+ credential?: CredentialProof | undefined;
};
/**
@@ -385,6 +461,14 @@ export declare type EnableMFARequest = Message<"bytebase.v1.EnableMFARequest"> &
* @generated from field: google.protobuf.Timestamp pending_version = 3;
*/
pendingVersion?: Timestamp | undefined;
+
+ /**
+ * Proof of the *existing* factor, not the new device above. Required for a
+ * rotation, and for first-time enrollment on an account with a password.
+ *
+ * @generated from field: bytebase.v1.CredentialProof credential = 4;
+ */
+ credential?: CredentialProof | undefined;
};
/**
@@ -404,6 +488,14 @@ export declare type DisableMFARequest = Message<"bytebase.v1.DisableMFARequest">
* @generated from field: string name = 1;
*/
name: string;
+
+ /**
+ * Required for a self-service call against a live factor, and then only
+ * otp_code or recovery_code. Unused on an admin-assisted call.
+ *
+ * @generated from field: bytebase.v1.CredentialProof credential = 2;
+ */
+ credential?: CredentialProof | undefined;
};
/**
@@ -473,6 +565,19 @@ export declare type ConfirmRecoveryCodesRequest = Message<"bytebase.v1.ConfirmRe
* @generated from field: google.protobuf.Timestamp pending_version = 2;
*/
pendingVersion?: Timestamp | undefined;
+
+ /**
+ * @generated from field: bytebase.v1.CredentialProof credential = 3;
+ */
+ credential?: CredentialProof | undefined;
+
+ /**
+ * Required for first-time enrollment, rejected otherwise. A *fresh* code,
+ * not the one EnableMFA took.
+ *
+ * @generated from field: string otp_code = 4;
+ */
+ otpCode: string;
};
/**
@@ -709,6 +814,20 @@ export declare const UserService: GenService<{
input: typeof UpdateEmailRequestSchema;
output: typeof UserSchema;
},
+ /**
+ * Sends a one-time code to the caller's own email, usable as
+ * CredentialProof.email_code. Bytebase Cloud only, and only while the
+ * account has no live MFA factor. Not AuthService.SendEmailLoginCode: that
+ * one starts a session, this one proves an existing one.
+ * Permissions required: None beyond being signed in as `name`.
+ *
+ * @generated from rpc bytebase.v1.UserService.RequestReauthCode
+ */
+ requestReauthCode: {
+ methodKind: "unary";
+ input: typeof RequestReauthCodeRequestSchema;
+ output: typeof EmptySchema;
+ },
/**
* Changes the caller's own password. An administrator resetting someone
* else's password uses UpdateUser with the `password` mask instead — that
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 9f1108921b..1a8de9cb77 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("ChV2MS91c2VyX3NlcnZpY2UucHJvdG8SC2J5dGViYXNlLnYxIjkKDkdldFVzZXJSZXF1ZXN0EicKBG5hbWUYASABKAlCGeBBAvpBEwoRYnl0ZWJhc2UuY29tL1VzZXIiQAoUQmF0Y2hHZXRVc2Vyc1JlcXVlc3QSKAoFbmFtZXMYASADKAlCGeBBAvpBEwoRYnl0ZWJhc2UuY29tL1VzZXIiOQoVQmF0Y2hHZXRVc2Vyc1Jlc3BvbnNlEiAKBXVzZXJzGAEgAygLMhEuYnl0ZWJhc2UudjEuVXNlciJfChBMaXN0VXNlcnNSZXF1ZXN0EhEKCXBhZ2Vfc2l6ZRgBIAEoBRISCgpwYWdlX3Rva2VuGAIgASgJEhQKDHNob3dfZGVsZXRlZBgDIAEoCBIOCgZmaWx0ZXIYBCABKAkiTgoRTGlzdFVzZXJzUmVzcG9uc2USIAoFdXNlcnMYASADKAsyES5ieXRlYmFzZS52MS5Vc2VyEhcKD25leHRfcGFnZV90b2tlbhgCIAEoCSI5ChFDcmVhdGVVc2VyUmVxdWVzdBIkCgR1c2VyGAEgASgLMhEuYnl0ZWJhc2UudjEuVXNlckID4EECItQBChFVcGRhdGVVc2VyUmVxdWVzdBIkCgR1c2VyGAEgASgLMhEuYnl0ZWJhc2UudjEuVXNlckID4EECEi8KC3VwZGF0ZV9tYXNrGAIgASgLMhouZ29vZ2xlLnByb3RvYnVmLkZpZWxkTWFzaxIVCg1hbGxvd19taXNzaW5nGAYgASgISgQIAxAESgQIBBAFSgQIBRAGUghvdHBfY29kZVIacmVnZW5lcmF0ZV90ZW1wX21mYV9zZWNyZXRSGXJlZ2VuZXJhdGVfcmVjb3ZlcnlfY29kZXMiPAoRRGVsZXRlVXNlclJlcXVlc3QSJwoEbmFtZRgBIAEoCUIZ4EEC+kETChFieXRlYmFzZS5jb20vVXNlciI+ChNVbmRlbGV0ZVVzZXJSZXF1ZXN0EicKBG5hbWUYASABKAlCGeBBAvpBEwoRYnl0ZWJhc2UuY29tL1VzZXIiWQoSVXBkYXRlRW1haWxSZXF1ZXN0EicKBG5hbWUYASABKAlCGeBBAvpBEwoRYnl0ZWJhc2UuY29tL1VzZXISGgoFZW1haWwYAiABKAlCC+BBArpIBXIDGP4BIm4KFUNoYW5nZVBhc3N3b3JkUmVxdWVzdBIvCgRuYW1lGAEgASgJQiHgQQL6QRMKEWJ5dGViYXNlLmNvbS9Vc2VyukgFcgMYhAISJAoMbmV3X3Bhc3N3b3JkGAIgASgJQg7gQQK6SARyAihI0OowASJMChlTdGFydE1GQUVucm9sbG1lbnRSZXF1ZXN0Ei8KBG5hbWUYASABKAlCIeBBAvpBEwoRYnl0ZWJhc2UuY29tL1VzZXK6SAVyAxiEAiK6AQoaU3RhcnRNRkFFbnJvbGxtZW50UmVzcG9uc2USGAoKb3RwX3NlY3JldBgBIAEoCUIE0OowARIcCg5yZWNvdmVyeV9jb2RlcxgCIAMoCUIE0OowARIvCgtleHBpcmVfdGltZRgDIAEoCzIaLmdvb2dsZS5wcm90b2J1Zi5UaW1lc3RhbXASMwoPcGVuZGluZ192ZXJzaW9uGAQgASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcCKlAQoQRW5hYmxlTUZBUmVxdWVzdBIvCgRuYW1lGAEgASgJQiHgQQL6QRMKEWJ5dGViYXNlLmNvbS9Vc2VyukgFcgMYhAISIAoIb3RwX2NvZGUYAiABKAlCDuBBArpIBHICGEDQ6jABEj4KD3BlbmRpbmdfdmVyc2lvbhgDIAEoCzIaLmdvb2dsZS5wcm90b2J1Zi5UaW1lc3RhbXBCCeBBArpIA8gBASJEChFEaXNhYmxlTUZBUmVxdWVzdBIvCgRuYW1lGAEgASgJQiHgQQL6QRMKEWJ5dGViYXNlLmNvbS9Vc2VyukgFcgMYhAIiUQoeUmVnZW5lcmF0ZVJlY292ZXJ5Q29kZXNSZXF1ZXN0Ei8KBG5hbWUYASABKAlCIeBBAvpBEwoRYnl0ZWJhc2UuY29tL1VzZXK6SAVyAxiEAiJ0Ch9SZWdlbmVyYXRlUmVjb3ZlcnlDb2Rlc1Jlc3BvbnNlEhwKDnJlY292ZXJ5X2NvZGVzGAEgAygJQgTQ6jABEjMKD3BlbmRpbmdfdmVyc2lvbhgCIAEoCzIaLmdvb2dsZS5wcm90b2J1Zi5UaW1lc3RhbXAijgEKG0NvbmZpcm1SZWNvdmVyeUNvZGVzUmVxdWVzdBIvCgRuYW1lGAEgASgJQiHgQQL6QRMKEWJ5dGViYXNlLmNvbS9Vc2VyukgFcgMYhAISPgoPcGVuZGluZ192ZXJzaW9uGAIgASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcEIJ4EECukgDyAEBIsEECgRVc2VyEhEKBG5hbWUYASABKAlCA+BBAxIhCgVzdGF0ZRgCIAEoDjISLmJ5dGViYXNlLnYxLlN0YXRlEhcKBWVtYWlsGAMgASgJQgi6SAVyAxj+ARIXCgV0aXRsZRgEIAEoCUIIukgFcgMYyAESIAoIcGFzc3dvcmQYBiABKAlCDuBBBLpIBHICKEjQ6jABEhgKC21mYV9lbmFibGVkGAggASgIQgPgQQMSEwoFcGhvbmUYDCABKAlCBNDqMAISMAoHcHJvZmlsZRgNIAEoCzIZLmJ5dGViYXNlLnYxLlVzZXIuUHJvZmlsZUIE0OowAhIXCgZncm91cHMYDiADKAlCB+BBA9DqMAISFgoJd29ya3NwYWNlGBAgASgJQgPgQQMajQEKB1Byb2ZpbGUSMwoPbGFzdF9sb2dpbl90aW1lGAEgASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcBI9ChlsYXN0X2NoYW5nZV9wYXNzd29yZF90aW1lGAIgASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcBIOCgZzb3VyY2UYAyABKAk6JepBIgoRYnl0ZWJhc2UuY29tL1VzZXISDXVzZXJzL3tlbWFpbH1KBAgFEAZKBAgHEAhKBAgPEBBKBAgJEApKBAgKEAtKBAgLEAxSD3RlbXBfb3RwX3NlY3JldFITdGVtcF9yZWNvdmVyeV9jb2Rlc1IcdGVtcF9vdHBfc2VjcmV0X2NyZWF0ZWRfdGltZTLnEAoLVXNlclNlcnZpY2USeAoHR2V0VXNlchIbLmJ5dGViYXNlLnYxLkdldFVzZXJSZXF1ZXN0GhEuYnl0ZWJhc2UudjEuVXNlciI92kEEbmFtZYrqMAxiYi51c2Vycy5nZXSQ6jABoOowBKjqMAmC0+STAhQSEi92MS97bmFtZT11c2Vycy8qfRKOAQoNQmF0Y2hHZXRVc2VycxIhLmJ5dGViYXNlLnYxLkJhdGNoR2V0VXNlcnNSZXF1ZXN0GiIuYnl0ZWJhc2UudjEuQmF0Y2hHZXRVc2Vyc1Jlc3BvbnNlIjaK6jAMYmIudXNlcnMuZ2V0kOowAaDqMASo6jAJgtPkkwIUEhIvdjEvdXNlcnM6YmF0Y2hHZXQSXQoOR2V0Q3VycmVudFVzZXISFi5nb29nbGUucHJvdG9idWYuRW1wdHkaES5ieXRlYmFzZS52MS5Vc2VyIiCA6jABkOowAqDqMAGC0+STAg4SDC92MS91c2Vycy9tZRKDAQoJTGlzdFVzZXJzEh0uYnl0ZWJhc2UudjEuTGlzdFVzZXJzUmVxdWVzdBoeLmJ5dGViYXNlLnYxLkxpc3RVc2Vyc1Jlc3BvbnNlIjfaQQZwYXJlbnSK6jANYmIudXNlcnMubGlzdJDqMAGg6jAEqOowCYLT5JMCCxIJL3YxL3VzZXJzEoIBCgpDcmVhdGVVc2VyEh4uYnl0ZWJhc2UudjEuQ3JlYXRlVXNlclJlcXVlc3QaES5ieXRlYmFzZS52MS5Vc2VyIkHaQQR1c2VyiuowD2JiLnVzZXJzLmNyZWF0ZZDqMAGY6jABoOowA6jqMAaC0+STAhE6BHVzZXIiCS92MS91c2VycxKJAQoKVXBkYXRlVXNlchIeLmJ5dGViYXNlLnYxLlVwZGF0ZVVzZXJSZXF1ZXN0GhEuYnl0ZWJhc2UudjEuVXNlciJI2kEQdXNlcix1cGRhdGVfbWFza5DqMAKY6jABoOowA6jqMAOC0+STAh86BHVzZXIyFy92MS97dXNlci5uYW1lPXVzZXJzLyp9EncKCkRlbGV0ZVVzZXISHi5ieXRlYmFzZS52MS5EZWxldGVVc2VyUmVxdWVzdBoWLmdvb2dsZS5wcm90b2J1Zi5FbXB0eSIx2kEEbmFtZZDqMAKY6jABoOowBKjqMAmC0+STAhQqEi92MS97bmFtZT11c2Vycy8qfRJ7CgxVbmRlbGV0ZVVzZXISIC5ieXRlYmFzZS52MS5VbmRlbGV0ZVVzZXJSZXF1ZXN0GhEuYnl0ZWJhc2UudjEuVXNlciI2kOowApjqMAGg6jAEqOowCYLT5JMCIDoBKiIbL3YxL3tuYW1lPXVzZXJzLyp9OnVuZGVsZXRlEqEBCgtVcGRhdGVFbWFpbBIfLmJ5dGViYXNlLnYxLlVwZGF0ZUVtYWlsUmVxdWVzdBoRLmJ5dGViYXNlLnYxLlVzZXIiXtpBCm5hbWUsZW1haWyK6jAUYmIudXNlcnMudXBkYXRlRW1haWyQ6jABmOowAaDqMAOo6jAGgtPkkwIjOgEqIh4vdjEve25hbWU9dXNlcnMvKn06dXBkYXRlRW1haWwSmQEKDkNoYW5nZVBhc3N3b3JkEiIuYnl0ZWJhc2UudjEuQ2hhbmdlUGFzc3dvcmRSZXF1ZXN0GhEuYnl0ZWJhc2UudjEuVXNlciJQ2kERbmFtZSxuZXdfcGFzc3dvcmSQ6jACmOowAaDqMAOo6jADgtPkkwImOgEqIiEvdjEve25hbWU9dXNlcnMvKn06Y2hhbmdlUGFzc3dvcmQSrgEKElN0YXJ0TUZBRW5yb2xsbWVudBImLmJ5dGViYXNlLnYxLlN0YXJ0TUZBRW5yb2xsbWVudFJlcXVlc3QaJy5ieXRlYmFzZS52MS5TdGFydE1GQUVucm9sbG1lbnRSZXNwb25zZSJH2kEEbmFtZZDqMAKY6jABoOowA6jqMAGC0+STAio6ASoiJS92MS97bmFtZT11c2Vycy8qfTpzdGFydE1GQUVucm9sbG1lbnQShgEKCUVuYWJsZU1GQRIdLmJ5dGViYXNlLnYxLkVuYWJsZU1GQVJlcXVlc3QaES5ieXRlYmFzZS52MS5Vc2VyIkfaQQ1uYW1lLG90cF9jb2RlkOowApjqMAGg6jADqOowA4LT5JMCIToBKiIcL3YxL3tuYW1lPXVzZXJzLyp9OmVuYWJsZU1GQRKAAQoKRGlzYWJsZU1GQRIeLmJ5dGViYXNlLnYxLkRpc2FibGVNRkFSZXF1ZXN0GhEuYnl0ZWJhc2UudjEuVXNlciI/2kEEbmFtZZDqMAKY6jABoOowA6jqMAOC0+STAiI6ASoiHS92MS97bmFtZT11c2Vycy8qfTpkaXNhYmxlTUZBEsIBChdSZWdlbmVyYXRlUmVjb3ZlcnlDb2RlcxIrLmJ5dGViYXNlLnYxLlJlZ2VuZXJhdGVSZWNvdmVyeUNvZGVzUmVxdWVzdBosLmJ5dGViYXNlLnYxLlJlZ2VuZXJhdGVSZWNvdmVyeUNvZGVzUmVzcG9uc2UiTNpBBG5hbWWQ6jACmOowAaDqMAOo6jABgtPkkwIvOgEqIiovdjEve25hbWU9dXNlcnMvKn06cmVnZW5lcmF0ZVJlY292ZXJ5Q29kZXMSngEKFENvbmZpcm1SZWNvdmVyeUNvZGVzEiguYnl0ZWJhc2UudjEuQ29uZmlybVJlY292ZXJ5Q29kZXNSZXF1ZXN0GhEuYnl0ZWJhc2UudjEuVXNlciJJ2kEEbmFtZZDqMAKY6jABoOowA6jqMAOC0+STAiw6ASoiJy92MS97bmFtZT11c2Vycy8qfTpjb25maXJtUmVjb3ZlcnlDb2Rlc0KmAQoPY29tLmJ5dGViYXNlLnYxQhBVc2VyU2VydmljZVByb3RvUAFaNGdpdGh1Yi5jb20vYnl0ZWJhc2UvYnl0ZWJhc2UvYmFja2VuZC9nZW5lcmF0ZWQtZ28vdjGiAgNCWFiqAgtCeXRlYmFzZS5WMcoCC0J5dGViYXNlXFYx4gIXQnl0ZWJhc2VcVjFcR1BCTWV0YWRhdGHqAgxCeXRlYmFzZTo6VjFiBnByb3RvMw", [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("ChV2MS91c2VyX3NlcnZpY2UucHJvdG8SC2J5dGViYXNlLnYxIjkKDkdldFVzZXJSZXF1ZXN0EicKBG5hbWUYASABKAlCGeBBAvpBEwoRYnl0ZWJhc2UuY29tL1VzZXIiQAoUQmF0Y2hHZXRVc2Vyc1JlcXVlc3QSKAoFbmFtZXMYASADKAlCGeBBAvpBEwoRYnl0ZWJhc2UuY29tL1VzZXIiOQoVQmF0Y2hHZXRVc2Vyc1Jlc3BvbnNlEiAKBXVzZXJzGAEgAygLMhEuYnl0ZWJhc2UudjEuVXNlciJfChBMaXN0VXNlcnNSZXF1ZXN0EhEKCXBhZ2Vfc2l6ZRgBIAEoBRISCgpwYWdlX3Rva2VuGAIgASgJEhQKDHNob3dfZGVsZXRlZBgDIAEoCBIOCgZmaWx0ZXIYBCABKAkiTgoRTGlzdFVzZXJzUmVzcG9uc2USIAoFdXNlcnMYASADKAsyES5ieXRlYmFzZS52MS5Vc2VyEhcKD25leHRfcGFnZV90b2tlbhgCIAEoCSI5ChFDcmVhdGVVc2VyUmVxdWVzdBIkCgR1c2VyGAEgASgLMhEuYnl0ZWJhc2UudjEuVXNlckID4EECItQBChFVcGRhdGVVc2VyUmVxdWVzdBIkCgR1c2VyGAEgASgLMhEuYnl0ZWJhc2UudjEuVXNlckID4EECEi8KC3VwZGF0ZV9tYXNrGAIgASgLMhouZ29vZ2xlLnByb3RvYnVmLkZpZWxkTWFzaxIVCg1hbGxvd19taXNzaW5nGAYgASgISgQIAxAESgQIBBAFSgQIBRAGUghvdHBfY29kZVIacmVnZW5lcmF0ZV90ZW1wX21mYV9zZWNyZXRSGXJlZ2VuZXJhdGVfcmVjb3ZlcnlfY29kZXMiPAoRRGVsZXRlVXNlclJlcXVlc3QSJwoEbmFtZRgBIAEoCUIZ4EEC+kETChFieXRlYmFzZS5jb20vVXNlciI+ChNVbmRlbGV0ZVVzZXJSZXF1ZXN0EicKBG5hbWUYASABKAlCGeBBAvpBEwoRYnl0ZWJhc2UuY29tL1VzZXIiWQoSVXBkYXRlRW1haWxSZXF1ZXN0EicKBG5hbWUYASABKAlCGeBBAvpBEwoRYnl0ZWJhc2UuY29tL1VzZXISGgoFZW1haWwYAiABKAlCC+BBArpIBXIDGP4BIq0BCg9DcmVkZW50aWFsUHJvb2YSJwoQY3VycmVudF9wYXNzd29yZBgBIAEoCUILukgEcgIoSNDqMAFIABIfCghvdHBfY29kZRgCIAEoCUILukgEcgIYQNDqMAFIABIkCg1yZWNvdmVyeV9jb2RlGAMgASgJQgu6SARyAhhA0OowAUgAEiEKCmVtYWlsX2NvZGUYBCABKAlCC7pIBHICGEDQ6jABSABCBwoFcHJvb2YiSwoYUmVxdWVzdFJlYXV0aENvZGVSZXF1ZXN0Ei8KBG5hbWUYASABKAlCIeBBAvpBEwoRYnl0ZWJhc2UuY29tL1VzZXK6SAVyAxiEAiKrAQoVQ2hhbmdlUGFzc3dvcmRSZXF1ZXN0Ei8KBG5hbWUYASABKAlCIeBBAvpBEwoRYnl0ZWJhc2UuY29tL1VzZXK6SAVyAxiEAhIkCgxuZXdfcGFzc3dvcmQYAiABKAlCDuBBArpIBHICKEjQ6jABEjsKCmNyZWRlbnRpYWwYAyABKAsyHC5ieXRlYmFzZS52MS5DcmVkZW50aWFsUHJvb2ZCCeBBArpIA8gBASJMChlTdGFydE1GQUVucm9sbG1lbnRSZXF1ZXN0Ei8KBG5hbWUYASABKAlCIeBBAvpBEwoRYnl0ZWJhc2UuY29tL1VzZXK6SAVyAxiEAiK6AQoaU3RhcnRNRkFFbnJvbGxtZW50UmVzcG9uc2USGAoKb3RwX3NlY3JldBgBIAEoCUIE0OowARIcCg5yZWNvdmVyeV9jb2RlcxgCIAMoCUIE0OowARIvCgtleHBpcmVfdGltZRgDIAEoCzIaLmdvb2dsZS5wcm90b2J1Zi5UaW1lc3RhbXASMwoPcGVuZGluZ192ZXJzaW9uGAQgASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcCLcAQoQRW5hYmxlTUZBUmVxdWVzdBIvCgRuYW1lGAEgASgJQiHgQQL6QRMKEWJ5dGViYXNlLmNvbS9Vc2VyukgFcgMYhAISIAoIb3RwX2NvZGUYAiABKAlCDuBBArpIBHICGEDQ6jABEj4KD3BlbmRpbmdfdmVyc2lvbhgDIAEoCzIaLmdvb2dsZS5wcm90b2J1Zi5UaW1lc3RhbXBCCeBBArpIA8gBARI1CgpjcmVkZW50aWFsGAQgASgLMhwuYnl0ZWJhc2UudjEuQ3JlZGVudGlhbFByb29mQgPgQQEiewoRRGlzYWJsZU1GQVJlcXVlc3QSLwoEbmFtZRgBIAEoCUIh4EEC+kETChFieXRlYmFzZS5jb20vVXNlcrpIBXIDGIQCEjUKCmNyZWRlbnRpYWwYAiABKAsyHC5ieXRlYmFzZS52MS5DcmVkZW50aWFsUHJvb2ZCA+BBASJRCh5SZWdlbmVyYXRlUmVjb3ZlcnlDb2Rlc1JlcXVlc3QSLwoEbmFtZRgBIAEoCUIh4EEC+kETChFieXRlYmFzZS5jb20vVXNlcrpIBXIDGIQCInQKH1JlZ2VuZXJhdGVSZWNvdmVyeUNvZGVzUmVzcG9uc2USHAoOcmVjb3ZlcnlfY29kZXMYASADKAlCBNDqMAESMwoPcGVuZGluZ192ZXJzaW9uGAIgASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcCLtAQobQ29uZmlybVJlY292ZXJ5Q29kZXNSZXF1ZXN0Ei8KBG5hbWUYASABKAlCIeBBAvpBEwoRYnl0ZWJhc2UuY29tL1VzZXK6SAVyAxiEAhI+Cg9wZW5kaW5nX3ZlcnNpb24YAiABKAsyGi5nb29nbGUucHJvdG9idWYuVGltZXN0YW1wQgngQQK6SAPIAQESOwoKY3JlZGVudGlhbBgDIAEoCzIcLmJ5dGViYXNlLnYxLkNyZWRlbnRpYWxQcm9vZkIJ4EECukgDyAEBEiAKCG90cF9jb2RlGAQgASgJQg7gQQG6SARyAhhA0OowASLBBAoEVXNlchIRCgRuYW1lGAEgASgJQgPgQQMSIQoFc3RhdGUYAiABKA4yEi5ieXRlYmFzZS52MS5TdGF0ZRIXCgVlbWFpbBgDIAEoCUIIukgFcgMY/gESFwoFdGl0bGUYBCABKAlCCLpIBXIDGMgBEiAKCHBhc3N3b3JkGAYgASgJQg7gQQS6SARyAihI0OowARIYCgttZmFfZW5hYmxlZBgIIAEoCEID4EEDEhMKBXBob25lGAwgASgJQgTQ6jACEjAKB3Byb2ZpbGUYDSABKAsyGS5ieXRlYmFzZS52MS5Vc2VyLlByb2ZpbGVCBNDqMAISFwoGZ3JvdXBzGA4gAygJQgfgQQPQ6jACEhYKCXdvcmtzcGFjZRgQIAEoCUID4EEDGo0BCgdQcm9maWxlEjMKD2xhc3RfbG9naW5fdGltZRgBIAEoCzIaLmdvb2dsZS5wcm90b2J1Zi5UaW1lc3RhbXASPQoZbGFzdF9jaGFuZ2VfcGFzc3dvcmRfdGltZRgCIAEoCzIaLmdvb2dsZS5wcm90b2J1Zi5UaW1lc3RhbXASDgoGc291cmNlGAMgASgJOiXqQSIKEWJ5dGViYXNlLmNvbS9Vc2VyEg11c2Vycy97ZW1haWx9SgQIBRAGSgQIBxAISgQIDxAQSgQICRAKSgQIChALSgQICxAMUg90ZW1wX290cF9zZWNyZXRSE3RlbXBfcmVjb3ZlcnlfY29kZXNSHHRlbXBfb3RwX3NlY3JldF9jcmVhdGVkX3RpbWUyhBIKC1VzZXJTZXJ2aWNlEngKB0dldFVzZXISGy5ieXRlYmFzZS52MS5HZXRVc2VyUmVxdWVzdBoRLmJ5dGViYXNlLnYxLlVzZXIiPdpBBG5hbWWK6jAMYmIudXNlcnMuZ2V0kOowAaDqMASo6jAJgtPkkwIUEhIvdjEve25hbWU9dXNlcnMvKn0SjgEKDUJhdGNoR2V0VXNlcnMSIS5ieXRlYmFzZS52MS5CYXRjaEdldFVzZXJzUmVxdWVzdBoiLmJ5dGViYXNlLnYxLkJhdGNoR2V0VXNlcnNSZXNwb25zZSI2iuowDGJiLnVzZXJzLmdldJDqMAGg6jAEqOowCYLT5JMCFBISL3YxL3VzZXJzOmJhdGNoR2V0El0KDkdldEN1cnJlbnRVc2VyEhYuZ29vZ2xlLnByb3RvYnVmLkVtcHR5GhEuYnl0ZWJhc2UudjEuVXNlciIggOowAZDqMAKg6jABgtPkkwIOEgwvdjEvdXNlcnMvbWUSgwEKCUxpc3RVc2VycxIdLmJ5dGViYXNlLnYxLkxpc3RVc2Vyc1JlcXVlc3QaHi5ieXRlYmFzZS52MS5MaXN0VXNlcnNSZXNwb25zZSI32kEGcGFyZW50iuowDWJiLnVzZXJzLmxpc3SQ6jABoOowBKjqMAmC0+STAgsSCS92MS91c2VycxKCAQoKQ3JlYXRlVXNlchIeLmJ5dGViYXNlLnYxLkNyZWF0ZVVzZXJSZXF1ZXN0GhEuYnl0ZWJhc2UudjEuVXNlciJB2kEEdXNlcorqMA9iYi51c2Vycy5jcmVhdGWQ6jABmOowAaDqMAOo6jAGgtPkkwIROgR1c2VyIgkvdjEvdXNlcnMSiQEKClVwZGF0ZVVzZXISHi5ieXRlYmFzZS52MS5VcGRhdGVVc2VyUmVxdWVzdBoRLmJ5dGViYXNlLnYxLlVzZXIiSNpBEHVzZXIsdXBkYXRlX21hc2uQ6jACmOowAaDqMAOo6jADgtPkkwIfOgR1c2VyMhcvdjEve3VzZXIubmFtZT11c2Vycy8qfRJ3CgpEZWxldGVVc2VyEh4uYnl0ZWJhc2UudjEuRGVsZXRlVXNlclJlcXVlc3QaFi5nb29nbGUucHJvdG9idWYuRW1wdHkiMdpBBG5hbWWQ6jACmOowAaDqMASo6jAJgtPkkwIUKhIvdjEve25hbWU9dXNlcnMvKn0SewoMVW5kZWxldGVVc2VyEiAuYnl0ZWJhc2UudjEuVW5kZWxldGVVc2VyUmVxdWVzdBoRLmJ5dGViYXNlLnYxLlVzZXIiNpDqMAKY6jABoOowBKjqMAmC0+STAiA6ASoiGy92MS97bmFtZT11c2Vycy8qfTp1bmRlbGV0ZRKhAQoLVXBkYXRlRW1haWwSHy5ieXRlYmFzZS52MS5VcGRhdGVFbWFpbFJlcXVlc3QaES5ieXRlYmFzZS52MS5Vc2VyIl7aQQpuYW1lLGVtYWlsiuowFGJiLnVzZXJzLnVwZGF0ZUVtYWlskOowAZjqMAGg6jADqOowBoLT5JMCIzoBKiIeL3YxL3tuYW1lPXVzZXJzLyp9OnVwZGF0ZUVtYWlsEpoBChFSZXF1ZXN0UmVhdXRoQ29kZRIlLmJ5dGViYXNlLnYxLlJlcXVlc3RSZWF1dGhDb2RlUmVxdWVzdBoWLmdvb2dsZS5wcm90b2J1Zi5FbXB0eSJG2kEEbmFtZZDqMAKY6jABoOowA6jqMAKC0+STAik6ASoiJC92MS97bmFtZT11c2Vycy8qfTpyZXF1ZXN0UmVhdXRoQ29kZRKZAQoOQ2hhbmdlUGFzc3dvcmQSIi5ieXRlYmFzZS52MS5DaGFuZ2VQYXNzd29yZFJlcXVlc3QaES5ieXRlYmFzZS52MS5Vc2VyIlDaQRFuYW1lLG5ld19wYXNzd29yZJDqMAKY6jABoOowA6jqMAOC0+STAiY6ASoiIS92MS97bmFtZT11c2Vycy8qfTpjaGFuZ2VQYXNzd29yZBKuAQoSU3RhcnRNRkFFbnJvbGxtZW50EiYuYnl0ZWJhc2UudjEuU3RhcnRNRkFFbnJvbGxtZW50UmVxdWVzdBonLmJ5dGViYXNlLnYxLlN0YXJ0TUZBRW5yb2xsbWVudFJlc3BvbnNlIkfaQQRuYW1lkOowApjqMAGg6jADqOowAYLT5JMCKjoBKiIlL3YxL3tuYW1lPXVzZXJzLyp9OnN0YXJ0TUZBRW5yb2xsbWVudBKGAQoJRW5hYmxlTUZBEh0uYnl0ZWJhc2UudjEuRW5hYmxlTUZBUmVxdWVzdBoRLmJ5dGViYXNlLnYxLlVzZXIiR9pBDW5hbWUsb3RwX2NvZGWQ6jACmOowAaDqMAOo6jADgtPkkwIhOgEqIhwvdjEve25hbWU9dXNlcnMvKn06ZW5hYmxlTUZBEoABCgpEaXNhYmxlTUZBEh4uYnl0ZWJhc2UudjEuRGlzYWJsZU1GQVJlcXVlc3QaES5ieXRlYmFzZS52MS5Vc2VyIj/aQQRuYW1lkOowApjqMAGg6jADqOowA4LT5JMCIjoBKiIdL3YxL3tuYW1lPXVzZXJzLyp9OmRpc2FibGVNRkESwgEKF1JlZ2VuZXJhdGVSZWNvdmVyeUNvZGVzEisuYnl0ZWJhc2UudjEuUmVnZW5lcmF0ZVJlY292ZXJ5Q29kZXNSZXF1ZXN0GiwuYnl0ZWJhc2UudjEuUmVnZW5lcmF0ZVJlY292ZXJ5Q29kZXNSZXNwb25zZSJM2kEEbmFtZZDqMAKY6jABoOowA6jqMAGC0+STAi86ASoiKi92MS97bmFtZT11c2Vycy8qfTpyZWdlbmVyYXRlUmVjb3ZlcnlDb2RlcxKeAQoUQ29uZmlybVJlY292ZXJ5Q29kZXMSKC5ieXRlYmFzZS52MS5Db25maXJtUmVjb3ZlcnlDb2Rlc1JlcXVlc3QaES5ieXRlYmFzZS52MS5Vc2VyIknaQQRuYW1lkOowApjqMAGg6jADqOowA4LT5JMCLDoBKiInL3YxL3tuYW1lPXVzZXJzLyp9OmNvbmZpcm1SZWNvdmVyeUNvZGVzQqYBCg9jb20uYnl0ZWJhc2UudjFCEFVzZXJTZXJ2aWNlUHJvdG9QAVo0Z2l0aHViLmNvbS9ieXRlYmFzZS9ieXRlYmFzZS9iYWNrZW5kL2dlbmVyYXRlZC1nby92MaICA0JYWKoCC0J5dGViYXNlLlYxygILQnl0ZWJhc2VcVjHiAhdCeXRlYmFzZVxWMVxHUEJNZXRhZGF0YeoCDEJ5dGViYXNlOjpWMWIGcHJvdG8z", [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.
@@ -88,75 +88,89 @@ export const UndeleteUserRequestSchema = /*@__PURE__*/
export const UpdateEmailRequestSchema = /*@__PURE__*/
messageDesc(file_v1_user_service, 9);
+/**
+ * Describes the message bytebase.v1.CredentialProof.
+ * Use `create(CredentialProofSchema)` to create a new message.
+ */
+export const CredentialProofSchema = /*@__PURE__*/
+ messageDesc(file_v1_user_service, 10);
+
+/**
+ * Describes the message bytebase.v1.RequestReauthCodeRequest.
+ * Use `create(RequestReauthCodeRequestSchema)` to create a new message.
+ */
+export const RequestReauthCodeRequestSchema = /*@__PURE__*/
+ messageDesc(file_v1_user_service, 11);
+
/**
* Describes the message bytebase.v1.ChangePasswordRequest.
* Use `create(ChangePasswordRequestSchema)` to create a new message.
*/
export const ChangePasswordRequestSchema = /*@__PURE__*/
- messageDesc(file_v1_user_service, 10);
+ messageDesc(file_v1_user_service, 12);
/**
* Describes the message bytebase.v1.StartMFAEnrollmentRequest.
* Use `create(StartMFAEnrollmentRequestSchema)` to create a new message.
*/
export const StartMFAEnrollmentRequestSchema = /*@__PURE__*/
- messageDesc(file_v1_user_service, 11);
+ messageDesc(file_v1_user_service, 13);
/**
* Describes the message bytebase.v1.StartMFAEnrollmentResponse.
* Use `create(StartMFAEnrollmentResponseSchema)` to create a new message.
*/
export const StartMFAEnrollmentResponseSchema = /*@__PURE__*/
- messageDesc(file_v1_user_service, 12);
+ messageDesc(file_v1_user_service, 14);
/**
* Describes the message bytebase.v1.EnableMFARequest.
* Use `create(EnableMFARequestSchema)` to create a new message.
*/
export const EnableMFARequestSchema = /*@__PURE__*/
- messageDesc(file_v1_user_service, 13);
+ messageDesc(file_v1_user_service, 15);
/**
* Describes the message bytebase.v1.DisableMFARequest.
* Use `create(DisableMFARequestSchema)` to create a new message.
*/
export const DisableMFARequestSchema = /*@__PURE__*/
- messageDesc(file_v1_user_service, 14);
+ messageDesc(file_v1_user_service, 16);
/**
* Describes the message bytebase.v1.RegenerateRecoveryCodesRequest.
* Use `create(RegenerateRecoveryCodesRequestSchema)` to create a new message.
*/
export const RegenerateRecoveryCodesRequestSchema = /*@__PURE__*/
- messageDesc(file_v1_user_service, 15);
+ messageDesc(file_v1_user_service, 17);
/**
* Describes the message bytebase.v1.RegenerateRecoveryCodesResponse.
* Use `create(RegenerateRecoveryCodesResponseSchema)` to create a new message.
*/
export const RegenerateRecoveryCodesResponseSchema = /*@__PURE__*/
- messageDesc(file_v1_user_service, 16);
+ messageDesc(file_v1_user_service, 18);
/**
* Describes the message bytebase.v1.ConfirmRecoveryCodesRequest.
* Use `create(ConfirmRecoveryCodesRequestSchema)` to create a new message.
*/
export const ConfirmRecoveryCodesRequestSchema = /*@__PURE__*/
- messageDesc(file_v1_user_service, 17);
+ messageDesc(file_v1_user_service, 19);
/**
* Describes the message bytebase.v1.User.
* Use `create(UserSchema)` to create a new message.
*/
export const UserSchema = /*@__PURE__*/
- messageDesc(file_v1_user_service, 18);
+ messageDesc(file_v1_user_service, 20);
/**
* Describes the message bytebase.v1.User.Profile.
* Use `create(User_ProfileSchema)` to create a new message.
*/
export const User_ProfileSchema = /*@__PURE__*/
- messageDesc(file_v1_user_service, 18, 0);
+ messageDesc(file_v1_user_service, 20, 0);
/**
* UserService manages user accounts and authentication.
diff --git a/frontend/vitest.config.ts b/frontend/vitest.config.ts
index 133d5b9712..58bf120b76 100644
--- a/frontend/vitest.config.ts
+++ b/frontend/vitest.config.ts
@@ -16,6 +16,13 @@ export default mergeConfig(
url: "http://localhost/",
},
},
+ // Vitest's 5s/10s defaults are tuned for a fast machine. Setting up a
+ // jsdom environment and rendering a page in one of the heavier
+ // beforeEach hooks runs comfortably under them locally but not on the
+ // self-hosted CI runner, where the suite is several times slower. These
+ // are still far below any real hang.
+ testTimeout: 15000,
+ hookTimeout: 30000,
exclude: [...configDefaults.exclude, "e2e/*", "tests/e2e/**"],
root: fileURLToPath(new URL("./", import.meta.url)),
setupFiles: ["./vitest.setup.ts"],
diff --git a/proto/gen/grpc-doc/openapi.yaml b/proto/gen/grpc-doc/openapi.yaml
index 86bf1c812a..289d22e541 100644
--- a/proto/gen/grpc-doc/openapi.yaml
+++ b/proto/gen/grpc-doc/openapi.yaml
@@ -355,6 +355,8 @@ paths:
description: |-
Requests a password reset email for the given email address.
Always returns success to avoid leaking whether the email exists.
+ Requires the workspace's SMTP mail delivery setting; without it the
+ recovery route is an admin password reset.
Permissions required: None
operationId: AuthService_RequestPasswordReset
requestBody:
@@ -400,6 +402,8 @@ paths:
description: |-
Sends a 6-digit verification code to the email for login/signup.
Always returns success (no email enumeration). Enforces 60-sec resend cooldown.
+ The signed-in counterpart is UserService.RequestReauthCode; LOGIN and
+ REAUTH codes are not interchangeable.
Permissions required: None
operationId: AuthService_SendEmailLoginCode
requestBody:
@@ -17353,9 +17357,13 @@ paths:
title: new_password
description: |
string.max_bytes = 72
+ credential:
+ title: credential
+ $ref: '#/components/schemas/bytebase.v1.CredentialProof'
title: ChangePasswordRequest
required:
- newPassword
+ - credential
additionalProperties: false
required: true
responses:
@@ -17395,9 +17403,20 @@ paths:
The pending_version of the codes being confirmed. Confirming promotes
exactly the set this version identifies, or nothing.
$ref: '#/components/schemas/google.protobuf.Timestamp'
+ credential:
+ title: credential
+ $ref: '#/components/schemas/bytebase.v1.CredentialProof'
+ otpCode:
+ type: string
+ title: otp_code
+ maxLength: 64
+ description: |-
+ (OPTIONAL) Required for first-time enrollment, rejected otherwise. A *fresh* code,
+ not the one EnableMFA took.
title: ConfirmRecoveryCodesRequest
required:
- pendingVersion
+ - credential
additionalProperties: false
required: true
responses:
@@ -17426,6 +17445,21 @@ paths:
required: true
schema:
type: string
+ requestBody:
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ credential:
+ title: credential
+ description: |-
+ (OPTIONAL) Required for a self-service call against a live factor, and then only
+ otp_code or recovery_code. Unused on an admin-assisted call.
+ $ref: '#/components/schemas/bytebase.v1.CredentialProof'
+ title: DisableMFARequest
+ additionalProperties: false
+ required: true
responses:
"200":
description: Success
@@ -17470,6 +17504,12 @@ paths:
title: pending_version
description: The pending_version this enrollment was minted with.
$ref: '#/components/schemas/google.protobuf.Timestamp'
+ credential:
+ title: credential
+ description: |-
+ (OPTIONAL) Proof of the *existing* factor, not the new device above. Required for a
+ rotation, and for first-time enrollment on an account with a password.
+ $ref: '#/components/schemas/bytebase.v1.CredentialProof'
title: EnableMFARequest
required:
- otpCode
@@ -17508,6 +17548,32 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/bytebase.v1.RegenerateRecoveryCodesResponse'
+ /v1/users/{user}:requestReauthCode:
+ post:
+ tags:
+ - UserService
+ summary: RequestReauthCode
+ description: |-
+ Sends a one-time code to the caller's own email, usable as
+ CredentialProof.email_code. Bytebase Cloud only, and only while the
+ account has no live MFA factor. Not AuthService.SendEmailLoginCode: that
+ one starts a session, this one proves an existing one.
+ Permissions required: None beyond being signed in as `name`.
+ operationId: UserService_RequestReauthCode
+ parameters:
+ - name: user
+ in: path
+ description: The user id.
+ required: true
+ schema:
+ type: string
+ responses:
+ "200":
+ description: Success
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/google.protobuf.Empty'
/v1/users/{user}:startMFAEnrollment:
post:
tags:
@@ -20723,10 +20789,14 @@ components:
title: new_password
description: |
string.max_bytes = 72
+ credential:
+ title: credential
+ $ref: '#/components/schemas/bytebase.v1.CredentialProof'
title: ChangePasswordRequest
required:
- name
- newPassword
+ - credential
additionalProperties: false
bytebase.v1.Changelog:
type: object
@@ -21114,10 +21184,21 @@ components:
The pending_version of the codes being confirmed. Confirming promotes
exactly the set this version identifies, or nothing.
$ref: '#/components/schemas/google.protobuf.Timestamp'
+ credential:
+ title: credential
+ $ref: '#/components/schemas/bytebase.v1.CredentialProof'
+ otpCode:
+ type: string
+ title: otp_code
+ maxLength: 64
+ description: |-
+ (OPTIONAL) Required for first-time enrollment, rejected otherwise. A *fresh* code,
+ not the one EnableMFA took.
title: ConfirmRecoveryCodesRequest
required:
- name
- pendingVersion
+ - credential
additionalProperties: false
bytebase.v1.CreateAccessGrantRequest:
type: object
@@ -21557,6 +21638,58 @@ components:
- workloadIdentity
additionalProperties: false
description: Request message for creating a workload identity.
+ bytebase.v1.CredentialProof:
+ type: object
+ oneOf:
+ - type: object
+ properties:
+ currentPassword:
+ type: string
+ title: current_password
+ description: |
+ The account's current password. Refused by a factor-touching method
+ while a live MFA factor exists.
+ string.max_bytes = 72
+ title: current_password
+ required:
+ - currentPassword
+ - type: object
+ properties:
+ emailCode:
+ type: string
+ title: email_code
+ maxLength: 64
+ description: |-
+ A one-time code from RequestReauthCode. Bytebase Cloud only, and only
+ while the account has no live MFA factor.
+ title: email_code
+ required:
+ - emailCode
+ - type: object
+ properties:
+ otpCode:
+ type: string
+ title: otp_code
+ maxLength: 64
+ description: A live code from the account's enrolled TOTP authenticator.
+ title: otp_code
+ required:
+ - otpCode
+ - type: object
+ properties:
+ recoveryCode:
+ type: string
+ title: recovery_code
+ maxLength: 64
+ description: A single-use MFA recovery code.
+ title: recovery_code
+ required:
+ - recoveryCode
+ title: CredentialProof
+ additionalProperties: false
+ description: |-
+ One proof that the caller currently controls a credential on the account.
+ Exactly one field must be set; enforced in the handler.
bytebase.v1.DataClassificationSetting:
type: object
properties:
@@ -22793,6 +22926,12 @@ components:
description: |-
Format: users/{email}. The caller's own, or another user's with
bb.users.update.
+ credential:
+ title: credential
+ description: |-
+ (OPTIONAL) Required for a self-service call against a live factor, and then only
+ otp_code or recovery_code. Unused on an admin-assisted call.
+ $ref: '#/components/schemas/bytebase.v1.CredentialProof'
title: DisableMFARequest
required:
- name
@@ -22886,6 +23025,12 @@ components:
title: pending_version
description: The pending_version this enrollment was minted with.
$ref: '#/components/schemas/google.protobuf.Timestamp'
+ credential:
+ title: credential
+ description: |-
+ (OPTIONAL) Proof of the *existing* factor, not the new device above. Required for a
+ rotation, and for first-time enrollment on an account with a password.
+ $ref: '#/components/schemas/bytebase.v1.CredentialProof'
title: EnableMFARequest
required:
- name
@@ -28875,6 +29020,18 @@ components:
Format: workspaces/{workspace}
title: RequestPasswordResetRequest
additionalProperties: false
+ bytebase.v1.RequestReauthCodeRequest:
+ type: object
+ properties:
+ name:
+ type: string
+ title: name
+ maxLength: 260
+ description: 'Format: users/{email}. Must be the caller''s own name.'
+ title: RequestReauthCodeRequest
+ required:
+ - name
+ additionalProperties: false
bytebase.v1.ResetPasswordRequest:
type: object
properties:
diff --git a/proto/gen/grpc-doc/store/README.md b/proto/gen/grpc-doc/store/README.md
index 1c6f12ec61..b670e7d53b 100644
--- a/proto/gen/grpc-doc/store/README.md
+++ b/proto/gen/grpc-doc/store/README.md
@@ -947,6 +947,7 @@ Stored as the enum name string in email_verification_code.purpose column.
| EMAIL_VERIFICATION_CODE_PURPOSE_UNSPECIFIED | 0 | |
| LOGIN | 1 | |
| PASSWORD_RESET | 2 | |
+| REAUTH | 3 | Re-authentication proof for a credential change (CredentialProof.email_code). Never accepted by Login. |
diff --git a/proto/gen/grpc-doc/store/index.html b/proto/gen/grpc-doc/store/index.html
index 609579fc14..1ab29b623d 100644
--- a/proto/gen/grpc-doc/store/index.html
+++ b/proto/gen/grpc-doc/store/index.html
@@ -3173,6 +3173,13 @@ This information is not authenticated and should be treated accordingly. </p></t
<td><p></p></td>
</tr>
+ <tr>
+ <td>REAUTH</td>
+ <td>3</td>
+ <td><p>Re-authentication proof for a credential change
+(CredentialProof.email_code). Never accepted by Login.</p></td>
+ </tr>
+
</tbody>
</table>
diff --git a/proto/gen/grpc-doc/v1/README.md b/proto/gen/grpc-doc/v1/README.md
index 3b1b799671..01191e1160 100644
--- a/proto/gen/grpc-doc/v1/README.md
+++ b/proto/gen/grpc-doc/v1/README.md
@@ -313,6 +313,7 @@
- [ChangePasswordRequest](#bytebase-v1-ChangePasswordRequest)
- [ConfirmRecoveryCodesRequest](#bytebase-v1-ConfirmRecoveryCodesRequest)
- [CreateUserRequest](#bytebase-v1-CreateUserRequest)
+ - [CredentialProof](#bytebase-v1-CredentialProof)
- [DeleteUserRequest](#bytebase-v1-DeleteUserRequest)
- [DisableMFARequest](#bytebase-v1-DisableMFARequest)
- [EnableMFARequest](#bytebase-v1-EnableMFARequest)
@@ -321,6 +322,7 @@
- [ListUsersResponse](#bytebase-v1-ListUsersResponse)
- [RegenerateRecoveryCodesRequest](#bytebase-v1-RegenerateRecoveryCodesRequest)
- [RegenerateRecoveryCodesResponse](#bytebase-v1-RegenerateRecoveryCodesResponse)
+ - [RequestReauthCodeRequest](#bytebase-v1-RequestReauthCodeRequest)
- [StartMFAEnrollmentRequest](#bytebase-v1-StartMFAEnrollmentRequest)
- [StartMFAEnrollmentResponse](#bytebase-v1-StartMFAEnrollmentResponse)
- [UndeleteUserRequest](#bytebase-v1-UndeleteUserRequest)
@@ -870,7 +872,7 @@ already keeps for the wording.
| ---- | ------ | ----------- |
| MCP_DENIAL_REASON_UNSPECIFIED | 0 | No reason recorded. The method is still denied — mcp_method_class is what enforces — and the denial falls back to generic wording. CI rejects this on a method classified FORBIDDEN or EXCLUDED. |
| MINTS_CREDENTIAL | 1 | Puts a token for the caller&#39;s own principal in the response body. |
-| RESETS_CREDENTIAL | 2 | Drives the out-of-band reset flow that sets or delivers the secret a login accepts. |
+| RESETS_CREDENTIAL | 2 | Drives the out-of-band reset flow that sets or delivers the secret a login or a credential change accepts. |
| TAKES_OVER_ACCOUNT | 3 | Rewrites an account&#39;s own credentials, which would let the session log in as that account. |
| ENDS_SESSION | 4 | Destroys the human&#39;s own login session. |
| ENDS_MEMBERSHIP | 5 | Destroys the caller&#39;s own workspace membership and mints a plain workspace token on the way out. |
@@ -5446,6 +5448,7 @@ SettingService manages workspace-level settings and configurations.
| ----- | ---- | ----- | ----------- |
| name | [string](#string) | | Format: users/{email}. Must be the caller&#39;s own name. |
| new_password | [string](#string) | | |
+| credential | [CredentialProof](#bytebase-v1-CredentialProof) | | |
@@ -5462,6 +5465,8 @@ SettingService manages workspace-level settings and configurations.
| ----- | ---- | ----- | ----------- |
| name | [string](#string) | | Format: users/{email}. Must be the caller&#39;s own name. |
| pending_version | [google.protobuf.Timestamp](#google-protobuf-Timestamp) | | The pending_version of the codes being confirmed. Confirming promotes exactly the set this version identifies, or nothing. |
+| credential | [CredentialProof](#bytebase-v1-CredentialProof) | | |
+| otp_code | [string](#string) | | Required for first-time enrollment, rejected otherwise. A *fresh* code, not the one EnableMFA took. |
@@ -5483,6 +5488,25 @@ SettingService manages workspace-level settings and configurations.
+<a name="bytebase-v1-CredentialProof"></a>
+
+### CredentialProof
+One proof that the caller currently controls a credential on the account.
+Exactly one field must be set; enforced in the handler.
+
+
+| Field | Type | Label | Description |
+| ----- | ---- | ----- | ----------- |
+| current_password | [string](#string) | | The account&#39;s current password. Refused by a factor-touching method while a live MFA factor exists. |
+| otp_code | [string](#string) | | A live code from the account&#39;s enrolled TOTP authenticator. |
+| recovery_code | [string](#string) | | A single-use MFA recovery code. |
+| email_code | [string](#string) | | A one-time code from RequestReauthCode. Bytebase Cloud only, and only while the account has no live MFA factor. |
+
+
+
+
+
+
<a name="bytebase-v1-DeleteUserRequest"></a>
### DeleteUserRequest
@@ -5507,6 +5531,7 @@ SettingService manages workspace-level settings and configurations.
| Field | Type | Label | Description |
| ----- | ---- | ----- | ----------- |
| name | [string](#string) | | Format: users/{email}. The caller&#39;s own, or another user&#39;s with bb.users.update. |
+| credential | [CredentialProof](#bytebase-v1-CredentialProof) | | Required for a self-service call against a live factor, and then only otp_code or recovery_code. Unused on an admin-assisted call. |
@@ -5524,6 +5549,7 @@ SettingService manages workspace-level settings and configurations.
| name | [string](#string) | | Format: users/{email}. Must be the caller&#39;s own name. |
| otp_code | [string](#string) | | A code from the authenticator the pending secret was just added to. |
| pending_version | [google.protobuf.Timestamp](#google-protobuf-Timestamp) | | The pending_version this enrollment was minted with. |
+| credential | [CredentialProof](#bytebase-v1-CredentialProof) | | Proof of the *existing* factor, not the new device above. Required for a rotation, and for first-time enrollment on an account with a password. |
@@ -5616,6 +5642,21 @@ For example: name == &#34;ed&#34; name.contains(&#34;ed&#34;) email == &#34;ed@b
+<a name="bytebase-v1-RequestReauthCodeRequest"></a>
+
+### RequestReauthCodeRequest
+
+
+
+| Field | Type | Label | Description |
+| ----- | ---- | ----- | ----------- |
+| name | [string](#string) | | Format: users/{email}. Must be the caller&#39;s own name. |
+
+
+
+
+
+
<a name="bytebase-v1-StartMFAEnrollmentRequest"></a>
### StartMFAEnrollmentRequest
@@ -5762,6 +5803,7 @@ UserService manages user accounts and authentication.
| DeleteUser | [DeleteUserRequest](#bytebase-v1-DeleteUserRequest) | [.google.protobuf.Empty](#google-protobuf-Empty) | Deletes a user. Requires bb.users.delete permission with additional validation: the last remaining workspace admin cannot be deleted. Permissions required: bb.users.delete |
| UndeleteUser | [UndeleteUserRequest](#bytebase-v1-UndeleteUserRequest) | [User](#bytebase-v1-User) | Restores a deleted user. Permissions required: bb.users.undelete |
| UpdateEmail | [UpdateEmailRequest](#bytebase-v1-UpdateEmailRequest) | [User](#bytebase-v1-User) | Updates a user&#39;s email address. Permissions required: bb.users.updateEmail |
+| RequestReauthCode | [RequestReauthCodeRequest](#bytebase-v1-RequestReauthCodeRequest) | [.google.protobuf.Empty](#google-protobuf-Empty) | Sends a one-time code to the caller&#39;s own email, usable as CredentialProof.email_code. Bytebase Cloud only, and only while the account has no live MFA factor. Not AuthService.SendEmailLoginCode: that one starts a session, this one proves an existing one. Permissions required: None beyond being signed in as `name`. |
| ChangePassword | [ChangePasswordRequest](#bytebase-v1-ChangePasswordRequest) | [User](#bytebase-v1-User) | Changes the caller&#39;s own password. An administrator resetting someone else&#39;s password uses UpdateUser with the `password` mask instead — that is a different operation with a different audit story, even though both end in a new password hash. Permissions required: None beyond being signed in as `name`. |
| StartMFAEnrollment | [StartMFAEnrollmentRequest](#bytebase-v1-StartMFAEnrollmentRequest) | [StartMFAEnrollmentResponse](#bytebase-v1-StartMFAEnrollmentResponse) | Mints a pending TOTP secret and recovery codes for the caller&#39;s own account and returns them. Nothing goes live until ConfirmRecoveryCodes, so an abandoned enrollment leaves the account exactly as it was. Permissions required: None beyond being signed in as `name`. |
| EnableMFA | [EnableMFARequest](#bytebase-v1-EnableMFARequest) | [User](#bytebase-v1-User) | Verifies an otp_code against the pending enrollment. Nothing is written: this is the step that catches a mistyped authenticator before the caller is shown recovery codes, and promotion happens at ConfirmRecoveryCodes so an account is never MFA-required with codes its owner never saved. Permissions required: None beyond being signed in as `name`. It writes nothing itself, but it is a required step of installing a factor on the account, which is why it is denied on the same grounds as the promotion it precedes. |
@@ -6084,9 +6126,9 @@ AuthService handles user authentication operations.
| Signup | [SignupRequest](#bytebase-v1-SignupRequest) | [LoginResponse](#bytebase-v1-LoginResponse) | Registers a new user account. Creates a principal and assigns a workspace: - If the user&#39;s email was pre-invited to a workspace, joins that workspace. - Otherwise, creates a new workspace with the user as admin. Returns access tokens so the user is logged in immediately after signup. |
| Refresh | [RefreshRequest](#bytebase-v1-RefreshRequest) | [RefreshResponse](#bytebase-v1-RefreshResponse) | Refreshes the access token using the refresh token cookie. Permissions required: None (validates via refresh token cookie) |
| SwitchWorkspace | [SwitchWorkspaceRequest](#bytebase-v1-SwitchWorkspaceRequest) | [LoginResponse](#bytebase-v1-LoginResponse) | Switches the current user&#39;s active workspace and issues new tokens. The user must be a member of the target workspace. |
-| RequestPasswordReset | [RequestPasswordResetRequest](#bytebase-v1-RequestPasswordResetRequest) | [.google.protobuf.Empty](#google-protobuf-Empty) | Requests a password reset email for the given email address. Always returns success to avoid leaking whether the email exists. Permissions required: None |
+| RequestPasswordReset | [RequestPasswordResetRequest](#bytebase-v1-RequestPasswordResetRequest) | [.google.protobuf.Empty](#google-protobuf-Empty) | Requests a password reset email for the given email address. Always returns success to avoid leaking whether the email exists. Requires the workspace&#39;s SMTP mail delivery setting; without it the recovery route is an admin password reset. Permissions required: None |
| ResetPassword | [ResetPasswordRequest](#bytebase-v1-ResetPasswordRequest) | [.google.protobuf.Empty](#google-protobuf-Empty) | Resets the user&#39;s password using a password reset token from email. Permissions required: None (validates via token) |
-| SendEmailLoginCode | [SendEmailLoginCodeRequest](#bytebase-v1-SendEmailLoginCodeRequest) | [.google.protobuf.Empty](#google-protobuf-Empty) | Sends a 6-digit verification code to the email for login/signup. Always returns success (no email enumeration). Enforces 60-sec resend cooldown. Permissions required: None |
+| SendEmailLoginCode | [SendEmailLoginCodeRequest](#bytebase-v1-SendEmailLoginCodeRequest) | [.google.protobuf.Empty](#google-protobuf-Empty) | Sends a 6-digit verification code to the email for login/signup. Always returns success (no email enumeration). Enforces 60-sec resend cooldown. The signed-in counterpart is UserService.RequestReauthCode; LOGIN and REAUTH codes are not interchangeable. Permissions required: None |
diff --git a/proto/gen/grpc-doc/v1/index.html b/proto/gen/grpc-doc/v1/index.html
index a78f4b668f..059dd75b64 100644
--- a/proto/gen/grpc-doc/v1/index.html
+++ b/proto/gen/grpc-doc/v1/index.html
@@ -1365,6 +1365,10 @@
<a href="#bytebase.v1.CreateUserRequest"><span class="badge">M</span>CreateUserRequest</a>
</li>
+ <li>
+ <a href="#bytebase.v1.CredentialProof"><span class="badge">M</span>CredentialProof</a>
+ </li>
+
<li>
<a href="#bytebase.v1.DeleteUserRequest"><span class="badge">M</span>DeleteUserRequest</a>
</li>
@@ -1397,6 +1401,10 @@
<a href="#bytebase.v1.RegenerateRecoveryCodesResponse"><span class="badge">M</span>RegenerateRecoveryCodesResponse</a>
</li>
+ <li>
+ <a href="#bytebase.v1.RequestReauthCodeRequest"><span class="badge">M</span>RequestReauthCodeRequest</a>
+ </li>
+
<li>
<a href="#bytebase.v1.StartMFAEnrollmentRequest"><span class="badge">M</span>StartMFAEnrollmentRequest</a>
</li>
@@ -3343,7 +3351,7 @@ on a method classified FORBIDDEN or EXCLUDED.</p></td>
<td>RESETS_CREDENTIAL</td>
<td>2</td>
<td><p>Drives the out-of-band reset flow that sets or delivers the secret a
-login accepts.</p></td>
+login or a credential change accepts.</p></td>
</tr>
<tr>
@@ -15647,6 +15655,13 @@ Format: users/{email} </p></td>
<td><p> </p></td>
</tr>
+ <tr>
+ <td>credential</td>
+ <td><a href="#bytebase.v1.CredentialProof">CredentialProof</a></td>
+ <td></td>
+ <td><p> </p></td>
+ </tr>
+
</tbody>
</table>
@@ -15679,6 +15694,21 @@ Format: users/{email} </p></td>
exactly the set this version identifies, or nothing. </p></td>
</tr>
+ <tr>
+ <td>credential</td>
+ <td><a href="#bytebase.v1.CredentialProof">CredentialProof</a></td>
+ <td></td>
+ <td><p> </p></td>
+ </tr>
+
+ <tr>
+ <td>otp_code</td>
+ <td><a href="#string">string</a></td>
+ <td></td>
+ <td><p>Required for first-time enrollment, rejected otherwise. A *fresh* code,
+not the one EnableMFA took. </p></td>
+ </tr>
+
</tbody>
</table>
@@ -15710,6 +15740,53 @@ exactly the set this version identifies, or nothing. </p></td>
+ <h3 id="bytebase.v1.CredentialProof">CredentialProof</h3>
+ <p>One proof that the caller currently controls a credential on the account.</p><p>Exactly one field must be set; enforced in the handler.</p>
+
+
+ <table class="field-table">
+ <thead>
+ <tr><td>Field</td><td>Type</td><td>Label</td><td>Description</td></tr>
+ </thead>
+ <tbody>
+
+ <tr>
+ <td>current_password</td>
+ <td><a href="#string">string</a></td>
+ <td></td>
+ <td><p>The account&#39;s current password. Refused by a factor-touching method
+while a live MFA factor exists. </p></td>
+ </tr>
+
+ <tr>
+ <td>otp_code</td>
+ <td><a href="#string">string</a></td>
+ <td></td>
+ <td><p>A live code from the account&#39;s enrolled TOTP authenticator. </p></td>
+ </tr>
+
+ <tr>
+ <td>recovery_code</td>
+ <td><a href="#string">string</a></td>
+ <td></td>
+ <td><p>A single-use MFA recovery code. </p></td>
+ </tr>
+
+ <tr>
+ <td>email_code</td>
+ <td><a href="#string">string</a></td>
+ <td></td>
+ <td><p>A one-time code from RequestReauthCode. Bytebase Cloud only, and only
+while the account has no live MFA factor. </p></td>
+ </tr>
+
+ </tbody>
+ </table>
+
+
+
+
+
<h3 id="bytebase.v1.DeleteUserRequest">DeleteUserRequest</h3>
<p></p>
@@ -15753,6 +15830,14 @@ Format: users/{email} </p></td>
bb.users.update. </p></td>
</tr>
+ <tr>
+ <td>credential</td>
+ <td><a href="#bytebase.v1.CredentialProof">CredentialProof</a></td>
+ <td></td>
+ <td><p>Required for a self-service call against a live factor, and then only
+otp_code or recovery_code. Unused on an admin-assisted call. </p></td>
+ </tr>
+
</tbody>
</table>
@@ -15791,6 +15876,14 @@ bb.users.update. </p></td>
<td><p>The pending_version this enrollment was minted with. </p></td>
</tr>
+ <tr>
+ <td>credential</td>
+ <td><a href="#bytebase.v1.CredentialProof">CredentialProof</a></td>
+ <td></td>
+ <td><p>Proof of the *existing* factor, not the new device above. Required for a
+rotation, and for first-time enrollment on an account with a password. </p></td>
+ </tr>
+
</tbody>
</table>
@@ -15980,6 +16073,30 @@ If this field is omitted, there are no subsequent pages. </p></td>
+ <h3 id="bytebase.v1.RequestReauthCodeRequest">RequestReauthCodeRequest</h3>
+ <p></p>
+
+
+ <table class="field-table">
+ <thead>
+ <tr><td>Field</td><td>Type</td><td>Label</td><td>Description</td></tr>
+ </thead>
+ <tbody>
+
+ <tr>
+ <td>name</td>
+ <td><a href="#string">string</a></td>
+ <td></td>
+ <td><p>Format: users/{email}. Must be the caller&#39;s own name. </p></td>
+ </tr>
+
+ </tbody>
+ </table>
+
+
+
+
+
<h3 id="bytebase.v1.StartMFAEnrollmentRequest">StartMFAEnrollmentRequest</h3>
<p></p>
@@ -16374,6 +16491,17 @@ Permissions required: bb.users.undelete</p></td>
Permissions required: bb.users.updateEmail</p></td>
</tr>
+ <tr>
+ <td>RequestReauthCode</td>
+ <td><a href="#bytebase.v1.RequestReauthCodeRequest">RequestReauthCodeRequest</a></td>
+ <td><a href="#google.protobuf.Empty">.google.protobuf.Empty</a></td>
+ <td><p>Sends a one-time code to the caller&#39;s own email, usable as
+CredentialProof.email_code. Bytebase Cloud only, and only while the
+account has no live MFA factor. Not AuthService.SendEmailLoginCode: that
+one starts a session, this one proves an existing one.
+Permissions required: None beyond being signed in as `name`.</p></td>
+ </tr>
+
<tr>
<td>ChangePassword</td>
<td><a href="#bytebase.v1.ChangePasswordRequest">ChangePasswordRequest</a></td>
@@ -16550,6 +16678,16 @@ Permissions required: None beyond being signed in as `name`.</p></td>
+ <tr>
+ <td>RequestReauthCode</td>
+ <td>POST</td>
+ <td>/v1/{name=users/*}:requestReauthCode</td>
+ <td>*</td>
+ </tr>
+
+
+
+
<tr>
<td>ChangePassword</td>
<td>POST</td>
@@ -17316,6 +17454,8 @@ The user must be a member of the target workspace.</p></td>
<td><a href="#google.protobuf.Empty">.google.protobuf.Empty</a></td>
<td><p>Requests a password reset email for the given email address.
Always returns success to avoid leaking whether the email exists.
+Requires the workspace&#39;s SMTP mail delivery setting; without it the
+recovery route is an admin password reset.
Permissions required: None</p></td>
</tr>
@@ -17333,6 +17473,8 @@ Permissions required: None (validates via token)</p></td>
<td><a href="#google.protobuf.Empty">.google.protobuf.Empty</a></td>
<td><p>Sends a 6-digit verification code to the email for login/signup.
Always returns success (no email enumeration). Enforces 60-sec resend cooldown.
+The signed-in counterpart is UserService.RequestReauthCode; LOGIN and
+REAUTH codes are not interchangeable.
Permissions required: None</p></td>
</tr>
diff --git a/proto/store/store/auth.proto b/proto/store/store/auth.proto
index 3acff6fc75..38d61a3dd2 100644
--- a/proto/store/store/auth.proto
+++ b/proto/store/store/auth.proto
@@ -10,6 +10,9 @@ enum EmailVerificationCodePurpose {
EMAIL_VERIFICATION_CODE_PURPOSE_UNSPECIFIED = 0;
LOGIN = 1;
PASSWORD_RESET = 2;
+ // Re-authentication proof for a credential change
+ // (CredentialProof.email_code). Never accepted by Login.
+ REAUTH = 3;
}
// LoginAttemptKind names which credential's attempt limit a login_attempt row
diff --git a/proto/v1/v1/annotation.proto b/proto/v1/v1/annotation.proto
index 88b6f55803..d93e5501ca 100644
--- a/proto/v1/v1/annotation.proto
+++ b/proto/v1/v1/annotation.proto
@@ -135,7 +135,7 @@ enum MCPDenialReason {
// Puts a token for the caller's own principal in the response body.
MINTS_CREDENTIAL = 1;
// Drives the out-of-band reset flow that sets or delivers the secret a
- // login accepts.
+ // login or a credential change accepts.
RESETS_CREDENTIAL = 2;
// Rewrites an account's own credentials, which would let the session log in
// as that account.
diff --git a/proto/v1/v1/auth_service.proto b/proto/v1/v1/auth_service.proto
index 5e8d423a29..7d9ae33686 100644
--- a/proto/v1/v1/auth_service.proto
+++ b/proto/v1/v1/auth_service.proto
@@ -113,6 +113,8 @@ service AuthService {
// Requests a password reset email for the given email address.
// Always returns success to avoid leaking whether the email exists.
+ // Requires the workspace's SMTP mail delivery setting; without it the
+ // recovery route is an admin password reset.
// Permissions required: None
rpc RequestPasswordReset(RequestPasswordResetRequest) returns (google.protobuf.Empty) {
option (google.api.http) = {
@@ -140,6 +142,8 @@ service AuthService {
// Sends a 6-digit verification code to the email for login/signup.
// Always returns success (no email enumeration). Enforces 60-sec resend cooldown.
+ // The signed-in counterpart is UserService.RequestReauthCode; LOGIN and
+ // REAUTH codes are not interchangeable.
// Permissions required: None
rpc SendEmailLoginCode(SendEmailLoginCodeRequest) returns (google.protobuf.Empty) {
option (google.api.http) = {
diff --git a/proto/v1/v1/user_service.proto b/proto/v1/v1/user_service.proto
index c380d9eb30..9e8a75875a 100644
--- a/proto/v1/v1/user_service.proto
+++ b/proto/v1/v1/user_service.proto
@@ -131,6 +131,23 @@ service UserService {
option (bytebase.v1.mcp_denial_reason) = MINTS_CREDENTIAL_FOR_OTHERS;
}
+ // Sends a one-time code to the caller's own email, usable as
+ // CredentialProof.email_code. Bytebase Cloud only, and only while the
+ // account has no live MFA factor. Not AuthService.SendEmailLoginCode: that
+ // one starts a session, this one proves an existing one.
+ // Permissions required: None beyond being signed in as `name`.
+ rpc RequestReauthCode(RequestReauthCodeRequest) returns (google.protobuf.Empty) {
+ option (google.api.http) = {
+ post: "/v1/{name=users/*}:requestReauthCode"
+ body: "*"
+ };
+ option (google.api.method_signature) = "name";
+ option (bytebase.v1.auth_method) = CUSTOM;
+ option (bytebase.v1.audit) = true;
+ option (bytebase.v1.mcp_method_class) = FORBIDDEN;
+ option (bytebase.v1.mcp_denial_reason) = RESETS_CREDENTIAL;
+ }
+
// Changes the caller's own password. An administrator resetting someone
// else's password uses UpdateUser with the `password` mask instead — that
// is a different operation with a different audit story, even though both
@@ -364,6 +381,47 @@ message UpdateEmailRequest {
];
}
+// One proof that the caller currently controls a credential on the account.
+// Exactly one field must be set; enforced in the handler.
+message CredentialProof {
+ oneof proof {
+ // The account's current password. Refused by a factor-touching method
+ // while a live MFA factor exists.
+ string current_password = 1 [
+ (bytebase.v1.audit_behavior) = SENSITIVE,
+ (buf.validate.field).string.max_bytes = 72
+ ];
+
+ // A live code from the account's enrolled TOTP authenticator.
+ string otp_code = 2 [
+ (bytebase.v1.audit_behavior) = SENSITIVE,
+ (buf.validate.field).string.max_len = 64
+ ];
+
+ // A single-use MFA recovery code.
+ string recovery_code = 3 [
+ (bytebase.v1.audit_behavior) = SENSITIVE,
+ (buf.validate.field).string.max_len = 64
+ ];
+
+ // A one-time code from RequestReauthCode. Bytebase Cloud only, and only
+ // while the account has no live MFA factor.
+ string email_code = 4 [
+ (bytebase.v1.audit_behavior) = SENSITIVE,
+ (buf.validate.field).string.max_len = 64
+ ];
+ }
+}
+
+message RequestReauthCodeRequest {
+ // Format: users/{email}. Must be the caller's own name.
+ string name = 1 [
+ (google.api.field_behavior) = REQUIRED,
+ (google.api.resource_reference) = {type: "bytebase.com/User"},
+ (buf.validate.field).string.max_len = 260
+ ];
+}
+
message ChangePasswordRequest {
// Format: users/{email}. Must be the caller's own name.
string name = 1 [
@@ -377,6 +435,11 @@ message ChangePasswordRequest {
(bytebase.v1.audit_behavior) = SENSITIVE,
(buf.validate.field).string.max_bytes = 72
];
+
+ CredentialProof credential = 3 [
+ (google.api.field_behavior) = REQUIRED,
+ (buf.validate.field).required = true
+ ];
}
message StartMFAEnrollmentRequest {
@@ -426,6 +489,10 @@ message EnableMFARequest {
(google.api.field_behavior) = REQUIRED,
(buf.validate.field).required = true
];
+
+ // Proof of the *existing* factor, not the new device above. Required for a
+ // rotation, and for first-time enrollment on an account with a password.
+ CredentialProof credential = 4 [(google.api.field_behavior) = OPTIONAL];
}
message DisableMFARequest {
@@ -436,6 +503,10 @@ message DisableMFARequest {
(google.api.resource_reference) = {type: "bytebase.com/User"},
(buf.validate.field).string.max_len = 260
];
+
+ // Required for a self-service call against a live factor, and then only
+ // otp_code or recovery_code. Unused on an admin-assisted call.
+ CredentialProof credential = 2 [(google.api.field_behavior) = OPTIONAL];
}
message RegenerateRecoveryCodesRequest {
@@ -469,6 +540,19 @@ message ConfirmRecoveryCodesRequest {
(google.api.field_behavior) = REQUIRED,
(buf.validate.field).required = true
];
+
+ CredentialProof credential = 3 [
+ (google.api.field_behavior) = REQUIRED,
+ (buf.validate.field).required = true
+ ];
+
+ // Required for first-time enrollment, rejected otherwise. A *fresh* code,
+ // not the one EnableMFA took.
+ string otp_code = 4 [
+ (google.api.field_behavior) = OPTIONAL,
+ (bytebase.v1.audit_behavior) = SENSITIVE,
+ (buf.validate.field).string.max_len = 64
+ ];
}
message User {