Explorar o código

Merge branch 'master' into nafees/saml-sso-okta

Mohammed Nafees %!s(int64=3) %!d(string=hai) anos
pai
achega
bc79218db6

+ 2 - 1
.github/workflows/build-dev-cli.yaml

@@ -24,7 +24,8 @@ jobs:
         run: |
           DOCKER_BUILDKIT=1 docker build . \
             -t public.ecr.aws/o1j4x7p4/porter-cli:dev \
-            -f ./services/porter_cli_container/dev.Dockerfile
+            -f ./services/porter_cli_container/dev.Dockerfile \
+            --build-arg SENTRY_DSN=${{ secrets.SENTRY_DSN }}
       - name: Push
         run: |
           docker push public.ecr.aws/o1j4x7p4/porter-cli:dev

+ 45 - 0
.github/workflows/porter_preview_env.yml

@@ -0,0 +1,45 @@
+"on":
+  workflow_dispatch:
+    inputs:
+      pr_branch_from:
+        description: Pull request head branch
+        required: true
+        type: string
+      pr_branch_into:
+        description: Pull request base branch
+        required: true
+        type: string
+      pr_number:
+        description: Pull request number
+        required: true
+        type: string
+      pr_title:
+        description: Pull request title
+        required: true
+        type: string
+name: Porter Preview Environment
+jobs:
+  porter-preview:
+    runs-on: ubuntu-latest
+    steps:
+    - name: Checkout code
+      uses: actions/checkout@v2.3.4
+    - name: Create Porter preview env
+      timeout-minutes: 30
+      uses: porter-dev/porter-preview-action@v0.2.1
+      with:
+        action_id: ${{ github.run_id }}
+        cluster: "2481"
+        host: https://dashboard.getporter.dev
+        installation_id: "18533943"
+        namespace: pr-${{ github.event.inputs.pr_number }}-porter
+        pr_branch_from: ${{ github.event.inputs.pr_branch_from }}
+        pr_branch_into: ${{ github.event.inputs.pr_branch_into }}
+        pr_id: ${{ github.event.inputs.pr_number }}
+        pr_name: ${{ github.event.inputs.pr_title }}
+        project: "6680"
+        repo_name: porter
+        repo_owner: porter-dev
+        token: ${{ secrets.PORTER_PREVIEW_6680_2481 }}
+    concurrency:
+      group: ${{ github.workflow }}-${{ github.event.inputs.pr_number }}

+ 4 - 3
.github/workflows/prerelease.yaml

@@ -142,7 +142,7 @@ jobs:
           NODE_ENV: production
       - name: Build Linux binaries
         run: |
-          go build -ldflags="-w -s -X 'github.com/porter-dev/porter/cli/cmd/config.Version=${{steps.tag_name.outputs.tag}}'" -a -tags cli -o ./porter ./cli &
+          go build -ldflags="-w -s -X 'github.com/porter-dev/porter/cli/cmd/config.Version=${{steps.tag_name.outputs.tag}}' -X 'github.com/porter-dev/porter/cli/cmd/errors.SentryDSN=${{secrets.SENTRY_DSN}}'" -a -tags cli -o ./porter ./cli &
           go build -ldflags="-w -s -X 'main.Version=${{steps.tag_name.outputs.tag}}'" -a -o ./docker-credential-porter ./cmd/docker-credential-porter/ &
           go build -ldflags="-w -s -X 'main.Version=${{steps.tag_name.outputs.tag}}'" -a -tags ee -o ./portersvr ./cmd/app/ &
           wait
@@ -199,7 +199,7 @@ jobs:
           EOL
       - name: Build and Zip MacOS amd64 binaries
         run: |
-          go build -ldflags="-w -s -X 'github.com/porter-dev/porter/cli/cmd/config.Version=${{steps.tag_name.outputs.tag}}'" -a -tags cli -o ./amd64/porter ./cli &
+          go build -ldflags="-w -s -X 'github.com/porter-dev/porter/cli/cmd/config.Version=${{steps.tag_name.outputs.tag}}' -X 'github.com/porter-dev/porter/cli/cmd/errors.SentryDSN=${{secrets.SENTRY_DSN}}'" -a -tags cli -o ./amd64/porter ./cli &
           go build -ldflags="-w -s -X 'main.Version=${{steps.tag_name.outputs.tag}}'" -a -o ./amd64/docker-credential-porter ./cmd/docker-credential-porter/ &
           go build -ldflags="-w -s -X 'main.Version=${{steps.tag_name.outputs.tag}}'" -a -tags ee -o ./amd64/portersvr ./cmd/app/ &
           wait
@@ -462,7 +462,8 @@ jobs:
           docker build ./services/porter_cli_container \
             -t public.ecr.aws/o1j4x7p4/porter-cli:${{steps.tag_name.outputs.tag}} \
             -f ./services/porter_cli_container/Dockerfile \
-            --build-arg VERSION=${{steps.tag_name.outputs.tag}}
+            --build-arg VERSION=${{steps.tag_name.outputs.tag}} \
+            --build-arg SENTRY_DSN=${{secrets.SENTRY_DSN}}
       - name: Push
         run: |
           docker push public.ecr.aws/o1j4x7p4/porter-cli:${{steps.tag_name.outputs.tag}}

+ 1 - 0
.github/workflows/release.yaml

@@ -81,6 +81,7 @@ jobs:
           curl -L https://github.com/porter-dev/porter/releases/download/${version}/porter_${version}_Darwin_x86_64.zip --output $name
 
           sha=$(cat porter_${{steps.tag_name.outputs.tag}}_Darwin_x86_64.zip | openssl sha256 | sed 's/(stdin)= //g')
+          sha=${sha#"SHA256"}
 
           cat >porter.rb <<EOL
           class Porter < Formula

+ 5 - 4
Makefile

@@ -1,5 +1,6 @@
-BINDIR      := $(CURDIR)/bin
-VERSION ?= dev
+BINDIR     := $(CURDIR)/bin
+VERSION    ?= dev
+SENTRY_DSN ?= 
 
 start-dev: install setup-env-files
 	bash ./scripts/dev-environment/StartDevServer.sh
@@ -14,10 +15,10 @@ setup-env-files:
 	bash ./scripts/dev-environment/CreateDefaultEnvFiles.sh
 
 build-cli:
-	go build -ldflags="-w -s -X 'github.com/porter-dev/porter/cli/cmd/config.Version=${VERSION}'" -a -tags cli -o $(BINDIR)/porter ./cli
+	go build -ldflags="-w -s -X 'github.com/porter-dev/porter/cli/cmd/config.Version=${VERSION}' -X 'github.com/porter-dev/porter/cli/cmd/errors.SentryDSN=${SENTRY_DSN}'" -a -tags cli -o $(BINDIR)/porter ./cli
 
 build-cli-dev:
-	go build -ldflags="-X 'github.com/porter-dev/porter/cli/cmd/config.Version=${VERSION}'" -tags cli -o $(BINDIR)/porter ./cli
+	go build -ldflags="-X 'github.com/porter-dev/porter/cli/cmd/config.Version=${VERSION}' -X 'github.com/porter-dev/porter/cli/cmd/errors.SentryDSN=${SENTRY_DSN}'" -tags cli -o $(BINDIR)/porter ./cli
 
 start-provisioner-dev: install setup-env-files
 	bash ./scripts/dev-environment/StartProvisionerServer.sh

+ 1 - 1
api/client/registry.go

@@ -31,7 +31,7 @@ func (c *Client) CreateRegistry(
 func (c *Client) CreateHelmRepo(
 	ctx context.Context,
 	projectID uint,
-	req *types.CreateHelmRepoRequest,
+	req *types.CreateUpdateHelmRepoRequest,
 ) (*types.HelmRepo, error) {
 	resp := &types.HelmRepo{}
 

+ 121 - 1
api/server/handlers/environment/create.go

@@ -6,6 +6,7 @@ import (
 	"fmt"
 	"net/http"
 	"strings"
+	"sync"
 
 	"github.com/google/go-github/v41/github"
 	"github.com/porter-dev/porter/api/server/handlers"
@@ -19,6 +20,7 @@ import (
 	"github.com/porter-dev/porter/internal/integrations/ci/actions"
 	"github.com/porter-dev/porter/internal/models"
 	"github.com/porter-dev/porter/internal/models/integrations"
+	"gorm.io/gorm"
 )
 
 type CreateEnvironmentHandler struct {
@@ -209,9 +211,127 @@ func (c *CreateEnvironmentHandler) ServeHTTP(w http.ResponseWriter, r *http.Requ
 		}
 	}
 
-	c.WriteResult(w, r, env.ToEnvironmentType())
+	envType := env.ToEnvironmentType()
+
+	if len(envType.GitDeployBranches) > 0 && c.Config().ServerConf.EnableAutoPreviewBranchDeploy {
+		errs := autoDeployBranch(env, c.Config(), envType.GitDeployBranches, false)
+
+		if len(errs) > 0 {
+			errString := errs[0].Error()
+
+			for _, e := range errs {
+				errString += ": " + e.Error()
+			}
+
+			c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(
+				fmt.Errorf("error auto deploying preview branches: %s", errString), http.StatusConflict),
+			)
+			return
+		}
+	}
+
+	c.WriteResult(w, r, envType)
 }
 
 func getGithubWebhookURLFromUID(serverURL, webhookUID string) string {
 	return fmt.Sprintf("%s/api/github/incoming_webhook/%s", serverURL, string(webhookUID))
 }
+
+func autoDeployBranch(
+	env *models.Environment,
+	config *config.Config,
+	branches []string,
+	onlyNewDeployments bool,
+) []error {
+	var (
+		errs []error
+		wg   sync.WaitGroup
+	)
+
+	for _, branch := range branches {
+		wg.Add(1)
+
+		go func(errs []error, branch string) {
+			defer wg.Done()
+			errs = append(errs, createWorkflowDispatchForBranch(env, config, onlyNewDeployments, branch)...)
+		}(errs, branch)
+	}
+
+	wg.Wait()
+
+	return errs
+}
+
+func createWorkflowDispatchForBranch(
+	env *models.Environment,
+	config *config.Config,
+	onlyNewDeployments bool,
+	branch string,
+) []error {
+	var errs []error
+
+	client, err := getGithubClientFromEnvironment(config, env)
+
+	if err != nil {
+		errs = append(errs, err)
+		return errs
+	}
+
+	var deplID uint
+
+	depl, err := config.Repo.Environment().ReadDeploymentForBranch(env.ID, env.GitRepoOwner, env.GitRepoName, branch)
+
+	if err == nil {
+		if onlyNewDeployments {
+			return errs
+		}
+
+		deplID = depl.ID
+	} else {
+		if errors.Is(err, gorm.ErrRecordNotFound) {
+			depl, err := config.Repo.Environment().CreateDeployment(&models.Deployment{
+				EnvironmentID: env.ID,
+				Status:        types.DeploymentStatusCreating,
+				PRName:        fmt.Sprintf("Deployment for branch %s", branch),
+				RepoName:      env.GitRepoName,
+				RepoOwner:     env.GitRepoOwner,
+				PRBranchFrom:  branch,
+				PRBranchInto:  branch,
+			})
+
+			if err != nil {
+				errs = append(errs, fmt.Errorf("error creating deployment for branch %s: %w", branch, err))
+				return errs
+			}
+
+			deplID = depl.ID
+		} else {
+			errs = append(errs, fmt.Errorf("error reading deployment for branch %s: %w", branch, err))
+			return errs
+		}
+	}
+
+	if deplID == 0 {
+		errs = append(errs, fmt.Errorf("deployment id is 0 for branch %s", branch))
+		return errs
+	}
+
+	_, err = client.Actions.CreateWorkflowDispatchEventByFileName(
+		context.Background(), env.GitRepoOwner, env.GitRepoName, fmt.Sprintf("porter_%s_env.yml", env.Name),
+		github.CreateWorkflowDispatchEventRequest{
+			Ref: branch,
+			Inputs: map[string]interface{}{
+				"pr_number":      fmt.Sprintf("%d", deplID),
+				"pr_title":       fmt.Sprintf("Deployment for branch %s", branch),
+				"pr_branch_from": branch,
+				"pr_branch_into": branch,
+			},
+		},
+	)
+
+	if err != nil {
+		errs = append(errs, err)
+	}
+
+	return errs
+}

+ 1 - 1
api/server/handlers/environment/finalize_deployment_with_errors.go

@@ -125,7 +125,7 @@ func (c *FinalizeDeploymentWithErrorsHandler) ServeHTTP(w http.ResponseWriter, r
 	var lastErrors []string
 
 	for resName, errString := range request.Errors {
-		lastErrors = append(lastErrors, "%s: %s,", resName, errString)
+		lastErrors = append(lastErrors, fmt.Sprintf("%s: %s", resName, errString))
 	}
 
 	depl.LastErrors = strings.Join(lastErrors, ",")

+ 17 - 0
api/server/handlers/environment/update_environment_settings.go

@@ -133,6 +133,23 @@ func (c *UpdateEnvironmentSettingsHandler) ServeHTTP(w http.ResponseWriter, r *h
 		}
 
 		env.GitDeployBranches = strings.Join(request.GitDeployBranches, ",")
+
+		if len(request.GitDeployBranches) > 0 && c.Config().ServerConf.EnableAutoPreviewBranchDeploy {
+			errs := autoDeployBranch(env, c.Config(), request.GitDeployBranches, true)
+
+			if len(errs) > 0 {
+				errString := errs[0].Error()
+
+				for _, e := range errs {
+					errString += ": " + e.Error()
+				}
+
+				c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(
+					fmt.Errorf("error auto deploying preview branches: %s", errString), http.StatusConflict),
+				)
+				return
+			}
+		}
 	}
 
 	if request.DisableNewComments != env.NewCommentsDisabled {

+ 1 - 1
api/server/handlers/helmrepo/create.go

@@ -31,7 +31,7 @@ func NewHelmRepoCreateHandler(
 func (p *HelmRepoCreateHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
 	proj, _ := r.Context().Value(types.ProjectScope).(*models.Project)
 
-	request := &types.CreateHelmRepoRequest{}
+	request := &types.CreateUpdateHelmRepoRequest{}
 
 	ok := p.DecodeAndValidate(w, r, request)
 

+ 92 - 0
api/server/handlers/helmrepo/update.go

@@ -0,0 +1,92 @@
+package helmrepo
+
+import (
+	"errors"
+	"fmt"
+	"net/http"
+
+	"github.com/porter-dev/porter/api/server/handlers"
+	"github.com/porter-dev/porter/api/server/shared"
+	"github.com/porter-dev/porter/api/server/shared/apierrors"
+	"github.com/porter-dev/porter/api/server/shared/config"
+	"github.com/porter-dev/porter/api/server/shared/requestutils"
+	"github.com/porter-dev/porter/api/types"
+	"github.com/porter-dev/porter/internal/models"
+	"gorm.io/gorm"
+)
+
+type HelmRepoUpdateHandler struct {
+	handlers.PorterHandlerReadWriter
+}
+
+func NewHelmRepoUpdateHandler(
+	config *config.Config,
+	decoderValidator shared.RequestDecoderValidator,
+	writer shared.ResultWriter,
+) *HelmRepoUpdateHandler {
+	return &HelmRepoUpdateHandler{
+		PorterHandlerReadWriter: handlers.NewDefaultPorterHandler(config, decoderValidator, writer),
+	}
+}
+
+func (p *HelmRepoUpdateHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+	proj, _ := r.Context().Value(types.ProjectScope).(*models.Project)
+
+	helmRepoID, reqErr := requestutils.GetURLParamUint(r, "helm_repo_id")
+
+	if reqErr != nil {
+		p.HandleAPIError(w, r, reqErr)
+		return
+	}
+
+	helmRepo, err := p.Repo().HelmRepo().ReadHelmRepo(proj.ID, helmRepoID)
+
+	if err != nil {
+		if errors.Is(err, gorm.ErrRecordNotFound) {
+			p.HandleAPIError(w, r, apierrors.NewErrNotFound(fmt.Errorf("no such helm repo")))
+			return
+		}
+
+		p.HandleAPIError(w, r, apierrors.NewErrInternal(err))
+		return
+	}
+
+	request := &types.CreateUpdateHelmRepoRequest{}
+
+	ok := p.DecodeAndValidate(w, r, request)
+
+	if !ok {
+		return
+	}
+
+	// if a basic integration is specified, verify that it exists in the project
+	if request.BasicIntegrationID != 0 {
+		_, err := p.Repo().BasicIntegration().ReadBasicIntegration(proj.ID, request.BasicIntegrationID)
+
+		if err != nil {
+			if errors.Is(err, gorm.ErrRecordNotFound) {
+				p.HandleAPIError(w, r, apierrors.NewErrForbidden(
+					fmt.Errorf("basic integration with id %d not found in project %d", request.BasicIntegrationID, proj.ID),
+				))
+
+				return
+			}
+
+			p.HandleAPIError(w, r, apierrors.NewErrInternal(err))
+			return
+		}
+	}
+
+	helmRepo.Name = request.Name
+	helmRepo.RepoURL = request.URL
+	helmRepo.BasicAuthIntegrationID = request.BasicIntegrationID
+
+	helmRepo, err = p.Repo().HelmRepo().UpdateHelmRepo(helmRepo)
+
+	if err != nil {
+		p.HandleAPIError(w, r, apierrors.NewErrInternal(err))
+		return
+	}
+
+	p.WriteResult(w, r, helmRepo.ToHelmRepoType())
+}

+ 11 - 2
api/server/handlers/infra/forms.go

@@ -297,7 +297,7 @@ tabs:
           value: "12.7"
         - label: "v12.8"
           value: "12.8"
-          - label: "v12.9"
+        - label: "v12.9"
           value: "12.9"
         - label: "v12.10"
           value: "12.10"
@@ -471,7 +471,7 @@ tabs:
           value: m6i.4xlarge
         - label: r5.large
           value: r5.large
-        - value: r5.xlarge
+        - label: r5.xlarge
           value: r5.xlarge
     - type: string-input
       label: 👤 Issuer Email
@@ -758,6 +758,15 @@ tabs:
           value: t3.large
         - label: t3.xlarge
           value: t3.xlarge
+  - name: kms_secret_encryption
+    contents:
+    - type: heading
+      label: KMS Encryption
+    - type: checkbox
+      variable: is_kms_enabled
+      label: Encrypt all Kubernetes secrets with AWS Key Management Service (KMS)
+      settings:
+        default: false
 `
 
 const gcrForm = `name: GCR

+ 29 - 0
api/server/router/helm_repo.go

@@ -81,6 +81,35 @@ func getHelmRepoRoutes(
 		Router:   r,
 	})
 
+	// PATCH /api/projects/{project_id}/helmrepos/{helm_repo_id} -> registry.NewHelmRepoUpdateHandler
+	updateEndpoint := factory.NewAPIEndpoint(
+		&types.APIRequestMetadata{
+			Verb:   types.APIVerbUpdate,
+			Method: types.HTTPVerbPatch,
+			Path: &types.Path{
+				Parent:       basePath,
+				RelativePath: relPath,
+			},
+			Scopes: []types.PermissionScope{
+				types.UserScope,
+				types.ProjectScope,
+				types.HelmRepoScope,
+			},
+		},
+	)
+
+	updateHandler := helmrepo.NewHelmRepoUpdateHandler(
+		config,
+		factory.GetDecoderValidator(),
+		factory.GetResultWriter(),
+	)
+
+	routes = append(routes, &router.Route{
+		Endpoint: updateEndpoint,
+		Handler:  updateHandler,
+		Router:   r,
+	})
+
 	// DELETE /api/projects/{project_id}/helmrepos/{helm_repo_id} -> registry.NewHelmRepoDeleteHandler
 	deleteEndpoint := factory.NewAPIEndpoint(
 		&types.APIRequestMetadata{

+ 4 - 0
api/server/shared/config/env/envconfs.go

@@ -111,6 +111,10 @@ type ServerConf struct {
 	// imagePullSecrets into a kubernetes deployment (Porter application)
 	DisablePullSecretsInjection bool `env:"DISABLE_PULL_SECRETS_INJECTION,default=false"`
 
+	// EnableAutoPreviewBranchDeploy is used to enable preview branch deployments automatically
+	// The default behaviour is to automatically create preview deployment against a deploy branch
+	EnableAutoPreviewBranchDeploy bool `env:"ENABLE_AUTO_PREVIEW_BRANCH_DEPLOY,default=true"`
+
 	// DisableTemporaryKubeconfig is used to denote if Porter should not
 	// create a temporary kubeconfig file for a cluster. When set to true, the
 	// /api/projects/{project_id}/clusters/{cluster_id}/kubeconfig will be disabled.

+ 2 - 2
api/types/helm_repo.go

@@ -14,8 +14,8 @@ type HelmRepo struct {
 
 type GetHelmRepoResponse HelmRepo
 
-type CreateHelmRepoRequest struct {
-	URL                string `json:"url"`
+type CreateUpdateHelmRepoRequest struct {
+	URL                string `json:"url" form:"required"`
 	Name               string `json:"name" form:"required"`
 	BasicIntegrationID uint   `json:"basic_integration_id"`
 }

+ 1 - 1
cli/cmd/connect/helmrepo.go

@@ -77,7 +77,7 @@ Password:`)
 	reg, err := client.CreateHelmRepo(
 		context.Background(),
 		projectID,
-		&types.CreateHelmRepoRequest{
+		&types.CreateUpdateHelmRepoRequest{
 			URL:                repoURL,
 			Name:               repoName,
 			BasicIntegrationID: basicIntegrationID,

+ 3 - 1
cli/cmd/errors.go

@@ -10,6 +10,7 @@ import (
 	api "github.com/porter-dev/porter/api/client"
 	"github.com/porter-dev/porter/api/types"
 	"github.com/porter-dev/porter/cli/cmd/config"
+	cliErrors "github.com/porter-dev/porter/cli/cmd/errors"
 )
 
 var ErrNotLoggedIn error = errors.New("You are not logged in.")
@@ -52,7 +53,8 @@ func checkLoginAndRun(args []string, runner func(user *types.GetAuthenticatedUse
 			return nil
 		}
 
-		red.Fprintf(os.Stderr, "Error: %v\n", err.Error())
+		cliErrors.GetErrorHandler().HandleError(err)
+
 		return err
 	}
 

+ 52 - 0
cli/cmd/errors/error_handler.go

@@ -0,0 +1,52 @@
+package errors
+
+import (
+	"fmt"
+	"os"
+
+	"github.com/fatih/color"
+	"github.com/getsentry/sentry-go"
+	"github.com/porter-dev/porter/cli/cmd/config"
+)
+
+var SentryDSN string = ""
+
+type errorHandler interface {
+	HandleError(error)
+}
+
+type standardErrorHandler struct{}
+
+func (h *standardErrorHandler) HandleError(err error) {
+	color.New(color.FgRed).Fprintf(os.Stderr, "error: %s\n", err.Error())
+}
+
+type sentryErrorHandler struct{}
+
+func (h *sentryErrorHandler) HandleError(err error) {
+	if SentryDSN != "" {
+		localHub := sentry.CurrentHub().Clone()
+
+		localHub.ConfigureScope(func(scope *sentry.Scope) {
+			scope.SetTags(map[string]string{
+				"host":    config.GetCLIConfig().Host,
+				"project": fmt.Sprintf("%d", config.GetCLIConfig().Project),
+				"cluster": fmt.Sprintf("%d", config.GetCLIConfig().Cluster),
+			})
+		})
+
+		if eventID := localHub.CaptureException(err); eventID == nil {
+			color.New(color.FgRed).Fprintf(os.Stderr, "error in sending exception to sentry\n")
+		}
+	}
+
+	color.New(color.FgRed).Fprintf(os.Stderr, "error: %s\n", err.Error())
+}
+
+func GetErrorHandler() errorHandler {
+	if SentryDSN != "" {
+		return &sentryErrorHandler{}
+	}
+
+	return &standardErrorHandler{}
+}

+ 27 - 0
cli/main.go

@@ -1,11 +1,38 @@
+//go:build cli
 // +build cli
 
 package main
 
 import (
+	"os"
+	"time"
+
+	"github.com/fatih/color"
+	"github.com/getsentry/sentry-go"
 	"github.com/porter-dev/porter/cli/cmd"
+	"github.com/porter-dev/porter/cli/cmd/config"
+	"github.com/porter-dev/porter/cli/cmd/errors"
 )
 
 func main() {
+	if errors.SentryDSN != "" {
+		err := sentry.Init(sentry.ClientOptions{
+			Dsn:         errors.SentryDSN,
+			Environment: "cli",
+			Debug:       config.Version == "dev",
+			Release:     config.Version,
+			IgnoreErrors: []string{
+				"Forbidden",
+			},
+		})
+
+		if err != nil {
+			color.New(color.FgRed).Fprintf(os.Stderr, "error initialising sentry: %s\n", err)
+			os.Exit(1)
+		}
+
+		defer sentry.Flush(2 * time.Second)
+	}
+
 	cmd.Execute()
 }

+ 1 - 1
dashboard/src/components/porter-form/FormDebugger.tsx

@@ -61,7 +61,7 @@ export default class FormDebugger extends Component<PropsType, StateType> {
     try {
       formData = yaml.load(this.state.rawYaml);
     } catch (err: any) {
-      console.log("YAML parsing error.");
+      console.log("YAML parsing error.", err);
     }
     return (
       <StyledFormDebugger>

+ 3 - 1
dashboard/src/components/repo-selector/ActionDetails.tsx

@@ -137,10 +137,12 @@ const ActionDetails: React.FC<PropsType> = (props) => {
         />
       )}
       <InputRow
-        disabled={true}
+        // Currently there is a bug which is failing to detect the correct application folder root path. As a hotfix, we are enabling the user to manually set the application folder path.
+        disabled={false}
         label={dockerfilePath ? "Docker build context" : "Application folder"}
         type="text"
         width="100%"
+        setValue={(value) => typeof value === "string" && setFolderPath(value)}
         value={folderPath}
       />
       {renderRegistrySection()}

+ 2 - 2
dashboard/src/main/home/Home.tsx

@@ -435,9 +435,9 @@ class Home extends Component<PropsType, StateType> {
                 return <Onboarding />;
               }}
             />
-            {this.context.user.isPorterUser ||
+            {this.context?.user?.isPorterUser ||
             overrideInfraTabEnabled({
-              projectID: this.context.currentProject.id,
+              projectID: this.context?.currentProject?.id,
             }) ? (
               <Route
                 path="/infrastructure"

+ 10 - 1
dashboard/src/main/home/cluster-dashboard/expanded-chart/jobs/ConnectToJobInstructionsModal.tsx

@@ -1,5 +1,6 @@
 import Modal from "main/home/modals/Modal";
-import React from "react";
+import React, { useContext } from "react";
+import { Context } from "shared/Context";
 import { ChartType } from "shared/types";
 import styled from "styled-components";
 
@@ -8,6 +9,7 @@ const ConnectToJobInstructionsModal: React.FC<{
   onClose: () => void;
   chartName: string;
 }> = ({ show, chartName, onClose }) => {
+  const { currentCluster, currentProject } = useContext(Context);
   if (!show) {
     return null;
   }
@@ -27,6 +29,13 @@ const ConnectToJobInstructionsModal: React.FC<{
       ).
       <br />
       <br />
+      Run the following commands to set your current project and cluster
+      <Code>
+        porter config set-project {currentProject.id}
+        <br />
+        porter config set-cluster {currentCluster.id}
+      </Code>
+      <br />
       Run the following line of code, and make sure to change the command to
       something your container can run:
       <Code>porter run {chartName || "[APP-NAME]"} -- [COMMAND]</Code>

+ 10 - 32
dashboard/src/main/home/provisioner/AWSFormSection.tsx

@@ -83,6 +83,7 @@ const AWSFormSectionFC: React.FC<PropsType> = (props) => {
   const [selectedInfras, setSelectedInfras] = useState([...provisionOptions]);
   const [buttonStatus, setButtonStatus] = useState("");
   const [provisionConfirmed, setProvisionConfirmed] = useState(false);
+  const [eksUseKms, setEksUseKms] = useState(false);
   // This is added only for tracking purposes
   // With this prop we will track down if the user has had an intent of filling the formulary
   const [isFormDirty, setIsFormDirty] = useState(false);
@@ -217,6 +218,7 @@ const AWSFormSectionFC: React.FC<PropsType> = (props) => {
             cluster_name: clusterName,
             machine_type: awsMachineType,
             issuer_email: context.user.email,
+            is_kms_enabled: eksUseKms,
           },
         },
         { project_id: currentProject.id }
@@ -339,38 +341,6 @@ const AWSFormSectionFC: React.FC<PropsType> = (props) => {
           }}
           label="⚙️ AWS Machine Type"
         />
-        {/*
-        <Helper>
-          Estimated Cost:{" "}
-          <CostHighlight highlight={this.props.highlightCosts}>
-            {`\$${
-              70 + 3 * costMapping[this.state.awsMachineType] + 30
-            }/Month`}
-          </CostHighlight>
-          <Tooltip
-            title={
-              <div
-                style={{
-                  fontFamily: "Work Sans, sans-serif",
-                  fontSize: "12px",
-                  fontWeight: "normal",
-                  padding: "5px 6px",
-                }}
-              >
-                EKS cost: ~$70/month <br />
-                Machine (x3) cost: ~$
-                {`${3 * costMapping[this.state.awsMachineType]}`}/month <br />
-                Networking cost: ~$30/month
-              </div>
-            }
-            placement="top"
-          >
-            <StyledInfoTooltip>
-              <i className="material-icons">help_outline</i>
-            </StyledInfoTooltip>
-          </Tooltip>
-        </Helper>
-        */}
         <InputRow
           type="text"
           value={awsAccessId}
@@ -410,6 +380,14 @@ const AWSFormSectionFC: React.FC<PropsType> = (props) => {
           }}
         />
         {renderClusterNameSection()}
+        <CheckboxRow
+          checked={eksUseKms}
+          toggle={() => {
+            setIsFormDirty(true);
+            setEksUseKms(!eksUseKms);
+          }}
+          label="Enable secret encryption with AWS Key Management Service"
+        />
         <Helper>
           By default, Porter creates a cluster with three t2.medium instances
           (2vCPUs and 4GB RAM each). AWS will bill you for any provisioned

+ 153 - 149
docs/getting-started/aws.md

@@ -1,8 +1,9 @@
 # Quick Installation
+
 Porter runs on a Kubernetes cluster in your own AWS account. You can provision a cluster through Porter by inputting the credentials of your AWS IAM account. You can also delete all resources provided by Porter with one-click.
 
 > 🚧
-> 
+>
 > Quick Installation uses **AdministratorAccess** permissions to set up Porter. You can optionally specify the minimum IAM policies for provisioning a cluster and registry.
 
 <br />
@@ -19,7 +20,7 @@ Porter runs on a Kubernetes cluster in your own AWS account. You can provision a
 
 Optionally, if you don't want to grant Porter **AdministratorAccess**, you can follow these additional steps to configure the minimum required policy **(otherwise, skip to step 3).**
 
-To instead specify the minimum required policy, select **Attach existing policies directly**, and click on **Create Policy**. 
+To instead specify the minimum required policy, select **Attach existing policies directly**, and click on **Create Policy**.
 
 ![Minimum required policy attachment](https://files.readme.io/a1901d1-Screen_Shot_2021-02-16_at_4.55.06_PM.png "Screen Shot 2021-02-16 at 4.55.06 PM.png")
 
@@ -27,156 +28,159 @@ You will be prompted to enter your custom policy. Click on the **JSON** tab.
 
 ![Custom policy JSON](https://files.readme.io/c9b4d96-Screen_Shot_2021-02-16_at_5.00.00_PM.png "Screen Shot 2021-02-16 at 5.00.00 PM.png")
 
-Copy and paste the below JSON to the field. 
+Copy and paste the below JSON to the field.
 
 ```json
 {
-    "Version": "2012-10-17",
-    "Statement": [
-        {
-            "Sid": "VisualEditor0",
-            "Effect": "Allow",
-            "Action": [
-                "autoscaling:AttachInstances",
-                "autoscaling:CreateAutoScalingGroup",
-                "autoscaling:CreateLaunchConfiguration",
-                "autoscaling:CreateOrUpdateTags",
-                "autoscaling:DeleteAutoScalingGroup",
-                "autoscaling:DeleteLaunchConfiguration",
-                "autoscaling:DeleteTags",
-                "autoscaling:Describe*",
-                "autoscaling:DetachInstances",
-                "autoscaling:SetDesiredCapacity",
-                "autoscaling:UpdateAutoScalingGroup",
-                "autoscaling:SuspendProcesses",
-                "ec2:AllocateAddress",
-                "ec2:AssignPrivateIpAddresses",
-                "ec2:Associate*",
-                "ec2:AttachInternetGateway",
-                "ec2:AttachNetworkInterface",
-                "ec2:AuthorizeSecurityGroupEgress",
-                "ec2:AuthorizeSecurityGroupIngress",
-                "ec2:CreateDefaultSubnet",
-                "ec2:CreateDhcpOptions",
-                "ec2:CreateEgressOnlyInternetGateway",
-                "ec2:CreateInternetGateway",
-                "ec2:CreateNatGateway",
-                "ec2:CreateNetworkInterface",
-                "ec2:CreateRoute",
-                "ec2:CreateRouteTable",
-                "ec2:CreateSecurityGroup",
-                "ec2:CreateSubnet",
-                "ec2:CreateTags",
-                "ec2:CreateVolume",
-                "ec2:CreateVpc",
-                "ec2:CreateVpcEndpoint",
-                "ec2:DeleteDhcpOptions",
-                "ec2:DeleteEgressOnlyInternetGateway",
-                "ec2:DeleteInternetGateway",
-                "ec2:DeleteNatGateway",
-                "ec2:DeleteNetworkInterface",
-                "ec2:DeleteRoute",
-                "ec2:DeleteRouteTable",
-                "ec2:DeleteSecurityGroup",
-                "ec2:DeleteSubnet",
-                "ec2:DeleteTags",
-                "ec2:DeleteVolume",
-                "ec2:DeleteVpc",
-                "ec2:DeleteVpnGateway",
-                "ec2:Describe*",
-                "ec2:DetachInternetGateway",
-                "ec2:DetachNetworkInterface",
-                "ec2:DetachVolume",
-                "ec2:Disassociate*",
-                "ec2:ModifySubnetAttribute",
-                "ec2:ModifyVpcAttribute",
-                "ec2:ModifyVpcEndpoint",
-                "ec2:ReleaseAddress",
-                "ec2:RevokeSecurityGroupEgress",
-                "ec2:RevokeSecurityGroupIngress",
-                "ec2:UpdateSecurityGroupRuleDescriptionsEgress",
-                "ec2:UpdateSecurityGroupRuleDescriptionsIngress",
-                "ec2:CreateLaunchTemplate",
-                "ec2:CreateLaunchTemplateVersion",
-                "ec2:DeleteLaunchTemplate",
-                "ec2:DeleteLaunchTemplateVersions",
-                "ec2:DescribeLaunchTemplates",
-                "ec2:DescribeLaunchTemplateVersions",
-                "ec2:GetLaunchTemplateData",
-                "ec2:ModifyLaunchTemplate",
-                "ec2:RunInstances",
-                "eks:CreateCluster",
-                "eks:DeleteCluster",
-                "eks:DescribeCluster",
-                "eks:ListClusters",
-                "eks:UpdateClusterConfig",
-                "eks:UpdateClusterVersion",
-                "eks:DescribeUpdate",
-                "eks:TagResource",
-                "eks:UntagResource",
-                "eks:ListTagsForResource",
-                "eks:CreateFargateProfile",
-                "eks:DeleteFargateProfile",
-                "eks:DescribeFargateProfile",
-                "eks:ListFargateProfiles",
-                "eks:CreateNodegroup",
-                "eks:DeleteNodegroup",
-                "eks:DescribeNodegroup",
-                "eks:ListNodegroups",
-                "eks:UpdateNodegroupConfig",
-                "eks:UpdateNodegroupVersion",
-                "iam:AddRoleToInstanceProfile",
-                "iam:AttachRolePolicy",
-                "iam:CreateInstanceProfile",
-                "iam:CreateOpenIDConnectProvider",
-                "iam:CreateServiceLinkedRole",
-                "iam:CreatePolicy",
-                "iam:CreatePolicyVersion",
-                "iam:CreateRole",
-                "iam:DeleteInstanceProfile",
-                "iam:DeleteOpenIDConnectProvider",
-                "iam:DeletePolicy",
-                "iam:DeletePolicyVersion",
-                "iam:DeleteRole",
-                "iam:DeleteRolePolicy",
-                "iam:DeleteServiceLinkedRole",
-                "iam:DetachRolePolicy",
-                "iam:GetInstanceProfile",
-                "iam:GetOpenIDConnectProvider",
-                "iam:GetPolicy",
-                "iam:GetPolicyVersion",
-                "iam:GetRole",
-                "iam:GetRolePolicy",
-                "iam:List*",
-                "iam:PassRole",
-                "iam:PutRolePolicy",
-                "iam:RemoveRoleFromInstanceProfile",
-                "iam:TagOpenIDConnectProvider",
-                "iam:TagRole",
-                "iam:UntagRole",
-                "iam:UpdateAssumeRolePolicy",
-                "logs:CreateLogGroup",
-                "logs:DescribeLogGroups",
-                "logs:DeleteLogGroup",
-                "logs:ListTagsLogGroup",
-                "logs:PutRetentionPolicy",
-                "kms:CreateAlias",
-                "kms:CreateGrant",
-                "kms:CreateKey",
-                "kms:DeleteAlias",
-                "kms:DescribeKey",
-                "kms:GetKeyPolicy",
-                "kms:GetKeyRotationStatus",
-                "kms:ListAliases",
-                "kms:ListResourceTags",
-                "kms:ScheduleKeyDeletion"
-            ],
-            "Resource": "*"
-        }
-    ]
+  "Version": "2012-10-17",
+  "Statement": [
+    {
+      "Sid": "VisualEditor0",
+      "Effect": "Allow",
+      "Action": [
+        "autoscaling:AttachInstances",
+        "autoscaling:CreateAutoScalingGroup",
+        "autoscaling:CreateLaunchConfiguration",
+        "autoscaling:CreateOrUpdateTags",
+        "autoscaling:DeleteAutoScalingGroup",
+        "autoscaling:DeleteLaunchConfiguration",
+        "autoscaling:DeleteTags",
+        "autoscaling:Describe*",
+        "autoscaling:DetachInstances",
+        "autoscaling:SetDesiredCapacity",
+        "autoscaling:UpdateAutoScalingGroup",
+        "autoscaling:SuspendProcesses",
+        "ec2:AllocateAddress",
+        "ec2:AssignPrivateIpAddresses",
+        "ec2:Associate*",
+        "ec2:AttachInternetGateway",
+        "ec2:AttachNetworkInterface",
+        "ec2:AuthorizeSecurityGroupEgress",
+        "ec2:AuthorizeSecurityGroupIngress",
+        "ec2:CreateDefaultSubnet",
+        "ec2:CreateDhcpOptions",
+        "ec2:CreateEgressOnlyInternetGateway",
+        "ec2:CreateInternetGateway",
+        "ec2:CreateNatGateway",
+        "ec2:CreateNetworkInterface",
+        "ec2:CreateRoute",
+        "ec2:CreateRouteTable",
+        "ec2:CreateSecurityGroup",
+        "ec2:CreateSubnet",
+        "ec2:CreateTags",
+        "ec2:CreateVolume",
+        "ec2:CreateVpc",
+        "ec2:CreateVpcEndpoint",
+        "ec2:DeleteDhcpOptions",
+        "ec2:DeleteEgressOnlyInternetGateway",
+        "ec2:DeleteInternetGateway",
+        "ec2:DeleteNatGateway",
+        "ec2:DeleteNetworkInterface",
+        "ec2:DeleteRoute",
+        "ec2:DeleteRouteTable",
+        "ec2:DeleteSecurityGroup",
+        "ec2:DeleteSubnet",
+        "ec2:DeleteTags",
+        "ec2:DeleteVolume",
+        "ec2:DeleteVpc",
+        "ec2:DeleteVpnGateway",
+        "ec2:Describe*",
+        "ec2:DetachInternetGateway",
+        "ec2:DetachNetworkInterface",
+        "ec2:DetachVolume",
+        "ec2:Disassociate*",
+        "ec2:ModifySubnetAttribute",
+        "ec2:ModifyVpcAttribute",
+        "ec2:ModifyVpcEndpoint",
+        "ec2:ReleaseAddress",
+        "ec2:RevokeSecurityGroupEgress",
+        "ec2:RevokeSecurityGroupIngress",
+        "ec2:UpdateSecurityGroupRuleDescriptionsEgress",
+        "ec2:UpdateSecurityGroupRuleDescriptionsIngress",
+        "ec2:CreateLaunchTemplate",
+        "ec2:CreateLaunchTemplateVersion",
+        "ec2:DeleteLaunchTemplate",
+        "ec2:DeleteLaunchTemplateVersions",
+        "ec2:DescribeLaunchTemplates",
+        "ec2:DescribeLaunchTemplateVersions",
+        "ec2:GetLaunchTemplateData",
+        "ec2:ModifyLaunchTemplate",
+        "ec2:RunInstances",
+        "eks:CreateCluster",
+        "eks:DeleteCluster",
+        "eks:DescribeCluster",
+        "eks:ListClusters",
+        "eks:UpdateClusterConfig",
+        "eks:UpdateClusterVersion",
+        "eks:DescribeUpdate",
+        "eks:TagResource",
+        "eks:UntagResource",
+        "eks:ListTagsForResource",
+        "eks:CreateFargateProfile",
+        "eks:DeleteFargateProfile",
+        "eks:DescribeFargateProfile",
+        "eks:ListFargateProfiles",
+        "eks:CreateNodegroup",
+        "eks:DeleteNodegroup",
+        "eks:DescribeNodegroup",
+        "eks:ListNodegroups",
+        "eks:UpdateNodegroupConfig",
+        "eks:UpdateNodegroupVersion",
+        "iam:AddRoleToInstanceProfile",
+        "iam:AttachRolePolicy",
+        "iam:CreateInstanceProfile",
+        "iam:CreateOpenIDConnectProvider",
+        "iam:CreateServiceLinkedRole",
+        "iam:CreatePolicy",
+        "iam:CreatePolicyVersion",
+        "iam:CreateRole",
+        "iam:DeleteInstanceProfile",
+        "iam:DeleteOpenIDConnectProvider",
+        "iam:DeletePolicy",
+        "iam:DeletePolicyVersion",
+        "iam:DeleteRole",
+        "iam:DeleteRolePolicy",
+        "iam:DeleteServiceLinkedRole",
+        "iam:DetachRolePolicy",
+        "iam:GetInstanceProfile",
+        "iam:GetOpenIDConnectProvider",
+        "iam:GetPolicy",
+        "iam:GetPolicyVersion",
+        "iam:GetRole",
+        "iam:GetRolePolicy",
+        "iam:List*",
+        "iam:PassRole",
+        "iam:PutRolePolicy",
+        "iam:RemoveRoleFromInstanceProfile",
+        "iam:TagOpenIDConnectProvider",
+        "iam:TagRole",
+        "iam:UntagRole",
+        "iam:UpdateAssumeRolePolicy",
+        "logs:CreateLogGroup",
+        "logs:DescribeLogGroups",
+        "logs:DeleteLogGroup",
+        "logs:ListTagsLogGroup",
+        "logs:PutRetentionPolicy",
+        "kms:CreateAlias",
+        "kms:CreateGrant",
+        "kms:CreateKey",
+        "kms:DeleteAlias",
+        "kms:DescribeKey",
+        "kms:GetKeyPolicy",
+        "kms:GetKeyRotationStatus",
+        "kms:Get*",
+        "kms:ListAliases",
+        "kms:ListResourceTags",
+        "kms:ScheduleKeyDeletion"
+      ],
+      "Resource": "*"
+    }
+  ]
 }
 ```
 
+Note: `kms:Get*` is only required if you have enabled KMS secret encryption whilst creating the cluster
+
 Click on **Create a Policy** and give it a name to create a custom policy.
 
 Once you've created the custom policy, attach this policy to your IAM user along with the `AmazonEC2ContainerRegistryFullAccess` policy. Permission policies for your IAM user should look like the image below. In this example, the custom policy has been named **porter-minimum-permissions**.
@@ -200,7 +204,7 @@ After clicking **Create Project** from Porter, installation will begin automatic
 # Deleting Provisioned Resources
 
 > 🚧 AWS Deletion Instability
-> 
+>
 > Deleting resources on AWS via Porter may result in dangling resources. After clicking delete, please make sure to check your AWS console to see if all resources have properly been removed. You can remove any dangling resources via either the AWS console or the CLI.
 
 Because it is difficult to keep track of all the resources created by Porter, we recommend that you delete all provisioned resources through Porter. This will ensure that you do not get charged on AWS for lingering resources.
@@ -209,9 +213,9 @@ To delete resources, click on **Cluster Settings** from the **Cluster Dashboard*
 
 ![Delete cluster](https://files.readme.io/c1ed31a-Screen_Shot_2021-01-09_at_2.59.49_PM.png "Screen Shot 2021-01-09 at 2.59.49 PM.png")
 
-Click **Delete Cluster** to remove the cluster from Porter and delete resources in your AWS console. It may take up to 30 minutes for these resources to be deleted from your AWS console. 
+Click **Delete Cluster** to remove the cluster from Porter and delete resources in your AWS console. It may take up to 30 minutes for these resources to be deleted from your AWS console.
 
-**Note that you can only delete cluster resources that have been provisioned via Porter.** 
+**Note that you can only delete cluster resources that have been provisioned via Porter.**
 
 ![Delete cluster confirmation](https://files.readme.io/a7b36fc-Screen_Shot_2021-01-09_at_3.02.07_PM.png "Screen Shot 2021-01-09 at 3.02.07 PM.png")
 

+ 30 - 0
porter.yaml

@@ -0,0 +1,30 @@
+version: v2beta1
+
+builds:
+- name: porter
+  method: docker
+  dockerfile: ./docker/Dockerfile
+  env:
+    raw: {}
+    import_from:
+      - default/base-env
+
+apps:
+- name: porter-dashboard
+  depends_on:
+    - postgres
+  helm_chart:
+    name: web
+  build_ref: porter
+  helm_values: # refer https://github.com/porter-dev/porter-charts/blob/master/applications/web/values.yaml
+    container:
+      command: 
+    resources:
+      requests:
+        cpu: 400m
+        memory: 512Mi
+
+addons:
+- name: postgres
+  helm_chart:
+    name: postgres

+ 3 - 6
services/cli_install_script_container/install.sh

@@ -14,12 +14,9 @@ download_and_install() {
 
     echo "[INFO] Since the Porter CLI gets installed in /usr/local/bin, you may be asked to input your password."
 
-    name=$(curl -s https://api.github.com/repos/porter-dev/porter/releases/latest | grep "browser_download_url.*/porter_.*_${osname}_x86_64\.zip" | cut -d ":" -f 2,3 | tr -d \")
-    name=$(basename $name)
-
-    curl -L https://github.com/porter-dev/porter/releases/latest/download/$name --output $name
-    unzip -a $name
-    rm $name
+    curl -L $(curl -s https://api.github.com/repos/porter-dev/porter/releases/latest | grep "browser_download_url.*/porter_.*_${osname}_x86_64\.zip" | cut -d ":" -f 2,3 | tr -d \") --output porter.zip
+    unzip -a porter.zip
+    rm porter.zip
 
     chmod +x ./porter
     sudo mv ./porter /usr/local/bin/porter