-
Notifications
You must be signed in to change notification settings - Fork 0
/
cert.go
72 lines (58 loc) · 2.66 KB
/
cert.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package tlsx
import (
"crypto/tls"
"encoding/base64"
"fmt"
"github.com/pkg/errors"
"github.com/spf13/viper"
)
var ErrNoCertificatesConfigured = errors.New("no tls configuration was found")
var ErrInvalidCertificateConfiguration = errors.New("tls configuration is invalid")
func HTTPSCertificate() ([]tls.Certificate, error) {
return Certificate("HTTPS_TLS")
}
func HTTPSCertificateHelpMessage() string {
return CertificateHelpMessage("HTTPS_TLS")
}
// CertificateHelpMessage returns a help message for configuring TLS Certificates
func CertificateHelpMessage(prefix string) string {
return `- ` + prefix + `_CERT_PATH: The path to the TLS certificate (pem encoded).
Example: ` + prefix + `_CERT_PATH=~/cert.pem
- ` + prefix + `_KEY_PATH: The path to the TLS private key (pem encoded).
Example: ` + prefix + `_KEY_PATH=~/key.pem
- ` + prefix + `_CERT: Base64 encoded (without padding) string of the TLS certificate (PEM encoded) to be used for HTTP over TLS (HTTPS).
Example: ` + prefix + `_CERT="-----BEGIN CERTIFICATE-----\nMIIDZTCCAk2gAwIBAgIEV5xOtDANBgkqhkiG9w0BAQ0FADA0MTIwMAYDVQQDDClP..."
- ` + prefix + `_KEY: Base64 encoded (without padding) string of the private key (PEM encoded) to be used for HTTP over TLS (HTTPS).
Example: ` + prefix + `_KEY="-----BEGIN ENCRYPTED PRIVATE KEY-----\nMIIFDjBABgkqhkiG9w0BBQ0wMzAbBgkqhkiG9w0BBQwwDg..."
`
}
// Certificate returns loads a TLS Certificate by looking at environment variables
func Certificate(prefix string) ([]tls.Certificate, error) {
certString, keyString := viper.GetString(prefix+"_CERT"), viper.GetString(prefix+"_KEY")
certPath, keyPath := viper.GetString(prefix+"_CERT_PATH"), viper.GetString(prefix+"_KEY_PATH")
if certString == "" && keyString == "" && certPath == "" && keyPath == "" {
return nil, errors.WithStack(ErrNoCertificatesConfigured)
} else if certString != "" && keyString != "" {
tlsCertBytes, err := base64.StdEncoding.DecodeString(certString)
if err != nil {
return nil, fmt.Errorf("unable to base64 decode the TLS certificate: %v", err)
}
tlsKeyBytes, err := base64.StdEncoding.DecodeString(keyString)
if err != nil {
return nil, fmt.Errorf("unable to base64 decode the TLS private key: %v", err)
}
cert, err := tls.X509KeyPair(tlsCertBytes, tlsKeyBytes)
if err != nil {
return nil, fmt.Errorf("unable to load X509 key pair: %v", err)
}
return []tls.Certificate{cert}, nil
}
if certPath != "" && keyPath != "" {
cert, err := tls.LoadX509KeyPair(certPath, keyPath)
if err != nil {
return nil, fmt.Errorf("unable to load X509 key pair from files: %v", err)
}
return []tls.Certificate{cert}, nil
}
return nil, errors.WithStack(ErrInvalidCertificateConfiguration)
}