...

Source file src/edge-infra.dev/pkg/sds/lib/ci/dsds-sandboxes/iampolicyclient.go

Documentation: edge-infra.dev/pkg/sds/lib/ci/dsds-sandboxes

     1  package dsdssandboxes
     2  
     3  import (
     4  	"context"
     5  	"strings"
     6  	"time"
     7  
     8  	crm "google.golang.org/api/cloudresourcemanager/v1"
     9  )
    10  
    11  var (
    12  	ownerRole = "roles/owner"
    13  )
    14  
    15  type IamPolicyClient struct {
    16  	getIamPolicy func(string, *crm.GetIamPolicyRequest) (*crm.Policy, error)
    17  }
    18  
    19  func NewIamPolicyClient() (*IamPolicyClient, error) {
    20  	ctx := context.Background()
    21  	crmService, err := crm.NewService(ctx)
    22  	if err != nil {
    23  		return nil, err
    24  	}
    25  
    26  	// Wrap crm service call in a closure to allow for mocking
    27  	fetchPolicyMethod := func(project string, request *crm.GetIamPolicyRequest) (*crm.Policy, error) {
    28  		return crmService.Projects.GetIamPolicy(project, request).Do()
    29  	}
    30  
    31  	return &IamPolicyClient{getIamPolicy: fetchPolicyMethod}, nil
    32  }
    33  
    34  // Return  list of users who have the owner role on a GCP project
    35  func (i *IamPolicyClient) GetProjectOwners(project string) ([]string, error) {
    36  	policy, err := i.getProjectPolicy(project)
    37  	if err != nil {
    38  		return nil, err
    39  	}
    40  
    41  	ownerList := ownersFromPolicy(policy)
    42  	return filterUsers(ownerList), nil
    43  }
    44  
    45  func (i *IamPolicyClient) getProjectPolicy(project string) (*crm.Policy, error) {
    46  	ctx := context.Background()
    47  
    48  	_, cancel := context.WithTimeout(ctx, time.Second*10)
    49  	defer cancel()
    50  	request := new(crm.GetIamPolicyRequest)
    51  
    52  	return i.getIamPolicy(project, request)
    53  }
    54  
    55  func ownersFromPolicy(policy *crm.Policy) []string {
    56  	ret := make([]string, 0)
    57  	for _, binding := range policy.Bindings {
    58  		if binding.Role == ownerRole {
    59  			ret = append(ret, binding.Members...)
    60  		}
    61  	}
    62  	return ret
    63  }
    64  
    65  func filterUsers(memberList []string) []string {
    66  	ret := make([]string, 0)
    67  	for _, member := range memberList {
    68  		if strings.HasPrefix(member, "user") {
    69  			ret = append(ret, member)
    70  		}
    71  	}
    72  	return ret
    73  }
    74  

View as plain text