Skip to content

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

refactor(api): move password and MFA changes onto their own methods (#21252)

Danny Xuffe660e8fe72
diff --git a/backend/api/mcp/gen/openapi.yaml b/backend/api/mcp/gen/openapi.yaml
index 916cfa1b79..ca2e007f27 100644
--- a/backend/api/mcp/gen/openapi.yaml
+++ b/backend/api/mcp/gen/openapi.yaml
@@ -7151,6 +7151,87 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/bytebase.v1.BatchGetUsersResponse'
+ /bytebase.v1.UserService/ChangePassword:
+ post:
+ tags:
+ - bytebase.v1.UserService
+ summary: ChangePassword
+ description: |-
+ 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
+ end in a new password hash.
+ Permissions required: None beyond being signed in as `name`.
+ operationId: bytebase.v1.UserService.ChangePassword
+ 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.ChangePasswordRequest'
+ 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/bytebase.v1.User'
+ /bytebase.v1.UserService/ConfirmRecoveryCodes:
+ post:
+ tags:
+ - bytebase.v1.UserService
+ summary: ConfirmRecoveryCodes
+ description: |-
+ Promotes the pending recovery codes. During first-time enrollment this is
+ also where the pending TOTP secret goes live, so the factor and the codes
+ that recover it start existing in the same write.
+ Permissions required: None beyond being signed in as `name`.
+ operationId: bytebase.v1.UserService.ConfirmRecoveryCodes
+ 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.ConfirmRecoveryCodesRequest'
+ 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/bytebase.v1.User'
/bytebase.v1.UserService/CreateUser:
post:
tags:
@@ -7228,6 +7309,91 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/google.protobuf.Empty'
+ /bytebase.v1.UserService/DisableMFA:
+ post:
+ tags:
+ - bytebase.v1.UserService
+ summary: DisableMFA
+ description: |-
+ Turns MFA off, clearing the entire MFA config — live and pending state
+ alike. Callers may disable their own; an administrator may disable
+ another user's with bb.users.update, which is how a locked-out user is
+ recovered.
+ Permissions required: bb.users.update, unless `name` is the caller's own.
+ operationId: bytebase.v1.UserService.DisableMFA
+ 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.DisableMFARequest'
+ 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/bytebase.v1.User'
+ /bytebase.v1.UserService/EnableMFA:
+ post:
+ tags:
+ - bytebase.v1.UserService
+ summary: EnableMFA
+ description: |-
+ 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.
+ operationId: bytebase.v1.UserService.EnableMFA
+ 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.EnableMFARequest'
+ 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/bytebase.v1.User'
/bytebase.v1.UserService/GetCurrentUser:
post:
tags:
@@ -7344,6 +7510,86 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/bytebase.v1.ListUsersResponse'
+ /bytebase.v1.UserService/RegenerateRecoveryCodes:
+ post:
+ tags:
+ - bytebase.v1.UserService
+ summary: RegenerateRecoveryCodes
+ description: |-
+ Mints a pending recovery-code set beside the live one and returns it.
+ The old codes keep working until ConfirmRecoveryCodes promotes these, so
+ a caller who closes the page mid-way is not left without any.
+ Permissions required: None beyond being signed in as `name`.
+ operationId: bytebase.v1.UserService.RegenerateRecoveryCodes
+ 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.RegenerateRecoveryCodesRequest'
+ 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/bytebase.v1.RegenerateRecoveryCodesResponse'
+ /bytebase.v1.UserService/StartMFAEnrollment:
+ post:
+ tags:
+ - bytebase.v1.UserService
+ summary: StartMFAEnrollment
+ description: |-
+ Mints a pending TOTP secret and recovery codes for the caller'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`.
+ operationId: bytebase.v1.UserService.StartMFAEnrollment
+ 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.StartMFAEnrollmentRequest'
+ 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/bytebase.v1.StartMFAEnrollmentResponse'
/bytebase.v1.UserService/UndeleteUser:
post:
tags:
@@ -9652,6 +9898,21 @@ components:
description: Optional free-form comment. Max 500 chars (Stripe limit).
title: CancelPurchaseRequest
additionalProperties: false
+ bytebase.v1.ChangePasswordRequest:
+ type: object
+ properties:
+ name:
+ type: string
+ title: name
+ maxLength: 260
+ description: 'Format: users/{email}. Must be the caller''s own name.'
+ newPassword:
+ type: string
+ title: new_password
+ description: |
+ string.max_bytes = 72
+ title: ChangePasswordRequest
+ additionalProperties: false
bytebase.v1.Changelog:
type: object
properties:
@@ -10020,6 +10281,24 @@ components:
description: The comment describing the composite type.
title: CompositeTypeMetadata
additionalProperties: false
+ bytebase.v1.ConfirmRecoveryCodesRequest:
+ type: object
+ properties:
+ name:
+ type: string
+ title: name
+ maxLength: 260
+ description: 'Format: users/{email}. Must be the caller''s own name.'
+ pendingVersion:
+ title: pending_version
+ description: |-
+ The pending_version of the codes being confirmed. Confirming promotes
+ exactly the set this version identifies, or nothing.
+ $ref: '#/components/schemas/google.protobuf.Timestamp'
+ title: ConfirmRecoveryCodesRequest
+ required:
+ - pendingVersion
+ additionalProperties: false
bytebase.v1.CreateAccessGrantRequest:
type: object
properties:
@@ -11553,6 +11832,18 @@ components:
title: DimensionalConfig
additionalProperties: false
description: DimensionalConfig defines dimensional and constraint parameters for spatial indexes.
+ bytebase.v1.DisableMFARequest:
+ type: object
+ properties:
+ name:
+ type: string
+ title: name
+ maxLength: 260
+ description: |-
+ Format: users/{email}. The caller's own, or another user's with
+ bb.users.update.
+ title: DisableMFARequest
+ additionalProperties: false
bytebase.v1.EmailSetting:
type: object
allOf:
@@ -11624,6 +11915,27 @@ components:
enum:
- TYPE_UNSPECIFIED
- SMTP
+ bytebase.v1.EnableMFARequest:
+ type: object
+ properties:
+ name:
+ type: string
+ title: name
+ maxLength: 260
+ description: 'Format: users/{email}. Must be the caller''s own name.'
+ otpCode:
+ type: string
+ title: otp_code
+ maxLength: 64
+ description: A code from the authenticator the pending secret was just added to.
+ pendingVersion:
+ title: pending_version
+ description: The pending_version this enrollment was minted with.
+ $ref: '#/components/schemas/google.protobuf.Timestamp'
+ title: EnableMFARequest
+ required:
+ - pendingVersion
+ additionalProperties: false
bytebase.v1.Engine:
type: string
title: Engine
@@ -17208,6 +17520,31 @@ components:
title: RefreshResponse
additionalProperties: false
description: Response from refreshing the access token.
+ bytebase.v1.RegenerateRecoveryCodesRequest:
+ type: object
+ properties:
+ name:
+ type: string
+ title: name
+ maxLength: 260
+ description: 'Format: users/{email}. Must be the caller''s own name.'
+ title: RegenerateRecoveryCodesRequest
+ additionalProperties: false
+ bytebase.v1.RegenerateRecoveryCodesResponse:
+ type: object
+ properties:
+ recoveryCodes:
+ type: array
+ items:
+ type: string
+ title: recovery_codes
+ description: The pending recovery codes, shown once for the caller to save.
+ pendingVersion:
+ title: pending_version
+ description: Identifies this mint; see StartMFAEnrollmentResponse.pending_version.
+ $ref: '#/components/schemas/google.protobuf.Timestamp'
+ title: RegenerateRecoveryCodesResponse
+ additionalProperties: false
bytebase.v1.RejectIssueRequest:
type: object
properties:
@@ -19308,6 +19645,45 @@ components:
description: The tasks within this stage.
title: Stage
additionalProperties: false
+ bytebase.v1.StartMFAEnrollmentRequest:
+ type: object
+ properties:
+ name:
+ type: string
+ title: name
+ maxLength: 260
+ description: 'Format: users/{email}. Must be the caller''s own name.'
+ title: StartMFAEnrollmentRequest
+ additionalProperties: false
+ bytebase.v1.StartMFAEnrollmentResponse:
+ type: object
+ properties:
+ otpSecret:
+ type: string
+ title: otp_secret
+ description: |-
+ The pending TOTP secret. The only response that carries it — it is never
+ readable from the User resource.
+ recoveryCodes:
+ type: array
+ items:
+ type: string
+ title: recovery_codes
+ description: The pending recovery codes, shown once for the caller to save.
+ expireTime:
+ title: expire_time
+ description: When this enrollment stops being confirmable.
+ $ref: '#/components/schemas/google.protobuf.Timestamp'
+ pendingVersion:
+ title: pending_version
+ description: |-
+ Identifies this mint. Echo it back to EnableMFA and
+ ConfirmRecoveryCodes; a mint from another tab or device replaces the
+ pending state, and those methods refuse a version that is no longer the
+ pending one rather than promoting something this caller never saw.
+ $ref: '#/components/schemas/google.protobuf.Timestamp'
+ title: StartMFAEnrollmentResponse
+ additionalProperties: false
bytebase.v1.State:
type: string
title: State
@@ -21350,22 +21726,6 @@ components:
title: update_mask
description: The list of fields to update.
$ref: '#/components/schemas/google.protobuf.FieldMask'
- otpCode:
- type:
- - string
- - "null"
- title: otp_code
- description: The otp_code is used to verify the user's identity by MFA.
- regenerateTempMfaSecret:
- type: boolean
- title: regenerate_temp_mfa_secret
- description: |-
- The regenerate_temp_mfa_secret flag means to regenerate temporary MFA secret for user.
- This is used for MFA setup. The temporary MFA secret and recovery codes will be returned in the response.
- regenerateRecoveryCodes:
- type: boolean
- title: regenerate_recovery_codes
- description: The regenerate_recovery_codes flag means to regenerate recovery codes for user.
allowMissing:
type: boolean
title: allow_missing
@@ -21464,21 +21824,9 @@ components:
mfaEnabled:
type: boolean
title: mfa_enabled
- description: The mfa_enabled flag means if the user has enabled MFA.
- tempOtpSecret:
- type: string
- title: temp_otp_secret
- description: Temporary OTP secret used during MFA setup and regeneration.
- tempRecoveryCodes:
- type: array
- items:
- type: string
- title: temp_recovery_codes
- description: Temporary recovery codes used during MFA setup and regeneration.
- tempOtpSecretCreatedTime:
- title: temp_otp_secret_created_time
- description: Timestamp when temp_otp_secret was created. Used by frontend to show countdown timer.
- $ref: '#/components/schemas/google.protobuf.Timestamp'
+ description: |-
+ Whether the user has a live MFA factor. Set by ConfirmRecoveryCodes and
+ DisableMFA, never by an update.
phone:
type: string
title: phone
diff --git a/backend/api/v1/audit_redact_inventory_test.go b/backend/api/v1/audit_redact_inventory_test.go
index 1d93c661bb..73e437fd37 100644
--- a/backend/api/v1/audit_redact_inventory_test.go
+++ b/backend/api/v1/audit_redact_inventory_test.go
@@ -295,6 +295,7 @@ var auditRecordedFields = []string{
"bytebase.v1.CancelPlanCheckRunRequest.name",
"bytebase.v1.CancelPurchaseRequest.comment",
"bytebase.v1.CancelPurchaseRequest.feedback",
+ "bytebase.v1.ChangePasswordRequest.name",
"bytebase.v1.Changelog.name",
"bytebase.v1.Changelog.plan_title",
"bytebase.v1.Changelog.schema",
@@ -324,6 +325,7 @@ var auditRecordedFields = []string{
"bytebase.v1.CompositeTypeAttribute.type",
"bytebase.v1.CompositeTypeMetadata.comment",
"bytebase.v1.CompositeTypeMetadata.name",
+ "bytebase.v1.ConfirmRecoveryCodesRequest.name",
"bytebase.v1.CreateAccessGrantRequest.parent",
"bytebase.v1.CreateDatabaseGroupRequest.database_group_id",
"bytebase.v1.CreateDatabaseGroupRequest.parent",
@@ -429,10 +431,12 @@ var auditRecordedFields = []string{
"bytebase.v1.DiffSchemaResponse.diff",
"bytebase.v1.DimensionConstraint.dimension",
"bytebase.v1.DimensionalConfig.data_type",
+ "bytebase.v1.DisableMFARequest.name",
"bytebase.v1.EmailSetting.SMTPConfig.host",
"bytebase.v1.EmailSetting.SMTPConfig.username",
"bytebase.v1.EmailSetting.from",
"bytebase.v1.EmailSetting.from_name",
+ "bytebase.v1.EnableMFARequest.name",
"bytebase.v1.EnumTypeMetadata.comment",
"bytebase.v1.EnumTypeMetadata.name",
"bytebase.v1.EnumTypeMetadata.values",
@@ -788,6 +792,7 @@ var auditRecordedFields = []string{
"bytebase.v1.QueryResult.column_type_names",
"bytebase.v1.QueryResult.error",
"bytebase.v1.QueryResult.statement",
+ "bytebase.v1.RegenerateRecoveryCodesRequest.name",
"bytebase.v1.RejectIssueRequest.comment",
"bytebase.v1.RejectIssueRequest.name",
"bytebase.v1.Release.File.path",
@@ -912,6 +917,7 @@ var auditRecordedFields = []string{
"bytebase.v1.Stage.environment",
"bytebase.v1.Stage.id",
"bytebase.v1.Stage.name",
+ "bytebase.v1.StartMFAEnrollmentRequest.name",
"bytebase.v1.StorageConfig.buffering",
"bytebase.v1.StorageConfig.data_compression",
"bytebase.v1.StorageConfig.sort_in_tempdb",
diff --git a/backend/api/v1/audit_redact_test.go b/backend/api/v1/audit_redact_test.go
index 39c5399f1d..79573d4f72 100644
--- a/backend/api/v1/audit_redact_test.go
+++ b/backend/api/v1/audit_redact_test.go
@@ -180,9 +180,19 @@ func TestAuditRowKeepsItsSubstance(t *testing.T) {
},
{
// A failed validation neither consumes the code nor suppresses the
- // row, so this used to write a still-live OTP.
+ // 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]"},
+ },
+ {
+ 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: "user update retains who was updated",
- value: &v1pb.UpdateUserRequest{User: &v1pb.User{Name: "users/[email protected]"}, OtpCode: &otpCode},
+ value: &v1pb.UpdateUserRequest{User: &v1pb.User{Name: "users/[email protected]"}},
want: []string{"users/[email protected]"},
},
{
diff --git a/backend/api/v1/mcp_gate_test.go b/backend/api/v1/mcp_gate_test.go
index 739cdb6210..b035208d0e 100644
--- a/backend/api/v1/mcp_gate_test.go
+++ b/backend/api/v1/mcp_gate_test.go
@@ -127,6 +127,12 @@ func TestForbiddenClassMembership(t *testing.T) {
v1connect.IssueServiceApproveIssueProcedure,
v1connect.IssueServiceRejectIssueProcedure,
v1connect.IssueServiceRetryIssueApprovalProcedure,
+ v1connect.UserServiceChangePasswordProcedure,
+ v1connect.UserServiceStartMFAEnrollmentProcedure,
+ v1connect.UserServiceEnableMFAProcedure,
+ v1connect.UserServiceDisableMFAProcedure,
+ v1connect.UserServiceRegenerateRecoveryCodesProcedure,
+ v1connect.UserServiceConfirmRecoveryCodesProcedure,
}
got := forbiddenProceduresFromDescriptors(t)
@@ -160,6 +166,12 @@ func TestForbiddenClassMembership(t *testing.T) {
v1connect.WorkspaceServiceRotateDirectorySyncTokenProcedure: v1pb.MCPDenialReason_MINTS_CREDENTIAL_FOR_OTHERS,
v1connect.UserServiceCreateUserProcedure: v1pb.MCPDenialReason_MINTS_CREDENTIAL_FOR_OTHERS,
v1connect.UserServiceUpdateEmailProcedure: v1pb.MCPDenialReason_MINTS_CREDENTIAL_FOR_OTHERS,
+ v1connect.UserServiceChangePasswordProcedure: v1pb.MCPDenialReason_TAKES_OVER_ACCOUNT,
+ v1connect.UserServiceStartMFAEnrollmentProcedure: v1pb.MCPDenialReason_MINTS_CREDENTIAL,
+ v1connect.UserServiceEnableMFAProcedure: v1pb.MCPDenialReason_TAKES_OVER_ACCOUNT,
+ v1connect.UserServiceDisableMFAProcedure: v1pb.MCPDenialReason_TAKES_OVER_ACCOUNT,
+ v1connect.UserServiceRegenerateRecoveryCodesProcedure: v1pb.MCPDenialReason_MINTS_CREDENTIAL,
+ v1connect.UserServiceConfirmRecoveryCodesProcedure: v1pb.MCPDenialReason_TAKES_OVER_ACCOUNT,
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 2d771f2cbc..e672831213 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 | 86 | served by no ceiling this phase ships |
-| FORBIDDEN | 28 | never served, whatever the ceiling |
+| FORBIDDEN | 34 | never served, whatever the ceiling |
| MCP_METHOD_CLASS_UNSPECIFIED | 0 | unclassified — CI rejects this, and the gate refuses it |
-| **total** | **211** | |
+| **total** | **217** | |
| Method | Class | Reason | Permission |
|---|---|---|---|
@@ -213,11 +213,17 @@ served by no ceiling.
| SubscriptionService/UploadLicense | EXCLUDED | ADMINISTERS_THE_WORKSPACE | bb.subscription.manage |
| SubscriptionService/VerifyCheckoutSession | EXCLUDED | ADMINISTERS_THE_WORKSPACE | bb.subscription.manage |
| UserService/BatchGetUsers | EXCLUDED | ADMINISTERS_THE_WORKSPACE | bb.users.get |
+| UserService/ChangePassword | FORBIDDEN | TAKES_OVER_ACCOUNT | — |
+| UserService/ConfirmRecoveryCodes | FORBIDDEN | TAKES_OVER_ACCOUNT | — |
| UserService/CreateUser | FORBIDDEN | MINTS_CREDENTIAL_FOR_OTHERS | bb.users.create |
| UserService/DeleteUser | EXCLUDED | ADMINISTERS_THE_WORKSPACE | — |
+| UserService/DisableMFA | FORBIDDEN | TAKES_OVER_ACCOUNT | — |
+| UserService/EnableMFA | FORBIDDEN | TAKES_OVER_ACCOUNT | — |
| UserService/GetCurrentUser | READ | — | — |
| UserService/GetUser | EXCLUDED | ADMINISTERS_THE_WORKSPACE | bb.users.get |
| UserService/ListUsers | EXCLUDED | ADMINISTERS_THE_WORKSPACE | bb.users.list |
+| UserService/RegenerateRecoveryCodes | FORBIDDEN | MINTS_CREDENTIAL | — |
+| UserService/StartMFAEnrollment | FORBIDDEN | MINTS_CREDENTIAL | — |
| UserService/UndeleteUser | EXCLUDED | ADMINISTERS_THE_WORKSPACE | — |
| UserService/UpdateEmail | FORBIDDEN | MINTS_CREDENTIAL_FOR_OTHERS | bb.users.updateEmail |
| UserService/UpdateUser | FORBIDDEN | TAKES_OVER_ACCOUNT | — |
diff --git a/backend/api/v1/user_service.go b/backend/api/v1/user_service.go
index 036959aedd..54c754dfac 100644
--- a/backend/api/v1/user_service.go
+++ b/backend/api/v1/user_service.go
@@ -372,43 +372,19 @@ func (s *UserService) UpdateUser(ctx context.Context, request *connect.Request[v
if user.Type != storepb.PrincipalType_END_USER {
return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("password can be mutated for end users only"))
}
+ 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 err := s.validatePassword(ctx, common.GetWorkspaceIDFromContext(ctx), request.Msg.User.Password); err != nil {
return nil, err
}
passwordPatch = &request.Msg.User.Password
case "mfa_enabled":
- if request.Msg.User.MfaEnabled {
- if user.MFAConfig.TempOtpSecret == "" || len(user.MFAConfig.TempRecoveryCodes) == 0 {
- return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("MFA is not setup yet"))
- }
- if isMFATempSecretExpired(user.MFAConfig) {
- return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("MFA setup has expired, please regenerate the temporary secret"))
- }
- // Promote temp secrets to permanent and clear temp fields to prevent reuse
- patch.MFAConfig = &storepb.MFAConfig{
- OtpSecret: user.MFAConfig.TempOtpSecret,
- RecoveryCodes: user.MFAConfig.TempRecoveryCodes,
- TempOtpSecret: "",
- TempRecoveryCodes: nil,
- TempOtpSecretCreatedTime: nil,
- }
- } else {
- setting, err := s.store.GetWorkspaceProfileSetting(ctx, common.GetWorkspaceIDFromContext(ctx))
- if err != nil {
- return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to find workspace setting"))
- }
- if setting.Require_2Fa {
- isWorkspaceAdmin, err := isUserWorkspaceAdmin(ctx, s.store, callerUser, common.GetWorkspaceIDFromContext(ctx))
- if err != nil {
- return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to check user roles"))
- }
- // Allow workspace admin to disable 2FA even if it is required.
- if !isWorkspaceAdmin {
- return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("2FA is required and cannot be disabled"))
- }
- }
- patch.MFAConfig = &storepb.MFAConfig{}
- }
+ // 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"))
case "phone":
if request.Msg.User.Phone != "" {
if err := common.ValidatePhone(request.Msg.User.Phone); err != nil {
@@ -437,69 +413,12 @@ 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))
}
}
- // This flag is mainly used for validating OTP code when user setup MFA.
- // We only validate OTP code but not update user.
- if request.Msg.OtpCode != nil {
- if isMFATempSecretExpired(user.MFAConfig) {
- return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("MFA setup has expired, please regenerate the temporary secret"))
- }
- isValid := totp.Validate(*request.Msg.OtpCode, user.MFAConfig.TempOtpSecret)
- if !isValid {
- return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("invalid OTP code"))
- }
- }
- // This flag will regenerate temp secret and temp recovery codes.
- // It will be used when user setup MFA and regenerating recovery codes.
- if request.Msg.RegenerateTempMfaSecret {
- tempSecret, err := generateRandSecret(user.Email)
- if err != nil {
- return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to generate MFA secret"))
- }
- tempRecoveryCodes, err := generateRecoveryCodes(10)
- if err != nil {
- return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to generate recovery codes"))
- }
- patch.MFAConfig = &storepb.MFAConfig{
- TempOtpSecret: tempSecret,
- TempRecoveryCodes: tempRecoveryCodes,
- TempOtpSecretCreatedTime: timestamppb.Now(),
- }
- if user.MFAConfig != nil {
- patch.MFAConfig.OtpSecret = user.MFAConfig.OtpSecret
- patch.MFAConfig.RecoveryCodes = user.MFAConfig.RecoveryCodes
- }
- }
- // This flag will update user's recovery codes with temp recovery codes.
- // It will be used when user regenerate recovery codes after two phase commit.
- if request.Msg.RegenerateRecoveryCodes {
- if user.MFAConfig.OtpSecret == "" {
- return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("MFA is not enabled"))
- }
- if len(user.MFAConfig.TempRecoveryCodes) == 0 {
- return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("No recovery codes to update"))
- }
- patch.MFAConfig = &storepb.MFAConfig{
- OtpSecret: user.MFAConfig.OtpSecret,
- RecoveryCodes: user.MFAConfig.TempRecoveryCodes,
- }
- }
-
user, err = s.store.UpdateUser(ctx, user, patch)
if err != nil {
return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to update user"))
}
- // Only the two requests that drive MFA enrollment answer with the
- // enrollment secrets. regenerate_temp_mfa_secret mints them, and the
- // otp_code verification is the step the console moves to the recovery-code
- // screen from, reading the codes out of that response. A title, phone or
- // password update happening to land inside an open enrollment window has no
- // business carrying a TOTP seed back.
- convertResponse := convertToUser
- if request.Msg.RegenerateTempMfaSecret || request.Msg.OtpCode != nil {
- convertResponse = convertToUserMintingMFAEnrollment
- }
- userResponse, err := convertResponse(ctx, s.iamManager, user)
+ userResponse, err := convertToUser(ctx, s.iamManager, user)
if err != nil {
return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to convert user"))
}
@@ -717,6 +636,283 @@ func (s *UserService) UpdateEmail(ctx context.Context, request *connect.Request[
// 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.
+//
+// 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.
+
+// ChangePassword changes the caller's own password.
+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"))
+ }
+ 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)
+ 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})
+ if err != nil {
+ return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to update user"))
+ }
+ // Every session of this account, the caller's own included, has to be
+ // re-established with the new password.
+ 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))
+ }
+ 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.
+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 {
+ return nil, err
+ }
+ tempSecret, err := generateRandSecret(caller.Email)
+ if err != nil {
+ return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to generate MFA secret"))
+ }
+ tempRecoveryCodes, err := generateRecoveryCodes(10)
+ 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))
+
+ // 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 {
+ 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,
+ }), 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.
+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 {
+ return nil, err
+ }
+ if isMFATempSecretExpired(caller.MFAConfig) {
+ return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("MFA setup has expired, please restart the enrollment"))
+ }
+ if !totp.Validate(request.Msg.OtpCode, caller.MFAConfig.GetTempOtpSecret()) {
+ return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("invalid OTP code"))
+ }
+ 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.
+func (s *UserService) DisableMFA(ctx context.Context, request *connect.Request[v1pb.DisableMFARequest]) (*connect.Response[v1pb.User], error) {
+ callerUser, ok := GetUserFromContext(ctx)
+ if !ok {
+ return nil, connect.NewError(connect.CodePermissionDenied, errors.Errorf("failed to get caller user"))
+ }
+ email, err := common.GetUserEmail(request.Msg.Name)
+ if err != nil {
+ return nil, connect.NewError(connect.CodeInvalidArgument, err)
+ }
+ if err := validateEndUserEmail(email); err != nil {
+ return nil, err
+ }
+ user, err := s.store.GetUserByEmail(ctx, email)
+ if err != nil {
+ return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to get user"))
+ }
+ if user == nil || user.MemberDeleted {
+ return nil, connect.NewError(connect.CodeNotFound, errors.Errorf("user %q not found", email))
+ }
+
+ if callerUser.ID != user.ID {
+ // 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 {
+ return nil, connect.NewError(connect.CodePermissionDenied, errors.Errorf("updating other users is not allowed in SaaS mode"))
+ }
+ hasPermission, err := s.iamManager.CheckPermission(ctx, permission.UsersUpdate, callerUser, common.GetWorkspaceIDFromContext(ctx))
+ if err != nil {
+ return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to check permission with error: %v", err.Error()))
+ }
+ if !hasPermission {
+ return nil, connect.NewError(connect.CodePermissionDenied, errors.Errorf("user does not have permission %q", permission.UsersUpdate))
+ }
+ }
+
+ // A non-admin caller cannot turn MFA off while the workspace requires it,
+ // self-service or admin-assisted alike — unchanged from UpdateUser.
+ setting, err := s.store.GetWorkspaceProfileSetting(ctx, common.GetWorkspaceIDFromContext(ctx))
+ if err != nil {
+ return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to find workspace setting"))
+ }
+ if setting.Require_2Fa {
+ isWorkspaceAdmin, err := isUserWorkspaceAdmin(ctx, s.store, callerUser, common.GetWorkspaceIDFromContext(ctx))
+ if err != nil {
+ return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to check user roles"))
+ }
+ if !isWorkspaceAdmin {
+ return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("2FA is required and cannot be disabled"))
+ }
+ }
+
+ 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"))
+ }
+ 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.
+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))
+
+ // 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 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"))
+ }
+
+ return connect.NewResponse(&v1pb.RegenerateRecoveryCodesResponse{
+ RecoveryCodes: tempRecoveryCodes,
+ PendingVersion: version,
+ }), 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.
+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"))
+ }
+
+ mfaConfig := &storepb.MFAConfig{
+ OtpSecret: caller.MFAConfig.GetOtpSecret(),
+ RecoveryCodes: caller.MFAConfig.GetTempRecoveryCodes(),
+ }
+ // A pending secret means an enrollment — the account's first factor, or a
+ // replacement for the one it already has — and either way that secret is
+ // the one the caller just proved they can generate codes from, so it is
+ // the one that goes live. Only RegenerateRecoveryCodes leaves no pending
+ // secret, and only there does the live factor survive untouched.
+ if pendingSecret := caller.MFAConfig.GetTempOtpSecret(); pendingSecret != "" {
+ if isMFATempSecretExpired(caller.MFAConfig) {
+ return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("MFA setup has expired, please restart the enrollment"))
+ }
+ mfaConfig.OtpSecret = pendingSecret
+ } else if mfaConfig.OtpSecret == "" {
+ return nil, connect.NewError(connect.CodeFailedPrecondition, errors.Errorf("no MFA enrollment in progress, call StartMFAEnrollment first"))
+ }
+
+ // 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
+ // administrator just cleared.
+ 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"))
+ }
+ if user == nil {
+ return nil, errSupersededPendingMFAState
+ }
+ 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.
+func (*UserService) resolveSelfUser(ctx context.Context, name string) (*store.UserMessage, error) {
+ caller, ok := GetUserFromContext(ctx)
+ if !ok {
+ return nil, connect.NewError(connect.CodePermissionDenied, errors.Errorf("failed to get caller user"))
+ }
+ email, err := common.GetUserEmail(name)
+ if err != nil {
+ return nil, connect.NewError(connect.CodeInvalidArgument, err)
+ }
+ if err := validateEndUserEmail(email); err != nil {
+ return nil, err
+ }
+ if caller.Email != email {
+ return nil, connect.NewError(connect.CodePermissionDenied, errors.Errorf("name must be the caller's own account"))
+ }
+ return caller, nil
+}
+
+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 {
+ return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to convert user"))
+ }
+ return connect.NewResponse(v1User), nil
+}
+
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 {
@@ -741,54 +937,10 @@ func convertToUser(ctx context.Context, iamManager *iam.Manager, user *store.Use
if user.MFAConfig != nil {
convertedUser.MfaEnabled = user.MFAConfig.OtpSecret != ""
- // Only expose MFA enrollment state to the user themselves.
- if currentUser, ok := GetUserFromContext(ctx); ok && currentUser.ID == user.ID {
- // The created time is not a secret. It says an enrollment is open
- // and when it expires, which is what the console counts down from,
- // and it is what tells a client the two fields below are missing
- // because they were redacted rather than because there is nothing
- // to enroll.
- //
- // An expired enrollment is not an open one, so it does not come
- // back. Nothing clears the stored timestamp when the window runs
- // out — the two writes are a commit, which nils it, and a
- // regenerate, which moves it — so an abandoned setup would
- // otherwise keep answering "still open" forever, and a client
- // holding the secrets from it would go on holding them. The rule
- // for what counts as expired stays in isMFATempSecretExpired, the
- // same one that refuses to verify against a stale seed.
- if !isMFATempSecretExpired(user.MFAConfig) {
- convertedUser.TempOtpSecretCreatedTime = user.MFAConfig.TempOtpSecretCreatedTime
- }
- }
}
return convertedUser, nil
}
-// convertToUserMintingMFAEnrollment is that exception: UpdateUser generates the
-// temporary TOTP seed and recovery codes, and its response is the only place
-// the human ever sees them — the console renders the QR code and the
-// recovery-code list straight from it, and the server keeps no other way to
-// hand them over. UpdateUser is FORBIDDEN to MCP, so an intact response here
-// adds nothing an agent can reach.
-//
-// It adds the secrets exactly where the read exposed the created time, and asks
-// nothing else. The read already decided who may see this enrollment and
-// whether there is one: it sets the created time only when the subject is the
-// caller and the window is open. Re-deriving that here would be a second copy
-// of a rule that has to give the same answer.
-func convertToUserMintingMFAEnrollment(ctx context.Context, iamManager *iam.Manager, user *store.UserMessage) (*v1pb.User, error) {
- converted, err := convertToUser(ctx, iamManager, user)
- if err != nil {
- return nil, err
- }
- if converted.TempOtpSecretCreatedTime != nil {
- converted.TempOtpSecret = user.MFAConfig.TempOtpSecret
- converted.TempRecoveryCodes = user.MFAConfig.TempRecoveryCodes
- }
- return converted, nil
-}
-
func validateEndUserEmail(email string) error {
if common.IsServiceAccountEmail(email) {
return connect.NewError(connect.CodeInvalidArgument, errors.Errorf("email for end users cannot end with %v", common.ServiceAccountSuffix))
diff --git a/backend/api/v1/user_service_mfa_enrollment_test.go b/backend/api/v1/user_service_mfa_enrollment_test.go
deleted file mode 100644
index 6957cc4233..0000000000
--- a/backend/api/v1/user_service_mfa_enrollment_test.go
+++ /dev/null
@@ -1,160 +0,0 @@
-package v1
-
-import (
- "context"
- "fmt"
- "testing"
- "time"
-
- "github.com/stretchr/testify/require"
- "google.golang.org/protobuf/types/known/timestamppb"
-
- "github.com/bytebase/bytebase/backend/common"
- "github.com/bytebase/bytebase/backend/common/testcontainer"
- "github.com/bytebase/bytebase/backend/component/iam"
- storepb "github.com/bytebase/bytebase/backend/generated-go/store"
- "github.com/bytebase/bytebase/backend/migrator"
- "github.com/bytebase/bytebase/backend/store"
-)
-
-const mfaEnrollmentTestWorkspace = "mfa-enrollment-test"
-
-// newMFAEnrollmentFixture boots a migrated store with one workspace, because
-// convertToUser resolves the subject's groups through the IAM manager and that
-// needs somewhere real to look.
-func newMFAEnrollmentFixture(t *testing.T) (*store.Store, *iam.Manager) {
- 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))
- _, err := db.ExecContext(ctx, fmt.Sprintf(
- `INSERT INTO workspace (resource_id) VALUES ('%s')`, mfaEnrollmentTestWorkspace))
- require.NoError(t, err)
-
- pgURL := fmt.Sprintf(
- "host=%s port=%s user=postgres password=root-password database=postgres",
- container.GetHost(), container.GetPort(),
- )
- stores, err := store.New(ctx, pgURL, false)
- require.NoError(t, err)
- iamManager, err := iam.NewManager(stores, nil, false)
- require.NoError(t, err)
- return stores, iamManager
-}
-
-// TestConvertToUserWithholdsAnExpiredEnrollment covers the third way an MFA
-// enrollment window ends, and the only one nothing writes down.
-//
-// A commit nils temp_otp_secret_created_time and a regenerate moves it, so
-// either is visible to a client comparing what it holds against what it reads.
-// Expiry does neither: isMFATempSecretExpired decides it by comparing the
-// stored timestamp with the clock, and nothing clears the row. So a setup the
-// user abandoned would go on reporting an open window forever, and the console,
-// which carries the enrollment secrets across a refresh for exactly as long as
-// the window it holds is the window being read, would carry them forever with
-// it.
-//
-// The rule for what counts as expired is not duplicated to get this: the
-// converter asks the same function the OTP verification asks.
-func TestConvertToUserWithholdsAnExpiredEnrollment(t *testing.T) {
- ctx := context.Background()
- stores, iamManager := newMFAEnrollmentFixture(t)
-
- enrolling := func(t *testing.T, email string, age time.Duration) (context.Context, *store.UserMessage) {
- t.Helper()
- user, err := stores.CreateUser(ctx, &store.UserMessage{
- Email: email,
- Name: email,
- Type: storepb.PrincipalType_END_USER,
- })
- require.NoError(t, err)
-
- // CreateUser answers with an empty MFAConfig whatever it was handed, so
- // the enrollment has to be written as an update. Getting this wrong
- // makes every assertion below pass for the wrong reason: an empty
- // config reads as expired, so nothing is exposed and the test proves
- // nothing.
- user, err = stores.UpdateUser(ctx, user, &store.UpdateUserMessage{
- MFAConfig: &storepb.MFAConfig{
- TempOtpSecret: "SEEDTHECONSOLEISSHOWING",
- TempRecoveryCodes: []string{"code-1", "code-2"},
- TempOtpSecretCreatedTime: timestamppb.New(time.Now().Add(-age)),
- },
- })
- require.NoError(t, err)
- require.NotNil(t, user.MFAConfig.TempOtpSecretCreatedTime,
- "precondition: the enrollment has to be stored for this to be testing anything")
-
- // The subject has to be the caller: the enrollment is only ever exposed
- // to the person enrolling.
- selfCtx := context.WithValue(ctx, common.WorkspaceIDContextKey, mfaEnrollmentTestWorkspace)
- selfCtx = context.WithValue(selfCtx, common.UserContextKey, user)
- return selfCtx, user
- }
-
- t.Run("an open window reads back open, without its secrets", func(t *testing.T) {
- selfCtx, user := enrolling(t, "[email protected]", time.Minute)
-
- got, err := convertToUser(selfCtx, iamManager, user)
- require.NoError(t, err)
- require.NotNil(t, got.TempOtpSecretCreatedTime,
- "the console counts down from this and it is not a secret")
- require.Empty(t, got.TempOtpSecret)
- require.Empty(t, got.TempRecoveryCodes)
- })
-
- t.Run("and the request that mints it gets the secrets too", func(t *testing.T) {
- selfCtx, user := enrolling(t, "[email protected]", time.Minute)
-
- got, err := convertToUserMintingMFAEnrollment(selfCtx, iamManager, user)
- require.NoError(t, err)
- require.Equal(t, "SEEDTHECONSOLEISSHOWING", got.TempOtpSecret)
- require.Len(t, got.TempRecoveryCodes, 2)
- })
-
- t.Run("an expired window reads back as no window at all", func(t *testing.T) {
- selfCtx, user := enrolling(t, "[email protected]", 6*time.Minute)
-
- got, err := convertToUser(selfCtx, iamManager, user)
- require.NoError(t, err)
- require.Nil(t, got.TempOtpSecretCreatedTime,
- "an abandoned setup must stop reporting an open enrollment, or the console holds its seed forever")
- require.Empty(t, got.TempOtpSecret)
- require.Empty(t, got.TempRecoveryCodes)
- })
-
- t.Run("and not even to the request that would have minted it", func(t *testing.T) {
- // UpdateUser refuses to verify against an expired seed, so a response
- // carrying one would be offering something the server will not accept.
- selfCtx, user := enrolling(t, "[email protected]", 6*time.Minute)
-
- got, err := convertToUserMintingMFAEnrollment(selfCtx, iamManager, user)
- require.NoError(t, err)
- require.Empty(t, got.TempOtpSecret)
- require.Empty(t, got.TempRecoveryCodes)
- require.Nil(t, got.TempOtpSecretCreatedTime)
- })
-
- t.Run("somebody else's enrollment is never exposed, open or not", func(t *testing.T) {
- selfCtx, subject := enrolling(t, "[email protected]", time.Minute)
- _ = selfCtx
- other, err := stores.CreateUser(ctx, &store.UserMessage{
- Email: "[email protected]",
- Name: "onlooker",
- Type: storepb.PrincipalType_END_USER,
- })
- require.NoError(t, err)
-
- otherCtx := context.WithValue(ctx, common.WorkspaceIDContextKey, mfaEnrollmentTestWorkspace)
- otherCtx = context.WithValue(otherCtx, common.UserContextKey, other)
-
- got, err := convertToUser(otherCtx, iamManager, subject)
- require.NoError(t, err)
- require.Nil(t, got.TempOtpSecretCreatedTime)
- require.Empty(t, got.TempOtpSecret)
- require.Empty(t, got.TempRecoveryCodes)
- })
-}
diff --git a/backend/generated-go/v1/user_service.pb.go b/backend/generated-go/v1/user_service.pb.go
index 759d27f84d..c6ac0f371f 100644
--- a/backend/generated-go/v1/user_service.pb.go
+++ b/backend/generated-go/v1/user_service.pb.go
@@ -369,13 +369,6 @@ type UpdateUserRequest struct {
User *User `protobuf:"bytes,1,opt,name=user,proto3" json:"user,omitempty"`
// The list of fields to update.
UpdateMask *fieldmaskpb.FieldMask `protobuf:"bytes,2,opt,name=update_mask,json=updateMask,proto3" json:"update_mask,omitempty"`
- // The otp_code is used to verify the user's identity by MFA.
- OtpCode *string `protobuf:"bytes,3,opt,name=otp_code,json=otpCode,proto3,oneof" json:"otp_code,omitempty"`
- // The regenerate_temp_mfa_secret flag means to regenerate temporary MFA secret for user.
- // This is used for MFA setup. The temporary MFA secret and recovery codes will be returned in the response.
- RegenerateTempMfaSecret bool `protobuf:"varint,4,opt,name=regenerate_temp_mfa_secret,json=regenerateTempMfaSecret,proto3" json:"regenerate_temp_mfa_secret,omitempty"`
- // The regenerate_recovery_codes flag means to regenerate recovery codes for user.
- RegenerateRecoveryCodes bool `protobuf:"varint,5,opt,name=regenerate_recovery_codes,json=regenerateRecoveryCodes,proto3" json:"regenerate_recovery_codes,omitempty"`
// If set to true, and the user is not found, a new user will be created.
// In this situation, `update_mask` is ignored.
AllowMissing bool `protobuf:"varint,6,opt,name=allow_missing,json=allowMissing,proto3" json:"allow_missing,omitempty"`
@@ -427,27 +420,6 @@ func (x *UpdateUserRequest) GetUpdateMask() *fieldmaskpb.FieldMask {
return nil
}
-func (x *UpdateUserRequest) GetOtpCode() string {
- if x != nil && x.OtpCode != nil {
- return *x.OtpCode
- }
- return ""
-}
-
-func (x *UpdateUserRequest) GetRegenerateTempMfaSecret() bool {
- if x != nil {
- return x.RegenerateTempMfaSecret
- }
- return false
-}
-
-func (x *UpdateUserRequest) GetRegenerateRecoveryCodes() bool {
- if x != nil {
- return x.RegenerateRecoveryCodes
- }
- return false
-}
-
func (x *UpdateUserRequest) GetAllowMissing() bool {
if x != nil {
return x.AllowMissing
@@ -603,6 +575,443 @@ func (x *UpdateEmailRequest) GetEmail() string {
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"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *ChangePasswordRequest) Reset() {
+ *x = ChangePasswordRequest{}
+ mi := &file_v1_user_service_proto_msgTypes[10]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *ChangePasswordRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*ChangePasswordRequest) ProtoMessage() {}
+
+func (x *ChangePasswordRequest) 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 ChangePasswordRequest.ProtoReflect.Descriptor instead.
+func (*ChangePasswordRequest) Descriptor() ([]byte, []int) {
+ return file_v1_user_service_proto_rawDescGZIP(), []int{10}
+}
+
+func (x *ChangePasswordRequest) GetName() string {
+ if x != nil {
+ return x.Name
+ }
+ return ""
+}
+
+func (x *ChangePasswordRequest) GetNewPassword() string {
+ if x != nil {
+ return x.NewPassword
+ }
+ return ""
+}
+
+type StartMFAEnrollmentRequest 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"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *StartMFAEnrollmentRequest) Reset() {
+ *x = StartMFAEnrollmentRequest{}
+ mi := &file_v1_user_service_proto_msgTypes[11]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *StartMFAEnrollmentRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*StartMFAEnrollmentRequest) ProtoMessage() {}
+
+func (x *StartMFAEnrollmentRequest) 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 StartMFAEnrollmentRequest.ProtoReflect.Descriptor instead.
+func (*StartMFAEnrollmentRequest) Descriptor() ([]byte, []int) {
+ return file_v1_user_service_proto_rawDescGZIP(), []int{11}
+}
+
+func (x *StartMFAEnrollmentRequest) GetName() string {
+ if x != nil {
+ return x.Name
+ }
+ return ""
+}
+
+type StartMFAEnrollmentResponse struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ // The pending TOTP secret. The only response that carries it — it is never
+ // readable from the User resource.
+ OtpSecret string `protobuf:"bytes,1,opt,name=otp_secret,json=otpSecret,proto3" json:"otp_secret,omitempty"`
+ // The pending recovery codes, shown once for the caller to save.
+ RecoveryCodes []string `protobuf:"bytes,2,rep,name=recovery_codes,json=recoveryCodes,proto3" json:"recovery_codes,omitempty"`
+ // When this enrollment stops being confirmable.
+ ExpireTime *timestamppb.Timestamp `protobuf:"bytes,3,opt,name=expire_time,json=expireTime,proto3" json:"expire_time,omitempty"`
+ // Identifies this mint. Echo it back to EnableMFA and
+ // ConfirmRecoveryCodes; a mint from another tab or device replaces the
+ // pending state, and those methods refuse a version that is no longer the
+ // pending one rather than promoting something this caller never saw.
+ PendingVersion *timestamppb.Timestamp `protobuf:"bytes,4,opt,name=pending_version,json=pendingVersion,proto3" json:"pending_version,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *StartMFAEnrollmentResponse) Reset() {
+ *x = StartMFAEnrollmentResponse{}
+ mi := &file_v1_user_service_proto_msgTypes[12]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *StartMFAEnrollmentResponse) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*StartMFAEnrollmentResponse) ProtoMessage() {}
+
+func (x *StartMFAEnrollmentResponse) ProtoReflect() protoreflect.Message {
+ mi := &file_v1_user_service_proto_msgTypes[12]
+ 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 StartMFAEnrollmentResponse.ProtoReflect.Descriptor instead.
+func (*StartMFAEnrollmentResponse) Descriptor() ([]byte, []int) {
+ return file_v1_user_service_proto_rawDescGZIP(), []int{12}
+}
+
+func (x *StartMFAEnrollmentResponse) GetOtpSecret() string {
+ if x != nil {
+ return x.OtpSecret
+ }
+ return ""
+}
+
+func (x *StartMFAEnrollmentResponse) GetRecoveryCodes() []string {
+ if x != nil {
+ return x.RecoveryCodes
+ }
+ return nil
+}
+
+func (x *StartMFAEnrollmentResponse) GetExpireTime() *timestamppb.Timestamp {
+ if x != nil {
+ return x.ExpireTime
+ }
+ return nil
+}
+
+func (x *StartMFAEnrollmentResponse) GetPendingVersion() *timestamppb.Timestamp {
+ if x != nil {
+ return x.PendingVersion
+ }
+ return nil
+}
+
+type EnableMFARequest 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"`
+ // A code from the authenticator the pending secret was just added to.
+ 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
+}
+
+func (x *EnableMFARequest) Reset() {
+ *x = EnableMFARequest{}
+ mi := &file_v1_user_service_proto_msgTypes[13]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *EnableMFARequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*EnableMFARequest) ProtoMessage() {}
+
+func (x *EnableMFARequest) ProtoReflect() protoreflect.Message {
+ mi := &file_v1_user_service_proto_msgTypes[13]
+ 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 EnableMFARequest.ProtoReflect.Descriptor instead.
+func (*EnableMFARequest) Descriptor() ([]byte, []int) {
+ return file_v1_user_service_proto_rawDescGZIP(), []int{13}
+}
+
+func (x *EnableMFARequest) GetName() string {
+ if x != nil {
+ return x.Name
+ }
+ return ""
+}
+
+func (x *EnableMFARequest) GetOtpCode() string {
+ if x != nil {
+ return x.OtpCode
+ }
+ return ""
+}
+
+func (x *EnableMFARequest) GetPendingVersion() *timestamppb.Timestamp {
+ if x != nil {
+ return x.PendingVersion
+ }
+ 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"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *DisableMFARequest) Reset() {
+ *x = DisableMFARequest{}
+ mi := &file_v1_user_service_proto_msgTypes[14]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *DisableMFARequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*DisableMFARequest) ProtoMessage() {}
+
+func (x *DisableMFARequest) ProtoReflect() protoreflect.Message {
+ mi := &file_v1_user_service_proto_msgTypes[14]
+ 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 DisableMFARequest.ProtoReflect.Descriptor instead.
+func (*DisableMFARequest) Descriptor() ([]byte, []int) {
+ return file_v1_user_service_proto_rawDescGZIP(), []int{14}
+}
+
+func (x *DisableMFARequest) GetName() string {
+ if x != nil {
+ return x.Name
+ }
+ return ""
+}
+
+type RegenerateRecoveryCodesRequest 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"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *RegenerateRecoveryCodesRequest) Reset() {
+ *x = RegenerateRecoveryCodesRequest{}
+ mi := &file_v1_user_service_proto_msgTypes[15]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *RegenerateRecoveryCodesRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*RegenerateRecoveryCodesRequest) ProtoMessage() {}
+
+func (x *RegenerateRecoveryCodesRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_v1_user_service_proto_msgTypes[15]
+ 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 RegenerateRecoveryCodesRequest.ProtoReflect.Descriptor instead.
+func (*RegenerateRecoveryCodesRequest) Descriptor() ([]byte, []int) {
+ return file_v1_user_service_proto_rawDescGZIP(), []int{15}
+}
+
+func (x *RegenerateRecoveryCodesRequest) GetName() string {
+ if x != nil {
+ return x.Name
+ }
+ return ""
+}
+
+type RegenerateRecoveryCodesResponse struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ // The pending recovery codes, shown once for the caller to save.
+ RecoveryCodes []string `protobuf:"bytes,1,rep,name=recovery_codes,json=recoveryCodes,proto3" json:"recovery_codes,omitempty"`
+ // Identifies this mint; see StartMFAEnrollmentResponse.pending_version.
+ PendingVersion *timestamppb.Timestamp `protobuf:"bytes,2,opt,name=pending_version,json=pendingVersion,proto3" json:"pending_version,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *RegenerateRecoveryCodesResponse) Reset() {
+ *x = RegenerateRecoveryCodesResponse{}
+ mi := &file_v1_user_service_proto_msgTypes[16]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *RegenerateRecoveryCodesResponse) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*RegenerateRecoveryCodesResponse) ProtoMessage() {}
+
+func (x *RegenerateRecoveryCodesResponse) ProtoReflect() protoreflect.Message {
+ mi := &file_v1_user_service_proto_msgTypes[16]
+ 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 RegenerateRecoveryCodesResponse.ProtoReflect.Descriptor instead.
+func (*RegenerateRecoveryCodesResponse) Descriptor() ([]byte, []int) {
+ return file_v1_user_service_proto_rawDescGZIP(), []int{16}
+}
+
+func (x *RegenerateRecoveryCodesResponse) GetRecoveryCodes() []string {
+ if x != nil {
+ return x.RecoveryCodes
+ }
+ return nil
+}
+
+func (x *RegenerateRecoveryCodesResponse) GetPendingVersion() *timestamppb.Timestamp {
+ if x != nil {
+ return x.PendingVersion
+ }
+ return nil
+}
+
+type ConfirmRecoveryCodesRequest 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"`
+ // 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
+}
+
+func (x *ConfirmRecoveryCodesRequest) Reset() {
+ *x = ConfirmRecoveryCodesRequest{}
+ mi := &file_v1_user_service_proto_msgTypes[17]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *ConfirmRecoveryCodesRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*ConfirmRecoveryCodesRequest) ProtoMessage() {}
+
+func (x *ConfirmRecoveryCodesRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_v1_user_service_proto_msgTypes[17]
+ 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 ConfirmRecoveryCodesRequest.ProtoReflect.Descriptor instead.
+func (*ConfirmRecoveryCodesRequest) Descriptor() ([]byte, []int) {
+ return file_v1_user_service_proto_rawDescGZIP(), []int{17}
+}
+
+func (x *ConfirmRecoveryCodesRequest) GetName() string {
+ if x != nil {
+ return x.Name
+ }
+ return ""
+}
+
+func (x *ConfirmRecoveryCodesRequest) GetPendingVersion() *timestamppb.Timestamp {
+ if x != nil {
+ return x.PendingVersion
+ }
+ return nil
+}
+
type User struct {
state protoimpl.MessageState `protogen:"open.v1"`
// The name of the user.
@@ -616,14 +1025,9 @@ type User struct {
Title string `protobuf:"bytes,4,opt,name=title,proto3" json:"title,omitempty"`
// The password for authentication. Only used during user creation or password updates.
Password string `protobuf:"bytes,6,opt,name=password,proto3" json:"password,omitempty"`
- // The mfa_enabled flag means if the user has enabled MFA.
+ // Whether the user has a live MFA factor. Set by ConfirmRecoveryCodes and
+ // DisableMFA, never by an update.
MfaEnabled bool `protobuf:"varint,8,opt,name=mfa_enabled,json=mfaEnabled,proto3" json:"mfa_enabled,omitempty"`
- // Temporary OTP secret used during MFA setup and regeneration.
- TempOtpSecret string `protobuf:"bytes,9,opt,name=temp_otp_secret,json=tempOtpSecret,proto3" json:"temp_otp_secret,omitempty"`
- // Temporary recovery codes used during MFA setup and regeneration.
- TempRecoveryCodes []string `protobuf:"bytes,10,rep,name=temp_recovery_codes,json=tempRecoveryCodes,proto3" json:"temp_recovery_codes,omitempty"`
- // Timestamp when temp_otp_secret was created. Used by frontend to show countdown timer.
- TempOtpSecretCreatedTime *timestamppb.Timestamp `protobuf:"bytes,11,opt,name=temp_otp_secret_created_time,json=tempOtpSecretCreatedTime,proto3" json:"temp_otp_secret_created_time,omitempty"`
// Should be a valid E.164 compliant phone number.
// Could be empty.
Phone string `protobuf:"bytes,12,opt,name=phone,proto3" json:"phone,omitempty"`
@@ -641,7 +1045,7 @@ type User struct {
func (x *User) Reset() {
*x = User{}
- mi := &file_v1_user_service_proto_msgTypes[10]
+ mi := &file_v1_user_service_proto_msgTypes[18]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -653,7 +1057,7 @@ func (x *User) String() string {
func (*User) ProtoMessage() {}
func (x *User) ProtoReflect() protoreflect.Message {
- mi := &file_v1_user_service_proto_msgTypes[10]
+ mi := &file_v1_user_service_proto_msgTypes[18]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -666,7 +1070,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{10}
+ return file_v1_user_service_proto_rawDescGZIP(), []int{18}
}
func (x *User) GetName() string {
@@ -711,27 +1115,6 @@ func (x *User) GetMfaEnabled() bool {
return false
}
-func (x *User) GetTempOtpSecret() string {
- if x != nil {
- return x.TempOtpSecret
- }
- return ""
-}
-
-func (x *User) GetTempRecoveryCodes() []string {
- if x != nil {
- return x.TempRecoveryCodes
- }
- return nil
-}
-
-func (x *User) GetTempOtpSecretCreatedTime() *timestamppb.Timestamp {
- if x != nil {
- return x.TempOtpSecretCreatedTime
- }
- return nil
-}
-
func (x *User) GetPhone() string {
if x != nil {
return x.Phone
@@ -774,7 +1157,7 @@ type User_Profile struct {
func (x *User_Profile) Reset() {
*x = User_Profile{}
- mi := &file_v1_user_service_proto_msgTypes[11]
+ mi := &file_v1_user_service_proto_msgTypes[19]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -786,7 +1169,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[11]
+ mi := &file_v1_user_service_proto_msgTypes[19]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -799,7 +1182,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{10, 0}
+ return file_v1_user_service_proto_rawDescGZIP(), []int{18, 0}
}
func (x *User_Profile) GetLastLoginTime() *timestamppb.Timestamp {
@@ -846,16 +1229,12 @@ const file_v1_user_service_proto_rawDesc = "" +
"\x05users\x18\x01 \x03(\v2\x11.bytebase.v1.UserR\x05users\x12&\n" +
"\x0fnext_page_token\x18\x02 \x01(\tR\rnextPageToken\"?\n" +
"\x11CreateUserRequest\x12*\n" +
- "\x04user\x18\x01 \x01(\v2\x11.bytebase.v1.UserB\x03\xe0A\x02R\x04user\"\xcd\x02\n" +
+ "\x04user\x18\x01 \x01(\v2\x11.bytebase.v1.UserB\x03\xe0A\x02R\x04user\"\xf4\x01\n" +
"\x11UpdateUserRequest\x12*\n" +
"\x04user\x18\x01 \x01(\v2\x11.bytebase.v1.UserB\x03\xe0A\x02R\x04user\x12;\n" +
"\vupdate_mask\x18\x02 \x01(\v2\x1a.google.protobuf.FieldMaskR\n" +
- "updateMask\x12$\n" +
- "\botp_code\x18\x03 \x01(\tB\x04\xd0\xea0\x01H\x00R\aotpCode\x88\x01\x01\x12;\n" +
- "\x1aregenerate_temp_mfa_secret\x18\x04 \x01(\bR\x17regenerateTempMfaSecret\x12:\n" +
- "\x19regenerate_recovery_codes\x18\x05 \x01(\bR\x17regenerateRecoveryCodes\x12#\n" +
- "\rallow_missing\x18\x06 \x01(\bR\fallowMissingB\v\n" +
- "\t_otp_code\"B\n" +
+ "updateMask\x12#\n" +
+ "\rallow_missing\x18\x06 \x01(\bR\fallowMissingJ\x04\b\x03\x10\x04J\x04\b\x04\x10\x05J\x04\b\x05\x10\x06R\botp_codeR\x1aregenerate_temp_mfa_secretR\x19regenerate_recovery_codes\"B\n" +
"\x11DeleteUserRequest\x12-\n" +
"\x04name\x18\x01 \x01(\tB\x19\xe0A\x02\xfaA\x13\n" +
"\x11bytebase.com/UserR\x04name\"D\n" +
@@ -865,19 +1244,47 @@ 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\"\xa9\x06\n" +
+ "\x05email\x18\x02 \x01(\tB\v\xe0A\x02\xbaH\x05r\x03\x18\xfe\x01R\x05email\"\x81\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" +
+ "\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" +
+ "\x1aStartMFAEnrollmentResponse\x12#\n" +
+ "\n" +
+ "otp_secret\x18\x01 \x01(\tB\x04\xd0\xea0\x01R\totpSecret\x12+\n" +
+ "\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" +
+ "\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" +
+ "\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" +
+ "\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" +
+ "\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" +
"\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" +
"\x05email\x18\x03 \x01(\tB\b\xbaH\x05r\x03\x18\xfe\x01R\x05email\x12\x1e\n" +
"\x05title\x18\x04 \x01(\tB\b\xbaH\x05r\x03\x18\xc8\x01R\x05title\x12*\n" +
- "\bpassword\x18\x06 \x01(\tB\x0e\xe0A\x04\xbaH\x04r\x02(H\xd0\xea0\x01R\bpassword\x12\x1f\n" +
- "\vmfa_enabled\x18\b \x01(\bR\n" +
- "mfaEnabled\x12,\n" +
- "\x0ftemp_otp_secret\x18\t \x01(\tB\x04\xd0\xea0\x01R\rtempOtpSecret\x124\n" +
- "\x13temp_recovery_codes\x18\n" +
- " \x03(\tB\x04\xd0\xea0\x01R\x11tempRecoveryCodes\x12Z\n" +
- "\x1ctemp_otp_secret_created_time\x18\v \x01(\v2\x1a.google.protobuf.TimestampR\x18tempOtpSecretCreatedTime\x12\x1a\n" +
+ "\bpassword\x18\x06 \x01(\tB\x0e\xe0A\x04\xbaH\x04r\x02(H\xd0\xea0\x01R\bpassword\x12$\n" +
+ "\vmfa_enabled\x18\b \x01(\bB\x03\xe0A\x03R\n" +
+ "mfaEnabled\x12\x1a\n" +
"\x05phone\x18\f \x01(\tB\x04\xd0\xea0\x02R\x05phone\x129\n" +
"\aprofile\x18\r \x01(\v2\x19.bytebase.v1.User.ProfileB\x04\xd0\xea0\x02R\aprofile\x12\x1f\n" +
"\x06groups\x18\x0e \x03(\tB\a\xe0A\x03\xd0\xea0\x02R\x06groups\x12!\n" +
@@ -886,7 +1293,9 @@ const file_v1_user_service_proto_rawDesc = "" +
"\x0flast_login_time\x18\x01 \x01(\v2\x1a.google.protobuf.TimestampR\rlastLoginTime\x12U\n" +
"\x19last_change_password_time\x18\x02 \x01(\v2\x1a.google.protobuf.TimestampR\x16lastChangePasswordTime\x12\x16\n" +
"\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\x102\xa8\t\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" +
"\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" +
@@ -900,7 +1309,14 @@ 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/*}:updateEmailB\xa6\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\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" +
+ "\n" +
+ "DisableMFA\x12\x1e.bytebase.v1.DisableMFARequest\x1a\x11.bytebase.v1.User\"?\xdaA\x04name\x90\xea0\x02\x98\xea0\x01\xa0\xea0\x03\xa8\xea0\x03\x82\xd3\xe4\x93\x02\":\x01*\"\x1d/v1/{name=users/*}:disableMFA\x12\xc2\x01\n" +
+ "\x17RegenerateRecoveryCodes\x12+.bytebase.v1.RegenerateRecoveryCodesRequest\x1a,.bytebase.v1.RegenerateRecoveryCodesResponse\"L\xdaA\x04name\x90\xea0\x02\x98\xea0\x01\xa0\xea0\x03\xa8\xea0\x01\x82\xd3\xe4\x93\x02/:\x01*\"*/v1/{name=users/*}:regenerateRecoveryCodes\x12\x9e\x01\n" +
+ "\x14ConfirmRecoveryCodes\x12(.bytebase.v1.ConfirmRecoveryCodesRequest\x1a\x11.bytebase.v1.User\"I\xdaA\x04name\x90\xea0\x02\x98\xea0\x01\xa0\xea0\x03\xa8\xea0\x03\x82\xd3\xe4\x93\x02,:\x01*\"'/v1/{name=users/*}:confirmRecoveryCodesB\xa6\x01\n" +
"\x0fcom.bytebase.v1B\x10UserServiceProtoP\x01Z4github.com/bytebase/bytebase/backend/generated-go/v1\xa2\x02\x03BXX\xaa\x02\vBytebase.V1\xca\x02\vBytebase\\V1\xe2\x02\x17Bytebase\\V1\\GPBMetadata\xea\x02\fBytebase::V1b\x06proto3"
var (
@@ -915,59 +1331,83 @@ 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, 12)
+var file_v1_user_service_proto_msgTypes = make([]protoimpl.MessageInfo, 20)
var file_v1_user_service_proto_goTypes = []any{
- (*GetUserRequest)(nil), // 0: bytebase.v1.GetUserRequest
- (*BatchGetUsersRequest)(nil), // 1: bytebase.v1.BatchGetUsersRequest
- (*BatchGetUsersResponse)(nil), // 2: bytebase.v1.BatchGetUsersResponse
- (*ListUsersRequest)(nil), // 3: bytebase.v1.ListUsersRequest
- (*ListUsersResponse)(nil), // 4: bytebase.v1.ListUsersResponse
- (*CreateUserRequest)(nil), // 5: bytebase.v1.CreateUserRequest
- (*UpdateUserRequest)(nil), // 6: bytebase.v1.UpdateUserRequest
- (*DeleteUserRequest)(nil), // 7: bytebase.v1.DeleteUserRequest
- (*UndeleteUserRequest)(nil), // 8: bytebase.v1.UndeleteUserRequest
- (*UpdateEmailRequest)(nil), // 9: bytebase.v1.UpdateEmailRequest
- (*User)(nil), // 10: bytebase.v1.User
- (*User_Profile)(nil), // 11: bytebase.v1.User.Profile
- (*fieldmaskpb.FieldMask)(nil), // 12: google.protobuf.FieldMask
- (State)(0), // 13: bytebase.v1.State
- (*timestamppb.Timestamp)(nil), // 14: google.protobuf.Timestamp
- (*emptypb.Empty)(nil), // 15: google.protobuf.Empty
+ (*GetUserRequest)(nil), // 0: bytebase.v1.GetUserRequest
+ (*BatchGetUsersRequest)(nil), // 1: bytebase.v1.BatchGetUsersRequest
+ (*BatchGetUsersResponse)(nil), // 2: bytebase.v1.BatchGetUsersResponse
+ (*ListUsersRequest)(nil), // 3: bytebase.v1.ListUsersRequest
+ (*ListUsersResponse)(nil), // 4: bytebase.v1.ListUsersResponse
+ (*CreateUserRequest)(nil), // 5: bytebase.v1.CreateUserRequest
+ (*UpdateUserRequest)(nil), // 6: bytebase.v1.UpdateUserRequest
+ (*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
}
var file_v1_user_service_proto_depIdxs = []int32{
- 10, // 0: bytebase.v1.BatchGetUsersResponse.users:type_name -> bytebase.v1.User
- 10, // 1: bytebase.v1.ListUsersResponse.users:type_name -> bytebase.v1.User
- 10, // 2: bytebase.v1.CreateUserRequest.user:type_name -> bytebase.v1.User
- 10, // 3: bytebase.v1.UpdateUserRequest.user:type_name -> bytebase.v1.User
- 12, // 4: bytebase.v1.UpdateUserRequest.update_mask:type_name -> google.protobuf.FieldMask
- 13, // 5: bytebase.v1.User.state:type_name -> bytebase.v1.State
- 14, // 6: bytebase.v1.User.temp_otp_secret_created_time:type_name -> google.protobuf.Timestamp
- 11, // 7: bytebase.v1.User.profile:type_name -> bytebase.v1.User.Profile
- 14, // 8: bytebase.v1.User.Profile.last_login_time:type_name -> google.protobuf.Timestamp
- 14, // 9: bytebase.v1.User.Profile.last_change_password_time:type_name -> google.protobuf.Timestamp
- 0, // 10: bytebase.v1.UserService.GetUser:input_type -> bytebase.v1.GetUserRequest
- 1, // 11: bytebase.v1.UserService.BatchGetUsers:input_type -> bytebase.v1.BatchGetUsersRequest
- 15, // 12: bytebase.v1.UserService.GetCurrentUser:input_type -> google.protobuf.Empty
- 3, // 13: bytebase.v1.UserService.ListUsers:input_type -> bytebase.v1.ListUsersRequest
- 5, // 14: bytebase.v1.UserService.CreateUser:input_type -> bytebase.v1.CreateUserRequest
- 6, // 15: bytebase.v1.UserService.UpdateUser:input_type -> bytebase.v1.UpdateUserRequest
- 7, // 16: bytebase.v1.UserService.DeleteUser:input_type -> bytebase.v1.DeleteUserRequest
- 8, // 17: bytebase.v1.UserService.UndeleteUser:input_type -> bytebase.v1.UndeleteUserRequest
- 9, // 18: bytebase.v1.UserService.UpdateEmail:input_type -> bytebase.v1.UpdateEmailRequest
- 10, // 19: bytebase.v1.UserService.GetUser:output_type -> bytebase.v1.User
- 2, // 20: bytebase.v1.UserService.BatchGetUsers:output_type -> bytebase.v1.BatchGetUsersResponse
- 10, // 21: bytebase.v1.UserService.GetCurrentUser:output_type -> bytebase.v1.User
- 4, // 22: bytebase.v1.UserService.ListUsers:output_type -> bytebase.v1.ListUsersResponse
- 10, // 23: bytebase.v1.UserService.CreateUser:output_type -> bytebase.v1.User
- 10, // 24: bytebase.v1.UserService.UpdateUser:output_type -> bytebase.v1.User
- 15, // 25: bytebase.v1.UserService.DeleteUser:output_type -> google.protobuf.Empty
- 10, // 26: bytebase.v1.UserService.UndeleteUser:output_type -> bytebase.v1.User
- 10, // 27: bytebase.v1.UserService.UpdateEmail:output_type -> bytebase.v1.User
- 19, // [19:28] is the sub-list for method output_type
- 10, // [10:19] is the sub-list for method input_type
- 10, // [10:10] is the sub-list for extension type_name
- 10, // [10:10] is the sub-list for extension extendee
- 0, // [0:10] is the sub-list for field type_name
+ 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
}
func init() { file_v1_user_service_proto_init() }
@@ -977,14 +1417,13 @@ func file_v1_user_service_proto_init() {
}
file_v1_annotation_proto_init()
file_v1_common_proto_init()
- file_v1_user_service_proto_msgTypes[6].OneofWrappers = []any{}
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: 12,
+ NumMessages: 20,
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 5f8f756949..328ba73806 100644
--- a/backend/generated-go/v1/user_service.pb.gw.go
+++ b/backend/generated-go/v1/user_service.pb.gw.go
@@ -403,6 +403,276 @@ func local_request_UserService_UpdateEmail_0(ctx context.Context, marshaler runt
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
+ 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.ChangePassword(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
+ return msg, metadata, err
+}
+
+func local_request_UserService_ChangePassword_0(ctx context.Context, marshaler runtime.Marshaler, server UserServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
+ var (
+ protoReq ChangePasswordRequest
+ 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.ChangePassword(ctx, &protoReq)
+ return msg, metadata, err
+}
+
+func request_UserService_StartMFAEnrollment_0(ctx context.Context, marshaler runtime.Marshaler, client UserServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
+ var (
+ protoReq StartMFAEnrollmentRequest
+ 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.StartMFAEnrollment(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
+ return msg, metadata, err
+}
+
+func local_request_UserService_StartMFAEnrollment_0(ctx context.Context, marshaler runtime.Marshaler, server UserServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
+ var (
+ protoReq StartMFAEnrollmentRequest
+ 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.StartMFAEnrollment(ctx, &protoReq)
+ return msg, metadata, err
+}
+
+func request_UserService_EnableMFA_0(ctx context.Context, marshaler runtime.Marshaler, client UserServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
+ var (
+ protoReq EnableMFARequest
+ 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.EnableMFA(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
+ return msg, metadata, err
+}
+
+func local_request_UserService_EnableMFA_0(ctx context.Context, marshaler runtime.Marshaler, server UserServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
+ var (
+ protoReq EnableMFARequest
+ 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.EnableMFA(ctx, &protoReq)
+ return msg, metadata, err
+}
+
+func request_UserService_DisableMFA_0(ctx context.Context, marshaler runtime.Marshaler, client UserServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
+ var (
+ protoReq DisableMFARequest
+ 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.DisableMFA(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
+ return msg, metadata, err
+}
+
+func local_request_UserService_DisableMFA_0(ctx context.Context, marshaler runtime.Marshaler, server UserServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
+ var (
+ protoReq DisableMFARequest
+ 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.DisableMFA(ctx, &protoReq)
+ return msg, metadata, err
+}
+
+func request_UserService_RegenerateRecoveryCodes_0(ctx context.Context, marshaler runtime.Marshaler, client UserServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
+ var (
+ protoReq RegenerateRecoveryCodesRequest
+ 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.RegenerateRecoveryCodes(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
+ return msg, metadata, err
+}
+
+func local_request_UserService_RegenerateRecoveryCodes_0(ctx context.Context, marshaler runtime.Marshaler, server UserServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
+ var (
+ protoReq RegenerateRecoveryCodesRequest
+ 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.RegenerateRecoveryCodes(ctx, &protoReq)
+ return msg, metadata, err
+}
+
+func request_UserService_ConfirmRecoveryCodes_0(ctx context.Context, marshaler runtime.Marshaler, client UserServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
+ var (
+ protoReq ConfirmRecoveryCodesRequest
+ 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.ConfirmRecoveryCodes(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
+ return msg, metadata, err
+}
+
+func local_request_UserService_ConfirmRecoveryCodes_0(ctx context.Context, marshaler runtime.Marshaler, server UserServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
+ var (
+ protoReq ConfirmRecoveryCodesRequest
+ 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.ConfirmRecoveryCodes(ctx, &protoReq)
+ return msg, metadata, err
+}
+
// RegisterUserServiceHandlerServer registers the http handlers for service UserService to "mux".
// UnaryRPC :call UserServiceServer directly.
// StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906.
@@ -589,6 +859,126 @@ 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_ChangePassword_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/ChangePassword", runtime.WithHTTPPathPattern("/v1/{name=users/*}:changePassword"))
+ if err != nil {
+ runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
+ return
+ }
+ resp, md, err := local_request_UserService_ChangePassword_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_ChangePassword_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
+ })
+ mux.Handle(http.MethodPost, pattern_UserService_StartMFAEnrollment_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/StartMFAEnrollment", runtime.WithHTTPPathPattern("/v1/{name=users/*}:startMFAEnrollment"))
+ if err != nil {
+ runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
+ return
+ }
+ resp, md, err := local_request_UserService_StartMFAEnrollment_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_StartMFAEnrollment_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
+ })
+ mux.Handle(http.MethodPost, pattern_UserService_EnableMFA_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/EnableMFA", runtime.WithHTTPPathPattern("/v1/{name=users/*}:enableMFA"))
+ if err != nil {
+ runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
+ return
+ }
+ resp, md, err := local_request_UserService_EnableMFA_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_EnableMFA_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
+ })
+ mux.Handle(http.MethodPost, pattern_UserService_DisableMFA_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/DisableMFA", runtime.WithHTTPPathPattern("/v1/{name=users/*}:disableMFA"))
+ if err != nil {
+ runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
+ return
+ }
+ resp, md, err := local_request_UserService_DisableMFA_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_DisableMFA_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
+ })
+ mux.Handle(http.MethodPost, pattern_UserService_RegenerateRecoveryCodes_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/RegenerateRecoveryCodes", runtime.WithHTTPPathPattern("/v1/{name=users/*}:regenerateRecoveryCodes"))
+ if err != nil {
+ runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
+ return
+ }
+ resp, md, err := local_request_UserService_RegenerateRecoveryCodes_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_RegenerateRecoveryCodes_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
+ })
+ mux.Handle(http.MethodPost, pattern_UserService_ConfirmRecoveryCodes_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/ConfirmRecoveryCodes", runtime.WithHTTPPathPattern("/v1/{name=users/*}:confirmRecoveryCodes"))
+ if err != nil {
+ runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
+ return
+ }
+ resp, md, err := local_request_UserService_ConfirmRecoveryCodes_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_ConfirmRecoveryCodes_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
+ })
return nil
}
@@ -782,29 +1172,143 @@ 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_ChangePassword_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/ChangePassword", runtime.WithHTTPPathPattern("/v1/{name=users/*}:changePassword"))
+ if err != nil {
+ runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
+ return
+ }
+ resp, md, err := request_UserService_ChangePassword_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_ChangePassword_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
+ })
+ mux.Handle(http.MethodPost, pattern_UserService_StartMFAEnrollment_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/StartMFAEnrollment", runtime.WithHTTPPathPattern("/v1/{name=users/*}:startMFAEnrollment"))
+ if err != nil {
+ runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
+ return
+ }
+ resp, md, err := request_UserService_StartMFAEnrollment_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_StartMFAEnrollment_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
+ })
+ mux.Handle(http.MethodPost, pattern_UserService_EnableMFA_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/EnableMFA", runtime.WithHTTPPathPattern("/v1/{name=users/*}:enableMFA"))
+ if err != nil {
+ runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
+ return
+ }
+ resp, md, err := request_UserService_EnableMFA_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_EnableMFA_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
+ })
+ mux.Handle(http.MethodPost, pattern_UserService_DisableMFA_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/DisableMFA", runtime.WithHTTPPathPattern("/v1/{name=users/*}:disableMFA"))
+ if err != nil {
+ runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
+ return
+ }
+ resp, md, err := request_UserService_DisableMFA_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_DisableMFA_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
+ })
+ mux.Handle(http.MethodPost, pattern_UserService_RegenerateRecoveryCodes_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/RegenerateRecoveryCodes", runtime.WithHTTPPathPattern("/v1/{name=users/*}:regenerateRecoveryCodes"))
+ if err != nil {
+ runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
+ return
+ }
+ resp, md, err := request_UserService_RegenerateRecoveryCodes_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_RegenerateRecoveryCodes_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
+ })
+ mux.Handle(http.MethodPost, pattern_UserService_ConfirmRecoveryCodes_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/ConfirmRecoveryCodes", runtime.WithHTTPPathPattern("/v1/{name=users/*}:confirmRecoveryCodes"))
+ if err != nil {
+ runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
+ return
+ }
+ resp, md, err := request_UserService_ConfirmRecoveryCodes_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_ConfirmRecoveryCodes_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
+ })
return nil
}
var (
- pattern_UserService_GetUser_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 2, 5, 2}, []string{"v1", "users", "name"}, ""))
- pattern_UserService_BatchGetUsers_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "users"}, "batchGet"))
- pattern_UserService_GetCurrentUser_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "users", "me"}, ""))
- pattern_UserService_ListUsers_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "users"}, ""))
- pattern_UserService_CreateUser_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "users"}, ""))
- pattern_UserService_UpdateUser_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 2, 5, 2}, []string{"v1", "users", "user.name"}, ""))
- 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_GetUser_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 2, 5, 2}, []string{"v1", "users", "name"}, ""))
+ pattern_UserService_BatchGetUsers_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "users"}, "batchGet"))
+ pattern_UserService_GetCurrentUser_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "users", "me"}, ""))
+ pattern_UserService_ListUsers_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "users"}, ""))
+ pattern_UserService_CreateUser_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "users"}, ""))
+ pattern_UserService_UpdateUser_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 2, 5, 2}, []string{"v1", "users", "user.name"}, ""))
+ 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_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"))
+ pattern_UserService_DisableMFA_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 2, 5, 2}, []string{"v1", "users", "name"}, "disableMFA"))
+ pattern_UserService_RegenerateRecoveryCodes_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 2, 5, 2}, []string{"v1", "users", "name"}, "regenerateRecoveryCodes"))
+ pattern_UserService_ConfirmRecoveryCodes_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 2, 5, 2}, []string{"v1", "users", "name"}, "confirmRecoveryCodes"))
)
var (
- forward_UserService_GetUser_0 = runtime.ForwardResponseMessage
- forward_UserService_BatchGetUsers_0 = runtime.ForwardResponseMessage
- forward_UserService_GetCurrentUser_0 = runtime.ForwardResponseMessage
- forward_UserService_ListUsers_0 = runtime.ForwardResponseMessage
- forward_UserService_CreateUser_0 = runtime.ForwardResponseMessage
- forward_UserService_UpdateUser_0 = runtime.ForwardResponseMessage
- forward_UserService_DeleteUser_0 = runtime.ForwardResponseMessage
- forward_UserService_UndeleteUser_0 = runtime.ForwardResponseMessage
- forward_UserService_UpdateEmail_0 = runtime.ForwardResponseMessage
+ forward_UserService_GetUser_0 = runtime.ForwardResponseMessage
+ forward_UserService_BatchGetUsers_0 = runtime.ForwardResponseMessage
+ forward_UserService_GetCurrentUser_0 = runtime.ForwardResponseMessage
+ forward_UserService_ListUsers_0 = runtime.ForwardResponseMessage
+ forward_UserService_CreateUser_0 = runtime.ForwardResponseMessage
+ forward_UserService_UpdateUser_0 = runtime.ForwardResponseMessage
+ forward_UserService_DeleteUser_0 = runtime.ForwardResponseMessage
+ forward_UserService_UndeleteUser_0 = runtime.ForwardResponseMessage
+ forward_UserService_UpdateEmail_0 = runtime.ForwardResponseMessage
+ forward_UserService_ChangePassword_0 = runtime.ForwardResponseMessage
+ forward_UserService_StartMFAEnrollment_0 = runtime.ForwardResponseMessage
+ forward_UserService_EnableMFA_0 = runtime.ForwardResponseMessage
+ forward_UserService_DisableMFA_0 = runtime.ForwardResponseMessage
+ forward_UserService_RegenerateRecoveryCodes_0 = runtime.ForwardResponseMessage
+ forward_UserService_ConfirmRecoveryCodes_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 d5b260408f..1efbce081c 100644
--- a/backend/generated-go/v1/user_service_equal.pb.go
+++ b/backend/generated-go/v1/user_service_equal.pb.go
@@ -130,22 +130,55 @@ func (x *UpdateUserRequest) Equal(y *UpdateUserRequest) bool {
} else if !proto.Equal(x.UpdateMask, y.UpdateMask) {
return false
}
- if p, q := x.OtpCode, y.OtpCode; (p == nil && q != nil) || (p != nil && (q == nil || *p != *q)) {
+ if x.AllowMissing != y.AllowMissing {
return false
}
- if x.RegenerateTempMfaSecret != y.RegenerateTempMfaSecret {
+ return true
+}
+
+func (x *DeleteUserRequest) Equal(y *DeleteUserRequest) bool {
+ if x == y {
+ return true
+ }
+ if x == nil || y == nil {
+ return x == nil && y == nil
+ }
+ if x.Name != y.Name {
return false
}
- if x.RegenerateRecoveryCodes != y.RegenerateRecoveryCodes {
+ return true
+}
+
+func (x *UndeleteUserRequest) Equal(y *UndeleteUserRequest) bool {
+ if x == y {
+ return true
+ }
+ if x == nil || y == nil {
+ return x == nil && y == nil
+ }
+ if x.Name != y.Name {
return false
}
- if x.AllowMissing != y.AllowMissing {
+ return true
+}
+
+func (x *UpdateEmailRequest) Equal(y *UpdateEmailRequest) bool {
+ if x == y {
+ return true
+ }
+ if x == nil || y == nil {
+ return x == nil && y == nil
+ }
+ if x.Name != y.Name {
+ return false
+ }
+ if x.Email != y.Email {
return false
}
return true
}
-func (x *DeleteUserRequest) Equal(y *DeleteUserRequest) bool {
+func (x *ChangePasswordRequest) Equal(y *ChangePasswordRequest) bool {
if x == y {
return true
}
@@ -155,10 +188,13 @@ func (x *DeleteUserRequest) Equal(y *DeleteUserRequest) bool {
if x.Name != y.Name {
return false
}
+ if x.NewPassword != y.NewPassword {
+ return false
+ }
return true
}
-func (x *UndeleteUserRequest) Equal(y *UndeleteUserRequest) bool {
+func (x *StartMFAEnrollmentRequest) Equal(y *StartMFAEnrollmentRequest) bool {
if x == y {
return true
}
@@ -171,7 +207,34 @@ func (x *UndeleteUserRequest) Equal(y *UndeleteUserRequest) bool {
return true
}
-func (x *UpdateEmailRequest) Equal(y *UpdateEmailRequest) bool {
+func (x *StartMFAEnrollmentResponse) Equal(y *StartMFAEnrollmentResponse) bool {
+ if x == y {
+ return true
+ }
+ if x == nil || y == nil {
+ return x == nil && y == nil
+ }
+ if x.OtpSecret != y.OtpSecret {
+ return false
+ }
+ if len(x.RecoveryCodes) != len(y.RecoveryCodes) {
+ return false
+ }
+ for i := 0; i < len(x.RecoveryCodes); i++ {
+ if x.RecoveryCodes[i] != y.RecoveryCodes[i] {
+ return false
+ }
+ }
+ if p, q := x.ExpireTime, y.ExpireTime; (p == nil && q != nil) || (p != nil && (q == nil || p.Seconds != q.Seconds || p.Nanos != q.Nanos)) {
+ return false
+ }
+ 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
+ }
+ return true
+}
+
+func (x *EnableMFARequest) Equal(y *EnableMFARequest) bool {
if x == y {
return true
}
@@ -181,7 +244,73 @@ func (x *UpdateEmailRequest) Equal(y *UpdateEmailRequest) bool {
if x.Name != y.Name {
return false
}
- if x.Email != y.Email {
+ if x.OtpCode != y.OtpCode {
+ return false
+ }
+ 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
+ }
+ return true
+}
+
+func (x *DisableMFARequest) Equal(y *DisableMFARequest) 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 *RegenerateRecoveryCodesRequest) Equal(y *RegenerateRecoveryCodesRequest) 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 *RegenerateRecoveryCodesResponse) Equal(y *RegenerateRecoveryCodesResponse) bool {
+ if x == y {
+ return true
+ }
+ if x == nil || y == nil {
+ return x == nil && y == nil
+ }
+ if len(x.RecoveryCodes) != len(y.RecoveryCodes) {
+ return false
+ }
+ for i := 0; i < len(x.RecoveryCodes); i++ {
+ if x.RecoveryCodes[i] != y.RecoveryCodes[i] {
+ return false
+ }
+ }
+ 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
+ }
+ return true
+}
+
+func (x *ConfirmRecoveryCodesRequest) Equal(y *ConfirmRecoveryCodesRequest) bool {
+ if x == y {
+ return true
+ }
+ if x == nil || y == nil {
+ return x == nil && y == nil
+ }
+ if x.Name != y.Name {
+ return false
+ }
+ 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
}
return true
@@ -231,20 +360,6 @@ func (x *User) Equal(y *User) bool {
if x.MfaEnabled != y.MfaEnabled {
return false
}
- if x.TempOtpSecret != y.TempOtpSecret {
- return false
- }
- if len(x.TempRecoveryCodes) != len(y.TempRecoveryCodes) {
- return false
- }
- for i := 0; i < len(x.TempRecoveryCodes); i++ {
- if x.TempRecoveryCodes[i] != y.TempRecoveryCodes[i] {
- return false
- }
- }
- if p, q := x.TempOtpSecretCreatedTime, y.TempOtpSecretCreatedTime; (p == nil && q != nil) || (p != nil && (q == nil || p.Seconds != q.Seconds || p.Nanos != q.Nanos)) {
- return false
- }
if x.Phone != y.Phone {
return false
}
diff --git a/backend/generated-go/v1/user_service_grpc.pb.go b/backend/generated-go/v1/user_service_grpc.pb.go
index 9f8dad4537..a019ab5995 100644
--- a/backend/generated-go/v1/user_service_grpc.pb.go
+++ b/backend/generated-go/v1/user_service_grpc.pb.go
@@ -20,15 +20,21 @@ import (
const _ = grpc.SupportPackageIsVersion9
const (
- UserService_GetUser_FullMethodName = "/bytebase.v1.UserService/GetUser"
- UserService_BatchGetUsers_FullMethodName = "/bytebase.v1.UserService/BatchGetUsers"
- UserService_GetCurrentUser_FullMethodName = "/bytebase.v1.UserService/GetCurrentUser"
- UserService_ListUsers_FullMethodName = "/bytebase.v1.UserService/ListUsers"
- UserService_CreateUser_FullMethodName = "/bytebase.v1.UserService/CreateUser"
- UserService_UpdateUser_FullMethodName = "/bytebase.v1.UserService/UpdateUser"
- UserService_DeleteUser_FullMethodName = "/bytebase.v1.UserService/DeleteUser"
- UserService_UndeleteUser_FullMethodName = "/bytebase.v1.UserService/UndeleteUser"
- UserService_UpdateEmail_FullMethodName = "/bytebase.v1.UserService/UpdateEmail"
+ UserService_GetUser_FullMethodName = "/bytebase.v1.UserService/GetUser"
+ UserService_BatchGetUsers_FullMethodName = "/bytebase.v1.UserService/BatchGetUsers"
+ UserService_GetCurrentUser_FullMethodName = "/bytebase.v1.UserService/GetCurrentUser"
+ UserService_ListUsers_FullMethodName = "/bytebase.v1.UserService/ListUsers"
+ UserService_CreateUser_FullMethodName = "/bytebase.v1.UserService/CreateUser"
+ UserService_UpdateUser_FullMethodName = "/bytebase.v1.UserService/UpdateUser"
+ UserService_DeleteUser_FullMethodName = "/bytebase.v1.UserService/DeleteUser"
+ UserService_UndeleteUser_FullMethodName = "/bytebase.v1.UserService/UndeleteUser"
+ UserService_UpdateEmail_FullMethodName = "/bytebase.v1.UserService/UpdateEmail"
+ UserService_ChangePassword_FullMethodName = "/bytebase.v1.UserService/ChangePassword"
+ UserService_StartMFAEnrollment_FullMethodName = "/bytebase.v1.UserService/StartMFAEnrollment"
+ UserService_EnableMFA_FullMethodName = "/bytebase.v1.UserService/EnableMFA"
+ UserService_DisableMFA_FullMethodName = "/bytebase.v1.UserService/DisableMFA"
+ UserService_RegenerateRecoveryCodes_FullMethodName = "/bytebase.v1.UserService/RegenerateRecoveryCodes"
+ UserService_ConfirmRecoveryCodes_FullMethodName = "/bytebase.v1.UserService/ConfirmRecoveryCodes"
)
// UserServiceClient is the client API for UserService service.
@@ -69,6 +75,42 @@ 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)
+ // 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
+ // end in a new password hash.
+ // Permissions required: None beyond being signed in as `name`.
+ ChangePassword(ctx context.Context, in *ChangePasswordRequest, opts ...grpc.CallOption) (*User, error)
+ // Mints a pending TOTP secret and recovery codes for the caller'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`.
+ StartMFAEnrollment(ctx context.Context, in *StartMFAEnrollmentRequest, opts ...grpc.CallOption) (*StartMFAEnrollmentResponse, error)
+ // 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.
+ EnableMFA(ctx context.Context, in *EnableMFARequest, opts ...grpc.CallOption) (*User, error)
+ // Turns MFA off, clearing the entire MFA config — live and pending state
+ // alike. Callers may disable their own; an administrator may disable
+ // another user's with bb.users.update, which is how a locked-out user is
+ // recovered.
+ // Permissions required: bb.users.update, unless `name` is the caller's own.
+ DisableMFA(ctx context.Context, in *DisableMFARequest, opts ...grpc.CallOption) (*User, error)
+ // Mints a pending recovery-code set beside the live one and returns it.
+ // The old codes keep working until ConfirmRecoveryCodes promotes these, so
+ // a caller who closes the page mid-way is not left without any.
+ // Permissions required: None beyond being signed in as `name`.
+ RegenerateRecoveryCodes(ctx context.Context, in *RegenerateRecoveryCodesRequest, opts ...grpc.CallOption) (*RegenerateRecoveryCodesResponse, error)
+ // Promotes the pending recovery codes. During first-time enrollment this is
+ // also where the pending TOTP secret goes live, so the factor and the codes
+ // that recover it start existing in the same write.
+ // Permissions required: None beyond being signed in as `name`.
+ ConfirmRecoveryCodes(ctx context.Context, in *ConfirmRecoveryCodesRequest, opts ...grpc.CallOption) (*User, error)
}
type userServiceClient struct {
@@ -169,6 +211,66 @@ func (c *userServiceClient) UpdateEmail(ctx context.Context, in *UpdateEmailRequ
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)
+ err := c.cc.Invoke(ctx, UserService_ChangePassword_FullMethodName, in, out, cOpts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *userServiceClient) StartMFAEnrollment(ctx context.Context, in *StartMFAEnrollmentRequest, opts ...grpc.CallOption) (*StartMFAEnrollmentResponse, error) {
+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
+ out := new(StartMFAEnrollmentResponse)
+ err := c.cc.Invoke(ctx, UserService_StartMFAEnrollment_FullMethodName, in, out, cOpts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *userServiceClient) EnableMFA(ctx context.Context, in *EnableMFARequest, opts ...grpc.CallOption) (*User, error) {
+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
+ out := new(User)
+ err := c.cc.Invoke(ctx, UserService_EnableMFA_FullMethodName, in, out, cOpts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *userServiceClient) DisableMFA(ctx context.Context, in *DisableMFARequest, opts ...grpc.CallOption) (*User, error) {
+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
+ out := new(User)
+ err := c.cc.Invoke(ctx, UserService_DisableMFA_FullMethodName, in, out, cOpts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *userServiceClient) RegenerateRecoveryCodes(ctx context.Context, in *RegenerateRecoveryCodesRequest, opts ...grpc.CallOption) (*RegenerateRecoveryCodesResponse, error) {
+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
+ out := new(RegenerateRecoveryCodesResponse)
+ err := c.cc.Invoke(ctx, UserService_RegenerateRecoveryCodes_FullMethodName, in, out, cOpts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *userServiceClient) ConfirmRecoveryCodes(ctx context.Context, in *ConfirmRecoveryCodesRequest, opts ...grpc.CallOption) (*User, error) {
+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
+ out := new(User)
+ err := c.cc.Invoke(ctx, UserService_ConfirmRecoveryCodes_FullMethodName, in, out, cOpts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
// UserServiceServer is the server API for UserService service.
// All implementations must embed UnimplementedUserServiceServer
// for forward compatibility.
@@ -207,6 +309,42 @@ type UserServiceServer interface {
// Updates a user's email address.
// Permissions required: bb.users.updateEmail
UpdateEmail(context.Context, *UpdateEmailRequest) (*User, 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
+ // end in a new password hash.
+ // Permissions required: None beyond being signed in as `name`.
+ ChangePassword(context.Context, *ChangePasswordRequest) (*User, error)
+ // Mints a pending TOTP secret and recovery codes for the caller'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`.
+ StartMFAEnrollment(context.Context, *StartMFAEnrollmentRequest) (*StartMFAEnrollmentResponse, error)
+ // 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.
+ EnableMFA(context.Context, *EnableMFARequest) (*User, error)
+ // Turns MFA off, clearing the entire MFA config — live and pending state
+ // alike. Callers may disable their own; an administrator may disable
+ // another user's with bb.users.update, which is how a locked-out user is
+ // recovered.
+ // Permissions required: bb.users.update, unless `name` is the caller's own.
+ DisableMFA(context.Context, *DisableMFARequest) (*User, error)
+ // Mints a pending recovery-code set beside the live one and returns it.
+ // The old codes keep working until ConfirmRecoveryCodes promotes these, so
+ // a caller who closes the page mid-way is not left without any.
+ // Permissions required: None beyond being signed in as `name`.
+ RegenerateRecoveryCodes(context.Context, *RegenerateRecoveryCodesRequest) (*RegenerateRecoveryCodesResponse, error)
+ // Promotes the pending recovery codes. During first-time enrollment this is
+ // also where the pending TOTP secret goes live, so the factor and the codes
+ // that recover it start existing in the same write.
+ // Permissions required: None beyond being signed in as `name`.
+ ConfirmRecoveryCodes(context.Context, *ConfirmRecoveryCodesRequest) (*User, error)
mustEmbedUnimplementedUserServiceServer()
}
@@ -244,6 +382,24 @@ 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) ChangePassword(context.Context, *ChangePasswordRequest) (*User, error) {
+ return nil, status.Error(codes.Unimplemented, "method ChangePassword not implemented")
+}
+func (UnimplementedUserServiceServer) StartMFAEnrollment(context.Context, *StartMFAEnrollmentRequest) (*StartMFAEnrollmentResponse, error) {
+ return nil, status.Error(codes.Unimplemented, "method StartMFAEnrollment not implemented")
+}
+func (UnimplementedUserServiceServer) EnableMFA(context.Context, *EnableMFARequest) (*User, error) {
+ return nil, status.Error(codes.Unimplemented, "method EnableMFA not implemented")
+}
+func (UnimplementedUserServiceServer) DisableMFA(context.Context, *DisableMFARequest) (*User, error) {
+ return nil, status.Error(codes.Unimplemented, "method DisableMFA not implemented")
+}
+func (UnimplementedUserServiceServer) RegenerateRecoveryCodes(context.Context, *RegenerateRecoveryCodesRequest) (*RegenerateRecoveryCodesResponse, error) {
+ return nil, status.Error(codes.Unimplemented, "method RegenerateRecoveryCodes not implemented")
+}
+func (UnimplementedUserServiceServer) ConfirmRecoveryCodes(context.Context, *ConfirmRecoveryCodesRequest) (*User, error) {
+ return nil, status.Error(codes.Unimplemented, "method ConfirmRecoveryCodes not implemented")
+}
func (UnimplementedUserServiceServer) mustEmbedUnimplementedUserServiceServer() {}
func (UnimplementedUserServiceServer) testEmbeddedByValue() {}
@@ -427,6 +583,114 @@ func _UserService_UpdateEmail_Handler(srv interface{}, ctx context.Context, dec
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 {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(UserServiceServer).ChangePassword(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: UserService_ChangePassword_FullMethodName,
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(UserServiceServer).ChangePassword(ctx, req.(*ChangePasswordRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _UserService_StartMFAEnrollment_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(StartMFAEnrollmentRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(UserServiceServer).StartMFAEnrollment(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: UserService_StartMFAEnrollment_FullMethodName,
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(UserServiceServer).StartMFAEnrollment(ctx, req.(*StartMFAEnrollmentRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _UserService_EnableMFA_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(EnableMFARequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(UserServiceServer).EnableMFA(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: UserService_EnableMFA_FullMethodName,
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(UserServiceServer).EnableMFA(ctx, req.(*EnableMFARequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _UserService_DisableMFA_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(DisableMFARequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(UserServiceServer).DisableMFA(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: UserService_DisableMFA_FullMethodName,
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(UserServiceServer).DisableMFA(ctx, req.(*DisableMFARequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _UserService_RegenerateRecoveryCodes_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(RegenerateRecoveryCodesRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(UserServiceServer).RegenerateRecoveryCodes(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: UserService_RegenerateRecoveryCodes_FullMethodName,
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(UserServiceServer).RegenerateRecoveryCodes(ctx, req.(*RegenerateRecoveryCodesRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _UserService_ConfirmRecoveryCodes_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(ConfirmRecoveryCodesRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(UserServiceServer).ConfirmRecoveryCodes(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: UserService_ConfirmRecoveryCodes_FullMethodName,
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(UserServiceServer).ConfirmRecoveryCodes(ctx, req.(*ConfirmRecoveryCodesRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
// UserService_ServiceDesc is the grpc.ServiceDesc for UserService service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
@@ -470,6 +734,30 @@ var UserService_ServiceDesc = grpc.ServiceDesc{
MethodName: "UpdateEmail",
Handler: _UserService_UpdateEmail_Handler,
},
+ {
+ MethodName: "ChangePassword",
+ Handler: _UserService_ChangePassword_Handler,
+ },
+ {
+ MethodName: "StartMFAEnrollment",
+ Handler: _UserService_StartMFAEnrollment_Handler,
+ },
+ {
+ MethodName: "EnableMFA",
+ Handler: _UserService_EnableMFA_Handler,
+ },
+ {
+ MethodName: "DisableMFA",
+ Handler: _UserService_DisableMFA_Handler,
+ },
+ {
+ MethodName: "RegenerateRecoveryCodes",
+ Handler: _UserService_RegenerateRecoveryCodes_Handler,
+ },
+ {
+ MethodName: "ConfirmRecoveryCodes",
+ Handler: _UserService_ConfirmRecoveryCodes_Handler,
+ },
},
Streams: []grpc.StreamDesc{},
Metadata: "v1/user_service.proto",
diff --git a/backend/generated-go/v1/v1connect/user_service.connect.go b/backend/generated-go/v1/v1connect/user_service.connect.go
index 1ac316a536..c99995a44f 100644
--- a/backend/generated-go/v1/v1connect/user_service.connect.go
+++ b/backend/generated-go/v1/v1connect/user_service.connect.go
@@ -55,6 +55,22 @@ const (
UserServiceUndeleteUserProcedure = "/bytebase.v1.UserService/UndeleteUser"
// UserServiceUpdateEmailProcedure is the fully-qualified name of the UserService's UpdateEmail RPC.
UserServiceUpdateEmailProcedure = "/bytebase.v1.UserService/UpdateEmail"
+ // UserServiceChangePasswordProcedure is the fully-qualified name of the UserService's
+ // ChangePassword RPC.
+ UserServiceChangePasswordProcedure = "/bytebase.v1.UserService/ChangePassword"
+ // UserServiceStartMFAEnrollmentProcedure is the fully-qualified name of the UserService's
+ // StartMFAEnrollment RPC.
+ UserServiceStartMFAEnrollmentProcedure = "/bytebase.v1.UserService/StartMFAEnrollment"
+ // UserServiceEnableMFAProcedure is the fully-qualified name of the UserService's EnableMFA RPC.
+ UserServiceEnableMFAProcedure = "/bytebase.v1.UserService/EnableMFA"
+ // UserServiceDisableMFAProcedure is the fully-qualified name of the UserService's DisableMFA RPC.
+ UserServiceDisableMFAProcedure = "/bytebase.v1.UserService/DisableMFA"
+ // UserServiceRegenerateRecoveryCodesProcedure is the fully-qualified name of the UserService's
+ // RegenerateRecoveryCodes RPC.
+ UserServiceRegenerateRecoveryCodesProcedure = "/bytebase.v1.UserService/RegenerateRecoveryCodes"
+ // UserServiceConfirmRecoveryCodesProcedure is the fully-qualified name of the UserService's
+ // ConfirmRecoveryCodes RPC.
+ UserServiceConfirmRecoveryCodesProcedure = "/bytebase.v1.UserService/ConfirmRecoveryCodes"
)
// UserServiceClient is a client for the bytebase.v1.UserService service.
@@ -91,6 +107,42 @@ 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)
+ // 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
+ // end in a new password hash.
+ // Permissions required: None beyond being signed in as `name`.
+ ChangePassword(context.Context, *connect.Request[v1.ChangePasswordRequest]) (*connect.Response[v1.User], error)
+ // Mints a pending TOTP secret and recovery codes for the caller'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`.
+ StartMFAEnrollment(context.Context, *connect.Request[v1.StartMFAEnrollmentRequest]) (*connect.Response[v1.StartMFAEnrollmentResponse], error)
+ // 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.
+ EnableMFA(context.Context, *connect.Request[v1.EnableMFARequest]) (*connect.Response[v1.User], error)
+ // Turns MFA off, clearing the entire MFA config — live and pending state
+ // alike. Callers may disable their own; an administrator may disable
+ // another user's with bb.users.update, which is how a locked-out user is
+ // recovered.
+ // Permissions required: bb.users.update, unless `name` is the caller's own.
+ DisableMFA(context.Context, *connect.Request[v1.DisableMFARequest]) (*connect.Response[v1.User], error)
+ // Mints a pending recovery-code set beside the live one and returns it.
+ // The old codes keep working until ConfirmRecoveryCodes promotes these, so
+ // a caller who closes the page mid-way is not left without any.
+ // Permissions required: None beyond being signed in as `name`.
+ RegenerateRecoveryCodes(context.Context, *connect.Request[v1.RegenerateRecoveryCodesRequest]) (*connect.Response[v1.RegenerateRecoveryCodesResponse], error)
+ // Promotes the pending recovery codes. During first-time enrollment this is
+ // also where the pending TOTP secret goes live, so the factor and the codes
+ // that recover it start existing in the same write.
+ // Permissions required: None beyond being signed in as `name`.
+ ConfirmRecoveryCodes(context.Context, *connect.Request[v1.ConfirmRecoveryCodesRequest]) (*connect.Response[v1.User], error)
}
// NewUserServiceClient constructs a client for the bytebase.v1.UserService service. By default, it
@@ -158,20 +210,62 @@ func NewUserServiceClient(httpClient connect.HTTPClient, baseURL string, opts ..
connect.WithSchema(userServiceMethods.ByName("UpdateEmail")),
connect.WithClientOptions(opts...),
),
+ changePassword: connect.NewClient[v1.ChangePasswordRequest, v1.User](
+ httpClient,
+ baseURL+UserServiceChangePasswordProcedure,
+ connect.WithSchema(userServiceMethods.ByName("ChangePassword")),
+ connect.WithClientOptions(opts...),
+ ),
+ startMFAEnrollment: connect.NewClient[v1.StartMFAEnrollmentRequest, v1.StartMFAEnrollmentResponse](
+ httpClient,
+ baseURL+UserServiceStartMFAEnrollmentProcedure,
+ connect.WithSchema(userServiceMethods.ByName("StartMFAEnrollment")),
+ connect.WithClientOptions(opts...),
+ ),
+ enableMFA: connect.NewClient[v1.EnableMFARequest, v1.User](
+ httpClient,
+ baseURL+UserServiceEnableMFAProcedure,
+ connect.WithSchema(userServiceMethods.ByName("EnableMFA")),
+ connect.WithClientOptions(opts...),
+ ),
+ disableMFA: connect.NewClient[v1.DisableMFARequest, v1.User](
+ httpClient,
+ baseURL+UserServiceDisableMFAProcedure,
+ connect.WithSchema(userServiceMethods.ByName("DisableMFA")),
+ connect.WithClientOptions(opts...),
+ ),
+ regenerateRecoveryCodes: connect.NewClient[v1.RegenerateRecoveryCodesRequest, v1.RegenerateRecoveryCodesResponse](
+ httpClient,
+ baseURL+UserServiceRegenerateRecoveryCodesProcedure,
+ connect.WithSchema(userServiceMethods.ByName("RegenerateRecoveryCodes")),
+ connect.WithClientOptions(opts...),
+ ),
+ confirmRecoveryCodes: connect.NewClient[v1.ConfirmRecoveryCodesRequest, v1.User](
+ httpClient,
+ baseURL+UserServiceConfirmRecoveryCodesProcedure,
+ connect.WithSchema(userServiceMethods.ByName("ConfirmRecoveryCodes")),
+ connect.WithClientOptions(opts...),
+ ),
}
}
// userServiceClient implements UserServiceClient.
type userServiceClient struct {
- getUser *connect.Client[v1.GetUserRequest, v1.User]
- batchGetUsers *connect.Client[v1.BatchGetUsersRequest, v1.BatchGetUsersResponse]
- getCurrentUser *connect.Client[emptypb.Empty, v1.User]
- listUsers *connect.Client[v1.ListUsersRequest, v1.ListUsersResponse]
- createUser *connect.Client[v1.CreateUserRequest, v1.User]
- updateUser *connect.Client[v1.UpdateUserRequest, v1.User]
- deleteUser *connect.Client[v1.DeleteUserRequest, emptypb.Empty]
- undeleteUser *connect.Client[v1.UndeleteUserRequest, v1.User]
- updateEmail *connect.Client[v1.UpdateEmailRequest, v1.User]
+ getUser *connect.Client[v1.GetUserRequest, v1.User]
+ batchGetUsers *connect.Client[v1.BatchGetUsersRequest, v1.BatchGetUsersResponse]
+ getCurrentUser *connect.Client[emptypb.Empty, v1.User]
+ listUsers *connect.Client[v1.ListUsersRequest, v1.ListUsersResponse]
+ createUser *connect.Client[v1.CreateUserRequest, v1.User]
+ updateUser *connect.Client[v1.UpdateUserRequest, v1.User]
+ deleteUser *connect.Client[v1.DeleteUserRequest, emptypb.Empty]
+ undeleteUser *connect.Client[v1.UndeleteUserRequest, v1.User]
+ updateEmail *connect.Client[v1.UpdateEmailRequest, v1.User]
+ changePassword *connect.Client[v1.ChangePasswordRequest, v1.User]
+ startMFAEnrollment *connect.Client[v1.StartMFAEnrollmentRequest, v1.StartMFAEnrollmentResponse]
+ enableMFA *connect.Client[v1.EnableMFARequest, v1.User]
+ disableMFA *connect.Client[v1.DisableMFARequest, v1.User]
+ regenerateRecoveryCodes *connect.Client[v1.RegenerateRecoveryCodesRequest, v1.RegenerateRecoveryCodesResponse]
+ confirmRecoveryCodes *connect.Client[v1.ConfirmRecoveryCodesRequest, v1.User]
}
// GetUser calls bytebase.v1.UserService.GetUser.
@@ -219,6 +313,36 @@ func (c *userServiceClient) UpdateEmail(ctx context.Context, req *connect.Reques
return c.updateEmail.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)
+}
+
+// StartMFAEnrollment calls bytebase.v1.UserService.StartMFAEnrollment.
+func (c *userServiceClient) StartMFAEnrollment(ctx context.Context, req *connect.Request[v1.StartMFAEnrollmentRequest]) (*connect.Response[v1.StartMFAEnrollmentResponse], error) {
+ return c.startMFAEnrollment.CallUnary(ctx, req)
+}
+
+// EnableMFA calls bytebase.v1.UserService.EnableMFA.
+func (c *userServiceClient) EnableMFA(ctx context.Context, req *connect.Request[v1.EnableMFARequest]) (*connect.Response[v1.User], error) {
+ return c.enableMFA.CallUnary(ctx, req)
+}
+
+// DisableMFA calls bytebase.v1.UserService.DisableMFA.
+func (c *userServiceClient) DisableMFA(ctx context.Context, req *connect.Request[v1.DisableMFARequest]) (*connect.Response[v1.User], error) {
+ return c.disableMFA.CallUnary(ctx, req)
+}
+
+// RegenerateRecoveryCodes calls bytebase.v1.UserService.RegenerateRecoveryCodes.
+func (c *userServiceClient) RegenerateRecoveryCodes(ctx context.Context, req *connect.Request[v1.RegenerateRecoveryCodesRequest]) (*connect.Response[v1.RegenerateRecoveryCodesResponse], error) {
+ return c.regenerateRecoveryCodes.CallUnary(ctx, req)
+}
+
+// ConfirmRecoveryCodes calls bytebase.v1.UserService.ConfirmRecoveryCodes.
+func (c *userServiceClient) ConfirmRecoveryCodes(ctx context.Context, req *connect.Request[v1.ConfirmRecoveryCodesRequest]) (*connect.Response[v1.User], error) {
+ return c.confirmRecoveryCodes.CallUnary(ctx, req)
+}
+
// UserServiceHandler is an implementation of the bytebase.v1.UserService service.
type UserServiceHandler interface {
// Get the user.
@@ -253,6 +377,42 @@ 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)
+ // 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
+ // end in a new password hash.
+ // Permissions required: None beyond being signed in as `name`.
+ ChangePassword(context.Context, *connect.Request[v1.ChangePasswordRequest]) (*connect.Response[v1.User], error)
+ // Mints a pending TOTP secret and recovery codes for the caller'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`.
+ StartMFAEnrollment(context.Context, *connect.Request[v1.StartMFAEnrollmentRequest]) (*connect.Response[v1.StartMFAEnrollmentResponse], error)
+ // 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.
+ EnableMFA(context.Context, *connect.Request[v1.EnableMFARequest]) (*connect.Response[v1.User], error)
+ // Turns MFA off, clearing the entire MFA config — live and pending state
+ // alike. Callers may disable their own; an administrator may disable
+ // another user's with bb.users.update, which is how a locked-out user is
+ // recovered.
+ // Permissions required: bb.users.update, unless `name` is the caller's own.
+ DisableMFA(context.Context, *connect.Request[v1.DisableMFARequest]) (*connect.Response[v1.User], error)
+ // Mints a pending recovery-code set beside the live one and returns it.
+ // The old codes keep working until ConfirmRecoveryCodes promotes these, so
+ // a caller who closes the page mid-way is not left without any.
+ // Permissions required: None beyond being signed in as `name`.
+ RegenerateRecoveryCodes(context.Context, *connect.Request[v1.RegenerateRecoveryCodesRequest]) (*connect.Response[v1.RegenerateRecoveryCodesResponse], error)
+ // Promotes the pending recovery codes. During first-time enrollment this is
+ // also where the pending TOTP secret goes live, so the factor and the codes
+ // that recover it start existing in the same write.
+ // Permissions required: None beyond being signed in as `name`.
+ ConfirmRecoveryCodes(context.Context, *connect.Request[v1.ConfirmRecoveryCodesRequest]) (*connect.Response[v1.User], error)
}
// NewUserServiceHandler builds an HTTP handler from the service implementation. It returns the path
@@ -316,6 +476,42 @@ func NewUserServiceHandler(svc UserServiceHandler, opts ...connect.HandlerOption
connect.WithSchema(userServiceMethods.ByName("UpdateEmail")),
connect.WithHandlerOptions(opts...),
)
+ userServiceChangePasswordHandler := connect.NewUnaryHandler(
+ UserServiceChangePasswordProcedure,
+ svc.ChangePassword,
+ connect.WithSchema(userServiceMethods.ByName("ChangePassword")),
+ connect.WithHandlerOptions(opts...),
+ )
+ userServiceStartMFAEnrollmentHandler := connect.NewUnaryHandler(
+ UserServiceStartMFAEnrollmentProcedure,
+ svc.StartMFAEnrollment,
+ connect.WithSchema(userServiceMethods.ByName("StartMFAEnrollment")),
+ connect.WithHandlerOptions(opts...),
+ )
+ userServiceEnableMFAHandler := connect.NewUnaryHandler(
+ UserServiceEnableMFAProcedure,
+ svc.EnableMFA,
+ connect.WithSchema(userServiceMethods.ByName("EnableMFA")),
+ connect.WithHandlerOptions(opts...),
+ )
+ userServiceDisableMFAHandler := connect.NewUnaryHandler(
+ UserServiceDisableMFAProcedure,
+ svc.DisableMFA,
+ connect.WithSchema(userServiceMethods.ByName("DisableMFA")),
+ connect.WithHandlerOptions(opts...),
+ )
+ userServiceRegenerateRecoveryCodesHandler := connect.NewUnaryHandler(
+ UserServiceRegenerateRecoveryCodesProcedure,
+ svc.RegenerateRecoveryCodes,
+ connect.WithSchema(userServiceMethods.ByName("RegenerateRecoveryCodes")),
+ connect.WithHandlerOptions(opts...),
+ )
+ userServiceConfirmRecoveryCodesHandler := connect.NewUnaryHandler(
+ UserServiceConfirmRecoveryCodesProcedure,
+ svc.ConfirmRecoveryCodes,
+ connect.WithSchema(userServiceMethods.ByName("ConfirmRecoveryCodes")),
+ connect.WithHandlerOptions(opts...),
+ )
return "/bytebase.v1.UserService/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case UserServiceGetUserProcedure:
@@ -336,6 +532,18 @@ func NewUserServiceHandler(svc UserServiceHandler, opts ...connect.HandlerOption
userServiceUndeleteUserHandler.ServeHTTP(w, r)
case UserServiceUpdateEmailProcedure:
userServiceUpdateEmailHandler.ServeHTTP(w, r)
+ case UserServiceChangePasswordProcedure:
+ userServiceChangePasswordHandler.ServeHTTP(w, r)
+ case UserServiceStartMFAEnrollmentProcedure:
+ userServiceStartMFAEnrollmentHandler.ServeHTTP(w, r)
+ case UserServiceEnableMFAProcedure:
+ userServiceEnableMFAHandler.ServeHTTP(w, r)
+ case UserServiceDisableMFAProcedure:
+ userServiceDisableMFAHandler.ServeHTTP(w, r)
+ case UserServiceRegenerateRecoveryCodesProcedure:
+ userServiceRegenerateRecoveryCodesHandler.ServeHTTP(w, r)
+ case UserServiceConfirmRecoveryCodesProcedure:
+ userServiceConfirmRecoveryCodesHandler.ServeHTTP(w, r)
default:
http.NotFound(w, r)
}
@@ -380,3 +588,27 @@ func (UnimplementedUserServiceHandler) UndeleteUser(context.Context, *connect.Re
func (UnimplementedUserServiceHandler) UpdateEmail(context.Context, *connect.Request[v1.UpdateEmailRequest]) (*connect.Response[v1.User], error) {
return nil, connect.NewError(connect.CodeUnimplemented, errors.New("bytebase.v1.UserService.UpdateEmail 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"))
+}
+
+func (UnimplementedUserServiceHandler) StartMFAEnrollment(context.Context, *connect.Request[v1.StartMFAEnrollmentRequest]) (*connect.Response[v1.StartMFAEnrollmentResponse], error) {
+ return nil, connect.NewError(connect.CodeUnimplemented, errors.New("bytebase.v1.UserService.StartMFAEnrollment is not implemented"))
+}
+
+func (UnimplementedUserServiceHandler) EnableMFA(context.Context, *connect.Request[v1.EnableMFARequest]) (*connect.Response[v1.User], error) {
+ return nil, connect.NewError(connect.CodeUnimplemented, errors.New("bytebase.v1.UserService.EnableMFA is not implemented"))
+}
+
+func (UnimplementedUserServiceHandler) DisableMFA(context.Context, *connect.Request[v1.DisableMFARequest]) (*connect.Response[v1.User], error) {
+ return nil, connect.NewError(connect.CodeUnimplemented, errors.New("bytebase.v1.UserService.DisableMFA is not implemented"))
+}
+
+func (UnimplementedUserServiceHandler) RegenerateRecoveryCodes(context.Context, *connect.Request[v1.RegenerateRecoveryCodesRequest]) (*connect.Response[v1.RegenerateRecoveryCodesResponse], error) {
+ return nil, connect.NewError(connect.CodeUnimplemented, errors.New("bytebase.v1.UserService.RegenerateRecoveryCodes is not implemented"))
+}
+
+func (UnimplementedUserServiceHandler) ConfirmRecoveryCodes(context.Context, *connect.Request[v1.ConfirmRecoveryCodesRequest]) (*connect.Response[v1.User], error) {
+ return nil, connect.NewError(connect.CodeUnimplemented, errors.New("bytebase.v1.UserService.ConfirmRecoveryCodes is not implemented"))
+}
diff --git a/backend/store/mfa_pending_version_test.go b/backend/store/mfa_pending_version_test.go
new file mode 100644
index 0000000000..474abfe471
--- /dev/null
+++ b/backend/store/mfa_pending_version_test.go
@@ -0,0 +1,127 @@
+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)
+
+ user, err := s.CreateUser(ctx, &store.UserMessage{
+ Email: "[email protected]",
+ Name: "Pending",
+ PasswordHash: "unused",
+ })
+ 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")
+}
diff --git a/backend/store/principal.go b/backend/store/principal.go
index 89faa412ea..735be66e5e 100644
--- a/backend/store/principal.go
+++ b/backend/store/principal.go
@@ -3,6 +3,7 @@ package store
import (
"context"
"database/sql"
+ "encoding/json"
"fmt"
"strings"
"time"
@@ -330,6 +331,94 @@ func listUserImpl(ctx context.Context, txn *sql.Tx, find *FindUserMessage) ([]*U
return userMessages, 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
+// resurrects the factor an administrator disabled, or the recovery codes a
+// confirmation just rotated away, whenever either commits while the mint is in
+// flight.
+//
+// All three are always written, so a regeneration clears any pending secret an
+// 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 {
+ codesJSON, err := json.Marshal(tempRecoveryCodes)
+ if err != nil {
+ return err
+ }
+ // protojson's spelling for the MFAConfig fields, and its timestamp format:
+ // this JSON is read back through protojson.Unmarshal.
+ q := qb.Q().Space(`
+ UPDATE principal
+ SET mfa_config = jsonb_set(
+ jsonb_set(
+ jsonb_set(mfa_config, '{tempOtpSecret}', to_jsonb(?::text)),
+ '{tempRecoveryCodes}', ?::jsonb),
+ '{tempOtpSecretCreatedTime}', to_jsonb(?::text))
+ WHERE id = ?
+ RETURNING email
+ `, tempOtpSecret, codesJSON, createdTime.UTC().Format(time.RFC3339Nano), userID)
+ query, args, err := q.ToSQL()
+ if err != nil {
+ return errors.Wrapf(err, "failed to build sql")
+ }
+ var email string
+ if err := s.GetDB().QueryRowContext(ctx, query, args...).Scan(&email); err != nil {
+ return errors.Wrapf(err, "failed to set pending mfa state")
+ }
+ s.userEmailCache.Remove(email)
+ return nil
+}
+
+// UpdateUserMFAConfigIfPending replaces the account's MFA config, but only
+// while the pending enrollment recorded on the row is still the one the caller
+// verified. Returns nil when it is not: another tab minted a fresh enrollment,
+// or an administrator disabled MFA, in between.
+//
+// The comparison has to happen in the same statement as the write. Checking a
+// user read moments earlier and then writing unconditionally leaves a window
+// where a confirmation promotes an enrollment nobody is waiting for — or
+// re-enables MFA the administrator just cleared for a locked-out user.
+func (s *Store) UpdateUserMFAConfigIfPending(ctx context.Context, userID int, expectedPendingVersion time.Time, mfaConfig *storepb.MFAConfig) (*UserMessage, error) {
+ mfaConfigBytes, err := protojson.Marshal(mfaConfig)
+ if err != nil {
+ return nil, err
+ }
+ // tempOtpSecretCreatedTime is protojson's camelCase spelling, and comparing
+ // 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.
+ 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)
+ sqlStr, args, err := q.ToSQL()
+ if err != nil {
+ return nil, errors.Wrapf(err, "failed to build sql")
+ }
+
+ tx, err := s.GetDB().BeginTx(ctx, nil)
+ if err != nil {
+ return nil, err
+ }
+ defer tx.Rollback()
+
+ updatedUser, err := scanPrincipalRow(ctx, tx, sqlStr, args)
+ if err != nil {
+ if errors.Is(err, sql.ErrNoRows) {
+ return nil, nil
+ }
+ return nil, errors.Wrapf(err, "failed to update mfa config")
+ }
+ if err := tx.Commit(); err != nil {
+ return nil, err
+ }
+
+ s.userEmailCache.Add(updatedUser.Email, updatedUser)
+ return updatedUser, nil
+}
+
// scanPrincipalRow scans a principal row into a UserMessage (without groups).
func scanPrincipalRow(ctx context.Context, tx *sql.Tx, sqlStr string, args []any) (*UserMessage, error) {
var user UserMessage
diff --git a/backend/tests/login_audit_test.go b/backend/tests/login_audit_test.go
index efface2f64..cbdd62eba3 100644
--- a/backend/tests/login_audit_test.go
+++ b/backend/tests/login_audit_test.go
@@ -42,18 +42,21 @@ func TestLoginFailureLockout(t *testing.T) {
a.NoError(err)
defer metadataDB.Close()
userName := common.FormatUserEmail("[email protected]")
- mfaSetup, err := ctl.userServiceClient.UpdateUser(ctx, connect.NewRequest(&v1pb.UpdateUserRequest{
- User: &v1pb.User{Name: userName},
- UpdateMask: &fieldmaskpb.FieldMask{},
- RegenerateTempMfaSecret: true,
+ mfaSetup, err := ctl.userServiceClient.StartMFAEnrollment(ctx, connect.NewRequest(&v1pb.StartMFAEnrollmentRequest{
+ Name: userName,
}))
a.NoError(err)
- validOTP, err := totp.GenerateCode(mfaSetup.Msg.TempOtpSecret, time.Now())
+ validOTP, err := totp.GenerateCode(mfaSetup.Msg.OtpSecret, time.Now())
a.NoError(err)
- _, err = ctl.userServiceClient.UpdateUser(ctx, connect.NewRequest(&v1pb.UpdateUserRequest{
- User: &v1pb.User{Name: userName, MfaEnabled: true},
- UpdateMask: &fieldmaskpb.FieldMask{Paths: []string{"mfa_enabled"}},
- OtpCode: &validOTP,
+ _, err = ctl.userServiceClient.EnableMFA(ctx, connect.NewRequest(&v1pb.EnableMFARequest{
+ Name: userName,
+ OtpCode: validOTP,
+ PendingVersion: mfaSetup.Msg.PendingVersion,
+ }))
+ a.NoError(err)
+ _, err = ctl.userServiceClient.ConfirmRecoveryCodes(ctx, connect.NewRequest(&v1pb.ConfirmRecoveryCodesRequest{
+ Name: userName,
+ PendingVersion: mfaSetup.Msg.PendingVersion,
}))
a.NoError(err)
diff --git a/backend/tests/mcp_forbidden_class_test.go b/backend/tests/mcp_forbidden_class_test.go
index b34d13ac8c..cb1af09d6a 100644
--- a/backend/tests/mcp_forbidden_class_test.go
+++ b/backend/tests/mcp_forbidden_class_test.go
@@ -7,7 +7,6 @@ import (
"connectrpc.com/connect"
"github.com/stretchr/testify/require"
- "google.golang.org/protobuf/types/known/fieldmaskpb"
v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"
)
@@ -193,9 +192,9 @@ func TestWebUserStillChangesPasswordAndLogsIn(t *testing.T) {
// console does.
admin := ctl.authInterceptor.token
ctl.authInterceptor.token = login.Msg.Token
- _, err = ctl.userServiceClient.UpdateUser(ctx, connect.NewRequest(&v1pb.UpdateUserRequest{
- User: &v1pb.User{Name: "users/" + webEmail, Password: newPassword},
- UpdateMask: &fieldmaskpb.FieldMask{Paths: []string{"password"}},
+ _, err = ctl.userServiceClient.ChangePassword(ctx, connect.NewRequest(&v1pb.ChangePasswordRequest{
+ Name: "users/" + webEmail,
+ NewPassword: newPassword,
}))
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 f0e55f159a..7b7083e4dc 100644
--- a/backend/tests/read_path_secret_test.go
+++ b/backend/tests/read_path_secret_test.go
@@ -100,18 +100,14 @@ func TestReadPathHidesTheWebhookURL(t *testing.T) {
}
}
-// TestReadPathHidesTheMFAEnrollmentSecrets covers the third leak and the
-// constraint that makes it awkward: one converter serves both the reads and the
-// RPC that mints the enrollment. The mint has to keep the secrets — the console
-// renders the QR code and the recovery codes out of that response and the
-// server keeps no other copy to hand over — and every read has to lose them.
-//
-// GetUser is here beside GetCurrentUser because the leak was never
-// GetCurrentUser's: the converter exposed the fields to any read whose subject
-// was the caller, so reading your own profile through GetUser leaked the same
-// TOTP seed. GetUser stays EXCLUDED for MCP on other grounds, which is exactly
-// why the fix could not live in one RPC.
-func TestReadPathHidesTheMFAEnrollmentSecrets(t *testing.T) {
+// TestEnrollmentSecretsLiveOnlyInTheMintingResponses covers the third leak and
+// what replaced the fix for it. The secrets used to ride on the User resource,
+// where every read had to remember to drop them; they now exist only in the
+// responses of the two methods that mint them, and the User message has no
+// field left to leak. This asserts the half a type cannot: that the minting
+// responses do carry them, and that enrollment still completes against the
+// seed the caller was handed.
+func TestEnrollmentSecretsLiveOnlyInTheMintingResponses(t *testing.T) {
t.Parallel()
a := require.New(t)
ctx := context.Background()
@@ -121,63 +117,35 @@ func TestReadPathHidesTheMFAEnrollmentSecrets(t *testing.T) {
defer ctl.Close(ctx)
userName := common.FormatUserEmail("[email protected]")
- minted, err := ctl.userServiceClient.UpdateUser(ctx, connect.NewRequest(&v1pb.UpdateUserRequest{
- User: &v1pb.User{Name: userName},
- UpdateMask: &fieldmaskpb.FieldMask{},
- RegenerateTempMfaSecret: true,
+ minted, err := ctl.userServiceClient.StartMFAEnrollment(ctx, connect.NewRequest(&v1pb.StartMFAEnrollmentRequest{
+ Name: userName,
}))
a.NoError(err)
- a.NotEmpty(minted.Msg.TempOtpSecret, "the minting response is the only place the console can read the TOTP seed")
- a.NotEmpty(minted.Msg.TempRecoveryCodes, "and the only place it can read the recovery codes")
- a.NotNil(minted.Msg.TempOtpSecretCreatedTime, "the countdown needs the moment the window opened")
+ a.NotEmpty(minted.Msg.OtpSecret, "the minting response is the only place the console can read the TOTP seed")
+ a.NotEmpty(minted.Msg.RecoveryCodes, "and the only place it can read the recovery codes")
+ a.NotNil(minted.Msg.ExpireTime, "the countdown needs to know when the window closes")
- current, err := ctl.userServiceClient.GetCurrentUser(ctx, connect.NewRequest(&emptypb.Empty{}))
- a.NoError(err)
- self, err := ctl.userServiceClient.GetUser(ctx, connect.NewRequest(&v1pb.GetUserRequest{Name: userName}))
+ // The enrollment completes against the seed the console was handed, which
+ // is what makes it safe for the reads to carry nothing.
+ otp, err := totp.GenerateCode(minted.Msg.OtpSecret, time.Now())
a.NoError(err)
-
- for rpc, user := range map[string]*v1pb.User{"GetCurrentUser": current.Msg, "GetUser": self.Msg} {
- a.Empty(user.TempOtpSecret, "%s returns the TOTP seed of an open enrollment", rpc)
- a.Empty(user.TempRecoveryCodes, "%s returns the recovery codes of an open enrollment", rpc)
- a.NotNil(user.TempOtpSecretCreatedTime,
- "%s must still say an enrollment is open and when it expires; that is not a secret", rpc)
- }
-
- // An update that mints nothing does not answer with the enrollment either,
- // even though the window is open. UpdateUser is one RPC doing several jobs,
- // and only the two that drive the enrollment carry it back.
- renamed, err := ctl.userServiceClient.UpdateUser(ctx, connect.NewRequest(&v1pb.UpdateUserRequest{
- User: &v1pb.User{Name: userName, Title: "Demo Renamed"},
- UpdateMask: &fieldmaskpb.FieldMask{Paths: []string{"title"}},
+ _, err = ctl.userServiceClient.EnableMFA(ctx, connect.NewRequest(&v1pb.EnableMFARequest{
+ Name: userName,
+ OtpCode: otp,
+ PendingVersion: minted.Msg.PendingVersion,
}))
a.NoError(err)
- a.Equal("Demo Renamed", renamed.Msg.Title)
- a.Empty(renamed.Msg.TempOtpSecret, "a title update mints nothing and must carry nothing")
- a.Empty(renamed.Msg.TempRecoveryCodes)
-
- // The enrollment still completes, which is the whole point of leaving the
- // minting response alone: the seed the console was handed is the seed the
- // server validates against. The otp_code verification is the other request
- // that answers with the enrollment, because it is the step the console
- // moves to the recovery-code screen from.
- otp, err := totp.GenerateCode(minted.Msg.TempOtpSecret, time.Now())
- a.NoError(err)
- verified, err := ctl.userServiceClient.UpdateUser(ctx, connect.NewRequest(&v1pb.UpdateUserRequest{
- User: &v1pb.User{Name: userName},
- UpdateMask: &fieldmaskpb.FieldMask{},
- OtpCode: &otp,
+
+ confirmed, err := ctl.userServiceClient.ConfirmRecoveryCodes(ctx, connect.NewRequest(&v1pb.ConfirmRecoveryCodesRequest{
+ Name: userName,
+ PendingVersion: minted.Msg.PendingVersion,
}))
a.NoError(err)
- a.NotEmpty(verified.Msg.TempRecoveryCodes,
- "the console reads the recovery codes it asks the user to save out of this response")
+ a.True(confirmed.Msg.MfaEnabled, "confirming the codes is what makes the factor live")
- enabled, err := ctl.userServiceClient.UpdateUser(ctx, connect.NewRequest(&v1pb.UpdateUserRequest{
- User: &v1pb.User{Name: userName, MfaEnabled: true},
- UpdateMask: &fieldmaskpb.FieldMask{Paths: []string{"mfa_enabled"}},
- OtpCode: &otp,
- }))
+ current, err := ctl.userServiceClient.GetCurrentUser(ctx, connect.NewRequest(&emptypb.Empty{}))
a.NoError(err)
- a.True(enabled.Msg.MfaEnabled)
+ a.True(current.Msg.MfaEnabled, "the read still reports that a factor exists")
}
// TestMCPServesTheReadsTheRedactionFreed is the regression this batch exists to
@@ -217,10 +185,8 @@ func TestMCPServesTheReadsTheRedactionFreed(t *testing.T) {
}))
a.NoError(err)
- _, err = ctl.userServiceClient.UpdateUser(ctx, connect.NewRequest(&v1pb.UpdateUserRequest{
- User: &v1pb.User{Name: common.FormatUserEmail("[email protected]")},
- UpdateMask: &fieldmaskpb.FieldMask{},
- RegenerateTempMfaSecret: true,
+ _, err = ctl.userServiceClient.StartMFAEnrollment(ctx, connect.NewRequest(&v1pb.StartMFAEnrollmentRequest{
+ Name: common.FormatUserEmail("[email protected]"),
}))
a.NoError(err)
@@ -303,3 +269,198 @@ func TestMCPServesTheReadsTheRedactionFreed(t *testing.T) {
"%s must still be refused for what it does; got %q", tc.operation, got.Error)
}
}
+
+// TestMFAReplacementPromotesTheNewAuthenticator covers the enrollment the
+// account page reaches through Edit rather than Enable: a user who already has
+// a factor scans a new authenticator, and it is the new one that has to be live
+// afterwards. Confirming only the recovery codes while leaving the old secret in
+// place reports success and then rejects every code from the authenticator the
+// user just set up — a lockout as soon as they delete the old entry.
+func TestMFAReplacementPromotesTheNewAuthenticator(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)
+
+ userName := common.FormatUserEmail("[email protected]")
+ enroll := func() string {
+ t.Helper()
+ 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,
+ PendingVersion: minted.Msg.PendingVersion,
+ }))
+ a.NoError(err)
+ _, err = ctl.userServiceClient.ConfirmRecoveryCodes(ctx, connect.NewRequest(&v1pb.ConfirmRecoveryCodesRequest{
+ Name: userName,
+ PendingVersion: minted.Msg.PendingVersion,
+ }))
+ a.NoError(err)
+ return minted.Msg.OtpSecret
+ }
+
+ firstSecret := enroll()
+ replacementSecret := enroll()
+ a.NotEqual(firstSecret, replacementSecret)
+
+ // Sign in with the replacement authenticator. This is the assertion that
+ // matters: the login path validates against the stored live secret, so it
+ // passes only if the enrollment promoted the one just scanned.
+ adminToken := ctl.authInterceptor.token
+ ctl.authInterceptor.token = ""
+ defer func() { ctl.authInterceptor.token = adminToken }()
+
+ mfaStart, err := ctl.authServiceClient.Login(ctx, connect.NewRequest(&v1pb.LoginRequest{
+ Email: "[email protected]",
+ Password: "1024bytebase",
+ }))
+ a.NoError(err)
+ mfaTempToken := mfaStart.Msg.GetMfaTempToken()
+ a.NotEmpty(mfaTempToken, "the account must still require a second factor")
+
+ otp, err := totp.GenerateCode(replacementSecret, time.Now())
+ a.NoError(err)
+ loggedIn, err := ctl.authServiceClient.Login(ctx, connect.NewRequest(&v1pb.LoginRequest{
+ OtpCode: &otp,
+ MfaTempToken: &mfaTempToken,
+ }))
+ a.NoError(err, "a code from the newly enrolled authenticator must be accepted")
+ a.NotEmpty(loggedIn.Msg.Token)
+}
+
+// TestSupersededPendingStateIsRefused covers two flows racing for the one
+// pending slot: a recovery-code regeneration open in one tab while an
+// enrollment starts in another. The regeneration's confirmation must not
+// promote the enrollment's secret — the caller never saw it, and the codes it
+// downloaded are not the ones that would go live. Both are lockouts, so the
+// stale confirmation is refused instead.
+func TestSupersededPendingStateIsRefused(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)
+
+ userName := common.FormatUserEmail("[email protected]")
+ enrolled, err := ctl.userServiceClient.StartMFAEnrollment(ctx, connect.NewRequest(&v1pb.StartMFAEnrollmentRequest{
+ Name: userName,
+ }))
+ a.NoError(err)
+ otp, err := totp.GenerateCode(enrolled.Msg.OtpSecret, time.Now())
+ a.NoError(err)
+ _, err = ctl.userServiceClient.EnableMFA(ctx, connect.NewRequest(&v1pb.EnableMFARequest{
+ Name: userName,
+ OtpCode: otp,
+ PendingVersion: enrolled.Msg.PendingVersion,
+ }))
+ a.NoError(err)
+ _, err = ctl.userServiceClient.ConfirmRecoveryCodes(ctx, connect.NewRequest(&v1pb.ConfirmRecoveryCodesRequest{
+ Name: userName,
+ PendingVersion: enrolled.Msg.PendingVersion,
+ }))
+ a.NoError(err)
+
+ // Tab one opens the regeneration view and is shown a code set.
+ regenerated, err := ctl.userServiceClient.RegenerateRecoveryCodes(ctx, connect.NewRequest(&v1pb.RegenerateRecoveryCodesRequest{
+ Name: userName,
+ }))
+ a.NoError(err)
+
+ // Tab two starts replacing the authenticator, which takes over the one
+ // pending slot.
+ replacement, err := ctl.userServiceClient.StartMFAEnrollment(ctx, connect.NewRequest(&v1pb.StartMFAEnrollmentRequest{
+ Name: userName,
+ }))
+ a.NoError(err)
+ a.NotEqual(enrolled.Msg.OtpSecret, replacement.Msg.OtpSecret)
+
+ // Tab one saves its codes and confirms.
+ _, err = ctl.userServiceClient.ConfirmRecoveryCodes(ctx, connect.NewRequest(&v1pb.ConfirmRecoveryCodesRequest{
+ Name: userName,
+ PendingVersion: regenerated.Msg.PendingVersion,
+ }))
+ a.Equal(connect.CodeFailedPrecondition, connect.CodeOf(err),
+ "a confirmation whose pending state was superseded must be refused")
+
+ // The account still signs in with the authenticator it had, which is the
+ // point: nothing was promoted behind the user's back.
+ adminToken := ctl.authInterceptor.token
+ ctl.authInterceptor.token = ""
+ defer func() { ctl.authInterceptor.token = adminToken }()
+
+ mfaStart, err := ctl.authServiceClient.Login(ctx, connect.NewRequest(&v1pb.LoginRequest{
+ Email: "[email protected]",
+ Password: "1024bytebase",
+ }))
+ a.NoError(err)
+ mfaTempToken := mfaStart.Msg.GetMfaTempToken()
+ a.NotEmpty(mfaTempToken)
+ liveOTP, err := totp.GenerateCode(enrolled.Msg.OtpSecret, time.Now())
+ a.NoError(err)
+ loggedIn, err := ctl.authServiceClient.Login(ctx, connect.NewRequest(&v1pb.LoginRequest{
+ OtpCode: &liveOTP,
+ MfaTempToken: &mfaTempToken,
+ }))
+ a.NoError(err, "the authenticator the user actually enrolled must still work")
+ a.NotEmpty(loggedIn.Msg.Token)
+}
+
+// TestConfirmationCannotRevivePendingStateItRaced pins the promotion's version
+// predicate rather than the read in front of it. An administrator clearing a
+// locked-out user's factor, or another tab minting a fresh enrollment, can land
+// between a confirmation's check and its write; without the predicate on the
+// write itself, that confirmation still promotes what it read and brings back a
+// factor the administrator just removed.
+func TestConfirmationCannotRevivePendingStateItRaced(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)
+
+ userName := common.FormatUserEmail("[email protected]")
+ 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,
+ 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.
+ _, err = ctl.userServiceClient.DisableMFA(ctx, connect.NewRequest(&v1pb.DisableMFARequest{
+ Name: userName,
+ }))
+ a.NoError(err)
+
+ // The stale tab confirms with the version it was handed.
+ _, err = ctl.userServiceClient.ConfirmRecoveryCodes(ctx, connect.NewRequest(&v1pb.ConfirmRecoveryCodesRequest{
+ Name: userName,
+ PendingVersion: minted.Msg.PendingVersion,
+ }))
+ a.Equal(connect.CodeFailedPrecondition, connect.CodeOf(err),
+ "a confirmation whose pending state is gone must be refused")
+
+ current, err := ctl.userServiceClient.GetCurrentUser(ctx, connect.NewRequest(&emptypb.Empty{}))
+ a.NoError(err)
+ a.False(current.Msg.MfaEnabled, "MFA must stay off once it has been disabled")
+}
diff --git a/frontend/src/routes/auth/PasswordResetPage.test.tsx b/frontend/src/routes/auth/PasswordResetPage.test.tsx
index 7b192e8d0e..da3c81eaee 100644
--- a/frontend/src/routes/auth/PasswordResetPage.test.tsx
+++ b/frontend/src/routes/auth/PasswordResetPage.test.tsx
@@ -22,6 +22,9 @@ const mocks = vi.hoisted(() => ({
login: vi.fn(async () => {}),
})),
updateUser: vi.fn(),
+ changePassword: vi.fn(async () => ({ name: "users/1" })),
+ fetchCurrentUser: vi.fn(async () => ({ name: "users/1" })),
+ setCurrentUser: vi.fn(),
pushNotification: vi.fn(),
routerReplace: vi.fn(),
routerPush: vi.fn(),
@@ -48,6 +51,8 @@ vi.mock("@/stores/app", () => {
const getState = () => ({
...mocks.appStoreState,
updateUser: mocks.updateUser,
+ fetchCurrentUser: mocks.fetchCurrentUser,
+ setCurrentUser: mocks.setCurrentUser,
loadAuthenticationInfo: vi.fn().mockResolvedValue(undefined),
login: mocks.login,
setRequireResetPassword: mocks.setRequireResetPassword,
@@ -77,6 +82,9 @@ vi.mock("@/api", () => ({
resetPassword: mocks.resetPassword,
requestPasswordReset: mocks.requestPasswordReset,
},
+ userServiceClientConnect: {
+ changePassword: mocks.changePassword,
+ },
}));
vi.mock("@/lib/workspace", () => ({
@@ -236,6 +244,39 @@ describe("PasswordResetPage", () => {
unmount();
});
+ // The forced reset is the caller changing their own password, which
+ // UpdateUser refuses — it keeps the password mask for administrators
+ // resetting someone else. Sending it there strands the user on this page
+ // with no way to finish signing in.
+ test("forced-reset mode: confirm calls changePassword", async () => {
+ const { container, render, unmount } = renderIntoContainer(
+ <PasswordResetPage />
+ );
+ render();
+
+ const passwordInputs = container.querySelectorAll<HTMLInputElement>(
+ 'input[type="password"]'
+ );
+ setInputValue(passwordInputs[0], "Passw0rd!");
+ setInputValue(passwordInputs[1], "Passw0rd!");
+ const confirmBtn = Array.from(
+ container.querySelectorAll<HTMLButtonElement>("button")
+ ).find((b) => b.textContent === "common.confirm")!;
+ act(() => {
+ confirmBtn.click();
+ });
+ await flushPromises();
+
+ expect(mocks.changePassword).toHaveBeenCalledWith(
+ expect.objectContaining({ name: "users/1", newPassword: "Passw0rd!" })
+ );
+ expect(mocks.updateUser).not.toHaveBeenCalled();
+ // The response is adopted rather than refetched, so the shared user the
+ // guards read is current before this page navigates away.
+ expect(mocks.setCurrentUser).toHaveBeenCalledWith({ name: "users/1" });
+ unmount();
+ });
+
test("code mode: confirm calls resetPassword and logs in on success", async () => {
mocks.currentRoute.value.query = { email: "[email protected]" };
mocks.resetPassword.mockResolvedValue({});
diff --git a/frontend/src/routes/auth/PasswordResetPage.tsx b/frontend/src/routes/auth/PasswordResetPage.tsx
index 270bbf85ba..d9cdee2b52 100644
--- a/frontend/src/routes/auth/PasswordResetPage.tsx
+++ b/frontend/src/routes/auth/PasswordResetPage.tsx
@@ -1,8 +1,7 @@
import { create } from "@bufbuild/protobuf";
-import { FieldMaskSchema } from "@bufbuild/protobuf/wkt";
import { useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
-import { authServiceClientConnect } from "@/api";
+import { authServiceClientConnect, userServiceClientConnect } from "@/api";
import { router } from "@/app/router";
import { AUTH_SIGNIN_MODULE } from "@/app/router/handles";
import logoFull from "@/assets/logo-full.svg";
@@ -21,7 +20,7 @@ import {
LoginRequestSchema,
ResetPasswordRequestSchema,
} from "@/types/proto-es/v1/auth_service_pb";
-import { UpdateUserRequestSchema } from "@/types/proto-es/v1/user_service_pb";
+import { ChangePasswordRequestSchema } from "@/types/proto-es/v1/user_service_pb";
export function PasswordResetPage() {
const { t } = useTranslation();
@@ -153,13 +152,13 @@ export function PasswordResetPage() {
// Forced-reset mode
if (!currentUser) return;
- const patch = { ...currentUser, password };
- await useAppStore.getState().updateUser(
- create(UpdateUserRequestSchema, {
- user: patch,
- updateMask: create(FieldMaskSchema, { paths: ["password"] }),
+ const updated = await userServiceClientConnect.changePassword(
+ create(ChangePasswordRequestSchema, {
+ name: currentUser.name,
+ newPassword: password,
})
);
+ useAppStore.getState().setCurrentUser(updated);
pushNotification({
module: "bytebase",
style: "SUCCESS",
diff --git a/frontend/src/routes/workspace/profile/AccountSettingsPage.test.tsx b/frontend/src/routes/workspace/profile/AccountSettingsPage.test.tsx
index 7e38eed4e2..c98483e436 100644
--- a/frontend/src/routes/workspace/profile/AccountSettingsPage.test.tsx
+++ b/frontend/src/routes/workspace/profile/AccountSettingsPage.test.tsx
@@ -25,6 +25,7 @@ const updatedCurrentUser = {
};
const mocks = vi.hoisted(() => ({
+ setCurrentUser: vi.fn(),
useCurrentUser: vi.fn(() => legacyCurrentUser),
getWorkspaceRolesByName: vi.fn(() => new Set<string>()),
hasFeature: vi.fn(() => true),
@@ -49,6 +50,9 @@ vi.mock("@/stores/app", () => {
const buildState = () => ({
updateUser: mocks.updateUser,
updateEmail: mocks.updateEmail,
+ // The page adopts the user its mutations answer with; without this the
+ // disable path throws an unhandled rejection that reads as a pass.
+ setCurrentUser: mocks.setCurrentUser,
updateCurrentUserNameForEmailChange: () => {},
roleList: [],
workspacePolicy: undefined,
diff --git a/frontend/src/routes/workspace/profile/AccountSettingsPage.tsx b/frontend/src/routes/workspace/profile/AccountSettingsPage.tsx
index 140a3c874e..28f6e66fd1 100644
--- a/frontend/src/routes/workspace/profile/AccountSettingsPage.tsx
+++ b/frontend/src/routes/workspace/profile/AccountSettingsPage.tsx
@@ -4,6 +4,7 @@ import type { ConnectError } from "@connectrpc/connect";
import { Ellipsis } from "lucide-react";
import { useCallback, useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
+import { userServiceClientConnect } from "@/api";
import { router } from "@/app/router";
import { ACCOUNT_ROUTE_TWO_FACTOR } from "@/app/router/handles";
import { FeatureBadge } from "@/components/FeatureBadge";
@@ -32,7 +33,11 @@ import { pushNotification } from "@/stores";
import { useAppStore } from "@/stores/app";
import { AccountType, getAccountTypeByEmail } from "@/types";
import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";
-import { UpdateUserRequestSchema } from "@/types/proto-es/v1/user_service_pb";
+import {
+ ChangePasswordRequestSchema,
+ DisableMFARequestSchema,
+ UpdateUserRequestSchema,
+} from "@/types/proto-es/v1/user_service_pb";
import { hasWorkspacePermissionV2, setDocumentTitle } from "@/utils";
import { SettingsCard, SettingsRow } from "./SettingsCard";
import { getPasswordErrors, UserPasswordSection } from "./UserPasswordSection";
@@ -161,10 +166,10 @@ export function AccountSettingsPage() {
if (!allowSavePassword) return;
setSavingPassword(true);
try {
- const updated = await updateUser(
- create(UpdateUserRequestSchema, {
- user: { ...user, password },
- updateMask: create(FieldMaskSchema, { paths: ["password"] }),
+ const updated = await userServiceClientConnect.changePassword(
+ create(ChangePasswordRequestSchema, {
+ name: user.name,
+ newPassword: password,
})
);
setCurrentUser(updated);
@@ -177,14 +182,7 @@ export function AccountSettingsPage() {
} finally {
setSavingPassword(false);
}
- }, [
- allowSavePassword,
- password,
- user,
- updateUser,
- notifyUpdated,
- notifyError,
- ]);
+ }, [allowSavePassword, password, user.name, notifyUpdated, notifyError]);
const handleEnable2FA = useCallback(() => {
if (!has2FAFeature) {
@@ -212,13 +210,15 @@ export function AccountSettingsPage() {
if (disabling2FA) return;
setDisabling2FA(true);
try {
- const updated = await updateUser(
- create(UpdateUserRequestSchema, {
- user: { name: user.name, mfaEnabled: false },
- updateMask: create(FieldMaskSchema, { paths: ["mfa_enabled"] }),
- })
+ const updated = await userServiceClientConnect.disableMFA(
+ create(DisableMFARequestSchema, { name: user.name })
);
setCurrentUser(updated);
+ // The router guard reads mfa_enabled off the shared store, not this
+ // page's copy: a workspace admin who turns their own factor off while
+ // the workspace requires MFA has to be sent back to enrollment now,
+ // not whenever the session next revalidates.
+ useAppStore.getState().setCurrentUser(updated);
setShowDisable2FAConfirm(false);
setShowRegenerateView(false);
pushNotification({
@@ -231,7 +231,7 @@ export function AccountSettingsPage() {
} finally {
setDisabling2FA(false);
}
- }, [disabling2FA, user.name, updateUser, notifyError, t]);
+ }, [disabling2FA, user.name, notifyError, t]);
return (
<WorkspacePageLayout>
@@ -393,7 +393,6 @@ export function AccountSettingsPage() {
to regenerate recovery codes the account no longer has. */}
{isMFAEnabled && showRegenerateView && (
<RegenerateRecoveryCodesView
- recoveryCodes={currentUser.tempRecoveryCodes}
onClose={() => setShowRegenerateView(false)}
/>
)}
diff --git a/frontend/src/routes/workspace/two-factor/RegenerateRecoveryCodesView.tsx b/frontend/src/routes/workspace/two-factor/RegenerateRecoveryCodesView.tsx
index 66f256501a..152244c084 100644
--- a/frontend/src/routes/workspace/two-factor/RegenerateRecoveryCodesView.tsx
+++ b/frontend/src/routes/workspace/two-factor/RegenerateRecoveryCodesView.tsx
@@ -1,52 +1,52 @@
import { create } from "@bufbuild/protobuf";
-import { FieldMaskSchema } from "@bufbuild/protobuf/wkt";
+import type { Timestamp } from "@bufbuild/protobuf/wkt";
import { useCallback, useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
+import { userServiceClientConnect } from "@/api";
import { Button } from "@/components/ui/button";
import { useCurrentUser } from "@/hooks/useAppState";
import { pushNotification } from "@/stores";
-import { useAppStore } from "@/stores/app";
-import { UpdateUserRequestSchema } from "@/types/proto-es/v1/user_service_pb";
+import {
+ ConfirmRecoveryCodesRequestSchema,
+ RegenerateRecoveryCodesRequestSchema,
+} from "@/types/proto-es/v1/user_service_pb";
import { RecoveryCodesView } from "./RecoveryCodesView";
interface RegenerateRecoveryCodesViewProps {
- recoveryCodes: string[];
onClose: () => void;
}
export function RegenerateRecoveryCodesView({
- recoveryCodes,
onClose,
}: RegenerateRecoveryCodesViewProps) {
const { t } = useTranslation();
- const updateUser = useAppStore((state) => state.updateUser);
const currentUser = useCurrentUser();
+ const [recoveryCodes, setRecoveryCodes] = useState<string[]>([]);
+ const [pendingVersion, setPendingVersion] = useState<Timestamp | undefined>();
const [recoveryCodesDownloaded, setRecoveryCodesDownloaded] = 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
+ // they are confirmed below.
useEffect(() => {
- updateUser(
- create(UpdateUserRequestSchema, {
- user: {
- name: currentUser.name,
- },
- updateMask: create(FieldMaskSchema, {
- paths: [],
- }),
- regenerateTempMfaSecret: true,
- })
- );
- }, []);
+ userServiceClientConnect
+ .regenerateRecoveryCodes(
+ create(RegenerateRecoveryCodesRequestSchema, { name: currentUser.name })
+ )
+ .then((response) => {
+ setRecoveryCodes([...response.recoveryCodes]);
+ setPendingVersion(response.pendingVersion);
+ });
+ }, [currentUser.name]);
- const regenerateRecoveryCodes = useCallback(async () => {
- await updateUser(
- create(UpdateUserRequestSchema, {
- user: {
- name: currentUser.name,
- },
- updateMask: create(FieldMaskSchema, {
- paths: [],
- }),
- regenerateRecoveryCodes: true,
+ const confirmRecoveryCodes = useCallback(async () => {
+ // 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,
})
);
pushNotification({
@@ -55,7 +55,7 @@ export function RegenerateRecoveryCodesView({
title: t("two-factor.messages.recovery-codes-regenerated"),
});
onClose();
- }, [currentUser.name, onClose, t, updateUser]);
+ }, [currentUser.name, onClose, pendingVersion, t]);
return (
<>
@@ -69,7 +69,7 @@ export function RegenerateRecoveryCodesView({
</Button>
<Button
disabled={!recoveryCodesDownloaded}
- onClick={regenerateRecoveryCodes}
+ onClick={confirmRecoveryCodes}
>
{t("two-factor.setup-steps.recovery-codes-saved")}
</Button>
diff --git a/frontend/src/routes/workspace/two-factor/TwoFactorSetupPage.test.tsx b/frontend/src/routes/workspace/two-factor/TwoFactorSetupPage.test.tsx
index 874c74b94c..69d35e94bc 100644
--- a/frontend/src/routes/workspace/two-factor/TwoFactorSetupPage.test.tsx
+++ b/frontend/src/routes/workspace/two-factor/TwoFactorSetupPage.test.tsx
@@ -7,28 +7,26 @@ import { beforeEach, describe, expect, test, vi } from "vitest";
globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
).IS_REACT_ACT_ENVIRONMENT = true;
-const currentTimestamp = () => ({
- seconds: BigInt(Math.floor(Date.now() / 1000)),
+const expireTimestamp = () => ({
+ seconds: BigInt(Math.floor(Date.now() / 1000) + 300),
nanos: 0,
});
-const legacyCurrentUser = {
+const currentUser = {
name: "users/[email protected]",
- tempOtpSecret: "old-secret",
- tempOtpSecretCreatedTime: currentTimestamp(),
- tempRecoveryCodes: [],
};
-const regeneratedCurrentUser = {
- ...legacyCurrentUser,
- tempOtpSecret: "new-secret",
- tempOtpSecretCreatedTime: currentTimestamp(),
+const mintedEnrollment = {
+ otpSecret: "new-secret",
+ recoveryCodes: ["code-1", "code-2"],
+ expireTime: expireTimestamp(),
};
const mocks = vi.hoisted(() => ({
- useCurrentUser: vi.fn(() => legacyCurrentUser),
- updateUser: vi.fn(async () => regeneratedCurrentUser),
+ useCurrentUser: vi.fn(() => currentUser),
+ startMFAEnrollment: vi.fn(async () => mintedEnrollment),
+ setCurrentUser: vi.fn(),
pushNotification: vi.fn(),
routerReplace: vi.fn(),
currentRoute: {
@@ -43,10 +41,16 @@ vi.mock("@/hooks/useAppState", () => ({
vi.mock("@/stores/app", () => ({
useAppStore: (selector: (state: unknown) => unknown) =>
selector({
- updateUser: mocks.updateUser,
+ setCurrentUser: mocks.setCurrentUser,
}),
}));
+vi.mock("@/api", () => ({
+ userServiceClientConnect: {
+ startMFAEnrollment: mocks.startMFAEnrollment,
+ },
+}));
+
vi.mock("@/stores", () => ({
pushNotification: mocks.pushNotification,
}));
@@ -74,7 +78,9 @@ vi.mock("@/types/proto-es/v1/user_service_pb", async (importOriginal) => {
>();
return {
...actual,
- UpdateUserRequestSchema: {},
+ StartMFAEnrollmentRequestSchema: {},
+ EnableMFARequestSchema: {},
+ ConfirmRecoveryCodesRequestSchema: {},
};
});
@@ -146,17 +152,15 @@ beforeEach(async () => {
});
describe("TwoFactorSetupPage", () => {
- test("renders regenerated MFA secret from the update response", async () => {
+ test("renders the secret from the enrollment response, not from the user", async () => {
const { container, render, unmount } = renderIntoContainer(
<TwoFactorSetupPage />
);
await render();
- expect(mocks.updateUser).toHaveBeenCalledWith(
- expect.objectContaining({
- regenerateTempMfaSecret: true,
- })
+ expect(mocks.startMFAEnrollment).toHaveBeenCalledWith(
+ expect.objectContaining({ name: currentUser.name })
);
expect(
container
diff --git a/frontend/src/routes/workspace/two-factor/TwoFactorSetupPage.tsx b/frontend/src/routes/workspace/two-factor/TwoFactorSetupPage.tsx
index 1b3dd22986..bd9bbac7b5 100644
--- a/frontend/src/routes/workspace/two-factor/TwoFactorSetupPage.tsx
+++ b/frontend/src/routes/workspace/two-factor/TwoFactorSetupPage.tsx
@@ -1,9 +1,10 @@
import { create } from "@bufbuild/protobuf";
-import { FieldMaskSchema } from "@bufbuild/protobuf/wkt";
+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";
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 { LearnMoreLink } from "@/components/LearnMoreLink";
@@ -13,13 +14,28 @@ import { StepIndicator } from "@/components/ui/step-indicator";
import { useCurrentUser } from "@/hooks/useAppState";
import { pushNotification } from "@/stores";
import { useAppStore } from "@/stores/app";
-import { UpdateUserRequestSchema } from "@/types/proto-es/v1/user_service_pb";
+import {
+ ConfirmRecoveryCodesRequestSchema,
+ EnableMFARequestSchema,
+ StartMFAEnrollmentRequestSchema,
+} from "@/types/proto-es/v1/user_service_pb";
import { RecoveryCodesView } from "./RecoveryCodesView";
import { TwoFactorSecretModal } from "./TwoFactorSecretModal";
const ISSUER_NAME = "Bytebase";
const DIGITS = 6;
-const MFA_TEMP_SECRET_EXPIRATION = 5 * 60 * 1000; // 5 minutes
+
+// 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;
@@ -31,9 +47,9 @@ interface TwoFactorSetupPageProps {
export function TwoFactorSetupPage({ cancelAction }: TwoFactorSetupPageProps) {
const { t } = useTranslation();
- const updateUser = useAppStore((state) => state.updateUser);
- const legacyCurrentUser = useCurrentUser();
- const [currentUser, setCurrentUser] = useState(legacyCurrentUser);
+ const currentUser = useCurrentUser();
+ const setCurrentUser = useAppStore((state) => state.setCurrentUser);
+ const [enrollment, setEnrollment] = useState<Enrollment | undefined>();
const [currentStep, setCurrentStep] = useState<Step>(SETUP_AUTH_APP_STEP);
const [showSecretModal, setShowSecretModal] = useState(false);
@@ -44,13 +60,9 @@ export function TwoFactorSetupPage({ cancelAction }: TwoFactorSetupPageProps) {
const [isExpiringSoon, setIsExpiringSoon] = useState(false);
const countdownRef = useRef<ReturnType<typeof setInterval> | null>(null);
- // Keep a ref to currentUser so the interval callback always reads fresh state
- const currentUserRef = useRef(currentUser);
- currentUserRef.current = currentUser;
-
- useEffect(() => {
- setCurrentUser(legacyCurrentUser);
- }, [legacyCurrentUser]);
+ // Keep a ref to the enrollment so the interval callback always reads fresh state
+ const enrollmentRef = useRef(enrollment);
+ enrollmentRef.current = enrollment;
const stopCountdown = useCallback(() => {
if (countdownRef.current) {
@@ -60,15 +72,14 @@ export function TwoFactorSetupPage({ cancelAction }: TwoFactorSetupPageProps) {
}, []);
const updateCountdown = useCallback(() => {
- const cu = currentUserRef.current;
- if (!cu.tempOtpSecretCreatedTime) {
+ const expireTime = enrollmentRef.current?.expireTime;
+ if (!expireTime) {
setIsExpired(true);
setTimeRemaining("0:00");
return;
}
- const createdAt = Number(cu.tempOtpSecretCreatedTime.seconds) * 1000;
- const remaining = MFA_TEMP_SECRET_EXPIRATION - (Date.now() - createdAt);
+ const remaining = Number(expireTime.seconds) * 1000 - Date.now();
if (remaining <= 0) {
setIsExpired(true);
@@ -90,46 +101,38 @@ export function TwoFactorSetupPage({ cancelAction }: TwoFactorSetupPageProps) {
countdownRef.current = setInterval(updateCountdown, 1000);
}, [updateCountdown, stopCountdown]);
- const regenerateTempMfaSecret = useCallback(async () => {
- const user = await updateUser(
- create(UpdateUserRequestSchema, {
- user: {
- name: currentUser.name,
- },
- updateMask: create(FieldMaskSchema, {
- paths: [],
- }),
- regenerateTempMfaSecret: true,
- })
+ const startEnrollment = useCallback(async () => {
+ const response = await userServiceClientConnect.startMFAEnrollment(
+ create(StartMFAEnrollmentRequestSchema, { name: currentUser.name })
);
- setCurrentUser(user);
- }, [currentUser.name, updateUser]);
+ setEnrollment({
+ otpSecret: response.otpSecret,
+ recoveryCodes: [...response.recoveryCodes],
+ expireTime: response.expireTime,
+ pendingVersion: response.pendingVersion,
+ });
+ }, [currentUser.name]);
- // On mount: regenerate secret and start countdown
+ // On mount: mint an enrollment and start counting down to its expiry
useEffect(() => {
- regenerateTempMfaSecret().then(() => {
+ startEnrollment().then(() => {
startCountdown();
});
return stopCountdown;
- }, [regenerateTempMfaSecret, startCountdown, stopCountdown]);
+ }, [startEnrollment, startCountdown, stopCountdown]);
- const otpauthUrl = `otpauth://totp/${ISSUER_NAME}:${currentUser.email}?algorithm=SHA1&digits=${DIGITS}&issuer=${ISSUER_NAME}&period=30&secret=${currentUser.tempOtpSecret}`;
+ const otpauthUrl = `otpauth://totp/${ISSUER_NAME}:${currentUser.email}?algorithm=SHA1&digits=${DIGITS}&issuer=${ISSUER_NAME}&period=30&secret=${enrollment?.otpSecret ?? ""}`;
const verifyOTPCode = useCallback(
async (codes: string[]) => {
try {
- const user = await updateUser(
- create(UpdateUserRequestSchema, {
- user: {
- name: currentUser.name,
- },
- updateMask: create(FieldMaskSchema, {
- paths: [],
- }),
+ await userServiceClientConnect.enableMFA(
+ create(EnableMFARequestSchema, {
+ name: currentUser.name,
otpCode: codes.join(""),
+ pendingVersion: enrollment?.pendingVersion,
})
);
- setCurrentUser(user);
} catch (error) {
pushNotification({
module: "bytebase",
@@ -140,7 +143,7 @@ export function TwoFactorSetupPage({ cancelAction }: TwoFactorSetupPageProps) {
}
return true;
},
- [currentUser.name, updateUser]
+ [currentUser.name, enrollment?.pendingVersion]
);
const handleOtpFinish = useCallback(
@@ -168,9 +171,9 @@ export function TwoFactorSetupPage({ cancelAction }: TwoFactorSetupPageProps) {
const handleRegenerateSecret = useCallback(async () => {
setOtpCodes([]);
- await regenerateTempMfaSecret();
+ await startEnrollment();
startCountdown();
- }, [regenerateTempMfaSecret, startCountdown]);
+ }, [startEnrollment, startCountdown]);
const cancelSetup = useCallback(() => {
if (cancelAction) {
@@ -183,17 +186,19 @@ export function TwoFactorSetupPage({ cancelAction }: TwoFactorSetupPageProps) {
}, [cancelAction]);
const tryFinishSetup = useCallback(async () => {
- await updateUser(
- create(UpdateUserRequestSchema, {
- user: {
- name: currentUser.name,
- mfaEnabled: true,
- },
- updateMask: create(FieldMaskSchema, {
- paths: ["mfa_enabled"],
- }),
+ // 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,
})
);
+ // 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
+ // that and mint a second enrollment for a factor already enabled.
+ setCurrentUser(enabled);
pushNotification({
module: "bytebase",
style: "SUCCESS",
@@ -205,7 +210,7 @@ export function TwoFactorSetupPage({ cancelAction }: TwoFactorSetupPageProps) {
} else {
router.replace({ name: ACCOUNT_ROUTE });
}
- }, [currentUser.name, t, updateUser]);
+ }, [currentUser.name, enrollment?.pendingVersion, setCurrentUser, t]);
const allowNext =
currentStep === SETUP_AUTH_APP_STEP
@@ -319,7 +324,7 @@ export function TwoFactorSetupPage({ cancelAction }: TwoFactorSetupPageProps) {
{currentStep === DOWNLOAD_RECOVERY_CODES_STEP && (
<div className="w-full max-w-2xl mx-auto">
<RecoveryCodesView
- recoveryCodes={[...currentUser.tempRecoveryCodes]}
+ recoveryCodes={enrollment?.recoveryCodes ?? []}
onDownload={() => setRecoveryCodesDownloaded(true)}
/>
</div>
@@ -350,7 +355,7 @@ export function TwoFactorSetupPage({ cancelAction }: TwoFactorSetupPageProps) {
</div>
<TwoFactorSecretModal
- secret={currentUser.tempOtpSecret}
+ secret={enrollment?.otpSecret ?? ""}
open={showSecretModal}
onClose={() => setShowSecretModal(false)}
/>
diff --git a/frontend/src/routes/workspace/users/UserRowMenu.test.tsx b/frontend/src/routes/workspace/users/UserRowMenu.test.tsx
index cb8adbacd4..ade38af2c9 100644
--- a/frontend/src/routes/workspace/users/UserRowMenu.test.tsx
+++ b/frontend/src/routes/workspace/users/UserRowMenu.test.tsx
@@ -25,6 +25,13 @@ const mocks = vi.hoisted(() => ({
pushNotification: vi.fn(),
updateUser: vi.fn(),
updateEmail: vi.fn(),
+ disableMFA: vi.fn(async () => activeUser),
+}));
+
+vi.mock("@/api", () => ({
+ userServiceClientConnect: {
+ disableMFA: mocks.disableMFA,
+ },
}));
vi.mock("@/utils", () => ({
@@ -61,8 +68,16 @@ vi.mock("@/components/ui/dropdown-menu", () => ({
DropdownMenuContent: ({ children }: { children: React.ReactNode }) => (
<div data-testid="menu">{children}</div>
),
- DropdownMenuItem: ({ children }: { children: React.ReactNode }) => (
- <div data-testid="menu-item">{children}</div>
+ DropdownMenuItem: ({
+ children,
+ onClick,
+ }: {
+ children: React.ReactNode;
+ onClick?: () => void;
+ }) => (
+ <button type="button" data-testid="menu-item" onClick={onClick}>
+ {children}
+ </button>
),
DropdownMenuSeparator: () => <hr />,
}));
@@ -144,6 +159,42 @@ describe("UserRowMenu", () => {
unmount();
});
+ // The menu is an administrator's recovery path for a locked-out member, and
+ // the only method that clears someone else's factor is DisableMFA. Sending
+ // this through UpdateUser instead is refused server-side, and nothing else
+ // in this file would notice.
+ test("resets MFA through DisableMFA", async () => {
+ const { container, unmount } = await renderMenu(activeUser);
+
+ const openDialog = [
+ ...container.querySelectorAll('[data-testid="menu-item"]'),
+ ].find(
+ (item) => item.textContent === "settings.members.admin.reset-mfa"
+ ) as HTMLElement;
+ await act(async () => {
+ openDialog.click();
+ await Promise.resolve();
+ });
+ // The dialog repeats the action's label on its confirming button; the
+ // menu item that opened it is gone by then.
+ const confirm = [...container.querySelectorAll("button")].find(
+ (button) =>
+ button.textContent === "settings.members.admin.reset-mfa" &&
+ button.getAttribute("data-testid") !== "menu-item"
+ ) as HTMLElement;
+ await act(async () => {
+ confirm.click();
+ await Promise.resolve();
+ });
+
+ expect(mocks.disableMFA).toHaveBeenCalledWith(
+ expect.objectContaining({ name: activeUser.name })
+ );
+ expect(mocks.updateUser).not.toHaveBeenCalled();
+
+ unmount();
+ });
+
test("offers no MFA reset for someone who never enrolled", async () => {
const { container, unmount } = await renderMenu({
...activeUser,
diff --git a/frontend/src/routes/workspace/users/UserRowMenu.tsx b/frontend/src/routes/workspace/users/UserRowMenu.tsx
index 980164236a..efab5a7592 100644
--- a/frontend/src/routes/workspace/users/UserRowMenu.tsx
+++ b/frontend/src/routes/workspace/users/UserRowMenu.tsx
@@ -4,6 +4,7 @@ import type { ConnectError } from "@connectrpc/connect";
import { Ellipsis } from "lucide-react";
import { useState } from "react";
import { useTranslation } from "react-i18next";
+import { userServiceClientConnect } from "@/api";
import { Alert } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import { CopyButton } from "@/components/ui/copy-button";
@@ -26,7 +27,10 @@ import { useAppStore } from "@/stores/app";
import { AccountType, getAccountTypeByEmail } from "@/types";
import { State } from "@/types/proto-es/v1/common_pb";
import type { User } from "@/types/proto-es/v1/user_service_pb";
-import { UpdateUserRequestSchema } from "@/types/proto-es/v1/user_service_pb";
+import {
+ DisableMFARequestSchema,
+ UpdateUserRequestSchema,
+} from "@/types/proto-es/v1/user_service_pb";
import { hasWorkspacePermissionV2 } from "@/utils";
import { EmailInput } from "../profile/EmailInput";
import { getPasswordErrors } from "../profile/UserPasswordSection";
@@ -175,11 +179,8 @@ export function UserRowMenu({
const handleResetMfa = async () => {
setProcessing(true);
try {
- const updated = await updateUser(
- create(UpdateUserRequestSchema, {
- user: { name: user.name, mfaEnabled: false },
- updateMask: create(FieldMaskSchema, { paths: ["mfa_enabled"] }),
- })
+ const updated = await userServiceClientConnect.disableMFA(
+ create(DisableMFARequestSchema, { name: user.name })
);
onUserUpdated(updated);
pushNotification({
diff --git a/frontend/src/stores/app/auth.ts b/frontend/src/stores/app/auth.ts
index 131a975b6c..f022dc05cd 100644
--- a/frontend/src/stores/app/auth.ts
+++ b/frontend/src/stores/app/auth.ts
@@ -24,7 +24,6 @@ import type { User } from "@/types/proto-es/v1/user_service_pb";
import { UNKNOWN_USER_NAME } from "@/types/v1/user";
import { storageKeyResetPassword } from "@/utils/storage-keys";
import type { AppSliceCreator, AuthSlice } from "./types";
-import { keepMfaEnrollment } from "./utils";
// `users/{email}` → `{email}`.
function emailOf(currentUserName: string | undefined): string {
@@ -146,11 +145,10 @@ export const createAuthSlice: AppSliceCreator<AuthSlice> = (set, get) => ({
// the server — login/signup need the fresh authenticated user).
fetchCurrentUser: async (silent = false) => {
try {
- const fresh = await userServiceClientConnect.getCurrentUser(
+ const user = await userServiceClientConnect.getCurrentUser(
{},
{ contextValues: createContextValues().set(silentContextKey, silent) }
);
- const user = keepMfaEnrollment(fresh, get().currentUser);
set({ currentUser: user, currentUserName: user.name });
return user;
} catch {
@@ -158,6 +156,9 @@ export const createAuthSlice: AppSliceCreator<AuthSlice> = (set, get) => ({
}
},
+ setCurrentUser: (user) =>
+ set({ currentUser: user, currentUserName: user.name }),
+
// sometimes we have to redirect users even if we don't want to redirect them.
// for example, the user is forced to reset their password,
// or the user is using the LDAP to signin.
diff --git a/frontend/src/stores/app/index.test.ts b/frontend/src/stores/app/index.test.ts
index ea9be77cb2..b8e19597bc 100644
--- a/frontend/src/stores/app/index.test.ts
+++ b/frontend/src/stores/app/index.test.ts
@@ -1,5 +1,4 @@
import { create as createProto } from "@bufbuild/protobuf";
-import { TimestampSchema } from "@bufbuild/protobuf/wkt";
import { beforeEach, describe, expect, test, vi } from "vitest";
import { silentContextKey } from "@/api/context-key";
import { isValidDatabaseGroupName, UNKNOWN_PROJECT_NAME } from "@/types";
@@ -507,6 +506,20 @@ describe("useAppStore", () => {
expect(store.getState().isLoggedIn()).toBe(true);
});
+ // Mutations that answer with the updated user adopt it directly: the router
+ // guard reads this state, and a refetch that failed would leave it stale
+ // while fetchCurrentUser swallowed the error.
+ test("adopts a user handed to setCurrentUser", () => {
+ const store = createAppStore();
+ const enabled = createProto(UserSchema, { ...user, mfaEnabled: true });
+
+ store.getState().setCurrentUser(enabled);
+
+ expect(store.getState().currentUser?.mfaEnabled).toBe(true);
+ expect(store.getState().currentUserName).toBe(enabled.name);
+ expect(store.getState().isLoggedIn()).toBe(true);
+ });
+
test("fetches the current user silently when requested", async () => {
mocks.getCurrentUser.mockResolvedValue(user);
const store = createAppStore();
@@ -518,139 +531,6 @@ describe("useAppStore", () => {
).toBe(true);
});
- // The MFA enrollment secrets ride out only on the UpdateUser response that
- // mints them; the read the session revalidation makes no longer carries them.
- // That revalidation fires every five minutes, which is the whole enrollment
- // window, so the two tests below are the difference between a QR code the
- // user can finish scanning and one that disappears under them.
- test("session revalidation keeps the MFA enrollment secrets it cannot refetch", async () => {
- const enrolling = createProto(UserSchema, {
- ...user,
- tempOtpSecret: "SEEDFROMTHEMINT",
- tempRecoveryCodes: ["code-1", "code-2"],
- tempOtpSecretCreatedTime: createProto(TimestampSchema, { seconds: 1n }),
- });
- mocks.getCurrentUser.mockResolvedValue(
- createProto(UserSchema, {
- ...user,
- tempOtpSecretCreatedTime: createProto(TimestampSchema, { seconds: 1n }),
- })
- );
- const store = createAppStore();
- store.setState({ currentUser: enrolling, currentUserName: enrolling.name });
-
- await store.getState().fetchCurrentUser();
-
- expect(store.getState().currentUser?.tempOtpSecret).toBe("SEEDFROMTHEMINT");
- expect(store.getState().currentUser?.tempRecoveryCodes).toEqual([
- "code-1",
- "code-2",
- ]);
- });
-
- test("session revalidation drops them once the enrollment window closes", async () => {
- const enrolling = createProto(UserSchema, {
- ...user,
- tempOtpSecret: "SEEDFROMTHEMINT",
- tempRecoveryCodes: ["code-1"],
- tempOtpSecretCreatedTime: createProto(TimestampSchema, { seconds: 1n }),
- });
- // The server clears the created time when the enrollment commits, which is
- // what says the secrets are gone rather than merely redacted.
- mocks.getCurrentUser.mockResolvedValue(
- createProto(UserSchema, { ...user, mfaEnabled: true })
- );
- const store = createAppStore();
- store.setState({ currentUser: enrolling, currentUserName: enrolling.name });
-
- await store.getState().fetchCurrentUser();
-
- expect(store.getState().currentUser?.tempOtpSecret).toBe("");
- expect(store.getState().currentUser?.tempRecoveryCodes).toEqual([]);
- });
-
- test("session revalidation drops them when another client minted a new seed", async () => {
- const enrolling = createProto(UserSchema, {
- ...user,
- tempOtpSecret: "SEEDFROMTHEMINT",
- tempRecoveryCodes: ["code-1"],
- tempOtpSecretCreatedTime: createProto(TimestampSchema, { seconds: 1n }),
- });
- // A second tab regenerated: the read reports an open window, but a later
- // one, so the seed we hold is the one the server threw away.
- mocks.getCurrentUser.mockResolvedValue(
- createProto(UserSchema, {
- ...user,
- tempOtpSecretCreatedTime: createProto(TimestampSchema, { seconds: 2n }),
- })
- );
- const store = createAppStore();
- store.setState({ currentUser: enrolling, currentUserName: enrolling.name });
-
- await store.getState().fetchCurrentUser();
-
- expect(store.getState().currentUser?.tempOtpSecret).toBe("");
- expect(store.getState().currentUser?.tempRecoveryCodes).toEqual([]);
- });
-
- test("a non-minting self-update keeps the enrollment the console is showing", async () => {
- // The account page saves a title from the same screen that shows the
- // recovery codes, and that response no longer carries them.
- const window = createProto(TimestampSchema, { seconds: 1n });
- const enrolling = createProto(UserSchema, {
- ...user,
- tempOtpSecret: "SEEDFROMTHEMINT",
- tempRecoveryCodes: ["code-1"],
- tempOtpSecretCreatedTime: window,
- });
- mocks.getUser.mockResolvedValue(enrolling);
- mocks.updateUser.mockResolvedValue(
- createProto(UserSchema, {
- ...user,
- title: "Renamed",
- tempOtpSecretCreatedTime: window,
- })
- );
- const store = createAppStore();
- store.setState({ currentUser: enrolling, currentUserName: enrolling.name });
-
- await store.getState().updateUser({
- user: { name: user.name, title: "Renamed" },
- updateMask: { paths: ["title"] },
- } as never);
-
- expect(store.getState().currentUser?.title).toBe("Renamed");
- expect(store.getState().currentUser?.tempOtpSecret).toBe("SEEDFROMTHEMINT");
- expect(store.getState().currentUser?.tempRecoveryCodes).toEqual(["code-1"]);
- });
-
- test("and drops them for a reseed inside the same second", async () => {
- const enrolling = createProto(UserSchema, {
- ...user,
- tempOtpSecret: "SEEDFROMTHEMINT",
- tempRecoveryCodes: ["code-1"],
- tempOtpSecretCreatedTime: createProto(TimestampSchema, {
- seconds: 1n,
- nanos: 100,
- }),
- });
- mocks.getCurrentUser.mockResolvedValue(
- createProto(UserSchema, {
- ...user,
- tempOtpSecretCreatedTime: createProto(TimestampSchema, {
- seconds: 1n,
- nanos: 200,
- }),
- })
- );
- const store = createAppStore();
- store.setState({ currentUser: enrolling, currentUserName: enrolling.name });
-
- await store.getState().fetchCurrentUser();
-
- expect(store.getState().currentUser?.tempOtpSecret).toBe("");
- });
-
test("auto logout preserves the full current path for signin redirect", async () => {
const fakeLocation = {
pathname: "/sql-editor/projects/prod/instances/pg/databases/app",
diff --git a/frontend/src/stores/app/types.ts b/frontend/src/stores/app/types.ts
index 01db7b2b8b..b35eb3d4af 100644
--- a/frontend/src/stores/app/types.ts
+++ b/frontend/src/stores/app/types.ts
@@ -200,6 +200,10 @@ export type AuthSlice = {
setRequireResetPassword: (value: boolean) => void;
setUnauthenticatedOccurred: (value: boolean) => void;
fetchCurrentUser: (silent?: boolean) => Promise<User | undefined>;
+ // Adopt a user a mutation just returned. Preferred over refetching when the
+ // caller already holds the authoritative row: a refetch can fail, and
+ // fetchCurrentUser swallows that, leaving guards reading stale state.
+ setCurrentUser: (user: User) => void;
login: (params: {
request: LoginRequest;
redirect?: boolean;
diff --git a/frontend/src/stores/app/user.ts b/frontend/src/stores/app/user.ts
index c2e8ade5d4..63aa792088 100644
--- a/frontend/src/stores/app/user.ts
+++ b/frontend/src/stores/app/user.ts
@@ -25,7 +25,6 @@ import {
} from "@/types/proto-es/v1/user_service_pb";
import { ensureUserFullName } from "@/utils/v1/user";
import type { AppSliceCreator, UserFilter, UserSlice } from "./types";
-import { keepMfaEnrollment } from "./utils";
const UNKNOWN_PROJECT_NAME_LEGACY = "projects/-";
@@ -205,9 +204,6 @@ export const createUserSlice: AppSliceCreator<UserSlice> = (set, get) => {
createProto(UpdateUserRequestSchema, {
user: request.user,
updateMask: request.updateMask,
- otpCode: request.otpCode,
- regenerateTempMfaSecret: request.regenerateTempMfaSecret,
- regenerateRecoveryCodes: request.regenerateRecoveryCodes,
allowMissing: request.allowMissing,
})
);
@@ -215,7 +211,7 @@ export const createUserSlice: AppSliceCreator<UserSlice> = (set, get) => {
usersByName: { ...state.usersByName, [response.name]: response },
currentUser:
state.currentUser?.name === response.name
- ? keepMfaEnrollment(response, state.currentUser)
+ ? response
: state.currentUser,
}));
return response;
diff --git a/frontend/src/stores/app/utils.ts b/frontend/src/stores/app/utils.ts
index 53c999593e..9616ff3d64 100644
--- a/frontend/src/stores/app/utils.ts
+++ b/frontend/src/stores/app/utils.ts
@@ -304,38 +304,3 @@ export function getProjectResourceId(project: Project) {
// 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
-// as an open one.
-export function keepMfaEnrollment(
- fresh: User,
- previous: User | undefined
-): User {
- if (!previous || previous.name !== fresh.name) return fresh;
- if (fresh.tempOtpSecret || fresh.tempRecoveryCodes.length > 0) return fresh;
- if (!previous.tempOtpSecret && previous.tempRecoveryCodes.length === 0) {
- return fresh;
- }
- // Carry them only while the read describes the same enrollment we hold. The
- // server keeps one enrollment per user and replaces the seed, the codes and
- // the created time together, so a created time that moved means another tab
- // or another device minted a new seed. Keeping ours then would render a QR
- // code the server has already discarded, and every code typed off it would
- // be rejected.
- const held = previous.tempOtpSecretCreatedTime;
- const read = fresh.tempOtpSecretCreatedTime;
- // Nanos as well as seconds: two mints inside the same wall-clock second are
- // rare and not impossible, and comparing only seconds would call the second
- // one the same enrollment and carry the seed it replaced.
- if (
- !held ||
- !read ||
- held.seconds !== read.seconds ||
- held.nanos !== read.nanos
- ) {
- return fresh;
- }
- return {
- ...fresh,
- tempOtpSecret: previous.tempOtpSecret,
- tempRecoveryCodes: previous.tempRecoveryCodes,
- };
-}
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 9bb2bcf0b9..1c8369ffbb 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
@@ -197,28 +197,6 @@ export declare type UpdateUserRequest = Message<"bytebase.v1.UpdateUserRequest">
*/
updateMask?: FieldMask | undefined;
- /**
- * The otp_code is used to verify the user's identity by MFA.
- *
- * @generated from field: optional string otp_code = 3;
- */
- otpCode?: string | undefined;
-
- /**
- * The regenerate_temp_mfa_secret flag means to regenerate temporary MFA secret for user.
- * This is used for MFA setup. The temporary MFA secret and recovery codes will be returned in the response.
- *
- * @generated from field: bool regenerate_temp_mfa_secret = 4;
- */
- regenerateTempMfaSecret: boolean;
-
- /**
- * The regenerate_recovery_codes flag means to regenerate recovery codes for user.
- *
- * @generated from field: bool regenerate_recovery_codes = 5;
- */
- regenerateRecoveryCodes: boolean;
-
/**
* If set to true, and the user is not found, a new user will be created.
* In this situation, `update_mask` is ignored.
@@ -299,6 +277,210 @@ export declare type UpdateEmailRequest = Message<"bytebase.v1.UpdateEmailRequest
*/
export declare const UpdateEmailRequestSchema: GenMessage<UpdateEmailRequest>;
+/**
+ * @generated from message bytebase.v1.ChangePasswordRequest
+ */
+export declare type ChangePasswordRequest = Message<"bytebase.v1.ChangePasswordRequest"> & {
+ /**
+ * Format: users/{email}. Must be the caller's own name.
+ *
+ * @generated from field: string name = 1;
+ */
+ name: string;
+
+ /**
+ * @generated from field: string new_password = 2;
+ */
+ newPassword: string;
+};
+
+/**
+ * Describes the message bytebase.v1.ChangePasswordRequest.
+ * Use `create(ChangePasswordRequestSchema)` to create a new message.
+ */
+export declare const ChangePasswordRequestSchema: GenMessage<ChangePasswordRequest>;
+
+/**
+ * @generated from message bytebase.v1.StartMFAEnrollmentRequest
+ */
+export declare type StartMFAEnrollmentRequest = Message<"bytebase.v1.StartMFAEnrollmentRequest"> & {
+ /**
+ * Format: users/{email}. Must be the caller's own name.
+ *
+ * @generated from field: string name = 1;
+ */
+ name: string;
+};
+
+/**
+ * Describes the message bytebase.v1.StartMFAEnrollmentRequest.
+ * Use `create(StartMFAEnrollmentRequestSchema)` to create a new message.
+ */
+export declare const StartMFAEnrollmentRequestSchema: GenMessage<StartMFAEnrollmentRequest>;
+
+/**
+ * @generated from message bytebase.v1.StartMFAEnrollmentResponse
+ */
+export declare type StartMFAEnrollmentResponse = Message<"bytebase.v1.StartMFAEnrollmentResponse"> & {
+ /**
+ * The pending TOTP secret. The only response that carries it — it is never
+ * readable from the User resource.
+ *
+ * @generated from field: string otp_secret = 1;
+ */
+ otpSecret: string;
+
+ /**
+ * The pending recovery codes, shown once for the caller to save.
+ *
+ * @generated from field: repeated string recovery_codes = 2;
+ */
+ recoveryCodes: string[];
+
+ /**
+ * When this enrollment stops being confirmable.
+ *
+ * @generated from field: google.protobuf.Timestamp expire_time = 3;
+ */
+ expireTime?: Timestamp | undefined;
+
+ /**
+ * Identifies this mint. Echo it back to EnableMFA and
+ * ConfirmRecoveryCodes; a mint from another tab or device replaces the
+ * pending state, and those methods refuse a version that is no longer the
+ * pending one rather than promoting something this caller never saw.
+ *
+ * @generated from field: google.protobuf.Timestamp pending_version = 4;
+ */
+ pendingVersion?: Timestamp | undefined;
+};
+
+/**
+ * Describes the message bytebase.v1.StartMFAEnrollmentResponse.
+ * Use `create(StartMFAEnrollmentResponseSchema)` to create a new message.
+ */
+export declare const StartMFAEnrollmentResponseSchema: GenMessage<StartMFAEnrollmentResponse>;
+
+/**
+ * @generated from message bytebase.v1.EnableMFARequest
+ */
+export declare type EnableMFARequest = Message<"bytebase.v1.EnableMFARequest"> & {
+ /**
+ * Format: users/{email}. Must be the caller's own name.
+ *
+ * @generated from field: string name = 1;
+ */
+ name: string;
+
+ /**
+ * A code from the authenticator the pending secret was just added to.
+ *
+ * @generated from field: string otp_code = 2;
+ */
+ otpCode: string;
+
+ /**
+ * The pending_version this enrollment was minted with.
+ *
+ * @generated from field: google.protobuf.Timestamp pending_version = 3;
+ */
+ pendingVersion?: Timestamp | undefined;
+};
+
+/**
+ * Describes the message bytebase.v1.EnableMFARequest.
+ * Use `create(EnableMFARequestSchema)` to create a new message.
+ */
+export declare const EnableMFARequestSchema: GenMessage<EnableMFARequest>;
+
+/**
+ * @generated from message bytebase.v1.DisableMFARequest
+ */
+export declare type DisableMFARequest = Message<"bytebase.v1.DisableMFARequest"> & {
+ /**
+ * Format: users/{email}. The caller's own, or another user's with
+ * bb.users.update.
+ *
+ * @generated from field: string name = 1;
+ */
+ name: string;
+};
+
+/**
+ * Describes the message bytebase.v1.DisableMFARequest.
+ * Use `create(DisableMFARequestSchema)` to create a new message.
+ */
+export declare const DisableMFARequestSchema: GenMessage<DisableMFARequest>;
+
+/**
+ * @generated from message bytebase.v1.RegenerateRecoveryCodesRequest
+ */
+export declare type RegenerateRecoveryCodesRequest = Message<"bytebase.v1.RegenerateRecoveryCodesRequest"> & {
+ /**
+ * Format: users/{email}. Must be the caller's own name.
+ *
+ * @generated from field: string name = 1;
+ */
+ name: string;
+};
+
+/**
+ * Describes the message bytebase.v1.RegenerateRecoveryCodesRequest.
+ * Use `create(RegenerateRecoveryCodesRequestSchema)` to create a new message.
+ */
+export declare const RegenerateRecoveryCodesRequestSchema: GenMessage<RegenerateRecoveryCodesRequest>;
+
+/**
+ * @generated from message bytebase.v1.RegenerateRecoveryCodesResponse
+ */
+export declare type RegenerateRecoveryCodesResponse = Message<"bytebase.v1.RegenerateRecoveryCodesResponse"> & {
+ /**
+ * The pending recovery codes, shown once for the caller to save.
+ *
+ * @generated from field: repeated string recovery_codes = 1;
+ */
+ recoveryCodes: string[];
+
+ /**
+ * Identifies this mint; see StartMFAEnrollmentResponse.pending_version.
+ *
+ * @generated from field: google.protobuf.Timestamp pending_version = 2;
+ */
+ pendingVersion?: Timestamp | undefined;
+};
+
+/**
+ * Describes the message bytebase.v1.RegenerateRecoveryCodesResponse.
+ * Use `create(RegenerateRecoveryCodesResponseSchema)` to create a new message.
+ */
+export declare const RegenerateRecoveryCodesResponseSchema: GenMessage<RegenerateRecoveryCodesResponse>;
+
+/**
+ * @generated from message bytebase.v1.ConfirmRecoveryCodesRequest
+ */
+export declare type ConfirmRecoveryCodesRequest = Message<"bytebase.v1.ConfirmRecoveryCodesRequest"> & {
+ /**
+ * Format: users/{email}. Must be the caller's own name.
+ *
+ * @generated from field: string name = 1;
+ */
+ name: string;
+
+ /**
+ * The pending_version of the codes being confirmed. Confirming promotes
+ * exactly the set this version identifies, or nothing.
+ *
+ * @generated from field: google.protobuf.Timestamp pending_version = 2;
+ */
+ pendingVersion?: Timestamp | undefined;
+};
+
+/**
+ * Describes the message bytebase.v1.ConfirmRecoveryCodesRequest.
+ * Use `create(ConfirmRecoveryCodesRequestSchema)` to create a new message.
+ */
+export declare const ConfirmRecoveryCodesRequestSchema: GenMessage<ConfirmRecoveryCodesRequest>;
+
/**
* @generated from message bytebase.v1.User
*/
@@ -340,33 +522,13 @@ export declare type User = Message<"bytebase.v1.User"> & {
password: string;
/**
- * The mfa_enabled flag means if the user has enabled MFA.
+ * Whether the user has a live MFA factor. Set by ConfirmRecoveryCodes and
+ * DisableMFA, never by an update.
*
* @generated from field: bool mfa_enabled = 8;
*/
mfaEnabled: boolean;
- /**
- * Temporary OTP secret used during MFA setup and regeneration.
- *
- * @generated from field: string temp_otp_secret = 9;
- */
- tempOtpSecret: string;
-
- /**
- * Temporary recovery codes used during MFA setup and regeneration.
- *
- * @generated from field: repeated string temp_recovery_codes = 10;
- */
- tempRecoveryCodes: string[];
-
- /**
- * Timestamp when temp_otp_secret was created. Used by frontend to show countdown timer.
- *
- * @generated from field: google.protobuf.Timestamp temp_otp_secret_created_time = 11;
- */
- tempOtpSecretCreatedTime?: Timestamp | undefined;
-
/**
* Should be a valid E.164 compliant phone number.
* Could be empty.
@@ -547,5 +709,89 @@ export declare const UserService: GenService<{
input: typeof UpdateEmailRequestSchema;
output: typeof UserSchema;
},
+ /**
+ * 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
+ * end in a new password hash.
+ * Permissions required: None beyond being signed in as `name`.
+ *
+ * @generated from rpc bytebase.v1.UserService.ChangePassword
+ */
+ changePassword: {
+ methodKind: "unary";
+ input: typeof ChangePasswordRequestSchema;
+ output: typeof UserSchema;
+ },
+ /**
+ * Mints a pending TOTP secret and recovery codes for the caller'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`.
+ *
+ * @generated from rpc bytebase.v1.UserService.StartMFAEnrollment
+ */
+ startMFAEnrollment: {
+ methodKind: "unary";
+ input: typeof StartMFAEnrollmentRequestSchema;
+ output: typeof StartMFAEnrollmentResponseSchema;
+ },
+ /**
+ * 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.
+ *
+ * @generated from rpc bytebase.v1.UserService.EnableMFA
+ */
+ enableMFA: {
+ methodKind: "unary";
+ input: typeof EnableMFARequestSchema;
+ output: typeof UserSchema;
+ },
+ /**
+ * Turns MFA off, clearing the entire MFA config — live and pending state
+ * alike. Callers may disable their own; an administrator may disable
+ * another user's with bb.users.update, which is how a locked-out user is
+ * recovered.
+ * Permissions required: bb.users.update, unless `name` is the caller's own.
+ *
+ * @generated from rpc bytebase.v1.UserService.DisableMFA
+ */
+ disableMFA: {
+ methodKind: "unary";
+ input: typeof DisableMFARequestSchema;
+ output: typeof UserSchema;
+ },
+ /**
+ * Mints a pending recovery-code set beside the live one and returns it.
+ * The old codes keep working until ConfirmRecoveryCodes promotes these, so
+ * a caller who closes the page mid-way is not left without any.
+ * Permissions required: None beyond being signed in as `name`.
+ *
+ * @generated from rpc bytebase.v1.UserService.RegenerateRecoveryCodes
+ */
+ regenerateRecoveryCodes: {
+ methodKind: "unary";
+ input: typeof RegenerateRecoveryCodesRequestSchema;
+ output: typeof RegenerateRecoveryCodesResponseSchema;
+ },
+ /**
+ * Promotes the pending recovery codes. During first-time enrollment this is
+ * also where the pending TOTP secret goes live, so the factor and the codes
+ * that recover it start existing in the same write.
+ * Permissions required: None beyond being signed in as `name`.
+ *
+ * @generated from rpc bytebase.v1.UserService.ConfirmRecoveryCodes
+ */
+ confirmRecoveryCodes: {
+ methodKind: "unary";
+ input: typeof ConfirmRecoveryCodesRequestSchema;
+ output: typeof UserSchema;
+ },
}>;
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 53ea80afa6..9f1108921b 100644
--- a/frontend/src/types/proto-es/v1/user_service_pb.js
+++ b/frontend/src/types/proto-es/v1/user_service_pb.js
@@ -16,7 +16,7 @@ import { file_v1_common } from "./common_pb";
* Describes the file v1/user_service.proto.
*/
export const file_v1_user_service = /*@__PURE__*/
- fileDesc("ChV2MS91c2VyX3NlcnZpY2UucHJvdG8SC2J5dGViYXNlLnYxIjkKDkdldFVzZXJSZXF1ZXN0EicKBG5hbWUYASABKAlCGeBBAvpBEwoRYnl0ZWJhc2UuY29tL1VzZXIiQAoUQmF0Y2hHZXRVc2Vyc1JlcXVlc3QSKAoFbmFtZXMYASADKAlCGeBBAvpBEwoRYnl0ZWJhc2UuY29tL1VzZXIiOQoVQmF0Y2hHZXRVc2Vyc1Jlc3BvbnNlEiAKBXVzZXJzGAEgAygLMhEuYnl0ZWJhc2UudjEuVXNlciJfChBMaXN0VXNlcnNSZXF1ZXN0EhEKCXBhZ2Vfc2l6ZRgBIAEoBRISCgpwYWdlX3Rva2VuGAIgASgJEhQKDHNob3dfZGVsZXRlZBgDIAEoCBIOCgZmaWx0ZXIYBCABKAkiTgoRTGlzdFVzZXJzUmVzcG9uc2USIAoFdXNlcnMYASADKAsyES5ieXRlYmFzZS52MS5Vc2VyEhcKD25leHRfcGFnZV90b2tlbhgCIAEoCSI5ChFDcmVhdGVVc2VyUmVxdWVzdBIkCgR1c2VyGAEgASgLMhEuYnl0ZWJhc2UudjEuVXNlckID4EECIvIBChFVcGRhdGVVc2VyUmVxdWVzdBIkCgR1c2VyGAEgASgLMhEuYnl0ZWJhc2UudjEuVXNlckID4EECEi8KC3VwZGF0ZV9tYXNrGAIgASgLMhouZ29vZ2xlLnByb3RvYnVmLkZpZWxkTWFzaxIbCghvdHBfY29kZRgDIAEoCUIE0OowAUgAiAEBEiIKGnJlZ2VuZXJhdGVfdGVtcF9tZmFfc2VjcmV0GAQgASgIEiEKGXJlZ2VuZXJhdGVfcmVjb3ZlcnlfY29kZXMYBSABKAgSFQoNYWxsb3dfbWlzc2luZxgGIAEoCEILCglfb3RwX2NvZGUiPAoRRGVsZXRlVXNlclJlcXVlc3QSJwoEbmFtZRgBIAEoCUIZ4EEC+kETChFieXRlYmFzZS5jb20vVXNlciI+ChNVbmRlbGV0ZVVzZXJSZXF1ZXN0EicKBG5hbWUYASABKAlCGeBBAvpBEwoRYnl0ZWJhc2UuY29tL1VzZXIiWQoSVXBkYXRlRW1haWxSZXF1ZXN0EicKBG5hbWUYASABKAlCGeBBAvpBEwoRYnl0ZWJhc2UuY29tL1VzZXISGgoFZW1haWwYAiABKAlCC+BBArpIBXIDGP4BIuoECgRVc2VyEhEKBG5hbWUYASABKAlCA+BBAxIhCgVzdGF0ZRgCIAEoDjISLmJ5dGViYXNlLnYxLlN0YXRlEhcKBWVtYWlsGAMgASgJQgi6SAVyAxj+ARIXCgV0aXRsZRgEIAEoCUIIukgFcgMYyAESIAoIcGFzc3dvcmQYBiABKAlCDuBBBLpIBHICKEjQ6jABEhMKC21mYV9lbmFibGVkGAggASgIEh0KD3RlbXBfb3RwX3NlY3JldBgJIAEoCUIE0OowARIhChN0ZW1wX3JlY292ZXJ5X2NvZGVzGAogAygJQgTQ6jABEkAKHHRlbXBfb3RwX3NlY3JldF9jcmVhdGVkX3RpbWUYCyABKAsyGi5nb29nbGUucHJvdG9idWYuVGltZXN0YW1wEhMKBXBob25lGAwgASgJQgTQ6jACEjAKB3Byb2ZpbGUYDSABKAsyGS5ieXRlYmFzZS52MS5Vc2VyLlByb2ZpbGVCBNDqMAISFwoGZ3JvdXBzGA4gAygJQgfgQQPQ6jACEhYKCXdvcmtzcGFjZRgQIAEoCUID4EEDGo0BCgdQcm9maWxlEjMKD2xhc3RfbG9naW5fdGltZRgBIAEoCzIaLmdvb2dsZS5wcm90b2J1Zi5UaW1lc3RhbXASPQoZbGFzdF9jaGFuZ2VfcGFzc3dvcmRfdGltZRgCIAEoCzIaLmdvb2dsZS5wcm90b2J1Zi5UaW1lc3RhbXASDgoGc291cmNlGAMgASgJOiXqQSIKEWJ5dGViYXNlLmNvbS9Vc2VyEg11c2Vycy97ZW1haWx9SgQIBRAGSgQIBxAISgQIDxAQMqgJCgtVc2VyU2VydmljZRJ4CgdHZXRVc2VyEhsuYnl0ZWJhc2UudjEuR2V0VXNlclJlcXVlc3QaES5ieXRlYmFzZS52MS5Vc2VyIj3aQQRuYW1liuowDGJiLnVzZXJzLmdldJDqMAGg6jAEqOowCYLT5JMCFBISL3YxL3tuYW1lPXVzZXJzLyp9Eo4BCg1CYXRjaEdldFVzZXJzEiEuYnl0ZWJhc2UudjEuQmF0Y2hHZXRVc2Vyc1JlcXVlc3QaIi5ieXRlYmFzZS52MS5CYXRjaEdldFVzZXJzUmVzcG9uc2UiNorqMAxiYi51c2Vycy5nZXSQ6jABoOowBKjqMAmC0+STAhQSEi92MS91c2VyczpiYXRjaEdldBJdCg5HZXRDdXJyZW50VXNlchIWLmdvb2dsZS5wcm90b2J1Zi5FbXB0eRoRLmJ5dGViYXNlLnYxLlVzZXIiIIDqMAGQ6jACoOowAYLT5JMCDhIML3YxL3VzZXJzL21lEoMBCglMaXN0VXNlcnMSHS5ieXRlYmFzZS52MS5MaXN0VXNlcnNSZXF1ZXN0Gh4uYnl0ZWJhc2UudjEuTGlzdFVzZXJzUmVzcG9uc2UiN9pBBnBhcmVudIrqMA1iYi51c2Vycy5saXN0kOowAaDqMASo6jAJgtPkkwILEgkvdjEvdXNlcnMSggEKCkNyZWF0ZVVzZXISHi5ieXRlYmFzZS52MS5DcmVhdGVVc2VyUmVxdWVzdBoRLmJ5dGViYXNlLnYxLlVzZXIiQdpBBHVzZXKK6jAPYmIudXNlcnMuY3JlYXRlkOowAZjqMAGg6jADqOowBoLT5JMCEToEdXNlciIJL3YxL3VzZXJzEokBCgpVcGRhdGVVc2VyEh4uYnl0ZWJhc2UudjEuVXBkYXRlVXNlclJlcXVlc3QaES5ieXRlYmFzZS52MS5Vc2VyIkjaQRB1c2VyLHVwZGF0ZV9tYXNrkOowApjqMAGg6jADqOowA4LT5JMCHzoEdXNlcjIXL3YxL3t1c2VyLm5hbWU9dXNlcnMvKn0SdwoKRGVsZXRlVXNlchIeLmJ5dGViYXNlLnYxLkRlbGV0ZVVzZXJSZXF1ZXN0GhYuZ29vZ2xlLnByb3RvYnVmLkVtcHR5IjHaQQRuYW1lkOowApjqMAGg6jAEqOowCYLT5JMCFCoSL3YxL3tuYW1lPXVzZXJzLyp9EnsKDFVuZGVsZXRlVXNlchIgLmJ5dGViYXNlLnYxLlVuZGVsZXRlVXNlclJlcXVlc3QaES5ieXRlYmFzZS52MS5Vc2VyIjaQ6jACmOowAaDqMASo6jAJgtPkkwIgOgEqIhsvdjEve25hbWU9dXNlcnMvKn06dW5kZWxldGUSoQEKC1VwZGF0ZUVtYWlsEh8uYnl0ZWJhc2UudjEuVXBkYXRlRW1haWxSZXF1ZXN0GhEuYnl0ZWJhc2UudjEuVXNlciJe2kEKbmFtZSxlbWFpbIrqMBRiYi51c2Vycy51cGRhdGVFbWFpbJDqMAGY6jABoOowA6jqMAaC0+STAiM6ASoiHi92MS97bmFtZT11c2Vycy8qfTp1cGRhdGVFbWFpbEKmAQoPY29tLmJ5dGViYXNlLnYxQhBVc2VyU2VydmljZVByb3RvUAFaNGdpdGh1Yi5jb20vYnl0ZWJhc2UvYnl0ZWJhc2UvYmFja2VuZC9nZW5lcmF0ZWQtZ28vdjGiAgNCWFiqAgtCeXRlYmFzZS5WMcoCC0J5dGViYXNlXFYx4gIXQnl0ZWJhc2VcVjFcR1BCTWV0YWRhdGHqAgxCeXRlYmFzZTo6VjFiBnByb3RvMw", [file_buf_validate_validate, file_google_api_annotations, file_google_api_client, file_google_api_field_behavior, file_google_api_resource, file_google_protobuf_empty, file_google_protobuf_field_mask, file_google_protobuf_timestamp, file_v1_annotation, file_v1_common]);
+ 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]);
/**
* Describes the message bytebase.v1.GetUserRequest.
@@ -88,19 +88,75 @@ export const UndeleteUserRequestSchema = /*@__PURE__*/
export const UpdateEmailRequestSchema = /*@__PURE__*/
messageDesc(file_v1_user_service, 9);
+/**
+ * Describes the message bytebase.v1.ChangePasswordRequest.
+ * Use `create(ChangePasswordRequestSchema)` to create a new message.
+ */
+export const ChangePasswordRequestSchema = /*@__PURE__*/
+ messageDesc(file_v1_user_service, 10);
+
+/**
+ * Describes the message bytebase.v1.StartMFAEnrollmentRequest.
+ * Use `create(StartMFAEnrollmentRequestSchema)` to create a new message.
+ */
+export const StartMFAEnrollmentRequestSchema = /*@__PURE__*/
+ messageDesc(file_v1_user_service, 11);
+
+/**
+ * Describes the message bytebase.v1.StartMFAEnrollmentResponse.
+ * Use `create(StartMFAEnrollmentResponseSchema)` to create a new message.
+ */
+export const StartMFAEnrollmentResponseSchema = /*@__PURE__*/
+ messageDesc(file_v1_user_service, 12);
+
+/**
+ * Describes the message bytebase.v1.EnableMFARequest.
+ * Use `create(EnableMFARequestSchema)` to create a new message.
+ */
+export const EnableMFARequestSchema = /*@__PURE__*/
+ messageDesc(file_v1_user_service, 13);
+
+/**
+ * Describes the message bytebase.v1.DisableMFARequest.
+ * Use `create(DisableMFARequestSchema)` to create a new message.
+ */
+export const DisableMFARequestSchema = /*@__PURE__*/
+ messageDesc(file_v1_user_service, 14);
+
+/**
+ * Describes the message bytebase.v1.RegenerateRecoveryCodesRequest.
+ * Use `create(RegenerateRecoveryCodesRequestSchema)` to create a new message.
+ */
+export const RegenerateRecoveryCodesRequestSchema = /*@__PURE__*/
+ messageDesc(file_v1_user_service, 15);
+
+/**
+ * Describes the message bytebase.v1.RegenerateRecoveryCodesResponse.
+ * Use `create(RegenerateRecoveryCodesResponseSchema)` to create a new message.
+ */
+export const RegenerateRecoveryCodesResponseSchema = /*@__PURE__*/
+ messageDesc(file_v1_user_service, 16);
+
+/**
+ * Describes the message bytebase.v1.ConfirmRecoveryCodesRequest.
+ * Use `create(ConfirmRecoveryCodesRequestSchema)` to create a new message.
+ */
+export const ConfirmRecoveryCodesRequestSchema = /*@__PURE__*/
+ messageDesc(file_v1_user_service, 17);
+
/**
* Describes the message bytebase.v1.User.
* Use `create(UserSchema)` to create a new message.
*/
export const UserSchema = /*@__PURE__*/
- messageDesc(file_v1_user_service, 10);
+ messageDesc(file_v1_user_service, 18);
/**
* 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, 10, 0);
+ messageDesc(file_v1_user_service, 18, 0);
/**
* UserService manages user accounts and authentication.
diff --git a/proto/gen/grpc-doc/openapi.yaml b/proto/gen/grpc-doc/openapi.yaml
index 9e9179bf77..b9c418a098 100644
--- a/proto/gen/grpc-doc/openapi.yaml
+++ b/proto/gen/grpc-doc/openapi.yaml
@@ -17128,26 +17128,6 @@ paths:
`INVALID_ARGUMENT` error if any path is unmappable.
schema:
type: string
- - name: otpCode
- in: query
- description: The otp_code is used to verify the user's identity by MFA.
- schema:
- type: string
- title: otp_code
- - name: regenerateTempMfaSecret
- in: query
- description: |-
- The regenerate_temp_mfa_secret flag means to regenerate temporary MFA secret for user.
- This is used for MFA setup. The temporary MFA secret and recovery codes will be returned in the response.
- schema:
- type: boolean
- title: regenerate_temp_mfa_secret
- - name: regenerateRecoveryCodes
- in: query
- description: The regenerate_recovery_codes flag means to regenerate recovery codes for user.
- schema:
- type: boolean
- title: regenerate_recovery_codes
- name: allowMissing
in: query
description: |-
@@ -17179,6 +17159,216 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/bytebase.v1.User'
+ /v1/users/{user}:changePassword:
+ post:
+ tags:
+ - UserService
+ summary: ChangePassword
+ description: |-
+ 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
+ end in a new password hash.
+ Permissions required: None beyond being signed in as `name`.
+ operationId: UserService_ChangePassword
+ parameters:
+ - name: user
+ in: path
+ description: The user id.
+ required: true
+ schema:
+ type: string
+ requestBody:
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ newPassword:
+ type: string
+ title: new_password
+ description: |
+ string.max_bytes = 72
+ title: ChangePasswordRequest
+ required:
+ - newPassword
+ additionalProperties: false
+ required: true
+ responses:
+ "200":
+ description: Success
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/bytebase.v1.User'
+ /v1/users/{user}:confirmRecoveryCodes:
+ post:
+ tags:
+ - UserService
+ summary: ConfirmRecoveryCodes
+ description: |-
+ Promotes the pending recovery codes. During first-time enrollment this is
+ also where the pending TOTP secret goes live, so the factor and the codes
+ that recover it start existing in the same write.
+ Permissions required: None beyond being signed in as `name`.
+ operationId: UserService_ConfirmRecoveryCodes
+ parameters:
+ - name: user
+ in: path
+ description: The user id.
+ required: true
+ schema:
+ type: string
+ requestBody:
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ pendingVersion:
+ title: pending_version
+ description: |-
+ The pending_version of the codes being confirmed. Confirming promotes
+ exactly the set this version identifies, or nothing.
+ $ref: '#/components/schemas/google.protobuf.Timestamp'
+ title: ConfirmRecoveryCodesRequest
+ required:
+ - pendingVersion
+ additionalProperties: false
+ required: true
+ responses:
+ "200":
+ description: Success
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/bytebase.v1.User'
+ /v1/users/{user}:disableMFA:
+ post:
+ tags:
+ - UserService
+ summary: DisableMFA
+ description: |-
+ Turns MFA off, clearing the entire MFA config — live and pending state
+ alike. Callers may disable their own; an administrator may disable
+ another user's with bb.users.update, which is how a locked-out user is
+ recovered.
+ Permissions required: bb.users.update, unless `name` is the caller's own.
+ operationId: UserService_DisableMFA
+ 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/bytebase.v1.User'
+ /v1/users/{user}:enableMFA:
+ post:
+ tags:
+ - UserService
+ summary: EnableMFA
+ description: |-
+ 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.
+ operationId: UserService_EnableMFA
+ parameters:
+ - name: user
+ in: path
+ description: The user id.
+ required: true
+ schema:
+ type: string
+ requestBody:
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ otpCode:
+ type: string
+ title: otp_code
+ maxLength: 64
+ description: A code from the authenticator the pending secret was just added to.
+ pendingVersion:
+ title: pending_version
+ description: The pending_version this enrollment was minted with.
+ $ref: '#/components/schemas/google.protobuf.Timestamp'
+ title: EnableMFARequest
+ required:
+ - otpCode
+ - pendingVersion
+ additionalProperties: false
+ required: true
+ responses:
+ "200":
+ description: Success
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/bytebase.v1.User'
+ /v1/users/{user}:regenerateRecoveryCodes:
+ post:
+ tags:
+ - UserService
+ summary: RegenerateRecoveryCodes
+ description: |-
+ Mints a pending recovery-code set beside the live one and returns it.
+ The old codes keep working until ConfirmRecoveryCodes promotes these, so
+ a caller who closes the page mid-way is not left without any.
+ Permissions required: None beyond being signed in as `name`.
+ operationId: UserService_RegenerateRecoveryCodes
+ 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/bytebase.v1.RegenerateRecoveryCodesResponse'
+ /v1/users/{user}:startMFAEnrollment:
+ post:
+ tags:
+ - UserService
+ summary: StartMFAEnrollment
+ description: |-
+ Mints a pending TOTP secret and recovery codes for the caller'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`.
+ operationId: UserService_StartMFAEnrollment
+ 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/bytebase.v1.StartMFAEnrollmentResponse'
/v1/users/{user}:undelete:
post:
tags:
@@ -20353,6 +20543,24 @@ components:
description: Optional free-form comment. Max 500 chars (Stripe limit).
title: CancelPurchaseRequest
additionalProperties: false
+ bytebase.v1.ChangePasswordRequest:
+ type: object
+ properties:
+ name:
+ type: string
+ title: name
+ maxLength: 260
+ description: 'Format: users/{email}. Must be the caller''s own name.'
+ newPassword:
+ type: string
+ title: new_password
+ description: |
+ string.max_bytes = 72
+ title: ChangePasswordRequest
+ required:
+ - name
+ - newPassword
+ additionalProperties: false
bytebase.v1.Changelog:
type: object
properties:
@@ -20725,6 +20933,25 @@ components:
description: The comment describing the composite type.
title: CompositeTypeMetadata
additionalProperties: false
+ bytebase.v1.ConfirmRecoveryCodesRequest:
+ type: object
+ properties:
+ name:
+ type: string
+ title: name
+ maxLength: 260
+ description: 'Format: users/{email}. Must be the caller''s own name.'
+ pendingVersion:
+ title: pending_version
+ description: |-
+ The pending_version of the codes being confirmed. Confirming promotes
+ exactly the set this version identifies, or nothing.
+ $ref: '#/components/schemas/google.protobuf.Timestamp'
+ title: ConfirmRecoveryCodesRequest
+ required:
+ - name
+ - pendingVersion
+ additionalProperties: false
bytebase.v1.CreateAccessGrantRequest:
type: object
properties:
@@ -22389,6 +22616,20 @@ components:
title: DimensionalConfig
additionalProperties: false
description: DimensionalConfig defines dimensional and constraint parameters for spatial indexes.
+ bytebase.v1.DisableMFARequest:
+ type: object
+ properties:
+ name:
+ type: string
+ title: name
+ maxLength: 260
+ description: |-
+ Format: users/{email}. The caller's own, or another user's with
+ bb.users.update.
+ title: DisableMFARequest
+ required:
+ - name
+ additionalProperties: false
bytebase.v1.EmailSetting:
type: object
allOf:
@@ -22461,6 +22702,29 @@ components:
enum:
- TYPE_UNSPECIFIED
- SMTP
+ bytebase.v1.EnableMFARequest:
+ type: object
+ properties:
+ name:
+ type: string
+ title: name
+ maxLength: 260
+ description: 'Format: users/{email}. Must be the caller''s own name.'
+ otpCode:
+ type: string
+ title: otp_code
+ maxLength: 64
+ description: A code from the authenticator the pending secret was just added to.
+ pendingVersion:
+ title: pending_version
+ description: The pending_version this enrollment was minted with.
+ $ref: '#/components/schemas/google.protobuf.Timestamp'
+ title: EnableMFARequest
+ required:
+ - name
+ - otpCode
+ - pendingVersion
+ additionalProperties: false
bytebase.v1.Engine:
type: string
title: Engine
@@ -28210,6 +28474,33 @@ components:
title: RefreshResponse
additionalProperties: false
description: Response from refreshing the access token.
+ bytebase.v1.RegenerateRecoveryCodesRequest:
+ type: object
+ properties:
+ name:
+ type: string
+ title: name
+ maxLength: 260
+ description: 'Format: users/{email}. Must be the caller''s own name.'
+ title: RegenerateRecoveryCodesRequest
+ required:
+ - name
+ additionalProperties: false
+ bytebase.v1.RegenerateRecoveryCodesResponse:
+ type: object
+ properties:
+ recoveryCodes:
+ type: array
+ items:
+ type: string
+ title: recovery_codes
+ description: The pending recovery codes, shown once for the caller to save.
+ pendingVersion:
+ title: pending_version
+ description: Identifies this mint; see StartMFAEnrollmentResponse.pending_version.
+ $ref: '#/components/schemas/google.protobuf.Timestamp'
+ title: RegenerateRecoveryCodesResponse
+ additionalProperties: false
bytebase.v1.RejectIssueRequest:
type: object
properties:
@@ -30395,6 +30686,47 @@ components:
description: The tasks within this stage.
title: Stage
additionalProperties: false
+ bytebase.v1.StartMFAEnrollmentRequest:
+ type: object
+ properties:
+ name:
+ type: string
+ title: name
+ maxLength: 260
+ description: 'Format: users/{email}. Must be the caller''s own name.'
+ title: StartMFAEnrollmentRequest
+ required:
+ - name
+ additionalProperties: false
+ bytebase.v1.StartMFAEnrollmentResponse:
+ type: object
+ properties:
+ otpSecret:
+ type: string
+ title: otp_secret
+ description: |-
+ The pending TOTP secret. The only response that carries it — it is never
+ readable from the User resource.
+ recoveryCodes:
+ type: array
+ items:
+ type: string
+ title: recovery_codes
+ description: The pending recovery codes, shown once for the caller to save.
+ expireTime:
+ title: expire_time
+ description: When this enrollment stops being confirmable.
+ $ref: '#/components/schemas/google.protobuf.Timestamp'
+ pendingVersion:
+ title: pending_version
+ description: |-
+ Identifies this mint. Echo it back to EnableMFA and
+ ConfirmRecoveryCodes; a mint from another tab or device replaces the
+ pending state, and those methods refuse a version that is no longer the
+ pending one rather than promoting something this caller never saw.
+ $ref: '#/components/schemas/google.protobuf.Timestamp'
+ title: StartMFAEnrollmentResponse
+ additionalProperties: false
bytebase.v1.State:
type: string
title: State
@@ -32521,22 +32853,6 @@ components:
title: update_mask
description: The list of fields to update.
$ref: '#/components/schemas/google.protobuf.FieldMask'
- otpCode:
- type:
- - string
- - "null"
- title: otp_code
- description: The otp_code is used to verify the user's identity by MFA.
- regenerateTempMfaSecret:
- type: boolean
- title: regenerate_temp_mfa_secret
- description: |-
- The regenerate_temp_mfa_secret flag means to regenerate temporary MFA secret for user.
- This is used for MFA setup. The temporary MFA secret and recovery codes will be returned in the response.
- regenerateRecoveryCodes:
- type: boolean
- title: regenerate_recovery_codes
- description: The regenerate_recovery_codes flag means to regenerate recovery codes for user.
allowMissing:
type: boolean
title: allow_missing
@@ -32645,21 +32961,10 @@ components:
mfaEnabled:
type: boolean
title: mfa_enabled
- description: The mfa_enabled flag means if the user has enabled MFA.
- tempOtpSecret:
- type: string
- title: temp_otp_secret
- description: Temporary OTP secret used during MFA setup and regeneration.
- tempRecoveryCodes:
- type: array
- items:
- type: string
- title: temp_recovery_codes
- description: Temporary recovery codes used during MFA setup and regeneration.
- tempOtpSecretCreatedTime:
- title: temp_otp_secret_created_time
- description: Timestamp when temp_otp_secret was created. Used by frontend to show countdown timer.
- $ref: '#/components/schemas/google.protobuf.Timestamp'
+ description: |-
+ Whether the user has a live MFA factor. Set by ConfirmRecoveryCodes and
+ DisableMFA, never by an update.
+ readOnly: true
phone:
type: string
title: phone
diff --git a/proto/gen/grpc-doc/v1/README.md b/proto/gen/grpc-doc/v1/README.md
index c4eb25f9d5..3644a8635e 100644
--- a/proto/gen/grpc-doc/v1/README.md
+++ b/proto/gen/grpc-doc/v1/README.md
@@ -311,11 +311,19 @@
- [v1/user_service.proto](#v1_user_service-proto)
- [BatchGetUsersRequest](#bytebase-v1-BatchGetUsersRequest)
- [BatchGetUsersResponse](#bytebase-v1-BatchGetUsersResponse)
+ - [ChangePasswordRequest](#bytebase-v1-ChangePasswordRequest)
+ - [ConfirmRecoveryCodesRequest](#bytebase-v1-ConfirmRecoveryCodesRequest)
- [CreateUserRequest](#bytebase-v1-CreateUserRequest)
- [DeleteUserRequest](#bytebase-v1-DeleteUserRequest)
+ - [DisableMFARequest](#bytebase-v1-DisableMFARequest)
+ - [EnableMFARequest](#bytebase-v1-EnableMFARequest)
- [GetUserRequest](#bytebase-v1-GetUserRequest)
- [ListUsersRequest](#bytebase-v1-ListUsersRequest)
- [ListUsersResponse](#bytebase-v1-ListUsersResponse)
+ - [RegenerateRecoveryCodesRequest](#bytebase-v1-RegenerateRecoveryCodesRequest)
+ - [RegenerateRecoveryCodesResponse](#bytebase-v1-RegenerateRecoveryCodesResponse)
+ - [StartMFAEnrollmentRequest](#bytebase-v1-StartMFAEnrollmentRequest)
+ - [StartMFAEnrollmentResponse](#bytebase-v1-StartMFAEnrollmentResponse)
- [UndeleteUserRequest](#bytebase-v1-UndeleteUserRequest)
- [UpdateEmailRequest](#bytebase-v1-UpdateEmailRequest)
- [UpdateUserRequest](#bytebase-v1-UpdateUserRequest)
@@ -5439,6 +5447,38 @@ SettingService manages workspace-level settings and configurations.
+<a name="bytebase-v1-ChangePasswordRequest"></a>
+
+### ChangePasswordRequest
+
+
+
+| Field | Type | Label | Description |
+| ----- | ---- | ----- | ----------- |
+| name | [string](#string) | | Format: users/{email}. Must be the caller&#39;s own name. |
+| new_password | [string](#string) | | |
+
+
+
+
+
+
+<a name="bytebase-v1-ConfirmRecoveryCodesRequest"></a>
+
+### ConfirmRecoveryCodesRequest
+
+
+
+| Field | Type | Label | Description |
+| ----- | ---- | ----- | ----------- |
+| 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. |
+
+
+
+
+
+
<a name="bytebase-v1-CreateUserRequest"></a>
### CreateUserRequest
@@ -5469,6 +5509,38 @@ SettingService manages workspace-level settings and configurations.
+<a name="bytebase-v1-DisableMFARequest"></a>
+
+### DisableMFARequest
+
+
+
+| Field | Type | Label | Description |
+| ----- | ---- | ----- | ----------- |
+| name | [string](#string) | | Format: users/{email}. The caller&#39;s own, or another user&#39;s with bb.users.update. |
+
+
+
+
+
+
+<a name="bytebase-v1-EnableMFARequest"></a>
+
+### EnableMFARequest
+
+
+
+| Field | Type | Label | Description |
+| ----- | ---- | ----- | ----------- |
+| 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. |
+
+
+
+
+
+
<a name="bytebase-v1-GetUserRequest"></a>
### GetUserRequest
@@ -5524,6 +5596,70 @@ For example: name == &#34;ed&#34; name.contains(&#34;ed&#34;) email == &#34;ed@b
+<a name="bytebase-v1-RegenerateRecoveryCodesRequest"></a>
+
+### RegenerateRecoveryCodesRequest
+
+
+
+| Field | Type | Label | Description |
+| ----- | ---- | ----- | ----------- |
+| name | [string](#string) | | Format: users/{email}. Must be the caller&#39;s own name. |
+
+
+
+
+
+
+<a name="bytebase-v1-RegenerateRecoveryCodesResponse"></a>
+
+### RegenerateRecoveryCodesResponse
+
+
+
+| Field | Type | Label | Description |
+| ----- | ---- | ----- | ----------- |
+| recovery_codes | [string](#string) | repeated | The pending recovery codes, shown once for the caller to save. |
+| pending_version | [google.protobuf.Timestamp](#google-protobuf-Timestamp) | | Identifies this mint; see StartMFAEnrollmentResponse.pending_version. |
+
+
+
+
+
+
+<a name="bytebase-v1-StartMFAEnrollmentRequest"></a>
+
+### StartMFAEnrollmentRequest
+
+
+
+| Field | Type | Label | Description |
+| ----- | ---- | ----- | ----------- |
+| name | [string](#string) | | Format: users/{email}. Must be the caller&#39;s own name. |
+
+
+
+
+
+
+<a name="bytebase-v1-StartMFAEnrollmentResponse"></a>
+
+### StartMFAEnrollmentResponse
+
+
+
+| Field | Type | Label | Description |
+| ----- | ---- | ----- | ----------- |
+| otp_secret | [string](#string) | | The pending TOTP secret. The only response that carries it — it is never readable from the User resource. |
+| recovery_codes | [string](#string) | repeated | The pending recovery codes, shown once for the caller to save. |
+| expire_time | [google.protobuf.Timestamp](#google-protobuf-Timestamp) | | When this enrollment stops being confirmable. |
+| pending_version | [google.protobuf.Timestamp](#google-protobuf-Timestamp) | | Identifies this mint. Echo it back to EnableMFA and ConfirmRecoveryCodes; a mint from another tab or device replaces the pending state, and those methods refuse a version that is no longer the pending one rather than promoting something this caller never saw. |
+
+
+
+
+
+
<a name="bytebase-v1-UndeleteUserRequest"></a>
### UndeleteUserRequest
@@ -5567,9 +5703,6 @@ For example: name == &#34;ed&#34; name.contains(&#34;ed&#34;) email == &#34;ed@b
The user&#39;s `name` field is used to identify the user to update. Format: users/{email} |
| update_mask | [google.protobuf.FieldMask](#google-protobuf-FieldMask) | | The list of fields to update. |
-| otp_code | [string](#string) | optional | The otp_code is used to verify the user&#39;s identity by MFA. |
-| regenerate_temp_mfa_secret | [bool](#bool) | | The regenerate_temp_mfa_secret flag means to regenerate temporary MFA secret for user. This is used for MFA setup. The temporary MFA secret and recovery codes will be returned in the response. |
-| regenerate_recovery_codes | [bool](#bool) | | The regenerate_recovery_codes flag means to regenerate recovery codes for user. |
| allow_missing | [bool](#bool) | | If set to true, and the user is not found, a new user will be created. In this situation, `update_mask` is ignored. |
@@ -5590,10 +5723,7 @@ The user&#39;s `name` field is used to identify the user to update. Format: user
| email | [string](#string) | | The email address of the user, used for login and notifications. |
| title | [string](#string) | | The display title or full name of the user. |
| password | [string](#string) | | The password for authentication. Only used during user creation or password updates. |
-| mfa_enabled | [bool](#bool) | | The mfa_enabled flag means if the user has enabled MFA. |
-| temp_otp_secret | [string](#string) | | Temporary OTP secret used during MFA setup and regeneration. |
-| temp_recovery_codes | [string](#string) | repeated | Temporary recovery codes used during MFA setup and regeneration. |
-| temp_otp_secret_created_time | [google.protobuf.Timestamp](#google-protobuf-Timestamp) | | Timestamp when temp_otp_secret was created. Used by frontend to show countdown timer. |
+| mfa_enabled | [bool](#bool) | | Whether the user has a live MFA factor. Set by ConfirmRecoveryCodes and DisableMFA, never by an update. |
| phone | [string](#string) | | Should be a valid E.164 compliant phone number. Could be empty. |
| profile | [User.Profile](#bytebase-v1-User-Profile) | | User profile metadata. |
| groups | [string](#string) | repeated | The groups for the user. Format: groups/{email} |
@@ -5643,6 +5773,12 @@ 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 |
+| 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. |
+| DisableMFA | [DisableMFARequest](#bytebase-v1-DisableMFARequest) | [User](#bytebase-v1-User) | Turns MFA off, clearing the entire MFA config — live and pending state alike. Callers may disable their own; an administrator may disable another user&#39;s with bb.users.update, which is how a locked-out user is recovered. Permissions required: bb.users.update, unless `name` is the caller&#39;s own. |
+| RegenerateRecoveryCodes | [RegenerateRecoveryCodesRequest](#bytebase-v1-RegenerateRecoveryCodesRequest) | [RegenerateRecoveryCodesResponse](#bytebase-v1-RegenerateRecoveryCodesResponse) | Mints a pending recovery-code set beside the live one and returns it. The old codes keep working until ConfirmRecoveryCodes promotes these, so a caller who closes the page mid-way is not left without any. Permissions required: None beyond being signed in as `name`. |
+| ConfirmRecoveryCodes | [ConfirmRecoveryCodesRequest](#bytebase-v1-ConfirmRecoveryCodesRequest) | [User](#bytebase-v1-User) | Promotes the pending recovery codes. During first-time enrollment this is also where the pending TOTP secret goes live, so the factor and the codes that recover it start existing in the same write. Permissions required: None beyond being signed in as `name`. |
diff --git a/proto/gen/grpc-doc/v1/index.html b/proto/gen/grpc-doc/v1/index.html
index 998d1cf22f..ce9ea287c2 100644
--- a/proto/gen/grpc-doc/v1/index.html
+++ b/proto/gen/grpc-doc/v1/index.html
@@ -1357,6 +1357,14 @@
<a href="#bytebase.v1.BatchGetUsersResponse"><span class="badge">M</span>BatchGetUsersResponse</a>
</li>
+ <li>
+ <a href="#bytebase.v1.ChangePasswordRequest"><span class="badge">M</span>ChangePasswordRequest</a>
+ </li>
+
+ <li>
+ <a href="#bytebase.v1.ConfirmRecoveryCodesRequest"><span class="badge">M</span>ConfirmRecoveryCodesRequest</a>
+ </li>
+
<li>
<a href="#bytebase.v1.CreateUserRequest"><span class="badge">M</span>CreateUserRequest</a>
</li>
@@ -1365,6 +1373,14 @@
<a href="#bytebase.v1.DeleteUserRequest"><span class="badge">M</span>DeleteUserRequest</a>
</li>
+ <li>
+ <a href="#bytebase.v1.DisableMFARequest"><span class="badge">M</span>DisableMFARequest</a>
+ </li>
+
+ <li>
+ <a href="#bytebase.v1.EnableMFARequest"><span class="badge">M</span>EnableMFARequest</a>
+ </li>
+
<li>
<a href="#bytebase.v1.GetUserRequest"><span class="badge">M</span>GetUserRequest</a>
</li>
@@ -1377,6 +1393,22 @@
<a href="#bytebase.v1.ListUsersResponse"><span class="badge">M</span>ListUsersResponse</a>
</li>
+ <li>
+ <a href="#bytebase.v1.RegenerateRecoveryCodesRequest"><span class="badge">M</span>RegenerateRecoveryCodesRequest</a>
+ </li>
+
+ <li>
+ <a href="#bytebase.v1.RegenerateRecoveryCodesResponse"><span class="badge">M</span>RegenerateRecoveryCodesResponse</a>
+ </li>
+
+ <li>
+ <a href="#bytebase.v1.StartMFAEnrollmentRequest"><span class="badge">M</span>StartMFAEnrollmentRequest</a>
+ </li>
+
+ <li>
+ <a href="#bytebase.v1.StartMFAEnrollmentResponse"><span class="badge">M</span>StartMFAEnrollmentResponse</a>
+ </li>
+
<li>
<a href="#bytebase.v1.UndeleteUserRequest"><span class="badge">M</span>UndeleteUserRequest</a>
</li>
@@ -15598,6 +15630,69 @@ Format: users/{email} </p></td>
+ <h3 id="bytebase.v1.ChangePasswordRequest">ChangePasswordRequest</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>
+
+ <tr>
+ <td>new_password</td>
+ <td><a href="#string">string</a></td>
+ <td></td>
+ <td><p> </p></td>
+ </tr>
+
+ </tbody>
+ </table>
+
+
+
+
+
+ <h3 id="bytebase.v1.ConfirmRecoveryCodesRequest">ConfirmRecoveryCodesRequest</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>
+
+ <tr>
+ <td>pending_version</td>
+ <td><a href="#google.protobuf.Timestamp">google.protobuf.Timestamp</a></td>
+ <td></td>
+ <td><p>The pending_version of the codes being confirmed. Confirming promotes
+exactly the set this version identifies, or nothing. </p></td>
+ </tr>
+
+ </tbody>
+ </table>
+
+
+
+
+
<h3 id="bytebase.v1.CreateUserRequest">CreateUserRequest</h3>
<p></p>
@@ -15647,6 +15742,69 @@ Format: users/{email} </p></td>
+ <h3 id="bytebase.v1.DisableMFARequest">DisableMFARequest</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}. The caller&#39;s own, or another user&#39;s with
+bb.users.update. </p></td>
+ </tr>
+
+ </tbody>
+ </table>
+
+
+
+
+
+ <h3 id="bytebase.v1.EnableMFARequest">EnableMFARequest</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>
+
+ <tr>
+ <td>otp_code</td>
+ <td><a href="#string">string</a></td>
+ <td></td>
+ <td><p>A code from the authenticator the pending secret was just added to. </p></td>
+ </tr>
+
+ <tr>
+ <td>pending_version</td>
+ <td><a href="#google.protobuf.Timestamp">google.protobuf.Timestamp</a></td>
+ <td></td>
+ <td><p>The pending_version this enrollment was minted with. </p></td>
+ </tr>
+
+ </tbody>
+ </table>
+
+
+
+
+
<h3 id="bytebase.v1.GetUserRequest">GetUserRequest</h3>
<p></p>
@@ -15774,6 +15932,134 @@ If this field is omitted, there are no subsequent pages. </p></td>
+ <h3 id="bytebase.v1.RegenerateRecoveryCodesRequest">RegenerateRecoveryCodesRequest</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.RegenerateRecoveryCodesResponse">RegenerateRecoveryCodesResponse</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>recovery_codes</td>
+ <td><a href="#string">string</a></td>
+ <td>repeated</td>
+ <td><p>The pending recovery codes, shown once for the caller to save. </p></td>
+ </tr>
+
+ <tr>
+ <td>pending_version</td>
+ <td><a href="#google.protobuf.Timestamp">google.protobuf.Timestamp</a></td>
+ <td></td>
+ <td><p>Identifies this mint; see StartMFAEnrollmentResponse.pending_version. </p></td>
+ </tr>
+
+ </tbody>
+ </table>
+
+
+
+
+
+ <h3 id="bytebase.v1.StartMFAEnrollmentRequest">StartMFAEnrollmentRequest</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.StartMFAEnrollmentResponse">StartMFAEnrollmentResponse</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>otp_secret</td>
+ <td><a href="#string">string</a></td>
+ <td></td>
+ <td><p>The pending TOTP secret. The only response that carries it — it is never
+readable from the User resource. </p></td>
+ </tr>
+
+ <tr>
+ <td>recovery_codes</td>
+ <td><a href="#string">string</a></td>
+ <td>repeated</td>
+ <td><p>The pending recovery codes, shown once for the caller to save. </p></td>
+ </tr>
+
+ <tr>
+ <td>expire_time</td>
+ <td><a href="#google.protobuf.Timestamp">google.protobuf.Timestamp</a></td>
+ <td></td>
+ <td><p>When this enrollment stops being confirmable. </p></td>
+ </tr>
+
+ <tr>
+ <td>pending_version</td>
+ <td><a href="#google.protobuf.Timestamp">google.protobuf.Timestamp</a></td>
+ <td></td>
+ <td><p>Identifies this mint. Echo it back to EnableMFA and
+ConfirmRecoveryCodes; a mint from another tab or device replaces the
+pending state, and those methods refuse a version that is no longer the
+pending one rather than promoting something this caller never saw. </p></td>
+ </tr>
+
+ </tbody>
+ </table>
+
+
+
+
+
<h3 id="bytebase.v1.UndeleteUserRequest">UndeleteUserRequest</h3>
<p></p>
@@ -15859,28 +16145,6 @@ Format: users/{email} </p></td>
<td><p>The list of fields to update. </p></td>
</tr>
- <tr>
- <td>otp_code</td>
- <td><a href="#string">string</a></td>
- <td>optional</td>
- <td><p>The otp_code is used to verify the user&#39;s identity by MFA. </p></td>
- </tr>
-
- <tr>
- <td>regenerate_temp_mfa_secret</td>
- <td><a href="#bool">bool</a></td>
- <td></td>
- <td><p>The regenerate_temp_mfa_secret flag means to regenerate temporary MFA secret for user.
-This is used for MFA setup. The temporary MFA secret and recovery codes will be returned in the response. </p></td>
- </tr>
-
- <tr>
- <td>regenerate_recovery_codes</td>
- <td><a href="#bool">bool</a></td>
- <td></td>
- <td><p>The regenerate_recovery_codes flag means to regenerate recovery codes for user. </p></td>
- </tr>
-
<tr>
<td>allow_missing</td>
<td><a href="#bool">bool</a></td>
@@ -15946,28 +16210,8 @@ Format: users/{email} </p></td>
<td>mfa_enabled</td>
<td><a href="#bool">bool</a></td>
<td></td>
- <td><p>The mfa_enabled flag means if the user has enabled MFA. </p></td>
- </tr>
-
- <tr>
- <td>temp_otp_secret</td>
- <td><a href="#string">string</a></td>
- <td></td>
- <td><p>Temporary OTP secret used during MFA setup and regeneration. </p></td>
- </tr>
-
- <tr>
- <td>temp_recovery_codes</td>
- <td><a href="#string">string</a></td>
- <td>repeated</td>
- <td><p>Temporary recovery codes used during MFA setup and regeneration. </p></td>
- </tr>
-
- <tr>
- <td>temp_otp_secret_created_time</td>
- <td><a href="#google.protobuf.Timestamp">google.protobuf.Timestamp</a></td>
- <td></td>
- <td><p>Timestamp when temp_otp_secret was created. Used by frontend to show countdown timer. </p></td>
+ <td><p>Whether the user has a live MFA factor. Set by ConfirmRecoveryCodes and
+DisableMFA, never by an update. </p></td>
</tr>
<tr>
@@ -16137,6 +16381,72 @@ Permissions required: bb.users.undelete</p></td>
Permissions required: bb.users.updateEmail</p></td>
</tr>
+ <tr>
+ <td>ChangePassword</td>
+ <td><a href="#bytebase.v1.ChangePasswordRequest">ChangePasswordRequest</a></td>
+ <td><a href="#bytebase.v1.User">User</a></td>
+ <td><p>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`.</p></td>
+ </tr>
+
+ <tr>
+ <td>StartMFAEnrollment</td>
+ <td><a href="#bytebase.v1.StartMFAEnrollmentRequest">StartMFAEnrollmentRequest</a></td>
+ <td><a href="#bytebase.v1.StartMFAEnrollmentResponse">StartMFAEnrollmentResponse</a></td>
+ <td><p>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`.</p></td>
+ </tr>
+
+ <tr>
+ <td>EnableMFA</td>
+ <td><a href="#bytebase.v1.EnableMFARequest">EnableMFARequest</a></td>
+ <td><a href="#bytebase.v1.User">User</a></td>
+ <td><p>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.</p></td>
+ </tr>
+
+ <tr>
+ <td>DisableMFA</td>
+ <td><a href="#bytebase.v1.DisableMFARequest">DisableMFARequest</a></td>
+ <td><a href="#bytebase.v1.User">User</a></td>
+ <td><p>Turns MFA off, clearing the entire MFA config — live and pending state
+alike. Callers may disable their own; an administrator may disable
+another user&#39;s with bb.users.update, which is how a locked-out user is
+recovered.
+Permissions required: bb.users.update, unless `name` is the caller&#39;s own.</p></td>
+ </tr>
+
+ <tr>
+ <td>RegenerateRecoveryCodes</td>
+ <td><a href="#bytebase.v1.RegenerateRecoveryCodesRequest">RegenerateRecoveryCodesRequest</a></td>
+ <td><a href="#bytebase.v1.RegenerateRecoveryCodesResponse">RegenerateRecoveryCodesResponse</a></td>
+ <td><p>Mints a pending recovery-code set beside the live one and returns it.
+The old codes keep working until ConfirmRecoveryCodes promotes these, so
+a caller who closes the page mid-way is not left without any.
+Permissions required: None beyond being signed in as `name`.</p></td>
+ </tr>
+
+ <tr>
+ <td>ConfirmRecoveryCodes</td>
+ <td><a href="#bytebase.v1.ConfirmRecoveryCodesRequest">ConfirmRecoveryCodesRequest</a></td>
+ <td><a href="#bytebase.v1.User">User</a></td>
+ <td><p>Promotes the pending recovery codes. During first-time enrollment this is
+also where the pending TOTP secret goes live, so the factor and the codes
+that recover it start existing in the same write.
+Permissions required: None beyond being signed in as `name`.</p></td>
+ </tr>
+
</tbody>
</table>
@@ -16245,6 +16555,66 @@ Permissions required: bb.users.updateEmail</p></td>
</tr>
+
+
+ <tr>
+ <td>ChangePassword</td>
+ <td>POST</td>
+ <td>/v1/{name=users/*}:changePassword</td>
+ <td>*</td>
+ </tr>
+
+
+
+
+ <tr>
+ <td>StartMFAEnrollment</td>
+ <td>POST</td>
+ <td>/v1/{name=users/*}:startMFAEnrollment</td>
+ <td>*</td>
+ </tr>
+
+
+
+
+ <tr>
+ <td>EnableMFA</td>
+ <td>POST</td>
+ <td>/v1/{name=users/*}:enableMFA</td>
+ <td>*</td>
+ </tr>
+
+
+
+
+ <tr>
+ <td>DisableMFA</td>
+ <td>POST</td>
+ <td>/v1/{name=users/*}:disableMFA</td>
+ <td>*</td>
+ </tr>
+
+
+
+
+ <tr>
+ <td>RegenerateRecoveryCodes</td>
+ <td>POST</td>
+ <td>/v1/{name=users/*}:regenerateRecoveryCodes</td>
+ <td>*</td>
+ </tr>
+
+
+
+
+ <tr>
+ <td>ConfirmRecoveryCodes</td>
+ <td>POST</td>
+ <td>/v1/{name=users/*}:confirmRecoveryCodes</td>
+ <td>*</td>
+ </tr>
+
+
</tbody>
</table>
diff --git a/proto/v1/v1/user_service.proto b/proto/v1/v1/user_service.proto
index 3ed1226472..c380d9eb30 100644
--- a/proto/v1/v1/user_service.proto
+++ b/proto/v1/v1/user_service.proto
@@ -130,6 +130,108 @@ service UserService {
option (bytebase.v1.mcp_method_class) = FORBIDDEN;
option (bytebase.v1.mcp_denial_reason) = MINTS_CREDENTIAL_FOR_OTHERS;
}
+
+ // 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
+ // end in a new password hash.
+ // Permissions required: None beyond being signed in as `name`.
+ rpc ChangePassword(ChangePasswordRequest) returns (User) {
+ option (google.api.http) = {
+ post: "/v1/{name=users/*}:changePassword"
+ body: "*"
+ };
+ option (google.api.method_signature) = "name,new_password";
+ option (bytebase.v1.auth_method) = CUSTOM;
+ option (bytebase.v1.audit) = true;
+ option (bytebase.v1.mcp_method_class) = FORBIDDEN;
+ option (bytebase.v1.mcp_denial_reason) = TAKES_OVER_ACCOUNT;
+ }
+
+ // Mints a pending TOTP secret and recovery codes for the caller'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`.
+ rpc StartMFAEnrollment(StartMFAEnrollmentRequest) returns (StartMFAEnrollmentResponse) {
+ option (google.api.http) = {
+ post: "/v1/{name=users/*}:startMFAEnrollment"
+ 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) = MINTS_CREDENTIAL;
+ }
+
+ // 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.
+ rpc EnableMFA(EnableMFARequest) returns (User) {
+ option (google.api.http) = {
+ post: "/v1/{name=users/*}:enableMFA"
+ body: "*"
+ };
+ option (google.api.method_signature) = "name,otp_code";
+ option (bytebase.v1.auth_method) = CUSTOM;
+ option (bytebase.v1.audit) = true;
+ option (bytebase.v1.mcp_method_class) = FORBIDDEN;
+ option (bytebase.v1.mcp_denial_reason) = TAKES_OVER_ACCOUNT;
+ }
+
+ // Turns MFA off, clearing the entire MFA config — live and pending state
+ // alike. Callers may disable their own; an administrator may disable
+ // another user's with bb.users.update, which is how a locked-out user is
+ // recovered.
+ // Permissions required: bb.users.update, unless `name` is the caller's own.
+ rpc DisableMFA(DisableMFARequest) returns (User) {
+ option (google.api.http) = {
+ post: "/v1/{name=users/*}:disableMFA"
+ 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) = TAKES_OVER_ACCOUNT;
+ }
+
+ // Mints a pending recovery-code set beside the live one and returns it.
+ // The old codes keep working until ConfirmRecoveryCodes promotes these, so
+ // a caller who closes the page mid-way is not left without any.
+ // Permissions required: None beyond being signed in as `name`.
+ rpc RegenerateRecoveryCodes(RegenerateRecoveryCodesRequest) returns (RegenerateRecoveryCodesResponse) {
+ option (google.api.http) = {
+ post: "/v1/{name=users/*}:regenerateRecoveryCodes"
+ 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) = MINTS_CREDENTIAL;
+ }
+
+ // Promotes the pending recovery codes. During first-time enrollment this is
+ // also where the pending TOTP secret goes live, so the factor and the codes
+ // that recover it start existing in the same write.
+ // Permissions required: None beyond being signed in as `name`.
+ rpc ConfirmRecoveryCodes(ConfirmRecoveryCodesRequest) returns (User) {
+ option (google.api.http) = {
+ post: "/v1/{name=users/*}:confirmRecoveryCodes"
+ 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) = TAKES_OVER_ACCOUNT;
+ }
}
message GetUserRequest {
@@ -218,15 +320,10 @@ message UpdateUserRequest {
// The list of fields to update.
google.protobuf.FieldMask update_mask = 2;
- // The otp_code is used to verify the user's identity by MFA.
- optional string otp_code = 3 [(bytebase.v1.audit_behavior) = SENSITIVE];
-
- // The regenerate_temp_mfa_secret flag means to regenerate temporary MFA secret for user.
- // This is used for MFA setup. The temporary MFA secret and recovery codes will be returned in the response.
- bool regenerate_temp_mfa_secret = 4;
-
- // The regenerate_recovery_codes flag means to regenerate recovery codes for user.
- bool regenerate_recovery_codes = 5;
+ // MFA enrollment moved to the dedicated methods: StartMFAEnrollment,
+ // EnableMFA, DisableMFA, RegenerateRecoveryCodes, ConfirmRecoveryCodes.
+ reserved 3, 4, 5;
+ reserved "otp_code", "regenerate_temp_mfa_secret", "regenerate_recovery_codes";
// If set to true, and the user is not found, a new user will be created.
// In this situation, `update_mask` is ignored.
@@ -267,6 +364,113 @@ message UpdateEmailRequest {
];
}
+message ChangePasswordRequest {
+ // 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
+ ];
+
+ string new_password = 2 [
+ (google.api.field_behavior) = REQUIRED,
+ (bytebase.v1.audit_behavior) = SENSITIVE,
+ (buf.validate.field).string.max_bytes = 72
+ ];
+}
+
+message StartMFAEnrollmentRequest {
+ // 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 StartMFAEnrollmentResponse {
+ // The pending TOTP secret. The only response that carries it — it is never
+ // readable from the User resource.
+ string otp_secret = 1 [(bytebase.v1.audit_behavior) = SENSITIVE];
+
+ // The pending recovery codes, shown once for the caller to save.
+ repeated string recovery_codes = 2 [(bytebase.v1.audit_behavior) = SENSITIVE];
+
+ // When this enrollment stops being confirmable.
+ google.protobuf.Timestamp expire_time = 3;
+
+ // Identifies this mint. Echo it back to EnableMFA and
+ // ConfirmRecoveryCodes; a mint from another tab or device replaces the
+ // pending state, and those methods refuse a version that is no longer the
+ // pending one rather than promoting something this caller never saw.
+ google.protobuf.Timestamp pending_version = 4;
+}
+
+message EnableMFARequest {
+ // 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
+ ];
+
+ // A code from the authenticator the pending secret was just added to.
+ string otp_code = 2 [
+ (google.api.field_behavior) = REQUIRED,
+ (bytebase.v1.audit_behavior) = SENSITIVE,
+ (buf.validate.field).string.max_len = 64
+ ];
+
+ // The pending_version this enrollment was minted with.
+ google.protobuf.Timestamp pending_version = 3 [
+ (google.api.field_behavior) = REQUIRED,
+ (buf.validate.field).required = true
+ ];
+}
+
+message DisableMFARequest {
+ // Format: users/{email}. The caller's own, or another user's with
+ // bb.users.update.
+ string name = 1 [
+ (google.api.field_behavior) = REQUIRED,
+ (google.api.resource_reference) = {type: "bytebase.com/User"},
+ (buf.validate.field).string.max_len = 260
+ ];
+}
+
+message RegenerateRecoveryCodesRequest {
+ // 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 RegenerateRecoveryCodesResponse {
+ // The pending recovery codes, shown once for the caller to save.
+ repeated string recovery_codes = 1 [(bytebase.v1.audit_behavior) = SENSITIVE];
+
+ // Identifies this mint; see StartMFAEnrollmentResponse.pending_version.
+ google.protobuf.Timestamp pending_version = 2;
+}
+
+message ConfirmRecoveryCodesRequest {
+ // 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
+ ];
+
+ // The pending_version of the codes being confirmed. Confirming promotes
+ // exactly the set this version identifies, or nothing.
+ google.protobuf.Timestamp pending_version = 2 [
+ (google.api.field_behavior) = REQUIRED,
+ (buf.validate.field).required = true
+ ];
+}
+
message User {
reserved 5, 7, 15;
@@ -295,17 +499,15 @@ message User {
(buf.validate.field).string.max_bytes = 72
];
- // The mfa_enabled flag means if the user has enabled MFA.
- bool mfa_enabled = 8;
-
- // Temporary OTP secret used during MFA setup and regeneration.
- string temp_otp_secret = 9 [(bytebase.v1.audit_behavior) = SENSITIVE];
-
- // Temporary recovery codes used during MFA setup and regeneration.
- repeated string temp_recovery_codes = 10 [(bytebase.v1.audit_behavior) = SENSITIVE];
+ // Whether the user has a live MFA factor. Set by ConfirmRecoveryCodes and
+ // DisableMFA, never by an update.
+ bool mfa_enabled = 8 [(google.api.field_behavior) = OUTPUT_ONLY];
- // Timestamp when temp_otp_secret was created. Used by frontend to show countdown timer.
- google.protobuf.Timestamp temp_otp_secret_created_time = 11;
+ // Pending enrollment state is no longer readable from the user resource:
+ // StartMFAEnrollment and RegenerateRecoveryCodes return it once, to the
+ // caller enrolling, and nowhere else.
+ reserved 9, 10, 11;
+ reserved "temp_otp_secret", "temp_recovery_codes", "temp_otp_secret_created_time";
// Should be a valid E.164 compliant phone number.
// Could be empty.