-
-
Notifications
You must be signed in to change notification settings - Fork 48
/
accounts.go
293 lines (259 loc) · 9.39 KB
/
accounts.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
// Copyright 2020 - Offen Authors <hioffen@posteo.de>
// SPDX-License-Identifier: Apache-2.0
package persistence
import (
"errors"
"fmt"
"github.com/gofrs/uuid"
"github.com/offen/offen/server/keys"
)
func (p *persistenceLayer) GetAccount(accountID string, includeStyles, includeEvents bool, eventsSince string) (AccountResult, error) {
var account Account
var err error
if includeEvents {
account, err = p.dal.FindAccount(FindAccountQueryIncludeEvents{
AccountID: accountID,
Since: eventsSince,
})
} else {
account, err = p.dal.FindAccount(FindAccountQueryActiveByID(accountID))
}
if err != nil {
return AccountResult{}, fmt.Errorf("persistence: error looking up account data: %w", err)
}
result := AccountResult{
AccountID: account.AccountID,
Name: account.Name,
Created: account.Created,
}
if includeStyles {
result.AccountStyles = account.AccountStyles
}
key, err := account.WrapPublicKey()
if err != nil {
return AccountResult{}, fmt.Errorf("persistence: error wrapping account public key: %v", err)
}
result.PublicKey = key
if !includeEvents {
return result, nil
}
result.EncryptedPrivateKey = account.EncryptedPrivateKey
eventResults := EventsByAccountID{}
secrets := EncryptedSecretsByID{}
seqs := []string{}
for _, evt := range account.Events {
eventResults[evt.AccountID] = append(eventResults[evt.AccountID], EventResult{
SecretID: evt.SecretID,
EventID: evt.EventID,
Payload: evt.Payload,
})
if evt.SecretID != nil {
secrets[*evt.SecretID] = evt.Secret.EncryptedSecret
}
seqs = append(seqs, evt.Sequence)
}
if len(eventResults) != 0 {
result.Events = &eventResults
}
if len(secrets) != 0 {
result.Secrets = &secrets
}
if eventsSince != "" {
pruned, err := p.dal.FindTombstones(FindTombstonesQueryByAccounts{
AccountIDs: []string{accountID},
Since: eventsSince,
})
if err != nil {
return AccountResult{}, fmt.Errorf("persistence: error finding deleted events: %w", err)
}
var prunedIDs []string
for _, tombstone := range pruned {
prunedIDs = append(prunedIDs, tombstone.EventID)
seqs = append(seqs, tombstone.Sequence)
}
result.DeletedEvents = prunedIDs
}
result.Sequence = getLatestSeq(seqs)
return result, nil
}
func (p *persistenceLayer) AssociateUserSecret(accountID, userID, encryptedUserSecret string) error {
account, err := p.dal.FindAccount(FindAccountQueryActiveByID(accountID))
if err != nil {
return fmt.Errorf(`persistence: error looking up account with id "%s": %w`, accountID, err)
}
hashedUserID, hashErr := account.HashUserID(userID)
if hashErr != nil {
return fmt.Errorf("persistence: erro hashing user id: %w", err)
}
secret, err := p.dal.FindSecret(FindSecretQueryBySecretID(hashedUserID))
if err != nil {
var notFound ErrUnknownSecret
if !errors.As(err, ¬Found) {
return fmt.Errorf("persistence: error looking up user: %v", err)
}
} else {
// In this branch the following case is covered: a user whose hashed
// identifier is known, has sent a new user secret to be saved. This means
// all events previously saved using their identifier cannot be accessed
// by them anymore as the key that has been used to encrypt the event's payloads
// is not known to the user anymore. This means all events that are
// currently associated to the identifier will be migrated to a newly
// created identifier which will be used to "park" them. It is important
// to update these event's EventIDs as this means they will be considered
// "deleted" by clients.
parkedID, parkedIDErr := uuid.NewV4()
if parkedIDErr != nil {
return fmt.Errorf("persistence: error creating identifier for parking events: %v", parkedIDErr)
}
parkedHash, parkErr := account.HashUserID(parkedID.String())
if parkErr != nil {
return fmt.Errorf("persistence: error hashing parked id: %v", parkErr)
}
txn, err := p.dal.Transaction()
if err != nil {
return fmt.Errorf("persistence: error creating transaction: %w", err)
}
if err := txn.CreateSecret(&Secret{
SecretID: parkedHash,
EncryptedSecret: secret.EncryptedSecret,
}); err != nil {
txn.Rollback()
return fmt.Errorf("persistence: error creating user for use as migration target: %w", err)
}
if err := txn.DeleteSecret(DeleteSecretQueryBySecretID(secret.SecretID)); err != nil {
txn.Rollback()
return fmt.Errorf("persistence: error deleting existing user: %v", err)
}
// The previous user is now deleted so all orphaned events need to be
// copied over to the one used for parking the events.
var idsToDelete []string
orphanedEvents, err := txn.FindEvents(FindEventsQueryForSecretIDs{
SecretIDs: []string{hashedUserID},
})
if err != nil {
return fmt.Errorf("persistence: error looking up orphaned events: %w", err)
}
sequence, seqErr := NewULID()
if seqErr != nil {
return fmt.Errorf("persistence: error creating sequence for parked events: %w", err)
}
for _, orphan := range orphanedEvents {
newID, err := siblingEventID(orphan.EventID)
if err != nil {
txn.Rollback()
return fmt.Errorf("persistence: error creating new event id: %w", err)
}
if err := txn.CreateEvent(&Event{
EventID: newID,
Sequence: sequence,
AccountID: orphan.AccountID,
SecretID: &parkedHash,
Payload: orphan.Payload,
}); err != nil {
return fmt.Errorf("persistence: error migrating an existing event: %w", err)
}
if err := txn.CreateTombstone(&Tombstone{
EventID: orphan.EventID,
AccountID: orphan.AccountID,
SecretID: orphan.SecretID,
Sequence: sequence,
}); err != nil {
return fmt.Errorf("persistence: error creating tombstone for migrated event: %w", err)
}
idsToDelete = append(idsToDelete, orphan.EventID)
}
if _, err := txn.DeleteEvents(DeleteEventsQueryByEventIDs(idsToDelete)); err != nil {
txn.Rollback()
return fmt.Errorf("persistence: error deleting orphaned events: %w", err)
}
if err := txn.Commit(); err != nil {
return fmt.Errorf("persistence: error committing transaction: %w", err)
}
}
if err := p.dal.CreateSecret(&Secret{
SecretID: hashedUserID,
EncryptedSecret: encryptedUserSecret,
}); err != nil {
return fmt.Errorf("persistence: error creating user: %w", err)
}
return nil
}
func (p *persistenceLayer) CreateAccount(name, emailAddress, password string) error {
accountUsers, err := p.dal.FindAccountUsers(FindAccountUsersQueryAllAccountUsers{true, false})
if err != nil {
return fmt.Errorf("persistence: error looking up account users: %w", err)
}
match, err := selectAccountUser(accountUsers, emailAddress)
if err != nil {
return fmt.Errorf("persistence: error looking up account user %s: %w", emailAddress, err)
}
if err := keys.CompareString(password, match.HashedPassword); err != nil {
return fmt.Errorf("persistence: passwords did not match: %w", err)
}
allAccounts, allAccountsErr := p.dal.FindAccounts(FindAccountsQueryAllAccounts{})
if allAccountsErr != nil {
return fmt.Errorf("persistence: error looking up all existing accounts: %w", err)
}
for _, account := range allAccounts {
if account.Name == name {
return fmt.Errorf("persistence: account named %s already exists", name)
}
}
account, key, err := newAccount(name, "")
if err != nil {
return fmt.Errorf("persistence: error creating account: %w", err)
}
relationship, err := newAccountUserRelationship(match.AccountUserID, account.AccountID)
if err != nil {
return fmt.Errorf("persistence: error creating relationship: %w", err)
}
if err := relationship.addEmailEncryptedKey(key, match.Salt, emailAddress); err != nil {
return fmt.Errorf("persistence: error adding email encrypted key: %w", err)
}
if err := relationship.addPasswordEncryptedKey(key, match.Salt, password); err != nil {
return fmt.Errorf("persistence: error adding password encrypted key: %w", err)
}
txn, err := p.dal.Transaction()
if err != nil {
return fmt.Errorf("persistence: error creating transaction: %w", err)
}
if err := txn.CreateAccount(account); err != nil {
txn.Rollback()
return fmt.Errorf("persistence: error persisting account: %w", err)
}
if err := txn.CreateAccountUserRelationship(relationship); err != nil {
txn.Rollback()
return fmt.Errorf("persistence: error persisting relationship: %w", err)
}
if err := txn.Commit(); err != nil {
return fmt.Errorf("persistence: error committing transaction: %w", err)
}
return nil
}
func (p *persistenceLayer) RetireAccount(accountID string) error {
account, lookupErr := p.dal.FindAccount(FindAccountQueryByID(accountID))
if lookupErr != nil {
return fmt.Errorf("persistence: error looking up account to retire: %w", lookupErr)
}
if account.Retired {
return ErrUnknownAccount(fmt.Sprintf("persistence: account %s already retired", accountID))
}
txn, txnErr := p.dal.Transaction()
if txnErr != nil {
return fmt.Errorf("persistence: error creating transaction: %w", txnErr)
}
account.Retired = true
if err := txn.UpdateAccount(&account); err != nil {
txn.Rollback()
return fmt.Errorf("persistence: error retiring account %s: %w", accountID, err)
}
if err := txn.DeleteAccountUserRelationships(DeleteAccountUserRelationshipsQueryByAccountID(accountID)); err != nil {
txn.Rollback()
return fmt.Errorf("persistence: error deleting account user relationships for retired account %s: %w", accountID, err)
}
if err := txn.Commit(); err != nil {
txn.Rollback()
return fmt.Errorf("persistence: error committing account retiring: %w", err)
}
return nil
}