Skip to content

Commit

Permalink
Allow user to provide existing CA certificate and key
Browse files Browse the repository at this point in the history
  • Loading branch information
tsaarni committed Oct 16, 2020
1 parent e9dc12d commit 0dc7d08
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 5 deletions.
23 changes: 19 additions & 4 deletions pkg/certificate/certificate.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,9 @@ type Certificate struct {
NotAfter *time.Time `yaml:"not_after"`

// generated at runtime, not read from yaml
Key crypto.Signer `yaml:"-"`
Cert []byte `yaml:"-"`
Key crypto.Signer `yaml:"-"`
Cert []byte `yaml:"-"`
Generated bool `hash:"-"`
}

// getKeyUsage converts key usage string representation to x509.KeyUsage
Expand Down Expand Up @@ -247,6 +248,9 @@ func (c *Certificate) Generate(ca *Certificate) error {

c.Cert, err = x509.CreateCertificate(rand.Reader, template, issuerCert, c.Key.Public(), issuerKey)

// Mark the state as valid
c.Generated = true

return err
}

Expand Down Expand Up @@ -311,16 +315,27 @@ func (c *Certificate) Load(srcdir string) error {
return err
}
decoded, _ = pem.Decode(buf)
if decoded == nil || decoded.Type != "PRIVATE KEY" {
if decoded == nil {
return fmt.Errorf("Error while decoding %s", keyFilename)
}

var key interface{}
if decoded.Type == "PRIVATE KEY" {
key, err = x509.ParsePKCS8PrivateKey(decoded.Bytes)
} else if decoded.Type == "RSA PRIVATE KEY" {
key, err = x509.ParsePKCS1PrivateKey(decoded.Bytes)
} else {
return fmt.Errorf("Error while decoding %s", keyFilename)
}

key, err := x509.ParsePKCS8PrivateKey(decoded.Bytes)
if err != nil {
return err
}
c.Key = key.(crypto.Signer)

// Mark the state as valid
c.Generated = true

return nil
}

Expand Down
11 changes: 10 additions & 1 deletion pkg/certificate/manifest.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,11 +67,20 @@ func GenerateCertficatesFromManifest(manifestFilename, stateFilename, destinatio
allCerts[c.Subject] = &c

// compare hash from state file to has of loaded certificate
if state[c.Subject] == c.Hash() {
hash, ok := state[c.Subject]
if hash == c.Hash() {
fmt.Printf("No changes: skipping %s\n", c.Filename)
continue // continue to next certificate in manifest
}

// if certificate is already valid but it did not exist in state file:
// "adopt" the existing certificate like we would have generated it
if c.Generated && !ok {
fmt.Printf("Recognized existing certificate: skipping %s\n", c.Filename)
state[c.Subject] = c.Hash()
continue // continue to next certificate in manifest
}

ca, ok := allCerts[c.Issuer]
if c.Issuer != "" && !ok {
return fmt.Errorf("Issuer field defined but CA certificate `%s` not found", c.Issuer)
Expand Down

0 comments on commit 0dc7d08

Please sign in to comment.