Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat: implement add GitHub as Git provider (#998)
Joe Chen8d4945f63a4e
diff --git a/frontend/src/assets/github_admin_settings.png b/frontend/src/assets/github_admin_settings.pngnew file mode 100644index 0000000000..dab635e7feBinary files /dev/null and b/frontend/src/assets/github_admin_settings.png differdiff --git a/frontend/src/components/VCSCard.vue b/frontend/src/components/VCSCard.vueindex 4f035e9a41..dba1a5ee8e 100644--- a/frontend/src/components/VCSCard.vue+++ b/frontend/src/components/VCSCard.vue@@ -7,6 +7,9 @@<template v-if="vcs.type.startsWith('GITLAB')"><img class="h-6 w-auto" src="../assets/gitlab-logo.svg" /></template>+ <template v-if="vcs.type.startsWith('GITHUB')">+ <img class="h-6 w-auto" src="../assets/github-logo.svg" />+ </template><h3 class="text-lg leading-6 font-medium text-main">{{ vcs.name }}</h3>diff --git a/frontend/src/components/VCSProviderBasicInfoPanel.vue b/frontend/src/components/VCSProviderBasicInfoPanel.vueindex 72004094d3..58142f3ed4 100644--- a/frontend/src/components/VCSProviderBasicInfoPanel.vue+++ b/frontend/src/components/VCSProviderBasicInfoPanel.vue@@ -12,6 +12,7 @@type="radio"class="btn"value="GITLAB_SELF_HOST"+ @change="changeType()"/><img class="h-6 w-auto" src="../assets/gitlab-logo.svg" /><label class="whitespace-nowrap"@@ -20,6 +21,19 @@}}</label></div>+ <div v-if="isDev" class="radio space-x-2">+ <input+ v-model="config.type"+ name="GitHub.com"+ tabindex="-1"+ type="radio"+ class="btn"+ value="GITHUB_COM"+ @change="changeType()"+ />+ <img class="h-6 w-auto" src="../assets/github-logo.svg" />+ <label class="whitespace-nowrap">GitHub.com</label>+ </div></div><div class="mt-4 relative"><div class="relative flex justify-start">@@ -41,7 +55,10 @@</div><label class="whitespace-nowrap">GitHub Enterprise </label></div>- <div class="flex flex-row space-x-2 items-center text-control">+ <div+ v-if="!isDev"+ class="flex flex-row space-x-2 items-center text-control"+ ><div class="h-5 w-5"><img src="../assets/github-logo.svg" /></div>@@ -60,8 +77,9 @@</p><BBTextFieldclass="mt-2 w-full"- :placeholder="'https://gitlab.example.com'":value="config.instanceUrl"+ :placeholder="instanceUrlPlaceholder"+ :disabled="instanceUrlDisabled"@input="changeUrl($event.target.value)"/><p v-if="state.showUrlError" class="mt-2 text-sm text-error">@@ -93,7 +111,7 @@import { computed, onUnmounted, PropType, reactive } from "vue";import isEmpty from "lodash-es/isEmpty";import { TEXT_VALIDATION_DELAY, VCSConfig } from "../types";-import { isUrl } from "../utils";+import { isUrl, isDev } from "../utils";import { useI18n } from "vue-i18n";interface LocalState {@@ -125,6 +143,8 @@ export default {const namePlaceholder = computed((): string => {if (props.config.type == "GITLAB_SELF_HOST") {return t("version-control.setting.add-git-provider.gitlab-self-host");+ } else if (props.config.type == "GITHUB_COM") {+ return "GitHub.com";}return "";});@@ -134,10 +154,28 @@ export default {return t("version-control.setting.add-git-provider.basic-info.gitlab-instance-url");+ } else if (props.config.type == "GITHUB_COM") {+ return t(+ "version-control.setting.add-git-provider.basic-info.github-instance-url"+ );}return "";});+ const instanceUrlPlaceholder = computed((): string => {+ if (props.config.type == "GITLAB_SELF_HOST") {+ return "https://gitlab.example.com";+ } else if (props.config.type == "GITHUB_COM") {+ return "https://github.com";+ }+ return "";+ });++ // github.com instance url is always https://github.com+ const instanceUrlDisabled = computed((): boolean => {+ return props.config.type == "GITHUB_COM";+ });+const changeUrl = (value: string) => {props.config.instanceUrl = value;@@ -163,7 +201,28 @@ export default {}};- return { state, namePlaceholder, instanceUrlLabel, changeUrl };+ // FIXME: Unexpected mutation of "config" prop. Do we care?+ const changeType = () => {+ if (props.config.type == "GITLAB_SELF_HOST") {+ props.config.instanceUrl = "";+ props.config.name = t(+ "version-control.setting.add-git-provider.gitlab-self-host"+ );+ } else if (props.config.type == "GITHUB_COM") {+ props.config.instanceUrl = "https://github.com";+ props.config.name = "GitHub.com";+ }+ };++ return {+ state,+ namePlaceholder,+ instanceUrlLabel,+ instanceUrlPlaceholder,+ instanceUrlDisabled,+ changeUrl,+ changeType,+ };},};</script>diff --git a/frontend/src/components/VCSProviderConfirmPanel.vue b/frontend/src/components/VCSProviderConfirmPanel.vueindex b52534c574..7e923411df 100644--- a/frontend/src/components/VCSProviderConfirmPanel.vue+++ b/frontend/src/components/VCSProviderConfirmPanel.vue@@ -35,6 +35,13 @@}}</div></div>+ <div+ v-if="config.type == 'GITHUB_COM'"+ class="flex flex-row items-center space-x-2"+ >+ <img class="h-6 w-auto" src="../assets/github-logo.svg" />+ <div class="whitespace-nowrap">GitHub.com</div>+ </div></dd></div><div class="grid grid-cols-4 gap-4 px-4 py-2">diff --git a/frontend/src/components/VCSProviderOAuthPanel.vue b/frontend/src/components/VCSProviderOAuthPanel.vueindex 5c7ebe57e7..ca9378a347 100644--- a/frontend/src/components/VCSProviderOAuthPanel.vue+++ b/frontend/src/components/VCSProviderOAuthPanel.vue@@ -4,7 +4,14 @@<template v-if="config.type == 'GITLAB_SELF_HOST'">{{$t(- "version-control.setting.add-git-provider.oauth-info.register-oauth-application"+ "version-control.setting.add-git-provider.oauth-info.gitlab-register-oauth-application"+ )+ }}+ </template>+ <template v-if="config.type == 'GITHUB_COM'">+ {{+ $t(+ "version-control.setting.add-git-provider.oauth-info.github-register-oauth-application")}}</template>@@ -15,7 +22,7 @@1.{{$t(- "version-control.setting.add-git-provider.oauth-info.login-as-admin"+ "version-control.setting.add-git-provider.oauth-info.gitlab-login-as-admin")}}<img class="w-auto" src="../assets/gitlab_admin_area.png" />@@ -24,7 +31,7 @@2.{{$t(- "version-control.setting.add-git-provider.oauth-info.visit-admin-page"+ "version-control.setting.add-git-provider.oauth-info.gitlab-visit-admin-page")}}<a@@ -95,7 +102,69 @@4.{{$t(- "version-control.setting.add-git-provider.oauth-info.paste-oauth-info"+ "version-control.setting.add-git-provider.oauth-info.gitlab-paste-oauth-info"+ )+ }}+ </li>+ </template>+ <template v-if="config.type == 'GITHUB_COM'">+ <li>+ 1.+ {{+ $t(+ "version-control.setting.add-git-provider.oauth-info.github-login-as-admin"+ )+ }}+ <img class="w-auto" src="../assets/github_admin_settings.png" />+ </li>+ <li>+ 2.+ {{+ $t(+ "version-control.setting.add-git-provider.oauth-info.github-visit-admin-page"+ )+ }}+ </li>+ <li>+ 3.+ {{+ $t(+ "version-control.setting.add-git-provider.oauth-info.create-oauth-app"+ )+ }}+ <div class="m-4 flex justify-center">+ <dl+ class="divide-y divide-block-border border border-block-border shadow rounded-lg"+ >+ <div class="grid grid-cols-2 gap-4 px-4 py-2">+ <dt class="text-sm font-medium text-control-light text-right">+ Application name+ </dt>+ <dd class="text-sm text-main">Bytebase</dd>+ </div>+ <div class="grid grid-cols-2 gap-4 px-4 py-2 items-center">+ <dt class="text-sm font-medium text-control-light text-right">+ Authorization callback URL+ </dt>+ <dd class="text-sm text-main items-center flex">+ {{ redirectUrl() }}+ <button+ tabindex="-1"+ class="ml-1 text-sm font-medium text-control-light hover:bg-gray-100"+ @click.prevent="copyRedirectURI"+ >+ <heroicons-outline:clipboard class="w-6 h-6" />+ </button>+ </dd>+ </div>+ </dl>+ </div>+ </li>+ <li>+ 4.+ {{+ $t(+ "version-control.setting.add-git-provider.oauth-info.github-paste-oauth-info")}}</li>@@ -112,11 +181,7 @@@input="(e: any) => changeApplicationId(e.target.value)"/><p v-if="state.showApplicationIdError" class="mt-2 text-sm text-error">- {{- $t(- "version-control.setting.add-git-provider.oauth-info.application-id-error"- )- }}+ {{ applicationIdErrorDescription }}</p><div class="mt-4 textlabel">Secret <span class="text-red-600">*</span>@@ -128,9 +193,7 @@@input="(e: any) => changeSecret(e.target.value)"/><p v-if="state.showSecretError" class="mt-2 text-sm text-error">- {{- $t("version-control.setting.add-git-provider.oauth-info.secret-error")- }}+ {{ secretErrorDescription }}</p></div></div>@@ -152,6 +215,7 @@ import {VCSConfig,redirectUrl,} from "../types";+import { useI18n } from "vue-i18n";import { pushNotification } from "@/store";interface LocalState {@@ -170,13 +234,20 @@ export default defineComponent({},},setup(props) {+ const { t } = useI18n();const state = reactive<LocalState>({showApplicationIdError:!isEmpty(props.config.applicationId) &&- !isValidVCSApplicationIdOrSecret(props.config.applicationId),+ !isValidVCSApplicationIdOrSecret(+ props.config.type,+ props.config.applicationId+ ),showSecretError:!isEmpty(props.config.secret) &&- !isValidVCSApplicationIdOrSecret(props.config.secret),+ !isValidVCSApplicationIdOrSecret(+ props.config.type,+ props.config.secret+ ),});onUnmounted(() => {@@ -191,6 +262,8 @@ export default defineComponent({const createAdminApplicationUrl = computed((): string => {if (props.config.type == "GITLAB_SELF_HOST") {return `${props.config.instanceUrl}/admin/applications/new`;+ } else if (props.config.type == "GITHUB_COM") {+ return `https://github.com/settings/applications/new`;}return "";});@@ -214,7 +287,12 @@ export default defineComponent({}// If text becomes valid, we immediately clear the error.// otherwise, we delay TEXT_VALIDATION_DELAY to do the validation in case there is continous keystroke.- if (isValidVCSApplicationIdOrSecret(props.config.applicationId)) {+ if (+ isValidVCSApplicationIdOrSecret(+ props.config.type,+ props.config.applicationId+ )+ ) {state.showApplicationIdError = false;} else {state.applicationIdValidationTimer = setTimeout(() => {@@ -222,12 +300,19 @@ export default defineComponent({// Otherwise, we hide the error if input is either empty or valid.if (state.showApplicationIdError) {state.showApplicationIdError = !isValidVCSApplicationIdOrSecret(+ props.config.type,props.config.applicationId);} else {state.showApplicationIdError =- !isValidVCSApplicationIdOrSecret(props.config.applicationId) &&- !isValidVCSApplicationIdOrSecret(props.config.applicationId);+ !isValidVCSApplicationIdOrSecret(+ props.config.type,+ props.config.applicationId+ ) &&+ !isValidVCSApplicationIdOrSecret(+ props.config.type,+ props.config.applicationId+ );}}, TEXT_VALIDATION_DELAY);}@@ -242,7 +327,9 @@ export default defineComponent({}// If text becomes valid, we immediately clear the error.// otherwise, we delay TEXT_VALIDATION_DELAY to do the validation in case there is continous keystroke.- if (isValidVCSApplicationIdOrSecret(props.config.secret)) {+ if (+ isValidVCSApplicationIdOrSecret(props.config.type, props.config.secret)+ ) {state.showSecretError = false;} else {state.secretValidationTimer = setTimeout(() => {@@ -250,17 +337,47 @@ export default defineComponent({// Otherwise, we hide the error if input is either empty or valid.if (state.showSecretError) {state.showSecretError = !isValidVCSApplicationIdOrSecret(+ props.config.type,props.config.secret);} else {state.showSecretError =!isEmpty(props.config.secret) &&- !isValidVCSApplicationIdOrSecret(props.config.secret);+ !isValidVCSApplicationIdOrSecret(+ props.config.type,+ props.config.secret+ );}}, TEXT_VALIDATION_DELAY);}};+ const applicationIdErrorDescription = computed((): string => {+ if (props.config.type == "GITLAB_SELF_HOST") {+ return t(+ "version-control.setting.add-git-provider.oauth-info.gitlab-application-id-error"+ );+ } else if (props.config.type == "GITHUB_COM") {+ return t(+ "version-control.setting.add-git-provider.oauth-info.github-application-id-error"+ );+ }+ return "";+ });++ const secretErrorDescription = computed((): string => {+ if (props.config.type == "GITLAB_SELF_HOST") {+ return t(+ "version-control.setting.add-git-provider.oauth-info.gitlab-secret-error"+ );+ } else if (props.config.type == "GITHUB_COM") {+ return t(+ "version-control.setting.add-git-provider.oauth-info.github-secret-error"+ );+ }+ return "";+ });+return {redirectUrl,state,@@ -268,6 +385,8 @@ export default defineComponent({copyRedirectURI,changeApplicationId,changeSecret,+ applicationIdErrorDescription,+ secretErrorDescription,};},});diff --git a/frontend/src/components/VCSSetupWizard.vue b/frontend/src/components/VCSSetupWizard.vueindex a9f510bdb5..8dc9cff0c2 100644--- a/frontend/src/components/VCSSetupWizard.vue+++ b/frontend/src/components/VCSSetupWizard.vue@@ -102,7 +102,10 @@ export default defineComponent({const eventListener = (event: Event) => {const payload = (event as CustomEvent).detail as OAuthWindowEventPayload;if (isEmpty(payload.error)) {- if (state.config.type == "GITLAB_SELF_HOST") {+ if (+ state.config.type == "GITLAB_SELF_HOST" ||+ state.config.type == "GITHUB_COM"+ ) {useOAuthStore().exchangeVCSToken({vcsType: state.config.type,@@ -128,8 +131,14 @@ export default defineComponent({return isUrl(state.config.instanceUrl);} else if (state.currentStep == OAUTH_INFO_STEP) {return (- isValidVCSApplicationIdOrSecret(state.config.applicationId) &&- isValidVCSApplicationIdOrSecret(state.config.secret)+ isValidVCSApplicationIdOrSecret(+ state.config.type,+ state.config.applicationId+ ) &&+ isValidVCSApplicationIdOrSecret(+ state.config.type,+ state.config.secret+ ));}return true;@@ -140,6 +149,10 @@ export default defineComponent({return t("version-control.setting.add-git-provider.gitlab-self-host-admin-requirement");+ } else if (state.config.type == "GITHUB_COM") {+ return t(+ "version-control.setting.add-git-provider.github-com-admin-requirement"+ );}return "";});@@ -158,8 +171,12 @@ export default defineComponent({// 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) {+ let authorizeUrl = `${state.config.instanceUrl}/oauth/authorize`;+ if (state.config.type == "GITHUB_COM") {+ authorizeUrl = `https://github.com/login/oauth/authorize`;+ }const newWindow = openWindowForOAuth(- `${state.config.instanceUrl}/oauth/authorize`,+ authorizeUrl,state.config.applicationId,"bb.oauth.register-vcs");diff --git a/frontend/src/locales/en.yml b/frontend/src/locales/en.ymlindex 73c1c1f684..dd11974017 100644--- a/frontend/src/locales/en.yml+++ b/frontend/src/locales/en.yml@@ -1070,6 +1070,12 @@ version-control:Bytebase as a GitLab instance-wide OAuth application, then provide youthat Application ID and Secret to fill at the 'OAuth application info'step.+ github-com-admin-requirement: >-+ You need to be an admin of your chosen GitHub organization to configure+ this. Otherwise, you need to ask your GitHub organization admin to register+ Bytebase as a GitHub organization-wide OAuth application, then provide you+ that Application ID and Secret to fill at the 'OAuth application info'+ step.ouath-info-correct: Verified OAuth info is correctcheck-oauth-info-match: >-Please make sure Secret matches the one from your GitLab instance@@ -1083,6 +1089,7 @@ version-control:gitlab-instance-url-label: >-The VCS instance URL. Make sure this instance and Bytebase are networkreachable from each other.+ github-instance-url: GitHub instance URLinstance-url-error: Instance URL must begin with https:// or http://display-name: Display namedisplay-name-label: >-@@ -1090,32 +1097,48 @@ version-control:using the same Git provider.oauth-info:self: OAuth application info- register-oauth-application: Register Bytebase as a GitLab instance-wide OAuth application.- login-as-admin: >-+ gitlab-register-oauth-application: Register Bytebase as a GitLab instance-wide OAuth application.+ gitlab-login-as-admin: >-Login as an Admin user to the GitLab instance. The account must be anAdmin of the entire GitLab instance (it has a wrench icon on the topbar).- visit-admin-page: >-+ gitlab-visit-admin-page: >-Go to the Admin page by clicking the wrench icon, then navigate to"Applications" section and click "New application" button.- direct-link: Direct link- create-oauth-app: Create your Bytebase OAuth application with the following info.- paste-oauth-info: >-+ gitlab-paste-oauth-info: >-Paste the Application ID and Secret from that just created applicationinto fields below.- application-id-error: Application ID must be a 64-character alphanumeric string- secret-error: Secret must be a 64-character alphanumeric string+ github-register-oauth-application: Register Bytebase as a GitHub organization-wide OAuth application.+ github-login-as-admin: >-+ Login as an organization admin user to the GitHub.com. The account must be an+ organization admin of the GitHub organization (able to access the organiztion Settings page).+ github-visit-admin-page: >-+ Go to the Settings page, then navigate to "Developer settings > OAuth Apps" section+ and click "Register an application" button.+ github-paste-oauth-info: >-+ Paste the Client ID and Client secret from that just created application+ into fields below.+ direct-link: Direct link+ create-oauth-app: Create your Bytebase OAuth application with the following info.+ gitlab-application-id-error: Application ID must be a 64-character alphanumeric string+ gitlab-secret-error: Secret must be a 64-character alphanumeric string+ github-application-id-error: Application ID must be a 20-character alphanumeric string+ github-secret-error: Secret must be a 40-character alphanumeric stringconfirm:confirm-info: Confirm the infoconfirm-description: >-After creation, this Git provider can be chosen under the projectdashboard "Version Control" tab by the project owner.git-provider:- application-id-label: >-+ gitlab-application-id-label: >-Application ID for the registered GitLab instance-wide OAuthapplication.view-in-gitlab: View in GitLabsecret-label-gitlab: Secret for the registered GitLab instance-wide OAuth application.+ github-application-id-label: >-+ Client ID for the registered GitHub organization-wide OAuth+ application.+ secret-label-github: Client secret for the registered GitHub organization-wide OAuth application.delete: To delete this provider, unlink all repositories first.archive:archived: Archiveddiff --git a/frontend/src/locales/zh-CN.yml b/frontend/src/locales/zh-CN.ymlindex 795644034d..6a711b7d57 100644--- a/frontend/src/locales/zh-CN.yml+++ b/frontend/src/locales/zh-CN.yml@@ -938,6 +938,8 @@ version-control:gitlab-self-host-admin-requirement: >-您必须是 GitLab 实例的管理员才能进行该配置。否则您需要让您的 GitLab 实例管理员把 Bytebase 先注册为 GitLab整个实例级别的 OAuth 应用,之后再让对方提供给您注册完成后的应用 ID 以及 Secret,以让您在「OAuth 应用信息」步骤进行填写。+ github-com-admin-requirement: >-+ 您必须是 GitHub 组织的管理员才能进行该配置。否则您需要让您的 GitHub 组织管理员把 Bytebase 先注册为组织级别的 OAuth 应用,之后再让对方提供给您注册完成后的应用 ID 以及 Secret,以让您在「OAuth 应用信息」步骤进行填写。ouath-info-correct: OAuth 信息验证成功check-oauth-info-match: 请确认 Secret 和注册在 GitLab 实例上的应用信息匹配。add-success: 成功添加了 Git 提供方「{vcs}」@@ -947,26 +949,38 @@ version-control:self: 基本信息gitlab-instance-url: GitLab 实例 URLgitlab-instance-url-label: VCS 实例 URL。请确认这个实例和 Bytebase 之间网络是互通的。+ github-instance-url: GitHub 实例 URLinstance-url-error: 实例 URL 必须以 https:// or http:// 开头display-name: 展示名称display-name-label: 一个可选的展示名称用以区分不同的 Git 供应方。oauth-info:self: OAuth 应用信息- register-oauth-application: 注册 Bytebase 为一个 GitLab 实例级别 (instance-wide) 的 OAuth 应用。- login-as-admin: 以管理员身份登录 GitLab 实例。这个账号必须是整个 GitLab 实例的管理员 (会看到小扳手在顶栏)。- visit-admin-page: 通过点击小扳手访问管理员界面,然后导航到「应用」分区,再点击「创建应用」。+ gitlab-register-oauth-application: 注册 Bytebase 为一个 GitLab 实例级别 (instance-wide) 的 OAuth 应用。+ gitlab-login-as-admin: 以管理员身份登录 GitLab 实例。这个账号必须是整个 GitLab 实例的管理员 (会看到小扳手在顶栏)。+ gitlab-visit-admin-page: 通过点击小扳手访问管理员界面,然后导航到「应用」分区,再点击「创建应用」。+ gitlab-paste-oauth-info: 从刚创建好的应用上粘贴它的应用 ID 和 Secret 到下面的字段。+ github-register-oauth-application: 注册 Bytebase 为一个 GitHub 组织级别 (organization-wide) 的 OAuth 应用。+ github-login-as-admin: >-+ 以组织管理员身份登录 GitHub.com。这个账号必须是 GitHub 组织的管理员 (能够进入组织 Settings 页面)。+ github-visit-admin-page: >-+ 进入组织 Settings 页面,然后导航到「Developer settings > OAuth Apps」分区,再点击「Register an application」。+ github-paste-oauth-info: >-+ 从刚创建好的应用上粘贴它的 Client ID 和 Client secret 到下面的字段。direct-link: 直达链接create-oauth-app: 使用如下信息来创建您的 Bytebase OAuth 应用。- paste-oauth-info: 从刚创建好的应用上粘贴他的应用 ID 和 Secret 到下面的字段。- application-id-error: 应用 ID 必须是 64 个字母长度- secret-error: Secret 必须是 64 个字母长度+ gitlab-application-id-error: 应用 ID 必须是 64 个字母长度+ gitlab-secret-error: Secret 必须是 64 个字母长度+ github-application-id-error: 应用 ID 必须是 20 个字母长度+ github-secret-error: Secret 必须是 40 个字母长度confirm:confirm-info: 确认信息confirm-description: 创建完成后,这个 Git 供应方将出现在项目面板「版本控制」Tab 下,可以被项目所有者选中。git-provider:- application-id-label: 注册为 GitLab 实例级 OAuth 应用的应用 ID。+ gitlab-application-id-label: 注册为 GitLab 实例级 OAuth 应用的应用 ID。view-in-gitlab: 查看 GitLabsecret-label-gitlab: 注册为 GitLab 实例级 OAuth 应用的 Secret。+ github-application-id-label: 注册为 GitHub 组织级别 OAuth 应用的 Client ID。+ secret-label-github: 注册为 GitHub 组织级别 OAuth 应用的 Client secret。delete: 删除这个提供方前,需要先解除所有仓库的关联。archive:archived: 已归档diff --git a/frontend/src/types/oauth.ts b/frontend/src/types/oauth.tsindex d1d66b6afd..52a6742264 100644--- a/frontend/src/types/oauth.ts+++ b/frontend/src/types/oauth.ts@@ -45,7 +45,7 @@ export function openWindowForOAuth(return window.open(`${endpoint}?client_id=${applicationId}&redirect_uri=${encodeURIComponent(redirectUrl()- )}&state=${stateQueryParameter}&response_type=code&scope=api`,+ )}&state=${stateQueryParameter}&response_type=code&scope=api,repo`,"oauth","location=yes,left=200,top=200,height=640,width=480,scrollbars=yes,status=yes");diff --git a/frontend/src/types/vcs.ts b/frontend/src/types/vcs.tsindex ef5846336e..2977d7bfac 100644--- a/frontend/src/types/vcs.ts+++ b/frontend/src/types/vcs.ts@@ -1,7 +1,7 @@import { VCSId } from "./id";import { Principal } from "./principal";-export type VCSType = "GITLAB_SELF_HOST";+export type VCSType = "GITLAB_SELF_HOST" | "GITHUB_COM";export interface VCSConfig {type: VCSType;@@ -70,6 +70,14 @@ export type VCSPushEvent = {fileCommit: VCSFileCommit;};-export function isValidVCSApplicationIdOrSecret(str: string): boolean {- return /^[a-zA-Z0-9_]{64}$/.test(str);+export function isValidVCSApplicationIdOrSecret(+ vcsType: VCSType,+ str: string+): boolean {+ if (vcsType == "GITLAB_SELF_HOST") {+ return /^[a-zA-Z0-9_]{64}$/.test(str);+ } else if (vcsType == "GITHUB_COM") {+ return /^[a-zA-Z0-9_]{20}$|^[a-zA-Z0-9_]{40}$/.test(str);+ }+ return false;}diff --git a/frontend/src/views/SettingWorkspaceVCSDetail.vue b/frontend/src/views/SettingWorkspaceVCSDetail.vueindex 60ec597f5b..2bc349dc66 100644--- a/frontend/src/views/SettingWorkspaceVCSDetail.vue+++ b/frontend/src/views/SettingWorkspaceVCSDetail.vue@@ -14,6 +14,13 @@</div><img class="h-6 w-auto" src="../assets/gitlab-logo.svg" /></div>+ <div+ v-if="vcs.type == 'GITHUB_COM'"+ class="flex flex-row items-center space-x-2"+ >+ <div class="textlabel whitespace-nowrap">GitHub.com</div>+ <img class="h-6 w-auto" src="../assets/github-logo.svg" />+ </div></div><div>@@ -58,11 +65,22 @@</label><p class="mt-1 textinfolabel"><template v-if="vcs.type == 'GITLAB_SELF_HOST'">- {{ $t("version-control.setting.git-provider.application-id-label") }}+ {{+ $t(+ "version-control.setting.git-provider.gitlab-application-id-label"+ )+ }}<a :href="adminApplicationUrl" target="_blank" class="normal-link">{{$t("version-control.setting.git-provider.view-in-gitlab")}}</a></template>+ <template v-if="vcs.type == 'GITHUB_COM'">+ {{+ $t(+ "version-control.setting.git-provider.github-application-id-label"+ )+ }}+ </template></p><inputid="applicationid"@@ -79,6 +97,9 @@<template v-if="vcs.type == 'GITLAB_SELF_HOST'">{{ $t("version-control.setting.git-provider.secret-label-gitlab") }}</template>+ <template v-if="vcs.type == 'GITHUB_COM'">+ {{ $t("version-control.setting.git-provider.secret-label-github") }}+ </template></p><inputid="secret"@@ -205,7 +226,10 @@ export default defineComponent({const eventListener = (event: Event) => {const payload = (event as CustomEvent).detail as OAuthWindowEventPayload;if (isEmpty(payload.error)) {- if (vcs.value.type == "GITLAB_SELF_HOST") {+ if (+ vcs.value.type == "GITLAB_SELF_HOST" ||+ vcs.value.type == "GITHUB_COM"+ ) {useOAuthStore().exchangeVCSTokenWithID({vcsId: idFromSlug(props.vcsSlug),@@ -253,8 +277,12 @@ export default defineComponent({state.applicationId != vcs.value.applicationId ||!isEmpty(state.secret)) {+ let authorizeUrl = `${vcs.value.instanceUrl}/oauth/authorize`;+ if (vcs.value.type == "GITHUB_COM") {+ authorizeUrl = `https://github.com/login/oauth/authorize`;+ }const newWindow = openWindowForOAuth(- `${vcs.value.instanceUrl}/oauth/authorize`,+ authorizeUrl,vcs.value.applicationId,"bb.oauth.register-vcs");@@ -284,13 +312,16 @@ export default defineComponent({});});} else {+ // If the 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.var description = "";if (vcs.value.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.";+ } else if (vcs.value.type == "GITHUB_COM") {+ description =+ "Please make sure Client secret matches the one from your GitHub.com Application.";}pushNotification({module: "bytebase",diff --git a/plugin/vcs/github/github.go b/plugin/vcs/github/github.goindex 817ef8cf3b..9f67757a8d 100644--- a/plugin/vcs/github/github.go+++ b/plugin/vcs/github/github.go@@ -7,6 +7,7 @@ import ("fmt""io""net/http"+ "net/url""strconv""strings"@@ -116,9 +117,61 @@ func (p *Provider) FetchRepositoryActiveMemberList(ctx context.Context, oauthCtxreturn nil, errors.New("not implemented yet") // TODO: https://github.com/bytebase/bytebase/issues/928}-// ExchangeOAuthToken exchange oauth content with the provided authentication code.-func (p *Provider) ExchangeOAuthToken(ctx context.Context, instanceURL string, oauthExchange *common.OAuthExchange) (*vcs.OAuthToken, error) {- return nil, errors.New("not implemented yet")+// oauthResponse is a GitHub OAuth response.+type oauthResponse struct {+ AccessToken string `json:"access_token" `+ Error string `json:"error,omitempty"`+ ErrorDescription string `json:"error_description,omitempty"`+}++// toVCSOAuthToken converts the response to *vcs.OAuthToken.+func (o oauthResponse) toVCSOAuthToken() *vcs.OAuthToken {+ oauthToken := &vcs.OAuthToken{+ AccessToken: o.AccessToken,+ // GitHub OAuth token never expires+ }+ return oauthToken+}++// ExchangeOAuthToken exchanges OAuth content with the provided authorization code.+func (p *Provider) ExchangeOAuthToken(ctx context.Context, _ string, oauthExchange *common.OAuthExchange) (*vcs.OAuthToken, error) {+ urlParams := &url.Values{}+ urlParams.Set("client_id", oauthExchange.ClientID)+ urlParams.Set("client_secret", oauthExchange.ClientSecret)+ urlParams.Set("code", oauthExchange.Code)+ urlParams.Set("redirect_uri", oauthExchange.RedirectURL)+ url := fmt.Sprintf("https://github.com/login/oauth/access_token?%s", urlParams.Encode())++ req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, nil)+ if err != nil {+ urlParams.Set("client_secret", "**redacted**")+ redactedURL := fmt.Sprintf("https://github.com/login/oauth/access_token?%s", urlParams.Encode())+ return nil, errors.Wrapf(err, "construct POST %s", redactedURL)+ }++ // GitHub returns URL-encoded parameters as the response format by default,+ // we need to ask for a JSON response explicitly.+ req.Header.Set("Accept", "application/json")++ resp, err := p.client.Do(req)+ if err != nil {+ return nil, fmt.Errorf("failed to exchange OAuth token, error: %v", err)+ }++ body, err := io.ReadAll(resp.Body)+ if err != nil {+ return nil, fmt.Errorf("failed to read OAuth response body, code %v, error: %v", resp.StatusCode, err)+ }+ defer func() { _ = resp.Body.Close() }()++ oauthResp := new(oauthResponse)+ if err := json.Unmarshal(body, oauthResp); err != nil {+ return nil, fmt.Errorf("failed to unmarshal OAuth response body, code %v, error: %v", resp.StatusCode, err)+ }+ if oauthResp.Error != "" {+ return nil, fmt.Errorf("failed to exchange OAuth token, error: %v, error_description: %v", oauthResp.Error, oauthResp.ErrorDescription)+ }+ return oauthResp.toVCSOAuthToken(), nil}// FetchRepositoryList fetched all repositories in which the authenticated userdiff --git a/plugin/vcs/github/github_test.go b/plugin/vcs/github/github_test.goindex a3e0ab1578..c2a6c10af2 100644--- a/plugin/vcs/github/github_test.go+++ b/plugin/vcs/github/github_test.go@@ -91,6 +91,49 @@ func TestProvider_FetchUserInfo(t *testing.T) {assert.Equal(t, want, got)}+func TestProvider_ExchangeOAuthToken(t *testing.T) {+ p := newProvider(+ vcs.ProviderConfig{+ Client: &http.Client{+ Transport: &common.MockRoundTripper{+ MockRoundTrip: func(r *http.Request) (*http.Response, error) {+ assert.Equal(t, "/login/oauth/access_token", r.URL.Path)+ assert.Equal(t, "client_id=test_client_id&client_secret=test_client_secret&code=test_code&redirect_uri=http%3A%2F%2Flocalhost%3A3000", r.URL.RawQuery)+ assert.Equal(t, "application/json", r.Header.Get("Accept"))+ return &http.Response{+ StatusCode: http.StatusOK,+ // Example response taken from https://docs.github.com/en/developers/apps/building-oauth-apps/authorizing-oauth-apps#response+ Body: io.NopCloser(strings.NewReader(`+{+ "access_token":"gho_16C7e42F292c6912E7710c838347Ae178B4a",+ "scope":"repo,gist",+ "token_type":"bearer"+}+`)),+ }, nil+ },+ },+ },+ },+ )++ ctx := context.Background()+ got, err := p.ExchangeOAuthToken(ctx, "",+ &common.OAuthExchange{+ ClientID: "test_client_id",+ ClientSecret: "test_client_secret",+ Code: "test_code",+ RedirectURL: "http://localhost:3000",+ },+ )+ require.NoError(t, err)++ want := &vcs.OAuthToken{+ AccessToken: "gho_16C7e42F292c6912E7710c838347Ae178B4a",+ }+ assert.Equal(t, want, got)+}+func TestOAuth_RefreshToken(t *testing.T) {ctx := context.Background()client := &http.Client{diff --git a/plugin/vcs/gitlab/gitlab.go b/plugin/vcs/gitlab/gitlab.goindex 5fa13986f5..3991b6032c 100644--- a/plugin/vcs/gitlab/gitlab.go+++ b/plugin/vcs/gitlab/gitlab.go@@ -214,7 +214,7 @@ func (p *Provider) APIURL(instanceURL string) string {return fmt.Sprintf("%s/%s", instanceURL, apiPath)}-// gitlab oauth response+// oauthResponse is a GitLab OAuth response.type oauthResponse struct {AccessToken string `json:"access_token" `RefreshToken string `json:"refresh_token"`@@ -225,7 +225,7 @@ type oauthResponse struct {ErrorDescription string `json:"error_description,omitempty"`}-// convert to *vcs.OAuthToken+// toVCSOAuthToken converts the response to *vcs.OAuthToken.func (o oauthResponse) toVCSOAuthToken() *vcs.OAuthToken {oauthToken := &vcs.OAuthToken{AccessToken: o.AccessToken,@@ -242,7 +242,7 @@ func (o oauthResponse) toVCSOAuthToken() *vcs.OAuthToken {return oauthToken}-// ExchangeOAuthToken exchange oauth content with the provided authentication code.+// ExchangeOAuthToken exchanges OAuth content with the provided authorization code.func (p *Provider) ExchangeOAuthToken(ctx context.Context, instanceURL string, oauthExchange *common.OAuthExchange) (*vcs.OAuthToken, error) {urlParams := &url.Values{}urlParams.Set("client_id", oauthExchange.ClientID)@@ -258,25 +258,24 @@ func (p *Provider) ExchangeOAuthToken(ctx context.Context, instanceURL string, oredactedURL := fmt.Sprintf("%s/oauth/token?%s", instanceURL, urlParams.Encode())return nil, errors.Wrapf(err, "construct POST %s", redactedURL)}- req.Header.Set("Content-Type", "application/json")resp, err := p.client.Do(req)if err != nil {- return nil, fmt.Errorf("failed to exchange Oauth Token, error: %v", err)+ return nil, fmt.Errorf("failed to exchange OAuth token, error: %v", err)}body, err := io.ReadAll(resp.Body)if err != nil {- return nil, fmt.Errorf("failed to read oauth response body, code %v, error: %v", resp.StatusCode, err)+ return nil, fmt.Errorf("failed to read OAuth response body, code %v, error: %v", resp.StatusCode, err)}- defer resp.Body.Close()+ defer func() { _ = resp.Body.Close() }()oauthResp := new(oauthResponse)if err := json.Unmarshal(body, oauthResp); err != nil {- return nil, fmt.Errorf("failed to unmarshal oauth response body, code %v, error: %v", resp.StatusCode, err)+ return nil, fmt.Errorf("failed to unmarshal OAuth response body, code %v, error: %v", resp.StatusCode, err)}if oauthResp.Error != "" {- return nil, fmt.Errorf("failed to exchange Oauth Token, error: %v, error_description: %v", oauthResp.Error, oauthResp.ErrorDescription)+ return nil, fmt.Errorf("failed to exchange OAuth token, error: %v, error_description: %v", oauthResp.Error, oauthResp.ErrorDescription)}return oauthResp.toVCSOAuthToken(), nil}diff --git a/plugin/vcs/gitlab/gitlab_test.go b/plugin/vcs/gitlab/gitlab_test.goindex 0ab7bb9f98..5f8c41c534 100644--- a/plugin/vcs/gitlab/gitlab_test.go+++ b/plugin/vcs/gitlab/gitlab_test.go@@ -67,6 +67,54 @@ func TestProvider_FetchUserInfo(t *testing.T) {assert.Equal(t, want, got)}+func TestProvider_ExchangeOAuthToken(t *testing.T) {+ p := newProvider(+ vcs.ProviderConfig{+ Client: &http.Client{+ Transport: &common.MockRoundTripper{+ MockRoundTrip: func(r *http.Request) (*http.Response, error) {+ assert.Equal(t, "/oauth/token", r.URL.Path)+ assert.Equal(t, "client_id=test_client_id&client_secret=test_client_secret&code=test_code&grant_type=authorization_code&redirect_uri=http%3A%2F%2Flocalhost%3A3000", r.URL.RawQuery)+ return &http.Response{+ StatusCode: http.StatusOK,+ // Example response taken from https://docs.gitlab.com/ee/api/oauth2.html#authorization-code-flow+ Body: io.NopCloser(strings.NewReader(`+{+ "access_token": "de6780bc506a0446309bd9362820ba8aed28aa506c71eedbe1c5c4f9dd350e54",+ "token_type": "bearer",+ "expires_in": 7200,+ "refresh_token": "8257e65c97202ed1726cf9571600918f3bffb2544b26e00a61df9897668c33a1",+ "created_at": 1607635748+}+`)),+ }, nil+ },+ },+ },+ },+ )++ ctx := context.Background()+ got, err := p.ExchangeOAuthToken(ctx, "",+ &common.OAuthExchange{+ ClientID: "test_client_id",+ ClientSecret: "test_client_secret",+ Code: "test_code",+ RedirectURL: "http://localhost:3000",+ },+ )+ require.NoError(t, err)++ want := &vcs.OAuthToken{+ AccessToken: "de6780bc506a0446309bd9362820ba8aed28aa506c71eedbe1c5c4f9dd350e54",+ RefreshToken: "8257e65c97202ed1726cf9571600918f3bffb2544b26e00a61df9897668c33a1",+ ExpiresIn: 7200,+ CreatedAt: 1607635748,+ ExpiresTs: 1607642948,+ }+ assert.Equal(t, want, got)+}+func TestOAuth_RefreshToken(t *testing.T) {ctx := context.Background()client := &http.Client{diff --git a/server/oauth.go b/server/oauth.goindex 7a1a51e939..76fbb242a1 100644--- a/server/oauth.go+++ b/server/oauth.go@@ -10,6 +10,7 @@ import ("github.com/bytebase/bytebase/api""github.com/bytebase/bytebase/common"vcsPlugin "github.com/bytebase/bytebase/plugin/vcs"+ _ "github.com/bytebase/bytebase/plugin/vcs/github" // Import to call the init until it is imported from somewhere else)func (s *Server) registerOAuthRoutes(g *echo.Group) {diff --git a/server/vcs.go b/server/vcs.goindex 55f5615bf0..3417161672 100644--- a/server/vcs.go+++ b/server/vcs.go@@ -6,11 +6,12 @@ import ("strconv""strings"+ "github.com/google/jsonapi"+ "github.com/labstack/echo/v4"+"github.com/bytebase/bytebase/api""github.com/bytebase/bytebase/common""github.com/bytebase/bytebase/plugin/vcs"- "github.com/google/jsonapi"- "github.com/labstack/echo/v4")func (s *Server) registerVCSRoutes(g *echo.Group) {@@ -24,7 +25,7 @@ func (s *Server) registerVCSRoutes(g *echo.Group) {}// Trim ending "/"vcsCreate.InstanceURL = strings.TrimRight(vcsCreate.InstanceURL, "/")- vcsCreate.APIURL = vcs.Get(vcs.GitLabSelfHost, vcs.ProviderConfig{Logger: s.l}).APIURL(vcsCreate.InstanceURL)+ vcsCreate.APIURL = vcs.Get(vcsCreate.Type, vcs.ProviderConfig{Logger: s.l}).APIURL(vcsCreate.InstanceURL)vcs, err := s.store.CreateVCS(ctx, vcsCreate)if err != nil {