-
Notifications
You must be signed in to change notification settings - Fork 28
/
encrypting_repository.go
279 lines (225 loc) · 9.15 KB
/
encrypting_repository.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
package storage
import (
"context"
"crypto/rand"
"fmt"
"time"
"github.com/Peripli/service-manager/pkg/log"
"github.com/Peripli/service-manager/pkg/security"
"github.com/Peripli/service-manager/pkg/query"
"github.com/Peripli/service-manager/pkg/types"
)
// LockerCreatorFunc is a function building a storage.Locker with a specific advisory index
type LockerCreatorFunc func(advisoryIndex int) Locker
// Locker provides basic Lock/Unlock functionality
type Locker interface {
// Lock locks the storage so that only one process can acquire it. Returns an error if the process has already acquired the lock, but waits if the lock is acquired by different connection
Lock(ctx context.Context) error
// TryLock tries to lock the storage, if it is already locked it returns an error, that it is already locked and does not wait
TryLock(ctx context.Context) error
// Unlock releases the acquired lock.
Unlock(ctx context.Context) error
}
// KeyStore interface for encryption key operations
type KeyStore interface {
// GetEncryptionKey returns the encryption key from the storage after applying the specified transformation function
GetEncryptionKey(ctx context.Context, transformationFunc func(context.Context, []byte, []byte) ([]byte, error)) ([]byte, error)
// SetEncryptionKey sets the provided encryption key in the KeyStore after applying the specified transformation function
SetEncryptionKey(ctx context.Context, key []byte, transformationFunc func(context.Context, []byte, []byte) ([]byte, error)) error
}
// EncryptingDecorator creates a TransactionalRepositoryDecorator that can be used to add encrypting/decrypting logic to a TransactionalRepository
func EncryptingDecorator(ctx context.Context, encrypter security.Encrypter, keyStore KeyStore, locker Locker) TransactionalRepositoryDecorator {
return func(next TransactionalRepository) (TransactionalRepository, error) {
ctx, cancelFunc := context.WithTimeout(ctx, 2*time.Second)
defer cancelFunc()
if err := locker.Lock(ctx); err != nil {
return nil, err
}
defer func() {
if err := locker.Unlock(ctx); err != nil {
log.C(ctx).WithError(err).Error("error while unlocking keystore")
}
}()
encryptionKey, err := keyStore.GetEncryptionKey(ctx, encrypter.Decrypt)
if err != nil {
return nil, err
}
if len(encryptionKey) == 0 {
logger := log.C(ctx)
logger.Info("No encryption key is present. Generating new one...")
newEncryptionKey := make([]byte, 32)
if _, err = rand.Read(newEncryptionKey); err != nil {
return nil, fmt.Errorf("could not generate encryption key: %v", err)
}
encryptionKey = newEncryptionKey
if err = keyStore.SetEncryptionKey(ctx, newEncryptionKey, encrypter.Encrypt); err != nil {
return nil, err
}
logger.Info("Successfully generated new encryption key")
}
return NewEncryptingRepository(next, encrypter, encryptionKey)
}
}
//NewEncryptingRepository creates a new TransactionalEncryptingRepository using the specified encrypter and encryption key
func NewEncryptingRepository(repository TransactionalRepository, encrypter security.Encrypter, key []byte) (*TransactionalEncryptingRepository, error) {
encryptingRepository := &TransactionalEncryptingRepository{
encryptingRepository: &encryptingRepository{
repository: repository,
encrypter: encrypter,
encryptionKey: key,
},
repository: repository,
}
return encryptingRepository, nil
}
type encryptingRepository struct {
repository Repository
encrypter security.Encrypter
encryptionKey []byte
}
//TransactionalEncryptingRepository is a TransactionalRepository with that also encrypts credentials of Secured objects
// before storing in the database them and decrypts credentials of Secured objects when reading them from the database
type TransactionalEncryptingRepository struct {
*encryptingRepository
repository TransactionalRepository
}
func (er *encryptingRepository) QueryForList(ctx context.Context, objectType types.ObjectType, queryName NamedQuery, queryParams map[string]interface{}) (types.ObjectList, error) {
objList, err := er.repository.QueryForList(ctx, objectType, queryName, queryParams)
if err != nil {
return nil, err
}
for i := 0; i < objList.Len(); i++ {
if err := er.decrypt(ctx, objList.ItemAt(i)); err != nil {
return nil, err
}
}
return objList, nil
}
func (er *encryptingRepository) Create(ctx context.Context, obj types.Object) (types.Object, error) {
if err := er.encrypt(ctx, obj); err != nil {
return nil, err
}
newObj, err := er.repository.Create(ctx, obj)
if err != nil {
return nil, err
}
if err := er.decrypt(ctx, newObj); err != nil {
return nil, err
}
return newObj, nil
}
func (er *encryptingRepository) Get(ctx context.Context, objectType types.ObjectType, criteria ...query.Criterion) (types.Object, error) {
obj, err := er.repository.Get(ctx, objectType, criteria...)
if err != nil {
return nil, err
}
if err := er.decrypt(ctx, obj); err != nil {
return nil, err
}
return obj, nil
}
func (er *encryptingRepository) GetForUpdate(ctx context.Context, objectType types.ObjectType, criteria ...query.Criterion) (types.Object, error) {
obj, err := er.repository.Get(ctx, objectType, criteria...)
if err != nil {
return nil, err
}
if err := er.decrypt(ctx, obj); err != nil {
return nil, err
}
return obj, nil
}
func (er *encryptingRepository) List(ctx context.Context, objectType types.ObjectType, criteria ...query.Criterion) (types.ObjectList, error) {
return er.list(ctx, objectType, true, criteria...)
}
func (er *encryptingRepository) ListNoLabels(ctx context.Context, objectType types.ObjectType, criteria ...query.Criterion) (types.ObjectList, error) {
return er.list(ctx, objectType, false, criteria...)
}
func (er *encryptingRepository) list(ctx context.Context, objectType types.ObjectType, withLabels bool, criteria ...query.Criterion) (types.ObjectList, error) {
var (
objList types.ObjectList
err error
)
if withLabels {
objList, err = er.repository.List(ctx, objectType, criteria...)
} else {
objList, err = er.repository.ListNoLabels(ctx, objectType, criteria...)
}
if err != nil {
return nil, err
}
for i := 0; i < objList.Len(); i++ {
if err := er.decrypt(ctx, objList.ItemAt(i)); err != nil {
return nil, err
}
}
return objList, nil
}
func (er *encryptingRepository) Count(ctx context.Context, objectType types.ObjectType, criteria ...query.Criterion) (int, error) {
return er.repository.Count(ctx, objectType, criteria...)
}
func (er *encryptingRepository) CountLabelValues(ctx context.Context, objectType types.ObjectType, criteria ...query.Criterion) (int, error) {
return er.repository.CountLabelValues(ctx, objectType, criteria...)
}
func (er *encryptingRepository) Update(ctx context.Context, obj types.Object, labelChanges types.LabelChanges, _ ...query.Criterion) (types.Object, error) {
if err := er.encrypt(ctx, obj); err != nil {
return nil, err
}
updatedObj, err := er.repository.Update(ctx, obj, labelChanges)
if err != nil {
return nil, err
}
if err := er.decrypt(ctx, updatedObj); err != nil {
return nil, err
}
return updatedObj, nil
}
func (cr *encryptingRepository) UpdateLabels(ctx context.Context, objectType types.ObjectType, objectID string, labelChanges types.LabelChanges, criteria ...query.Criterion) error {
return cr.repository.UpdateLabels(ctx, objectType, objectID, labelChanges, criteria...)
}
func (er *encryptingRepository) DeleteReturning(ctx context.Context, objectType types.ObjectType, criteria ...query.Criterion) (types.ObjectList, error) {
objList, err := er.repository.DeleteReturning(ctx, objectType, criteria...)
if err != nil {
return nil, err
}
for i := 0; i < objList.Len(); i++ {
if err := er.decrypt(ctx, objList.ItemAt(i)); err != nil {
return nil, err
}
}
return objList, nil
}
func (er *encryptingRepository) Delete(ctx context.Context, objectType types.ObjectType, criteria ...query.Criterion) error {
if err := er.repository.Delete(ctx, objectType, criteria...); err != nil {
return err
}
return nil
}
func (er *encryptingRepository) encrypt(ctx context.Context, obj types.Object) error {
if securedObject, isSecured := obj.(types.Secured); isSecured {
return securedObject.Encrypt(ctx, func(ctx context.Context, bytes []byte) ([]byte, error) {
return er.encrypter.Encrypt(ctx, bytes, er.encryptionKey)
})
}
return nil
}
func (er *encryptingRepository) decrypt(ctx context.Context, obj types.Object) error {
if securedObject, isSecured := obj.(types.Secured); isSecured {
return securedObject.Decrypt(ctx, func(ctx context.Context, bytes []byte) ([]byte, error) {
return er.encrypter.Decrypt(ctx, bytes, er.encryptionKey)
})
}
return nil
}
// InTransaction wraps repository passed in the transaction to also encypt/decrypt credentials
func (er *TransactionalEncryptingRepository) InTransaction(ctx context.Context, f func(ctx context.Context, storage Repository) error) error {
return er.repository.InTransaction(ctx, func(ctx context.Context, storage Repository) error {
return f(ctx, &encryptingRepository{
repository: storage,
encrypter: er.encrypter,
encryptionKey: er.encryptionKey,
})
})
}
func (er *encryptingRepository) GetEntities() []EntityMetadata {
return er.repository.GetEntities()
}