diff --git a/pkg/cryptutil/pem.go b/pkg/cryptutil/pem.go index 00d94b7b6..fb0720240 100644 --- a/pkg/cryptutil/pem.go +++ b/pkg/cryptutil/pem.go @@ -14,6 +14,11 @@ import ( // If the PEM data contains multiple certificates, signing certificates // will be moved after the things they sign. func NormalizePEM(data []byte) []byte { + // make sure the file has a trailing newline + if len(data) > 0 && !bytes.HasSuffix(data, []byte{'\n'}) { + data = append(data, '\n') + } + type Segment struct { ID int Data []byte diff --git a/pkg/cryptutil/pem_test.go b/pkg/cryptutil/pem_test.go index 30288503a..d286d7f02 100644 --- a/pkg/cryptutil/pem_test.go +++ b/pkg/cryptutil/pem_test.go @@ -1,6 +1,7 @@ package cryptutil_test import ( + "bytes" "slices" "testing" @@ -23,6 +24,11 @@ func TestNormalizePEM(t *testing.T) { input: slices.Concat(rootCA.PublicPEM, intermediateCA.PublicPEM, cert.PublicPEM, cert.PrivateKeyPEM), expect: slices.Concat(cert.PublicPEM, cert.PrivateKeyPEM, intermediateCA.PublicPEM, rootCA.PublicPEM), }, + { + // make sure we handle a file without a trailing newline + input: slices.Concat(intermediateCA.PublicPEM, bytes.TrimRight(cert.PublicPEM, "\n")), + expect: slices.Concat(cert.PublicPEM, intermediateCA.PublicPEM), + }, { input: slices.Concat(cert.PublicPEM, cert.PrivateKeyPEM, intermediateCA.PublicPEM, rootCA.PublicPEM), expect: slices.Concat(cert.PublicPEM, cert.PrivateKeyPEM, intermediateCA.PublicPEM, rootCA.PublicPEM),