refactor: move ReadCSRFile

This commit is contained in:
Fernandez Ludovic 2026-03-08 17:30:00 +01:00
commit 6a4723cb2f
4 changed files with 37 additions and 36 deletions

View file

@ -189,7 +189,7 @@ func renewForDomains(ctx context.Context, cmd *cli.Command, lazyClient lzSetUp,
}
func renewForCSR(ctx context.Context, cmd *cli.Command, lazyClient lzSetUp, certsStorage *storage.CertificatesStorage, hookManager *hook.Manager) error {
csr, err := readCSRFile(cmd.String(flgCSR))
csr, err := storage.ReadCSRFile(cmd.String(flgCSR))
if err != nil {
return fmt.Errorf("could not read CSR file %q: %w", cmd.String(flgCSR), err)
}

View file

@ -116,7 +116,7 @@ func obtainCertificate(ctx context.Context, cmd *cli.Command, client *lego.Clien
}
// read the CSR
csr, err := readCSRFile(cmd.String(flgCSR))
csr, err := storage.ReadCSRFile(cmd.String(flgCSR))
if err != nil {
return nil, err
}

View file

@ -3,6 +3,7 @@ package storage
import (
"crypto"
"crypto/x509"
"encoding/pem"
"fmt"
"log/slog"
"os"
@ -120,3 +121,37 @@ func ReadCertificateFile(filename string) ([]*x509.Certificate, error) {
return certs, nil
}
// ReadCSRFile reads a CSR file.
func ReadCSRFile(filename string) (*x509.CertificateRequest, error) {
bytes, err := os.ReadFile(filename)
if err != nil {
return nil, err
}
raw := bytes
// see if we can find a PEM-encoded CSR
var p *pem.Block
rest := bytes
for {
// decode a PEM block
p, rest = pem.Decode(rest)
// did we fail?
if p == nil {
break
}
// did we get a CSR?
if p.Type == "CERTIFICATE REQUEST" || p.Type == "NEW CERTIFICATE REQUEST" {
raw = p.Bytes
}
}
// no PEM-encoded CSR
// assume we were given a DER-encoded ASN.1 CSR
// (if this assumption is wrong, parsing these bytes will fail)
return x509.ParseCertificateRequest(raw)
}

View file

@ -4,7 +4,6 @@ import (
"context"
"crypto/x509"
"encoding/json"
"encoding/pem"
"errors"
"fmt"
"io"
@ -128,39 +127,6 @@ func checkRetry(ctx context.Context, resp *http.Response, err error) (bool, erro
return rt, nil
}
func readCSRFile(filename string) (*x509.CertificateRequest, error) {
bytes, err := os.ReadFile(filename)
if err != nil {
return nil, err
}
raw := bytes
// see if we can find a PEM-encoded CSR
var p *pem.Block
rest := bytes
for {
// decode a PEM block
p, rest = pem.Decode(rest)
// did we fail?
if p == nil {
break
}
// did we get a CSR?
if p.Type == "CERTIFICATE REQUEST" || p.Type == "NEW CERTIFICATE REQUEST" {
raw = p.Bytes
}
}
// no PEM-encoded CSR
// assume we were given a DER-encoded ASN.1 CSR
// (if this assumption is wrong, parsing these bytes will fail)
return x509.ParseCertificateRequest(raw)
}
func newObtainRequest(cmd *cli.Command, domains []string) certificate.ObtainRequest {
return certificate.ObtainRequest{
Domains: domains,