create_aws.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. package project_integration
  2. import (
  3. "net/http"
  4. "strings"
  5. "connectrpc.com/connect"
  6. porterv1 "github.com/porter-dev/api-contracts/generated/go/porter/v1"
  7. "github.com/porter-dev/porter/api/server/handlers"
  8. "github.com/porter-dev/porter/api/server/shared"
  9. "github.com/porter-dev/porter/api/server/shared/apierrors"
  10. "github.com/porter-dev/porter/api/server/shared/config"
  11. "github.com/porter-dev/porter/api/types"
  12. "github.com/porter-dev/porter/internal/models"
  13. ints "github.com/porter-dev/porter/internal/models/integrations"
  14. "github.com/porter-dev/porter/internal/telemetry"
  15. )
  16. type CreateAWSHandler struct {
  17. handlers.PorterHandlerReadWriter
  18. }
  19. func NewCreateAWSHandler(
  20. config *config.Config,
  21. decoderValidator shared.RequestDecoderValidator,
  22. writer shared.ResultWriter,
  23. ) *CreateAWSHandler {
  24. return &CreateAWSHandler{
  25. PorterHandlerReadWriter: handlers.NewDefaultPorterHandler(config, decoderValidator, writer),
  26. }
  27. }
  28. func (p *CreateAWSHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  29. ctx, span := telemetry.NewSpan(r.Context(), "serve-create-aws-integration")
  30. defer span.End()
  31. user, _ := ctx.Value(types.UserScope).(*models.User)
  32. project, _ := ctx.Value(types.ProjectScope).(*models.Project)
  33. request := &types.CreateAWSRequest{}
  34. if ok := p.DecodeAndValidate(w, r, request); !ok {
  35. err := telemetry.Error(ctx, span, nil, "error decoding request")
  36. p.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  37. return
  38. }
  39. aws := CreateAWSIntegration(request, project.ID, user.ID)
  40. aws, err := p.Repo().AWSIntegration().CreateAWSIntegration(aws)
  41. if err != nil {
  42. err = telemetry.Error(ctx, span, err, "error creating aws integration")
  43. p.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  44. return
  45. }
  46. res := types.CreateAWSResponse{
  47. AWSIntegration: aws.ToAWSIntegrationType(),
  48. }
  49. if project.GetFeatureFlag(models.CapiProvisionerEnabled, p.Config().LaunchDarklyClient) {
  50. telemetry.WithAttributes(span,
  51. telemetry.AttributeKV{Key: "target-arn", Value: request.TargetArn},
  52. telemetry.AttributeKV{Key: "external-id", Value: request.ExternalID},
  53. telemetry.AttributeKV{Key: "target-access-id", Value: request.AWSAccessKeyID},
  54. )
  55. if project.GetFeatureFlag(models.AWSACKAuthEnabled, p.Config().LaunchDarklyClient) {
  56. if request.TargetArn == "" {
  57. err = telemetry.Error(ctx, span, err, "target arn is required for AWS ACK auth")
  58. p.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest, "target arn is required for AWS ACK auth"))
  59. return
  60. }
  61. // if a user is changing the external ID, then we need to update the external ID for all projects that use that AWS account.
  62. // This is required since the same AWS account can be used across multiple projects. In order to change the external ID for a project,
  63. // the user must then have access to all projects that use that AWS account.
  64. // If we ever do a higher abstraction about porter projects, then we can tie the ability to access a cloud provider account to that higher abstraction.
  65. awsAccountIdPrefix := strings.TrimPrefix(request.TargetArn, "arn:aws:iam::")
  66. awsAccountId := strings.TrimSuffix(awsAccountIdPrefix, ":role/porter-manager")
  67. assumeRoles, err := p.Repo().AWSAssumeRoleChainer().ListByAwsAccountId(ctx, awsAccountId)
  68. if err != nil {
  69. err = telemetry.Error(ctx, span, err, "error listing assume role chains")
  70. p.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError, "error listing assume role chains"))
  71. return
  72. }
  73. requiredProjects := make(map[int]bool)
  74. for _, role := range assumeRoles {
  75. requiredProjects[role.ProjectID] = false
  76. }
  77. usersProject, err := p.Repo().Project().ListProjectsByUserID(user.ID)
  78. if err != nil {
  79. err = telemetry.Error(ctx, span, err, "error listing projects by user id")
  80. p.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError, "error listing projects by user id"))
  81. return
  82. }
  83. for _, project := range usersProject {
  84. if _, ok := requiredProjects[int(project.ID)]; ok {
  85. requiredProjects[int(project.ID)] = true
  86. }
  87. }
  88. for proj, required := range requiredProjects {
  89. if !required {
  90. err = telemetry.Error(ctx, span, err, "user does not have access to all projects that use this AWS account")
  91. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "missing-project", Value: proj})
  92. p.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusForbidden, "user does not have access to all projects that use this AWS account"))
  93. return
  94. }
  95. }
  96. credReq := porterv1.UpdateCloudProviderCredentialsRequest{
  97. ProjectId: int64(project.ID),
  98. CloudProvider: porterv1.EnumCloudProvider_ENUM_CLOUD_PROVIDER_AWS,
  99. CloudProviderCredentials: &porterv1.UpdateCloudProviderCredentialsRequest_AwsCredentials{
  100. AwsCredentials: &porterv1.AWSCredentials{
  101. TargetArn: request.TargetArn,
  102. ExternalId: request.ExternalID,
  103. },
  104. },
  105. }
  106. credResp, err := p.Config().ClusterControlPlaneClient.UpdateCloudProviderCredentials(ctx, connect.NewRequest(&credReq))
  107. if err != nil {
  108. err = telemetry.Error(ctx, span, err, "error updating AWS credential")
  109. p.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusPreconditionFailed, err.Error()))
  110. return
  111. }
  112. if credResp == nil {
  113. err = telemetry.Error(ctx, span, err, "error reading AWS credential response")
  114. p.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusPreconditionFailed, "response is nil"))
  115. return
  116. }
  117. if credResp.Msg == nil {
  118. err = telemetry.Error(ctx, span, err, "error reading AWS credential message")
  119. p.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusPreconditionFailed, "response message is nil"))
  120. return
  121. }
  122. res.CloudProviderCredentialIdentifier = credResp.Msg.CredentialsIdentifier
  123. res.PercentCompleted = credResp.Msg.PercentCompleted
  124. } else {
  125. credReq := porterv1.CreateAssumeRoleChainRequest{ //nolint:staticcheck // being deprecated by the above UpdateCloudProviderCredentials
  126. ProjectId: int64(project.ID),
  127. SourceArn: "arn:aws:iam::108458755588:role/CAPIManagement", // hard coded as this is the final hop for a CAPI cluster
  128. TargetAccessId: request.AWSAccessKeyID,
  129. TargetSecretKey: request.AWSSecretAccessKey,
  130. TargetArn: request.TargetArn,
  131. ExternalId: request.ExternalID,
  132. }
  133. credResp, err := p.Config().ClusterControlPlaneClient.CreateAssumeRoleChain(ctx, connect.NewRequest(&credReq)) //nolint:staticcheck // being deprecated by the above UpdateCloudProviderCredentials
  134. if err != nil {
  135. err = telemetry.Error(ctx, span, err, "error creating CAPI required credential")
  136. p.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusPreconditionFailed, err.Error()))
  137. return
  138. }
  139. res.CloudProviderCredentialIdentifier = credResp.Msg.TargetArn
  140. }
  141. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "cloud-provider-credential-identifier", Value: res.CloudProviderCredentialIdentifier})
  142. }
  143. p.WriteResult(w, r, res)
  144. }
  145. func CreateAWSIntegration(request *types.CreateAWSRequest, projectID, userID uint) *ints.AWSIntegration {
  146. resp := &ints.AWSIntegration{
  147. UserID: userID,
  148. ProjectID: projectID,
  149. AWSRegion: request.AWSRegion,
  150. AWSAssumeRoleArn: request.AWSAssumeRoleArn,
  151. AWSClusterID: []byte(request.AWSClusterID),
  152. AWSAccessKeyID: []byte(request.AWSAccessKeyID),
  153. AWSSecretAccessKey: []byte(request.AWSSecretAccessKey),
  154. }
  155. // attempt to populate the ARN
  156. resp.PopulateAWSArn()
  157. return resp
  158. }