-
-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
Copy pathAccount.java
550 lines (418 loc) · 14.8 KB
/
Account.java
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
/*
* Copyright 2013 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage;
import com.fasterxml.jackson.annotation.JsonFilter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import java.time.Clock;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import javax.annotation.Nullable;
import org.apache.commons.lang3.StringUtils;
import org.signal.libsignal.protocol.IdentityKey;
import org.signal.libsignal.zkgroup.backups.BackupCredentialType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
import org.whispersystems.textsecuregcm.auth.StoredRegistrationLock;
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.util.ByteArrayBase64UrlAdapter;
import org.whispersystems.textsecuregcm.util.IdentityKeyAdapter;
@JsonFilter("Account")
public class Account {
private static final Logger logger = LoggerFactory.getLogger(Account.class);
@JsonProperty
private UUID uuid;
@JsonProperty("pni")
private UUID phoneNumberIdentifier;
@JsonProperty
private String number;
@JsonProperty
@JsonSerialize(using = ByteArrayBase64UrlAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayBase64UrlAdapter.Deserializing.class)
@Nullable
private byte[] usernameHash;
@JsonProperty
@JsonSerialize(using = ByteArrayBase64UrlAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayBase64UrlAdapter.Deserializing.class)
@Nullable
private byte[] reservedUsernameHash;
@JsonProperty
@Nullable
private UUID usernameLinkHandle;
@JsonProperty("eu")
@Nullable
private byte[] encryptedUsername;
@JsonProperty
private List<Device> devices = new ArrayList<>();
@JsonProperty
@JsonSerialize(using = IdentityKeyAdapter.Serializer.class)
@JsonDeserialize(using = IdentityKeyAdapter.Deserializer.class)
private IdentityKey identityKey;
@JsonProperty("pniIdentityKey")
@JsonSerialize(using = IdentityKeyAdapter.Serializer.class)
@JsonDeserialize(using = IdentityKeyAdapter.Deserializer.class)
private IdentityKey phoneNumberIdentityKey;
@JsonProperty("cpv")
private String currentProfileVersion;
@JsonProperty
private List<AccountBadge> badges = new ArrayList<>();
@JsonProperty
private String registrationLock;
@JsonProperty
private String registrationLockSalt;
@JsonProperty("uak")
private byte[] unidentifiedAccessKey;
@JsonProperty("uua")
private boolean unrestrictedUnidentifiedAccess;
@JsonProperty("inCds")
private boolean discoverableByPhoneNumber = true;
@JsonProperty("bcr")
@Nullable
private byte[] messagesBackupCredentialRequest;
@JsonProperty("mbcr")
@Nullable
private byte[] mediaBackupCredentialRequest;
@JsonProperty("bv")
@Nullable
private BackupVoucher backupVoucher;
@JsonProperty
private int version;
@JsonProperty("holds")
private List<UsernameHold> usernameHolds = Collections.emptyList();
@JsonIgnore
private boolean stale;
public record UsernameHold(@JsonProperty("uh") byte[] usernameHash, @JsonProperty("e") long expirationSecs) {}
public record BackupVoucher(@JsonProperty("rl") long receiptLevel, @JsonProperty("e") Instant expiration) {}
public UUID getIdentifier(final IdentityType identityType) {
return switch (identityType) {
case ACI -> getUuid();
case PNI -> getPhoneNumberIdentifier();
};
}
public UUID getUuid() {
// this is the one method that may be called on a stale account
return uuid;
}
public void setUuid(final UUID uuid) {
requireNotStale();
this.uuid = uuid;
}
public UUID getPhoneNumberIdentifier() {
requireNotStale();
return phoneNumberIdentifier;
}
/**
* Tests whether this account's account identifier or phone number identifier (depending on the given service
* identifier's identity type) matches the given service identifier.
*
* @param serviceIdentifier the identifier to test
* @return {@code true} if this account's identifier or phone number identifier matches
*/
public boolean isIdentifiedBy(final ServiceIdentifier serviceIdentifier) {
return switch (serviceIdentifier.identityType()) {
case ACI -> serviceIdentifier.uuid().equals(uuid);
case PNI -> serviceIdentifier.uuid().equals(phoneNumberIdentifier);
};
}
public String getNumber() {
requireNotStale();
return number;
}
public void setNumber(final String number, final UUID phoneNumberIdentifier) {
requireNotStale();
this.number = number;
this.phoneNumberIdentifier = phoneNumberIdentifier;
}
public Optional<byte[]> getUsernameHash() {
requireNotStale();
return Optional.ofNullable(usernameHash);
}
public void setUsernameHash(final byte[] usernameHash) {
requireNotStale();
this.usernameHash = usernameHash;
}
public Optional<byte[]> getReservedUsernameHash() {
requireNotStale();
return Optional.ofNullable(reservedUsernameHash);
}
public void setReservedUsernameHash(final byte[] reservedUsernameHash) {
requireNotStale();
this.reservedUsernameHash = reservedUsernameHash;
}
@Nullable
public UUID getUsernameLinkHandle() {
requireNotStale();
return usernameLinkHandle;
}
public Optional<byte[]> getEncryptedUsername() {
requireNotStale();
return Optional.ofNullable(encryptedUsername);
}
public void setUsernameLinkDetails(@Nullable final UUID usernameLinkHandle, @Nullable final byte[] encryptedUsername) {
requireNotStale();
if ((usernameLinkHandle == null) ^ (encryptedUsername == null)) {
throw new IllegalArgumentException("Both or neither arguments must be null");
}
if (usernameHash == null && encryptedUsername != null) {
throw new IllegalArgumentException("usernameHash field must be set to store username link");
}
this.encryptedUsername = encryptedUsername;
this.usernameLinkHandle = usernameLinkHandle;
}
/*
* This method is intentionally left package-private so that it's only used
* when Account is read from DB
*/
void setUsernameLinkHandle(@Nullable final UUID usernameLinkHandle) {
requireNotStale();
this.usernameLinkHandle = usernameLinkHandle;
}
public void addDevice(final Device device) {
requireNotStale();
removeDevice(device.getId());
this.devices.add(device);
}
public void removeDevice(final byte deviceId) {
requireNotStale();
this.devices.removeIf(device -> device.getId() == deviceId);
}
public List<Device> getDevices() {
requireNotStale();
return devices;
}
public Device getPrimaryDevice() {
requireNotStale();
return getDevice(Device.PRIMARY_ID)
.orElseThrow(() -> new IllegalStateException("All accounts must have a primary device"));
}
public Optional<Device> getDevice(final byte deviceId) {
requireNotStale();
return devices.stream().filter(device -> device.getId() == deviceId).findFirst();
}
public boolean hasCapability(final DeviceCapability capability) {
requireNotStale();
return switch (capability.getAccountCapabilityMode()) {
case PRIMARY_DEVICE -> getPrimaryDevice().hasCapability(capability);
case ANY_DEVICE -> devices.stream().anyMatch(device -> device.hasCapability(capability));
case ALL_DEVICES -> devices.stream().allMatch(device -> device.hasCapability(capability));
};
}
public byte getNextDeviceId() {
requireNotStale();
byte candidateId = Device.PRIMARY_ID + 1;
while (getDevice(candidateId).isPresent()) {
candidateId++;
}
if (candidateId <= Device.PRIMARY_ID) {
throw new RuntimeException("device ID overflow");
}
return candidateId;
}
public void setIdentityKey(final IdentityKey identityKey) {
requireNotStale();
this.identityKey = identityKey;
}
public IdentityKey getIdentityKey(final IdentityType identityType) {
requireNotStale();
return switch (identityType) {
case ACI -> identityKey;
case PNI -> phoneNumberIdentityKey;
};
}
public void setPhoneNumberIdentityKey(final IdentityKey phoneNumberIdentityKey) {
this.phoneNumberIdentityKey = phoneNumberIdentityKey;
}
public long getLastSeen() {
requireNotStale();
return devices.stream()
.map(Device::getLastSeen)
.max(Long::compare)
.orElse(0L);
}
public Optional<String> getCurrentProfileVersion() {
requireNotStale();
return Optional.ofNullable(currentProfileVersion);
}
public void setCurrentProfileVersion(final String currentProfileVersion) {
requireNotStale();
this.currentProfileVersion = currentProfileVersion;
}
public List<AccountBadge> getBadges() {
requireNotStale();
return badges;
}
public void setBadges(final Clock clock, final List<AccountBadge> badges) {
requireNotStale();
this.badges = badges;
purgeStaleBadges(clock);
}
public void addBadge(final Clock clock, final AccountBadge badge) {
requireNotStale();
boolean added = false;
for (int i = 0; i < badges.size(); i++) {
final AccountBadge badgeInList = badges.get(i);
if (Objects.equals(badgeInList.id(), badge.id())) {
if (added) {
badges.remove(i);
i--;
} else {
badges.set(i, badgeInList.mergeWith(badge));
added = true;
}
}
}
if (!added) {
badges.add(badge);
}
purgeStaleBadges(clock);
}
public void makeBadgePrimaryIfExists(final Clock clock, final String badgeId) {
requireNotStale();
// early exit if it's already the first item in the list
if (!badges.isEmpty() && Objects.equals(badges.get(0).id(), badgeId)) {
purgeStaleBadges(clock);
return;
}
int indexOfBadge = -1;
for (int i = 1; i < badges.size(); i++) {
if (Objects.equals(badgeId, badges.get(i).id())) {
indexOfBadge = i;
break;
}
}
if (indexOfBadge != -1) {
badges.add(0, badges.remove(indexOfBadge));
}
purgeStaleBadges(clock);
}
public void removeBadge(final Clock clock, final String id) {
requireNotStale();
badges.removeIf(accountBadge -> Objects.equals(accountBadge.id(), id));
purgeStaleBadges(clock);
}
private void purgeStaleBadges(final Clock clock) {
final Instant now = clock.instant();
badges.removeIf(accountBadge -> now.isAfter(accountBadge.expiration()));
}
public void setRegistrationLockFromAttributes(final AccountAttributes attributes) {
if (StringUtils.isNotEmpty(attributes.getRegistrationLock())) {
final SaltedTokenHash credentials = SaltedTokenHash.generateFor(attributes.getRegistrationLock());
setRegistrationLock(credentials.hash(), credentials.salt());
} else {
setRegistrationLock(null, null);
}
}
public void setRegistrationLock(final String registrationLock, final String registrationLockSalt) {
requireNotStale();
this.registrationLock = registrationLock;
this.registrationLockSalt = registrationLockSalt;
}
public StoredRegistrationLock getRegistrationLock() {
requireNotStale();
return new StoredRegistrationLock(Optional.ofNullable(registrationLock), Optional.ofNullable(registrationLockSalt), Instant.ofEpochMilli(getLastSeen()));
}
public Optional<byte[]> getUnidentifiedAccessKey() {
requireNotStale();
return Optional.ofNullable(unidentifiedAccessKey);
}
public void setUnidentifiedAccessKey(final byte[] unidentifiedAccessKey) {
requireNotStale();
this.unidentifiedAccessKey = unidentifiedAccessKey;
}
public boolean isUnrestrictedUnidentifiedAccess() {
requireNotStale();
return unrestrictedUnidentifiedAccess;
}
public void setUnrestrictedUnidentifiedAccess(final boolean unrestrictedUnidentifiedAccess) {
requireNotStale();
this.unrestrictedUnidentifiedAccess = unrestrictedUnidentifiedAccess;
}
public boolean isDiscoverableByPhoneNumber() {
requireNotStale();
return this.discoverableByPhoneNumber;
}
public void setDiscoverableByPhoneNumber(final boolean discoverableByPhoneNumber) {
requireNotStale();
this.discoverableByPhoneNumber = discoverableByPhoneNumber;
}
public int getVersion() {
requireNotStale();
return version;
}
public void setVersion(final int version) {
requireNotStale();
this.version = version;
}
public void setBackupCredentialRequests(final byte[] messagesBackupCredentialRequest,
final byte[] mediaBackupCredentialRequest) {
requireNotStale();
this.messagesBackupCredentialRequest = messagesBackupCredentialRequest;
this.mediaBackupCredentialRequest = mediaBackupCredentialRequest;
}
public Optional<byte[]> getBackupCredentialRequest(final BackupCredentialType credentialType) {
requireNotStale();
return Optional.ofNullable(switch (credentialType) {
case MESSAGES -> messagesBackupCredentialRequest;
case MEDIA -> mediaBackupCredentialRequest;
});
}
public @Nullable BackupVoucher getBackupVoucher() {
requireNotStale();
return backupVoucher;
}
public void setBackupVoucher(final @Nullable BackupVoucher backupVoucher) {
requireNotStale();
this.backupVoucher = backupVoucher;
}
/**
* Have all this account's devices been manually locked?
*
* @see Device#hasLockedCredentials
*
* @return true if all the account's devices were locked, false otherwise.
*/
public boolean hasLockedCredentials() {
return devices.stream().allMatch(Device::hasLockedCredentials);
}
/**
* Lock account by invalidating authentication tokens.
*
* We only want to do this in cases where there is a potential conflict between the
* phone number holder and the registration lock holder. In that case, locking the
* account will ensure that either the registration lock holder proves ownership
* of the phone number, or after 7 days the phone number holder can register a new
* account.
*/
public void lockAuthTokenHash() {
devices.forEach(Device::lockAuthTokenHash);
}
public List<UsernameHold> getUsernameHolds() {
return Collections.unmodifiableList(usernameHolds);
}
public void setUsernameHolds(final List<UsernameHold> usernameHolds) {
this.requireNotStale();
this.usernameHolds = usernameHolds;
}
public void markStale() {
stale = true;
}
private void requireNotStale() {
assert !stale;
//noinspection ConstantConditions
if (stale) {
logger.error("Accessor called on stale account", new RuntimeException());
}
}
}