forked from manifoldco/torus-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
engine.go
568 lines (472 loc) · 15.3 KB
/
engine.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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
// Package logic exposes the core logic engine used for working with keyrings,
// keys, claims, teams, memberships, orgs, and other primitive objects core
// to the cryptography architecture
package logic
import (
"context"
"log"
"github.com/manifoldco/torus-cli/apitypes"
"github.com/manifoldco/torus-cli/base64"
"github.com/manifoldco/torus-cli/config"
"github.com/manifoldco/torus-cli/envelope"
"github.com/manifoldco/torus-cli/identity"
"github.com/manifoldco/torus-cli/primitive"
"github.com/manifoldco/torus-cli/daemon/crypto"
"github.com/manifoldco/torus-cli/daemon/db"
"github.com/manifoldco/torus-cli/daemon/observer"
"github.com/manifoldco/torus-cli/daemon/registry"
"github.com/manifoldco/torus-cli/daemon/session"
)
// Engine exposes methods for performing actions that will affect the keys,
// keyrings, keyring memberships, or credential objects.
//
// All data passing in and out of the engine is unencrypted for the currently
// logged in user.
type Engine struct {
config *config.Config
session session.Session
db *db.DB
crypto *crypto.Engine
client *registry.Client
Worklog Worklog
Machine Machine
Session Session
}
// NewEngine returns a new Engine
func NewEngine(c *config.Config, s session.Session, db *db.DB, e *crypto.Engine,
client *registry.Client) *Engine {
engine := &Engine{
config: c,
session: s,
db: db,
crypto: e,
client: client,
}
engine.Worklog = newWorklog(engine)
engine.Machine = Machine{engine: engine}
engine.Session = Session{engine: engine}
return engine
}
// AppendCredential attempts to append a plain-text Credential object to the
// Credential Graph.
func (e *Engine) AppendCredential(ctx context.Context, notifier *observer.Notifier,
cred *PlaintextCredentialEnvelope) (*PlaintextCredentialEnvelope, error) {
n := notifier.Notifier(4)
// Ensure we have an existing keyring for this credential's pathexp
graphs, err := e.client.CredentialGraph.List(ctx, "", cred.Body.PathExp,
e.session.AuthID())
if err != nil {
log.Printf("Error retrieving credential graphs: %s", err)
return nil, err
}
n.Notify(observer.Progress, "Credentials retrieved", true)
sigID, encID, kp, err := fetchKeyPairs(ctx, e.client, cred.Body.OrgID)
if err != nil {
log.Printf("Error fetching keypairs: %s", err)
return nil, err
}
n.Notify(observer.Progress, "Keypairs retrieved", true)
cgs := newCredentialGraphSet()
err = cgs.Add(graphs...)
if err != nil {
return nil, err
}
// Find the credentialgraph/keyring that we should store our credential in
graph, err := cgs.Head(cred.Body.PathExp)
if err != nil {
return nil, err
}
// Find the most recent version of this credential to act as our previous.
previousCred, err := cgs.HeadCredential(cred.Body.PathExp, cred.Body.Name)
if err != nil {
log.Printf("error finding credentials to match: %s", err)
return nil, err
}
var newGraph *registry.CredentialGraphV2
// No matching CredentialGraph/KeyRing for this credential.
// We'll make a new one now.
if graph == nil || graph.HasRevocations() {
newGraph, err = createCredentialGraph(ctx, cred.Body, graph,
sigID, encID, kp, e.client, e.crypto)
if err != nil {
log.Printf("error creating credential graph: %s", err)
return nil, err
}
cgs.Add(newGraph)
graph = newGraph
}
// Construct an encrypted and signed version of the credential
credBody := primitive.Credential{
State: cred.Body.State,
BaseCredential: primitive.BaseCredential{
Name: cred.Body.Name,
PathExp: cred.Body.PathExp,
KeyringID: graph.GetKeyring().ID,
ProjectID: cred.Body.ProjectID,
OrgID: cred.Body.OrgID,
Credential: &primitive.CredentialValue{
Algorithm: crypto.SecretBox,
},
},
}
if previousCred == nil {
log.Printf("no previous")
credBody.Previous = nil
credBody.CredentialVersion = 1
} else {
base, err := baseCredential(previousCred)
if err != nil {
return nil, err
}
credBody.Previous = previousCred.ID
credBody.CredentialVersion = base.CredentialVersion + 1
}
krm, mekshare, err := graph.FindMember(e.session.AuthID())
if err != nil {
log.Printf("Error finding keyring membership: %s", err)
return nil, err
}
encryptingKey, err := findEncryptingKey(ctx, e.client, credBody.OrgID,
krm.EncryptingKeyID)
if err != nil {
log.Printf("Error finding encrypting key: %s", err)
return nil, err
}
n.Notify(observer.Progress, "Encrypting key retrieved", true)
// Derive a key for the credential using the keyring master key
// and use the derived key to encrypt the credential
cekNonce, ctNonce, ct, err := e.crypto.BoxCredential(
ctx, []byte(cred.Body.Value), *mekshare.Key.Value, *mekshare.Key.Nonce,
&kp.Encryption, *encryptingKey.Key.Value)
if err != nil {
log.Printf("Error encrypting credential: %s", err)
return nil, err
}
credBody.Nonce = base64.NewValue(cekNonce)
credBody.Credential.Nonce = base64.NewValue(ctNonce)
credBody.Credential.Value = base64.NewValue(ct)
signed, err := e.crypto.SignedEnvelope(ctx, &credBody, sigID, &kp.Signature)
if err != nil {
log.Printf("Error signing credential body: %s", err)
return nil, err
}
n.Notify(observer.Progress, "Credential encrypted", true)
if newGraph != nil {
newGraph.Credentials = []envelope.Signed{*signed}
_, err = e.client.CredentialGraph.Post(ctx, &graph)
} else {
_, err = e.client.Credentials.Create(ctx, signed)
}
if err != nil {
log.Printf("error creating credential: %s", err)
return nil, err
}
return cred, nil
}
// RetrieveCredentials returns all credentials for the given CPath string
func (e *Engine) RetrieveCredentials(ctx context.Context,
notifier *observer.Notifier, cpath, cpathexp *string) ([]PlaintextCredentialEnvelope, error) {
if cpath != nil && cpathexp != nil {
panic("cannot use both cpath and cpathexp")
}
if cpath == nil && cpathexp == nil {
panic("cpath or cpathexp required")
}
var err error
var graphs []registry.CredentialGraph
if cpath != nil {
graphs, err = e.client.CredentialGraph.List(ctx, *cpath, nil, e.session.AuthID())
} else if cpathexp != nil {
graphs, err = e.client.CredentialGraph.Search(ctx, *cpathexp, e.session.AuthID())
}
if err != nil {
log.Printf("error retrieving credential graphs: %s", err)
return nil, err
}
cgs := newCredentialGraphSet()
err = cgs.Add(graphs...)
if err != nil {
return nil, err
}
activeGraphs, err := cgs.Prune()
if err != nil {
return nil, err
}
var steps uint = 1
for _, graph := range activeGraphs {
steps += uint(len(graph.GetCredentials()))
}
n := notifier.Notifier(steps)
n.Notify(observer.Progress, "Credentials retrieved", true)
keypairs := make(map[identity.ID]*crypto.KeyPairs)
encryptingKeys := make(map[identity.ID]*primitive.PublicKey)
// Loop over the trees and unpack the credentials; later on we will
// actually do real work and decrypt each of these credentials but for
// now we just need ot return a list of them!
creds := []PlaintextCredentialEnvelope{}
for _, graph := range activeGraphs {
var orgID *identity.ID
switch b := graph.GetKeyring().Body.(type) {
case *primitive.Keyring:
orgID = b.OrgID
case *primitive.KeyringV1:
orgID = b.OrgID
default:
return nil, &apitypes.Error{
Type: apitypes.InternalServerError,
Err: []string{"Malformed keyring body"},
}
}
kp, ok := keypairs[*orgID]
if !ok {
_, _, kp, err = fetchKeyPairs(ctx, e.client, orgID)
if err != nil {
log.Printf("Error fetching keypairs: %s", err)
return nil, err
}
keypairs[*orgID] = kp
}
krm, mekshare, err := graph.FindMember(e.session.AuthID())
if err != nil {
log.Printf("Error finding keyring membership: %s", err)
return nil, err
}
encryptingKey, ok := encryptingKeys[*krm.EncryptingKeyID]
if !ok {
encryptingKey, err = findEncryptingKey(ctx, e.client, orgID,
krm.EncryptingKeyID)
if err != nil {
log.Printf("Error finding encrypting key for user: %s", err)
return nil, err
}
encryptingKeys[*krm.EncryptingKeyID] = encryptingKey
}
err = e.crypto.WithUnboxer(ctx, *mekshare.Key.Value, *mekshare.Key.Nonce, &kp.Encryption, *encryptingKey.Key.Value, func(u crypto.Unboxer) error {
for _, cred := range graph.GetCredentials() {
var state *string
base, err := baseCredential(&cred)
if err != nil {
return err
}
if c, ok := cred.Body.(*primitive.Credential); ok {
state = c.State
}
pt, err := u.Unbox(ctx, *base.Credential.Value, *base.Nonce, *base.Credential.Nonce)
if err != nil {
log.Printf("Error decrypting credential: %s", err)
return err
}
plainCred := PlaintextCredentialEnvelope{
ID: cred.ID,
Version: cred.Version,
Body: &PlaintextCredential{
Name: base.Name,
PathExp: base.PathExp,
ProjectID: base.ProjectID,
OrgID: base.OrgID,
Value: string(pt),
State: state,
},
}
creds = append(creds, plainCred)
n.Notify(observer.Progress, "Credential decrypted", true)
}
return nil
})
if err != nil {
return nil, err
}
}
return creds, nil
}
// ApproveInvite approves an invitation of a user into an organzation by
// encoding them into a Keyring.
func (e *Engine) ApproveInvite(ctx context.Context, notifier *observer.Notifier,
InviteID *identity.ID) (*envelope.Unsigned, error) {
n := notifier.Notifier(3)
invite, err := e.client.OrgInvite.Get(ctx, InviteID)
if err != nil {
log.Printf("could not fetch org invitation: %s", err)
return nil, err
}
inviteBody := invite.Body.(*primitive.OrgInvite)
if inviteBody.State != primitive.OrgInviteAcceptedState {
log.Printf("invitation not in accepted state: %s", inviteBody.State)
return nil, &apitypes.Error{
Type: apitypes.BadRequestError,
Err: []string{"Invite must be accepted before it can be approved"},
}
}
n.Notify(observer.Progress, "Invite retrieved", true)
v1members, v2members, err := createKeyringMemberships(ctx, e.crypto,
e.client, e.session, inviteBody.OrgID, inviteBody.InviteeID)
if err != nil {
return nil, err
}
n.Notify(observer.Progress, "Keyring memberships created", true)
invite, err = e.client.OrgInvite.Approve(ctx, InviteID)
if err != nil {
log.Printf("could not approve org invite: %s", err)
return nil, err
}
n.Notify(observer.Progress, "Invite approved", true)
if len(v1members) != 0 {
_, err = e.client.KeyringMember.Post(ctx, v1members)
if err != nil {
log.Printf("error uploading memberships: %s", err)
return nil, err
}
}
for _, member := range v2members {
err = e.client.Keyring.Members.Post(ctx, member)
if err != nil {
log.Printf("error uploading memberships: %s", err)
return nil, err
}
}
return invite, nil
}
// GenerateKeypairs creates a signing and encrypting keypair for the current
// user for the given organization.
func (e *Engine) GenerateKeypairs(ctx context.Context, notifier *observer.Notifier,
OrgID *identity.ID) error {
n := notifier.Notifier(4)
kp, err := e.crypto.GenerateKeyPairs(ctx)
if err != nil {
log.Printf("Error generating keypairs: %s", err)
return err
}
n.Notify(observer.Progress, "Keypairs generated", true)
pubsig, privsig, err := packageSigningKeypair(ctx, e.crypto, e.session.AuthID(),
OrgID, kp)
if err != nil {
log.Printf("Error packaging signing keypair: %s", err)
return err
}
sigclaim, err := e.crypto.SignedEnvelope(
ctx, primitive.NewClaim(OrgID, e.session.AuthID(), pubsig.ID, pubsig.ID,
primitive.SignatureClaimType),
pubsig.ID, &kp.Signature)
if err != nil {
log.Printf("Error creating signature claim: %s", err)
return err
}
n.Notify(observer.Progress, "Signing keys signed", true)
pubsig, privsig, claims, err := e.client.KeyPairs.Post(ctx, pubsig,
privsig, sigclaim)
if err != nil {
log.Printf("Error uploading signature keypair: %s", err)
return err
}
objs := make([]envelope.Envelope, len(claims)+2)
objs[0] = pubsig
objs[1] = privsig
for i, claim := range claims {
objs[i+2] = &claim
}
err = e.db.Set(objs...)
if err != nil {
log.Printf("Error storing signing keys in local db: %s", err)
return err
}
n.Notify(observer.Progress, "Signing keys uploaded", true)
pubenc, privenc, err := packageEncryptionKeypair(ctx, e.crypto, e.session.AuthID(),
OrgID, kp, pubsig)
if err != nil {
log.Printf("Error packaging encryption keypair: %s", err)
}
encclaim, err := e.crypto.SignedEnvelope(
ctx, primitive.NewClaim(OrgID, e.session.AuthID(), pubenc.ID, pubenc.ID,
primitive.SignatureClaimType),
pubsig.ID, &kp.Signature)
if err != nil {
log.Printf("Error creating signature claim for encryption key: %s", err)
return err
}
n.Notify(observer.Progress, "Encryption keys signed", true)
pubenc, privenc, claims, err = e.client.KeyPairs.Post(ctx, pubenc,
privenc, encclaim)
if err != nil {
log.Printf("Error uploading encryption keypair: %s", err)
return err
}
objs = make([]envelope.Envelope, len(claims)+2)
objs[0] = pubenc
objs[1] = privenc
for i, claim := range claims {
objs[i+2] = &claim
}
err = e.db.Set(objs...)
if err != nil {
log.Printf("Error storing encryption keys in local db: %s", err)
return err
}
return nil
}
// RevokeKeypairs creates revocation claims for the signing and encrypting
// keypair for the current user for the given organization.
//
// A revocation claim is a self-signed claim that effectively deletes the
// keypairs.
func (e *Engine) RevokeKeypairs(ctx context.Context, notifier *observer.Notifier,
orgID *identity.ID) error {
n := notifier.Notifier(5)
encKP, sigKP, err := fetchRegistryKeyPairs(ctx, e.client, orgID)
if err != nil {
log.Printf("Error retrieving keypairs: %s", err)
return err
}
n.Notify(observer.Progress, "Keypairs retrieved", true)
if sigKP == nil { // no active keypairs; nothing to revoke
log.Println("No keys to revoke")
return nil
}
sigID := sigKP.PublicKey.ID
kp := bundleKeypairs(sigKP, encKP)
if encKP != nil { // the encryption keypair might already be revoked
encID := encKP.PublicKey.ID
prevEncClaim, err := encKP.HeadClaim()
if err != nil {
return err
}
encclaim, err := e.crypto.SignedEnvelope(
ctx, primitive.NewClaim(orgID, e.session.AuthID(), prevEncClaim.ID,
encID, primitive.RevocationClaimType),
sigID, &kp.Signature)
if err != nil {
log.Printf("Error creating revocation claim for encryption key: %s", err)
return err
}
n.Notify(observer.Progress, "Encryption keys revoked", true)
_, err = e.client.Claims.Create(ctx, encclaim)
if err != nil {
log.Printf("Error uploading encryption keypair revocation: %s", err)
return err
}
n.Notify(observer.Progress, "Encryption key revocation uploaded", true)
}
prevSigClaim, err := sigKP.HeadClaim()
if err != nil {
return err
}
sigclaim, err := e.crypto.SignedEnvelope(
ctx, primitive.NewClaim(orgID, e.session.AuthID(), prevSigClaim.ID,
sigID, primitive.RevocationClaimType),
sigID, &kp.Signature)
if err != nil {
log.Printf("Error creating revocation claim for signing key: %s", err)
return err
}
n.Notify(observer.Progress, "Signing keys revoked", true)
_, err = e.client.Claims.Create(ctx, sigclaim)
if err != nil {
log.Printf("Error uploading signature keypair revocation: %s", err)
return err
}
n.Notify(observer.Progress, "Signing key revocation uploaded", true)
return nil
}
// ChangePassword returns the new password object and re-encrypted masterkey object
func (e *Engine) ChangePassword(ctx context.Context, newPassword string) (*primitive.UserPassword, *primitive.MasterKey, error) {
return e.crypto.ChangePassword(ctx, newPassword)
}