Skip to content

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

feat: challenge MFA when signin (#5013)

boojackb5c3bfc582ed
diff --git a/backend/api/v1/auth_service.go b/backend/api/v1/auth_service.go
index caeca97ea1..4d3f659409 100644
--- a/backend/api/v1/auth_service.go
+++ b/backend/api/v1/auth_service.go
@@ -307,7 +307,7 @@ func (s *AuthService) UpdateUser(ctx context.Context, request *v1pb.UpdateUserRe
}
// This flag is mainly used for regenerating temp secret and recovery codes when user setup MFA.
if request.RegenerateTempMfaSecret {
- tempSecret, err := generateRandSecret(user.Name)
+ tempSecret, err := generateRandSecret(fmt.Sprintf("%s%d", userNamePrefix, user.ID))
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to generate MFA secret, error: %v", err)
}
@@ -730,7 +730,7 @@ func validateEmail(email string) error {
const (
// issuerName is the name of the issuer of the OTP token.
- issuerName = "Bytebase"
+ issuerName = "bytebase"
)
// generateRandSecret generates a random secret for the given account name.
diff --git a/backend/store/principal.go b/backend/store/principal.go
index 59b3885093..b4d691225d 100644
--- a/backend/store/principal.go
+++ b/backend/store/principal.go
@@ -433,24 +433,54 @@ func (s *Store) UpdateUser(ctx context.Context, userID int, patch *UpdateUserMes
defer tx.Rollback()
user := &UserMessage{}
- if err := tx.QueryRowContext(ctx, fmt.Sprintf(`
+ if common.FeatureFlag(common.FeatureFlagNoop) {
+ var mfaConfigBytes []byte
+ if err := tx.QueryRowContext(ctx, fmt.Sprintf(`
+ UPDATE principal
+ SET `+strings.Join(principalSet, ", ")+`
+ WHERE id = $%d
+ RETURNING id, email, name, type, password_hash, mfa_config
+ `, len(principalArgs)),
+ principalArgs...,
+ ).Scan(
+ &user.ID,
+ &user.Email,
+ &user.Name,
+ &user.Type,
+ &user.PasswordHash,
+ &mfaConfigBytes,
+ ); err != nil {
+ if err == sql.ErrNoRows {
+ return nil, nil
+ }
+ return nil, FormatError(err)
+ }
+ mfaConfig := storepb.MFAConfig{}
+ decoder := protojson.UnmarshalOptions{DiscardUnknown: true}
+ if err := decoder.Unmarshal(mfaConfigBytes, &mfaConfig); err != nil {
+ return nil, err
+ }
+ user.MFAConfig = &mfaConfig
+ } else {
+ if err := tx.QueryRowContext(ctx, fmt.Sprintf(`
UPDATE principal
SET `+strings.Join(principalSet, ", ")+`
WHERE id = $%d
RETURNING id, email, name, type, password_hash
`, len(principalArgs)),
- principalArgs...,
- ).Scan(
- &user.ID,
- &user.Email,
- &user.Name,
- &user.Type,
- &user.PasswordHash,
- ); err != nil {
- if err == sql.ErrNoRows {
- return nil, nil
+ principalArgs...,
+ ).Scan(
+ &user.ID,
+ &user.Email,
+ &user.Name,
+ &user.Type,
+ &user.PasswordHash,
+ ); err != nil {
+ if err == sql.ErrNoRows {
+ return nil, nil
+ }
+ return nil, FormatError(err)
}
- return nil, FormatError(err)
}
var rowStatus string
diff --git a/frontend/src/components/MFAChallengeModal.vue b/frontend/src/components/MFAChallengeModal.vue
new file mode 100644
index 0000000000..509cba9ec4
--- /dev/null
+++ b/frontend/src/components/MFAChallengeModal.vue
@@ -0,0 +1,109 @@
+<template>
+ <BBModal :title="modalTitle" :show-close="false">
+ <div class="w-72">
+ <div class="w-full mt-4 h-auto flex flex-col justify-start items-center">
+ <template v-if="state.selectedMFAType === 'OTP'">
+ <heroicons-outline:device-phone-mobile class="w-8 h-auto" />
+ <p class="my-2 mb-4">{{ $t("multi-factor.auth-code") }}</p>
+ <input
+ v-model="state.otpCode"
+ placeholder="XXXXXX"
+ class="textfield w-full"
+ type="text"
+ />
+ </template>
+ <template v-else-if="state.selectedMFAType === 'RECOVERY_CODE'">
+ <heroicons-outline:key class="w-8 h-auto" />
+ <p class="my-2 mb-4">{{ $t("multi-factor.recovery-code") }}</p>
+ <input
+ v-model="state.recoveryCode"
+ placeholder="XXXXXXXXXX"
+ class="textfield w-full"
+ type="text"
+ />
+ </template>
+ <button class="btn-success w-full mt-4" @click="challenge">
+ <span class="w-full text-center">{{ $t("common.verify") }}</span>
+ </button>
+ <p class="textinfolabel mt-2">
+ {{ challengeDescription }}
+ </p>
+ </div>
+ <hr class="my-3" />
+ <div class="text-sm mb-2">
+ <p class="">{{ $t("multi-factor.other-methods.self") }}:</p>
+ <ul class="list-disc list-inside pl-2 pt-1">
+ <li v-if="state.selectedMFAType !== 'OTP'">
+ <button class="accent-link" @click="state.selectedMFAType = 'OTP'">
+ {{ $t("multi-factor.other-methods.use-auth-app.self") }}
+ </button>
+ </li>
+ <li v-if="state.selectedMFAType !== 'RECOVERY_CODE'">
+ <button
+ class="accent-link"
+ @click="state.selectedMFAType = 'RECOVERY_CODE'"
+ >
+ {{ $t("multi-factor.other-methods.use-recovery-code.self") }}
+ </button>
+ </li>
+ </ul>
+ </div>
+ </div>
+ </BBModal>
+</template>
+
+<script lang="ts" setup>
+import { computed, reactive } from "vue";
+import { useI18n } from "vue-i18n";
+
+type MFAType = "OTP" | "RECOVERY_CODE";
+
+interface LocalState {
+ selectedMFAType: MFAType;
+ otpCode: string;
+ recoveryCode: string;
+}
+
+const props = defineProps({
+ title: {
+ type: String,
+ default: "",
+ },
+ challengeCallback: {
+ type: Function,
+ required: true,
+ },
+});
+
+const { t } = useI18n();
+const state = reactive<LocalState>({
+ selectedMFAType: "OTP",
+ otpCode: "",
+ recoveryCode: "",
+});
+
+const modalTitle = computed(() => {
+ return props.title ? props.title : t("multi-factor.self");
+});
+const challengeDescription = computed(() => {
+ if (state.selectedMFAType === "OTP") {
+ return t("multi-factor.other-methods.use-auth-app.description");
+ } else if (state.selectedMFAType === "RECOVERY_CODE") {
+ return t("multi-factor.other-methods.use-recovery-code.description");
+ } else {
+ return "";
+ }
+});
+
+const challenge = async () => {
+ if (state.selectedMFAType === "OTP") {
+ await props.challengeCallback({
+ otpCode: state.otpCode,
+ });
+ } else if (state.selectedMFAType === "RECOVERY_CODE") {
+ await props.challengeCallback({
+ recoveryCode: state.recoveryCode,
+ });
+ }
+};
+</script>
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index ce3b5d0246..9a0bb2c16f 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -225,7 +225,8 @@
"demo-mode": "Demo",
"operations": "Operations",
"on": "On",
- "off": "Off"
+ "off": "Off",
+ "verify": "Verify"
},
"error-page": {
"go-back-home": "Go back home"
@@ -1928,6 +1929,22 @@
"overflow": "The {resource} ID is too long. It should have less than 64 characters."
}
},
+ "multi-factor": {
+ "self": "Multi-factor authentication",
+ "auth-code": "Authentication code",
+ "recovery-code": "Recovery code",
+ "other-methods": {
+ "self": "Other methods",
+ "use-auth-app": {
+ "self": "Use your authenticator app",
+ "description": "Open the two-factor authenticator (TOTP) app on your mobile device to view your authentication code."
+ },
+ "use-recovery-code": {
+ "self": "Use a recovery code",
+ "description": "If you are unable to access your mobile device, enter one of your recovery codes to verify your identity."
+ }
+ }
+ },
"two-factor": {
"self": "Two-factor authentication",
"description": "Two-factor authentication provides an extra layer of security for member accounts. When signing in, you will be required to enter the security code generated by your Authenticator App.",
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index 6da85fe6ab..97389633b1 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -223,7 +223,8 @@
"demo-mode": "演示模式",
"operations": "操作",
"on": "开",
- "off": "关"
+ "off": "关",
+ "verify": "验证"
},
"error-page": {
"go-back-home": "回到主页"
@@ -1927,6 +1928,22 @@
"overflow": "{resource} ID 应该少于 64 个字符。"
}
},
+ "multi-factor": {
+ "self": "多重认证",
+ "auth-code": "认证码",
+ "recovery-code": "恢复码",
+ "other-methods": {
+ "self": "其他方法",
+ "use-auth-app": {
+ "self": "使用身份验证器应用程序",
+ "description": "在您的移动设备上打开双因素认证器(TOTP)应用程序,查看认证码。"
+ },
+ "use-recovery-code": {
+ "self": "使用恢复码",
+ "description": "如果您无法访问你的移动设备,请输入一个恢复代码来验证您的身份。"
+ }
+ }
+ },
"two-factor": {
"self": "双重认证",
"description": "双重认证为系统成员提供了一个额外的安全层。在登录时,用户需要输入由认证器应用程序生成的安全代码。",
diff --git a/frontend/src/store/modules/user.ts b/frontend/src/store/modules/user.ts
index 538ba97a26..64d9e15ac2 100644
--- a/frontend/src/store/modules/user.ts
+++ b/frontend/src/store/modules/user.ts
@@ -1,6 +1,11 @@
import { defineStore } from "pinia";
import { authServiceClient } from "@/grpcweb";
-import { User, userRoleToJSON, UserType } from "@/types/proto/v1/auth_service";
+import {
+ UpdateUserRequest,
+ User,
+ userRoleToJSON,
+ UserType,
+} from "@/types/proto/v1/auth_service";
import { isEqual, isUndefined } from "lodash-es";
import { getUserId, userNamePrefix } from "./v1/common";
import { Principal, PrincipalType, RoleType } from "@/types";
@@ -40,16 +45,14 @@ export const useUserStore = defineStore("user", {
this.userMapByName.set(user.name, user);
return user;
},
- async updateUser(update: Partial<User>) {
- const originData = await this.getOrFetchUserByName(update.name || "");
+ async updateUser(updateUserRequest: UpdateUserRequest) {
+ const name = updateUserRequest.user?.name || "";
+ const originData = await this.getOrFetchUserByName(name);
if (!originData) {
- throw new Error(`user with name ${update.name} not found`);
+ throw new Error(`user with name ${name} not found`);
}
- const user = await authServiceClient.updateUser({
- user: update,
- updateMask: getUpdateMaskFromUsers(originData, update),
- });
+ const user = await authServiceClient.updateUser(updateUserRequest);
this.userMapByName.set(user.name, user);
return user;
},
@@ -80,9 +83,9 @@ export const getUserNameWithUserId = (userId: number) => {
return `${userNamePrefix}${userId}`;
};
-const getUpdateMaskFromUsers = (
+export const getUpdateMaskFromUsers = (
origin: User,
- update: Partial<User>
+ update: User | Partial<User>
): string[] => {
const updateMask: string[] = [];
if (!isUndefined(update.title) && !isEqual(origin.title, update.title)) {
diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.ts
index faa3d0dd7e..44234754d7 100644
--- a/frontend/src/types/index.ts
+++ b/frontend/src/types/index.ts
@@ -48,3 +48,4 @@ export * from "./utils";
export * from "./onboardingGuide";
export * from "./schemaEditor";
export * from "./externalApproval";
+export * from "./mfa";
diff --git a/frontend/src/types/mfa.ts b/frontend/src/types/mfa.ts
new file mode 100644
index 0000000000..3ac57ecae5
--- /dev/null
+++ b/frontend/src/types/mfa.ts
@@ -0,0 +1,6 @@
+export interface MFAChallengeContext {
+ otpCode?: string;
+ recoveryCode?: string;
+}
+
+export type MFAChallengeCallback = (context: MFAChallengeContext) => any;
diff --git a/frontend/src/views/auth/Signin.vue b/frontend/src/views/auth/Signin.vue
index 7870863cf3..781701cb63 100644
--- a/frontend/src/views/auth/Signin.vue
+++ b/frontend/src/views/auth/Signin.vue
@@ -142,13 +142,22 @@
</div>
</div>
<AuthFooter />
+
+ <MFAChallengeModal
+ v-if="state.showMFAChallengeModal"
+ :challenge-callback="state.mfaChallengeCallback"
+ />
</template>
<script lang="ts" setup>
import { computed, onMounted, onUnmounted, reactive, watch } from "vue";
import { useRouter } from "vue-router";
import { storeToRefs } from "pinia";
-import { OAuthWindowEventPayload } from "@/types";
+import {
+ MFAChallengeCallback,
+ MFAChallengeContext,
+ OAuthWindowEventPayload,
+} from "@/types";
import { isValidEmail, openWindowForSSO } from "@/utils";
import {
featureToRef,
@@ -161,12 +170,16 @@ import {
IdentityProviderType,
} from "@/types/proto/v1/idp_service";
import AuthFooter from "./AuthFooter.vue";
+import MFAChallengeModal from "@/components/MFAChallengeModal.vue";
+import { Status } from "nice-grpc-common";
interface LocalState {
email: string;
password: string;
showPassword: boolean;
activeIdentityProvider?: IdentityProvider;
+ showMFAChallengeModal: boolean;
+ mfaChallengeCallback: MFAChallengeCallback;
}
const actuatorStore = useActuatorStore();
@@ -178,8 +191,11 @@ const state = reactive<LocalState>({
email: "",
password: "",
showPassword: false,
+ showMFAChallengeModal: false,
+ mfaChallengeCallback: (_: MFAChallengeContext) => undefined,
});
const { isDemo, disallowSignup } = storeToRefs(actuatorStore);
+const hasSSOFeature = featureToRef("bb.feature.sso");
const identityProviderList = computed(
() => identityProviderStore.identityProviderList
@@ -246,17 +262,33 @@ const loginWithIdentityProviderEventListener = async (event: Event) => {
if (payload.error) {
return;
}
- const code = payload.code;
- await authStore.login({
+
+ const signinContext = {
idpName: state.activeIdentityProvider.name,
- context: {
+ idpContext: {
oauth2Context: {
- code,
+ code: payload.code,
},
},
web: true,
- });
- router.push("/");
+ };
+ try {
+ await authStore.login({
+ ...signinContext,
+ });
+ router.push("/");
+ } catch (error: any) {
+ if (error.response.data.code === Status.FAILED_PRECONDITION) {
+ state.showMFAChallengeModal = true;
+ state.mfaChallengeCallback = async (mfaContext) => {
+ await authStore.login({
+ ...signinContext,
+ ...mfaContext,
+ });
+ router.push("/");
+ };
+ }
+ }
}
};
@@ -265,12 +297,28 @@ const allowSignin = computed(() => {
});
const trySignin = async () => {
- await authStore.login({
+ const signinContext = {
email: state.email,
password: state.password,
web: true,
- });
- router.push("/");
+ };
+ try {
+ await authStore.login({
+ ...signinContext,
+ });
+ router.push("/");
+ } catch (error: any) {
+ if (error.response.data.code === Status.FAILED_PRECONDITION) {
+ state.showMFAChallengeModal = true;
+ state.mfaChallengeCallback = async (mfaContext) => {
+ await authStore.login({
+ ...signinContext,
+ ...mfaContext,
+ });
+ router.push("/");
+ };
+ }
+ }
};
const trySigninWithIdentityProvider = async (
@@ -279,6 +327,4 @@ const trySigninWithIdentityProvider = async (
state.activeIdentityProvider = identityProvider;
await openWindowForSSO(identityProvider);
};
-
-const hasSSOFeature = featureToRef("bb.feature.sso");
</script>