From c2707f53243e09f444310dfd5099079d8723bd54 Mon Sep 17 00:00:00 2001 From: Paul Laffitte Date: Wed, 25 Feb 2026 14:38:00 +0100 Subject: [PATCH] fix: linter issues --- internal/certificate.go | 167 +++++++++++++++++++++----------------- internal/exporter_test.go | 51 ++++++++---- internal/kubernetes.go | 12 +-- 3 files changed, 130 insertions(+), 100 deletions(-) diff --git a/internal/certificate.go b/internal/certificate.go index 163e549..7fb1d0f 100644 --- a/internal/certificate.go +++ b/internal/certificate.go @@ -62,14 +62,14 @@ var DefaultYamlPaths = []YAMLCertRef{ } type certificateRef struct { - path string - format certificateFormat - certificates []*parsedCertificate - yamlPaths []YAMLCertRef - kubeSecret v1.Secret - kubeConfigMap v1.ConfigMap - kubeSecretKey string - kubeSecretLabels map[string]string + path string + format certificateFormat + certificates []*parsedCertificate + yamlPaths []YAMLCertRef + kubeSecret v1.Secret + kubeConfigMap v1.ConfigMap + kubeSecretKey string + kubeSecretLabels map[string]string } type parsedCertificate struct { @@ -131,83 +131,98 @@ func readAndParseYAMLFile(filePath string, yamlPaths []YAMLCertRef) ([]*parsedCe output := []*parsedCertificate{} for _, exprs := range yamlPaths { - file, err := os.Open(filePath) + certs, err := readAndParseYAMLEntry(filePath, exprs) if err != nil { return nil, err } - defer file.Close() + output = append(output, certs...) + } - var raw interface{} - err = yaml.NewDecoder(file).Decode(&raw) + return output, nil +} + +func readAndParseYAMLEntry(filePath string, exprs YAMLCertRef) (output []*parsedCertificate, retErr error) { + file, err := os.Open(filePath) + if err != nil { + return nil, err + } + defer func() { + if err := file.Close(); err != nil && retErr == nil { + retErr = err + } + }() + + var raw interface{} + err = yaml.NewDecoder(file).Decode(&raw) + if err != nil { + return nil, err + } + + entries, err := jsonpath.Read(raw, exprs.BasePathMatchExpr) + if err != nil { + return nil, err + } + for _, entry := range entries.([]interface{}) { + line, err := jsonpath.Read(entry, exprs.CertMatchSubExpr) + if err != nil { + continue + } + id, err := jsonpath.Read(entry, exprs.IDMatchSubExpr) + if err != nil { + continue + } + rawCerts, ok := line.(string) + if !ok { + return nil, err + } + + var decodedCerts []byte + switch exprs.Format { + case YAMLCertFormatBase64: + decodedCerts = []byte{} + encodedCerts := strings.Split(rawCerts, "\n") + + for _, encodedCert := range encodedCerts { + decodedCert, err := base64.StdEncoding.DecodeString(encodedCert) + if err != nil { + return nil, err + } + + decodedCerts = append(decodedCerts, decodedCert...) + decodedCerts = append(decodedCerts, '\n') + } + case YAMLCertFormatFile: + rawCertPaths := strings.TrimRight(string(rawCerts), "\n") + + for _, certPath := range strings.Split(rawCertPaths, "\n") { + if !path.IsAbs(certPath) { + certPath = path.Join(filepath.Dir(filePath), rawCertPaths) + } + + data, err := readFile(certPath) + if err != nil { + return nil, err + } + + decodedCerts = append(decodedCerts, data...) + } + } + + certs, err := parsePEM(decodedCerts) if err != nil { return nil, err } - entries, err := jsonpath.Read(raw, exprs.BasePathMatchExpr) - if err != nil { - return nil, err - } - for _, entry := range entries.([]interface{}) { - line, err := jsonpath.Read(entry, exprs.CertMatchSubExpr) - if err != nil { - continue - } - id, err := jsonpath.Read(entry, exprs.IDMatchSubExpr) - if err != nil { - continue - } - rawCerts, ok := line.(string) - if !ok { - return nil, err - } - - var decodedCerts []byte - if exprs.Format == YAMLCertFormatBase64 { - decodedCerts = []byte{} - encodedCerts := strings.Split(rawCerts, "\n") - - for _, encodedCert := range encodedCerts { - decodedCert, err := base64.StdEncoding.DecodeString(encodedCert) - if err != nil { - return nil, err - } - - decodedCerts = append(decodedCerts, decodedCert...) - decodedCerts = append(decodedCerts, '\n') - } - } else if exprs.Format == YAMLCertFormatFile { - rawCertPaths := strings.TrimRight(string(rawCerts), "\n") - - for _, certPath := range strings.Split(rawCertPaths, "\n") { - if !path.IsAbs(certPath) { - certPath = path.Join(filepath.Dir(filePath), rawCertPaths) - } - - data, err := readFile(certPath) - if err != nil { - return nil, err - } - - decodedCerts = append(decodedCerts, data...) - } - } - - certs, err := parsePEM(decodedCerts) - if err != nil { - return nil, err - } - - for index, cert := range certs { - displayName := id.(string) - if len(certs) > 1 { - displayName = fmt.Sprintf("%s(%d)", id, index) - } - output = append(output, &parsedCertificate{ - cert: cert, - userID: displayName, - yqMatchExpr: fmt.Sprintf("%s[:]%s", exprs.BasePathMatchExpr, exprs.CertMatchSubExpr[1:]), - }) + for index, cert := range certs { + displayName := id.(string) + if len(certs) > 1 { + displayName = fmt.Sprintf("%s(%d)", id, index) } + output = append(output, &parsedCertificate{ + cert: cert, + userID: displayName, + yqMatchExpr: fmt.Sprintf("%s[:]%s", exprs.BasePathMatchExpr, exprs.CertMatchSubExpr[1:]), + }) } } diff --git a/internal/exporter_test.go b/internal/exporter_test.go index 518f124..7998e16 100644 --- a/internal/exporter_test.go +++ b/internal/exporter_test.go @@ -27,10 +27,13 @@ import ( model "github.com/prometheus/client_model/go" "github.com/prometheus/common/expfmt" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) -const listenAddress = "127.0.0.1:9793" -const port = 9793 +const ( + listenAddress = "127.0.0.1:9793" + port = 9793 +) func TestRegularStartup(t *testing.T) { _, filename, _, _ := runtime.Caller(0) @@ -126,11 +129,13 @@ func TestMultiplePEM(t *testing.T) { for _, m := range foundNaMetrics { assert.Equal(t, naVal, m.GetGauge().GetValue(), fmt.Sprintf("x509_cert_not_after should be %f", naVal)) } + }) - removeGeneratedCertificate("/tmp/test.pem") - removeGeneratedCertificate("/tmp/test2.pem") - removeGeneratedCertificate("/tmp/test3.pem") - removeGeneratedCertificate("/tmp/test4.pem") + t.Cleanup(func() { + removeGeneratedCertificate(t, "/tmp/test.pem") + removeGeneratedCertificate(t, "/tmp/test2.pem") + removeGeneratedCertificate(t, "/tmp/test3.pem") + removeGeneratedCertificate(t, "/tmp/test4.pem") }) } @@ -197,7 +202,7 @@ func TestYAMLAbsolutePath(t *testing.T) { assert.Nil(t, err) data := strings.ReplaceAll(string(template), "{{PWD}}", path.Join(cwd, "..")) - err = os.WriteFile("/tmp/test-abs.yaml", []byte(data), 0644) + err = os.WriteFile("/tmp/test-abs.yaml", []byte(data), 0o644) assert.Nil(t, err) testRequest(t, &Exporter{ @@ -370,10 +375,14 @@ func TestErrorMetrics(t *testing.T) { } func TestBindAddrAlreadyInUse(t *testing.T) { - listener, _ := net.Listen("tcp", listenAddress) + listener, err := net.Listen("tcp", listenAddress) + require.NoError(t, err, "failed to create listener") + t.Cleanup(func() { + assert.NoError(t, listener.Close()) + }) + e := &Exporter{ListenAddress: listenAddress} - err := e.ListenAndServe() - listener.Close() + err = e.ListenAndServe() assert.NotNil(t, err, "no error was returned for bind failure") } @@ -605,8 +614,10 @@ func TestTrimPath(t *testing.T) { foundNaMetrics := getMetricsForName(metrics, "x509_cert_not_after") assert.Len(t, foundNaMetrics, 1, "missing x509_cert_not_after metric(s)") checkLabels(t, foundNaMetrics[0].GetLabel(), "/test.pem", false, 15) + }) - removeGeneratedCertificate(certPath) + t.Cleanup(func() { + removeGeneratedCertificate(t, certPath) }) } @@ -698,7 +709,9 @@ func TestExposeLabels(t *testing.T) { checkLabels(t, foundNaMetrics[0].GetLabel(), "/test.pem", false, 2) }) - removeGeneratedCertificate(certPath) + t.Cleanup(func() { + removeGeneratedCertificate(t, certPath) + }) } func TestFileGlobbing(t *testing.T) { @@ -959,8 +972,10 @@ func testSinglePEM(t *testing.T, expired float64, notBefore time.Time) { assert.GreaterOrEqual(t, vsValue, 0.) assert.LessOrEqual(t, vsValue, time.Minute.Seconds()) } + }) - removeGeneratedCertificate(certPath) + t.Cleanup(func() { + removeGeneratedCertificate(t, certPath) }) } @@ -1086,18 +1101,18 @@ func generateCertificate(path string, notBefore time.Time) { //nolint:errcheck pem.Encode(out, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes}) //nolint:errcheck - os.WriteFile(path, out.Bytes(), 00644) + os.WriteFile(path, out.Bytes(), 0o0644) out.Reset() //nolint:errcheck pem.Encode(out, getPEMBlockForKey(priv)) //nolint:errcheck - os.WriteFile(path+".key", out.Bytes(), 00644) + os.WriteFile(path+".key", out.Bytes(), 0o0644) } -func removeGeneratedCertificate(path string) { - os.Remove(path) - os.Remove(path + ".key") +func removeGeneratedCertificate(t assert.TestingT, path string) { + assert.NoError(t, os.Remove(path)) + assert.NoError(t, os.Remove(path+".key")) } func getPEMBlockForKey(priv interface{}) *pem.Block { diff --git a/internal/kubernetes.go b/internal/kubernetes.go index a550e76..a181b3f 100644 --- a/internal/kubernetes.go +++ b/internal/kubernetes.go @@ -55,10 +55,10 @@ func (exporter *Exporter) parseAllKubeObjects() ([]*certificateRef, []error) { } } output = append(output, &certificateRef{ - path: fmt.Sprintf("k8s/%s/%s", secret.GetNamespace(), secret.GetName()), - format: certificateFormatKubeSecret, - kubeSecret: secret, - kubeSecretKey: key, + path: fmt.Sprintf("k8s/%s/%s", secret.GetNamespace(), secret.GetName()), + format: certificateFormatKubeSecret, + kubeSecret: secret, + kubeSecretKey: key, kubeSecretLabels: filteredLabels, }) } @@ -286,8 +286,8 @@ func connectToKubernetesCluster(kubeconfigPath string, insecure bool, rateLimite } if insecure { - config.TLSClientConfig.Insecure = true - config.TLSClientConfig.CAData = nil + config.Insecure = true + config.CAData = nil } if rateLimiter != nil {