/
session.go
472 lines (406 loc) · 14.2 KB
/
session.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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
// Copyright IBM Corp. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package bcdb
import (
"context"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"encoding/base64"
"fmt"
"hash/crc32"
"io/ioutil"
"net"
"net/http"
"net/url"
"time"
"github.com/hyperledger-labs/orion-sdk-go/internal"
"github.com/hyperledger-labs/orion-sdk-go/pkg/config"
"github.com/hyperledger-labs/orion-server/pkg/certificateauthority"
"github.com/hyperledger-labs/orion-server/pkg/constants"
"github.com/hyperledger-labs/orion-server/pkg/crypto"
"github.com/hyperledger-labs/orion-server/pkg/cryptoservice"
"github.com/hyperledger-labs/orion-server/pkg/logger"
"github.com/hyperledger-labs/orion-server/pkg/marshal"
"github.com/hyperledger-labs/orion-server/pkg/types"
"github.com/pkg/errors"
"google.golang.org/protobuf/encoding/protojson"
)
// TODO refresh replicaSet and signature verifier when cluster config changes.
type dbSession struct {
userID string
signer Signer
verifier SignatureVerifier
userCert []byte
replicaSet internal.ReplicaSet
replicaSetVersion *types.Version
rootCAs *certificateauthority.CACertCollection
tlsEnabled bool
tlsRootCAs *certificateauthority.CACertCollection
clientAuthRequired bool
clientTlsConfig *tls.Config
txTimeout time.Duration
queryTimeout time.Duration
logger *logger.SugarLogger
restClient RestClient
}
// TxContextOption is a function that operates on a commonTxContext and applies a configuration option.
type TxContextOption func(svc *commonTxContext) error
// WithTxID provides an external transaction ID (txID) to the transaction context.
// The given txID must be unique in the database cluster to which it is submitted.
// The given txID must be safe to use as a URL segment (see segment-nz at: https://www.ietf.org/rfc/rfc3986.txt).
//
// Note that the database may reveal the transaction IDs it executed to other clients. Therefore, it is recommended
// not to include any sensitive information in it. It is recommended to generate the txID by hashing some identifier
// that includes enough entropy such that it reveals no information, e.g. `Hash(ID + Nonce)`, and convert the bytes to
// a URL-safe string representation.
func WithTxID(txID string) TxContextOption {
return func(txCtx *commonTxContext) error {
if len(txID) == 0 {
return errors.New("WithTxID: empty txID")
}
if err := constants.SafeURLSegmentNZ(txID); err != nil {
return errors.WithMessage(err, "WithTxID")
}
txCtx.txID = txID
return nil
}
}
// UsersTx returns user's transaction context
func (d *dbSession) UsersTx() (UsersTxContext, error) {
commonCtx, err := d.newCommonTxContext()
if err != nil {
return nil, err
}
userTx := &userTxContext{
commonTxContext: commonCtx,
}
return userTx, nil
}
// DBsTx returns database management transaction context
func (d *dbSession) DBsTx() (DBsTxContext, error) {
commonCtx, err := d.newCommonTxContext()
if err != nil {
return nil, err
}
dbsTx := &dbsTxContext{
commonTxContext: commonCtx,
createdDBs: map[string]*types.DBIndex{},
deletedDBs: map[string]bool{},
}
return dbsTx, nil
}
// DataTx returns data's transaction context
func (d *dbSession) DataTx(options ...TxContextOption) (DataTxContext, error) {
commonCtx, err := d.newCommonTxContext(options...)
if err != nil {
return nil, err
}
dataTx := &dataTxContext{
commonTxContext: commonCtx,
operations: make(map[string]*dbOperations),
txUsers: map[string]bool{
commonCtx.userID: true,
},
}
return dataTx, nil
}
// LoadDataTx loads a given data transaction envelope for inspection, co-signing, and commit
func (d *dbSession) LoadDataTx(txEnv *types.DataTxEnvelope) (LoadedDataTxContext, error) {
switch {
case txEnv == nil:
return nil, errors.New("transaction envelope is nil")
case txEnv.GetPayload() == nil:
return nil, errors.New("payload in the transaction envelope is nil")
case txEnv.GetSignatures() == nil || len(txEnv.GetSignatures()) == 0:
return nil, errors.New("transaction envelope does not have a signature")
case txEnv.GetPayload().GetTxId() == "":
return nil, errors.New("transaction ID in the transaction envelope is empty")
case len(txEnv.GetPayload().GetMustSignUserIds()) == 0:
return nil, errors.New("no user ID in the transaction envelope")
}
commonCtx, err := d.newCommonTxContext()
if err != nil {
return nil, err
}
commonCtx.txID = txEnv.Payload.TxId
dataTx := &loadedDataTxContext{
commonTxContext: commonCtx,
txEnv: txEnv,
}
return dataTx, nil
}
// ConfigTx returns config transaction context.
// This methods first reads the current ClusterConfig from the cluster.
// This is only available to sessions of an admin user.
func (d *dbSession) ConfigTx() (ConfigTxContext, error) {
commonCtx, err := d.newCommonTxContext()
if err != nil {
return nil, err
}
configTx := &configTxContext{
commonTxContext: commonCtx,
oldConfig: nil,
readOldConfigVersion: nil,
newConfig: nil,
}
if err = configTx.queryClusterConfig(); err != nil {
return nil, err
}
return configTx, nil
}
// Provenance returns handler to access provenance
func (d *dbSession) Provenance() (Provenance, error) {
commonCtx, err := d.newCommonTxContext()
if err != nil {
return nil, err
}
return &provenance{
commonCtx,
}, nil
}
// Ledger returns handler to access bcdb ledger data
func (d *dbSession) Ledger() (Ledger, error) {
commonCtx, err := d.newCommonTxContext()
if err != nil {
return nil, err
}
return &ledger{
commonCtx,
}, nil
}
// Query returns handler to access bcdb data through JSON query
func (d *dbSession) Query() (Query, error) {
commonCtx, err := d.newCommonTxContext()
if err != nil {
return nil, err
}
return &QueryExecutor{
commonCtx,
}, nil
}
func (d *dbSession) ReplicaSet(refresh bool) ([]*config.Replica, error) {
if refresh {
httpClient := newHTTPClient(d.tlsEnabled, d.clientTlsConfig)
if err := d.updateReplicaSetAndVerifier(httpClient, d.tlsEnabled); err != nil {
d.logger.Errorf("cannot update the replica set and signature verifier, error: %s", err)
return nil, errors.Wrap(err, "cannot update the replica set and signature verifier")
}
}
return d.replicaSet.ToConfigReplicaSet(), nil
}
func (d *dbSession) newCommonTxContext(options ...TxContextOption) (*commonTxContext, error) {
if d.restClient == nil {
d.restClient = NewRestClient(d.userID, newHTTPClient(d.tlsEnabled, d.clientTlsConfig), d.signer)
}
commonTxCtx := &commonTxContext{
userID: d.userID,
signer: d.signer,
userCert: d.userCert,
replicaSet: d.replicaSet,
verifier: d.verifier,
restClient: d.restClient,
commitTimeout: d.txTimeout,
queryTimeout: d.queryTimeout,
logger: d.logger,
}
for _, opt := range options {
if err := opt(commonTxCtx); err != nil {
return nil, errors.WithMessage(err, "error while applying option")
}
}
if len(commonTxCtx.txID) == 0 {
var err error
commonTxCtx.txID, err = computeTxID(d.userCert)
if err != nil {
return nil, err
}
}
return commonTxCtx, nil
}
// updateReplicaSetAndVerifier connects to the cluster, pulls the most recent cluster status, builds a signature
// verifier from it, and updates the replica-set.
func (d *dbSession) updateReplicaSetAndVerifier(httpClient *http.Client, tlsEnabled bool) error {
// get the latest status from replica set
clusterStatusEnv, err := d.getLatestClusterStatus(httpClient)
if err != nil {
return errors.Wrap(err, "failed to obtain the latest cluster status")
}
if d.replicaSetVersion != nil && compareVersion(clusterStatusEnv.GetResponse().GetVersion(), d.replicaSetVersion) < 0 {
d.logger.Debugf("Cluster config version from server: [%v] is smaller than the latest replica set version: [%v], skipping update.")
return nil
}
// create the verifier and verify the cluster status response envelope
verifier, err := d.createSignatureVerifier(clusterStatusEnv)
if err != nil {
return errors.Wrap(err, "failed to create signature verifier form servers' certificates")
}
replicaSet, err := internal.ClusterStatusToReplicaSet(clusterStatusEnv.GetResponse(), tlsEnabled)
if err != nil {
return errors.Wrap(err, "failed to create replica set with role from cluster status")
}
d.verifier = verifier
d.replicaSet = replicaSet
d.replicaSetVersion = clusterStatusEnv.GetResponse().GetVersion()
d.logger.Debugf("updated replica set, version: %+v, set: %v", d.replicaSetVersion, d.replicaSet)
return nil
}
func (d *dbSession) getClusterStatusFrom(replica *url.URL, httpClient *http.Client) (*types.GetClusterStatusResponseEnvelope, error) {
getStatus := &url.URL{
Path: constants.GetClusterStatus,
}
statusREST := replica.ResolveReference(getStatus)
ctx := context.TODO()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, statusREST.String(), nil)
if err != nil {
return nil, err
}
signature, err := cryptoservice.SignQuery(d.signer, &types.GetClusterStatusQuery{
UserId: d.userID,
NoCertificates: false,
})
if err != nil {
d.logger.Errorf("failed signed transaction, %s", err)
return nil, err
}
req.Header.Set("Accept", "application/json")
req.Header.Set(constants.UserHeader, d.userID)
req.Header.Set(constants.SignatureHeader, base64.StdEncoding.EncodeToString(signature))
response, err := httpClient.Do(req)
if err != nil {
d.logger.Errorf("failed to send transaction to server %s, due to %s", getStatus.String(), err)
return nil, err
}
if response.StatusCode != http.StatusOK {
d.logger.Errorf("error response from the server, %s", response.Status)
return nil, errors.New(fmt.Sprintf("error response from the server, %s", response.Status))
}
resEnv := &types.GetClusterStatusResponseEnvelope{}
responseBytes, err := ioutil.ReadAll(response.Body)
if err != nil {
return nil, err
}
err = protojson.Unmarshal(responseBytes, resEnv)
statusResp := resEnv.GetResponse()
d.logger.Debugf("Cluster status (from: %s) version: %+v", replica.String(), statusResp.GetVersion())
return resEnv, nil
}
// getLatestClusterStatus get the most updated cluster status out of all servers in the replica set.
// If the replica set is empty, use the bootstrap replica set.
func (d *dbSession) getLatestClusterStatus(httpClient *http.Client) (*types.GetClusterStatusResponseEnvelope, error) {
latestStatusEnv := &types.GetClusterStatusResponseEnvelope{}
latestFrom := ""
var lastErr error
for _, replica := range d.replicaSet {
statusRespEnv, err := d.getClusterStatusFrom(replica.URL, httpClient)
if err != nil {
d.logger.Debugf("Failed to get cluster status from server: %s; because: %s", replica.String(), err)
lastErr = err
continue
}
latestVersion := latestStatusEnv.GetResponse().GetVersion()
fetchedVersion := statusRespEnv.GetResponse().GetVersion()
if compareVersion(fetchedVersion, latestVersion) > 0 {
latestStatusEnv = statusRespEnv
latestFrom = fmt.Sprintf("%s", replica.String())
d.logger.Debugf("Got latest cluster status from server: %s", latestFrom)
}
}
if latestStatusEnv.GetResponse() == nil {
return nil, errors.New(fmt.Sprintf("failed to get cluster status from replica set: %+v; version: %+v, last error: %s", d.replicaSet, d.replicaSetVersion, lastErr))
}
d.logger.Debugf("Latest cluster status (from: %s) is: %+v", latestFrom, latestStatusEnv.GetResponse())
return latestStatusEnv, nil
}
// createSignatureVerifier creates a SignatureVerifier and verifies the cluster status response envelope with it
func (d *dbSession) createSignatureVerifier(clusterStatusEnv *types.GetClusterStatusResponseEnvelope) (SignatureVerifier, error) {
clusterStatus := clusterStatusEnv.GetResponse()
nodes := clusterStatus.GetNodes()
numNodes := len(nodes)
nodesCerts := map[string]*x509.Certificate{}
for i, node := range nodes {
d.logger.Debugf("Cluster Nodes: [%d/%d]: %s", i+1, numNodes, nodeConfigToString(node))
err := d.rootCAs.VerifyLeafCert(node.Certificate)
if err != nil {
return nil, err
}
cert, err := x509.ParseCertificate(node.Certificate)
if err != nil {
return nil, err
}
nodesCerts[node.Id] = cert
}
verifier, err := NewVerifier(nodesCerts, d.logger)
if err != nil {
return nil, err
}
respBytes, err := marshal.DefaultMarshaller().Marshal(clusterStatus)
if err != nil {
return nil, err
}
if err = verifier.Verify(
clusterStatus.GetHeader().GetNodeId(),
respBytes,
clusterStatusEnv.GetSignature()); err != nil {
d.logger.Errorf("failed to verify configuration response, error = %s", err)
return nil, errors.Errorf("failed to verify configuration response, error = %s", err)
}
d.logger.Debugf("Cluster Status: Leader: %s, Active: %v, Version: %v",
clusterStatus.GetLeader(), clusterStatus.GetActive(), clusterStatus.GetVersion())
return verifier, err
}
// TODO expose HTTP parameters, make client configurable, with good defaults. See:
// https://github.com/hyperledger-labs/orion-sdk-go/issues/28
func newHTTPClient(tlsEnabled bool, tlsConfig *tls.Config) *http.Client {
dialer := &net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}
httpClient := &http.Client{
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: dialer.DialContext,
ForceAttemptHTTP2: true,
MaxIdleConns: 100,
MaxIdleConnsPerHost: 100,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
},
}
if tlsEnabled {
httpClient.Transport.(*http.Transport).TLSClientConfig = tlsConfig
}
return httpClient
}
func computeTxID(userCert []byte) (string, error) {
nonce := make([]byte, 24)
_, err := rand.Read(nonce)
if err != nil {
return "", err
}
b := append(nonce, userCert...)
sha256Hash, err := crypto.ComputeSHA256Hash(b)
if err != nil {
return "", err
}
return base64.URLEncoding.EncodeToString(sha256Hash), nil
}
func nodeConfigToString(n *types.NodeConfig) string {
return fmt.Sprintf("Id: %s, Address: %s, Port: %d, Cert-hash: %x", n.Id, n.Address, n.Port, crc32.ChecksumIEEE(n.Certificate))
}
func compareVersion(x, y *types.Version) int {
if x.GetBlockNum() > y.GetBlockNum() {
return 1
}
if x.GetBlockNum() < y.GetBlockNum() {
return -1
}
if x.GetTxNum() > y.GetTxNum() {
return 1
}
if x.GetTxNum() < y.GetTxNum() {
return -1
}
return 0
}