Skip to content

DEV-78 - Allow specifying certificate file names #25

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Mar 22, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,5 @@ ca/
es-gencert-cli
certs.yml
.DS_Store
*.crt
*.key
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,8 @@ certificates:
dns-names: "localhost,eventstore-node2.localhost.com"
```

If you want to specify the name of the certificates from the config file, you can add the name field to the certificate definition. You can see an example of this in the [example configuration](references/named_certs.yml).

## Development

Building or working on `es-gencert-cli` requires a Go environment, version 1.14 or higher.
2 changes: 1 addition & 1 deletion certificates/boring_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,4 @@ import (

func isBoringEnabled() bool {
return boring.Enabled()
}
}
60 changes: 0 additions & 60 deletions certificates/certificates.go

This file was deleted.

47 changes: 27 additions & 20 deletions certificates/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,18 @@ import (
"math/big"
"os"
"path"
"text/tabwriter"
"path/filepath"
)

const defaultKeySize = 2048

const forceOption = "Force overwrite of existing files without prompting"

const (
ErrFileExists = "Error: Existing files would be overwritten. Use -force to proceed"
ForceFlagUsage = "Force overwrite of existing files without prompting"
NameFlagUsage = "The name of the CA certificate and key file"
OutDirFlagUsage = "The output directory"
DayFlagUsage = "the validity period of the certificate in days"
CaKeyFlagUsage = "the path to the CA key file"
CaCertFlagUsage = "the path to the CA certificate file"
)
const defaultKeySize = 2048

func generateSerialNumber(bits uint) (*big.Int, error) {
maxValue := new(big.Int).Lsh(big.NewInt(1), bits)
Expand Down Expand Up @@ -48,13 +50,9 @@ func writeFileWithDir(filePath string, data []byte, perm os.FileMode) error {
return os.WriteFile(filePath, data, perm)
}

func writeHelpOption(w *tabwriter.Writer, title string, description string) {
fmt.Fprintf(w, "\t-%s\t%s\n", title, description)
}

func writeCertAndKey(outputDir string, fileName string, certPem, privateKeyPem *bytes.Buffer, force bool) error {
certFile := path.Join(outputDir, fileName+".crt")
keyFile := path.Join(outputDir, fileName+".key")
certFile := filepath.Join(outputDir, fileName+".crt")
keyFile := filepath.Join(outputDir, fileName+".key")

if force {
if _, err := os.Stat(certFile); err == nil {
Expand All @@ -76,19 +74,12 @@ func writeCertAndKey(outputDir string, fileName string, certPem, privateKeyPem *

err = writeFileWithDir(keyFile, privateKeyPem.Bytes(), 0400)
if err != nil {
return fmt.Errorf("error writing certificate private key to %s: %s", keyFile, err.Error())
return fmt.Errorf("error writing private key to %s: %s", keyFile, err.Error())
}

return nil
}

func fileExists(path string, force bool) bool {
if _, err := os.Stat(path); !os.IsNotExist(err) && !force {
return true
}
return false
}

func readCertificateFromFile(path string) (*x509.Certificate, error) {
pemBytes, err := os.ReadFile(path)
if err != nil {
Expand Down Expand Up @@ -124,3 +115,19 @@ func readRSAKeyFromFile(path string) (*rsa.PrivateKey, error) {
}
return key, nil
}

func checkCertificatesLocationWithForce(dir, certificateName string, force bool) error {
// Throw an error if the path for the CA and key certificates already
// exists and the 'force' flag is not set.

checkFile := func(ext string) bool {
_, err := os.Stat(filepath.Join(dir, certificateName+ext))
return !os.IsNotExist(err)
}

if !force && (checkFile(".key") || checkFile(".crt")) {
return fmt.Errorf("existing files would be overwritten. Use -force to proceed")
}

return nil
}
69 changes: 42 additions & 27 deletions certificates/common_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,42 +3,57 @@ package certificates
import (
"crypto/rsa"
"crypto/x509"
"fmt"
"github.com/stretchr/testify/assert"
"os"
"path"
"path/filepath"
"regexp"
"strings"
"testing"
)

func assertFilesExist(t *testing.T, files ...string) {
for _, file := range files {
_, err := os.Stat(file)
assert.False(t, os.IsNotExist(err))
}
}
func extractErrors(errorMessage string) []string {
// Sometimes errors are shown in a multi-line format (multierror.Append), so we need to extract them and return them
// as a list. However, this method can be used with single line errors as well and will return a list with a single
// element. Also perform some basic cleanup of the error message (TrimSpace).

func generateAndAssertCACert(t *testing.T, years int, days int, outputDirCa string, force bool) (*x509.Certificate, *rsa.PrivateKey) {
certificateError := generateCACertificate(years, days, outputDirCa, nil, nil, force)
assert.NoError(t, certificateError)
var errors []string

certFilePath := path.Join(outputDirCa, "ca.crt")
keyFilePath := path.Join(outputDirCa, "ca.key")
assertFilesExist(t, certFilePath, keyFilePath)
// Pattern for multi-line errors
multiLinePattern := regexp.MustCompile(`\* (.+)`)
multiLineMatches := multiLinePattern.FindAllStringSubmatch(errorMessage, -1)

caCertificate, err := readCertificateFromFile(certFilePath)
assert.NoError(t, err)
caPrivateKey, err := readRSAKeyFromFile(keyFilePath)
assert.NoError(t, err)
ansiCodePattern := regexp.MustCompile(`\x1b\[[0-9;]*m`)
errorMessage = ansiCodePattern.ReplaceAllString(errorMessage, "")

return caCertificate, caPrivateKey
}

func cleanupDirsForTest(t *testing.T, dirs ...string) {
cleanupDirs := func() {
for _, dir := range dirs {
os.RemoveAll(dir)
if len(multiLineMatches) > 0 {
for _, match := range multiLineMatches {
if len(match) > 1 {
errors = append(errors, strings.TrimSpace(match[1]))
}
}
} else {
// Single line error
cleanedError := strings.TrimSpace(errorMessage)
errors = append(errors, cleanedError)
}

cleanupDirs()
t.Cleanup(cleanupDirs)
return errors
}

func readAndDecodeCertificateAndKey(t *testing.T, dir, name string) (*x509.Certificate, *rsa.PrivateKey) {
// In the test suite, we often need to verify that a certificate and key pair exist in a given directory.
// This is usually carried out after a call to the create_ca or create_node commands. This method reads the certificate
// and key from the given directory and returns them. It will throw an error if the certificate or key cannot be
// read from the given directory.

certPath := filepath.Join(dir, fmt.Sprintf("%s.crt", name))
keyPath := filepath.Join(dir, fmt.Sprintf("%s.key", name))

ca, caErr := readCertificateFromFile(certPath)
assert.NoError(t, caErr)

key, keyErr := readRSAKeyFromFile(keyPath)
assert.NoError(t, keyErr)

return ca, key
}
Loading
Loading