-
-
Notifications
You must be signed in to change notification settings - Fork 48
/
login.go
303 lines (268 loc) · 11.4 KB
/
login.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
// Copyright 2020 - Offen Authors <hioffen@posteo.de>
// SPDX-License-Identifier: Apache-2.0
package persistence
import (
"encoding/base64"
"errors"
"fmt"
"math/rand"
"time"
"github.com/lestrrat-go/jwx/jwk"
"github.com/offen/offen/server/keys"
)
func (p *persistenceLayer) Login(email, password string) (LoginResult, error) {
accountUser, err := p.findAccountUser(email, true, true)
if err != nil {
return LoginResult{}, fmt.Errorf("persistence: error looking up account user: %w", err)
}
if err := keys.CompareString(password, accountUser.HashedPassword); err != nil {
return LoginResult{}, fmt.Errorf("persistence: error comparing passwords: %w", err)
}
pwDerivedKey, pwDerivedKeyErr := keys.DeriveKey(password, accountUser.Salt)
if pwDerivedKeyErr != nil {
return LoginResult{}, fmt.Errorf("persistence: error deriving key from password: %w", pwDerivedKeyErr)
}
// the account user logging in might have pending invitations which we can
// populate with proper password encrypted keys now
var emailDerivedKey []byte
for idx, relationship := range accountUser.Relationships {
if relationship.PasswordEncryptedKeyEncryptionKey != "" {
continue
}
if emailDerivedKey == nil {
var err error
emailDerivedKey, err = keys.DeriveKey(email, accountUser.Salt)
if err != nil {
return LoginResult{}, fmt.Errorf("persistence: error deriving key from email: %w", err)
}
}
key, keyErr := keys.DecryptWith(emailDerivedKey, relationship.EmailEncryptedKeyEncryptionKey)
if keyErr != nil {
return LoginResult{}, fmt.Errorf("persistence: error decryption email encrypted key: %w", keyErr)
}
if err := relationship.addPasswordEncryptedKey(key, accountUser.Salt, password); err != nil {
return LoginResult{}, fmt.Errorf("persistence: error encrypting key for pending invitation: %w", err)
}
if err := p.dal.UpdateAccountUserRelationship(&relationship); err != nil {
return LoginResult{}, fmt.Errorf("persistence: error accepting pending invitation: %w", err)
}
accountUser.Relationships[idx] = relationship
}
var results []LoginAccountResult
for _, relationship := range accountUser.Relationships {
decryptedKey, decryptedKeyErr := keys.DecryptWith(pwDerivedKey, relationship.PasswordEncryptedKeyEncryptionKey)
if decryptedKeyErr != nil {
return LoginResult{}, fmt.Errorf(`persistence: failed decrypting key encryption key for account "%s": %w`, relationship.AccountID, decryptedKeyErr)
}
k, kErr := jwk.New(decryptedKey)
if kErr != nil {
return LoginResult{}, kErr
}
account, err := p.dal.FindAccount(FindAccountQueryByID(relationship.AccountID))
if err != nil {
return LoginResult{}, fmt.Errorf(`persistence: error looking up account with id "%s": %w`, relationship.AccountID, err)
}
result := LoginAccountResult{
AccountName: account.Name,
AccountID: relationship.AccountID,
Created: account.Created,
KeyEncryptionKey: k,
}
results = append(results, result)
}
return LoginResult{
AccountUserID: accountUser.AccountUserID,
AdminLevel: accountUser.AdminLevel,
Accounts: results,
}, nil
}
func (p *persistenceLayer) LookupAccountUser(accountUserID string) (LoginResult, error) {
accountUser, err := p.dal.FindAccountUser(
FindAccountUserQueryByAccountUserIDIncludeRelationships(accountUserID),
)
if err != nil {
return LoginResult{}, fmt.Errorf("persistence: error looking up account user: %w", err)
}
result := LoginResult{
AccountUserID: accountUser.AccountUserID,
AdminLevel: accountUser.AdminLevel,
Accounts: []LoginAccountResult{},
}
for _, relationship := range accountUser.Relationships {
result.Accounts = append(result.Accounts, LoginAccountResult{
AccountID: relationship.AccountID,
})
}
return result, nil
}
func (p *persistenceLayer) ChangePassword(userID, currentPassword, changedPassword string) error {
accountUser, err := p.dal.FindAccountUser(
FindAccountUserQueryByAccountUserIDIncludeRelationships(userID),
)
if err != nil {
return fmt.Errorf("persistence: error looking up account user: %w", err)
}
if err := keys.CompareString(currentPassword, accountUser.HashedPassword); err != nil {
return fmt.Errorf("persistence: current password did not match: %w", err)
}
if err := keys.ValidatePassword(changedPassword); err != nil {
return fmt.Errorf("persistence: error validating new password: %w", err)
}
newPasswordHash, hashErr := keys.HashString(changedPassword)
if hashErr != nil {
return fmt.Errorf("persistence: error hashing new password: %w", hashErr)
}
accountUser.HashedPassword = newPasswordHash.Marshal()
keyFromCurrentPassword, keyErr := keys.DeriveKey(currentPassword, accountUser.Salt)
if keyErr != nil {
return fmt.Errorf("persistence: error deriving key from current password: %w", keyErr)
}
for index, relationship := range accountUser.Relationships {
decryptedKey, decryptErr := keys.DecryptWith(keyFromCurrentPassword, relationship.PasswordEncryptedKeyEncryptionKey)
if decryptErr != nil {
return fmt.Errorf("persistence: error decrypting key using password: %w", decryptErr)
}
if err := relationship.addPasswordEncryptedKey(decryptedKey, accountUser.Salt, changedPassword); err != nil {
return fmt.Errorf("persistence: error updating password encrypted key: %w", err)
}
accountUser.Relationships[index] = relationship
}
if err := p.dal.UpdateAccountUser(&accountUser); err != nil {
return fmt.Errorf("persistence: error updating password for user: %w", err)
}
return nil
}
func (p *persistenceLayer) ResetPassword(emailAddress, password string, oneTimeKey []byte) error {
accountUser, err := p.findAccountUser(emailAddress, true, false)
if err != nil {
return fmt.Errorf("persistence: error looking up account user: %w", err)
}
if err := keys.ValidatePassword(password); err != nil {
return fmt.Errorf("persistence: error validating new password: %w", err)
}
for index, relationship := range accountUser.Relationships {
keyEncryptionKey, decryptionErr := keys.DecryptWith(oneTimeKey, relationship.OneTimeEncryptedKeyEncryptionKey)
if decryptionErr != nil {
return fmt.Errorf("persistence: error decrypting key encryption key: %w", decryptionErr)
}
if err := relationship.addPasswordEncryptedKey(keyEncryptionKey, accountUser.Salt, password); err != nil {
return fmt.Errorf("persistence: error adding password encrypted key to relationship: %w", err)
}
relationship.OneTimeEncryptedKeyEncryptionKey = ""
accountUser.Relationships[index] = relationship
}
passwordHash, hashErr := keys.HashString(password)
if hashErr != nil {
return fmt.Errorf("persistence: error hashing password: %w", hashErr)
}
accountUser.HashedPassword = passwordHash.Marshal()
if err := p.dal.UpdateAccountUser(accountUser); err != nil {
return fmt.Errorf("persistence: error updating password on account user: %w", err)
}
return nil
}
func (p *persistenceLayer) ChangeEmail(userID, newEmailAddress, currentEmailAddress, password string) error {
accountUser, err := p.findAccountUser(currentEmailAddress, true, true)
if err != nil {
return fmt.Errorf("persistence: error looking up account user: %w", err)
}
if accountUser.AccountUserID != userID {
return errors.New("persistence: current email did not match requester credentials")
}
if err := keys.CompareString(password, accountUser.HashedPassword); err != nil {
return fmt.Errorf("persistence: passwords did not match: %w", err)
}
if err := keys.CompareString(currentEmailAddress, accountUser.HashedEmail); err != nil {
return fmt.Errorf("persistence: current email did not match: %w", err)
}
existing, _ := p.findAccountUser(newEmailAddress, false, false)
if existing != nil && existing.AccountUserID != userID {
return fmt.Errorf("persistence: given email %s is already in use", newEmailAddress)
}
keyFromCurrentEmail, keyErr := keys.DeriveKey(currentEmailAddress, accountUser.Salt)
if keyErr != nil {
return fmt.Errorf("persistence: error deriving key from email: %w", keyErr)
}
hashedEmail, hashErr := keys.HashString(newEmailAddress)
if hashErr != nil {
return fmt.Errorf("persistence: error hashing updated email address: %w", hashErr)
}
accountUser.HashedEmail = hashedEmail.Marshal()
for index, relationship := range accountUser.Relationships {
decryptedKey, decryptionErr := keys.DecryptWith(keyFromCurrentEmail, relationship.EmailEncryptedKeyEncryptionKey)
if decryptionErr != nil {
return decryptionErr
}
if err := relationship.addEmailEncryptedKey(decryptedKey, accountUser.Salt, newEmailAddress); err != nil {
return fmt.Errorf("persistence: error adding email key to relationship: %w", err)
}
accountUser.Relationships[index] = relationship
}
if err := p.dal.UpdateAccountUser(accountUser); err != nil {
return fmt.Errorf("persistence: error updating hashed email on account user: %w", err)
}
return nil
}
func (p *persistenceLayer) GenerateOneTimeKey(emailAddress string) ([]byte, error) {
accountUser, err := p.findAccountUser(emailAddress, true, false)
if err != nil {
return nil, fmt.Errorf("persistence: error looking up account user: %w", err)
}
emailDerivedKey, deriveErr := keys.DeriveKey(emailAddress, accountUser.Salt)
if deriveErr != nil {
return nil, fmt.Errorf("error deriving key from email address: %w", deriveErr)
}
oneTimeKey, _ := keys.GenerateRandomValue(keys.DefaultEncryptionKeySize)
oneTimeKeyBytes, _ := base64.StdEncoding.DecodeString(oneTimeKey)
txn, err := p.dal.Transaction()
if err != nil {
return nil, fmt.Errorf("persistence: error creating transaction: %w", err)
}
for _, relationship := range accountUser.Relationships {
decryptedKey, decryptErr := keys.DecryptWith(emailDerivedKey, relationship.EmailEncryptedKeyEncryptionKey)
if decryptErr != nil {
txn.Rollback()
return nil, fmt.Errorf("persistence: error decrypting email encrypted key: %w", decryptErr)
}
if err := relationship.addOneTimeEncryptedKey(decryptedKey, oneTimeKeyBytes); err != nil {
txn.Rollback()
return nil, fmt.Errorf("persistence: erro adding one time key to relationship: %w", err)
}
if err := txn.UpdateAccountUserRelationship(&relationship); err != nil {
txn.Rollback()
return nil, fmt.Errorf("persistence: error updating relationship record: %w", err)
}
}
if err := txn.Commit(); err != nil {
return nil, fmt.Errorf("persistence: error committing transaction: %w", err)
}
return oneTimeKeyBytes, nil
}
func (p *persistenceLayer) findAccountUser(emailAddress string, includeRelationships, IncludeInvitations bool) (*AccountUser, error) {
accountUsers, err := p.dal.FindAccountUsers(FindAccountUsersQueryAllAccountUsers{
IncludeRelationships: includeRelationships,
IncludeInvitations: IncludeInvitations,
})
if err != nil {
return nil, fmt.Errorf("persistence: error looking up account users: %w", err)
}
match, err := selectAccountUser(accountUsers, emailAddress)
if err != nil {
return nil, fmt.Errorf("persistence: could not find user with email %s: %w", emailAddress, err)
}
return match, nil
}
func selectAccountUser(available []AccountUser, email string) (*AccountUser, error) {
// this is so that users that have signed up at a later point in time
// also get decent login times
rand.Seed(time.Now().UnixNano())
rand.Shuffle(len(available), func(i, j int) {
available[i], available[j] = available[j], available[i]
})
for _, user := range available {
if err := keys.CompareString(email, user.HashedEmail); err == nil {
return &user, nil
}
}
return nil, fmt.Errorf("persistence: no account user found for %s", email)
}