Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
GitLab oauth flow to retrieve access token and refresh token
天舟e227136d7d4f
diff --git a/backend/api/oauth.go b/backend/api/oauth.gonew file mode 100644index 0000000000..644671dc3a--- /dev/null+++ b/backend/api/oauth.go@@ -0,0 +1,8 @@+package api++type OAuthToken struct {+ AccessToken string `json:"access_token"`+ ExpiresIn int64 `json:"expires_in"`+ RefreshToken string `json:"refresh_token"`+ CreatedAt int64 `json:"created_at"`+}diff --git a/backend/api/vcs.go b/backend/api/vcs.goindex 8bde8bb88c..0883b72404 100644--- a/backend/api/vcs.go+++ b/backend/api/vcs.go@@ -39,7 +39,7 @@ type VCS struct {ApiURL string `jsonapi:"attr,apiURL"`ApplicationId string `jsonapi:"attr,applicationId"`Secret string `jsonapi:"attr,secret"`- AccessToken string `jsonapi:"attr,accessToken"`+ AccessToken string}type VCSCreate struct {@@ -48,9 +48,10 @@ type VCSCreate struct {CreatorId int// Domain specific fields- Name string `jsonapi:"attr,name"`- Type VCSType `jsonapi:"attr,type"`- InstanceURL string `jsonapi:"attr,instanceURL"`+ Name string `jsonapi:"attr,name"`+ Type VCSType `jsonapi:"attr,type"`+ InstanceURL string `jsonapi:"attr,instanceURL"`+ // ApiURL derives from InstanceURLApiURL stringApplicationId string `jsonapi:"attr,applicationId"`Secret string `jsonapi:"attr,secret"`@@ -79,7 +80,9 @@ type VCSPatch struct {UpdaterId int// Domain specific fields- AccessToken *string `jsonapi:"attr,accessToken"`+ AccessToken *string+ ExpireTs *int64+ RefreshToken *string}type VCSDelete struct {@@ -90,6 +93,16 @@ type VCSDelete struct {DeleterId int}+type VCSTokenCreate struct {+ // Standard fields+ CreatorId int++ // Domain specific fields+ // OAuth code and redirect url are used to exchange for the access token and refresh token+ Code string `jsonapi:"attr,code"`+ RedirectUrl string `jsonapi:"attr,redirectURL"`+}+type VCSService interface {CreateVCS(ctx context.Context, create *VCSCreate) (*VCS, error)FindVCSList(ctx context.Context, find *VCSFind) ([]*VCS, error)diff --git a/backend/server/acl_casbin_policy_owner.csv b/backend/server/acl_casbin_policy_owner.csvindex c44e3436ee..50f65b6edd 100644--- a/backend/server/acl_casbin_policy_owner.csv+++ b/backend/server/acl_casbin_policy_owner.csv@@ -46,3 +46,4 @@ p, OWNER, /vcs, GETp, OWNER, /vcs/{id}, GETp, OWNER, /vcs/{id}, PATCHp, OWNER, /vcs/{id}, DELETE+p, OWNER, /vcs/{id}/token, POSTdiff --git a/backend/server/vcs.go b/backend/server/vcs.goindex fec9039143..babbbce653 100644--- a/backend/server/vcs.go+++ b/backend/server/vcs.go@@ -1,8 +1,11 @@package serverimport (+ "bytes""context"+ "encoding/json""fmt"+ "io/ioutil""net/http""strconv"@@ -154,6 +157,100 @@ func (s *Server) registerVCSRoutes(g *echo.Group) {c.Response().WriteHeader(http.StatusOK)return nil})++ g.POST("/vcs/:vcsId/token", func(c echo.Context) error {+ 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("id"))).SetInternal(err)+ }++ vcsTokenCreate := &api.VCSTokenCreate{+ CreatorId: c.Get(GetPrincipalIdContextKey()).(int),+ }+ if err := jsonapi.UnmarshalPayload(c.Request().Body, vcsTokenCreate); err != nil {+ return echo.NewHTTPError(http.StatusBadRequest, "Malformatted create VCS token request").SetInternal(err)+ }++ vcsFind := &api.VCSFind{+ ID: &id,+ }+ vcs, err := s.VCSService.FindVCS(context.Background(), vcsFind)+ if err != nil {+ if bytebase.ErrorCode(err) == bytebase.ENOTFOUND {+ return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("VCS ID not found: %d", id))+ }+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch vcs ID: %v", id)).SetInternal(err)+ }++ oauthToken := &api.OAuthToken{}+ switch vcs.Type {+ case "GITLAB_SELF_HOST":+ url := fmt.Sprintf("%s/oauth/token?client_id=%s&client_secret=%s&code=%s&grant_type=authorization_code&redirect_uri=%s",+ vcs.InstanceURL,+ vcs.ApplicationId,+ vcs.Secret,+ vcsTokenCreate.Code,+ vcsTokenCreate.RedirectUrl,+ )+ req, err := http.NewRequest("POST",+ url, new(bytes.Buffer))+ if err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to construct request to fetch token for vcs ID: %v", id)).SetInternal(err)+ }++ req.Header.Set("Content-Type", "application/json")+ client := &http.Client{}+ res, err := client.Do(req)+ if err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch token for vcs ID: %v", id)).SetInternal(err)+ }+ defer res.Body.Close()++ body, err := ioutil.ReadAll(res.Body)+ if err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to read token response for vcs ID: %v", id)).SetInternal(err)+ }++ if err := json.Unmarshal(body, oauthToken); err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to unmarshal token response for vcs ID: %v", id)).SetInternal(err)+ }+ }++ vcsPatch := &api.VCSPatch{+ ID: id,+ UpdaterId: c.Get(GetPrincipalIdContextKey()).(int),+ }+ if oauthToken.AccessToken != "" {+ vcsPatch.AccessToken = &oauthToken.AccessToken+ }+ // 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 {+ ts := oauthToken.CreatedAt + oauthToken.ExpiresIn+ vcsPatch.ExpireTs = &ts+ }+ if oauthToken.RefreshToken != "" {+ vcsPatch.RefreshToken = &oauthToken.RefreshToken+ }++ updatedVCS, err := s.VCSService.PatchVCS(context.Background(), vcsPatch)+ if err != nil {+ if bytebase.ErrorCode(err) == bytebase.ENOTFOUND {+ return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("VCS ID not found: %d", id))+ }+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to change VCS ID: %v", id)).SetInternal(err)+ }++ if err := s.ComposeVCSRelationship(context.Background(), updatedVCS, c.Get(getIncludeKey()).([]string)); err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch updated VCS relationship").SetInternal(err)+ }++ c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)+ if err := jsonapi.MarshalPayload(c.Response().Writer, updatedVCS); err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to marshal vcs ID response: %v", id)).SetInternal(err)+ }+ return nil+ })}func (s *Server) ComposeVCSRelationship(ctx context.Context, vcs *api.VCS, includeList []string) error {diff --git a/backend/store/migration/0001_init_schema.up.sql b/backend/store/migration/0001_init_schema.up.sqlindex 5b87469e9e..6f4669619d 100644--- a/backend/store/migration/0001_init_schema.up.sql+++ b/backend/store/migration/0001_init_schema.up.sql@@ -656,7 +656,9 @@ CREATE TABLE vcs (),application_id TEXT NOT NULL,secret TEXT NOT NULL,- access_token TEXT NOT NULL DEFAULT ''+ access_token TEXT NOT NULL DEFAULT '',+ access_token_expiration_ts BIGINT NOT NULL DEFAULT 0,+ refresh_token TEXT NOT NULL DEFAULT '');INSERT INTOdiff --git a/backend/store/vcs.go b/backend/store/vcs.goindex 74b1eaa373..5fca39acb2 100644--- a/backend/store/vcs.go+++ b/backend/store/vcs.go@@ -252,7 +252,13 @@ func patchVCS(ctx context.Context, tx *Tx, patch *api.VCSPatch) (*api.VCS, error// Build UPDATE clause.set, args := []string{"updater_id = ?"}, []interface{}{patch.UpdaterId}if v := patch.AccessToken; v != nil {- set, args = append(set, "access_token = ?"), append(args, api.Role(*v))+ set, args = append(set, "access_token = ?"), append(args, *v)+ }+ if v := patch.ExpireTs; v != nil {+ set, args = append(set, "access_token_expiration_ts = ?"), append(args, *v)+ }+ if v := patch.RefreshToken; v != nil {+ set, args = append(set, "refresh_token = ?"), append(args, *v)}args = append(args, patch.ID)diff --git a/frontend/src/components/VCSCard.vue b/frontend/src/components/VCSCard.vueindex a4f7331e73..0f0e4efc28 100644--- a/frontend/src/components/VCSCard.vue+++ b/frontend/src/components/VCSCard.vue@@ -12,7 +12,7 @@<div class="py-4 sm:py-5 sm:grid sm:grid-cols-3 sm:gap-4"><dt class="text-sm font-medium text-gray-500">Redirect URL</dt><dd class="mt-1 flex text-sm text-gray-900 sm:mt-0 sm:col-span-2">- <span class="flex-grow">{{ redirectURL(vcs) }}</span>+ <span class="flex-grow">{{ redirectURL() }}</span></dd></div><div class="py-4 sm:grid sm:py-5 sm:grid-cols-3 sm:gap-4">@@ -70,7 +70,7 @@<script lang="ts">import { reactive, PropType } from "vue";-import { VCS, redirectURL } from "../types";+import { VCS, redirectURL, oauthStateKey, OAuthState } from "../types";import { randomString } from "../utils";interface LocalState {}@@ -88,12 +88,19 @@ export default {const state = reactive<LocalState>({});const linkVCS = (vcs: VCS) => {+ // Set state in current session to prevent CSRFconst state = randomString(40);+ const oauthState: OAuthState = {+ resourceType: "VCS",+ resourceId: vcs.id,+ };+ sessionStorage.setItem(oauthStateKey(state), JSON.stringify(oauthState));+window.open(`${vcs.instanceURL}/oauth/authorize?client_id=${vcs.applicationId}&redirect_uri=${encodeURIComponent(- redirectURL(vcs)+ redirectURL())}&response_type=code&state=${state}`,"_blank");diff --git a/frontend/src/router/index.ts b/frontend/src/router/index.tsindex ff7fa60d80..4276b7d9eb 100644--- a/frontend/src/router/index.ts+++ b/frontend/src/router/index.ts@@ -64,6 +64,11 @@ const routes: Array<RouteRecordRaw> = [},],},+ {+ path: "/oauth/callback",+ name: "oauth-callback",+ component: () => import("../views/OAuthCallback.vue"),+ },{path: "/",component: DashboardLayout,@@ -672,6 +677,7 @@ router.beforeEach((to, from, next) => {to.name === "error.403" ||to.name === "error.404" ||to.name === "error.500" ||+ to.name === "oauth-callback" ||to.name === "workspace.home" ||to.name === "workspace.inbox" ||to.name === "workspace.project" ||diff --git a/frontend/src/store/modules/vcs.ts b/frontend/src/store/modules/vcs.tsindex c353609178..6ae8028f4e 100644--- a/frontend/src/store/modules/vcs.ts+++ b/frontend/src/store/modules/vcs.ts@@ -10,6 +10,7 @@ import {empty,EMPTY_ID,Principal,+ VCSTokenCreate,} from "../../types";function convert(@@ -116,7 +117,7 @@ const actions = {const data = (await axios.patch(`/api/vcs/${vcsId}`, {data: {- type: "vcsPatch",+ type: "VCSCreate",attributes: vcsPatch,},})@@ -139,6 +140,28 @@ const actions = {commit("deleteVCSById", vcsId);},++ async createVCSToken(+ { commit, rootGetters }: any,+ { vcsId, tokenCreate }: { vcsId: VCSId; tokenCreate: VCSTokenCreate }+ ) {+ const data = (+ await axios.post(`/api/vcs/${vcsId}/token`, {+ data: {+ type: "VCSTokenCreate",+ attributes: tokenCreate,+ },+ })+ ).data;+ const createdVCS = convert(data.data, data.included, rootGetters);++ commit("setVCSById", {+ vcsId: createdVCS.id,+ vcs: createdVCS,+ });++ return createdVCS;+ },};const mutations = {diff --git a/frontend/src/types/common.ts b/frontend/src/types/common.tsindex 45be805fb9..8c88428085 100644--- a/frontend/src/types/common.ts+++ b/frontend/src/types/common.ts@@ -313,7 +313,6 @@ export const unknown = (apiURL: "",applicationId: "",secret: "",- accessToken: "",};switch (type) {@@ -573,7 +572,6 @@ export const empty = (apiURL: "",applicationId: "",secret: "",- accessToken: "",};switch (type) {diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.tsindex 4bc3036fa3..f6a9813ce4 100644--- a/frontend/src/types/index.ts+++ b/frontend/src/types/index.ts@@ -20,4 +20,5 @@ export * from "./notification";export * from "./plan";export * from "./store";+export * from "./oauth";export * from "./jsonapi";diff --git a/frontend/src/types/oauth.ts b/frontend/src/types/oauth.tsnew file mode 100644index 0000000000..7724a2dc12--- /dev/null+++ b/frontend/src/types/oauth.ts@@ -0,0 +1,13 @@+import { VCSId } from "./id";++export type OAuthResourceType = "VCS";+export type OAuthResourceId = VCSId;++export type OAuthState = {+ resourceType: OAuthResourceType;+ resourceId: OAuthResourceId;+};++export function oauthStateKey(state: string): string {+ return "oauthstate." + state;+}diff --git a/frontend/src/types/vcs.ts b/frontend/src/types/vcs.tsindex 3e97258d12..a1e463300a 100644--- a/frontend/src/types/vcs.ts+++ b/frontend/src/types/vcs.ts@@ -28,7 +28,6 @@ export type VCS = {apiURL: string;applicationId: string;secret: string;- accessToken: string;};export type VCSCreate = {@@ -46,15 +45,17 @@ export type VCSCreate = {export type VCSPatch = {// Standard fieldsupdaterId: PrincipalId;+};- // Domain specific fields- accessToken: string;+export type VCSTokenCreate = {+ code: string;+ redirectURL: string;};export function isValidApplicationIdOrSecret(str: string): boolean {return /^[a-zA-Z0-9_]{64}$/.test(str);}-export function redirectURL(vcs: VCS): string {- return `https://bytebase.com/auth/${vcs.uuid}/callback`;+export function redirectURL(): string {+ return `${window.location.origin}/oauth/callback`;}diff --git a/frontend/src/views/OAuthCallback.vue b/frontend/src/views/OAuthCallback.vuenew file mode 100644index 0000000000..929193464c--- /dev/null+++ b/frontend/src/views/OAuthCallback.vue@@ -0,0 +1,64 @@+<template>+ <h1>OAuth callback</h1>+</template>++<script lang="ts">+import { useRouter } from "vue-router";+import { useStore } from "vuex";+import {+ OAuthState,+ oauthStateKey,+ redirectURL,+ VCSTokenCreate,+} from "../types";+export default {+ name: "OAuthCallback",+ components: {},+ props: {},+ setup(props, ctx) {+ const store = useStore();+ const router = useRouter();++ const item = router.currentRoute.value.query.state+ ? sessionStorage.getItem(+ oauthStateKey(router.currentRoute.value.query.state as string)+ )+ : undefined;+ if (!item) {+ store.dispatch("notification/pushNotification", {+ module: "bytebase",+ style: "CRITICAL",+ title: `Invalid state passed to the oauth callback`,+ });+ router.replace({+ name: "setting.workspace.version-control",+ });+ } else {+ const oauthState = JSON.parse(item) as OAuthState;+ if (+ !oauthState ||+ oauthState.resourceType != "VCS" ||+ !oauthState.resourceId+ ) {+ store.dispatch("notification/pushNotification", {+ module: "bytebase",+ style: "CRITICAL",+ title: `Invalid oauth session state`,+ });+ router.replace({+ name: "setting.workspace.version-control",+ });+ } else {+ const tokenCreate: VCSTokenCreate = {+ code: router.currentRoute.value.query.code as string,+ redirectURL: redirectURL(),+ };+ store.dispatch("vcs/createVCSToken", {+ vcsId: oauthState.resourceId,+ tokenCreate,+ });+ }+ }+ },+};+</script>