From 42f55097a0e64c54f75a932db51a1349a900bfb3 Mon Sep 17 00:00:00 2001 From: Luis Presuel Date: Wed, 2 Apr 2025 02:33:14 -0600 Subject: [PATCH 1/2] fix: migration to golangci-lint v2 --- .golangci.bck.yml | 27 +++++++++ .golangci.yml | 60 +++++++++++++------- examples/provisionWithServiceAccount/main.go | 2 +- examples/simple-cli/main.go | 14 +++-- examples/simple-cli/vars.go | 8 ++- examples/tlspc-svc-account/main.go | 2 +- pkg/endpoint/endpoint.go | 7 ++- pkg/playbook/app/domain/connection.go | 46 ++++----------- pkg/playbook/app/service/service.go | 5 +- pkg/policy/policyUtils.go | 18 +++--- pkg/util/pemUtil.go | 3 + pkg/util/utils.go | 5 +- pkg/venafi/cloud/cloud.go | 3 +- pkg/venafi/cloud/cloudUtil.go | 7 ++- pkg/venafi/cloud/connector.go | 32 ++++++----- pkg/venafi/fake/connector.go | 6 ++ pkg/venafi/fake/fake.go | 1 + pkg/venafi/tpp/connector.go | 30 ++++++---- pkg/venafi/tpp/search.go | 10 +++- pkg/venafi/tpp/tpp.go | 8 +++ pkg/verror/errors.go | 4 ++ 21 files changed, 187 insertions(+), 111 deletions(-) create mode 100644 .golangci.bck.yml diff --git a/.golangci.bck.yml b/.golangci.bck.yml new file mode 100644 index 00000000..73c6ff47 --- /dev/null +++ b/.golangci.bck.yml @@ -0,0 +1,27 @@ +run: + tests: false + modules-download-mode: readonly + +linters: + disable: + - unused + enable: + - gosec + +issues: + exclude-rules: + - text: "composite literal uses unkeyed fields" + linters: + - govet + - text: "certificateRequest.Attributes" + linters: + - staticcheck + - text: "G505" + linters: + - gosec + - text: "G401" + linters: + - gosec + - text: "h.Write" + linters: + - errcheck \ No newline at end of file diff --git a/.golangci.yml b/.golangci.yml index 73c6ff47..67dfa561 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,27 +1,43 @@ +version: "2" run: - tests: false modules-download-mode: readonly - + tests: false linters: - disable: - - unused enable: - gosec - -issues: - exclude-rules: - - text: "composite literal uses unkeyed fields" - linters: - - govet - - text: "certificateRequest.Attributes" - linters: - - staticcheck - - text: "G505" - linters: - - gosec - - text: "G401" - linters: - - gosec - - text: "h.Write" - linters: - - errcheck \ No newline at end of file + disable: + - unused + exclusions: + generated: lax + presets: + - comments + - common-false-positives + - legacy + - std-error-handling + rules: + - linters: + - govet + text: composite literal uses unkeyed fields + - linters: + - staticcheck + text: certificateRequest.Attributes + - linters: + - gosec + text: G505 + - linters: + - gosec + text: G401 + - linters: + - errcheck + text: h.Write + paths: + - third_party$ + - builtin$ + - examples$ +formatters: + exclusions: + generated: lax + paths: + - third_party$ + - builtin$ + - examples$ diff --git a/examples/provisionWithServiceAccount/main.go b/examples/provisionWithServiceAccount/main.go index 027ca57b..effae339 100644 --- a/examples/provisionWithServiceAccount/main.go +++ b/examples/provisionWithServiceAccount/main.go @@ -15,7 +15,7 @@ const ( vcpURL = "VCP_URL" vcpZone = "VCP_ZONE" vcpApiKey = "CLOUD_APIKEY" - vcpTokenURL = "VCP_TOKEN_URL" + vcpTokenURL = "VCP_TOKEN_URL" // #nosec G101 // This is not a hardcoded credential vcpJWT = "VCP_JWT" envVarNotSet = "environment variable not set: %s" diff --git a/examples/simple-cli/main.go b/examples/simple-cli/main.go index 2e193063..69b70290 100644 --- a/examples/simple-cli/main.go +++ b/examples/simple-cli/main.go @@ -242,22 +242,24 @@ func main() { // 5. Retrieve certificate & key from new object // var importedRetriveReq = &certificate.Request{} - switch { - case config.ConnectorType == endpoint.ConnectorTypeTPP || config.ConnectorType == endpoint.ConnectorTypeFake: + switch config.ConnectorType { + case endpoint.ConnectorTypeFake: + fallthrough + case endpoint.ConnectorTypeTPP: importedRetriveReq = &certificate.Request{ PickupID: importResp.CertificateDN, Timeout: 180 * time.Second, KeyPassword: "newPassw0rd!", FetchPrivateKey: true, } - case config.ConnectorType == endpoint.ConnectorTypeCloud: - //You can retrieve imported certificate by thumbprint or certificate Id. + case endpoint.ConnectorTypeCloud: thumbprint := calcThumbprint(pcc.Certificate) importedRetriveReq = &certificate.Request{ Thumbprint: thumbprint, - //CertID: importResp.CertId, - Timeout: 180 * time.Second, + Timeout: 180 * time.Second, } + default: + t.Fatalf("unsupported connector type %s", config.ConnectorType) } pcc3, err := c.RetrieveCertificate(importedRetriveReq) diff --git a/examples/simple-cli/vars.go b/examples/simple-cli/vars.go index 37250736..6d3b8712 100644 --- a/examples/simple-cli/vars.go +++ b/examples/simple-cli/vars.go @@ -19,7 +19,7 @@ package main import ( "encoding/json" "fmt" - "io/ioutil" + "io" "log" "os" @@ -51,7 +51,11 @@ func init() { } trustBundleFilePath := os.Getenv("TRUST_BUNDLE_PATH") if trustBundleFilePath != "" { - buf, err := ioutil.ReadFile(trustBundleFilePath) + file, err := os.Open(trustBundleFilePath) + if err != nil { + panic(err) + } + buf, err := io.ReadAll(file) if err != nil { panic(err) } diff --git a/examples/tlspc-svc-account/main.go b/examples/tlspc-svc-account/main.go index 272ef155..3fa26a79 100644 --- a/examples/tlspc-svc-account/main.go +++ b/examples/tlspc-svc-account/main.go @@ -15,7 +15,7 @@ import ( const ( vcpURL = "VCP_URL" vcpZone = "VCP_ZONE" - vcpTokenURL = "VCP_TOKEN_URL" + vcpTokenURL = "VCP_TOKEN_URL" // #nosec G101 // This is not a hardcoded credential vcpJWT = "VCP_JWT" envVarNotSet = "environment variable not set: %s" diff --git a/pkg/endpoint/endpoint.go b/pkg/endpoint/endpoint.go index d5ae664a..44928b25 100644 --- a/pkg/endpoint/endpoint.go +++ b/pkg/endpoint/endpoint.go @@ -313,21 +313,22 @@ func (p *Policy) ValidateCertificateRequest(request *certificate.Request) error } if len(p.AllowedKeyConfigurations) > 0 { var keyValid bool - if parsedCSR.PublicKeyAlgorithm == x509.RSA { + switch parsedCSR.PublicKeyAlgorithm { + case x509.RSA: pubkey, ok := parsedCSR.PublicKey.(*rsa.PublicKey) if ok { keyValid = checkKey(certificate.KeyTypeRSA, pubkey.Size()*8, "", p.AllowedKeyConfigurations) } else { return fmt.Errorf("invalid key in csr") } - } else if parsedCSR.PublicKeyAlgorithm == x509.ECDSA { + case x509.ECDSA: pubkey, ok := parsedCSR.PublicKey.(*ecdsa.PublicKey) if ok { keyValid = checkKey(certificate.KeyTypeECDSA, 0, pubkey.Curve.Params().Name, p.AllowedKeyConfigurations) } else { return fmt.Errorf("invalid key in csr") } - } else if parsedCSR.PublicKeyAlgorithm == x509.Ed25519 { + case x509.Ed25519: _, ok := parsedCSR.PublicKey.(*ed25519.PublicKey) if ok { keyValid = checkKey(certificate.KeyTypeECDSA, 0, "ed25519", p.AllowedKeyConfigurations) diff --git a/pkg/playbook/app/domain/connection.go b/pkg/playbook/app/domain/connection.go index 188ccac0..bbac757e 100644 --- a/pkg/playbook/app/domain/connection.go +++ b/pkg/playbook/app/domain/connection.go @@ -105,47 +105,34 @@ func isValidTpp(c Connection) (bool, error) { func isValidVaaS(c Connection) (bool, error) { // Check if an API key has been provided - apikey := false - if c.Credentials.APIKey != "" { - apikey = true - } - - accesstoken := false - if c.Credentials.AccessToken != "" { - accesstoken = true - } + apikey := c.Credentials.APIKey != "" + venAccessToken := c.Credentials.AccessToken != "" // Check if an TokenURL has been provided - tokenurl := false - if c.Credentials.TokenURL != "" { - tokenurl = true - } + tokenUrl := c.Credentials.TokenURL != "" // Check if externalJWT has been provided - externaljwt := false - if c.Credentials.ExternalJWT != "" { - externaljwt = true - } + venExternalJWT := c.Credentials.ExternalJWT != "" // There's a valid service account IF both externalJWT and tokenURL provided svcaccount := false - if externaljwt && tokenurl { + if venExternalJWT && tokenUrl { svcaccount = true - } else if externaljwt && !tokenurl { + } else if venExternalJWT && !tokenUrl { // JWT Provided without token URL return false, ErrNoVCPTokenURL - } else if tokenurl && !externaljwt { + } else if tokenUrl && !venExternalJWT { // Token URL without an external JWT return false, ErrNoExternalJWT } // At this point, there are no valid credentials. Figure out why. - if !apikey && !svcaccount && !accesstoken { + if !apikey && !svcaccount && !venAccessToken { return false, ErrNoCredentials } // if we got here then at least one of the credential options was provided - if (svcaccount && apikey) || (svcaccount && accesstoken) || (apikey && accesstoken) { + if (svcaccount && apikey) || (svcaccount && venAccessToken) || (apikey && venAccessToken) { // more than one credential option is not acceptable return false, ErrAmbiguousVCPCreds } @@ -161,22 +148,13 @@ func isValidFirefly(c Connection) (bool, error) { } // Auth method: User-Password - userPassword := false - if c.Credentials.User != "" && c.Credentials.Password != "" { - userPassword = true - } + userPassword := c.Credentials.User != "" && c.Credentials.Password != "" //Auth method: Client Secret - cSecret := false - if c.Credentials.ClientSecret != "" { - cSecret = true - } + cSecret := c.Credentials.ClientSecret != "" //Auth method: Access Token - token := false - if c.Credentials.AccessToken != "" { - token = true - } + token := c.Credentials.AccessToken != "" if !userPassword && !cSecret && !token { return false, ErrNoCredentials diff --git a/pkg/playbook/app/service/service.go b/pkg/playbook/app/service/service.go index 9aa34894..dc7bcc6f 100644 --- a/pkg/playbook/app/service/service.go +++ b/pkg/playbook/app/service/service.go @@ -75,10 +75,7 @@ func Execute(config domain.Config, task domain.CertificateTask) []error { // Private Key should not be decrypted when csrOrigin is service and Platform is Firefly. // Firefly does not support encryption of private keys - decryptPK := true - if config.Connection.Platform == venafi.Firefly && csrOrigin == certificate.ServiceGeneratedCSR { - decryptPK = false - } + decryptPK := config.Connection.Platform == venafi.Firefly && csrOrigin == certificate.ServiceGeneratedCSR // This function will add the private key to the PCC when csrOrigin is local. // It will also decrypt the Private Key if it is encrypted diff --git a/pkg/policy/policyUtils.go b/pkg/policy/policyUtils.go index 49668fca..f8ec96bd 100644 --- a/pkg/policy/policyUtils.go +++ b/pkg/policy/policyUtils.go @@ -1062,10 +1062,11 @@ func BuildCloudCitRequest(ps *PolicySpecification, ca *CADetails) (*CloudPolicyR var ecKeyType *KeyType if ps.Policy != nil && ps.Policy.KeyPair != nil && len(ps.Policy.KeyPair.KeyTypes) > 0 { for _, val := range ps.Policy.KeyPair.KeyTypes { - if val == "RSA" { + switch val { + case "RSA": keyType = &KeyType{} keyType.KeyType = val - } else if val == "EC" { + case "EC": ecKeyType = &KeyType{} ecKeyType.KeyType = val } @@ -1163,21 +1164,21 @@ func BuildCloudCitRequest(ps *PolicySpecification, ca *CADetails) (*CloudPolicyR if ps.Default.KeyPair.KeyType != nil { key.Type = *(ps.Default.KeyPair.KeyType) - if key.Type == "RSA" { + switch key.Type { + case "RSA": if ps.Default.KeyPair.RsaKeySize != nil { key.Length = *(ps.Default.KeyPair.RsaKeySize) } else { //default key.Length = 2048 } - } else if key.Type == "EC" { + case "EC": if ps.Default.KeyPair.EllipticCurve != nil && *(ps.Default.KeyPair.EllipticCurve) != "" { key.Curve = *(ps.Default.KeyPair.EllipticCurve) } else { key.Curve = "P256" } } - shouldCreateKPRS = true } } @@ -1508,17 +1509,18 @@ func VerifyPolicySpec(bytes []byte, fileExt string) error { var err error var policySpecification PolicySpecification - if fileExt == JsonExtension { + switch fileExt { + case JsonExtension: err = json.Unmarshal(bytes, &policySpecification) if err != nil { return err } - } else if fileExt == YamlExtension { + case YamlExtension: err = yaml.Unmarshal(bytes, &policySpecification) if err != nil { return err } - } else { + default: return fmt.Errorf("the specified file is not supported") } diff --git a/pkg/util/pemUtil.go b/pkg/util/pemUtil.go index fee60579..54a4e17b 100644 --- a/pkg/util/pemUtil.go +++ b/pkg/util/pemUtil.go @@ -74,6 +74,9 @@ var rfc1423Algos = []rfc1423Algo{{ } // IncorrectPasswordError is returned when an incorrect password is detected. +// TODO: ignoring until we refactor "should have name of the form ErrFoo" (ST1012) +// +//nolint:staticcheck var IncorrectPasswordError = fmt.Errorf("x509: decryption password incorrect") func cipherByName(name string) *rfc1423Algo { diff --git a/pkg/util/utils.go b/pkg/util/utils.go index 823b2da2..3aad0cc0 100644 --- a/pkg/util/utils.go +++ b/pkg/util/utils.go @@ -72,12 +72,13 @@ func EncryptPkcs1PrivateKey(privateKey, password string) (string, error) { keyType := GetPrivateKeyType(privateKey, password) var encrypted *pem.Block var err error - if keyType == "RSA PRIVATE KEY" { + switch keyType { + case "RSA PRIVATE KEY": encrypted, err = X509EncryptPEMBlock(rand.Reader, "RSA PRIVATE KEY", block.Bytes, []byte(password), PEMCipherAES256) if err != nil { return "", nil } - } else if keyType == "EC PRIVATE KEY" { + case "EC PRIVATE KEY": encrypted, err = X509EncryptPEMBlock(rand.Reader, "EC PRIVATE KEY", block.Bytes, []byte(password), PEMCipherAES256) if err != nil { return "", nil diff --git a/pkg/venafi/cloud/cloud.go b/pkg/venafi/cloud/cloud.go index 1b352292..7acfab1c 100644 --- a/pkg/venafi/cloud/cloud.go +++ b/pkg/venafi/cloud/cloud.go @@ -314,7 +314,7 @@ func (c *Connector) getHTTPClient() *http.Client { func (c *Connector) request(method string, url string, data interface{}, authNotRequired ...bool) (statusCode int, statusText string, body []byte, err error) { if (c.accessToken == "" && c.user == nil) || (c.user != nil && c.user.Company == nil) { - if !(len(authNotRequired) == 1 && authNotRequired[0]) { + if len(authNotRequired) != 1 || !authNotRequired[0] { err = fmt.Errorf("%w: must be autheticated to make requests to TLSPC API", verror.VcertError) return } @@ -548,6 +548,7 @@ func checkCertificateRetireResults(httpStatusCode int, httpStatus string, body [ if err != nil { return err } else if resp.Count == 0 { + //nolint:staticcheck // TODO: we are ignoring ST1005 because we still need to determine if we are removing the initial capital letter from error msg return fmt.Errorf("Invalid thumbprint or certificate ID. No certificates were retired") } else { return nil diff --git a/pkg/venafi/cloud/cloudUtil.go b/pkg/venafi/cloud/cloudUtil.go index b6ad942d..c42d4048 100644 --- a/pkg/venafi/cloud/cloudUtil.go +++ b/pkg/venafi/cloud/cloudUtil.go @@ -183,14 +183,15 @@ func getCsrAttributes(c *Connector, req *certificate.Request) (*CsrAttributes, e } keyTypeParam := &KeyTypeParameters{} - if req.KeyType == certificate.KeyTypeRSA { + switch req.KeyType { + case certificate.KeyTypeRSA: keyTypeParam.KeyType = "RSA" if req.KeyLength > 0 { keyTypeParam.KeyLength = &req.KeyLength } else { keyTypeParam.KeyLength = util.GetIntRef(2048) } - } else if req.KeyType == certificate.KeyTypeECDSA { + case certificate.KeyTypeECDSA: keyTypeParam.KeyType = "EC" if req.KeyCurve.String() != "" { keyCurve := req.KeyCurve.String() @@ -200,7 +201,9 @@ func getCsrAttributes(c *Connector, req *certificate.Request) (*CsrAttributes, e defaultCurveStr := defaultCurve.String() keyTypeParam.KeyCurve = &defaultCurveStr } + default: } + csrAttr.KeyTypeParameters = keyTypeParam return &csrAttr, nil diff --git a/pkg/venafi/cloud/connector.go b/pkg/venafi/cloud/connector.go index 5aaa147b..f13c29bd 100644 --- a/pkg/venafi/cloud/connector.go +++ b/pkg/venafi/cloud/connector.go @@ -367,7 +367,8 @@ func (c *Connector) RetrieveCertificate(req *certificate.Request) (*certificate. if err != nil { return nil, err } - if statusCode == http.StatusOK { + switch statusCode { + case http.StatusOK: certificates, err := newPEMCollectionFromResponse(body, req.ChainOption) if err != nil { return nil, err @@ -376,9 +377,9 @@ func (c *Connector) RetrieveCertificate(req *certificate.Request) (*certificate. // Add certificate id to the request req.CertID = certificateId return certificates, err - } else if statusCode == http.StatusConflict { // Http Status Code 409 means the certificate has not been signed by the ca yet. + case http.StatusConflict: // Http Status Code 409 means the certificate has not been signed by the Certificate Authority yet. return nil, endpoint.ErrCertificatePending{CertificateID: req.PickupID} - } else { + default: return nil, fmt.Errorf("failed to retrieve certificate. StatusCode: %d -- Status: %s", statusCode, status) } } @@ -633,7 +634,7 @@ func (c *Connector) ImportCertificate(req *certificate.ImportRequest) (*certific err = json.Unmarshal(body, &r) if err != nil { return nil, fmt.Errorf("%w: can`t unmarshal json response %s", verror.ServerError, err) - } else if !(len(r.CertificateInformations) == 1) { + } else if len(r.CertificateInformations) != 1 { return nil, fmt.Errorf("%w: certificate was not imported on unknown reason", verror.ServerBadDataResponce) } time.Sleep(time.Second) @@ -852,9 +853,13 @@ func (c *Connector) RetrieveSystemVersion() (response string, err error) { func getCertificateId(c *Connector, req *certificate.Request) (string, error) { startTime := time.Now() - //Wait for certificate to be issued by checking its PickupID - //If certID is filled then certificate should be already issued. + if req == nil { + return "", fmt.Errorf("request is nil") + } + // Wait for certificate to be issued by checking its PickupID + // If certID is filled then certificate should be already issued. for { + //nolint:staticcheck // QF1006 won't happen as we already have other exit conditions based on time if req.PickupID == "" { break } @@ -862,10 +867,12 @@ func getCertificateId(c *Connector, req *certificate.Request) (string, error) { if err != nil { return "", fmt.Errorf("unable to retrieve: %s", err) } - if certStatus.Status == "ISSUED" { + switch certStatus.Status { + case "ISSUED": return certStatus.CertificateIdsList[0], nil - } else if certStatus.Status == "FAILED" { + case "FAILED": return "", fmt.Errorf("failed to retrieve certificate. Status: %v", certStatus) + default: } if req.Timeout == 0 { return "", endpoint.ErrCertificatePending{CertificateID: req.PickupID, Status: certStatus.Status} @@ -1093,12 +1100,11 @@ func retrieveServiceGeneratedCertData(c *Connector, req *certificate.Request, de return nil, fmt.Errorf("failed to retrieve KeyStore on VaaS, status: %s", status) } - rootFirst := false if req.ChainOption == certificate.ChainOptionRootFirst { - rootFirst = true + return ConvertZipBytesToPem(body, true) } - return ConvertZipBytesToPem(body, rootFirst) + return ConvertZipBytesToPem(body, false) } @@ -1242,8 +1248,8 @@ func (c *Connector) searchCertificates(req *SearchRequest) (*CertificateSearchRe } func (c *Connector) searchCertificatesByFingerprint(fp string) (*CertificateSearchResponse, error) { - fp = strings.Replace(fp, ":", "", -1) - fp = strings.Replace(fp, ".", "", -1) + fp = strings.ReplaceAll(fp, ":", "") + fp = strings.ReplaceAll(fp, ".", "") fp = strings.ToUpper(fp) req := &SearchRequest{ Expression: &Expression{ diff --git a/pkg/venafi/fake/connector.go b/pkg/venafi/fake/connector.go index 00ca2e28..8d53166b 100644 --- a/pkg/venafi/fake/connector.go +++ b/pkg/venafi/fake/connector.go @@ -14,6 +14,12 @@ * limitations under the License. */ +// Package fake provides a Fake connector for Venafi VCert +// +// TODO: we are ignoring this error "ST1005: error strings should not end with punctuation or newlines" since we still need +// to determine how feasible is to change the error message, even if we remove a newline +// +//nolint:staticcheck package fake import ( diff --git a/pkg/venafi/fake/fake.go b/pkg/venafi/fake/fake.go index 272ab771..8d10a398 100644 --- a/pkg/venafi/fake/fake.go +++ b/pkg/venafi/fake/fake.go @@ -46,6 +46,7 @@ func (c *Connector) GenerateRequest(config *endpoint.ZoneConfiguration, req *cer return nil default: + //nolint:staticcheck // TODO: we are ignoring ST1005 because we still need to determine if we are removing the newline char from error msg return fmt.Errorf("Unexpected option in PrivateKeyOrigin") } diff --git a/pkg/venafi/tpp/connector.go b/pkg/venafi/tpp/connector.go index 2fcf9e48..539f3fb4 100644 --- a/pkg/venafi/tpp/connector.go +++ b/pkg/venafi/tpp/connector.go @@ -14,6 +14,12 @@ * limitations under the License. */ +// Package tpp provides a TPP connector for Venafi VCert +// +// TODO: we are ignoring this error "ST1005: error strings should not end with punctuation or newlines" since we still need +// to determine how feasible is to change the error message, even if we remove a newline +// +//nolint:staticcheck package tpp import ( @@ -832,10 +838,10 @@ func (c *Connector) ResetCertificate(req *certificate.Request, restart bool) (er return fmt.Errorf("while resetting: %w", err) } - switch { - case statusCode == http.StatusOK: + switch statusCode { + case http.StatusOK: return nil - case statusCode == http.StatusBadRequest: + case http.StatusBadRequest: var decodedResetResponse certificateRequestResponse if err := json.Unmarshal(body, &decodedResetResponse); err != nil { return fmt.Errorf("failed to decode reset response: HTTP %d: %s: %s", statusCode, status, body) @@ -1572,14 +1578,15 @@ func (c *Connector) ReadPolicyConfiguration() (policy *endpoint.Policy, err erro Policy serverPolicy Error string } - if statusCode == http.StatusOK { + switch statusCode { + case http.StatusOK: err = json.Unmarshal(body, &r) if err != nil { return nil, err } p := r.Policy.toPolicy() policy = &p - } else if statusCode == http.StatusBadRequest { + case http.StatusBadRequest: err = json.Unmarshal(body, &r) if err != nil { return nil, err @@ -1587,7 +1594,7 @@ func (c *Connector) ReadPolicyConfiguration() (policy *endpoint.Policy, err erro if zoneNonFoundregexp.Match([]byte(r.Error)) { return nil, verror.ZoneNotFoundError } - } else { + default: return nil, fmt.Errorf("Invalid status: %s Server data: %s", status, body) } return @@ -1609,7 +1616,9 @@ func (c *Connector) ReadZoneConfiguration() (config *endpoint.ZoneConfiguration, Policy serverPolicy Error string } - if statusCode == http.StatusOK { + + switch statusCode { + case http.StatusOK: err = json.Unmarshal(body, &r) if err != nil { return nil, err @@ -1618,7 +1627,7 @@ func (c *Connector) ReadZoneConfiguration() (config *endpoint.ZoneConfiguration, r.Policy.toZoneConfig(zoneConfig) zoneConfig.Policy = p return zoneConfig, nil - } else if statusCode == http.StatusBadRequest { + case http.StatusBadRequest: err = json.Unmarshal(body, &r) if err != nil { return nil, err @@ -1626,9 +1635,10 @@ func (c *Connector) ReadZoneConfiguration() (config *endpoint.ZoneConfiguration, if zoneNonFoundregexp.Match([]byte(r.Error)) { return nil, verror.ZoneNotFoundError } + default: + return nil, fmt.Errorf("Invalid status: %s Server response: %s", status, string(body)) } - return nil, fmt.Errorf("Invalid status: %s Server response: %s", status, string(body)) - + return } func (c *Connector) ImportCertificate(req *certificate.ImportRequest) (*certificate.ImportResponse, error) { diff --git a/pkg/venafi/tpp/search.go b/pkg/venafi/tpp/search.go index bfadf62d..c544781f 100644 --- a/pkg/venafi/tpp/search.go +++ b/pkg/venafi/tpp/search.go @@ -14,6 +14,12 @@ * limitations under the License. */ +// Package tpp provides a TPP connector for Venafi VCert +// +// TODO: we are ignoring this error "ST1005: error strings should not end with punctuation or newlines" since we still need +// to determine how feasible is to change the error message, even if we remove a newline +// +//nolint:staticcheck package tpp import ( @@ -51,8 +57,8 @@ type CertificateDetailsResponse struct { } func (c *Connector) searchCertificatesByFingerprint(fp string) (*certificate.CertSearchResponse, error) { - fp = strings.Replace(fp, ":", "", -1) - fp = strings.Replace(fp, ".", "", -1) + fp = strings.ReplaceAll(fp, ":", "") + fp = strings.ReplaceAll(fp, ".", "") fp = strings.ToUpper(fp) var req certificate.SearchRequest diff --git a/pkg/venafi/tpp/tpp.go b/pkg/venafi/tpp/tpp.go index 49c72d28..c0684c5e 100644 --- a/pkg/venafi/tpp/tpp.go +++ b/pkg/venafi/tpp/tpp.go @@ -14,6 +14,12 @@ * limitations under the License. */ +// Package tpp defines necessary functions and structures to process TPP information +// +// TODO: we are ignoring this error "ST1005: error strings should not end with punctuation or newlines" since we still need +// to determine how feasible is to change the error message, even if we remove a newline +// +//nolint:staticcheck package tpp import ( @@ -569,6 +575,7 @@ func (c *Connector) getHTTPClient() *http.Client { // GenerateRequest creates a new certificate request, based on the zone/policy configuration and the user data func (c *Connector) GenerateRequest(config *endpoint.ZoneConfiguration, req *certificate.Request) (err error) { if req.KeyType == certificate.KeyTypeED25519 { + //nolint:staticcheck // TODO: we are ignoring ST1005 because we still need to determine if we are removing the newline char from error msg return fmt.Errorf("Unable to request certificate from TPP, ed25519 key type is not for TPP") } @@ -681,6 +688,7 @@ func parseRequestResult(httpStatusCode int, httpStatus string, body []byte) (str } return reqData.CertificateDN, nil default: + //nolint:staticcheck // TODO: we are ignoring ST1005 because we still need to determine if we are removing the newline char from error msg return "", fmt.Errorf("Unexpected status code on TPP Certificate Request.\n Status:\n %s. \n Body:\n %s\n", httpStatus, body) } } diff --git a/pkg/verror/errors.go b/pkg/verror/errors.go index 09695ffe..201f2947 100644 --- a/pkg/verror/errors.go +++ b/pkg/verror/errors.go @@ -1,3 +1,7 @@ +// Package verror provides a set of error variables for the VCert package. +// TODO: Every lint error in this file is because "should have name of the form ErrFoo" (ST1012) +// +//nolint:staticcheck package verror import "fmt" From 0dab6d7a30c118dcd43b2c740dd1f21007dde1d8 Mon Sep 17 00:00:00 2001 From: Luis Presuel Date: Thu, 3 Apr 2025 11:45:14 -0600 Subject: [PATCH 2/2] fix: finalize pending lint issues --- cmd/vcert/cmdCertificates.go | 8 +++++--- cmd/vcert/cmdCredentials.go | 4 +++- cmd/vcert/cmdHelper.go | 12 +++++++----- cmd/vcert/cmdPolicies.go | 24 ++++++++++++------------ cmd/vcert/cmdSSHCertificates.go | 4 +++- cmd/vcert/config.go | 2 +- cmd/vcert/passwords.go | 4 +++- cmd/vcert/result_writer.go | 9 ++++++--- cmd/vcert/slices.go | 4 +++- cmd/vcert/utils.go | 8 ++++---- cmd/vcert/validators.go | 4 +++- config.go | 2 +- examples/server/main.go | 25 +++++++++++++++++++++---- examples/simple-cli/main.go | 30 +++++++++++++++++++++--------- 14 files changed, 93 insertions(+), 47 deletions(-) diff --git a/cmd/vcert/cmdCertificates.go b/cmd/vcert/cmdCertificates.go index 045d1663..83a0223e 100644 --- a/cmd/vcert/cmdCertificates.go +++ b/cmd/vcert/cmdCertificates.go @@ -13,7 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - +// TODO: we are ignoring this error "ST1005: error strings should not end with punctuation or newlines" since we still need +// to determine how feasible is to change the error message, even if we remove a newline +//nolint:staticcheck package main import ( @@ -501,13 +503,13 @@ func doCommandRenew1(c *cli.Context) error { // will be just sending CSR to backend req = fillCertificateRequest(req, &flags) - case "local" == flags.csrOption || "" == flags.csrOption: + case flags.csrOption == "local" || flags.csrOption == "": // restore certificate request from old certificate req = certificate.NewRequest(oldCert) // override values with those from command line flags req = fillCertificateRequest(req, &flags) - case "service" == flags.csrOption: + case flags.csrOption == "service": // logger.Panic("service side renewal is not implemented") req = fillCertificateRequest(req, &flags) diff --git a/cmd/vcert/cmdCredentials.go b/cmd/vcert/cmdCredentials.go index 3720c232..33603f0d 100644 --- a/cmd/vcert/cmdCredentials.go +++ b/cmd/vcert/cmdCredentials.go @@ -13,7 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - +// TODO: we are ignoring this error "ST1005: error strings should not be capitalized" since we still need +// to determine how feasible is to change the error message, even if we change the capitalized character(s) +//nolint:staticcheck package main import ( diff --git a/cmd/vcert/cmdHelper.go b/cmd/vcert/cmdHelper.go index aba5fa8e..36867b21 100644 --- a/cmd/vcert/cmdHelper.go +++ b/cmd/vcert/cmdHelper.go @@ -13,7 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - +// TODO: we are ignoring this error "ST1005: error strings should not be capitalized" since we still need +// to determine how feasible is to change the error message, even if we change the capitalized character(s) +//nolint:staticcheck package main import ( @@ -263,15 +265,15 @@ func getVaaSCredentials(vaasConnector *cloud.Connector, cfg *vcert.Config) error return outputJSON(apiKey) } else { var headerMessage string - if statusCode == http.StatusCreated { + switch statusCode { + case http.StatusCreated: headerMessage = "the user account was created successfully. To complete the registration please review your email account and follow the link." - } else if statusCode == http.StatusAccepted { + case http.StatusAccepted: headerMessage = "the user account already exists therefore the API Key was rotated. To complete the activation of the rotated API Key," + " please review your email account and follow the link." - } else { // only is expected that the status code returned is 201 or 202 + default: // we only expected that the status code returned is either 201 or 202 return fmt.Errorf("unexpected http status code when the useraccount is tried to be created or api key rotated: %d", statusCode) } - fmt.Println(headerMessage) fmt.Println("api_key: ", apiKey.Key) fmt.Println("api_key_expires: ", apiKey.ValidityEndDateString) diff --git a/cmd/vcert/cmdPolicies.go b/cmd/vcert/cmdPolicies.go index f9875307..6a64f360 100644 --- a/cmd/vcert/cmdPolicies.go +++ b/cmd/vcert/cmdPolicies.go @@ -99,17 +99,18 @@ func doCommandCreatePolicy(c *cli.Context) error { //based on the extension call the appropriate method to feed the policySpecification //structure. var policySpecification policy.PolicySpecification - if fileExt == policy.JsonExtension { + switch fileExt { + case policy.JsonExtension: err = json.Unmarshal(bytes, &policySpecification) if err != nil { return err } - } else if fileExt == policy.YamlExtension { + case policy.YamlExtension: err = yaml.Unmarshal(bytes, &policySpecification) if err != nil { return err } - } else { + default: return fmt.Errorf("the specified file is not supported") } @@ -183,18 +184,19 @@ func doCommandGetPolicy(c *cli.Context) error { fileExt := policy.GetFileType(policySpecLocation) fileExt = strings.ToLower(fileExt) - if fileExt == policy.JsonExtension { - b, _ = json.MarshalIndent(ps, "", " ") + switch fileExt { + case policy.JsonExtension: + b, err = json.MarshalIndent(ps, "", " ") if err != nil { return err } - } else if fileExt == policy.YamlExtension { - b, _ = yaml.Marshal(ps) + case policy.YamlExtension: + b, err = yaml.Marshal(ps) if err != nil { return err } - } else { - return fmt.Errorf("the specified byte is not supported") + default: + return fmt.Errorf("the specified file is not supported") } err = os.WriteFile(policySpecLocation, b, 0600) @@ -204,9 +206,7 @@ func doCommandGetPolicy(c *cli.Context) error { log.Printf("policy was written in: %s", policySpecLocation) } else { - - b, _ = json.MarshalIndent(ps, "", " ") - + b, err = json.MarshalIndent(ps, "", " ") if err != nil { return err } diff --git a/cmd/vcert/cmdSSHCertificates.go b/cmd/vcert/cmdSSHCertificates.go index 93acad7a..f7f81a77 100644 --- a/cmd/vcert/cmdSSHCertificates.go +++ b/cmd/vcert/cmdSSHCertificates.go @@ -13,7 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - +// TODO: we are ignoring this error "ST1005: error strings should not be capitalized" since we still need +// to determine how feasible is to change the error message, even if we change the capitalized character(s) +//nolint:staticcheck package main import ( diff --git a/cmd/vcert/config.go b/cmd/vcert/config.go index 7336b413..ce5826f5 100644 --- a/cmd/vcert/config.go +++ b/cmd/vcert/config.go @@ -76,7 +76,7 @@ func buildConfig(c *cli.Context, flags *commandFlags) (cfg vcert.Config, err err } if c.Command.Name == commandEnrollName || c.Command.Name == commandPickupName { - if cfg.Zone == "" && cfg.ConnectorType != endpoint.ConnectorTypeFake && !(flags.pickupID != "" || flags.pickupIDFile != "") { + if cfg.Zone == "" && cfg.ConnectorType != endpoint.ConnectorTypeFake && (flags.pickupID == "" && flags.pickupIDFile == "") { return cfg, fmt.Errorf("zone cannot be empty. Use -z option") } } diff --git a/cmd/vcert/passwords.go b/cmd/vcert/passwords.go index bbee61ef..afbf9ff0 100644 --- a/cmd/vcert/passwords.go +++ b/cmd/vcert/passwords.go @@ -13,7 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - +// TODO: we are ignoring this error "ST1005: error strings should not be capitalized" since we still need +// to determine how feasible is to change the error message, even if we change the capitalized character(s) +//nolint:staticcheck package main import ( diff --git a/cmd/vcert/result_writer.go b/cmd/vcert/result_writer.go index efbe2d97..fba8edc1 100644 --- a/cmd/vcert/result_writer.go +++ b/cmd/vcert/result_writer.go @@ -330,17 +330,20 @@ func (r *Result) Flush() error { allFileOutput.CSR = r.Pcc.CSR var fileBytes []byte - if r.Config.Format == P12Format || r.Config.Format == LegacyP12Format { + switch r.Config.Format { + case LegacyP12Format: + fallthrough + case P12Format: fileBytes, err = allFileOutput.AsPKCS12(r.Config) if err != nil { return fmt.Errorf("failed to encode pkcs12: %s", err) } - } else if r.Config.Format == JKSFormat { + case JKSFormat: fileBytes, err = allFileOutput.AsJKS(r.Config) if err != nil { return err } - } else { + default: fileBytes, err = allFileOutput.Format(r.Config) if err != nil { return err diff --git a/cmd/vcert/slices.go b/cmd/vcert/slices.go index 07c6c742..37028354 100644 --- a/cmd/vcert/slices.go +++ b/cmd/vcert/slices.go @@ -13,7 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - +// TODO: we are ignoring this error "ST1005: error strings should not be capitalized" since we still need +// to determine how feasible is to change the error message, even if we change the capitalized character(s) +//nolint:staticcheck package main import ( diff --git a/cmd/vcert/utils.go b/cmd/vcert/utils.go index 72249617..f282c6ac 100644 --- a/cmd/vcert/utils.go +++ b/cmd/vcert/utils.go @@ -134,7 +134,7 @@ func fillCertificateRequest(req *certificate.Request, cf *commandFlags) *certifi req.CustomFields = append(req.CustomFields, certificate.CustomField{Name: "Origin", Value: origin, Type: certificate.CustomFieldOrigin}) switch true { - case 0 == strings.Index(cf.csrOption, "file:"): + case strings.Index(cf.csrOption, "file:") == 0: var err error csrFileName := cf.csrOption[5:] csr, err := readCSRfromFile(csrFileName) @@ -147,7 +147,7 @@ func fillCertificateRequest(req *certificate.Request, cf *commandFlags) *certifi } req.CsrOrigin = certificate.UserProvidedCSR - case "service" == cf.csrOption: + case cf.csrOption == "service": if cf.keyType != nil { req.KeyType = *cf.keyType } @@ -161,7 +161,7 @@ func fillCertificateRequest(req *certificate.Request, cf *commandFlags) *certifi } req.CsrOrigin = certificate.ServiceGeneratedCSR - default: // "local" == cf.csrOption: + default: // cf.csrOption == "local" if cf.keyType != nil { req.KeyType = *cf.keyType } @@ -225,7 +225,7 @@ func readThumbprintFromFile(fname string) (string, error) { // check if there's a thumbprint in the file s := strings.TrimSpace(string(bytes)) - s = strings.Replace(s, ":", "", -1) + s = strings.ReplaceAll(s, ":", "") s = strings.ToUpper(s) matched, _ := regexp.MatchString("^[A-F0-9]{40}$", s) if matched { diff --git a/cmd/vcert/validators.go b/cmd/vcert/validators.go index c1876ff2..f042163b 100644 --- a/cmd/vcert/validators.go +++ b/cmd/vcert/validators.go @@ -13,7 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - +// TODO: we are ignoring this error "ST1005: error strings should not be capitalized" since we still need +// to determine how feasible is to change the error message, even if we change the capitalized character(s) +//nolint:staticcheck package main import ( diff --git a/config.go b/config.go index 6788c429..474d6364 100644 --- a/config.go +++ b/config.go @@ -287,7 +287,7 @@ func validateSection(s *ini.Section) error { if m.has(fireflyClientIdKey) { //if it's not set any Flow Grant - if !((m.has(fireflyUserKey) && m.has(fireflyPasswordKey)) || m.has(fireflyClientSecretKey) || m.has(fireflyDeviceUrlKey)) { + if (!m.has(fireflyUserKey) || !m.has(fireflyPasswordKey)) && !m.has(fireflyClientSecretKey) && !m.has(fireflyDeviceUrlKey) { return fmt.Errorf("configuration issue in section %s: The OAuth Client ID is set but is not set any OAuth Flow grant", s.Name()) } diff --git a/examples/server/main.go b/examples/server/main.go index afcf3b42..abc6663c 100644 --- a/examples/server/main.go +++ b/examples/server/main.go @@ -2,10 +2,11 @@ package main import ( "fmt" - "io/ioutil" + "io" "log" "net/http" "os" + "time" "github.com/Venafi/vcert/v5" "github.com/Venafi/vcert/v5/pkg/endpoint" @@ -21,9 +22,21 @@ func main() { conf := initConfig() mux := http.NewServeMux() mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { - fmt.Fprintf(w, "It works! %v\n", r.Host) + _, err := fmt.Fprintf(w, "It works! %v\n", r.Host) + if err != nil { + return + } }) - log.Fatal(http.Serve(conf.NewListener("test.example.com:8443", "example.com"), mux)) + + server := &http.Server{ + Addr: ":8080", + Handler: mux, + ReadTimeout: 5 * time.Second, // Prevent slow clients from taking too long to send requests + WriteTimeout: 10 * time.Second, // Prevent slow responses from blocking connections + IdleTimeout: 120 * time.Second, // Limit idle connections + } + listener := conf.NewListener("test.example.com:8443", "example.com") + log.Fatal(server.Serve(listener)) } @@ -40,7 +53,11 @@ func initConfig() *vcert.Config { } trustBundleFilePath := os.Getenv("TRUST_BUNDLE_PATH") if trustBundleFilePath != "" { - buf, err := ioutil.ReadFile(trustBundleFilePath) + file, err := os.Open(trustBundleFilePath) + if err != nil { + panic(err) + } + buf, err := io.ReadAll(file) if err != nil { panic(err) } diff --git a/examples/simple-cli/main.go b/examples/simple-cli/main.go index 69b70290..264da99d 100644 --- a/examples/simple-cli/main.go +++ b/examples/simple-cli/main.go @@ -22,7 +22,7 @@ import ( "crypto/x509/pkix" "encoding/pem" "fmt" - "io/ioutil" + "io" t "log" "math/big" "net" @@ -67,8 +67,11 @@ func main() { // //Not all Venafi Cloud providers support IPAddress and EmailAddresses extensions. var enrollReq = &certificate.Request{} - switch { - case config.ConnectorType == endpoint.ConnectorTypeTPP || config.ConnectorType == endpoint.ConnectorTypeFake: + + switch config.ConnectorType { + case endpoint.ConnectorTypeFake: + fallthrough + case endpoint.ConnectorTypeTPP: enrollReq = &certificate.Request{ Subject: pkix.Name{ CommonName: commonName, @@ -92,7 +95,7 @@ func main() { {Name: "custom", Value: "2019-12-10"}, }, } - case config.ConnectorType == endpoint.ConnectorTypeCloud: + case endpoint.ConnectorTypeCloud: enrollReq = &certificate.Request{ Subject: pkix.Name{ CommonName: commonName, @@ -109,7 +112,7 @@ func main() { ChainOption: certificate.ChainOptionRootLast, KeyPassword: "newPassw0rd!", } - + default: } // @@ -209,8 +212,11 @@ func main() { // 4. Import certificate to another object of the same Zone // var importReq = &certificate.ImportRequest{} - switch { - case config.ConnectorType == endpoint.ConnectorTypeTPP || config.ConnectorType == endpoint.ConnectorTypeFake: + + switch config.ConnectorType { + case endpoint.ConnectorTypeFake: + fallthrough + case endpoint.ConnectorTypeTPP: importObjectName := fmt.Sprintf("%s-imported", commonName) importReq = &certificate.ImportRequest{ // if PolicyDN is empty, it is taken from cfg.Zone @@ -220,7 +226,7 @@ func main() { Password: "newPassw0rd!", Reconcile: false, } - case config.ConnectorType == endpoint.ConnectorTypeCloud: + case endpoint.ConnectorTypeCloud: importObjectName := fmt.Sprintf("%s-imported", commonName) importReq = &certificate.ImportRequest{ // if PolicyDN is empty, it is taken from cfg.Zone @@ -229,7 +235,9 @@ func main() { PrivateKeyData: "", Reconcile: false, } + default: } + importResp, err := c.ImportCertificate(importReq) if err != nil { t.Fatalf("could not import certificate: %s", err) @@ -276,7 +284,11 @@ func main() { var connectionTrustBundle *x509.CertPool trustBundleFilePath := os.Getenv("TRUST_BUNDLE_PATH") if trustBundleFilePath != "" { - buf, err := ioutil.ReadFile(trustBundleFilePath) + file, err := os.Open(trustBundleFilePath) + if err != nil { + panic(err) + } + buf, err := io.ReadAll(file) if err != nil { panic(err) }