-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathcache.go
280 lines (230 loc) · 6.04 KB
/
cache.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
package certify
import (
"context"
"crypto/tls"
"crypto/x509"
"encoding/pem"
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"sync"
"github.com/johanbrandhorst/certify/internal/keys"
)
const (
keyExt = ".key"
certExt = ".crt"
)
// Cache describes the interface that certificate caches must implement.
// Cache implementations must be thread safe.
type Cache interface {
// Get returns a certificate data for the specified key.
// If there's no such key, Get returns ErrCacheMiss.
Get(context.Context, string) (*tls.Certificate, error)
// Put stores the data in the cache under the specified key.
Put(context.Context, string, *tls.Certificate) error
// Delete removes a certificate data from the cache under the specified key.
// If there's no such key in the cache, Delete returns nil.
Delete(context.Context, string) error
}
// ErrCacheMiss should be returned by Cache implementations
// when a certificate could not be found.
var ErrCacheMiss = errors.New("no matching certificate found")
type memCache struct {
mu *sync.RWMutex
cache map[string]*tls.Certificate
}
// NewMemCache creates an in-memory cache that implements the Cache interface.
func NewMemCache() Cache {
return &memCache{
mu: &sync.RWMutex{},
cache: map[string]*tls.Certificate{},
}
}
func (m memCache) Get(_ context.Context, key string) (*tls.Certificate, error) {
m.mu.RLock()
defer m.mu.RUnlock()
cert, ok := m.cache[key]
if ok {
return cert, nil
}
return nil, ErrCacheMiss
}
func (m *memCache) Put(_ context.Context, key string, cert *tls.Certificate) error {
m.mu.Lock()
defer m.mu.Unlock()
m.cache[key] = cert
return nil
}
func (m *memCache) Delete(_ context.Context, key string) error {
m.mu.Lock()
defer m.mu.Unlock()
delete(m.cache, key)
return nil
}
// DirCache implements Cache using a directory on the local filesystem.
// If the directory does not exist, it will be created with 0700 permissions.
//
// It is strongly based on the acme/autocert DirCache type.
// https://github.com/golang/crypto/blob/88942b9c40a4c9d203b82b3731787b672d6e809b/acme/autocert/cache.go#L40
type DirCache string
// Get reads a certificate data from the specified file name.
func (d DirCache) Get(ctx context.Context, name string) (*tls.Certificate, error) {
name = filepath.Join(string(d), name)
var (
cert tls.Certificate
err error
done = make(chan struct{})
)
go func() {
cert, err = tls.LoadX509KeyPair(name+certExt, name+keyExt)
if err == nil {
// Need to parse the Leaf manually for expiration checks
var leaf *x509.Certificate
leaf, err = x509.ParseCertificate(cert.Certificate[0])
if err == nil {
cert.Leaf = leaf
}
}
close(done)
}()
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-done:
}
if os.IsNotExist(err) {
return nil, ErrCacheMiss
}
if err != nil {
return nil, err
}
return &cert, nil
}
// Put writes the certificate data to the specified file name.
// The file will be created with 0600 permissions.
func (d DirCache) Put(ctx context.Context, name string, cert *tls.Certificate) error {
if err := os.MkdirAll(string(d), 0o700); err != nil {
return err
}
done := make(chan struct{})
var (
err error
tmpKey, tmpCert string
newName = filepath.Join(string(d), name)
)
go func() {
defer close(done)
var tmpKey, tmpCert string
if tmpKey, tmpCert, err = d.writeTempFiles(name, cert); err != nil {
return
}
select {
case <-ctx.Done():
// Don't overwrite the file if the context was canceled.
default:
newName := filepath.Join(string(d), name)
err = os.Rename(tmpKey, newName+keyExt)
if err != nil {
return
}
err = os.Rename(tmpCert, newName+certExt)
if err != nil {
return
}
}
}()
select {
case <-ctx.Done():
return ctx.Err()
case <-done:
}
// Clean up after ourselves on error, remove all artifacts from this request
if err != nil {
err = removeWrapErr(tmpKey, err)
err = removeWrapErr(tmpCert, err)
err = removeWrapErr(newName+keyExt, err)
err = removeWrapErr(newName+certExt, err)
}
return err
}
// Delete removes the specified file name.
func (d DirCache) Delete(ctx context.Context, name string) error {
name = filepath.Join(string(d), name)
var (
err error
done = make(chan struct{})
)
go func() {
defer close(done)
err = removeWrapErr(name+keyExt, err)
err = removeWrapErr(name+certExt, err)
}()
select {
case <-ctx.Done():
return ctx.Err()
case <-done:
}
return err
}
func removeWrapErr(fileName string, err error) error {
if e := os.Remove(fileName); e != nil && !os.IsNotExist(e) {
err = fmt.Errorf("failed to delete %s: %v: %v", fileName, e, err)
}
return err
}
// writeTempFile writes b to a temporary file, closes the file and returns its path.
func (d DirCache) writeTempFiles(prefix string, cert *tls.Certificate) (string, string, error) {
keyPath, err := d.writeTempKey(prefix, cert)
if err != nil {
return "", "", err
}
certPath, err := d.writeTempCert(prefix, cert)
if err != nil {
return "", "", err
}
return keyPath, certPath, err
}
func (d DirCache) writeTempKey(prefix string, cert *tls.Certificate) (string, error) {
pem, err := keys.Marshal(cert.PrivateKey)
if err != nil {
return "", err
}
// TempFile uses 0600 permissions
f, err := ioutil.TempFile(string(d), prefix+keyExt)
if err != nil {
return "", err
}
if _, err = f.Write(pem); err != nil {
return "", err
}
return f.Name(), f.Close()
}
func (d DirCache) writeTempCert(prefix string, cert *tls.Certificate) (string, error) {
f, err := ioutil.TempFile(string(d), prefix+certExt)
if err != nil {
return "", err
}
for _, c := range cert.Certificate {
block := &pem.Block{
Type: "CERTIFICATE",
Bytes: c,
}
err := pem.Encode(f, block)
if err != nil {
return "", err
}
}
return f.Name(), f.Close()
}
type noopCache struct{}
func (*noopCache) Get(context.Context, string) (*tls.Certificate, error) {
return nil, ErrCacheMiss
}
func (*noopCache) Put(context.Context, string, *tls.Certificate) error {
return nil
}
func (*noopCache) Delete(context.Context, string) error {
return nil
}