-
Notifications
You must be signed in to change notification settings - Fork 0
/
tls.go
103 lines (85 loc) · 2.09 KB
/
tls.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package hyper
import (
"bytes"
"crypto/tls"
"encoding/base64"
"encoding/pem"
"errors"
"os"
)
var getenv = os.Getenv
var _ TLSDescriptor = environmentTLS{}
type TLSDescriptor interface {
from() (*tls.Config, error)
}
// -----------------------------------
// TLS from environment
type environmentTLS struct {
env EnvironmentTLSOpts
}
type EnvironmentTLSOpts struct {
TLSCert string
TLSCertBlockType string
TLSKey string
TLSKeyBlockType string
}
func NewEnvironmentTLS(e EnvironmentTLSOpts) TLSDescriptor {
return environmentTLS{env: e}
}
func (t environmentTLS) from() (*tls.Config, error) {
cert := getenv(t.env.TLSCert)
certBlockType := getenv(t.env.TLSCertBlockType)
key := getenv(t.env.TLSKey)
keyBlockName := getenv(t.env.TLSKeyBlockType)
if cert == "" || certBlockType == "" || key == "" || keyBlockName == "" {
return nil, errors.New("invalid certification setup")
}
certDecoded, err := base64.StdEncoding.DecodeString(cert)
if err != nil {
return nil, err
}
certBlock := pem.Block{
Type: certBlockType,
Bytes: certDecoded,
}
certBuf := new(bytes.Buffer)
if err := pem.Encode(certBuf, &certBlock); err != nil {
return nil, err
}
keyDecoded, err := base64.StdEncoding.DecodeString(key)
if err != nil {
return nil, err
}
keyBlock := pem.Block{
Type: keyBlockName,
Bytes: keyDecoded,
}
keyBuf := new(bytes.Buffer)
if err := pem.Encode(keyBuf, &keyBlock); err != nil {
return nil, err
}
certificate, err := tls.X509KeyPair(certBuf.Bytes(), keyBuf.Bytes())
if err != nil {
return nil, err
}
return &tls.Config{Certificates: []tls.Certificate{certificate}}, nil
}
// -----------------------------------
// TLS from file
type fileTLS struct {
env FileTLSOpts
}
type FileTLSOpts struct {
TLSCertPath string
TLSKeyPath string
}
func NewFileTLS(e FileTLSOpts) TLSDescriptor {
return fileTLS{env: e}
}
func (t fileTLS) from() (*tls.Config, error) {
cert, err := tls.LoadX509KeyPair(os.Getenv(t.env.TLSCertPath), os.Getenv(t.env.TLSKeyPath))
if err != nil {
return nil, err
}
return &tls.Config{Certificates: []tls.Certificate{cert}}, nil
}