github.com/openshift/installer@v1.4.17/pkg/destroy/gcp/policybinding.go (about) 1 package gcp 2 3 import ( 4 "context" 5 "fmt" 6 "strings" 7 8 "github.com/pkg/errors" 9 "github.com/sirupsen/logrus" 10 resourcemanager "google.golang.org/api/cloudresourcemanager/v3" 11 "k8s.io/apimachinery/pkg/util/sets" 12 ) 13 14 const ( 15 // projectNameFmt is the format string for project resource name. 16 projectNameFmt = "projects/%s" 17 ) 18 19 func (o *ClusterUninstaller) getProjectIAMPolicy(ctx context.Context) (*resourcemanager.Policy, error) { 20 o.Logger.Debug("Fetching project IAM policy") 21 ctx, cancel := context.WithTimeout(ctx, defaultTimeout) 22 defer cancel() 23 req := &resourcemanager.GetIamPolicyRequest{} 24 policy, err := o.rmSvc.Projects.GetIamPolicy(fmt.Sprintf(projectNameFmt, o.ProjectID), req).Context(ctx).Do() 25 if err != nil { 26 return nil, errors.Wrapf(err, "failed to fetch project IAM policy") 27 } 28 return policy, nil 29 } 30 31 func (o *ClusterUninstaller) setProjectIAMPolicy(ctx context.Context, policy *resourcemanager.Policy) error { 32 o.Logger.Debug("Setting project IAM policy") 33 ctx, cancel := context.WithTimeout(ctx, defaultTimeout) 34 defer cancel() 35 req := &resourcemanager.SetIamPolicyRequest{Policy: policy} 36 _, err := o.rmSvc.Projects.SetIamPolicy(fmt.Sprintf(projectNameFmt, o.ProjectID), req).Context(ctx).Do() 37 if err != nil { 38 return errors.Wrapf(err, "failed to set project IAM policy") 39 } 40 return nil 41 } 42 43 func (o *ClusterUninstaller) clearIAMPolicyBindings(policy *resourcemanager.Policy, emails sets.String, logger logrus.FieldLogger) bool { 44 removedBindings := false 45 for _, binding := range policy.Bindings { 46 members := []string{} 47 for _, member := range binding.Members { 48 email := policyMemberToEmail(member) 49 if emails.Has(email) { 50 logger.Debugf("IAM: removing %s from role %s", member, binding.Role) 51 removedBindings = true 52 continue 53 } 54 members = append(members, member) 55 } 56 binding.Members = members 57 } 58 return removedBindings 59 } 60 61 // policyMemberToEmail takes member of IAM policy binding and converts it to service account email. 62 // https://cloud.google.com/iam/docs/reference/rest/v1/Policy#Binding 63 // see members[] 64 func policyMemberToEmail(member string) string { 65 email := strings.TrimPrefix(strings.TrimPrefix(member, "deleted:"), "serviceAccount:") 66 if idx := strings.Index(email, "?uid"); idx != -1 { 67 email = email[:idx] 68 } 69 return email 70 }