Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions internal/shared/util/http/certlog.go
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,12 @@ func logPem(data []byte, filename, path, action string, log logr.Logger) {
log.Info("error: no block returned from pem.Decode()", "file", filename)
return
}
// Skip private keys and other non-certificate blocks, as
// x509.CertPool.AppendCertsFromPEM does.
if block.Type != "CERTIFICATE" {
log.V(defaultLogLevel).Info("skipping non-certificate PEM block", "file", filename, "type", block.Type)
continue
}
crt, err := x509.ParseCertificate(block.Bytes)
if err != nil {
log.Error(err, "error in x509.ParseCertificate()", "file", filename)
Expand Down
136 changes: 136 additions & 0 deletions internal/shared/util/http/certlog_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
package http_test

import (
"crypto/tls"
"crypto/x509"
"encoding/pem"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"testing"

"github.com/go-logr/logr"
"github.com/go-logr/logr/funcr"
"github.com/stretchr/testify/require"

httputil "github.com/operator-framework/operator-controller/internal/shared/util/http"
)

const goodCertsDir = "../../../../testdata/certs/good"

// newCaptureLogger returns a logger that records every line, including V(4) ones.
func newCaptureLogger() (logr.Logger, *[]string) {
var lines []string
log := funcr.New(func(prefix, args string) {
lines = append(lines, args)
}, funcr.Options{Verbosity: 4})
return log, &lines
}

func linesContaining(lines []string, substrs ...string) []string {
var out []string
for _, l := range lines {
match := true
for _, s := range substrs {
if !strings.Contains(l, s) {
match = false
break
}
}
if match {
out = append(out, l)
}
}
return out
}

func readCert(t *testing.T, path string) *x509.Certificate {
t.Helper()
data, err := os.ReadFile(path)
require.NoError(t, err)
block, _ := pem.Decode(data)
require.NotNil(t, block)
cert, err := x509.ParseCertificate(block.Bytes)
require.NoError(t, err)
return cert
}

// Amazon_Root_CA_3.pem holds a PRIVATE KEY block followed by a CERTIFICATE block.
// The certificate is loaded into the pool, so it must be logged too, and the key
// must not be reported as a certificate parse error.
func TestNewCertPoolLogsCertificatesAfterNonCertificateBlocks(t *testing.T) {
log, lines := newCaptureLogger()

_, err := httputil.NewCertPool(goodCertsDir, log)
require.NoError(t, err)

for _, file := range []string{"Amazon_Root_CA_1.pem", "Amazon_Root_CA_2.pem", "Amazon_Root_CA_3.pem"} {
require.Len(t, linesContaining(*lines, `"msg"="loading certificate"`, fmt.Sprintf(`"file"=%q`, file), `"subject"=`), 1,
"expected one certificate logged for %s, got log lines:\n%s", file, strings.Join(*lines, "\n"))
}
require.Empty(t, linesContaining(*lines, `"error"=`), "unexpected error log lines")
}

func TestLogDockerCertificates(t *testing.T) {
certsDir := t.TempDir()
hostDir := filepath.Join(certsDir, "registry.example.com:5000")
require.NoError(t, os.Mkdir(hostDir, 0o755))
require.NoError(t, os.Mkdir(filepath.Join(hostDir, "subdir"), 0o755))
for src, dst := range map[string]string{
"Amazon_Root_CA_1.pem": "ca.crt",
"Amazon_Root_CA_3.pem": "client.cert", // private key followed by a certificate
} {
data, err := os.ReadFile(filepath.Join(goodCertsDir, src))
require.NoError(t, err)
require.NoError(t, os.WriteFile(filepath.Join(hostDir, dst), data, 0o600))
}
require.NoError(t, os.WriteFile(filepath.Join(hostDir, "empty.crt"), nil, 0o600))
require.NoError(t, os.WriteFile(filepath.Join(certsDir, "not-a-host-dir"), nil, 0o600))

log, lines := newCaptureLogger()
httputil.LogDockerCertificates(certsDir, log)

for _, file := range []string{"ca.crt", "client.cert"} {
require.Len(t, linesContaining(*lines, `"msg"="dump docker certs directory"`, fmt.Sprintf(`"file"=%q`, file), `"subject"=`), 1,
"expected one certificate logged for %s, got log lines:\n%s", file, strings.Join(*lines, "\n"))
}
require.Len(t, linesContaining(*lines, `"file"="empty.crt"`, `"empty"="true"`), 1)
require.Len(t, linesContaining(*lines, `"msg"="ignoring subdirectory"`), 1)
require.Len(t, linesContaining(*lines, `"msg"="ignoring non-directory"`), 1)
require.Empty(t, linesContaining(*lines, `"error"=`), "unexpected error log lines")
}

func TestLogDockerCertificatesMissingDirectory(t *testing.T) {
log, lines := newCaptureLogger()
httputil.LogDockerCertificates(filepath.Join(t.TempDir(), "does-not-exist"), log)
require.Len(t, linesContaining(*lines, `"msg"="statting directory"`, `"error"=`), 1)
}

func TestLogCertificateVerificationError(t *testing.T) {
cert1 := readCert(t, filepath.Join(goodCertsDir, "Amazon_Root_CA_1.pem"))
cert2 := readCert(t, filepath.Join(goodCertsDir, "Amazon_Root_CA_2.pem"))
cvErr := &tls.CertificateVerificationError{
UnverifiedCertificates: []*x509.Certificate{cert1, cert2},
Err: errors.New("x509: certificate signed by unknown authority"),
}

for _, tc := range []struct {
name string
err error
expectFound bool
expectLogLine int
}{
{name: "nil error", err: nil},
{name: "unrelated error", err: errors.New("boom")},
{name: "certificate verification error", err: cvErr, expectFound: true, expectLogLine: 2},
{name: "wrapped certificate verification error", err: fmt.Errorf("pulling image: %w", cvErr), expectFound: true, expectLogLine: 2},
} {
t.Run(tc.name, func(t *testing.T) {
log, lines := newCaptureLogger()
require.Equal(t, tc.expectFound, httputil.LogCertificateVerificationError(tc.err, log))
require.Len(t, linesContaining(*lines, `"msg"="unverified cert"`), tc.expectLogLine)
})
}
}
Loading