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: move oauth token exchange logic to the backend (#930)
Zilong Zhoucfe8f89956fa
diff --git a/api/auth.go b/api/auth.goindex ed8dfefc54..2dff82f1e8 100644--- a/api/auth.go+++ b/api/auth.go@@ -15,9 +15,13 @@ type AuthProvider struct {// GitlabLogin is the API message for logins via Gitlab.type GitlabLogin struct {- ID int `jsonapi:"attr,id"`- Name string `jsonapi:"attr,name"`- AccessToken string `jsonapi:"attr,accessToken"`+ // VCSID is the ID of the chosen VCS role provider.+ VCSID int `jsonapi:"attr,vcsId"`+ // Name is the user configured name of the role provider.+ Name string `jsonapi:"attr,name"`+ // Code is the authentication code granted by GitLab server,+ // we will use this code to exchange the OAuth token.+ Code string `jsonapi:"attr,code"`}// Login is the API message for logins.diff --git a/api/oauth.go b/api/oauth.gonew file mode 100644index 0000000000..865fa6a49d--- /dev/null+++ b/api/oauth.go@@ -0,0 +1,8 @@+package api++// OAuthToken is the API message for OAuthToken.+type OAuthToken struct {+ AccessToken string `jsonapi:"attr,accessToken" `+ RefreshToken string `jsonapi:"attr,refreshToken"`+ ExpiresTs int64 `jsonapi:"attr,expiresAt"`+}diff --git a/api/vcs.go b/api/vcs.goindex 44f41109d8..35fce11f10 100644--- a/api/vcs.go+++ b/api/vcs.go@@ -24,9 +24,8 @@ type VCS struct {InstanceURL string `jsonapi:"attr,instanceUrl"`APIURL string `jsonapi:"attr,apiUrl"`ApplicationID string `jsonapi:"attr,applicationId"`- // Secret will be used for OAuth on the client side when setting up project GitOps workflow.- // So it should be returned to the response.- Secret string `jsonapi:"attr,secret"`+ // For safety concerns, we will not return the secret, and all relevant logic is dealt in the backend.+ Secret string}// VCSCreate is the API message for creating a VCS.@@ -80,3 +79,11 @@ type VCSDelete struct {// Value is assigned from the jwt subject field passed by the client.DeleterID int}++// ExternalRepository is the API message for external repository+type ExternalRepository struct {+ ID int64 `jsonapi:"primary,id"`+ Name string `jsonapi:"attr,name"`+ FullPath string `jsonapi:"attr,fullPath"`+ WebURL string `jsonapi:"attr,webUrl"`+}diff --git a/common/oauth.go b/common/oauth.goindex 14c2c7208f..6d1cae8fc8 100644--- a/common/oauth.go+++ b/common/oauth.go@@ -11,3 +11,11 @@ type OauthContext struct {RefreshToken stringRefresher TokenRefresher}++// OAuthExchange encapsulated the exchange OAuth context.+type OAuthExchange struct {+ ClientID string+ ClientSecret string+ Code string+ RedirectURL string+}diff --git a/frontend/src/components/RepositorySelectionPanel.vue b/frontend/src/components/RepositorySelectionPanel.vueindex 959a72838e..ad48a2a2ce 100644--- a/frontend/src/components/RepositorySelectionPanel.vue+++ b/frontend/src/components/RepositorySelectionPanel.vue@@ -2,7 +2,7 @@<BBAttention :style="'WARN'" :description="attentionText" /><div class="mt-4 space-y-2"><div class="flex justify-between items-center">- <button class="btn-icon" @click.prevent="prepareRepositoryList">+ <button class="btn-icon" @click.prevent="refreshRepositoryList"><heroicons-outline:refresh class="w-6 h-6" /></button><BBTableSearch@@ -36,81 +36,97 @@</template><script lang="ts">+export default { name: "RepositorySelectionPanel" };+</script>++<script setup lang="ts">import { useStore } from "vuex";-import { reactive, computed, PropType, watchEffect } from "vue";-import { ExternalRepositoryInfo, ProjectRepositoryConfig } from "../types";+import { reactive, computed, onMounted } from "vue";+import {+ ExternalRepositoryInfo,+ OAuthToken,+ ProjectRepositoryConfig,+} from "../types";interface LocalState {repositoryList: ExternalRepositoryInfo[];searchText: string;}-export default {- name: "RepositorySelectionPanel",- props: {- config: {- required: true,- type: Object as PropType<ProjectRepositoryConfig>,- },- },- emits: ["next"],- setup(props, { emit }) {- const store = useStore();- const state = reactive<LocalState>({- repositoryList: [],- searchText: "",- });+const props = defineProps<{ config: ProjectRepositoryConfig }>();++const emit = defineEmits<{+ (event: "next"): void;+ (event: "set-token", payload: OAuthToken): void;+ (event: "set-repository", payload: ExternalRepositoryInfo): void;+}>();++const store = useStore();+const state = reactive<LocalState>({+ repositoryList: [],+ searchText: "",+});++onMounted(() => {+ prepareRepositoryList();+});- const prepareRepositoryList = () => {- if (props.config.vcs.type == "GITLAB_SELF_HOST") {+const prepareRepositoryList = () => {+ if (props.config.vcs.type == "GITLAB_SELF_HOST") {+ store+ .dispatch("oauth/exchangeVCSToken", {+ vcsId: props.config.vcs.id,+ code: props.config.code,+ })+ .then((token: OAuthToken) => {+ emit("set-token", token);store.dispatch("gitlab/fetchProjectList", {vcs: props.config.vcs,- token: props.config.token.accessToken,+ token: token,}).then((list) => {state.repositoryList = list;});- }- };-- watchEffect(prepareRepositoryList);+ });+ }+};- const repositoryList = computed(() => {- if (state.searchText == "") {- return state.repositoryList;- }- return state.repositoryList.filter(- (repository: ExternalRepositoryInfo) => {- return repository.fullPath.toLowerCase().includes(state.searchText);- }- );- });+const refreshRepositoryList = () => {+ if (props.config.vcs.type == "GITLAB_SELF_HOST") {+ store+ .dispatch("gitlab/fetchProjectList", {+ vcs: props.config.vcs,+ token: props.config.token,+ })+ .then((list) => {+ state.repositoryList = list;+ });+ }+};- const attentionText = computed((): string => {- if (props.config.vcs.type == "GITLAB_SELF_HOST") {- return "repository.select-repository-attention-gitlab";- }- return "";- });+const repositoryList = computed(() => {+ if (state.searchText == "") {+ return state.repositoryList;+ }+ return state.repositoryList.filter((repository: ExternalRepositoryInfo) => {+ return repository.fullPath.toLowerCase().includes(state.searchText);+ });+});- const selectRepository = (repository: ExternalRepositoryInfo) => {- props.config.repositoryInfo = repository;- emit("next");- };+const attentionText = computed((): string => {+ if (props.config.vcs.type == "GITLAB_SELF_HOST") {+ return "repository.select-repository-attention-gitlab";+ }+ return "";+});- const changeSearchText = (searchText: string) => {- state.searchText = searchText;- };+const selectRepository = (repository: ExternalRepositoryInfo) => {+ emit("set-repository", repository);+ emit("next");+};- return {- state,- selectRepository,- repositoryList,- attentionText,- changeSearchText,- prepareRepositoryList,- };- },+const changeSearchText = (searchText: string) => {+ state.searchText = searchText;};</script>diff --git a/frontend/src/components/RepositorySetupWizard.vue b/frontend/src/components/RepositorySetupWizard.vueindex b524253b6c..f1f8bf09b7 100644--- a/frontend/src/components/RepositorySetupWizard.vue+++ b/frontend/src/components/RepositorySetupWizard.vue@@ -22,10 +22,19 @@@cancel="cancel"><template #0="{ next }">- <RepositoryVCSProviderPanel :config="state.config" @next="next()" />+ <RepositoryVCSProviderPanel+ @next="next()"+ @set-vcs="setVCS"+ @set-code="setCode"+ /></template><template #1="{ next }">- <RepositorySelectionPanel :config="state.config" @next="next()" />+ <RepositorySelectionPanel+ :config="state.config"+ @next="next()"+ @set-token="setToken"+ @set-repository="setRepository"+ /></template><template #2><RepositoryConfigPanel :config="state.config" :project="project" />@@ -44,6 +53,8 @@ import RepositoryVCSProviderPanel from "./RepositoryVCSProviderPanel.vue";import RepositorySelectionPanel from "./RepositorySelectionPanel.vue";import RepositoryConfigPanel from "./RepositoryConfigPanel.vue";import {+ ExternalRepositoryInfo,+ OAuthToken,Project,ProjectRepositoryConfig,RepositoryCreate,@@ -207,6 +218,22 @@ export default defineComponent({});};+ const setCode = (code: string) => {+ state.config.code = code;+ };++ const setToken = (token: OAuthToken) => {+ state.config.token = token;+ };++ const setVCS = (vcs: VCS) => {+ state.config.vcs = vcs;+ };++ const setRepository = (repository: ExternalRepositoryInfo) => {+ state.config.repositoryInfo = repository;+ };+return {state,stepList,@@ -214,6 +241,10 @@ export default defineComponent({tryChangeStep,tryFinishSetup,cancel,+ setCode,+ setVCS,+ setToken,+ setRepository,};},});diff --git a/frontend/src/components/RepositoryVCSProviderPanel.vue b/frontend/src/components/RepositoryVCSProviderPanel.vueindex 4e77e61126..e4b7dfa1b6 100644--- a/frontend/src/components/RepositoryVCSProviderPanel.vue+++ b/frontend/src/components/RepositoryVCSProviderPanel.vue@@ -34,116 +34,73 @@</template><script lang="ts">+export default { name: "RepositoryVCSProviderPanel" };+</script>++<script setup lang="ts">import { useStore } from "vuex";-import {- reactive,- computed,- PropType,- watchEffect,- onUnmounted,- onMounted,-} from "vue";+import { reactive, computed, watchEffect, onUnmounted, onMounted } from "vue";import isEmpty from "lodash-es/isEmpty";-import {- OAuthConfig,- OAuthToken,- OAuthWindowEventPayload,- openWindowForOAuth,- ProjectRepositoryConfig,- redirectUrl,- VCS,-} from "../types";+import { OAuthWindowEventPayload, openWindowForOAuth, VCS } from "../types";import { isOwner } from "../utils";interface LocalState {selectedVCS?: VCS;}-export default {- name: "RepositoryVCSProviderPanel",- props: {- config: {- required: true,- type: Object as PropType<ProjectRepositoryConfig>,- },- },- emits: ["next"],- setup(props, { emit }) {- const store = useStore();- const state = reactive<LocalState>({});+const emit = defineEmits<{+ (event: "next"): void;+ (event: "set-vcs", payload: VCS): void;+ (event: "set-code", payload: string): void;+}>();- const currentUser = computed(() => store.getters["auth/currentUser"]());+const store = useStore();+const state = reactive<LocalState>({});- const prepareVCSList = () => {- store.dispatch("vcs/fetchVCSList");- };+const currentUser = computed(() => store.getters["auth/currentUser"]());- watchEffect(prepareVCSList);+const prepareVCSList = () => {+ store.dispatch("vcs/fetchVCSList");+};- onMounted(() => {- window.addEventListener(- "bb.oauth.link-vcs-repository",- eventListener,- false- );- });- onUnmounted(() => {- window.removeEventListener("bb.oauth.link-vcs-repository", eventListener);- });+watchEffect(prepareVCSList);- const vcsList = computed(() => {- return store.getters["vcs/vcsList"]();- });+onMounted(() => {+ window.addEventListener("bb.oauth.link-vcs-repository", eventListener, false);+});+onUnmounted(() => {+ window.removeEventListener("bb.oauth.link-vcs-repository", eventListener);+});- const eventListener = (event: Event) => {- 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", {- oAuthConfig,- code: payload.code,- })- .then((token: OAuthToken) => {- props.config.vcs = state.selectedVCS!;- props.config.token = token;- emit("next");- });- } else {- store.dispatch("notification/pushNotification", {- module: "bytebase",- style: "CRITICAL",- title: payload.error,- });- }- };+const vcsList = computed(() => {+ return store.getters["vcs/vcsList"]();+});- const isCurrentUserOwner = computed(() => {- return isOwner(currentUser.value.role);+const eventListener = (event: Event) => {+ const payload = (event as CustomEvent).detail as OAuthWindowEventPayload;+ if (isEmpty(payload.error)) {+ emit("set-code", payload.code);+ emit("next");+ } else {+ store.dispatch("notification/pushNotification", {+ module: "bytebase",+ style: "CRITICAL",+ title: payload.error,});+ }+};- const selectVCS = (vcs: VCS) => {- state.selectedVCS = vcs;- openWindowForOAuth(- `${vcs.instanceUrl}/oauth/authorize`,- vcs.applicationId,- "bb.oauth.link-vcs-repository"- );- };+const isCurrentUserOwner = computed(() => {+ return isOwner(currentUser.value.role);+});- return {- state,- currentUser,- vcsList,- isCurrentUserOwner,- selectVCS,- };- },+const selectVCS = (vcs: VCS) => {+ state.selectedVCS = vcs;+ emit("set-vcs", vcs);+ openWindowForOAuth(+ `${vcs.instanceUrl}/oauth/authorize`,+ vcs.applicationId,+ "bb.oauth.link-vcs-repository"+ );};</script>diff --git a/frontend/src/components/VCSSetupWizard.vue b/frontend/src/components/VCSSetupWizard.vueindex 9bb0b6211e..4563861291 100644--- a/frontend/src/components/VCSSetupWizard.vue+++ b/frontend/src/components/VCSSetupWizard.vue@@ -26,7 +26,13 @@</template><script lang="ts">-import { reactive, computed, onUnmounted, onMounted } from "vue";+import {+ reactive,+ computed,+ defineComponent,+ onUnmounted,+ onMounted,+} from "vue";import { useRouter } from "vue-router";import { useStore } from "vuex";import isEmpty from "lodash-es/isEmpty";@@ -58,7 +64,7 @@ interface LocalState {oAuthResultCallback?: (token: OAuthToken | undefined) => void;}-export default {+export default defineComponent({name: "VCSSetupWizard",components: {VCSProviderBasicInfoPanel,@@ -235,5 +241,5 @@ export default {cancelSetup,};},-};+});</script>diff --git a/frontend/src/store/modules/gitlab.ts b/frontend/src/store/modules/gitlab.tsindex 66c0a4e970..bf1a3a83ba 100644--- a/frontend/src/store/modules/gitlab.ts+++ b/frontend/src/store/modules/gitlab.ts@@ -6,20 +6,21 @@ import {OAuthToken,} from "../../types";-const GITLAB_API_PATH = "api/v4";-const getters = {};function convertGitLabProject(project: any): ExternalRepositoryInfo {+ const attributes = project.attributes;return {externalId: project.id.toString(),- name: project.name,- fullPath: project.path_with_namespace,- webUrl: project.web_url,+ name: attributes.name,+ fullPath: attributes.fullPath,+ webUrl: attributes.webUrl,};}const actions = {+ // this actions is for initiating vcs ONLY+ // after creation, the frontend should in no case access the secret.async exchangeToken({}: any,{@@ -46,23 +47,19 @@ const actions = {return oAuthToken;},+ // TODO(zilong): here we still store the access token at the frontend, we may move this to the backendasync fetchProjectList({}: any,- { vcs, token }: { vcs: VCS; token: string }+ { vcs, token }: { vcs: VCS; token: OAuthToken }): Promise<ExternalRepositoryInfo[]> {- // We will use user's token to create webhook in the project, which requires the token owner to- // be at least the project maintainer(40)const data = (- await axios.get(- `${vcs.instanceUrl}/${GITLAB_API_PATH}/projects?membership=true&simple=true&min_access_level=40`,- {- headers: {- Authorization: "Bearer " + token,- },- }- )- ).data;-+ await axios.get(`/api/vcs/${vcs.id}/external-repository`, {+ headers: {+ accessToken: token.accessToken,+ refreshToken: token.refreshToken,+ },+ })+ ).data.data;return data.map((item: any) => convertGitLabProject(item));},};diff --git a/frontend/src/store/modules/oauth.ts b/frontend/src/store/modules/oauth.tsnew file mode 100644index 0000000000..61b7894c2e--- /dev/null+++ b/frontend/src/store/modules/oauth.ts@@ -0,0 +1,37 @@+import axios from "axios";+import { VCSId, OAuthToken, ResourceObject } from "../../types";++const convert = (raw: ResourceObject): OAuthToken => {+ const attr = raw.attributes;+ return {+ accessToken: attr.accessToken as string,+ refreshToken: attr.refreshToken as string,+ expiresTs: attr.expiresTs as number,+ };+};++const actions = {+ async exchangeVCSToken(+ {}: any,+ {+ vcsId,+ code,+ }: {+ vcsId: VCSId;+ code: string;+ }+ ): Promise<OAuthToken> {+ const data = (+ await axios.post(`/api/oauth/vcs/${vcsId}/exchange-token`, null, {+ headers: { code },+ })+ ).data.data;++ const token = convert(data);+ return token;+ },+};+export default {+ namespaced: true,+ actions,+};diff --git a/frontend/src/store/modules/vcs.ts b/frontend/src/store/modules/vcs.tsindex 573838b813..362d6beb50 100644--- a/frontend/src/store/modules/vcs.ts+++ b/frontend/src/store/modules/vcs.ts@@ -124,7 +124,7 @@ const actions = {const data = (await axios.patch(`/api/vcs/${vcsId}`, {data: {- type: "VCSCreate",+ type: "VCSPatch",attributes: vcsPatch,},})diff --git a/frontend/src/types/auth.ts b/frontend/src/types/auth.tsindex d0680156bc..5b5503bc26 100644--- a/frontend/src/types/auth.ts+++ b/frontend/src/types/auth.ts@@ -47,7 +47,7 @@ export const EmptyAuthProvider: AuthProvider = {};export type VCSLoginInfo = {- id: VCSId;+ vcsId: VCSId;name: string;- accessToken: string;+ code: string;};diff --git a/frontend/src/types/project.ts b/frontend/src/types/project.tsindex 8c89a6afb4..38cd1f1ddd 100644--- a/frontend/src/types/project.ts+++ b/frontend/src/types/project.ts@@ -103,8 +103,9 @@ export type ProjectMemberPatch = {export type ProjectRepositoryConfig = {vcs: VCS;- code: string;+ // TODO(zilong): get rid of the token in the frontend.token: OAuthToken;+ code: string;repositoryInfo: ExternalRepositoryInfo;repositoryConfig: RepositoryConfig;};diff --git a/frontend/src/views/SettingWorkspaceVCSDetail.vue b/frontend/src/views/SettingWorkspaceVCSDetail.vueindex c7016a6230..aa53921ca9 100644--- a/frontend/src/views/SettingWorkspaceVCSDetail.vue+++ b/frontend/src/views/SettingWorkspaceVCSDetail.vue@@ -137,7 +137,14 @@</template><script lang="ts">-import { reactive, computed, watchEffect, onMounted, onUnmounted } from "vue";+import {+ reactive,+ computed,+ watchEffect,+ onMounted,+ onUnmounted,+ defineComponent,+} from "vue";import { useStore } from "vuex";import { useRouter } from "vue-router";import RepositoryTable from "../components/RepositoryTable.vue";@@ -148,8 +155,6 @@ import {VCSPatch,openWindowForOAuth,OAuthWindowEventPayload,- OAuthConfig,- redirectUrl,OAuthToken,} from "../types";@@ -160,7 +165,7 @@ interface LocalState {oAuthResultCallback?: (token: OAuthToken | undefined) => void;}-export default {+export default defineComponent({name: "SettingWorkspaceVCSDetail",components: { RepositoryTable },props: {@@ -195,15 +200,9 @@ export default {const payload = (event as CustomEvent).detail as OAuthWindowEventPayload;if (isEmpty(payload.error)) {if (vcs.value.type == "GITLAB_SELF_HOST") {- const oAuthConfig: OAuthConfig = {- endpoint: `${vcs.value.instanceUrl}/oauth/token`,- applicationId: state.applicationId,- secret: state.secret,- redirectUrl: redirectUrl(),- };store- .dispatch("gitlab/exchangeToken", {- oAuthConfig,+ .dispatch("oauth/exchangeVCSToken", {+ vcsId: idFromSlug(props.vcsSlug),code: payload.code,}).then((token: OAuthToken) => {@@ -346,5 +345,5 @@ export default {deleteVCS,};},-};+});</script>diff --git a/frontend/src/views/auth/Signin.vue b/frontend/src/views/auth/Signin.vueindex 6a94b1f568..e5f82b2c40 100644--- a/frontend/src/views/auth/Signin.vue+++ b/frontend/src/views/auth/Signin.vue@@ -172,8 +172,6 @@ import {EmptyAuthProvider,VCSLoginInfo,LoginInfo,- OAuthConfig,- OAuthToken,OAuthWindowEventPayload,openWindowForOAuth,redirectUrl,@@ -236,32 +234,18 @@ export default defineComponent({if (payload.error) {return;}- const oAuthConfig: OAuthConfig = {- endpoint: `${state.activeAuthProvider.instanceUrl}/oauth/token`,- applicationId: state.activeAuthProvider.applicationId,- secret: state.activeAuthProvider.secret,- redirectUrl: redirectUrl(),+ const gitlabLoginInfo: VCSLoginInfo = {+ vcsId: state.activeAuthProvider.id,+ name: state.activeAuthProvider.name,+ code: payload.code,};store- .dispatch("gitlab/exchangeToken", {- oAuthConfig,- code: payload.code,+ .dispatch("auth/login", {+ authProvider: "GITLAB_SELF_HOST",+ payload: gitlabLoginInfo,})- .then((token: OAuthToken) => {- const gitlabLoginInfo: VCSLoginInfo = {- id: state.activeAuthProvider.id,- name: state.activeAuthProvider.name,- accessToken: token.accessToken,- };-- store- .dispatch("auth/login", {- authProvider: "GITLAB_SELF_HOST",- payload: gitlabLoginInfo,- })- .then(() => {- router.push("/");- });+ .then(() => {+ router.push("/");});};diff --git a/plugin/vcs/github/github.go b/plugin/vcs/github/github.goindex 3e5b3013cc..5852aac0ab 100644--- a/plugin/vcs/github/github.go+++ b/plugin/vcs/github/github.go@@ -107,6 +107,14 @@ func (p *Provider) FetchRepositoryActiveMemberList(ctx context.Context, oauthCtxreturn nil, errors.New("not implemented yet") // TODO: https://github.com/bytebase/bytebase/issues/928}+func (p *Provider) ExchangeOAuthToken(ctx context.Context, instanceURL string, oauthExchange *common.OAuthExchange) (*vcs.OAuthToken, error) {+ return nil, errors.New("not implemented yet")+}++func (p *Provider) FetchRepositoryList(ctx context.Context, oauthCtx common.OauthContext, instanceURL string) ([]*vcs.Repository, error) {+ return nil, errors.New("not implemented yet")+}+func (p *Provider) FetchRepositoryFileList(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID, ref, filePath string) ([]*vcs.RepositoryTreeNode, error) {return nil, errors.New("not implemented yet") // TODO: https://github.com/bytebase/bytebase/issues/928}diff --git a/plugin/vcs/gitlab/gitlab.go b/plugin/vcs/gitlab/gitlab.goindex b1819f004d..4a09781837 100644--- a/plugin/vcs/gitlab/gitlab.go+++ b/plugin/vcs/gitlab/gitlab.go@@ -167,6 +167,14 @@ type gitLabRepositoryMember struct {AccessLevel int32 `json:"access_level"`}+// gitLabRepository is the API message for repository in GitLab+type gitLabRepository struct {+ ID int64 `json:"id"`+ Name string `json:"name"`+ PathWithNamespace string `json:"path_with_namespace"`+ WebURL string `json:"web_url"`+}+func init() {vcs.Register(vcs.GitLabSelfHost, newProvider)}@@ -187,6 +195,99 @@ func (provider *Provider) APIURL(instanceURL string) string {return fmt.Sprintf("%s/%s", instanceURL, apiPath)}+// ExchangeOAuthToken exchange oauth content with the provdied authentication code+func (provider *Provider) ExchangeOAuthToken(ctx context.Context, instanceURL 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)+ urlParams.Set("grant_type", "authorization_code")+ url := fmt.Sprintf("%s/oauth/token?%s", instanceURL, urlParams.Encode())++ req, err := http.NewRequest("POST", url, nil)++ if err != nil {+ urlParams.Set("client_secrete", "**encrypted**")+ urlWithoutSecret := fmt.Sprintf("%s/oauth/token?%s", instanceURL, urlParams.Encode())+ return nil, fmt.Errorf("failed to construct POST %v (%w)", urlWithoutSecret, err)+ }++ req.Header.Set("Content-Type", "application/json")++ client := &http.Client{}+ resp, err := client.Do(req)+ if err != nil {+ return nil, fmt.Errorf("failed to exchange Oauth Token, code %v, error: %v", resp.StatusCode, 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)+ }++ oauthToken := &vcs.OAuthToken{}+ if err := json.Unmarshal(body, oauthToken); err != nil {+ return nil, fmt.Errorf("failed to unmarshal oauth response body, code %v, error: %v", resp.StatusCode, err)+ }++ // derivative expiresAt+ // For GitLab, as of 13.12, the default config won't expire the access token, thus this field is 0.+ // see https://gitlab.com/gitlab-org/gitlab/-/issues/21745.+ if oauthToken.ExpiresIn != 0 {+ oauthToken.ExpiresTs = oauthToken.CreatedAt + oauthToken.ExpiresIn+ }++ return oauthToken, nil+}++// FetchRepositoryList will fetch all repository in which the authenticated user has a maintainer role+func (provider *Provider) FetchRepositoryList(ctx context.Context, oauthCtx common.OauthContext, instanceURL string) ([]*vcs.Repository, error) {+ code, body, err := httpGet(+ instanceURL,+ // We will use user's token to create webhook in the project, which requires the token owner to+ // be at least the project maintainer(40)+ "projects?membership=true&simple=true&min_access_level=40",+ &oauthCtx.AccessToken,+ oauthContext{+ ClientID: oauthCtx.ClientID,+ ClientSecret: oauthCtx.ClientSecret,+ RefreshToken: oauthCtx.RefreshToken,+ },+ oauthCtx.Refresher,+ )+ if err != nil {+ return nil, err+ }++ if code == 404 {+ return nil, common.Errorf(common.NotFound, fmt.Errorf("failed to fetch repository list from GitLab instance %s", instanceURL))+ } else if code >= 300 {+ return nil, fmt.Errorf("failed to read repository list from GitLab instance %s, status code: %d",+ instanceURL,+ code,+ )+ }++ var gitLabrepository []gitLabRepository+ if err := json.Unmarshal([]byte(body), &gitLabrepository); err != nil {+ return nil, err+ }++ var repository []*vcs.Repository+ for _, gitLabRepo := range gitLabrepository {+ repo := &vcs.Repository{+ ID: gitLabRepo.ID,+ Name: gitLabRepo.Name,+ FullPath: gitLabRepo.PathWithNamespace,+ WebURL: gitLabRepo.WebURL,+ }+ repository = append(repository, repo)+ }++ return repository, nil+}+// fetchUserInfo will fetch user info from the given resourceURI, resourceURI should be either 'user' or 'users/:userID'func fetchUserInfo(ctx context.Context, oauthCtx common.OauthContext, instanceURL, resourceURI string) (*vcs.UserInfo, error) {code, body, err := httpGet(diff --git a/plugin/vcs/vcs.go b/plugin/vcs/vcs.goindex 5ad38f612a..2481e3ff38 100644--- a/plugin/vcs/vcs.go+++ b/plugin/vcs/vcs.go@@ -28,6 +28,17 @@ func (e Type) String() string {return "UNKNOWN"}+// OAuthToken is the API message for OAuthToken.+type OAuthToken struct {+ AccessToken string `json:"access_token" `+ RefreshToken string `json:"refresh_token"`+ ExpiresIn int64 `json:"expires_in"`+ CreatedAt int64 `json:"created_at"`+ // ExpiresTs is a derivative from ExpresIn and CreatedAt.+ // ExpiresTs = ExpiresIn == 0 ? 0 : CreatedAt + ExpiresIn+ ExpiresTs int64 `json:"expires_ts"`+}+// These payload types are only used when marshalling to the json format for saving into the database.// So we annotate with json tag using camelCase naming which is consistent with normal// json naming convention@@ -106,10 +117,25 @@ type RepositoryMember struct {RoleProvider Type `json:"roleProvider"`}+// Repository is the API message for repository info.+type Repository struct {+ ID int64 `json:"id"`+ Name string `json:"name"`+ FullPath string `json:"fullPath"`+ WebURL string `json:"webUrl"`+}+// Provider is the interface for VCS provider.type Provider interface {// Returns the API URL for a given VCS instance URLAPIURL(instanceURL string) string++ // Exchange oauth token with the provided code+ //+ // instanceURL: VCS instance URL+ // oauthExchange: api message for exchanging oauth token+ ExchangeOAuthToken(ctx context.Context, instanceURL string, oauthExchange *common.OAuthExchange) (*OAuthToken, error)+// Try to use this provider as an auth provider and fetch the user info from the OAuth context//// oauthCtx: OAuth context to write the file content@@ -127,6 +153,13 @@ type Provider interface {// instanceURL: VCS instance URL// repositoryID: the repository ID from the external VCS system (note this is NOT the ID of Bytebase's own repository resource)FetchRepositoryActiveMemberList(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID string) ([]*RepositoryMember, error)++ // Fetch all repository within a given user's scope+ //+ // oauthCtx: OAuth context to write the file content+ // instanceURL: VCS instance URL+ FetchRepositoryList(ctx context.Context, oauthCtx common.OauthContext, instanceURL string) ([]*Repository, error)+// Fetch the repository file list//// oauthCtx: OAuth context to read the repository tree@@ -135,6 +168,7 @@ type Provider interface {// ref: the unique name of a repository tree, could be a branch name in GitLab or a tree sha in GitHub// filePath: the path inside repository, used to get content of subdirectoriesFetchRepositoryFileList(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID, ref, filePath string) ([]*RepositoryTreeNode, error)+// Commits a new file//// oauthCtx: OAuth context to write the file contentdiff --git a/server/acl.go b/server/acl.goindex 1cbeae411b..4e6450ee72 100644--- a/server/acl.go+++ b/server/acl.go@@ -27,7 +27,7 @@ func aclMiddleware(l *zap.Logger, s *Server, ce *casbin.Enforcer, next echo.Handreturn func(c echo.Context) error {ctx := context.Background()// Skips auth, actuator, plan- if common.HasPrefixes(c.Path(), "/api/auth", "/api/actuator", "/api/plan") {+ if common.HasPrefixes(c.Path(), "/api/auth", "/api/actuator", "/api/plan", "/api/oauth") {return next(c)}diff --git a/server/acl_casbin_policy_dba.csv b/server/acl_casbin_policy_dba.csvindex 34ec05334f..f83de307ea 100644--- a/server/acl_casbin_policy_dba.csv+++ b/server/acl_casbin_policy_dba.csv@@ -80,6 +80,7 @@ p, DBA, /vcs/{id}, GETp, DBA, /vcs/{id}, PATCHp, DBA, /vcs/{id}, DELETEp, DBA, /vcs/{id}/repository, GET+p, DBA, /vcs/{id}/external-repository, GETp, DBA, /plan, GETp, DBA, /plan, PATCHp, DBA, /setting, GETdiff --git a/server/acl_casbin_policy_developer.csv b/server/acl_casbin_policy_developer.csvindex 40494c29a3..a35ed041ad 100644--- a/server/acl_casbin_policy_developer.csv+++ b/server/acl_casbin_policy_developer.csv@@ -70,6 +70,7 @@ p, DEVELOPER, /sql/ping, POSTp, DEVELOPER, /sql/execute, POSTp, DEVELOPER, /vcs, GETp, DEVELOPER, /vcs/{id}, GET+p, DEVELOPER, /vcs/{id}/external-repository, GETp, DEVELOPER, /plan, GETp, DEVELOPER, /plan, PATCHp, DEVELOPER, /setting, GET@@ -82,4 +83,4 @@ p, DEVELOPER, /sheet/{id}, PATCHp, DEVELOPER, /sheet/{id}, PATCH_SELFp, DEVELOPER, /sheet/{id}, DELETE_SELFp, DEVELOPER, /debug, GET-p, DEVELOPER, /debug, PATCH\ No newline at end of file+p, DEVELOPER, /debug, PATCHdiff --git a/server/acl_casbin_policy_owner.csv b/server/acl_casbin_policy_owner.csvindex c7428101b1..5280812da2 100644--- a/server/acl_casbin_policy_owner.csv+++ b/server/acl_casbin_policy_owner.csv@@ -84,6 +84,7 @@ p, OWNER, /vcs/{id}, GETp, OWNER, /vcs/{id}, PATCHp, OWNER, /vcs/{id}, DELETEp, OWNER, /vcs/{id}/repository, GET+p, OWNER, /vcs/{id}/external-repository, GETp, OWNER, /plan, GETp, OWNER, /plan, PATCHp, OWNER, /setting, GET@@ -99,4 +100,4 @@ p, OWNER, /sheet/{id}, PATCHp, OWNER, /sheet/{id}, PATCH_SELFp, OWNER, /sheet/{id}, DELETE_SELFp, OWNER, /debug, GET-p, OWNER, /debug, PATCH\ No newline at end of file+p, OWNER, /debug, PATCHdiff --git a/server/auth.go b/server/auth.goindex 8aea0d96fc..3ffd8b2964 100644--- a/server/auth.go+++ b/server/auth.go@@ -34,7 +34,7 @@ func (s *Server) registerAuthRoutes(g *echo.Group) {Name: vcs.Name,InstanceURL: vcs.InstanceURL,ApplicationID: vcs.ApplicationID,- Secret: vcs.Secret,+ // we do not return secret to the frontend for safety concern}authProviderList = append(authProviderList, newProvider)}@@ -83,7 +83,7 @@ func (s *Server) registerAuthRoutes(g *echo.Group) {if err := jsonapi.UnmarshalPayload(c.Request().Body, gitlabLogin); err != nil {return echo.NewHTTPError(http.StatusBadRequest, "Malformatted gitlab login request").SetInternal(err)}- vcsFound, err := s.store.GetVCSByID(ctx, gitlabLogin.ID)+ vcsFound, err := s.store.GetVCSByID(ctx, gitlabLogin.VCSID)if err != nil {return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch vcs, name: %v, ID: %v", gitlabLogin.Name, gitlabLogin.Name)).SetInternal(err)}@@ -91,11 +91,26 @@ func (s *Server) registerAuthRoutes(g *echo.Group) {return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("vcs do not exist, name: %v, ID: %v", gitlabLogin.Name, gitlabLogin.Name)).SetInternal(err)}+ // exchange OAuth Token+ oauthToken, err := vcsPlugin.Get(vcsFound.Type, vcsPlugin.ProviderConfig{Logger: s.l}).ExchangeOAuthToken(+ ctx,+ vcsFound.InstanceURL,+ &common.OAuthExchange{+ ClientID: vcsFound.ApplicationID,+ ClientSecret: vcsFound.Secret,+ Code: gitlabLogin.Code,+ RedirectURL: fmt.Sprintf("%s:%d/oauth/callback", s.frontendHost, s.frontendPort),+ },+ )+ if err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to exchange OAuth token").SetInternal(err)+ }+gitlabUserInfo, err := vcsPlugin.Get(vcs.GitLabSelfHost, vcsPlugin.ProviderConfig{Logger: s.l}).TryLogin(ctx,common.OauthContext{ClientID: vcsFound.ApplicationID,ClientSecret: vcsFound.Secret,- AccessToken: gitlabLogin.AccessToken,+ AccessToken: oauthToken.AccessToken,RefreshToken: "",Refresher: nil,},diff --git a/server/oauth.go b/server/oauth.gonew file mode 100644index 0000000000..002b6719f0--- /dev/null+++ b/server/oauth.go@@ -0,0 +1,63 @@+package server++import (+ "context"+ "fmt"+ "net/http"+ "strconv"++ "github.com/bytebase/bytebase/api"+ "github.com/bytebase/bytebase/common"+ vcsPlugin "github.com/bytebase/bytebase/plugin/vcs"+ "github.com/google/jsonapi"+ "github.com/labstack/echo/v4"+)++func (s *Server) registerOAuthRoutes(g *echo.Group) {+ g.POST("/oauth/vcs/:vcsID/exchange-token", func(c echo.Context) error {+ ctx := context.Background()++ vcsID, err := strconv.Atoi(c.Param("vcsID"))+ if err != nil {+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Failed to marshal oauth provider's ID: %v", c.Param("id"))).SetInternal(err)+ }+ code := c.Request().Header.Get("code")++ vcs, err := s.store.GetVCSByID(ctx, vcsID)+ if err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, err)+ }+ if vcs == nil {+ return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Failed to find VCS, ID: %v", vcsID)).SetInternal(err)+ }++ oauthToken := &api.OAuthToken{}+ switch vcs.Type {+ case vcsPlugin.GitLabSelfHost:+ oauthTokenRaw, err := vcsPlugin.Get(vcs.Type, vcsPlugin.ProviderConfig{Logger: s.l}).ExchangeOAuthToken(+ ctx,+ vcs.InstanceURL,+ &common.OAuthExchange{+ ClientID: vcs.ApplicationID,+ ClientSecret: vcs.Secret,+ Code: code,+ RedirectURL: fmt.Sprintf("%s:%d/oauth/callback", s.frontendHost, s.frontendPort),+ },+ )+ if err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to exchange OAuth token").SetInternal(err)+ }+ oauthToken.AccessToken = oauthTokenRaw.AccessToken+ oauthToken.RefreshToken = oauthTokenRaw.RefreshToken+ oauthToken.ExpiresTs = oauthTokenRaw.ExpiresTs+ }++ c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)+ if err := jsonapi.MarshalPayload(c.Response().Writer, oauthToken); err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal oauth token response").SetInternal(err)+ }++ return nil+ })++}diff --git a/server/server.go b/server/server.goindex eced4bedaa..ea5ca72e52 100644--- a/server/server.go+++ b/server/server.go@@ -221,6 +221,7 @@ func NewServer(logger *zap.Logger, storeInstance *store.Store, loggerLevel *zap.s.registerSettingRoutes(apiGroup)s.registerActuatorRoutes(apiGroup)s.registerAuthRoutes(apiGroup)+ s.registerOAuthRoutes(apiGroup)s.registerPrincipalRoutes(apiGroup)s.registerMemberRoutes(apiGroup)s.registerPolicyRoutes(apiGroup)diff --git a/server/vcs.go b/server/vcs.goindex d03bc03b64..49ccd075c2 100644--- a/server/vcs.go+++ b/server/vcs.go@@ -10,6 +10,7 @@ import ("github.com/bytebase/bytebase/api""github.com/bytebase/bytebase/common""github.com/bytebase/bytebase/plugin/vcs"+ vcsPlugin "github.com/bytebase/bytebase/plugin/vcs""github.com/google/jsonapi""github.com/labstack/echo/v4")@@ -153,4 +154,54 @@ func (s *Server) registerVCSRoutes(g *echo.Group) {}return nil})++ g.GET("/vcs/:vcsID/external-repository", func(c echo.Context) error {+ ctx := context.Background()+ id, err := strconv.Atoi(c.Param("vcsID"))+ if err != nil {+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("vcsID"))).SetInternal(err)+ }+ accessToken := c.Request().Header.Get("accessToken")+ refreshToken := c.Request().Header.Get("refreshToken")++ vcsFound, err := s.store.GetVCSByID(ctx, id)+ if err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch VCS, ID: %v", id)).SetInternal(err)+ }+ if vcsFound == nil {+ return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Failed to find VCS, ID: %v", id))+ }++ externalRepoListRaw, err := vcsPlugin.Get(vcsFound.Type, vcsPlugin.ProviderConfig{Logger: s.l}).FetchRepositoryList(+ ctx,+ common.OauthContext{+ ClientID: vcsFound.ApplicationID,+ ClientSecret: vcsFound.Secret,+ AccessToken: accessToken,+ RefreshToken: refreshToken,+ Refresher: nil,+ },+ vcsFound.InstanceURL,+ )+ if err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to find external repository, instance URL: %s", vcsFound.InstanceURL)).SetInternal(err)+ }++ var externalRepoList []*api.ExternalRepository+ for _, repo := range externalRepoListRaw {+ externalRepoList = append(externalRepoList, &api.ExternalRepository{+ ID: repo.ID,+ FullPath: repo.FullPath,+ Name: repo.Name,+ WebURL: repo.WebURL,+ })+ }++ c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)+ if err := jsonapi.MarshalPayload(c.Response().Writer, externalRepoList); err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal response").SetInternal(err)+ }++ return nil+ })}diff --git a/store/principal.go b/store/principal.goindex be640244ed..3ccb301681 100644--- a/store/principal.go+++ b/store/principal.go@@ -206,7 +206,7 @@ func (s *Store) findPrincipalRaw(ctx context.Context, find *api.PrincipalFind) (}if len(list) == 0 {- return nil, &common.Error{Code: common.NotFound, Err: fmt.Errorf("principal not found with PrincipalFind[%+v]", find)}+ return nil, nil} else if len(list) > 1 {return nil, &common.Error{Code: common.Conflict, Err: fmt.Errorf("found %d principals with PrincipalFind[%+v], expect 1", len(list), find)}}