Skip to content

Commit 0dc7d08

Browse files
committed
Allow user to provide existing CA certificate and key
1 parent e9dc12d commit 0dc7d08

File tree

2 files changed

+29
-5
lines changed

2 files changed

+29
-5
lines changed

pkg/certificate/certificate.go

+19-4
Original file line numberDiff line numberDiff line change
@@ -52,8 +52,9 @@ type Certificate struct {
5252
NotAfter *time.Time `yaml:"not_after"`
5353

5454
// generated at runtime, not read from yaml
55-
Key crypto.Signer `yaml:"-"`
56-
Cert []byte `yaml:"-"`
55+
Key crypto.Signer `yaml:"-"`
56+
Cert []byte `yaml:"-"`
57+
Generated bool `hash:"-"`
5758
}
5859

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

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

251+
// Mark the state as valid
252+
c.Generated = true
253+
250254
return err
251255
}
252256

@@ -311,16 +315,27 @@ func (c *Certificate) Load(srcdir string) error {
311315
return err
312316
}
313317
decoded, _ = pem.Decode(buf)
314-
if decoded == nil || decoded.Type != "PRIVATE KEY" {
318+
if decoded == nil {
319+
return fmt.Errorf("Error while decoding %s", keyFilename)
320+
}
321+
322+
var key interface{}
323+
if decoded.Type == "PRIVATE KEY" {
324+
key, err = x509.ParsePKCS8PrivateKey(decoded.Bytes)
325+
} else if decoded.Type == "RSA PRIVATE KEY" {
326+
key, err = x509.ParsePKCS1PrivateKey(decoded.Bytes)
327+
} else {
315328
return fmt.Errorf("Error while decoding %s", keyFilename)
316329
}
317330

318-
key, err := x509.ParsePKCS8PrivateKey(decoded.Bytes)
319331
if err != nil {
320332
return err
321333
}
322334
c.Key = key.(crypto.Signer)
323335

336+
// Mark the state as valid
337+
c.Generated = true
338+
324339
return nil
325340
}
326341

pkg/certificate/manifest.go

+10-1
Original file line numberDiff line numberDiff line change
@@ -67,11 +67,20 @@ func GenerateCertficatesFromManifest(manifestFilename, stateFilename, destinatio
6767
allCerts[c.Subject] = &c
6868

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

76+
// if certificate is already valid but it did not exist in state file:
77+
// "adopt" the existing certificate like we would have generated it
78+
if c.Generated && !ok {
79+
fmt.Printf("Recognized existing certificate: skipping %s\n", c.Filename)
80+
state[c.Subject] = c.Hash()
81+
continue // continue to next certificate in manifest
82+
}
83+
7584
ca, ok := allCerts[c.Issuer]
7685
if c.Issuer != "" && !ok {
7786
return fmt.Errorf("Issuer field defined but CA certificate `%s` not found", c.Issuer)

0 commit comments

Comments
 (0)