diff --git a/.golangci.yaml b/.golangci.yaml index c7ca4c2..1f1a377 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -1,23 +1,8 @@ issues: exclude-rules: - linters: - - errcheck - - forbidigo - - gci - - gocritic - gosec - - misspell - - unparam - - unused - - nilerr - nilnil - - staticcheck - - dupword - - noctx - - predeclared - - unconvert - - usestdlibvars - - gosimple text: ".*" linters: # Explicitly define all enabled linters diff --git a/cmd/cmd.go b/cmd/cmd.go index 7b2881b..619beb8 100644 --- a/cmd/cmd.go +++ b/cmd/cmd.go @@ -21,11 +21,11 @@ import ( "fmt" "io" + logf "github.com/cert-manager/cert-manager/pkg/logs" "github.com/spf13/cobra" "k8s.io/cli-runtime/pkg/genericclioptions" "k8s.io/component-base/logs" - logf "github.com/cert-manager/cert-manager/pkg/logs" "github.com/cert-manager/cmctl/v2/pkg/build" "github.com/cert-manager/cmctl/v2/pkg/build/commands" ) diff --git a/internal/versionchecker/test/testdata/fetch.go b/internal/versionchecker/test/testdata/fetch.go index 0dbf7fb..04a2ddd 100644 --- a/internal/versionchecker/test/testdata/fetch.go +++ b/internal/versionchecker/test/testdata/fetch.go @@ -44,9 +44,10 @@ const dummyVersion = "v99.99.99" func main() { ctx := context.Background() + stdOut := os.Stdout if len(os.Args) != 3 && len(os.Args) != 4 { - fmt.Printf("Usage: %s []\n", os.Args[0]) + fmt.Fprintf(stdOut, "Usage: %s []\n", os.Args[0]) os.Exit(1) } @@ -62,21 +63,21 @@ func main() { // Read the inventory file var inv Inventory if err := inv.read(manifestsPath); err != nil { - fmt.Printf("Error reading inventory: %v\n", err) + fmt.Fprintf(stdOut, "Error reading inventory: %v\n", err) inv.reset() } // If the passed version is identical to the latest version, we don't need to do anything if inv.LatestVersion == maxVersion && !force { - fmt.Printf("Version %s is already the latest version\n", maxVersion) + fmt.Fprintf(stdOut, "Version %s is already the latest version\n", maxVersion) os.Exit(0) } // Fetch the list of remote versions remoteVersions, err := listVersions(ctx, maxVersion) if err != nil { - fmt.Printf("Error listing versions: %v\n", err) + fmt.Fprintf(stdOut, "Error listing versions: %v\n", err) os.Exit(1) } @@ -119,7 +120,7 @@ func main() { } if err := group.Wait(); err != nil { - fmt.Printf("Error downloading manifests: %v\n", err) + fmt.Fprintf(stdOut, "Error downloading manifests: %v\n", err) os.Exit(1) } @@ -128,7 +129,7 @@ func main() { for result := range results { hash, err := manifestHash(result.manifest) if err != nil { - fmt.Printf("Error hashing manifest: %v\n", err) + fmt.Fprintf(stdOut, "Error hashing manifest: %v\n", err) os.Exit(1) } @@ -141,11 +142,11 @@ func main() { // Write the inventory file if err := inv.write(manifestsPath); err != nil { - fmt.Printf("Error writing inventory: %v\n", err) + fmt.Fprintf(stdOut, "Error writing inventory: %v\n", err) os.Exit(1) } - fmt.Printf("Updated inventory to version %s\n", maxVersion) + fmt.Fprintf(stdOut, "Updated inventory to version %s\n", maxVersion) } type Inventory struct { @@ -272,7 +273,7 @@ func (inv *Inventory) write(manifestsPath string) error { manifests = append(manifests, versionManifest{ versions: versions, - manifest: []byte(manifest), + manifest: manifest, }) } @@ -347,7 +348,7 @@ func listVersions(ctx context.Context, maxVersion string) (map[string]struct{}, func downloadManifests(ctx context.Context, version string) ([]byte, error) { url := fmt.Sprintf(downloadURL, version) - req, err := http.NewRequestWithContext(ctx, "GET", url, nil) + req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) if err != nil { return nil, err } @@ -375,20 +376,20 @@ func cleanupManifests(manifests []byte, version string) ([]byte, error) { decoder := yaml.NewDecoder(bytes.NewBuffer(manifests)) for { - var spec map[string]interface{} + var manifest map[string]interface{} - err := decoder.Decode(&spec) + err := decoder.Decode(&manifest) if errors.Is(err, io.EOF) { break } if err != nil { return nil, fmt.Errorf("failed to decode manifest: %v", err) } - if spec == nil { + if manifest == nil { continue } - kind, ok := spec["kind"].(string) + kind, ok := manifest["kind"].(string) if !ok { return nil, fmt.Errorf("kind is missing from manifest") } @@ -396,15 +397,15 @@ func cleanupManifests(manifests []byte, version string) ([]byte, error) { switch kind { case "CustomResourceDefinition": // remove all CRD schemas from yaml file - switch spec["spec"].(type) { + switch spec := manifest["spec"].(type) { case map[string]interface{}: - spec["spec"].(map[string]interface{})["versions"] = []interface{}{} + spec["versions"] = []interface{}{} case map[interface{}]interface{}: - spec["spec"].(map[interface{}]interface{})["versions"] = []interface{}{} + spec["versions"] = []interface{}{} } // remove status from CRD - delete(spec, "status") + delete(manifest, "status") case "Service", "Deployment": // keep only the CRD, Service and Deployment resources from yaml file @@ -412,7 +413,7 @@ func cleanupManifests(manifests []byte, version string) ([]byte, error) { continue } - yamlData, err := yaml.Marshal(spec) + yamlData, err := yaml.Marshal(manifest) if err != nil { return nil, fmt.Errorf("failed to marshal manifest: %v", err) } diff --git a/internal/versionchecker/test/versionchecker_test.go b/internal/versionchecker/test/versionchecker_test.go index 7e2977a..240d40d 100644 --- a/internal/versionchecker/test/versionchecker_test.go +++ b/internal/versionchecker/test/versionchecker_test.go @@ -19,7 +19,6 @@ package versionchecker import ( "bytes" "context" - _ "embed" "errors" "fmt" "io" @@ -38,6 +37,8 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client/fake" "github.com/cert-manager/cmctl/v2/internal/versionchecker" + + _ "embed" ) const dummyVersion = "v99.99.99" diff --git a/internal/versionchecker/versionchecker.go b/internal/versionchecker/versionchecker.go index 392c53f..3c5d2cc 100644 --- a/internal/versionchecker/versionchecker.go +++ b/internal/versionchecker/versionchecker.go @@ -46,10 +46,6 @@ type Version struct { Sources map[string]string `json:"sources"` } -func shouldReturn(err error) bool { - return (err == nil) || (!errors.Is(err, ErrVersionNotDetected)) -} - // Interface is used to check what cert-manager version is installed type Interface interface { Version(context.Context) (*Version, error) @@ -127,7 +123,7 @@ func (o *VersionChecker) Version(ctx context.Context) (*Version, error) { // Display both. err = fmt.Errorf("%v: %v", detectionError, err) } else if detectionError != nil { - // An error occured while trying to reduce the found versions to 1 version + // An error occurred while trying to reduce the found versions to 1 version err = detectionError } diff --git a/main.go b/main.go index e47a162..34f9c45 100644 --- a/main.go +++ b/main.go @@ -23,10 +23,10 @@ import ( "runtime" "strings" + logf "github.com/cert-manager/cert-manager/pkg/logs" cmdutil "k8s.io/kubectl/pkg/cmd/util" ctrl "sigs.k8s.io/controller-runtime" - logf "github.com/cert-manager/cert-manager/pkg/logs" ctlcmd "github.com/cert-manager/cmctl/v2/cmd" "github.com/cert-manager/cmctl/v2/internal/util" ) diff --git a/pkg/approve/approve.go b/pkg/approve/approve.go index afa97b0..143bc82 100644 --- a/pkg/approve/approve.go +++ b/pkg/approve/approve.go @@ -21,15 +21,15 @@ import ( "errors" "fmt" + apiutil "github.com/cert-manager/cert-manager/pkg/api/util" + cmapi "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1" + cmmeta "github.com/cert-manager/cert-manager/pkg/apis/meta/v1" "github.com/spf13/cobra" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/cli-runtime/pkg/genericclioptions" "k8s.io/kubectl/pkg/util/i18n" "k8s.io/kubectl/pkg/util/templates" - apiutil "github.com/cert-manager/cert-manager/pkg/api/util" - cmapi "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1" - cmmeta "github.com/cert-manager/cert-manager/pkg/apis/meta/v1" "github.com/cert-manager/cmctl/v2/pkg/build" "github.com/cert-manager/cmctl/v2/pkg/factory" ) diff --git a/pkg/check/api/api.go b/pkg/check/api/api.go index 755aadc..e963ded 100644 --- a/pkg/check/api/api.go +++ b/pkg/check/api/api.go @@ -22,6 +22,8 @@ import ( "fmt" "time" + logf "github.com/cert-manager/cert-manager/pkg/logs" + "github.com/cert-manager/cert-manager/pkg/util/cmapichecker" "github.com/spf13/cobra" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/util/wait" @@ -29,8 +31,6 @@ import ( "k8s.io/kubectl/pkg/util/i18n" "k8s.io/kubectl/pkg/util/templates" - logf "github.com/cert-manager/cert-manager/pkg/logs" - "github.com/cert-manager/cert-manager/pkg/util/cmapichecker" cmcmdutil "github.com/cert-manager/cmctl/v2/internal/util" "github.com/cert-manager/cmctl/v2/pkg/factory" ) diff --git a/pkg/convert/convert.go b/pkg/convert/convert.go index 0bc8ca9..68f0989 100644 --- a/pkg/convert/convert.go +++ b/pkg/convert/convert.go @@ -20,9 +20,8 @@ import ( "context" "fmt" + "github.com/cert-manager/cert-manager/pkg/ctl" logf "github.com/cert-manager/cert-manager/pkg/logs" - "github.com/cert-manager/cmctl/v2/pkg/build" - "github.com/spf13/cobra" metainternalversion "k8s.io/apimachinery/pkg/apis/meta/internalversion" "k8s.io/apimachinery/pkg/runtime" @@ -36,7 +35,7 @@ import ( "k8s.io/kubectl/pkg/util/i18n" "k8s.io/kubectl/pkg/util/templates" - "github.com/cert-manager/cert-manager/pkg/ctl" + "github.com/cert-manager/cmctl/v2/pkg/build" ) var ( diff --git a/pkg/create/certificaterequest/certificaterequest.go b/pkg/create/certificaterequest/certificaterequest.go index da6e612..8121612 100644 --- a/pkg/create/certificaterequest/certificaterequest.go +++ b/pkg/create/certificaterequest/certificaterequest.go @@ -24,6 +24,11 @@ import ( "os" "time" + apiutil "github.com/cert-manager/cert-manager/pkg/api/util" + cmapi "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1" + cmmeta "github.com/cert-manager/cert-manager/pkg/apis/meta/v1" + "github.com/cert-manager/cert-manager/pkg/ctl" + "github.com/cert-manager/cert-manager/pkg/util/pki" "github.com/spf13/cobra" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" @@ -34,11 +39,6 @@ import ( "k8s.io/kubectl/pkg/util/i18n" "k8s.io/kubectl/pkg/util/templates" - apiutil "github.com/cert-manager/cert-manager/pkg/api/util" - cmapi "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1" - cmmeta "github.com/cert-manager/cert-manager/pkg/apis/meta/v1" - "github.com/cert-manager/cert-manager/pkg/ctl" - "github.com/cert-manager/cert-manager/pkg/util/pki" "github.com/cert-manager/cmctl/v2/pkg/build" "github.com/cert-manager/cmctl/v2/pkg/factory" ) @@ -249,7 +249,7 @@ func (o *Options) Run(ctx context.Context, args []string) error { err = wait.PollUntilContextTimeout(ctx, time.Second, o.Timeout, false, func(ctx context.Context) (done bool, err error) { req, err = o.CMClient.CertmanagerV1().CertificateRequests(req.Namespace).Get(ctx, req.Name, metav1.GetOptions{}) if err != nil { - return false, nil + return false, nil // nolint: nilerr // Retry and keep polling until context is cancelled } return apiutil.CertificateRequestHasCondition(req, cmapi.CertificateRequestCondition{ Type: cmapi.CertificateRequestConditionReady, diff --git a/pkg/create/certificatesigningrequest/certificatesigningrequest.go b/pkg/create/certificatesigningrequest/certificatesigningrequest.go index cfe8813..e2195ac 100644 --- a/pkg/create/certificatesigningrequest/certificatesigningrequest.go +++ b/pkg/create/certificatesigningrequest/certificatesigningrequest.go @@ -25,7 +25,12 @@ import ( "strconv" "time" + apiutil "github.com/cert-manager/cert-manager/pkg/api/util" + "github.com/cert-manager/cert-manager/pkg/apis/certmanager" + cmapi "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1" experimentalapi "github.com/cert-manager/cert-manager/pkg/apis/experimental/v1alpha1" + "github.com/cert-manager/cert-manager/pkg/ctl" + "github.com/cert-manager/cert-manager/pkg/util/pki" "github.com/spf13/cobra" certificatesv1 "k8s.io/api/certificates/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -38,11 +43,6 @@ import ( "k8s.io/kubectl/pkg/util/i18n" "k8s.io/kubectl/pkg/util/templates" - apiutil "github.com/cert-manager/cert-manager/pkg/api/util" - "github.com/cert-manager/cert-manager/pkg/apis/certmanager" - cmapi "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1" - "github.com/cert-manager/cert-manager/pkg/ctl" - "github.com/cert-manager/cert-manager/pkg/util/pki" "github.com/cert-manager/cmctl/v2/pkg/build" "github.com/cert-manager/cmctl/v2/pkg/factory" ) diff --git a/pkg/deny/deny.go b/pkg/deny/deny.go index 3b8ece2..c08f83f 100644 --- a/pkg/deny/deny.go +++ b/pkg/deny/deny.go @@ -21,15 +21,15 @@ import ( "errors" "fmt" + apiutil "github.com/cert-manager/cert-manager/pkg/api/util" + cmapi "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1" + cmmeta "github.com/cert-manager/cert-manager/pkg/apis/meta/v1" "github.com/spf13/cobra" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/cli-runtime/pkg/genericclioptions" "k8s.io/kubectl/pkg/util/i18n" "k8s.io/kubectl/pkg/util/templates" - apiutil "github.com/cert-manager/cert-manager/pkg/api/util" - cmapi "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1" - cmmeta "github.com/cert-manager/cert-manager/pkg/apis/meta/v1" "github.com/cert-manager/cmctl/v2/pkg/build" "github.com/cert-manager/cmctl/v2/pkg/factory" ) diff --git a/pkg/factory/factory.go b/pkg/factory/factory.go index beba3d9..10f7dfa 100644 --- a/pkg/factory/factory.go +++ b/pkg/factory/factory.go @@ -17,6 +17,7 @@ limitations under the License. package factory import ( + cmclient "github.com/cert-manager/cert-manager/pkg/client/clientset/versioned" "github.com/spf13/cobra" "k8s.io/cli-runtime/pkg/genericclioptions" "k8s.io/client-go/kubernetes" @@ -25,8 +26,6 @@ import ( // Load all auth plugins _ "k8s.io/client-go/plugin/pkg/client/auth" - - cmclient "github.com/cert-manager/cert-manager/pkg/client/clientset/versioned" ) // Factory provides a set of clients and configurations to authenticate and @@ -71,7 +70,9 @@ func New(cmd *cobra.Command) *Factory { f.factory = util.NewFactory(kubeConfigFlags) kubeConfigFlags.AddFlags(cmd.Flags()) - cmd.RegisterFlagCompletionFunc("namespace", validArgsListNamespaces(f)) + if err := cmd.RegisterFlagCompletionFunc("namespace", validArgsListNamespaces(f)); err != nil { + panic(err) + } // Setup a PreRunE to populate the Factory. Catch the existing PreRunE command // if one was defined, and execute it second. diff --git a/pkg/inspect/secret/secret.go b/pkg/inspect/secret/secret.go index fae05de..ac99988 100644 --- a/pkg/inspect/secret/secret.go +++ b/pkg/inspect/secret/secret.go @@ -22,11 +22,14 @@ import ( "crypto/x509" "errors" "fmt" + "io" "net/url" "strings" "text/template" "time" + cmmeta "github.com/cert-manager/cert-manager/pkg/apis/meta/v1" + "github.com/cert-manager/cert-manager/pkg/util/pki" "github.com/spf13/cobra" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -35,8 +38,6 @@ import ( "k8s.io/kubectl/pkg/util/templates" k8sclock "k8s.io/utils/clock" - cmmeta "github.com/cert-manager/cert-manager/pkg/apis/meta/v1" - "github.com/cert-manager/cert-manager/pkg/util/pki" "github.com/cert-manager/cmctl/v2/pkg/build" "github.com/cert-manager/cmctl/v2/pkg/factory" ) @@ -117,7 +118,7 @@ func NewCmdInspectSecret(setupCtx context.Context, ioStreams genericclioptions.I return o.Validate(args) }, RunE: func(cmd *cobra.Command, args []string) error { - return o.Run(cmd.Context(), args) + return o.Run(cmd.Context(), args, ioStreams.Out) }, } @@ -138,7 +139,7 @@ func (o *Options) Validate(args []string) error { } // Run executes status certificate command -func (o *Options) Run(ctx context.Context, args []string) error { +func (o *Options) Run(ctx context.Context, args []string, stdout io.Writer) error { secret, err := o.KubeClient.CoreV1().Secrets(o.Namespace).Get(ctx, args[0], metav1.GetOptions{}) if err != nil { return fmt.Errorf("error when finding Secret %q: %w\n", args[0], err) @@ -164,23 +165,41 @@ func (o *Options) Run(ctx context.Context, args []string) error { return fmt.Errorf("error when parsing 'tls.crt': %w", err) } - out := []string{ - describeValidFor(x509Cert), - describeValidityPeriod(x509Cert), - describeIssuedBy(x509Cert), - describeIssuedFor(x509Cert), - describeCertificate(x509Cert), - describeDebugging(x509Cert, intermediates, secret.Data[cmmeta.TLSCAKey]), + var out []string + + for _, describeFn := range []func(*x509.Certificate) (string, error){ + describeValidFor, + describeValidityPeriod, + describeIssuedBy, + describeIssuedFor, + describeCertificate, + } { + desc, err := describeFn(x509Cert) + if err != nil { + return err + } + out = append(out, desc) + } + + if desc, err := describeDebugging(ctx, x509Cert, intermediates, secret.Data[cmmeta.TLSCAKey]); err != nil { + return err + } else { + out = append(out, desc) } - fmt.Println(strings.Join(out, "\n\n")) + fmt.Fprintln(stdout, strings.Join(out, "\n\n")) return nil } -func describeValidFor(cert *x509.Certificate) string { +func describeValidFor(cert *x509.Certificate) (string, error) { + tmpl, err := template.New("validForTemplate").Parse(validForTemplate) + if err != nil { + return "", err + } + var b bytes.Buffer - template.Must(template.New("validForTemplate").Parse(validForTemplate)).Execute(&b, struct { + err = tmpl.Execute(&b, struct { DNSNames string URIs string IPAddresses string @@ -194,12 +213,17 @@ func describeValidFor(cert *x509.Certificate) string { KeyUsage: printKeyUsage(pki.BuildCertManagerKeyUsages(cert.KeyUsage, cert.ExtKeyUsage)), }) - return b.String() + return b.String(), err } -func describeValidityPeriod(cert *x509.Certificate) string { +func describeValidityPeriod(cert *x509.Certificate) (string, error) { + tmpl, err := template.New("validityPeriodTemplate").Parse(validityPeriodTemplate) + if err != nil { + return "", err + } + var b bytes.Buffer - template.Must(template.New("validityPeriodTemplate").Parse(validityPeriodTemplate)).Execute(&b, struct { + err = tmpl.Execute(&b, struct { NotBefore string NotAfter string }{ @@ -207,12 +231,17 @@ func describeValidityPeriod(cert *x509.Certificate) string { NotAfter: cert.NotAfter.Format(time.RFC1123), }) - return b.String() + return b.String(), err } -func describeIssuedBy(cert *x509.Certificate) string { +func describeIssuedBy(cert *x509.Certificate) (string, error) { + tmpl, err := template.New("issuedByTemplate").Parse(issuedByTemplate) + if err != nil { + return "", err + } + var b bytes.Buffer - template.Must(template.New("issuedByTemplate").Parse(issuedByTemplate)).Execute(&b, struct { + err = tmpl.Execute(&b, struct { CommonName string Organization string OrganizationalUnit string @@ -224,12 +253,17 @@ func describeIssuedBy(cert *x509.Certificate) string { Country: printSliceOrOne(cert.Issuer.Country), }) - return b.String() + return b.String(), err } -func describeIssuedFor(cert *x509.Certificate) string { +func describeIssuedFor(cert *x509.Certificate) (string, error) { + tmpl, err := template.New("issuedForTemplate").Parse(issuedForTemplate) + if err != nil { + return "", err + } + var b bytes.Buffer - template.Must(template.New("issuedForTemplate").Parse(issuedForTemplate)).Execute(&b, struct { + err = tmpl.Execute(&b, struct { CommonName string Organization string OrganizationalUnit string @@ -241,12 +275,17 @@ func describeIssuedFor(cert *x509.Certificate) string { Country: printSliceOrOne(cert.Subject.Country), }) - return b.String() + return b.String(), err } -func describeCertificate(cert *x509.Certificate) string { +func describeCertificate(cert *x509.Certificate) (string, error) { + tmpl, err := template.New("certificateTemplate").Parse(certificateTemplate) + if err != nil { + return "", err + } + var b bytes.Buffer - template.Must(template.New("certificateTemplate").Parse(certificateTemplate)).Execute(&b, struct { + err = tmpl.Execute(&b, struct { SigningAlgorithm string PublicKeyAlgorithm string SerialNumber string @@ -264,25 +303,30 @@ func describeCertificate(cert *x509.Certificate) string { OCSP: printSliceOrOne(cert.OCSPServer), }) - return b.String() + return b.String(), err } -func describeDebugging(cert *x509.Certificate, intermediates [][]byte, ca []byte) string { +func describeDebugging(ctx context.Context, cert *x509.Certificate, intermediates [][]byte, ca []byte) (string, error) { + tmpl, err := template.New("debuggingTemplate").Parse(debuggingTemplate) + if err != nil { + return "", err + } + var b bytes.Buffer - template.Must(template.New("debuggingTemplate").Parse(debuggingTemplate)).Execute(&b, struct { + err = tmpl.Execute(&b, struct { TrustedByThisComputer string CRLStatus string OCSPStatus string }{ TrustedByThisComputer: describeTrusted(cert, intermediates), - CRLStatus: describeCRL(cert), - OCSPStatus: describeOCSP(cert, intermediates, ca), + CRLStatus: describeCRL(ctx, cert), + OCSPStatus: describeOCSP(ctx, cert, intermediates, ca), }) - return b.String() + return b.String(), err } -func describeCRL(cert *x509.Certificate) string { +func describeCRL(ctx context.Context, cert *x509.Certificate) string { if len(cert.CRLDistributionPoints) < 1 { return "No CRL endpoints set" } @@ -298,7 +342,7 @@ func describeCRL(cert *x509.Certificate) string { } hasChecked = true - valid, err := checkCRLValidCert(cert, crlURL) + valid, err := checkCRLValidCert(ctx, cert, crlURL) if err != nil { return fmt.Sprintf("Cannot check CRL: %s", err.Error()) } @@ -314,7 +358,7 @@ func describeCRL(cert *x509.Certificate) string { return "Valid" } -func describeOCSP(cert *x509.Certificate, intermediates [][]byte, ca []byte) string { +func describeOCSP(ctx context.Context, cert *x509.Certificate, intermediates [][]byte, ca []byte) string { if len(ca) > 1 { intermediates = append([][]byte{ca}, intermediates...) } @@ -326,7 +370,7 @@ func describeOCSP(cert *x509.Certificate, intermediates [][]byte, ca []byte) str return fmt.Sprintf("Cannot parse intermediate certificate: %s", err.Error()) } - valid, err := checkOCSPValidCert(cert, issuerCert) + valid, err := checkOCSPValidCert(ctx, cert, issuerCert) if err != nil { return fmt.Sprintf("Cannot check OCSP: %s", err.Error()) } diff --git a/pkg/inspect/secret/secret_test.go b/pkg/inspect/secret/secret_test.go index ae99a9d..43978a3 100644 --- a/pkg/inspect/secret/secret_test.go +++ b/pkg/inspect/secret/secret_test.go @@ -17,17 +17,16 @@ limitations under the License. package secret import ( + "context" "crypto/x509" "strings" "testing" "time" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - fakeclock "k8s.io/utils/clock/testing" - v1 "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1" "github.com/cert-manager/cert-manager/pkg/util/pki" "github.com/cert-manager/cert-manager/test/unit/gen" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) var ( @@ -64,7 +63,7 @@ func init() { Localities: []string{"San Francisco"}, Provinces: []string{"California"}, } - caX509Cert, err := pki.GenerateTemplate(caCertificateTemplate) + caX509Cert, err := pki.CertificateTemplateFromCertificate(caCertificateTemplate) if err != nil { panic(err) } @@ -100,7 +99,7 @@ func init() { Countries: []string{"GB"}, OrganizationalUnits: []string{"cert-manager"}, } - testX509Cert, err := pki.GenerateTemplate(testCertTemplate) + testX509Cert, err := pki.CertificateTemplateFromCertificate(testCertTemplate) if err != nil { panic(err) } @@ -140,7 +139,7 @@ func Test_describeCRL(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - if got := describeCRL(tt.cert); got != tt.want { + if got := describeCRL(context.TODO(), tt.cert); got != tt.want { t.Errorf("describeCRL() = %v, want %v", makeInvisibleVisible(got), makeInvisibleVisible(tt.want)) } }) @@ -168,9 +167,13 @@ func Test_describeCertificate(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - if got := describeCertificate(tt.cert); got != tt.want { + got, err := describeCertificate(tt.cert) + if got != tt.want { t.Errorf("describeCertificate() = %v, want %v", makeInvisibleVisible(got), makeInvisibleVisible(tt.want)) } + if err != nil { + t.Errorf("describeCertificate() error = %v", err) + } }) } } @@ -202,9 +205,13 @@ func Test_describeDebugging(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - if got := describeDebugging(tt.args.cert, tt.args.intermediates, tt.args.ca); got != tt.want { + got, err := describeDebugging(context.TODO(), tt.args.cert, tt.args.intermediates, tt.args.ca) + if got != tt.want { t.Errorf("describeDebugging() = %v, want %v", makeInvisibleVisible(got), makeInvisibleVisible(tt.want)) } + if err != nil { + t.Errorf("describeCertificate() error = %v", err) + } }) } } @@ -227,9 +234,13 @@ func Test_describeIssuedBy(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - if got := describeIssuedBy(tt.cert); got != tt.want { + got, err := describeIssuedBy(tt.cert) + if got != tt.want { t.Errorf("describeIssuedBy() = %v, want %v", makeInvisibleVisible(got), makeInvisibleVisible(tt.want)) } + if err != nil { + t.Errorf("describeIssuedBy() error = %v", err) + } }) } } @@ -252,9 +263,13 @@ func Test_describeIssuedFor(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - if got := describeIssuedFor(tt.cert); got != tt.want { + got, err := describeIssuedFor(tt.cert) + if got != tt.want { t.Errorf("describeIssuedFor() = %v, want %v", makeInvisibleVisible(got), makeInvisibleVisible(tt.want)) } + if err != nil { + t.Errorf("describeCertificate() error = %v", err) + } }) } } @@ -280,7 +295,7 @@ func Test_describeOCSP(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - if got := describeOCSP(tt.args.cert, tt.args.intermediates, tt.args.ca); got != tt.want { + if got := describeOCSP(context.TODO(), tt.args.cert, tt.args.intermediates, tt.args.ca); got != tt.want { t.Errorf("describeOCSP() = %v, want %v", makeInvisibleVisible(got), makeInvisibleVisible(tt.want)) } }) @@ -288,9 +303,6 @@ func Test_describeOCSP(t *testing.T) { } func Test_describeTrusted(t *testing.T) { - // set clock to when our test cert was trusted - t1, _ := time.Parse("Thu, 27 Nov 2020 10:00:00 UTC", time.RFC1123) - clock = fakeclock.NewFakeClock(t1) type args struct { cert *x509.Certificate intermediates [][]byte @@ -353,9 +365,13 @@ func Test_describeValidFor(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - if got := describeValidFor(tt.cert); got != tt.want { + got, err := describeValidFor(tt.cert) + if got != tt.want { t.Errorf("describeValidFor() = %v, want %v", makeInvisibleVisible(got), makeInvisibleVisible(tt.want)) } + if err != nil { + t.Errorf("describeIssuedBy() error = %v", err) + } }) } } @@ -376,16 +392,20 @@ func Test_describeValidityPeriod(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - if got := describeValidityPeriod(tt.cert); got != tt.want { + got, err := describeValidityPeriod(tt.cert) + if got != tt.want { t.Errorf("describeValidityPeriod() = %v, want %v", makeInvisibleVisible(got), makeInvisibleVisible(tt.want)) } + if err != nil { + t.Errorf("describeValidityPeriod() error = %v", err) + } }) } } func makeInvisibleVisible(in string) string { - in = strings.Replace(in, "\n", "\\n\n", -1) - in = strings.Replace(in, "\t", "\\t", -1) + in = strings.ReplaceAll(in, "\n", "\\n\n") + in = strings.ReplaceAll(in, "\t", "\\t") return in } diff --git a/pkg/inspect/secret/util.go b/pkg/inspect/secret/util.go index 04ec1d7..e7e1cda 100644 --- a/pkg/inspect/secret/util.go +++ b/pkg/inspect/secret/util.go @@ -18,6 +18,7 @@ package secret import ( "bytes" + "context" "crypto" "crypto/sha256" "crypto/x509" @@ -29,9 +30,8 @@ import ( "net/url" "strings" - "golang.org/x/crypto/ocsp" - cmapi "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1" + "golang.org/x/crypto/ocsp" ) func fingerprintCert(cert *x509.Certificate) string { @@ -51,7 +51,7 @@ func fingerprintCert(cert *x509.Certificate) string { return buf.String() } -func checkOCSPValidCert(leafCert, issuerCert *x509.Certificate) (bool, error) { +func checkOCSPValidCert(ctx context.Context, leafCert, issuerCert *x509.Certificate) (bool, error) { if len(leafCert.OCSPServer) < 1 { return false, errors.New("No OCSP Server set") } @@ -61,7 +61,7 @@ func checkOCSPValidCert(leafCert, issuerCert *x509.Certificate) (bool, error) { } for _, ocspServer := range leafCert.OCSPServer { - httpRequest, err := http.NewRequest(http.MethodPost, ocspServer, bytes.NewBuffer(buffer)) + httpRequest, err := http.NewRequestWithContext(ctx, http.MethodPost, ocspServer, bytes.NewBuffer(buffer)) if err != nil { return false, fmt.Errorf("error creating HTTP request: %w", err) } @@ -96,8 +96,13 @@ func checkOCSPValidCert(leafCert, issuerCert *x509.Certificate) (bool, error) { return true, nil } -func checkCRLValidCert(cert *x509.Certificate, url string) (bool, error) { - resp, err := http.Get(url) +func checkCRLValidCert(ctx context.Context, cert *x509.Certificate, url string) (bool, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) + if err != nil { + return false, fmt.Errorf("error creating HTTP request: %w", err) + } + + resp, err := http.DefaultClient.Do(req) if err != nil { return false, fmt.Errorf("error getting HTTP response: %w", err) } diff --git a/pkg/inspect/secret/util_test.go b/pkg/inspect/secret/util_test.go index 4d74895..9d641cd 100644 --- a/pkg/inspect/secret/util_test.go +++ b/pkg/inspect/secret/util_test.go @@ -186,9 +186,6 @@ func Test_printSliceOrOne(t *testing.T) { } func Test_splitPEMs(t *testing.T) { - type args struct { - certData []byte - } tests := []struct { name string certData []byte diff --git a/pkg/install/helm/applycrd.go b/pkg/install/helm/applycrd.go index c9ecb89..95a9a86 100644 --- a/pkg/install/helm/applycrd.go +++ b/pkg/install/helm/applycrd.go @@ -19,10 +19,9 @@ package helm import ( "time" + logf "github.com/cert-manager/cert-manager/pkg/logs" "helm.sh/helm/v3/pkg/action" "k8s.io/cli-runtime/pkg/resource" - - logf "github.com/cert-manager/cert-manager/pkg/logs" ) // CreateCRDs creates cert manager CRDs. Before calling this function, we diff --git a/pkg/install/helm/flags.go b/pkg/install/helm/flags.go index 42157d0..10fe9f8 100644 --- a/pkg/install/helm/flags.go +++ b/pkg/install/helm/flags.go @@ -25,7 +25,11 @@ import ( // Flags that are shared between the Install and the Uninstall command func AddInstallUninstallFlags(f *pflag.FlagSet, timeout *time.Duration, wait *bool) { f.DurationVar(timeout, "timeout", 300*time.Second, "Time to wait for any individual Kubernetes operation (like Jobs for hooks)") - f.MarkHidden("timeout") + if err := f.MarkHidden("timeout"); err != nil { + panic(err) + } f.BoolVar(wait, "wait", true, "If set, will wait until all Pods, PVCs, Services, and minimum number of Pods of a Deployment, StatefulSet, or ReplicaSet are in a ready state before marking the release as successful. It will wait for as long as --timeout") - f.MarkHidden("wait") + if err := f.MarkHidden("wait"); err != nil { + panic(err) + } } diff --git a/pkg/install/helm/settings.go b/pkg/install/helm/settings.go index d7af14e..076357b 100644 --- a/pkg/install/helm/settings.go +++ b/pkg/install/helm/settings.go @@ -22,12 +22,13 @@ import ( "os" logf "github.com/cert-manager/cert-manager/pkg/logs" - "github.com/cert-manager/cmctl/v2/pkg/factory" "github.com/go-logr/logr" "github.com/spf13/cobra" "github.com/spf13/pflag" "helm.sh/helm/v3/pkg/action" "helm.sh/helm/v3/pkg/cli" + + "github.com/cert-manager/cmctl/v2/pkg/factory" ) const defaultCertManagerNamespace = "cert-manager" @@ -73,7 +74,9 @@ func (n *NormalisedEnvSettings) Setup(ctx context.Context, cmd *cobra.Command) { // Fix the default namespace to be cert-manager cmd.Flag("namespace").DefValue = defaultCertManagerNamespace - cmd.Flag("namespace").Value.Set(defaultCertManagerNamespace) + if err := cmd.Flag("namespace").Value.Set(defaultCertManagerNamespace); err != nil { + panic(err) + } } func (n *NormalisedEnvSettings) setupEnvSettings(cmd *cobra.Command) { diff --git a/pkg/install/install.go b/pkg/install/install.go index d3588c1..1ecf116 100644 --- a/pkg/install/install.go +++ b/pkg/install/install.go @@ -23,6 +23,7 @@ import ( "strings" "time" + logf "github.com/cert-manager/cert-manager/pkg/logs" "github.com/spf13/cobra" "helm.sh/helm/v3/pkg/action" "helm.sh/helm/v3/pkg/chart" @@ -33,7 +34,6 @@ import ( "helm.sh/helm/v3/pkg/release" "k8s.io/cli-runtime/pkg/genericclioptions" - logf "github.com/cert-manager/cert-manager/pkg/logs" "github.com/cert-manager/cmctl/v2/pkg/build" "github.com/cert-manager/cmctl/v2/pkg/install/helm" ) @@ -117,9 +117,13 @@ func NewCmdInstall(setupCtx context.Context, ioStreams genericclioptions.IOStrea addChartPathOptionsFlags(cmd.Flags(), &options.client.ChartPathOptions) cmd.Flags().BoolVar(&options.client.CreateNamespace, "create-namespace", true, "Create the release namespace if not present") - cmd.Flags().MarkHidden("create-namespace") + if err := cmd.Flags().MarkHidden("create-namespace"); err != nil { + panic(err) + } cmd.Flags().StringVar(&options.ChartName, "chart-name", "cert-manager", "Name of the chart to install") - cmd.Flags().MarkHidden("chart-name") + if err := cmd.Flags().MarkHidden("chart-name"); err != nil { + panic(err) + } cmd.Flags().BoolVar(&options.DryRun, "dry-run", false, "Simulate install and output manifest") return cmd diff --git a/pkg/install/util.go b/pkg/install/util.go index 4b8dd1b..957db5c 100644 --- a/pkg/install/util.go +++ b/pkg/install/util.go @@ -28,22 +28,34 @@ import ( func addInstallFlags(f *pflag.FlagSet, client *action.Install) { f.StringVar(&client.ReleaseName, "release-name", "cert-manager", "Name of the helm release") - f.MarkHidden("release-name") + if err := f.MarkHidden("release-name"); err != nil { + panic(err) + } f.BoolVarP(&client.GenerateName, "generate-name", "g", false, "Generate the name (instead of using the default 'cert-manager' value)") - f.MarkHidden("generate-name") + if err := f.MarkHidden("generate-name"); err != nil { + panic(err) + } f.StringVar(&client.NameTemplate, "name-template", "", "Specify template used to name the release") - f.MarkHidden("name-template") + if err := f.MarkHidden("name-template"); err != nil { + panic(err) + } f.StringVar(&client.Description, "description", "cert-manager was installed using the cert-manager CLI", "Add a custom description") - f.MarkHidden("description") + if err := f.MarkHidden("description"); err != nil { + panic(err) + } } func addValueOptionsFlags(f *pflag.FlagSet, v *values.Options) { f.StringSliceVarP(&v.ValueFiles, "values", "f", []string{}, "Specify values in a YAML file or a URL (can specify multiple)") f.StringArrayVar(&v.Values, "set", []string{}, "Set values on the command line (can specify multiple or separate values with commas: key1=val1,key2=val2)") f.StringArrayVar(&v.StringValues, "set-string", []string{}, "Set STRING values on the command line (can specify multiple or separate values with commas: key1=val1,key2=val2)") - f.MarkHidden("set-string") + if err := f.MarkHidden("set-string"); err != nil { + panic(err) + } f.StringArrayVar(&v.FileValues, "set-file", []string{}, "Set values from respective files specified via the command line (can specify multiple or separate values with commas: key1=path1,key2=path2)") - f.MarkHidden("set-file") + if err := f.MarkHidden("set-file"); err != nil { + panic(err) + } } // defaultKeyring returns the expanded path to the default keyring. diff --git a/pkg/renew/renew.go b/pkg/renew/renew.go index 3ca7744..1b71ae9 100644 --- a/pkg/renew/renew.go +++ b/pkg/renew/renew.go @@ -22,6 +22,10 @@ import ( "fmt" "strings" + apiutil "github.com/cert-manager/cert-manager/pkg/api/util" + cmapi "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1" + cmmeta "github.com/cert-manager/cert-manager/pkg/apis/meta/v1" + cmclient "github.com/cert-manager/cert-manager/pkg/client/clientset/versioned" "github.com/spf13/cobra" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -31,10 +35,6 @@ import ( "k8s.io/kubectl/pkg/util/i18n" "k8s.io/kubectl/pkg/util/templates" - apiutil "github.com/cert-manager/cert-manager/pkg/api/util" - cmapi "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1" - cmmeta "github.com/cert-manager/cert-manager/pkg/apis/meta/v1" - cmclient "github.com/cert-manager/cert-manager/pkg/client/clientset/versioned" "github.com/cert-manager/cmctl/v2/pkg/build" "github.com/cert-manager/cmctl/v2/pkg/factory" ) diff --git a/pkg/status/certificate/certificate.go b/pkg/status/certificate/certificate.go index d6912ae..7db08b4 100644 --- a/pkg/status/certificate/certificate.go +++ b/pkg/status/certificate/certificate.go @@ -22,6 +22,11 @@ import ( "fmt" "time" + cmacme "github.com/cert-manager/cert-manager/pkg/apis/acme/v1" + cmapi "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1" + cmclient "github.com/cert-manager/cert-manager/pkg/client/clientset/versioned" + "github.com/cert-manager/cert-manager/pkg/ctl" + "github.com/cert-manager/cert-manager/pkg/util/predicate" "github.com/spf13/cobra" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -31,11 +36,6 @@ import ( "k8s.io/kubectl/pkg/util/i18n" "k8s.io/kubectl/pkg/util/templates" - cmacme "github.com/cert-manager/cert-manager/pkg/apis/acme/v1" - cmapi "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1" - cmclient "github.com/cert-manager/cert-manager/pkg/client/clientset/versioned" - "github.com/cert-manager/cert-manager/pkg/ctl" - "github.com/cert-manager/cert-manager/pkg/util/predicate" "github.com/cert-manager/cmctl/v2/pkg/build" "github.com/cert-manager/cmctl/v2/pkg/factory" ) @@ -127,7 +127,7 @@ func (o *Options) Run(ctx context.Context, args []string) error { // Build status of Certificate with data gathered status := StatusFromResources(data) - fmt.Fprintf(o.Out, status.String()) + fmt.Fprint(o.Out, status.String()) return nil } @@ -315,11 +315,12 @@ func findMatchingCR(cmClient cmclient.Interface, ctx context.Context, crt *cmapi } } - if len(possibleMatches) < 1 { + switch { + case len(possibleMatches) < 1: return nil, nil - } else if len(possibleMatches) == 1 { + case len(possibleMatches) == 1: return possibleMatches[0], nil - } else { + default: return nil, errors.New("found multiple certificate requests with expected revision and owner") } } @@ -342,11 +343,12 @@ func findMatchingOrder(cmClient cmclient.Interface, ctx context.Context, req *cm } } - if len(possibleMatches) < 1 { + switch { + case len(possibleMatches) < 1: return nil, nil - } else if len(possibleMatches) == 1 { + case len(possibleMatches) == 1: return possibleMatches[0], nil - } else { + default: return nil, fmt.Errorf("found multiple orders owned by CertificateRequest %s", req.Name) } } @@ -357,17 +359,18 @@ func getGenericIssuer(cmClient cmclient.Interface, ctx context.Context, crt *cma issuerKind = "Issuer" } - if crt.Spec.IssuerRef.Group != "cert-manager.io" && crt.Spec.IssuerRef.Group != "" { + switch { + case crt.Spec.IssuerRef.Group != "cert-manager.io" && crt.Spec.IssuerRef.Group != "": // TODO: Support Issuers/ClusterIssuers from other groups as well return nil, "", fmt.Errorf("The %s %q is not of the group cert-manager.io, this command currently does not support third party issuers.\nTo get more information about %q, try 'kubectl describe'\n", issuerKind, crt.Spec.IssuerRef.Name, crt.Spec.IssuerRef.Name) - } else if issuerKind == "Issuer" { + case issuerKind == "Issuer": issuer, issuerErr := cmClient.CertmanagerV1().Issuers(crt.Namespace).Get(ctx, crt.Spec.IssuerRef.Name, metav1.GetOptions{}) if issuerErr != nil { issuerErr = fmt.Errorf("error when getting Issuer: %v\n", issuerErr) } return issuer, issuerKind, issuerErr - } else { + default: // ClusterIssuer clusterIssuer, issuerErr := cmClient.CertmanagerV1().ClusterIssuers().Get(ctx, crt.Spec.IssuerRef.Name, metav1.GetOptions{}) if issuerErr != nil { diff --git a/pkg/status/certificate/certificate_test.go b/pkg/status/certificate/certificate_test.go index 837635d..21e9c20 100644 --- a/pkg/status/certificate/certificate_test.go +++ b/pkg/status/certificate/certificate_test.go @@ -24,14 +24,13 @@ import ( "testing" "time" - "github.com/stretchr/testify/assert" - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - cmacme "github.com/cert-manager/cert-manager/pkg/apis/acme/v1" cmapi "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1" cmmeta "github.com/cert-manager/cert-manager/pkg/apis/meta/v1" "github.com/cert-manager/cert-manager/test/unit/gen" + "github.com/stretchr/testify/assert" + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) func TestFormatStringSlice(t *testing.T) { diff --git a/pkg/status/certificate/types.go b/pkg/status/certificate/types.go index 756a4a2..467ffe6 100644 --- a/pkg/status/certificate/types.go +++ b/pkg/status/certificate/types.go @@ -24,13 +24,13 @@ import ( "math/big" "strings" + cmacme "github.com/cert-manager/cert-manager/pkg/apis/acme/v1" + cmapi "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1" + "github.com/cert-manager/cert-manager/pkg/util/pki" v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/kubectl/pkg/describe" - cmacme "github.com/cert-manager/cert-manager/pkg/apis/acme/v1" - cmapi "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1" - "github.com/cert-manager/cert-manager/pkg/util/pki" "github.com/cert-manager/cmctl/v2/pkg/status/util" ) diff --git a/pkg/uninstall/uninstall.go b/pkg/uninstall/uninstall.go index aaddcd5..d534ba6 100644 --- a/pkg/uninstall/uninstall.go +++ b/pkg/uninstall/uninstall.go @@ -147,7 +147,7 @@ func run(ctx context.Context, o options) (*release.UninstallReleaseResponse, err return res, nil } -func addCRDAnnotations(ctx context.Context, o options) error { +func addCRDAnnotations(_ context.Context, o options) error { if err := o.settings.ActionConfiguration.KubeClient.IsReachable(); err != nil { return err } diff --git a/pkg/upgrade/migrateapiversion/migrator.go b/pkg/upgrade/migrateapiversion/migrator.go index 66e8408..aa587e0 100644 --- a/pkg/upgrade/migrateapiversion/migrator.go +++ b/pkg/upgrade/migrateapiversion/migrator.go @@ -22,14 +22,13 @@ import ( "io" "time" + apiext "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/util/sets" "k8s.io/apimachinery/pkg/util/wait" "k8s.io/client-go/util/retry" - - apiext "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" "sigs.k8s.io/controller-runtime/pkg/client" ) @@ -190,7 +189,7 @@ func (m *Migrator) migrateResourcesForCRD(ctx context.Context, crd *apiext.Custo } } // add 500ms to the duration to ensure we always round up - duration := time.Now().Sub(startTime) + (time.Millisecond * 500) + duration := time.Since(startTime) + (time.Millisecond * 500) fmt.Fprintf(m.Out, " Successfully migrated %d %s objects in %s\n", len(list.Items), crd.Spec.Names.Kind, duration.Round(time.Second)) return nil } @@ -245,9 +244,9 @@ func storageVersionForCRD(crd *apiext.CustomResourceDefinition) string { // storedVersionsAdded returns a list of any versions added to the `status.storedVersions` field on // a CRD resource. -func storedVersionsAdded(old, new *apiext.CustomResourceDefinition) sets.Set[string] { - oldStoredVersions := sets.New[string](old.Status.StoredVersions...) - newStoredVersions := sets.New[string](new.Status.StoredVersions...) +func storedVersionsAdded(oldCRD, newCRD *apiext.CustomResourceDefinition) sets.Set[string] { + oldStoredVersions := sets.New[string](oldCRD.Status.StoredVersions...) + newStoredVersions := sets.New[string](newCRD.Status.StoredVersions...) return newStoredVersions.Difference(oldStoredVersions) } diff --git a/pkg/version/version.go b/pkg/version/version.go index 290d0ee..141a6af 100644 --- a/pkg/version/version.go +++ b/pkg/version/version.go @@ -22,12 +22,12 @@ import ( "errors" "fmt" + "github.com/cert-manager/cert-manager/pkg/util" "github.com/spf13/cobra" "k8s.io/apimachinery/pkg/runtime" "k8s.io/cli-runtime/pkg/genericclioptions" "sigs.k8s.io/yaml" - "github.com/cert-manager/cert-manager/pkg/util" "github.com/cert-manager/cmctl/v2/internal/versionchecker" "github.com/cert-manager/cmctl/v2/pkg/build" "github.com/cert-manager/cmctl/v2/pkg/factory" @@ -69,7 +69,7 @@ func versionLong() string { The CLI version is embedded in the binary and directly displayed. Determining the deployed cert-manager version is done by querying the cert-manger resources. First, the tool looks at the labels of the cert-manager CRD -resources. Then, it searches for the labels of the resources related the the +resources. Then, it searches for the labels of the resources related the cert-manager webhook linked in the CRDs. It also tries to derive the version from the docker image tag of that webhook service. After gathering all this version information, the tool checks if all versions are the same and returns diff --git a/test/integration/ctl_create_cr_test.go b/test/integration/ctl_create_cr_test.go index 2a466d5..67a8680 100644 --- a/test/integration/ctl_create_cr_test.go +++ b/test/integration/ctl_create_cr_test.go @@ -25,14 +25,14 @@ import ( "testing" "time" + cmapiv1 "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1" + cmmeta "github.com/cert-manager/cert-manager/pkg/apis/meta/v1" + "github.com/cert-manager/cert-manager/pkg/util/pki" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/wait" "k8s.io/cli-runtime/pkg/genericclioptions" - cmapiv1 "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1" - cmmeta "github.com/cert-manager/cert-manager/pkg/apis/meta/v1" - "github.com/cert-manager/cert-manager/pkg/util/pki" "github.com/cert-manager/cmctl/v2/pkg/create/certificaterequest" "github.com/cert-manager/cmctl/v2/pkg/factory" "github.com/cert-manager/cmctl/v2/test/integration/framework" @@ -315,7 +315,7 @@ func TestCtlCreateCRSuccessful(t *testing.T) { err = wait.PollUntilContextCancel(pollCtx, time.Second, true, func(ctx context.Context) (done bool, err error) { req, err = cmCl.CertmanagerV1().CertificateRequests(test.inputNamespace).Get(ctx, test.inputArgs[0], metav1.GetOptions{}) if err != nil { - return false, nil + return false, nil // nolint: nilerr // Retry and keep polling until context is cancelled } return true, nil }) diff --git a/test/integration/ctl_install_test.go b/test/integration/ctl_install_test.go index 6de3c6d..2024abb 100644 --- a/test/integration/ctl_install_test.go +++ b/test/integration/ctl_install_test.go @@ -27,10 +27,10 @@ import ( "time" "github.com/sergi/go-diff/diffmatchpatch" + logsapi "k8s.io/component-base/logs/api/v1" "github.com/cert-manager/cmctl/v2/cmd" "github.com/cert-manager/cmctl/v2/test/integration/install_framework" - logsapi "k8s.io/component-base/logs/api/v1" ) func TestCtlInstall(t *testing.T) { @@ -148,7 +148,9 @@ func executeCmctlAndCheckOutput( expErr bool, expOutput string, ) { - logsapi.ResetForTest(nil) + if err := logsapi.ResetForTest(nil); err != nil { + t.Fatal(err) + } executeAndCheckOutput(t, func(stdin io.Reader, stdout io.Writer) error { cmd := cmd.NewCertManagerCtlCommand(ctx, stdin, stdout, stdout) diff --git a/test/integration/ctl_renew_test.go b/test/integration/ctl_renew_test.go index c468421..d893e73 100644 --- a/test/integration/ctl_renew_test.go +++ b/test/integration/ctl_renew_test.go @@ -21,15 +21,14 @@ import ( "testing" "time" - corev1 "k8s.io/api/core/v1" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/cli-runtime/pkg/genericclioptions" - apiutil "github.com/cert-manager/cert-manager/pkg/api/util" cmapi "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1" cmmeta "github.com/cert-manager/cert-manager/pkg/apis/meta/v1" "github.com/cert-manager/cert-manager/test/unit/gen" + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/cli-runtime/pkg/genericclioptions" + "github.com/cert-manager/cmctl/v2/pkg/factory" "github.com/cert-manager/cmctl/v2/pkg/renew" "github.com/cert-manager/cmctl/v2/test/integration/framework" diff --git a/test/integration/ctl_status_certificate_test.go b/test/integration/ctl_status_certificate_test.go index 3201822..a66d346 100644 --- a/test/integration/ctl_status_certificate_test.go +++ b/test/integration/ctl_status_certificate_test.go @@ -24,13 +24,6 @@ import ( "testing" "time" - "github.com/sergi/go-diff/diffmatchpatch" - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/cli-runtime/pkg/genericclioptions" - "k8s.io/client-go/kubernetes" - "k8s.io/client-go/tools/reference" - apiutil "github.com/cert-manager/cert-manager/pkg/api/util" cmacme "github.com/cert-manager/cert-manager/pkg/apis/acme/v1" cmapi "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1" @@ -39,6 +32,13 @@ import ( "github.com/cert-manager/cert-manager/pkg/ctl" "github.com/cert-manager/cert-manager/pkg/util/pki" "github.com/cert-manager/cert-manager/test/unit/gen" + "github.com/sergi/go-diff/diffmatchpatch" + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/cli-runtime/pkg/genericclioptions" + "k8s.io/client-go/kubernetes" + "k8s.io/client-go/tools/reference" + "github.com/cert-manager/cmctl/v2/pkg/factory" statuscertcmd "github.com/cert-manager/cmctl/v2/pkg/status/certificate" "github.com/cert-manager/cmctl/v2/test/integration/framework" diff --git a/test/integration/ctl_uninstall_test.go b/test/integration/ctl_uninstall_test.go index 03b4677..f4b294a 100644 --- a/test/integration/ctl_uninstall_test.go +++ b/test/integration/ctl_uninstall_test.go @@ -24,10 +24,11 @@ import ( "testing" "time" - "github.com/cert-manager/cmctl/v2/test/integration/install_framework" "github.com/stretchr/testify/require" apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/typed/apiextensions/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + "github.com/cert-manager/cmctl/v2/test/integration/install_framework" ) func TestCtlUninstall(t *testing.T) { diff --git a/test/integration/framework/apiserver.go b/test/integration/framework/apiserver.go index 83179d5..da65c5d 100644 --- a/test/integration/framework/apiserver.go +++ b/test/integration/framework/apiserver.go @@ -24,6 +24,8 @@ import ( "strings" "testing" + "github.com/cert-manager/cert-manager/test/apiserver" + webhooktesting "github.com/cert-manager/cert-manager/test/webhook" admissionregistrationv1 "k8s.io/api/admissionregistration/v1" "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions" apiextensionsinstall "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/install" @@ -38,10 +40,6 @@ import ( "k8s.io/utils/ptr" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/envtest" - - "github.com/cert-manager/cert-manager/pkg/webhook/handlers" - "github.com/cert-manager/cert-manager/test/apiserver" - webhooktesting "github.com/cert-manager/cert-manager/test/webhook" ) type StopFunc func() @@ -49,8 +47,7 @@ type StopFunc func() // controlPlaneOptions has parameters for the control plane of the integration // test framework which can be overridden in tests. type controlPlaneOptions struct { - crdsDir *string - webhookConversionHandler handlers.ConversionHook + crdsDir *string } type RunControlPlaneOption func(*controlPlaneOptions) diff --git a/test/integration/framework/helpers.go b/test/integration/framework/helpers.go index 1494359..d214da1 100644 --- a/test/integration/framework/helpers.go +++ b/test/integration/framework/helpers.go @@ -21,6 +21,10 @@ import ( "testing" "time" + cmclient "github.com/cert-manager/cert-manager/pkg/client/clientset/versioned" + certmgrscheme "github.com/cert-manager/cert-manager/pkg/client/clientset/versioned/scheme" + cminformers "github.com/cert-manager/cert-manager/pkg/client/informers/externalversions" + controllerpkg "github.com/cert-manager/cert-manager/pkg/controller" "golang.org/x/sync/errgroup" corev1 "k8s.io/api/core/v1" apiext "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" @@ -35,11 +39,6 @@ import ( apireg "k8s.io/kube-aggregator/pkg/apis/apiregistration/v1" "k8s.io/kubectl/pkg/util/openapi" gwapi "sigs.k8s.io/gateway-api/apis/v1" - - cmclient "github.com/cert-manager/cert-manager/pkg/client/clientset/versioned" - certmgrscheme "github.com/cert-manager/cert-manager/pkg/client/clientset/versioned/scheme" - cminformers "github.com/cert-manager/cert-manager/pkg/client/informers/externalversions" - controllerpkg "github.com/cert-manager/cert-manager/pkg/controller" ) func NewEventRecorder(t *testing.T, scheme *runtime.Scheme) record.EventRecorder { @@ -66,11 +65,17 @@ func NewClients(t *testing.T, config *rest.Config) (kubernetes.Interface, cmclie cmFactory := cminformers.NewSharedInformerFactory(cmCl, 0) scheme := runtime.NewScheme() - kscheme.AddToScheme(scheme) - certmgrscheme.AddToScheme(scheme) - apiext.AddToScheme(scheme) - apireg.AddToScheme(scheme) - gwapi.AddToScheme(scheme) + for _, err := range []error{ + kscheme.AddToScheme(scheme), + certmgrscheme.AddToScheme(scheme), + apiext.AddToScheme(scheme), + apireg.AddToScheme(scheme), + gwapi.AddToScheme(scheme), + } { + if err != nil { + t.Fatal(err) + } + } return cl, cmCl, cmFactory, scheme } diff --git a/test/integration/migrate/ctl_upgrade_migrate_test.go b/test/integration/migrate/ctl_upgrade_migrate_test.go index 3d63c34..e134e52 100644 --- a/test/integration/migrate/ctl_upgrade_migrate_test.go +++ b/test/integration/migrate/ctl_upgrade_migrate_test.go @@ -22,6 +22,9 @@ import ( "testing" "time" + "github.com/cert-manager/cert-manager/pkg/webhook/handlers/testdata/apis/testgroup/install" + v1 "github.com/cert-manager/cert-manager/pkg/webhook/handlers/testdata/apis/testgroup/v1" + v2 "github.com/cert-manager/cert-manager/pkg/webhook/handlers/testdata/apis/testgroup/v2" apiextinstall "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/install" apiext "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -30,9 +33,6 @@ import ( "k8s.io/apimachinery/pkg/runtime/schema" "sigs.k8s.io/controller-runtime/pkg/client" - "github.com/cert-manager/cert-manager/pkg/webhook/handlers/testdata/apis/testgroup/install" - v1 "github.com/cert-manager/cert-manager/pkg/webhook/handlers/testdata/apis/testgroup/v1" - v2 "github.com/cert-manager/cert-manager/pkg/webhook/handlers/testdata/apis/testgroup/v2" "github.com/cert-manager/cmctl/v2/pkg/upgrade/migrateapiversion" "github.com/cert-manager/cmctl/v2/test/integration/framework" ) diff --git a/test/integration/testdata/apis/testgroup/fuzzer/fuzzer.go b/test/integration/testdata/apis/testgroup/fuzzer/fuzzer.go index e8d402c..4c35619 100644 --- a/test/integration/testdata/apis/testgroup/fuzzer/fuzzer.go +++ b/test/integration/testdata/apis/testgroup/fuzzer/fuzzer.go @@ -17,11 +17,10 @@ limitations under the License. package fuzzer import ( + "github.com/cert-manager/cert-manager/pkg/webhook/handlers/testdata/apis/testgroup" fuzz "github.com/google/gofuzz" runtimeserializer "k8s.io/apimachinery/pkg/runtime/serializer" "k8s.io/utils/ptr" - - "github.com/cert-manager/cert-manager/pkg/webhook/handlers/testdata/apis/testgroup" ) // Funcs returns the fuzzer functions for the apps api group. diff --git a/test/integration/testdata/apis/testgroup/install/install.go b/test/integration/testdata/apis/testgroup/install/install.go index 0c89f49..7ffbf17 100644 --- a/test/integration/testdata/apis/testgroup/install/install.go +++ b/test/integration/testdata/apis/testgroup/install/install.go @@ -19,12 +19,11 @@ limitations under the License. package install import ( - "k8s.io/apimachinery/pkg/runtime" - utilruntime "k8s.io/apimachinery/pkg/util/runtime" - "github.com/cert-manager/cert-manager/pkg/webhook/handlers/testdata/apis/testgroup" v1 "github.com/cert-manager/cert-manager/pkg/webhook/handlers/testdata/apis/testgroup/v1" v2 "github.com/cert-manager/cert-manager/pkg/webhook/handlers/testdata/apis/testgroup/v2" + "k8s.io/apimachinery/pkg/runtime" + utilruntime "k8s.io/apimachinery/pkg/util/runtime" ) // Install registers the API group and adds types to a scheme diff --git a/test/integration/testdata/apis/testgroup/install/roundtrip_test.go b/test/integration/testdata/apis/testgroup/install/roundtrip_test.go index 764dced..6cb5d69 100644 --- a/test/integration/testdata/apis/testgroup/install/roundtrip_test.go +++ b/test/integration/testdata/apis/testgroup/install/roundtrip_test.go @@ -19,9 +19,8 @@ package install import ( "testing" - "k8s.io/apimachinery/pkg/api/apitesting/roundtrip" - "github.com/cert-manager/cert-manager/pkg/webhook/handlers/testdata/apis/testgroup/fuzzer" + "k8s.io/apimachinery/pkg/api/apitesting/roundtrip" ) func TestRoundTripTypes(t *testing.T) { diff --git a/test/integration/testdata/apis/testgroup/v1/register.go b/test/integration/testdata/apis/testgroup/v1/register.go index 5bb86bc..16358cc 100644 --- a/test/integration/testdata/apis/testgroup/v1/register.go +++ b/test/integration/testdata/apis/testgroup/v1/register.go @@ -17,11 +17,10 @@ limitations under the License. package v1 import ( + "github.com/cert-manager/cert-manager/pkg/webhook/handlers/testdata/apis/testgroup" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" - - "github.com/cert-manager/cert-manager/pkg/webhook/handlers/testdata/apis/testgroup" ) // SchemeGroupVersion is group version used to register these objects diff --git a/test/integration/testdata/apis/testgroup/v2/convert.go b/test/integration/testdata/apis/testgroup/v2/convert.go index 4e2c691..483c69d 100644 --- a/test/integration/testdata/apis/testgroup/v2/convert.go +++ b/test/integration/testdata/apis/testgroup/v2/convert.go @@ -19,9 +19,8 @@ package v2 import ( "unsafe" - "k8s.io/apimachinery/pkg/conversion" - "github.com/cert-manager/cert-manager/pkg/webhook/handlers/testdata/apis/testgroup" + "k8s.io/apimachinery/pkg/conversion" ) func Convert_v2_TestType_To_testgroup_TestType(in *TestType, out *testgroup.TestType, s conversion.Scope) error { diff --git a/test/integration/testdata/apis/testgroup/v2/register.go b/test/integration/testdata/apis/testgroup/v2/register.go index a41b8b7..e0fdab1 100644 --- a/test/integration/testdata/apis/testgroup/v2/register.go +++ b/test/integration/testdata/apis/testgroup/v2/register.go @@ -17,11 +17,10 @@ limitations under the License. package v2 import ( + "github.com/cert-manager/cert-manager/pkg/webhook/handlers/testdata/apis/testgroup" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" - - "github.com/cert-manager/cert-manager/pkg/webhook/handlers/testdata/apis/testgroup" ) // SchemeGroupVersion is group version used to register these objects diff --git a/test/integration/testdata/apis/testgroup/validation/validation.go b/test/integration/testdata/apis/testgroup/validation/validation.go index 7678f0c..53c6ba1 100644 --- a/test/integration/testdata/apis/testgroup/validation/validation.go +++ b/test/integration/testdata/apis/testgroup/validation/validation.go @@ -17,12 +17,11 @@ limitations under the License. package validation import ( + "github.com/cert-manager/cert-manager/pkg/webhook/handlers/testdata/apis/testgroup" + v1 "github.com/cert-manager/cert-manager/pkg/webhook/handlers/testdata/apis/testgroup/v1" admissionv1 "k8s.io/api/admission/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/util/validation/field" - - "github.com/cert-manager/cert-manager/pkg/webhook/handlers/testdata/apis/testgroup" - v1 "github.com/cert-manager/cert-manager/pkg/webhook/handlers/testdata/apis/testgroup/v1" ) func ValidateTestType(_ *admissionv1.AdmissionRequest, obj runtime.Object) (field.ErrorList, []string) { diff --git a/test/integration/testdata/apis/testgroup/validation/validation_test.go b/test/integration/testdata/apis/testgroup/validation/validation_test.go index adada70..7142ec0 100644 --- a/test/integration/testdata/apis/testgroup/validation/validation_test.go +++ b/test/integration/testdata/apis/testgroup/validation/validation_test.go @@ -20,10 +20,9 @@ import ( "reflect" "testing" - "k8s.io/apimachinery/pkg/util/validation/field" - "github.com/cert-manager/cert-manager/pkg/webhook/handlers/testdata/apis/testgroup" v1 "github.com/cert-manager/cert-manager/pkg/webhook/handlers/testdata/apis/testgroup/v1" + "k8s.io/apimachinery/pkg/util/validation/field" ) func TestValidateTestType(t *testing.T) {