Просмотр исходного кода

feat(gcp): enable organization checking

Before this commit, users could specify a hardcoded list of project IDs
to restrict access to the GCP provisioner. While this works, it can be
both toilsome to the team maintaining the Smallstep installation and
unintuitive to the internal infrastructure users that may encounter
errors as a result of their project not being added.

This commit is a rough attempt at adding support for validating that a
GCP project belongs to a given GCP organization. It does this by using
the `projects.getAncestry` call in the Cloud Resource Manager API. If
a token's project claim does not have the given organization ID as its
topmost ancestor, the token is rejected. This will require the
`resourcemanager.projects.get` IAM permission on the organization.

The new `OrganizationID` configuration directive is compatible with the
existing `ProjectIDs` configuration. If `ProjectIDs` is non-empty, it
will take precedence over the `OrganizationID` and act as it did before,
with the minor difference that if `OrganizationID` is also non-empty,
the provisioner will check the project's ancestry before rejecting the
token.

There are a couple outstanding questions and tasks after this commit. I
tried to strike the right balance between production-ready and
proof-of-concept here, so I'm open to any suggestions.

- Is the `authority/provisioner/gcp` package the right place for adding
  this functionality? Is the new struct the right approach?
- We should add tests for validating the organization ID.
- How should users configure the authentication for the Cloud Resource
  Manager client? I expect this would be similar to the Cloud KMS
  integration.
- Does Smallstep Professional run in an environment that will be able to
  authenticate with Google? We would need to either grant permissions to
  a Smallstep-owned Google service account if it's run in GCP, or set up
  something like Google's Workload Identity Federation to handle a K8s,
  AWS, or Azure deployment.
Eric Norris 1 год назад
Родитель
Сommit
a3db8de661

+ 23 - 15
authority/provisioner/gcp.go

@@ -20,6 +20,7 @@ import (
 	"go.step.sm/crypto/sshutil"
 	"go.step.sm/crypto/x509util"
 
+	"github.com/smallstep/certificates/authority/provisioner/gcp"
 	"github.com/smallstep/certificates/errs"
 	"github.com/smallstep/certificates/webhook"
 )
@@ -71,6 +72,12 @@ func newGCPConfig() *gcpConfig {
 	}
 }
 
+// projectValidator is an interface to enable testing without using
+// gcp.OrganizationProjectValidator.
+type projectValidator interface {
+	ValidateProject(ctx context.Context, projectID string) error
+}
+
 // GCP is the provisioner that supports identity tokens created by the Google
 // Cloud Platform metadata API.
 //
@@ -93,6 +100,7 @@ type GCP struct {
 	Name                   string   `json:"name"`
 	ServiceAccounts        []string `json:"serviceAccounts"`
 	ProjectIDs             []string `json:"projectIDs"`
+	OrganizationID         string   `json:"organizationID"`
 	DisableCustomSANs      bool     `json:"disableCustomSANs"`
 	DisableTrustOnFirstUse bool     `json:"disableTrustOnFirstUse"`
 	DisableSSHCAUser       *bool    `json:"disableSSHCAUser,omitempty"`
@@ -103,6 +111,7 @@ type GCP struct {
 	config                 *gcpConfig
 	keyStore               *keyStore
 	ctl                    *Controller
+	projectValidator       projectValidator
 }
 
 // GetID returns the provisioner unique identifier. The name should uniquely
@@ -233,14 +242,22 @@ func (p *GCP) Init(config Config) (err error) {
 	}
 
 	config.Audiences = config.Audiences.WithFragment(p.GetIDForToken())
-	p.ctl, err = NewController(p, p.Claims, config, p.Options)
+
+	if p.ctl, err = NewController(p, p.Claims, config, p.Options); err != nil {
+		return
+	}
+
+	if p.projectValidator, err = gcp.NewOrganizationValidator(context.Background(), p.ProjectIDs, p.OrganizationID); err != nil {
+		return
+	}
+
 	return
 }
 
 // AuthorizeSign validates the given token and returns the sign options that
 // will be used on certificate creation.
 func (p *GCP) AuthorizeSign(ctx context.Context, token string) ([]SignOption, error) {
-	claims, err := p.authorizeToken(token)
+	claims, err := p.authorizeToken(ctx, token)
 	if err != nil {
 		return nil, errs.Wrap(http.StatusInternalServerError, err, "gcp.AuthorizeSign")
 	}
@@ -315,7 +332,7 @@ func (p *GCP) assertConfig() {
 // authorizeToken performs common jwt authorization actions and returns the
 // claims for case specific downstream parsing.
 // e.g. a Sign request will auth/validate different fields than a Revoke request.
-func (p *GCP) authorizeToken(token string) (*gcpPayload, error) {
+func (p *GCP) authorizeToken(ctx context.Context, token string) (*gcpPayload, error) {
 	jwt, err := jose.ParseSigned(token)
 	if err != nil {
 		return nil, errs.Wrap(http.StatusUnauthorized, err, "gcp.authorizeToken; error parsing gcp token")
@@ -368,17 +385,8 @@ func (p *GCP) authorizeToken(token string) (*gcpPayload, error) {
 	}
 
 	// validate projects
-	if len(p.ProjectIDs) > 0 {
-		var found bool
-		for _, pi := range p.ProjectIDs {
-			if pi == claims.Google.ComputeEngine.ProjectID {
-				found = true
-				break
-			}
-		}
-		if !found {
-			return nil, errs.Unauthorized("gcp.authorizeToken; invalid gcp token - invalid project id")
-		}
+	if err := p.projectValidator.ValidateProject(ctx, claims.Google.ComputeEngine.ProjectID); err != nil {
+		return nil, err
 	}
 
 	// validate instance age
@@ -414,7 +422,7 @@ func (p *GCP) AuthorizeSSHSign(ctx context.Context, token string) ([]SignOption,
 		return nil, err
 	}
 
-	claims, err := p.authorizeToken(token)
+	claims, err := p.authorizeToken(ctx, token)
 	if err != nil {
 		return nil, errs.Wrap(http.StatusInternalServerError, err, "gcp.AuthorizeSSHSign")
 	}

+ 78 - 0
authority/provisioner/gcp/projectvalidator.go

@@ -0,0 +1,78 @@
+package gcp
+
+import (
+	"context"
+	"net/http"
+
+	"github.com/smallstep/certificates/errs"
+
+	"google.golang.org/api/cloudresourcemanager/v1"
+)
+
+type ProjectValidator struct {
+	ProjectIDs []string
+}
+
+func (p *ProjectValidator) ValidateProject(_ context.Context, projectID string) error {
+	if len(p.ProjectIDs) == 0 {
+		return nil
+	}
+
+	for _, pi := range p.ProjectIDs {
+		if pi == projectID {
+			return nil
+		}
+	}
+
+	return errs.Unauthorized("gcp.authorizeToken; invalid gcp token - invalid project id")
+}
+
+type OrganizationValidator struct {
+	*ProjectValidator
+
+	OrganizationID  string
+	projectsService *cloudresourcemanager.ProjectsService
+}
+
+func NewOrganizationValidator(ctx context.Context, projectIDs []string, organizationID string) (*OrganizationValidator, error) {
+	crm, err := cloudresourcemanager.NewService(ctx)
+
+	if err != nil {
+		return nil, err
+	}
+
+	return &OrganizationValidator{
+		&ProjectValidator{projectIDs},
+		organizationID,
+		crm.Projects,
+	}, nil
+}
+
+func (p *OrganizationValidator) ValidateProject(ctx context.Context, projectID string) error {
+	err := p.ProjectValidator.ValidateProject(ctx, projectID)
+
+	if p.OrganizationID == "" {
+		return err
+	}
+
+	ancestry, err := p.projectsService.
+		GetAncestry(projectID, &cloudresourcemanager.GetAncestryRequest{}).
+		Context(ctx).
+		Do()
+
+	if err != nil {
+		return errs.Wrap(http.StatusInternalServerError, err, "gcp.authorizeToken")
+	}
+
+	if len(ancestry.Ancestor) < 1 {
+		return errs.InternalServer("gcp.authorizeToken; getAncestry response malformed")
+	}
+
+	progenitor := ancestry.Ancestor[len(ancestry.Ancestor)-1]
+
+	if progenitor.ResourceId.Type != "organization" || progenitor.ResourceId.Id != p.OrganizationID {
+		return errs.Unauthorized("gcp.authorizeToken; invalid gcp token - project does not belong to organization")
+	}
+
+	return nil
+}

+ 18 - 0
authority/provisioner/gcp/projectvalidator_test.go

@@ -0,0 +1,18 @@
+package gcp
+
+import (
+	"context"
+	"testing"
+)
+
+func TestProjectValidator(t *testing.T) {
+	validator := &ProjectValidator{ProjectIDs: []string{"allowed-1", "allowed-2"}}
+
+	if err := validator.ValidateProject(context.Background(), "not-allowed"); err == nil {
+		t.Errorf("ProjectValidator.ValidateProject() = nil, want err")
+	}
+
+	if err := validator.ValidateProject(context.Background(), "allowed-2"); err != nil {
+		t.Errorf("ProjectValidator.ValidateProject() = %v, want nil", err)
+	}
+}

+ 4 - 3
authority/provisioner/gcp_test.go

@@ -21,6 +21,7 @@ import (
 
 	"github.com/smallstep/assert"
 	"github.com/smallstep/certificates/api/render"
+	"github.com/smallstep/certificates/authority/provisioner/gcp"
 )
 
 func TestGCP_Getters(t *testing.T) {
@@ -292,7 +293,7 @@ func TestGCP_authorizeToken(t *testing.T) {
 		"fail/invalid-projectID": func(t *testing.T) test {
 			p, err := generateGCP()
 			assert.FatalError(t, err)
-			p.ProjectIDs = []string{"foo", "bar"}
+			p.projectValidator = &gcp.ProjectValidator{ProjectIDs: []string{"foo", "bar"}}
 			tok, err := generateGCPToken(p.ServiceAccounts[0],
 				"https://accounts.google.com", p.GetID(),
 				"instance-id", "instance-name", "project-id", "zone",
@@ -398,7 +399,7 @@ func TestGCP_authorizeToken(t *testing.T) {
 	for name, tt := range tests {
 		t.Run(name, func(t *testing.T) {
 			tc := tt(t)
-			if claims, err := tc.p.authorizeToken(tc.token); err != nil {
+			if claims, err := tc.p.authorizeToken(context.Background(), tc.token); err != nil {
 				if assert.NotNil(t, tc.err) {
 					var sc render.StatusCodedError
 					assert.Fatal(t, errors.As(err, &sc), "error does not implement StatusCodedError interface")
@@ -430,7 +431,7 @@ func TestGCP_AuthorizeSign(t *testing.T) {
 
 	p3, err := generateGCP()
 	assert.FatalError(t, err)
-	p3.ProjectIDs = []string{"other-project-id"}
+	p3.projectValidator = &gcp.ProjectValidator{ProjectIDs: []string{"other-project-id"}}
 	p3.ServiceAccounts = []string{"foo@developer.gserviceaccount.com"}
 	p3.InstanceAge = Duration{1 * time.Minute}
 

+ 3 - 0
authority/provisioner/utils_test.go

@@ -21,6 +21,8 @@ import (
 	"go.step.sm/crypto/pemutil"
 	"go.step.sm/crypto/randutil"
 	"golang.org/x/crypto/ssh"
+
+	"github.com/smallstep/certificates/authority/provisioner/gcp"
 )
 
 var (
@@ -374,6 +376,7 @@ func generateGCP() (*GCP, error) {
 			keySet: jose.JSONWebKeySet{Keys: []jose.JSONWebKey{*jwk}},
 			expiry: time.Now().Add(24 * time.Hour),
 		},
+		projectValidator: &gcp.ProjectValidator{},
 	}
 	p.ctl, err = NewController(p, p.Claims, Config{
 		Audiences: testAudiences.WithFragment("gcp/" + name),