Skip to content

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

feat: allow exchange OAuth token without an existing VCS (#1007)

Joe Chend8b5e5d1de84
diff --git a/api/vcs.go b/api/vcs.go
index 35fce11f10..bcd73d006a 100644
--- a/api/vcs.go
+++ b/api/vcs.go
@@ -87,3 +87,13 @@ type ExternalRepository struct {
FullPath string `jsonapi:"attr,fullPath"`
WebURL string `jsonapi:"attr,webUrl"`
}
+
+// VCSExchangeToken is the API message of exchanging token for a VCS.
+type VCSExchangeToken struct {
+ Code string `jsonapi:"attr,code"`
+ ID int `jsonapi:"attr,vcsId"`
+ Type vcs.Type `jsonapi:"attr,vcsType"`
+ InstanceURL string `jsonapi:"attr,instanceUrl"`
+ ClientID string `jsonapi:"attr,clientId"`
+ ClientSecret string `jsonapi:"attr,clientSecret"`
+}
diff --git a/frontend/src/components/RepositorySelectionPanel.vue b/frontend/src/components/RepositorySelectionPanel.vue
index cc4fab057c..dc1eacef80 100644
--- a/frontend/src/components/RepositorySelectionPanel.vue
+++ b/frontend/src/components/RepositorySelectionPanel.vue
@@ -75,7 +75,7 @@ onMounted(() => {
const prepareRepositoryList = () => {
if (props.config.vcs.type == "GITLAB_SELF_HOST") {
useOAuthStore()
- .exchangeVCSToken({
+ .exchangeVCSTokenWithID({
vcsId: props.config.vcs.id,
code: props.config.code,
})
diff --git a/frontend/src/components/VCSSetupWizard.vue b/frontend/src/components/VCSSetupWizard.vue
index 59bb68129c..ac9d73549a 100644
--- a/frontend/src/components/VCSSetupWizard.vue
+++ b/frontend/src/components/VCSSetupWizard.vue
@@ -47,13 +47,11 @@ import {
VCS,
openWindowForOAuth,
OAuthWindowEventPayload,
- OAuthConfig,
- redirectUrl,
OAuthToken,
} from "../types";
import { isUrl } from "../utils";
import { useI18n } from "vue-i18n";
-import { pushNotification } from "@/store";
+import { pushNotification, useOAuthStore } from "@/store";
const BASIC_INFO_STEP = 0;
const OAUTH_INFO_STEP = 1;
@@ -106,15 +104,12 @@ export default defineComponent({
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,
+ useOAuthStore()
+ .exchangeVCSToken({
+ vcsType: state.config.type,
+ instanceUrl: state.config.instanceUrl,
+ clientId: state.config.applicationId,
+ clientSecret: state.config.secret,
code: payload.code,
})
.then((token: OAuthToken) => {
diff --git a/frontend/src/store/modules/gitlab.ts b/frontend/src/store/modules/gitlab.ts
index bf1a3a83ba..39f4e915ad 100644
--- a/frontend/src/store/modules/gitlab.ts
+++ b/frontend/src/store/modules/gitlab.ts
@@ -1,10 +1,5 @@
import axios from "axios";
-import {
- ExternalRepositoryInfo,
- VCS,
- OAuthConfig,
- OAuthToken,
-} from "../../types";
+import { ExternalRepositoryInfo, VCS, OAuthToken } from "../../types";
const getters = {};
@@ -19,34 +14,6 @@ function convertGitLabProject(project: any): ExternalRepositoryInfo {
}
const actions = {
- // this actions is for initiating vcs ONLY
- // after creation, the frontend should in no case access the secret.
- async exchangeToken(
- {}: any,
- {
- oAuthConfig,
- code,
- }: {
- oAuthConfig: OAuthConfig;
- code: string;
- }
- ): Promise<OAuthToken> {
- const data = (
- await axios.post(
- `${oAuthConfig.endpoint}?client_id=${oAuthConfig.applicationId}&client_secret=${oAuthConfig.secret}&code=${code}&redirect_uri=${oAuthConfig.redirectUrl}&grant_type=authorization_code`
- )
- ).data;
-
- const oAuthToken: OAuthToken = {
- accessToken: data.access_token,
- refreshToken: data.refresh_token,
- // 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.
- expiresTs: data.expires_in == 0 ? 0 : data.created_at + data.expires_in,
- };
- return oAuthToken;
- },
-
// TODO(zilong): here we still store the access token at the frontend, we may move this to the backend
async fetchProjectList(
{}: any,
diff --git a/frontend/src/store/pinia-modules/oauth.ts b/frontend/src/store/pinia-modules/oauth.ts
index 5f1670969b..40de7df457 100644
--- a/frontend/src/store/pinia-modules/oauth.ts
+++ b/frontend/src/store/pinia-modules/oauth.ts
@@ -1,5 +1,5 @@
import axios from "axios";
-import { VCSId, OAuthToken, ResourceObject } from "@/types";
+import { VCSId, OAuthToken, ResourceObject, VCSType } from "@/types";
import { defineStore } from "pinia";
const convert = (raw: ResourceObject): OAuthToken => {
@@ -13,10 +13,57 @@ const convert = (raw: ResourceObject): OAuthToken => {
export const useOAuthStore = defineStore("oauth", {
actions: {
- async exchangeVCSToken({ vcsId, code }: { vcsId: VCSId; code: string }) {
+ // exchangeVCSTokenWithID uses "vcsId" to let the backend infer the details from an existing VCS provider.
+ async exchangeVCSTokenWithID({
+ vcsId,
+ code,
+ }: {
+ vcsId: VCSId;
+ code: string;
+ }): Promise<OAuthToken> {
const data = (
- await axios.post(`/api/oauth/vcs/${vcsId}/exchange-token`, null, {
- headers: { code },
+ await axios.post(`/api/oauth/vcs/exchange-token`, {
+ data: {
+ type: "exchangeToken",
+ attributes: {
+ code,
+ vcsId,
+ },
+ },
+ })
+ ).data.data;
+
+ const token = convert(data);
+ return token;
+ },
+
+ // exchangeVCSToken passes client details to the backend to allow the backend directly
+ // compose the request to the VCS host. This should only be used in the initial VCS set up.
+ async exchangeVCSToken({
+ vcsType,
+ instanceUrl,
+ clientId,
+ clientSecret,
+ code,
+ }: {
+ vcsType: VCSType;
+ instanceUrl: string;
+ clientId: string;
+ clientSecret: string;
+ code: string;
+ }): Promise<OAuthToken> {
+ const data = (
+ await axios.post(`/api/oauth/vcs/exchange-token`, {
+ data: {
+ type: "exchangeToken",
+ attributes: {
+ vcsType,
+ instanceUrl,
+ clientId,
+ clientSecret,
+ code,
+ },
+ },
})
).data.data;
diff --git a/frontend/src/views/SettingWorkspaceVCSDetail.vue b/frontend/src/views/SettingWorkspaceVCSDetail.vue
index 2b00ad354f..6dd79077ef 100644
--- a/frontend/src/views/SettingWorkspaceVCSDetail.vue
+++ b/frontend/src/views/SettingWorkspaceVCSDetail.vue
@@ -202,7 +202,7 @@ export default defineComponent({
if (isEmpty(payload.error)) {
if (vcs.value.type == "GITLAB_SELF_HOST") {
useOAuthStore()
- .exchangeVCSToken({
+ .exchangeVCSTokenWithID({
vcsId: idFromSlug(props.vcsSlug),
code: payload.code,
})
diff --git a/plugin/vcs/gitlab/gitlab.go b/plugin/vcs/gitlab/gitlab.go
index 8e47a85137..2522aa2a62 100644
--- a/plugin/vcs/gitlab/gitlab.go
+++ b/plugin/vcs/gitlab/gitlab.go
@@ -234,7 +234,7 @@ func (p *Provider) ExchangeOAuthToken(ctx context.Context, instanceURL string, o
resp, err := p.client.Do(req)
if err != nil {
- return nil, fmt.Errorf("failed to exchange Oauth Token, code %v, error: %v", resp.StatusCode, err)
+ return nil, fmt.Errorf("failed to exchange Oauth Token, error: %v", err)
}
body, err := io.ReadAll(resp.Body)
diff --git a/plugin/vcs/vcs.go b/plugin/vcs/vcs.go
index 946fbb1cb2..c166781469 100644
--- a/plugin/vcs/vcs.go
+++ b/plugin/vcs/vcs.go
@@ -34,7 +34,7 @@ type OAuthToken struct {
RefreshToken string `json:"refresh_token"`
ExpiresIn int64 `json:"expires_in"`
CreatedAt int64 `json:"created_at"`
- // ExpiresTs is a derivative from ExpresIn and CreatedAt.
+ // ExpiresTs is a derivative from ExpiresIn and CreatedAt.
// ExpiresTs = ExpiresIn == 0 ? 0 : CreatedAt + ExpiresIn
ExpiresTs int64 `json:"expires_ts"`
}
diff --git a/server/oauth.go b/server/oauth.go
index 002b6719f0..ed959a6f4a 100644
--- a/server/oauth.go
+++ b/server/oauth.go
@@ -1,63 +1,81 @@
package server
import (
- "context"
"fmt"
"net/http"
- "strconv"
+
+ "github.com/google/jsonapi"
+ "github.com/labstack/echo/v4"
"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)
+ // This is a generic endpoint of exchanging access token for VCS providers. It
+ // requires either the "vcsId" to infer the details from an existing VCS
+ // provider or "vcsType", "instanceURL", "clientId" and "clientSecret" to
+ // directly compose the request to the VCS host.
+ g.POST("/oauth/vcs/exchange-token", func(c echo.Context) error {
+ req := &api.VCSExchangeToken{}
+ if err := jsonapi.UnmarshalPayload(c.Request().Body, req); err != nil {
+ return echo.NewHTTPError(http.StatusBadRequest, "Malformed VCS exchange token request").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)
+ var vcsType vcsPlugin.Type
+ var instanceURL string
+ var oauthExchange *common.OAuthExchange
+ if req.ID > 0 {
+ vcs, err := s.store.GetVCSByID(c.Request().Context(), req.ID)
+ 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", req.ID))
+ }
+
+ vcsType = vcs.Type
+ instanceURL = vcs.InstanceURL
+ oauthExchange = &common.OAuthExchange{
+ ClientID: vcs.ApplicationID,
+ ClientSecret: vcs.Secret,
+ Code: req.Code,
+ }
+ } else {
+ vcsType = req.Type
+ if vcsType != vcsPlugin.GitLabSelfHost && vcsType != vcsPlugin.GitHubCom {
+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Unexpected VCS type: %s", vcsType))
+ }
+
+ instanceURL = req.InstanceURL
+ oauthExchange = &common.OAuthExchange{
+ ClientID: req.ClientID,
+ ClientSecret: req.ClientSecret,
+ Code: req.Code,
+ }
}
- 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),
- },
+ oauthExchange.RedirectURL = fmt.Sprintf("%s:%d/oauth/callback", s.frontendHost, s.frontendPort)
+ oauthToken, err := vcsPlugin.Get(vcsType, vcsPlugin.ProviderConfig{Logger: s.l}).
+ ExchangeOAuthToken(
+ c.Request().Context(),
+ instanceURL,
+ oauthExchange,
)
- 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
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to exchange OAuth token").SetInternal(err)
}
+ resp := &api.OAuthToken{
+ AccessToken: oauthToken.AccessToken,
+ RefreshToken: oauthToken.RefreshToken,
+ ExpiresTs: oauthToken.ExpiresTs,
+ }
c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
- if err := jsonapi.MarshalPayload(c.Response().Writer, oauthToken); err != nil {
+ if err := jsonapi.MarshalPayload(c.Response().Writer, resp); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal oauth token response").SetInternal(err)
}
-
return nil
})
-
}