From 307c148fa7b6810b4b1a493c260d6b38a72482af Mon Sep 17 00:00:00 2001 From: Marius Schulz Date: Mon, 17 Jun 2024 16:10:25 +0200 Subject: [PATCH] Formatting --- cmd/cmd.go | 4 +- cmd/managedpolicies/cmd.go | 2 +- cmd/managedpolicies/diff.go | 16 ++-- cmd/managedpolicies/get.go | 4 +- cmd/managedpolicies/save.go | 182 ++++++++++++++++++------------------ pkg/policies/cloudspec.go | 2 +- pkg/policies/gcp.go | 90 +++++++++--------- pkg/policies/policy.go | 6 +- 8 files changed, 150 insertions(+), 156 deletions(-) diff --git a/cmd/cmd.go b/cmd/cmd.go index 2a1f63be..7b3c8770 100644 --- a/cmd/cmd.go +++ b/cmd/cmd.go @@ -98,7 +98,7 @@ func NewCmdRoot(streams genericclioptions.IOStreams) *cobra.Command { rootCmd.AddCommand(promote.NewCmdPromote()) rootCmd.AddCommand(jira.Cmd) rootCmd.AddCommand(cloudtrail.NewCloudtrailCmd()) - rootCmd.AddCommand(managedpolicies.NewCmdManagedPolicies()) + rootCmd.AddCommand(managedpolicies.NewCmdManagedPolicies()) // Add cost command to use AWS Cost Manager rootCmd.AddCommand(cost.NewCmdCost(streams, globalOpts)) @@ -123,7 +123,7 @@ func help(cmd *cobra.Command, _ []string) { // Checks if the version check should be run func shouldRunVersionCheck(skipVersionCheckFlag bool, commandName string) bool { - + // If either are true, then the version check should NOT run, hence negation return !(skipVersionCheckFlag || canCommandSkipVersionCheck(commandName)) } diff --git a/cmd/managedpolicies/cmd.go b/cmd/managedpolicies/cmd.go index a4654d30..196117d8 100644 --- a/cmd/managedpolicies/cmd.go +++ b/cmd/managedpolicies/cmd.go @@ -30,7 +30,7 @@ func NewCmdManagedPolicies() *cobra.Command { managedPoliciesCommand.AddCommand(newCmdGet()) managedPoliciesCommand.AddCommand(newCmdDiff()) - managedPoliciesCommand.AddCommand(newCmdSave()) + managedPoliciesCommand.AddCommand(newCmdSave()) return managedPoliciesCommand } diff --git a/cmd/managedpolicies/diff.go b/cmd/managedpolicies/diff.go index 5ee29c6b..eb0fad8c 100644 --- a/cmd/managedpolicies/diff.go +++ b/cmd/managedpolicies/diff.go @@ -10,16 +10,15 @@ import ( cmdutil "k8s.io/kubectl/pkg/cmd/util" ) - type diffOptions struct { - BaseVersion string + BaseVersion string TargetVersion string - Cloud policies.CloudSpec + Cloud policies.CloudSpec } const ( - baseVersionFlagName = "base-version" - targetVersionFlagName = "target-version" + baseVersionFlagName = "base-version" + targetVersionFlagName = "target-version" ) func newCmdDiff() *cobra.Command { @@ -30,7 +29,7 @@ func newCmdDiff() *cobra.Command { Args: cobra.ExactArgs(0), DisableAutoGenTag: true, Run: func(cmd *cobra.Command, args []string) { - ops.Cloud = *cmd.Flag(cloudFlagName).Value.(*policies.CloudSpec) + ops.Cloud = *cmd.Flag(cloudFlagName).Value.(*policies.CloudSpec) cmdutil.CheckErr(ops.run()) }, } @@ -44,13 +43,13 @@ func newCmdDiff() *cobra.Command { } func (o *diffOptions) run() error { - fmt.Fprintf(os.Stderr ,"Downloading Credential Requests for %s\n", o.BaseVersion) + fmt.Fprintf(os.Stderr, "Downloading Credential Requests for %s\n", o.BaseVersion) baseDir, err := policies.DownloadCredentialRequests(o.BaseVersion, o.Cloud) if err != nil { return err } - fmt.Fprintf(os.Stderr ,"Downloading Credential Requests for %s\n", o.TargetVersion) + fmt.Fprintf(os.Stderr, "Downloading Credential Requests for %s\n", o.TargetVersion) targetDir, err := policies.DownloadCredentialRequests(o.TargetVersion, o.Cloud) if err != nil { return err @@ -61,4 +60,3 @@ func (o *diffOptions) run() error { return nil } - diff --git a/cmd/managedpolicies/get.go b/cmd/managedpolicies/get.go index c1da4da2..25cdd12c 100644 --- a/cmd/managedpolicies/get.go +++ b/cmd/managedpolicies/get.go @@ -7,7 +7,6 @@ import ( cmdutil "k8s.io/kubectl/pkg/cmd/util" ) - type getOptions struct { ReleaseVersion string Cloud policies.CloudSpec @@ -21,7 +20,7 @@ func newCmdGet() *cobra.Command { Args: cobra.ExactArgs(0), DisableAutoGenTag: true, Run: func(cmd *cobra.Command, args []string) { - ops.Cloud = *cmd.Flag(cloudFlagName).Value.(*policies.CloudSpec) + ops.Cloud = *cmd.Flag(cloudFlagName).Value.(*policies.CloudSpec) cmdutil.CheckErr(ops.run()) }, } @@ -43,4 +42,3 @@ func (o *getOptions) run() error { return nil } - diff --git a/cmd/managedpolicies/save.go b/cmd/managedpolicies/save.go index 8a1709c4..23b4322c 100644 --- a/cmd/managedpolicies/save.go +++ b/cmd/managedpolicies/save.go @@ -14,109 +14,107 @@ import ( ) type saveOptions struct { - OutFolder string - ReleaseVersion string - Cloud policies.CloudSpec - Force bool + OutFolder string + ReleaseVersion string + Cloud policies.CloudSpec + Force bool } -func newCmdSave() *cobra.Command{ - ops := &saveOptions{} - - saveCmd := &cobra.Command{ - Use: "save", - Short: "Save managed policies for use in mcc", - Args: cobra.ExactArgs(0), - DisableAutoGenTag: true, - Run: func(cmd *cobra.Command, _ []string) { - ops.Cloud = *cmd.Flag(cloudFlagName).Value.(*policies.CloudSpec) - cmdutil.CheckErr(ops.run()) - }, - } +func newCmdSave() *cobra.Command { + ops := &saveOptions{} + + saveCmd := &cobra.Command{ + Use: "save", + Short: "Save managed policies for use in mcc", + Args: cobra.ExactArgs(0), + DisableAutoGenTag: true, + Run: func(cmd *cobra.Command, _ []string) { + ops.Cloud = *cmd.Flag(cloudFlagName).Value.(*policies.CloudSpec) + cmdutil.CheckErr(ops.run()) + }, + } - saveCmd.Flags().StringVarP(&ops.OutFolder, "dir", "d", "", "Folder where the policy files should be written") - saveCmd.Flags().StringVarP(&ops.ReleaseVersion, "release-version", "r", "", "ocp version for which the policies should be downloaded") - saveCmd.Flags().BoolVarP(&ops.Force, "force", "f", false, "Overwrite existing files") + saveCmd.Flags().StringVarP(&ops.OutFolder, "dir", "d", "", "Folder where the policy files should be written") + saveCmd.Flags().StringVarP(&ops.ReleaseVersion, "release-version", "r", "", "ocp version for which the policies should be downloaded") + saveCmd.Flags().BoolVarP(&ops.Force, "force", "f", false, "Overwrite existing files") - saveCmd.MarkFlagRequired("out") - saveCmd.MarkFlagRequired("release-version") + saveCmd.MarkFlagRequired("out") + saveCmd.MarkFlagRequired("release-version") - return saveCmd + return saveCmd } - func (o *saveOptions) run() error { - err := os.MkdirAll(o.OutFolder, 0755) - if err != nil { - return err - } + err := os.MkdirAll(o.OutFolder, 0755) + if err != nil { + return err + } directory, err := policies.DownloadCredentialRequests(o.ReleaseVersion, o.Cloud) if err != nil { return err } - - allCredentialsRequests, err := policies.ParseCredentialsRequestsInDir(directory) - if err != nil { - return err - } - - filesToCreate := map[string][]byte{} - - if o.Cloud == policies.AWS { - for _, credReq := range(allCredentialsRequests) { - polDoc, err := policies.AWSCredentialsRequestToPolicyDocument(credReq) - if err != nil { - return fmt.Errorf("Error parsing CredentialsRequest '%s': %w", credReq.Name, err) - } - - filename := filepath.Join(o.OutFolder, fmt.Sprintf("%s.json", credReq.Name)) - out, err := json.MarshalIndent(polDoc, "", " ") - if err != nil { - return fmt.Errorf("Coulnd't Marshal sts policy '%s': %w", credReq.Name , err) - } - - filesToCreate[filename] = out - } - } else if o.Cloud == policies.GCP { - for _, credReq := range(allCredentialsRequests) { - sa, err := policies.CredentialsRequestToWifServiceAccount(credReq) - if err != nil { - return fmt.Errorf("Error parsing CredentialsRequest '%s': %w", credReq.Name, err) - } - - filename := filepath.Join(o.OutFolder, fmt.Sprintf("%s.yaml", sa.Id)) - outJSON, err := json.Marshal(sa) - if err != nil { - return fmt.Errorf("Coulnd't Marshal wif ServiceAccount '%s': %w", sa.Id, err) - } - out, err := yaml.JSONToYAML(outJSON) - if err != nil { - return fmt.Errorf("Error Converting json to yaml: %w", err) - } - filesToCreate[filename] = out - } - } - - for path, content := range(filesToCreate) { - _, err := os.Stat(path) - - if err != nil && !errors.Is(err, os.ErrNotExist) { - return err - } - - if err == nil && !o.Force { - fmt.Printf("Cowardly refusing to overwrite: '%s'. Append '--force' to overwrite existing files.\n", path) - continue - } - - fmt.Printf("Writing %s\n", path) - if err = os.WriteFile(path, content, 0600); err != nil { - return err - } - - } - - return nil -} + allCredentialsRequests, err := policies.ParseCredentialsRequestsInDir(directory) + if err != nil { + return err + } + + filesToCreate := map[string][]byte{} + + if o.Cloud == policies.AWS { + for _, credReq := range allCredentialsRequests { + polDoc, err := policies.AWSCredentialsRequestToPolicyDocument(credReq) + if err != nil { + return fmt.Errorf("Error parsing CredentialsRequest '%s': %w", credReq.Name, err) + } + + filename := filepath.Join(o.OutFolder, fmt.Sprintf("%s.json", credReq.Name)) + out, err := json.MarshalIndent(polDoc, "", " ") + if err != nil { + return fmt.Errorf("Coulnd't Marshal sts policy '%s': %w", credReq.Name, err) + } + + filesToCreate[filename] = out + } + } else if o.Cloud == policies.GCP { + for _, credReq := range allCredentialsRequests { + sa, err := policies.CredentialsRequestToWifServiceAccount(credReq) + if err != nil { + return fmt.Errorf("Error parsing CredentialsRequest '%s': %w", credReq.Name, err) + } + + filename := filepath.Join(o.OutFolder, fmt.Sprintf("%s.yaml", sa.Id)) + outJSON, err := json.Marshal(sa) + if err != nil { + return fmt.Errorf("Coulnd't Marshal wif ServiceAccount '%s': %w", sa.Id, err) + } + out, err := yaml.JSONToYAML(outJSON) + if err != nil { + return fmt.Errorf("Error Converting json to yaml: %w", err) + } + filesToCreate[filename] = out + } + } + + for path, content := range filesToCreate { + _, err := os.Stat(path) + + if err != nil && !errors.Is(err, os.ErrNotExist) { + return err + } + + if err == nil && !o.Force { + fmt.Printf("Cowardly refusing to overwrite: '%s'. Append '--force' to overwrite existing files.\n", path) + continue + } + + fmt.Printf("Writing %s\n", path) + if err = os.WriteFile(path, content, 0600); err != nil { + return err + } + + } + + return nil +} diff --git a/pkg/policies/cloudspec.go b/pkg/policies/cloudspec.go index 4602ddf5..dbc043c5 100644 --- a/pkg/policies/cloudspec.go +++ b/pkg/policies/cloudspec.go @@ -30,7 +30,7 @@ func (e *CloudSpec) Set(v string) error { case "aws", "sts": *e = AWS return nil - case "gcp", "wif": + case "gcp", "wif": *e = GCP return nil default: diff --git a/pkg/policies/gcp.go b/pkg/policies/gcp.go index 4d3e7be8..28167791 100644 --- a/pkg/policies/gcp.go +++ b/pkg/policies/gcp.go @@ -9,54 +9,54 @@ import ( const GCPRoleIDPrefix = "roles/" func GetGcpProviderSpec(credReq *cco.CredentialsRequest) (*cco.GCPProviderSpec, error) { - provSpecObject := cco.GCPProviderSpec{} - err := cco.Codec.DecodeProviderSpec(credReq.Spec.ProviderSpec, &provSpecObject) - if err != nil { - return nil, err - } + provSpecObject := cco.GCPProviderSpec{} + err := cco.Codec.DecodeProviderSpec(credReq.Spec.ProviderSpec, &provSpecObject) + if err != nil { + return nil, err + } - return &provSpecObject, nil + return &provSpecObject, nil } func CredentialsRequestToWifServiceAccount(credReq *cco.CredentialsRequest) (*ServiceAccount, error) { - gcpSpec, err := GetGcpProviderSpec(credReq) - - if err != nil { - return nil, err - } - - sa := &ServiceAccount{} - sa.AccessMethod = "wif" - sa.CredentialRequest = CredentialRequest{ - SecretRef: SecretRef{ - Name: credReq.Spec.SecretRef.Name, - Namespace: credReq.Spec.SecretRef.Namespace, - }, - ServiceAccountNames: credReq.Spec.ServiceAccountNames, - } - - sa.Id = credReq.Name - sa.Kind = "ServiceAccount" - sa.OsdRole = strings.Replace(credReq.Name, "openshift", "operator", 1) - - sa.Roles = []Role{} - - for _ , predefinedRole := range gcpSpec.PredefinedRoles { - sa.Roles = append(sa.Roles,Role{ - Id: strings.TrimPrefix(predefinedRole, GCPRoleIDPrefix), - Kind: "Role", - Predefined: true, - }) - } - - if len(gcpSpec.Permissions) > 0 { - sa.Roles = append(sa.Roles,Role{ - Id: credReq.Name, - Kind: "Role", - Permissions: gcpSpec.Permissions, - Predefined: false, - }) - } - return sa, nil + gcpSpec, err := GetGcpProviderSpec(credReq) + + if err != nil { + return nil, err + } + + sa := &ServiceAccount{} + sa.AccessMethod = "wif" + sa.CredentialRequest = CredentialRequest{ + SecretRef: SecretRef{ + Name: credReq.Spec.SecretRef.Name, + Namespace: credReq.Spec.SecretRef.Namespace, + }, + ServiceAccountNames: credReq.Spec.ServiceAccountNames, + } + + sa.Id = credReq.Name + sa.Kind = "ServiceAccount" + sa.OsdRole = strings.Replace(credReq.Name, "openshift", "operator", 1) + + sa.Roles = []Role{} + + for _, predefinedRole := range gcpSpec.PredefinedRoles { + sa.Roles = append(sa.Roles, Role{ + Id: strings.TrimPrefix(predefinedRole, GCPRoleIDPrefix), + Kind: "Role", + Predefined: true, + }) + } + + if len(gcpSpec.Permissions) > 0 { + sa.Roles = append(sa.Roles, Role{ + Id: credReq.Name, + Kind: "Role", + Permissions: gcpSpec.Permissions, + Predefined: false, + }) + } + return sa, nil } diff --git a/pkg/policies/policy.go b/pkg/policies/policy.go index a0f5db72..572364d6 100644 --- a/pkg/policies/policy.go +++ b/pkg/policies/policy.go @@ -8,9 +8,9 @@ import ( "path/filepath" "strings" - k8syaml "k8s.io/apimachinery/pkg/util/yaml" "github.com/coreos/go-semver/semver" cco "github.com/openshift/cloud-credential-operator/pkg/apis/cloudcredential/v1" + k8syaml "k8s.io/apimachinery/pkg/util/yaml" ) // DownloadCredentialRequests creates a temp directory and extracts credential request @@ -29,9 +29,9 @@ func DownloadCredentialRequests(version string, cloud CloudSpec) (string, error) crs := fmt.Sprintf("oc adm release extract %s --credentials-requests --cloud=%s --to=%s", version, cloud.String(), directory) - output, err := exec.Command("bash", "-c", crs).CombinedOutput() //#nosec G204 -- Subprocess launched with variable + output, err := exec.Command("bash", "-c", crs).CombinedOutput() //#nosec G204 -- Subprocess launched with variable if err != nil { - return "", fmt.Errorf("failed to run command '%s': %w - Output: %s",crs, err, output) + return "", fmt.Errorf("failed to run command '%s': %w - Output: %s", crs, err, output) } return directory, nil