Bladeren bron

refresh changes

Ivan Galakhov 4 jaren geleden
bovenliggende
commit
03c51f8628

+ 8 - 8
internal/forms/git_action.go

@@ -21,14 +21,14 @@ type CreateGitAction struct {
 // ToGitActionConfig converts the form to a gorm git action config model
 func (ca *CreateGitAction) ToGitActionConfig() (*models.GitActionConfig, error) {
 	return &models.GitActionConfig{
-		ReleaseID:      ca.ReleaseID,
-		GitRepo:        ca.GitRepo,
-		GitBranch:      ca.GitBranch,
-		ImageRepoURI:   ca.ImageRepoURI,
-		DockerfilePath: ca.DockerfilePath,
-		FolderPath:     ca.FolderPath,
-		GitRepoID:      ca.GitRepoID,
-		IsInstallation: true,
+		ReleaseID:            ca.ReleaseID,
+		GitRepo:              ca.GitRepo,
+		GitBranch:            ca.GitBranch,
+		ImageRepoURI:         ca.ImageRepoURI,
+		DockerfilePath:       ca.DockerfilePath,
+		FolderPath:           ca.FolderPath,
+		GithubInstallationID: ca.GitRepoID,
+		IsInstallation:       true,
 	}, nil
 }
 

+ 10 - 4
internal/integrations/ci/actions/actions.go

@@ -7,6 +7,7 @@ import (
 	"github.com/bradleyfalzon/ghinstallation"
 	"github.com/google/go-github/v33/github"
 	"github.com/porter-dev/porter/internal/models"
+	"github.com/porter-dev/porter/internal/oauth"
 	"github.com/porter-dev/porter/internal/repository"
 	"golang.org/x/crypto/nacl/box"
 	"golang.org/x/oauth2"
@@ -211,13 +212,18 @@ func (g *GithubActions) getClient() (*github.Client, error) {
 			return nil, err
 		}
 
-		tok := &oauth2.Token{
+		_, _, err = oauth.GetAccessToken(oauthInt.SharedOAuthModel, g.GithubConf, oauth.MakeUpdateOAuthIntegrationTokenFunction(oauthInt, g.Repo))
+
+		if err != nil {
+			return nil, err
+		}
+
+		client := github.NewClient(g.GithubConf.Client(oauth2.NoContext, &oauth2.Token{
 			AccessToken:  string(oauthInt.AccessToken),
 			RefreshToken: string(oauthInt.RefreshToken),
+			Expiry:       oauthInt.Expiry,
 			TokenType:    "Bearer",
-		}
-
-		client := github.NewClient(g.GithubConf.Client(oauth2.NoContext, tok))
+		}))
 
 		return client, nil
 	}

+ 2 - 2
internal/kubernetes/agent.go

@@ -991,7 +991,7 @@ func (a *Agent) ProvisionDOCR(
 		return nil, err
 	}
 
-	tok, _, err := oauth.GetAccessToken(oauthInt.AccessToken, oauthInt.RefreshToken, doAuth, oauth.MakeUpdateOAuthIntegrationTokenFunction(oauthInt, repo))
+	tok, _, err := oauth.GetAccessToken(oauthInt.SharedOAuthModel, doAuth, oauth.MakeUpdateOAuthIntegrationTokenFunction(oauthInt, repo))
 
 	if err != nil {
 		return nil, err
@@ -1043,7 +1043,7 @@ func (a *Agent) ProvisionDOKS(
 		return nil, err
 	}
 
-	tok, _, err := oauth.GetAccessToken(oauthInt.AccessToken, oauthInt.RefreshToken, doAuth, oauth.MakeUpdateOAuthIntegrationTokenFunction(oauthInt, repo))
+	tok, _, err := oauth.GetAccessToken(oauthInt.SharedOAuthModel, doAuth, oauth.MakeUpdateOAuthIntegrationTokenFunction(oauthInt, repo))
 
 	if err != nil {
 		return nil, err

+ 1 - 1
internal/kubernetes/config.go

@@ -339,7 +339,7 @@ func (conf *OutOfClusterConfig) CreateRawConfigFromCluster() (*api.Config, error
 			return nil, err
 		}
 
-		tok, _, err := oauth.GetAccessToken(oauthInt.AccessToken, oauthInt.RefreshToken, conf.DigitalOceanOAuth, oauth.MakeUpdateOAuthIntegrationTokenFunction(oauthInt, *conf.Repo))
+		tok, _, err := oauth.GetAccessToken(oauthInt.SharedOAuthModel, conf.DigitalOceanOAuth, oauth.MakeUpdateOAuthIntegrationTokenFunction(oauthInt, *conf.Repo))
 
 		if err != nil {
 			return nil, err

+ 3 - 3
internal/models/gitrepo.go

@@ -61,8 +61,8 @@ type GitActionConfig struct {
 	// The complete image repository uri to pull from
 	ImageRepoURI string `json:"image_repo_uri"`
 
-	// The git integration id
-	GitRepoID uint `json:"git_repo_id"`
+	// The git installation ID
+	GithubInstallationID uint `json:"git_repo_id"`
 
 	// The path to the dockerfile in the git repo
 	DockerfilePath string `json:"dockerfile_path"`
@@ -101,7 +101,7 @@ func (r *GitActionConfig) Externalize() *GitActionConfigExternal {
 		GitRepo:        r.GitRepo,
 		GitBranch:      r.GitBranch,
 		ImageRepoURI:   r.ImageRepoURI,
-		GitRepoID:      r.GitRepoID,
+		GitRepoID:      r.GithubInstallationID,
 		DockerfilePath: r.DockerfilePath,
 		FolderPath:     r.FolderPath,
 	}

+ 22 - 6
internal/oauth/config.go

@@ -4,6 +4,7 @@ import (
 	"context"
 	"crypto/rand"
 	"encoding/base64"
+	"fmt"
 	"github.com/porter-dev/porter/internal/models/integrations"
 	"github.com/porter-dev/porter/internal/repository"
 	"time"
@@ -108,18 +109,32 @@ func MakeUpdateOAuthIntegrationTokenFunction(o *integrations.OAuthIntegration, r
 	}
 }
 
+// MakeUpdateGithubAppOauthIntegrationFunction creates a function to be passed to GetAccessToken that updates the GithubAppOauthIntegration
+// if it needs to be updated
+func MakeUpdateGithubAppOauthIntegrationFunction(o *integrations.GithubAppOAuthIntegration, repo repository.Repository) func(accessToken []byte, refreshToken []byte, expiry time.Time) error {
+	return func(accessToken []byte, refreshToken []byte, expiry time.Time) error {
+		o.AccessToken = accessToken
+		o.RefreshToken = refreshToken
+		o.Expiry = expiry
+
+		_, err := repo.GithubAppOAuthIntegration.UpdateGithubAppOauthIntegration(o)
+
+		return err
+	}
+}
+
 // GetAccessToken retrieves an access token for a given client. It updates the
 // access token in the DB if necessary
 func GetAccessToken(
-	AccessToken []byte,
-	RefreshToken []byte,
+	prevToken integrations.SharedOAuthModel,
 	conf *oauth2.Config,
 	updateToken func(accessToken []byte, refreshToken []byte, expiry time.Time) error,
 ) (string, *time.Time, error) {
 	tokSource := conf.TokenSource(context.TODO(), &oauth2.Token{
-		AccessToken:  string(AccessToken),
-		RefreshToken: string(RefreshToken),
+		AccessToken:  string(prevToken.AccessToken),
+		RefreshToken: string(prevToken.RefreshToken),
 		TokenType:    "Bearer",
+		Expiry:       prevToken.Expiry,
 	})
 
 	token, err := tokSource.Token()
@@ -128,8 +143,9 @@ func GetAccessToken(
 		return "", nil, err
 	}
 
-	if token.AccessToken != string(AccessToken) {
-		err := updateToken(AccessToken, RefreshToken, token.Expiry)
+	if token.AccessToken != string(prevToken.AccessToken) {
+		fmt.Println("access happening...")
+		err := updateToken([]byte(token.AccessToken), []byte(token.RefreshToken), token.Expiry)
 
 		if err != nil {
 			return "", nil, err

+ 3 - 3
internal/registry/registry.go

@@ -226,7 +226,7 @@ func (r *Registry) listDOCRRepositories(
 		return nil, err
 	}
 
-	tok, _, err := oauth.GetAccessToken(oauthInt.AccessToken, oauthInt.RefreshToken, doAuth, oauth.MakeUpdateOAuthIntegrationTokenFunction(oauthInt, repo))
+	tok, _, err := oauth.GetAccessToken(oauthInt.SharedOAuthModel, doAuth, oauth.MakeUpdateOAuthIntegrationTokenFunction(oauthInt, repo))
 
 	if err != nil {
 		return nil, err
@@ -598,7 +598,7 @@ func (r *Registry) listDOCRImages(
 		return nil, err
 	}
 
-	tok, _, err := oauth.GetAccessToken(oauthInt.AccessToken, oauthInt.RefreshToken, doAuth, oauth.MakeUpdateOAuthIntegrationTokenFunction(oauthInt, repo))
+	tok, _, err := oauth.GetAccessToken(oauthInt.SharedOAuthModel, doAuth, oauth.MakeUpdateOAuthIntegrationTokenFunction(oauthInt, repo))
 
 	if err != nil {
 		return nil, err
@@ -919,7 +919,7 @@ func (r *Registry) getDOCRDockerConfigFile(
 		return nil, err
 	}
 
-	tok, _, err := oauth.GetAccessToken(oauthInt.AccessToken, oauthInt.RefreshToken, doAuth, oauth.MakeUpdateOAuthIntegrationTokenFunction(oauthInt, repo))
+	tok, _, err := oauth.GetAccessToken(oauthInt.SharedOAuthModel, doAuth, oauth.MakeUpdateOAuthIntegrationTokenFunction(oauthInt, repo))
 
 	if err != nil {
 		return nil, err

+ 4 - 4
internal/repository/gorm/git_action_config_test.go

@@ -20,10 +20,10 @@ func TestCreateGitActionConfig(t *testing.T) {
 	defer cleanup(tester, t)
 
 	ga := &models.GitActionConfig{
-		ReleaseID:    1,
-		GitRepo:      "porter-dev/porter",
-		ImageRepoURI: "gcr.io/project-123456/nginx",
-		GitRepoID:    1,
+		ReleaseID:            1,
+		GitRepo:              "porter-dev/porter",
+		ImageRepoURI:         "gcr.io/project-123456/nginx",
+		GithubInstallationID: 1,
 	}
 
 	expGA := *ga

+ 2 - 2
server/api/deploy_handler.go

@@ -352,7 +352,7 @@ func (app *App) HandleUninstallTemplate(w http.ResponseWriter, r *http.Request)
 
 				yaml.Unmarshal(rawValues, cEnv)
 
-				gr, err := app.Repo.GitRepo.ReadGitRepo(gitAction.GitRepoID)
+				gr, err := app.Repo.GitRepo.ReadGitRepo(gitAction.GithubInstallationID)
 
 				if err != nil {
 					if err != gorm.ErrRecordNotFound {
@@ -375,7 +375,7 @@ func (app *App) HandleUninstallTemplate(w http.ResponseWriter, r *http.Request)
 					ServerURL:              app.ServerConf.ServerURL,
 					GithubOAuthIntegration: gr,
 					GithubAppID:            app.GithubAppConf.AppID,
-					GithubInstallationID:   gitAction.GitRepoID,
+					GithubInstallationID:   gitAction.GithubInstallationID,
 					GitRepoName:            repoSplit[1],
 					GitRepoOwner:           repoSplit[0],
 					Repo:                   *app.Repo,

+ 5 - 19
server/api/integration_handler.go

@@ -7,7 +7,9 @@ import (
 	"encoding/hex"
 	"encoding/json"
 	"fmt"
+	"github.com/go-chi/chi"
 	"github.com/google/go-github/github"
+	"github.com/porter-dev/porter/internal/forms"
 	"github.com/porter-dev/porter/internal/oauth"
 	"golang.org/x/oauth2"
 	"gorm.io/gorm"
@@ -17,10 +19,6 @@ import (
 	"sort"
 	"strconv"
 	"strings"
-	"time"
-
-	"github.com/go-chi/chi"
-	"github.com/porter-dev/porter/internal/forms"
 
 	"github.com/porter-dev/porter/internal/models/integrations"
 	ints "github.com/porter-dev/porter/internal/models/integrations"
@@ -583,21 +581,9 @@ func (app *App) getGithubAppOauthTokenFromRequest(r *http.Request) (*oauth2.Toke
 		return nil, err
 	}
 
-	_, _, err = oauth.GetAccessToken(oauthInt.AccessToken, oauthInt.RefreshToken, &oauth2.Config{
-		ClientID:     app.GithubAppConf.ClientID,
-		ClientSecret: app.GithubAppConf.ClientSecret,
-		Endpoint:     app.GithubAppConf.Endpoint,
-		RedirectURL:  app.GithubAppConf.RedirectURL,
-		Scopes:       app.GithubAppConf.Scopes,
-	}, func(accessToken []byte, refreshToken []byte, expiry time.Time) error {
-		oauthInt.AccessToken = accessToken
-		oauthInt.RefreshToken = refreshToken
-		oauthInt.Expiry = expiry
-
-		_, err := app.Repo.GithubAppOAuthIntegration.UpdateGithubAppOauthIntegration(oauthInt)
-
-		return err
-	})
+	_, _, err = oauth.GetAccessToken(oauthInt.SharedOAuthModel,
+		&app.GithubAppConf.Config,
+		oauth.MakeUpdateGithubAppOauthIntegrationFunction(oauthInt, *app.Repo))
 
 	if err != nil {
 		return nil, err

+ 5 - 0
server/api/oauth_github_handler.go

@@ -334,6 +334,10 @@ func (app *App) HandleGithubAppOAuthCallback(w http.ResponseWriter, r *http.Requ
 		return
 	}
 
+	fmt.Println("exchange happaned")
+	fmt.Println(token.AccessToken)
+	fmt.Println(token.RefreshToken)
+
 	userID, err := app.getUserIDFromRequest(r)
 
 	if err != nil {
@@ -352,6 +356,7 @@ func (app *App) HandleGithubAppOAuthCallback(w http.ResponseWriter, r *http.Requ
 		SharedOAuthModel: integrations.SharedOAuthModel{
 			AccessToken:  []byte(token.AccessToken),
 			RefreshToken: []byte(token.RefreshToken),
+			Expiry:       token.Expiry,
 		},
 		UserID: user.ID,
 	}

+ 1 - 1
server/api/registry_handler.go

@@ -362,7 +362,7 @@ func (app *App) HandleGetProjectRegistryDOCRToken(w http.ResponseWriter, r *http
 				return
 			}
 
-			tok, expiry, err := oauth.GetAccessToken(oauthInt.AccessToken, oauthInt.RefreshToken, app.DOConf, oauth.MakeUpdateOAuthIntegrationTokenFunction(oauthInt, *app.Repo))
+			tok, expiry, err := oauth.GetAccessToken(oauthInt.SharedOAuthModel, app.DOConf, oauth.MakeUpdateOAuthIntegrationTokenFunction(oauthInt, *app.Repo))
 
 			if err != nil {
 				app.handleErrorDataRead(err, w)

+ 4 - 4
server/api/release_handler.go

@@ -937,7 +937,7 @@ func (app *App) HandleUpgradeRelease(w http.ResponseWriter, r *http.Request) {
 
 				yaml.Unmarshal([]byte(form.Values), cEnv)
 
-				gr, err := app.Repo.GitRepo.ReadGitRepo(gitAction.GitRepoID)
+				gr, err := app.Repo.GitRepo.ReadGitRepo(gitAction.GithubInstallationID)
 
 				if err != nil {
 					if err != gorm.ErrRecordNotFound {
@@ -952,7 +952,7 @@ func (app *App) HandleUpgradeRelease(w http.ResponseWriter, r *http.Request) {
 				gaRunner := &actions.GithubActions{
 					ServerURL:              app.ServerConf.ServerURL,
 					GithubOAuthIntegration: gr,
-					GithubInstallationID:   gitAction.GitRepoID,
+					GithubInstallationID:   gitAction.GithubInstallationID,
 					GithubAppID:            app.GithubAppConf.AppID,
 					GitRepoName:            repoSplit[1],
 					GitRepoOwner:           repoSplit[0],
@@ -1325,7 +1325,7 @@ func (app *App) HandleRollbackRelease(w http.ResponseWriter, r *http.Request) {
 
 				yaml.Unmarshal(rawValues, cEnv)
 
-				gr, err := app.Repo.GitRepo.ReadGitRepo(gitAction.GitRepoID)
+				gr, err := app.Repo.GitRepo.ReadGitRepo(gitAction.GithubInstallationID)
 
 				if err != nil {
 					if err != gorm.ErrRecordNotFound {
@@ -1347,7 +1347,7 @@ func (app *App) HandleRollbackRelease(w http.ResponseWriter, r *http.Request) {
 				gaRunner := &actions.GithubActions{
 					ServerURL:              app.ServerConf.ServerURL,
 					GithubOAuthIntegration: gr,
-					GithubInstallationID:   gitAction.GitRepoID,
+					GithubInstallationID:   gitAction.GithubInstallationID,
 					GithubAppID:            app.GithubAppConf.AppID,
 					GitRepoName:            repoSplit[1],
 					GitRepoOwner:           repoSplit[0],

+ 18 - 10
server/middleware/auth.go

@@ -6,6 +6,7 @@ import (
 	"encoding/json"
 	"errors"
 	"github.com/google/go-github/github"
+	"github.com/porter-dev/porter/internal/oauth"
 	"golang.org/x/oauth2"
 	"io/ioutil"
 	"net/http"
@@ -22,11 +23,11 @@ import (
 
 // Auth implements the authorization functions
 type Auth struct {
-	store             sessions.Store
-	cookieName        string
-	tokenConf         *token.TokenGeneratorConf
-	repo              *repository.Repository
-	GithubProjectConf *oauth2.Config
+	store         sessions.Store
+	cookieName    string
+	tokenConf     *token.TokenGeneratorConf
+	repo          *repository.Repository
+	GithubAppConf *oauth2.Config
 }
 
 // NewAuth returns a new Auth instance
@@ -35,9 +36,9 @@ func NewAuth(
 	cookieName string,
 	tokenConf *token.TokenGeneratorConf,
 	repo *repository.Repository,
-	GithubProjectConf *oauth2.Config,
+	GithubAppConf *oauth2.Config,
 ) *Auth {
-	return &Auth{store, cookieName, tokenConf, repo, GithubProjectConf}
+	return &Auth{store, cookieName, tokenConf, repo, GithubAppConf}
 }
 
 // BasicAuthenticate just checks that a user is logged in
@@ -408,8 +409,6 @@ func (auth *Auth) DoesUserHaveGitInstallationAccess(
 	gitRepoLoc IDLocation,
 ) http.Handler {
 	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
-		// TODO: needs to use new github integration implementation
-
 		grID, err := findGitInstallationIDInRequest(r, gitRepoLoc)
 
 		if err != nil {
@@ -454,7 +453,16 @@ func (auth *Auth) DoesUserHaveGitInstallationAccess(
 			return
 		}
 
-		client := github.NewClient(auth.GithubProjectConf.Client(oauth2.NoContext, &oauth2.Token{
+		_, _, err = oauth.GetAccessToken(oauthInt.SharedOAuthModel,
+			auth.GithubAppConf,
+			oauth.MakeUpdateGithubAppOauthIntegrationFunction(oauthInt, *auth.repo))
+
+		if err != nil {
+			http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
+			return
+		}
+
+		client := github.NewClient(auth.GithubAppConf.Client(oauth2.NoContext, &oauth2.Token{
 			AccessToken:  string(oauthInt.AccessToken),
 			RefreshToken: string(oauthInt.RefreshToken),
 			TokenType:    "Bearer",

+ 1 - 1
server/router/router.go

@@ -23,7 +23,7 @@ func New(a *api.App) *chi.Mux {
 
 	auth := mw.NewAuth(a.Store, a.ServerConf.CookieName, &token.TokenGeneratorConf{
 		TokenSecret: a.ServerConf.TokenGeneratorSecret,
-	}, a.Repo, a.GithubProjectConf)
+	}, a.Repo, &a.GithubAppConf.Config)
 
 	r.Route("/api", func(r chi.Router) {
 		r.Use(mw.ContentTypeJSON)