This repository has been archived by the owner on Aug 25, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 19
/
secret_split_lock.go
204 lines (164 loc) · 4.76 KB
/
secret_split_lock.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
/*
Copyright SecureKey Technologies Inc. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package secretsplitlock
import (
"context"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"github.com/hyperledger/aries-framework-go/pkg/secretlock"
"github.com/hyperledger/aries-framework-go/pkg/secretlock/local/masterlock/hkdf"
ariesstorage "github.com/hyperledger/aries-framework-go/pkg/storage"
"github.com/trustbloc/edge-core/pkg/log"
"github.com/trustbloc/edge-core/pkg/sss"
"github.com/trustbloc/edge-core/pkg/sss/base"
"github.com/trustbloc/hub-kms/pkg/internal/support"
)
const (
hubAuthSecretPath = "/secret" // path on Hub Auth to get secret share
cacheStore = "secretsplitlock"
)
// HubAuthParams defines parameters for HubAuth to get the secret share.
type HubAuthParams struct {
URL string
APIToken string
Subject string
}
// Options configures secret split lock dependencies.
type Options struct {
httpClient support.HTTPClient
secretSplitter sss.SecretSplitter
logger log.Logger
cacheProvider ariesstorage.Provider
}
// Option configures Options.
type Option func(options *Options)
// New returns a new secret split lock instance.
func New(secret []byte, params *HubAuthParams, options ...Option) (secretlock.Service, error) {
opts := &Options{
httpClient: http.DefaultClient,
secretSplitter: &base.Splitter{},
logger: log.New("hub-kms/secretsplitlock"),
}
for i := range options {
options[i](opts)
}
return createSecretSplitLock(secret, params, opts)
}
// WithHTTPClient sets the custom HTTP client.
func WithHTTPClient(c support.HTTPClient) Option {
return func(o *Options) {
o.httpClient = c
}
}
// WithSecretSplitter sets the custom secret splitter.
func WithSecretSplitter(s sss.SecretSplitter) Option {
return func(o *Options) {
o.secretSplitter = s
}
}
// WithLogger sets the custom logger.
func WithLogger(l log.Logger) Option {
return func(o *Options) {
o.logger = l
}
}
// WithCacheProvider sets a cache provider.
func WithCacheProvider(p ariesstorage.Provider) Option {
return func(o *Options) {
o.cacheProvider = p
}
}
func createSecretSplitLock(secret []byte, params *HubAuthParams, opts *Options) (secretlock.Service, error) {
if secret == nil {
return nil, errors.New("empty secret share")
}
fetchFunc := func() ([]byte, error) {
return fetch(params.URL, params.APIToken, params.Subject, opts.httpClient, opts.logger)
}
share, err := getSecretShare(params.Subject, opts.cacheProvider, fetchFunc)
if err != nil {
return nil, fmt.Errorf("get secret share: %w", err)
}
combined, err := opts.secretSplitter.Combine([][]byte{secret, share})
if err != nil {
return nil, fmt.Errorf("combine secrets: %w", err)
}
secLock, err := hkdf.NewMasterLock(string(combined), sha256.New, nil)
if err != nil {
return nil, fmt.Errorf("new master lock: %w", err)
}
return secLock, nil
}
func getSecretShare(cacheKey string, cacheProvider ariesstorage.Provider,
fetchFunc func() ([]byte, error)) ([]byte, error) {
if cacheProvider == nil {
return fetchFunc()
}
cache, err := cacheProvider.OpenStore(cacheStore)
if err != nil {
return nil, fmt.Errorf("open cache store: %w", err)
}
cachedSecret, getErr := cache.Get(cacheKey)
if getErr == nil {
return cachedSecret, nil
}
if errors.Is(getErr, ariesstorage.ErrDataNotFound) {
secret, fetchErr := fetchFunc()
if fetchErr != nil {
return nil, fetchErr
}
putErr := cache.Put(cacheKey, secret)
if putErr != nil {
return nil, fmt.Errorf("save to cache: %w", putErr)
}
return secret, nil
}
return nil, fmt.Errorf("get from cache: %w", getErr)
}
func fetch(serverURL, apiToken, subject string, httpClient support.HTTPClient, logger log.Logger) ([]byte, error) {
uri := fmt.Sprintf("%s%s?sub=%s", serverURL, hubAuthSecretPath, url.QueryEscape(subject))
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, uri, nil)
if err != nil {
return nil, err
}
req.Header.Set("authorization",
fmt.Sprintf("Bearer %s", base64.StdEncoding.EncodeToString([]byte(apiToken))),
)
resp, err := httpClient.Do(req)
if err != nil {
return nil, err
}
defer func() {
err = resp.Body.Close()
if err != nil {
logger.Errorf("failed to close response body")
}
}()
if resp.StatusCode != http.StatusOK {
body, errRead := ioutil.ReadAll(resp.Body)
if errRead != nil {
return nil, fmt.Errorf("read response body: %s", errRead)
}
return nil, fmt.Errorf("%s", body)
}
var secretResp struct {
Secret string `json:"secret"`
}
err = json.NewDecoder(resp.Body).Decode(&secretResp)
if err != nil {
return nil, err
}
secret, err := base64.StdEncoding.DecodeString(secretResp.Secret)
if err != nil {
return nil, err
}
return secret, nil
}