Skip to content

Commit

Permalink
OCM-7415 | feat: Ensure account roles have expected attached policies
Browse files Browse the repository at this point in the history
Signed-off-by: marcolan018 <llan@redhat.com>
  • Loading branch information
marcolan018 committed May 9, 2024
1 parent da3615e commit 6545ca1
Show file tree
Hide file tree
Showing 8 changed files with 422 additions and 177 deletions.
232 changes: 87 additions & 145 deletions cmd/upgrade/roles/cmd.go

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions pkg/aws/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,8 @@ type Client interface {
GetSecurityGroupIds(vpcId string) ([]ec2types.SecurityGroup, error)
FetchPublicSubnetMap(subnets []ec2types.Subnet) (map[string]bool, error)
GetIAMServiceQuota(quotaCode string) (*servicequotas.GetServiceQuotaOutput, error)
GetAccountRoleDefaultPolicy(roleName string, prefix string) (string, error)
GetOperatorRoleDefaultPolicy(roleName string) (string, error)
}

type AccessKeyGetter interface {
Expand Down
51 changes: 19 additions & 32 deletions pkg/aws/commandbuilder/helper/roles/roles.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,17 +51,16 @@ func ManualCommandsForMissingOperatorRole(input ManualCommandsForMissingOperator
}

type ManualCommandsForUpgradeOperatorRolePolicyInput struct {
HasPolicy bool
OperatorRolePolicyPrefix string
Operator *cmv1.STSOperator
CredRequest string
OperatorPolicyPath string
PolicyARN string
DefaultPolicyVersion string
PolicyName string
HasDetachPolicyCommandsForExpectedPolicy bool
OperatorRoleName string
FileName string
HasPolicy bool
OperatorRolePolicyPrefix string
Operator *cmv1.STSOperator
CredRequest string
OperatorPolicyPath string
PolicyARN string
DefaultPolicyVersion string
PolicyName string
OperatorRoleName string
FileName string
}

func ManualCommandsForUpgradeOperatorRolePolicy(input ManualCommandsForUpgradeOperatorRolePolicyInput) []string {
Expand All @@ -83,14 +82,6 @@ func ManualCommandsForUpgradeOperatorRolePolicy(input ManualCommandsForUpgradeOp
Build()
commands = append(commands, createPolicy)
} else {
if input.HasDetachPolicyCommandsForExpectedPolicy {
attachRolePolicy := awscb.NewIAMCommandBuilder().
SetCommand(awscb.AttachRolePolicy).
AddParam(awscb.RoleName, input.OperatorRoleName).
AddParam(awscb.PolicyArn, input.PolicyARN).
Build()
commands = append(commands, attachRolePolicy)
}
policyTags := map[string]string{
common.OpenShiftVersion: input.DefaultPolicyVersion,
}
Expand All @@ -113,16 +104,15 @@ func ManualCommandsForUpgradeOperatorRolePolicy(input ManualCommandsForUpgradeOp
}

type ManualCommandsForUpgradeAccountRolePolicyInput struct {
DefaultPolicyVersion string
RoleName string
HasPolicy bool
Prefix string
File string
PolicyName string
AccountPolicyPath string
PolicyARN string
HasInlinePolicy bool
HasDetachPolicyCommandsForExpectedPolicy bool
DefaultPolicyVersion string
RoleName string
HasPolicy bool
Prefix string
File string
PolicyName string
AccountPolicyPath string
PolicyARN string
HasInlinePolicy bool
}

func ManualCommandsForUpgradeAccountRolePolicy(input ManualCommandsForUpgradeAccountRolePolicyInput) []string {
Expand Down Expand Up @@ -167,9 +157,6 @@ func ManualCommandsForUpgradeAccountRolePolicy(input ManualCommandsForUpgradeAcc
}
commands = append(commands, createPolicy, attachRolePolicy, tagRole)
} else {
if input.HasDetachPolicyCommandsForExpectedPolicy {
commands = append(commands, attachRolePolicy)
}
createPolicyVersion := awscb.NewIAMCommandBuilder().
SetCommand(awscb.CreatePolicyVersion).
AddParam(awscb.PolicyArn, input.PolicyARN).
Expand Down
30 changes: 30 additions & 0 deletions pkg/aws/mock_client.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

34 changes: 34 additions & 0 deletions pkg/aws/policies.go
Original file line number Diff line number Diff line change
Expand Up @@ -1955,6 +1955,40 @@ func (c *awsClient) ListAttachedRolePolicies(roleName string) ([]string, error)
return policies, nil
}

func (c *awsClient) GetAccountRoleDefaultPolicy(roleName string, prefix string) (string, error) {
policies, err := getAttachedPolicies(c.iamClient, roleName, getAcctRolePolicyTags(prefix))
if err != nil {
return "", err
}
if len(policies) == 0 {
return "", nil
}
if len(policies) > 1 {
return "", fmt.Errorf("There are more than one Red Hat managed account role policy attached to the role %s",
roleName)
}
return policies[0], nil
}

func (c *awsClient) GetOperatorRoleDefaultPolicy(roleName string) (string, error) {
tagfilter, err := getOperatorRolePolicyTags(c.iamClient, roleName)
if err != nil {
return "", nil
}
policies, err := getAttachedPolicies(c.iamClient, roleName, tagfilter)
if err != nil {
return "", err
}
if len(policies) == 0 {
return "", nil
}
if len(policies) > 1 {
return "", fmt.Errorf("There are more than one Red Hat managed operator role policy attached to the role %s",
roleName)
}
return policies[0], nil
}

func (c *awsClient) validateManagedPolicy(policies map[string]*cmv1.AWSSTSPolicy, policyKey string,
roleName string) error {
managedPolicyARN, err := GetManagedPolicyARN(policies, policyKey)
Expand Down
104 changes: 104 additions & 0 deletions pkg/helper/rolepolicybindings/helpers.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
/*
Copyright (c) 2024 Red Hat, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package rolepolicybindings

import (
"fmt"
"strings"

"slices"

cmv1 "github.com/openshift-online/ocm-sdk-go/clustersmgmt/v1"

"github.com/openshift/rosa/pkg/aws"
)

const (
RolePolicyBindingFailedStatus = "failed"
)

func CheckRolePolicyBindingStatus(bindings *cmv1.RolePolicyBindingList) error {
for _, binding := range bindings.Slice() {
if binding.Status().Value() == RolePolicyBindingFailedStatus {
return fmt.Errorf("Failed to get attach policies of role %s: %s",
binding.Name(), binding.Status().Description())
}
}
return nil
}

func CheckMissingRolePolicyBindings(desired, actual *cmv1.RolePolicyBindingList) (string, bool) {
output := ""
actualBindings := map[string][]string{}
for _, binding := range actual.Slice() {
roleBindings := []string{}
if binding != nil && binding.Policies() != nil {
for _, policy := range binding.Policies() {
roleBindings = append(roleBindings, policy.Arn())
}
}
actualBindings[binding.Name()] = roleBindings
}
missingBindings := map[string][]string{}
for _, binding := range desired.Slice() {
if binding == nil {
continue
}
for _, policy := range binding.Policies() {
if !slices.Contains(actualBindings[binding.Name()], policy.Arn()) {
if missingBindings[binding.Name()] == nil {
missingBindings[binding.Name()] = []string{policy.Arn()}
} else {
missingBindings[binding.Name()] = append(missingBindings[binding.Name()],
policy.Arn())
}
output = fmt.Sprintf(output+"Policy '%s' missed in role '%s'\n", policy.Arn(), binding.Name())
}
}
}
if len(missingBindings) == 0 {
return output, false
}
output = output + "Run the following commands to attach the missing policies:\n"
for roleName, policies := range missingBindings {
output = output + fmt.Sprintf("rosa attach policy --role-name %s --policy-arns %s --mode auto\n",
roleName, strings.Join(policies[:], ","))
}
return output, true
}

func TransformToRolePolicyDetails(bindingList *cmv1.RolePolicyBindingList) map[string][]aws.PolicyDetail {
rolePolicyDetails := map[string][]aws.PolicyDetail{}
for _, binding := range bindingList.Slice() {
policyDetails := []aws.PolicyDetail{}
if binding.Policies() != nil {
for _, policy := range binding.Policies() {
policyType := policy.Type()
if policyType != aws.Inline {
policyType = aws.Attached
}
policyDetails = append(policyDetails, aws.PolicyDetail{
PolicyName: policy.Name(),
PolicyArn: policy.Arn(),
PolicyType: policyType,
})
}
}
rolePolicyDetails[binding.Name()] = policyDetails
}
return rolePolicyDetails
}
112 changes: 112 additions & 0 deletions pkg/helper/rolepolicybindings/helpers_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
/*
Copyright (c) 2024 Red Hat, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package rolepolicybindings

import (
"fmt"
"testing"

. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
cmv1 "github.com/openshift-online/ocm-sdk-go/clustersmgmt/v1"

"github.com/openshift/rosa/pkg/aws"
)

func TestIdp(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "RolePolicyBinding")
}

var (
roleName1 = "sample-role-1"
roleName2 = "sample-role-2"
policyArn1 = "sample-policy-arn-1"
policyName1 = "sample-policy-name-1"
policyArn2 = "sample-policy-arn-2"
policyName2 = "sample-policy-name-2"
errDesc = "sample-err-description"
failedBinding = cmv1.NewRolePolicyBinding().
Name(roleName1).
Status(cmv1.NewRolePolicyBindingStatus().
Value(RolePolicyBindingFailedStatus).
Description(errDesc))
policyBuilder1 = cmv1.NewRolePolicy().Arn(policyArn1).Name(policyName1).Type(aws.Inline)
policyBuilder2 = cmv1.NewRolePolicy().Arn(policyArn2).Name(policyName2).Type("customer")
binding1 = cmv1.NewRolePolicyBinding().
Name(roleName1).
Policies(policyBuilder1)
actualBinding2 = cmv1.NewRolePolicyBinding().
Name(roleName2).
Policies(policyBuilder2)
desiredBinding2 = cmv1.NewRolePolicyBinding().
Name(roleName2).
Policies(policyBuilder1, policyBuilder2)
)

var _ = Describe("Policy Service", func() {
Context("Attach Policy", Ordered, func() {
It("Test ValidateRolePolicyBindings", func() {
bindingList, err := cmv1.NewRolePolicyBindingList().Items(failedBinding).Build()
Expect(err).ShouldNot(HaveOccurred())
err = CheckRolePolicyBindingStatus(bindingList)
Expect(err).Should(HaveOccurred())
Expect(err.Error()).To(Equal(fmt.Sprintf("Failed to get attach policies of role %s: %s",
roleName1, errDesc)))
})
It("Test CheckMissingRolePolicyBindings -- No missing rolepolicy binding", func() {
desiredBindings, err := cmv1.NewRolePolicyBindingList().Items(binding1).Build()
Expect(err).ShouldNot(HaveOccurred())
actualBindings, err := cmv1.NewRolePolicyBindingList().Items(binding1).Build()
Expect(err).ShouldNot(HaveOccurred())
output, isBindingMissed := CheckMissingRolePolicyBindings(desiredBindings, actualBindings)
Expect(isBindingMissed).To(Equal(false))
Expect(output).To(Equal(""))
})
It("Test CheckMissingRolePolicyBindings -- Find missing rolepolicy binding", func() {
desiredBindings, err := cmv1.NewRolePolicyBindingList().Items(binding1, desiredBinding2).Build()
Expect(err).ShouldNot(HaveOccurred())
actualBindings, err := cmv1.NewRolePolicyBindingList().Items(binding1, actualBinding2).Build()
Expect(err).ShouldNot(HaveOccurred())
output, isBindingMissed := CheckMissingRolePolicyBindings(desiredBindings, actualBindings)
Expect(isBindingMissed).To(Equal(true))
Expect(output).To(Equal(fmt.Sprintf("Policy '%s' missed in role '%s'\n"+
"Run the following commands to attach the missing policies:\n"+
"rosa attach policy --role-name %s --policy-arns %s --mode auto\n",
policyArn1, roleName2, roleName2, policyArn1)))
})
It("Test TransformToRolePolicyDetails", func() {
bindingList, err := cmv1.NewRolePolicyBindingList().Items(binding1, actualBinding2).Build()
Expect(err).ShouldNot(HaveOccurred())
rolePoliyDetails := TransformToRolePolicyDetails(bindingList)
Expect(rolePoliyDetails[roleName1]).NotTo(BeNil())
Expect(rolePoliyDetails[roleName1]).To(HaveLen(1))
Expect(rolePoliyDetails[roleName1][0]).To(BeEquivalentTo(aws.PolicyDetail{
PolicyName: policyName1,
PolicyArn: policyArn1,
PolicyType: aws.Inline,
}))
Expect(rolePoliyDetails[roleName2]).NotTo(BeNil())
Expect(rolePoliyDetails[roleName2]).To(HaveLen(1))
Expect(rolePoliyDetails[roleName2][0]).To(BeEquivalentTo(aws.PolicyDetail{
PolicyName: policyName2,
PolicyArn: policyArn2,
PolicyType: aws.Attached,
}))
})
})
})

0 comments on commit 6545ca1

Please sign in to comment.