-
Notifications
You must be signed in to change notification settings - Fork 28
/
security.go
143 lines (127 loc) · 3.66 KB
/
security.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
/*
* Copyright 2018 The Service Manager Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package postgres
import (
"context"
"fmt"
"sync"
"time"
"github.com/Peripli/service-manager/pkg/query"
"github.com/Peripli/service-manager/pkg/security"
)
const securityLockIndex = 111
// Safe represents a secret entity
type Safe struct {
Secret []byte `db:"secret"`
CreatedAt time.Time `db:"created_at"`
UpdatedAt time.Time `db:"updated_at"`
}
type securityStorage struct {
db pgDB
encryptionKey []byte
isLocked bool
mutex *sync.Mutex
}
// Lock acquires a database lock so that only one process can manipulate the encryption key.
// Returns an error if the process has already acquired the lock
func (s *securityStorage) Lock(ctx context.Context) error {
s.mutex.Lock()
defer s.mutex.Unlock()
if s.isLocked {
return fmt.Errorf("lock is already acquired")
}
if _, err := s.db.ExecContext(ctx, "SELECT pg_advisory_lock($1)", securityLockIndex); err != nil {
return err
}
s.isLocked = true
return nil
}
// Unlock releases the database lock.
func (s *securityStorage) Unlock(ctx context.Context) error {
s.mutex.Lock()
defer s.mutex.Unlock()
if !s.isLocked {
return nil
}
if _, err := s.db.ExecContext(ctx, "SELECT pg_advisory_unlock($1)", securityLockIndex); err != nil {
return err
}
s.isLocked = false
return nil
}
// Fetcher returns a KeyFetcher configured to fetch a key from the database
func (s *securityStorage) Fetcher() security.KeyFetcher {
return &keyFetcher{s.db, []byte(s.encryptionKey)}
}
// Setter returns a KeySetter configured to set a key in the database
func (s *securityStorage) Setter() security.KeySetter {
return &keySetter{s.db, s.encryptionKey}
}
type keyFetcher struct {
db pgDB
encryptionKey []byte
}
// GetEncryptionKey returns the encryption key used to encrypt the credentials for brokers
func (s *keyFetcher) GetEncryptionKey(ctx context.Context) ([]byte, error) {
safe := &Safe{}
rows, err := listByFieldCriteria(ctx, s.db, "safe", []query.Criterion{})
defer closeRows(ctx, rows)
if err != nil {
return nil, err
}
if rows.Next() {
if err := rows.StructScan(safe); err != nil {
return nil, err
}
}
if len(safe.Secret) == 0 {
return []byte{}, nil
}
encryptedKey := []byte(safe.Secret)
return security.Decrypt(encryptedKey, s.encryptionKey)
}
type keySetter struct {
db pgDB
encryptionKey []byte
}
// Sets the encryption key by encrypting it beforehand with the encryption key in the environment
func (k *keySetter) SetEncryptionKey(ctx context.Context, key []byte) error {
rows, err := listByFieldCriteria(ctx, k.db, "safe", []query.Criterion{})
defer closeRows(ctx, rows)
if err != nil {
return err
}
existingKey := &Safe{}
if rows.Next() {
if err := rows.StructScan(existingKey); err != nil {
return err
}
if existingKey.Secret != nil && len(existingKey.Secret) > 0 {
return fmt.Errorf("encryption key is already set")
}
}
bytes, err := security.Encrypt(key, k.encryptionKey)
if err != nil {
return err
}
safe := Safe{
Secret: bytes,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}
_, err = create(ctx, k.db, "safe", safe)
return err
}