Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
Improve VCS OAuth setup workflow
天舟1fd48dfbb595
diff --git a/frontend/src/components/RepositorySetupWizard.vue b/frontend/src/components/RepositorySetupWizard.vueindex 5a3154e270..697a346077 100644--- a/frontend/src/components/RepositorySetupWizard.vue+++ b/frontend/src/components/RepositorySetupWizard.vue@@ -1,8 +1,8 @@<template><BBStepTab:stepItemList="stepList"- @select-step="selectStep"- @finish="finishSetup"+ @try-change-step="tryChangeStep"+ @try-finish="tryFinishSetup"><template v-slot:0="{ next }"><RepositoryVCSPanel :config="state.config" @next="next()" />@@ -55,11 +55,11 @@ export default {},});- const selectStep = (step: number) => {- console.log("select step", step);+ const tryChangeStep = (oldStep: number, newStep: number) => {+ console.log("select step", newStep);};- const finishSetup = () => {+ const tryFinishSetup = (allowFinishCallback: () => void) => {console.log("finish", state.config);store.dispatch("gitlab/createWebhook", {@@ -68,14 +68,16 @@ export default {branchFilter: state.config.branchFilter,token: state.config.accessToken,})- .then((createdHook) => {});+ .then((createdHook) => {+ allowFinishCallback();+ });};return {state,stepList,- selectStep,- finishSetup,+ tryChangeStep,+ tryFinishSetup,};},};diff --git a/frontend/src/components/RepositoryVCSPanel.vue b/frontend/src/components/RepositoryVCSPanel.vueindex c9797dd39c..cd18cac26f 100644--- a/frontend/src/components/RepositoryVCSPanel.vue+++ b/frontend/src/components/RepositoryVCSPanel.vue@@ -24,9 +24,10 @@ import {} from "@vue/runtime-core";import isEmpty from "lodash-es/isEmpty";import {+ OAuthConfig,OAuthWindowEvent,OAuthWindowEventPayload,- openWindowForVCSOAuth,+ openWindowForOAuth,ProjectRepoConfig,redirectURL,VCS,@@ -64,11 +65,16 @@ export default {const payload = (event as CustomEvent).detail as OAuthWindowEventPayload;if (isEmpty(payload.error)) {props.config.code = payload.code;+ const oAuthConfig: OAuthConfig = {+ endpoint: `${state.selectedVCS!.instanceURL}/oauth/token`,+ applicationId: state.selectedVCS!.applicationId,+ secret: state.selectedVCS!.secret,+ redirectURL: redirectURL(),+ };store.dispatch("gitlab/exchangeToken", {- vcs: state.selectedVCS,+ oAuthConfig,code: payload.code,- redirectURL: redirectURL(),}).then((token: string) => {props.config.vcs = state.selectedVCS!;@@ -90,7 +96,10 @@ export default {const selectVCS = (vcs: VCS) => {state.selectedVCS = vcs;- const newWindow = openWindowForVCSOAuth(vcs);+ const newWindow = openWindowForOAuth(+ `${vcs.instanceURL}/oauth/authorize`,+ vcs.applicationId+ );if (newWindow) {window.addEventListener(OAuthWindowEvent, eventListener, false);}diff --git a/frontend/src/components/VCSCard.vue b/frontend/src/components/VCSCard.vueindex fe91ce5cac..fe5bfc8080 100644--- a/frontend/src/components/VCSCard.vue+++ b/frontend/src/components/VCSCard.vue@@ -76,10 +76,10 @@ import {redirectURL,OAuthWindowEvent,OAuthWindowEventPayload,- openWindowForVCSOAuth,+ openWindowForOAuth,VCSTokenCreate,} from "../types";-import { isEmpty } from "lodash";+import isEmpty from "lodash-es/isEmpty";interface LocalState {}@@ -118,7 +118,10 @@ export default {});const linkVCS = () => {- const newWindow = openWindowForVCSOAuth(props.vcs);+ const newWindow = openWindowForOAuth(+ `${props.vcs.instanceURL}/oauth/authorize`,+ props.vcs.applicationId+ );if (newWindow) {window.addEventListener(OAuthWindowEvent, eventListener, false);}diff --git a/frontend/src/components/VCSProviderInfoPanel.vue b/frontend/src/components/VCSProviderBasicInfoPanel.vuesimilarity index 62%rename from frontend/src/components/VCSProviderInfoPanel.vuerename to frontend/src/components/VCSProviderBasicInfoPanel.vueindex 7c649faab4..f58e8ef741 100644--- a/frontend/src/components/VCSProviderInfoPanel.vue+++ b/frontend/src/components/VCSProviderBasicInfoPanel.vue@@ -1,5 +1,54 @@<template><div class="textlabel">+ Choose Git provider <span class="text-red-600">*</span>+ </div>+ <div class="pt-2 flex flex-row radio-set">+ <div class="radio space-x-2">+ <input+ name="Self-host GitLab"+ tabindex="-1"+ type="radio"+ class="btn"+ value="GITLAB_SELF_HOST"+ v-model="config.type"+ />+ <img class="h-6 w-auto" src="../assets/gitlab-logo.svg" />+ <label class="whitespace-nowrap"+ >Self-host GitLab Enterprise Edition (EE) or Community Edition (CE)+ </label>+ </div>+ </div>+ <div class="mt-4 relative">+ <div class="absolute inset-0 flex items-center" aria-hidden="true">+ <div class="w-full border-t border-block-border"></div>+ </div>+ <div class="relative flex justify-start">+ <span class="pr-2 bg-white text-sm text-control-light">+ Coming later+ </span>+ </div>+ </div>+ <div class="mt-2 flex flex-row itmes-center space-x-4 text-sm">+ <div class="flex flex-row space-x-2 items-center text-control">+ <div class="h-5 w-5">+ <img src="../assets/gitlab-logo.svg" />+ </div>+ <label class="whitespace-nowrap">GitLab.com </label>+ </div>+ <div class="flex flex-row space-x-2 items-center text-control">+ <div class="h-5 w-5">+ <img src="../assets/github-logo.svg" />+ </div>+ <label class="whitespace-nowrap">GitHub Enterprise </label>+ </div>+ <div class="flex flex-row space-x-2 items-center text-control">+ <div class="h-5 w-5">+ <img src="../assets/github-logo.svg" />+ </div>+ <label class="whitespace-nowrap">GitHub.com </label>+ </div>+ </div>+ <div class="mt-4 pt-6 border-t border-block-border textlabel">{{ instanceURLLabel }} <span class="text-red-600">*</span></div><p class="mt-1 textinfolabel">@@ -15,7 +64,7 @@<p v-if="state.showURLError" class="mt-2 text-sm text-error">Instance URL must begin with https:// or http://</p>- <div class="mt-4 textlabel">Display Name</div>+ <div class="mt-4 textlabel">Display name</div><p class="mt-1 textinfolabel">An optional display name to help identifying among different configs usingthe same Git provider.@@ -40,7 +89,7 @@ interface LocalState {}export default {- name: "VCSProviderInfoPanel",+ name: "VCSProviderBasicInfoPanel",props: {config: {required: true,diff --git a/frontend/src/components/VCSProviderConfirmPanel.vue b/frontend/src/components/VCSProviderConfirmPanel.vuenew file mode 100644index 0000000000..e106fc3fad--- /dev/null+++ b/frontend/src/components/VCSProviderConfirmPanel.vue@@ -0,0 +1,91 @@+<template>+ <div class="m-4 flex justify-center">+ <dl+ class="+ divide-y divide-block-border+ border border-block-border+ shadow+ rounded-lg+ "+ >+ <div class="px-4 py-5 sm:px-6">+ <h3 class="text-lg leading-6 font-medium text-main">+ Confirm to add this Git provider+ </h3>+ <p class="mt-1 textinfolabel">+ After creation, this Git provider can be selected under the "Version+ Control" tab from the project dashboard by the project owner.+ </p>+ </div>+ <div class="grid grid-cols-4 gap-4 px-4 py-2">+ <dt class="text-sm font-medium text-control-light text-right">Type</dt>+ <dd class="col-start-2 col-span-3 text-sm text-main">+ <div+ v-if="config.type == 'GITLAB_SELF_HOST'"+ class="flex flex-row items-center space-x-2"+ >+ <img class="h-6 w-auto" src="../assets/gitlab-logo.svg" />+ <div class="whitespace-nowrap">+ Self-host GitLab Enterprise Edition (EE) or Community Edition (CE)+ </div>+ </div>+ </dd>+ </div>+ <div class="grid grid-cols-4 gap-4 px-4 py-2">+ <dt class="text-sm font-medium text-control-light text-right">Name</dt>+ <dd class="col-start-2 col-span-3 text-sm text-main">+ {{ config.name }}+ </dd>+ </div>+ <div class="grid grid-cols-4 gap-4 px-4 py-2">+ <dt class="text-sm font-medium text-control-light text-right">+ Instance URL+ </dt>+ <dd class="col-start-2 col-span-3 text-sm text-main">+ {{ config.instanceURL }}+ </dd>+ </div>+ <div class="grid grid-cols-4 gap-4 px-4 py-2">+ <dt class="text-sm font-medium text-control-light text-right">+ Application ID+ </dt>+ <dd class="col-start-2 col-span-3 text-sm text-main">+ {{ config.applicationId }}+ </dd>+ </div>+ <div class="grid grid-cols-4 gap-4 px-4 py-2">+ <dt class="text-sm font-medium text-control-light text-right">+ Secret+ </dt>+ <dd class="col-start-2 col-span-3 text-sm text-main">+ {{ config.secret }}+ </dd>+ </div>+ </dl>+ </div>+</template>++<script lang="ts">+import { PropType, reactive } from "@vue/runtime-core";+import { VCSConfig, redirectURL } from "../types";++interface LocalState {}++export default {+ name: "VCSProviderConfirmPanel",+ props: {+ config: {+ required: true,+ type: Object as PropType<VCSConfig>,+ },+ },+ setup(props, ctx) {+ const state = reactive<LocalState>({});++ return {+ redirectURL,+ state,+ };+ },+};+</script>diff --git a/frontend/src/components/VCSProviderOAuthPanel.vue b/frontend/src/components/VCSProviderOAuthPanel.vueindex 00ed6cca98..8adf859874 100644--- a/frontend/src/components/VCSProviderOAuthPanel.vue+++ b/frontend/src/components/VCSProviderOAuthPanel.vue@@ -78,7 +78,7 @@</div><BBTextFieldclass="mt-2 w-full"- :placeholder="'ex. 5333b60a6c9f234272dac2ee6b3422aaf224e0a66def54e0d243b77be7a8edda'"+ :placeholder="'ex. 5333b60a6c9f234272dac2ee6b3422aaf224e0a66def54e0d243b77bexa8edda'":value="config.applicationId"@input="changeApplicatonId($event.target.value)"/>@@ -90,7 +90,7 @@</div><BBTextFieldclass="mt-2 w-full"- :placeholder="'ex. b9e0efc7a233403799b42620c60ff98c146895a27b6219912ad15f4e2251cc3a'"+ :placeholder="'ex. b9e0efc7a233403799b42620c60ff98c146895a27b6219912a215f4e2251cc3a'":value="config.secret"@input="changeSecret($event.target.value)"/>diff --git a/frontend/src/components/VCSProviderSelectionPanel.vue b/frontend/src/components/VCSProviderSelectionPanel.vuedeleted file mode 100644index f926001fd3..0000000000--- a/frontend/src/components/VCSProviderSelectionPanel.vue+++ /dev/null@@ -1,68 +0,0 @@-<template>- <div class="flex flex-row radio-set">- <div class="radio space-x-2">- <input- name="Self-host GitLab"- tabindex="-1"- type="radio"- class="btn"- value="GITLAB_SELF_HOST"- v-model="config.type"- />- <img class="h-6 w-auto" src="../assets/gitlab-logo.svg" />- <label class="whitespace-nowrap"- >Self-host GitLab Enterprise Edition (EE) or Community Edition (CE)- </label>- </div>- </div>- <div class="mt-4 relative">- <div class="absolute inset-0 flex items-center" aria-hidden="true">- <div class="w-full border-t border-block-border"></div>- </div>- <div class="relative flex justify-start">- <span class="pr-2 bg-white text-sm text-control-light">- Coming later- </span>- </div>- </div>- <div class="mt-2 flex flex-row itmes-center space-x-4">- <div class="flex flex-row space-x-2 items-center text-control">- <div class="h-5 w-5">- <img src="../assets/gitlab-logo.svg" />- </div>- <label class="whitespace-nowrap">GitLab.com </label>- </div>- <div class="flex flex-row space-x-2 items-center text-control">- <div class="h-5 w-5">- <img src="../assets/github-logo.svg" />- </div>- <label class="whitespace-nowrap">GitHub Enterprise </label>- </div>- <div class="flex flex-row space-x-2 items-center text-control">- <div class="h-5 w-5">- <img src="../assets/github-logo.svg" />- </div>- <label class="whitespace-nowrap">GitHub.com </label>- </div>- </div>-</template>--<script lang="ts">-import { PropType } from "@vue/runtime-core";-import { VCSConfig } from "../types";-export default {- name: "VCSProviderSelectionPanel",- props: {- config: {- required: true,- type: Object as PropType<VCSConfig>,- },- },- setup(props, ctx) {- const selectGitLabOnPrem = () => {- props.config.type = "GITLAB_SELF_HOST";- };- return { selectGitLabOnPrem };- },-};-</script>diff --git a/frontend/src/components/VCSSetupWizard.vue b/frontend/src/components/VCSSetupWizard.vueindex 20c8ed7f48..88e08a05b1 100644--- a/frontend/src/components/VCSSetupWizard.vue+++ b/frontend/src/components/VCSSetupWizard.vue@@ -1,21 +1,21 @@<template>- <BBAttention :description="attentionText" />+ <BBAttention v-if="showAttention" :description="attentionText" /><BBStepTabclass="mt-4":stepItemList="stepList":allowNext="allowNext"- @select-step="selectStep"- @finish="finishSetup"+ @try-change-step="tryChangeStep"+ @try-finish="tryFinishSetup"@cancel="cancelSetup"><template v-slot:0>- <VCSProviderSelectionPanel :config="state.config" />+ <VCSProviderBasicInfoPanel :config="state.config" /></template><template v-slot:1>- <VCSProviderInfoPanel :config="state.config" />+ <VCSProviderOAuthPanel :config="state.config" /></template><template v-slot:2>- <VCSProviderOAuthPanel :config="state.config" />+ <VCSProviderConfirmPanel :config="state.config" /></template></BBStepTab></template>@@ -24,36 +24,48 @@import { computed } from "@vue/runtime-core";import { reactive } from "@vue/reactivity";import { useRouter } from "vue-router";+import { useStore } from "vuex";+import isEmpty from "lodash-es/isEmpty";import { BBStepTabItem } from "../bbkit/types";-import VCSProviderSelectionPanel from "./VCSProviderSelectionPanel.vue";-import VCSProviderInfoPanel from "./VCSProviderInfoPanel.vue";+import VCSProviderBasicInfoPanel from "./VCSProviderBasicInfoPanel.vue";import VCSProviderOAuthPanel from "./VCSProviderOAuthPanel.vue";+import VCSProviderConfirmPanel from "./VCSProviderConfirmPanel.vue";import {isValidVCSApplicationIdOrSecret,VCSConfig,VCSCreate,+ VCS,+ openWindowForOAuth,+ OAuthWindowEventPayload,+ OAuthWindowEvent,+ OAuthConfig,+ redirectURL,} from "../types";import { isURL } from "../utils";-import { useStore } from "vuex";++const BASIC_INFO_STEP = 0;+const OAUTH_INFO_STEP = 1;+const CONFIRM_STEP = 2;const stepList: BBStepTabItem[] = [- { title: "Choose Git provider" },{ title: "Basic info" },{ title: "OAuth application info" },+ { title: "Confirm" },];interface LocalState {config: VCSConfig;currentStep: number;+ oauthResultCallback?: (success: boolean) => void;}export default {name: "VCSSetupWizard",props: {},components: {- VCSProviderSelectionPanel,- VCSProviderInfoPanel,+ VCSProviderBasicInfoPanel,VCSProviderOAuthPanel,+ VCSProviderConfirmPanel,},setup(props, ctx) {const store = useStore();@@ -64,7 +76,7 @@ export default {const state = reactive<LocalState>({config: {type: "GITLAB_SELF_HOST",- name: "",+ name: "GitLab self-host",instanceURL: "",applicationId: "",secret: "",@@ -72,12 +84,39 @@ export default {currentStep: 0,});+ const eventListener = (event: Event) => {+ const payload = (event as CustomEvent).detail as OAuthWindowEventPayload;+ if (isEmpty(payload.error)) {+ if (state.config.type == "GITLAB_SELF_HOST") {+ const oAuthConfig: OAuthConfig = {+ endpoint: `${state.config.instanceURL}/oauth/token`,+ applicationId: state.config.applicationId,+ secret: state.config.secret,+ redirectURL: redirectURL(),+ };+ store+ .dispatch("gitlab/exchangeToken", {+ oAuthConfig,+ code: payload.code,+ })+ .then((token: string) => {+ state.oauthResultCallback!(true);+ })+ .catch((error) => {+ state.oauthResultCallback!(false);+ });+ }+ } else {+ state.oauthResultCallback!(false);+ }++ window.removeEventListener(OAuthWindowEvent, eventListener);+ };+const allowNext = computed((): boolean => {- if (state.currentStep == 0) {- return true;- } else if (state.currentStep == 1) {+ if (state.currentStep == BASIC_INFO_STEP) {return isURL(state.config.instanceURL);- } else if (state.currentStep == 2) {+ } else if (state.currentStep == OAUTH_INFO_STEP) {return (isValidVCSApplicationIdOrSecret(state.config.applicationId) &&isValidVCSApplicationIdOrSecret(state.config.secret)@@ -88,26 +127,80 @@ export default {const attentionText = computed((): string => {if (state.config.type == "GITLAB_SELF_HOST") {- return "You need to be an Admin of your chosen GitLab instance to configure this. Otherwise, you need to ask your GitLab instance Admin to register a system OAuth application for Bytebase, then provide you that Application ID and Secret to fill in Step 3.";+ return "You need to be an Admin of your chosen GitLab instance to configure this. Otherwise, you need to ask your GitLab instance Admin to register Bytebase as a system OAuth application in GitLab, then provide you that Application ID and Secret to fill in the 'OAuth application info' step.";}return "";});- const selectStep = (step: number) => {- state.currentStep = step;- };+ const showAttention = computed((): boolean => {+ return state.currentStep != CONFIRM_STEP;+ });- const finishSetup = () => {- if (state.config.name == "") {- if (state.config.type == "GITLAB_SELF_HOST") {- state.config.name = state.config.instanceURL;+ const tryChangeStep = (+ oldStep: number,+ newStep: number,+ allowChangeCallback: () => void+ ) => {+ // If we are trying to move from OAuth step to Confirm step, we first verify+ // the OAuth info is correct. We achieve this by:+ // 1. Kicking of the OAuth workflow to verify the current user can login to the GitLab instance and the application id is correct.+ // 2. If step 1 succeeds, we will get a code, we use this code together with the secret to exchange for the access token. (see eventListener)+ if (state.currentStep == OAUTH_INFO_STEP && newStep > oldStep) {+ const newWindow = openWindowForOAuth(+ `${state.config.instanceURL}/oauth/authorize`,+ state.config.applicationId+ );+ if (newWindow) {+ state.oauthResultCallback = (success: boolean) => {+ if (success) {+ state.currentStep = newStep;+ allowChangeCallback();+ store.dispatch("notification/pushNotification", {+ module: "bytebase",+ style: "SUCCESS",+ title: "Verified OAuth info is correct",+ });+ } else {+ var description = "";+ if (state.config.type == "GITLAB_SELF_HOST") {+ // If application id mismatches, the OAuth workflow will stop early.+ // So the only possibility to reach here is we have a matching application id, while+ // we failed to exchange a token, and it's likely we are requesting with a wrong secret.+ description =+ "Please make sure Secret matches the one from your GitLab instance Application.";+ }+ store.dispatch("notification/pushNotification", {+ module: "bytebase",+ style: "CRITICAL",+ title: "Failed to setup OAuth",+ description: description,+ });+ }+ };+ window.addEventListener(OAuthWindowEvent, eventListener, false);}+ } else {+ state.currentStep = newStep;+ allowChangeCallback();}+ };++ const tryFinishSetup = (allowChangeCallback: () => void) => {const vcsCreate: VCSCreate = {creatorId: currentUser.value.id,...state.config,};- store.dispatch("vcs/createVCS", vcsCreate);+ store.dispatch("vcs/createVCS", vcsCreate).then((vcs: VCS) => {+ allowChangeCallback();+ router.push({+ name: "setting.workspace.version-control",+ });+ store.dispatch("notification/pushNotification", {+ module: "bytebase",+ style: "SUCCESS",+ title: `Successfully added Git provider '${vcs.name}'`,+ });+ });};const cancelSetup = () => {@@ -121,8 +214,9 @@ export default {state,allowNext,attentionText,- selectStep,- finishSetup,+ showAttention,+ tryChangeStep,+ tryFinishSetup,cancelSetup,};},diff --git a/frontend/src/store/modules/gitlab.ts b/frontend/src/store/modules/gitlab.tsindex 0a938374c7..c37be3b78f 100644--- a/frontend/src/store/modules/gitlab.ts+++ b/frontend/src/store/modules/gitlab.ts@@ -1,5 +1,5 @@import axios from "axios";-import { ExternalRepository, VCS } from "../../types";+import { ExternalRepository, VCS, OAuthConfig } from "../../types";const GITLAB_API_PATH = "api/v4";const GITLAB_WEBHOOK_PATH = "hook/gitlab";@@ -18,15 +18,21 @@ function convertGitLabProject(project: any): ExternalRepository {const actions = {async exchangeToken({}: any,- { vcs, code, redirectURL }: { vcs: VCS; code: string; redirectURL: string }+ {+ oAuthConfig,+ code,+ }: {+ oAuthConfig: OAuthConfig;+ code: string;+ }): Promise<string> {console.log("req",- `${vcs.instanceURL}/oauth/token?client_id=${vcs.applicationId}&client_secret=${vcs.secret}&code=${code}&redirect_uri=${redirectURL}&grant_type=authorization_code`+ `${oAuthConfig.endpoint}?client_id=${oAuthConfig.applicationId}&client_secret=${oAuthConfig.secret}&code=${code}&redirect_uri=${oAuthConfig.redirectURL}&grant_type=authorization_code`);const data = (await axios.post(- `${vcs.instanceURL}/oauth/token?client_id=${vcs.applicationId}&client_secret=${vcs.secret}&code=${code}&redirect_uri=${redirectURL}&grant_type=authorization_code`+ `${oAuthConfig.endpoint}?client_id=${oAuthConfig.applicationId}&client_secret=${oAuthConfig.secret}&code=${code}&redirect_uri=${oAuthConfig.redirectURL}&grant_type=authorization_code`)).data;return data.access_token;diff --git a/frontend/src/types/oauth.ts b/frontend/src/types/oauth.tsindex a245da3ec5..08bb9131db 100644--- a/frontend/src/types/oauth.ts+++ b/frontend/src/types/oauth.ts@@ -1,5 +1,11 @@import { randomString } from "../utils";-import { VCS } from "./vcs";++export type OAuthConfig = {+ endpoint: string;+ applicationId: string;+ secret: string;+ redirectURL: string;+};export const OAuthStateSessionKey = "oauthstate";@@ -13,14 +19,15 @@ export function redirectURL(): string {return `${window.location.origin}/oauth/callback`;}-export function openWindowForVCSOAuth(vcs: VCS): Window | null {+export function openWindowForOAuth(+ endpoint: string,+ applicationId: string+): Window | null {const stateQueryParameter = randomString(40);sessionStorage.setItem(OAuthStateSessionKey, stateQueryParameter);return window.open(- `${vcs.instanceURL}/oauth/authorize?client_id=${- vcs.applicationId- }&redirect_uri=${encodeURIComponent(+ `${endpoint}?client_id=${applicationId}&redirect_uri=${encodeURIComponent(redirectURL())}&state=${stateQueryParameter}&response_type=code&scope=api`,"oauth",