Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
Remove access_token, refresh_token in VCS
天舟d4cf5c67f955
diff --git a/backend/api/oauth.go b/backend/api/oauth.godeleted file mode 100644index 644671dc3a..0000000000--- a/backend/api/oauth.go+++ /dev/null@@ -1,8 +0,0 @@-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 f22cf559ea..8ced3a2e3f 100644--- a/backend/api/vcs.go+++ b/backend/api/vcs.go@@ -37,7 +37,6 @@ type VCS struct {ApiURL string `jsonapi:"attr,apiURL"`ApplicationId string `jsonapi:"attr,applicationId"`Secret string `jsonapi:"attr,secret"`- AccessToken string}type VCSCreate struct {@@ -73,11 +72,6 @@ type VCSPatch struct {// Standard fields// Value is assigned from the jwt subject field passed by the client.UpdaterId int-- // Domain specific fields- AccessToken *string- ExpireTs *int64- RefreshToken *string}type VCSDelete struct {@@ -88,16 +82,6 @@ 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 e7d1ac7a17..53fe0de26d 100644--- a/backend/server/acl_casbin_policy_owner.csv+++ b/backend/server/acl_casbin_policy_owner.csv@@ -46,5 +46,4 @@ p, OWNER, /vcs, GETp, OWNER, /vcs/{id}, GETp, OWNER, /vcs/{id}, PATCHp, OWNER, /vcs/{id}, DELETE-p, OWNER, /vcs/{id}/token, POSTp, OWNER, /vcs/{id}/repository, GETdiff --git a/backend/server/vcs.go b/backend/server/vcs.goindex 2c91d4cdad..5b9a4eb910 100644--- a/backend/server/vcs.go+++ b/backend/server/vcs.go@@ -1,11 +1,8 @@package serverimport (- "bytes""context"- "encoding/json""fmt"- "io/ioutil""net/http""strconv"@@ -149,100 +146,6 @@ func (s *Server) registerVCSRoutes(g *echo.Group) {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&redirect_uri=%s&grant_type=authorization_code",- 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- })-g.GET("/vcs/:vcsId/repository", func(c echo.Context) error {id, err := strconv.Atoi(c.Param("vcsId"))if err != nil {diff --git a/backend/store/migration/0001_init_schema.up.sql b/backend/store/migration/0001_init_schema.up.sqlindex 2ec8cbed54..4b49c25dc4 100644--- a/backend/store/migration/0001_init_schema.up.sql+++ b/backend/store/migration/0001_init_schema.up.sql@@ -653,10 +653,7 @@ CREATE TABLE vcs (OR api_url LIKE 'https:/%'),application_id TEXT NOT NULL,- secret TEXT NOT NULL,- access_token TEXT NOT NULL DEFAULT '',- access_token_expiration_ts BIGINT NOT NULL DEFAULT 0,- refresh_token TEXT NOT NULL DEFAULT ''+ secret TEXT NOT NULL);INSERT INTOdiff --git a/backend/store/seed/0160_vcs.sql b/backend/store/seed/0160_vcs.sqlindex 0857d5efd9..4db18eb546 100644--- a/backend/store/seed/0160_vcs.sql+++ b/backend/store/seed/0160_vcs.sql@@ -8,10 +8,7 @@ INSERT INTOinstance_url,api_url,application_id,- secret,- access_token,- access_token_expiration_ts,- refresh_token+ secret)VALUES(@@ -23,8 +20,5 @@ VALUES'http://gitlab.bytebase.com','http://gitlab.bytebase.com/api/v4','0d1f706e68e3bf22be6712752726a3eec2a9684ec098a9695015f484165ed922',- '77deb508304dd73fa9b6868d319e1832889c6fc8ea087f400e6efe35d7c6dd87',- '11f2e3a493cab3bafe56a5d8371ff1bd256c2a7386b005688c422313dcd215bf',- 0,- 'bba8a841ab2b60ba172ee0161152dd0b1f721726bbed801b5d91b1ec903a9e75'+ '77deb508304dd73fa9b6868d319e1832889c6fc8ea087f400e6efe35d7c6dd87');\ No newline at end of filediff --git a/backend/store/vcs.go b/backend/store/vcs.goindex deee40bdbc..077c81368a 100644--- a/backend/store/vcs.go+++ b/backend/store/vcs.go@@ -139,7 +139,7 @@ func createVCS(ctx context.Context, tx *Tx, create *api.VCSCreate) (*api.VCS, ersecret)VALUES (?, ?, ?, ?, ?, ?, ?, ?)- RETURNING id, creator_id, created_ts, updater_id, updated_ts, name, `+"`type`, instance_url, api_url, application_id, secret, access_token"+`+ RETURNING id, creator_id, created_ts, updater_id, updated_ts, name, `+"`type`, instance_url, api_url, application_id, secret"+``,create.CreatorId,create.CreatorId,@@ -170,7 +170,6 @@ func createVCS(ctx context.Context, tx *Tx, create *api.VCSCreate) (*api.VCS, er&vcs.ApiURL,&vcs.ApplicationId,&vcs.Secret,- &vcs.AccessToken,); err != nil {return nil, FormatError(err)}@@ -197,8 +196,7 @@ func findVCSList(ctx context.Context, tx *Tx, find *api.VCSFind) (_ []*api.VCS,instance_url,api_url,application_id,- secret,- access_token+ secretFROM vcsWHERE `+strings.Join(where, " AND "),args...,@@ -224,7 +222,6 @@ func findVCSList(ctx context.Context, tx *Tx, find *api.VCSFind) (_ []*api.VCS,&vcs.ApiURL,&vcs.ApplicationId,&vcs.Secret,- &vcs.AccessToken,); err != nil {return nil, FormatError(err)}@@ -242,16 +239,6 @@ func findVCSList(ctx context.Context, tx *Tx, find *api.VCSFind) (_ []*api.VCS,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, *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)// Execute update query with RETURNING.@@ -259,7 +246,7 @@ func patchVCS(ctx context.Context, tx *Tx, patch *api.VCSPatch) (*api.VCS, errorUPDATE vcsSET `+strings.Join(set, ", ")+`WHERE id = ?- RETURNING id, creator_id, created_ts, updater_id, updated_ts, name, `+"`type`, instance_url, api_url, application_id, secret, access_token"+`+ RETURNING id, creator_id, created_ts, updater_id, updated_ts, name, `+"`type`, instance_url, api_url, application_id, secret"+``,args...,)@@ -282,7 +269,6 @@ func patchVCS(ctx context.Context, tx *Tx, patch *api.VCSPatch) (*api.VCS, error&vcs.ApiURL,&vcs.ApplicationId,&vcs.Secret,- &vcs.AccessToken,); err != nil {return nil, FormatError(err)}diff --git a/frontend/src/components/VCSCard.vue b/frontend/src/components/VCSCard.vueindex fe5bfc8080..a184fe4bdc 100644--- a/frontend/src/components/VCSCard.vue+++ b/frontend/src/components/VCSCard.vue@@ -39,47 +39,14 @@<span class="flex-grow">{{ vcs.secret }}</span></dd></div>- <div class="py-4 sm:grid sm:py-5 sm:grid-cols-3 sm:gap-4">- <dt class="text-sm font-medium text-gray-500">OAuth Token</dt>- <dd class="mt-1 flex text-sm text-gray-900 sm:mt-0 sm:col-span-2">- <span class="flex-grow">{{ vcs.accessToken }}</span>- <span v-if="!vcs.accessToken" class="ml-4 flex-shrink-0">- <button- type="button"- class="- bg-white- rounded-md- font-medium- text-indigo-600- hover:text-indigo-500- focus:outline-none- focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500- "- @click.prevent="linkVCS"- >- <template v-if="vcs.type.startsWith('GITLAB')">- Link this GitLab instance- </template>- </button>- </span>- </dd>- </div></dl></div></template><script lang="ts">-import { reactive, PropType, onUnmounted } from "vue";+import { reactive, PropType } from "vue";import { useStore } from "vuex";-import {- VCS,- redirectURL,- OAuthWindowEvent,- OAuthWindowEventPayload,- openWindowForOAuth,- VCSTokenCreate,-} from "../types";-import isEmpty from "lodash-es/isEmpty";+import { VCS, redirectURL } from "../types";interface LocalState {}@@ -96,41 +63,11 @@ export default {const store = useStore();const state = reactive<LocalState>({});- const eventListener = (event: Event) => {- const payload = (event as CustomEvent).detail as OAuthWindowEventPayload;- if (isEmpty(payload.error)) {- const tokenCreate: VCSTokenCreate = {- code: payload.code,- redirectURL: redirectURL(),- };- store.dispatch("vcs/createVCSToken", {- vcsId: props.vcs.id,- tokenCreate,- });- } else {- }- };-store.dispatch("vcs/fetchRepositoryListByVCS", props.vcs);- onUnmounted(() => {- window.removeEventListener(OAuthWindowEvent, eventListener);- });-- const linkVCS = () => {- const newWindow = openWindowForOAuth(- `${props.vcs.instanceURL}/oauth/authorize`,- props.vcs.applicationId- );- if (newWindow) {- window.addEventListener(OAuthWindowEvent, eventListener, false);- }- };-return {state,redirectURL,- linkVCS,};},};diff --git a/frontend/src/store/modules/vcs.ts b/frontend/src/store/modules/vcs.tsindex 7cc26aee1d..485c3e2b19 100644--- a/frontend/src/store/modules/vcs.ts+++ b/frontend/src/store/modules/vcs.ts@@ -147,28 +147,6 @@ const actions = {commit("deleteVCSById", vcsId);},- async createVCSToken(- { commit }: 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);-- commit("setVCSById", {- vcsId: createdVCS.id,- vcs: createdVCS,- });-- return createdVCS;- },-async fetchRepositoryListByVCS({ commit }: any, vcs: VCS) {const repositoryList = (await axios.get(`/api/vcs/${vcs.id}/repository`)