mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-12-02 11:56:53 +00:00
Always use fresh/non-cached copies of accounts when making modifications
This commit is contained in:
1 parent
1e2d27585a
commit
9e6cbe8f82
46 files changed
+520
-516
No files matched your search
+1
-1
@@ -142,7 +142,7 @@ public class AccountAuthenticator implements Authenticator<BasicCredentials, Aut
|
||||
Metrics.summary(DAYS_SINCE_LAST_SEEN_DISTRIBUTION_NAME, IS_PRIMARY_DEVICE_TAG, String.valueOf(device.isPrimary()))
|
||||
.record(Duration.ofMillis(todayInMillisWithOffset - device.getLastSeen()).toDays());
|
||||
|
||||
return accountsManager.updateDeviceLastSeen(account, device, Util.todayInMillis(clock));
|
||||
return accountsManager.updateDeviceLastSeen(account.getIdentifier(IdentityType.ACI), device, Util.todayInMillis(clock));
|
||||
}
|
||||
|
||||
return account;
|
||||
|
||||
+1
-1
@@ -284,7 +284,7 @@ public class BackupAuthManager {
|
||||
accountsManager.update(account, a -> {
|
||||
// Receipt credential expirations must be day aligned. Make sure any manually set backupVoucher is also day
|
||||
// aligned
|
||||
final Account.BackupVoucher newPayment = new Account.BackupVoucher(
|
||||
final Account.BackupVoucher newPayment = new Account.BackupVoucher(
|
||||
backupVoucher.receiptLevel(),
|
||||
backupVoucher.expiration().truncatedTo(ChronoUnit.DAYS));
|
||||
final Account.BackupVoucher existingPayment = a.getBackupVoucher();
|
||||
|
||||
+28
-74
@@ -108,33 +108,26 @@ public class AccountController {
|
||||
public void setGcmRegistrationId(@Auth AuthenticatedDevice auth,
|
||||
@NotNull @Valid GcmRegistrationId registrationId) {
|
||||
|
||||
final Account account = accounts.getByAccountIdentifier(auth.accountIdentifier())
|
||||
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
|
||||
final String currentGcmId = accounts.getByAccountIdentifier(auth.accountIdentifier())
|
||||
.flatMap(account -> account.getDevice(auth.deviceId()))
|
||||
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED))
|
||||
.getGcmId();
|
||||
|
||||
final Device device = account.getDevice(auth.deviceId())
|
||||
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
|
||||
|
||||
if (Objects.equals(device.getGcmId(), registrationId.gcmRegistrationId())) {
|
||||
if (Objects.equals(currentGcmId, registrationId.gcmRegistrationId())) {
|
||||
return;
|
||||
}
|
||||
|
||||
accounts.updateDevice(account, device.getId(), d -> {
|
||||
d.setApnId(null);
|
||||
d.setGcmId(registrationId.gcmRegistrationId());
|
||||
d.setFetchesMessages(false);
|
||||
accounts.updateDevice(auth.accountIdentifier(), auth.deviceId(), device -> {
|
||||
device.setApnId(null);
|
||||
device.setGcmId(registrationId.gcmRegistrationId());
|
||||
device.setFetchesMessages(false);
|
||||
});
|
||||
}
|
||||
|
||||
@DELETE
|
||||
@Path("/gcm/")
|
||||
public void deleteGcmRegistrationId(@Auth AuthenticatedDevice auth) {
|
||||
final Account account = accounts.getByAccountIdentifier(auth.accountIdentifier())
|
||||
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
|
||||
|
||||
final Device device = account.getDevice(auth.deviceId())
|
||||
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
|
||||
|
||||
accounts.updateDevice(account, device.getId(), d -> {
|
||||
accounts.updateDevice(auth.accountIdentifier(), auth.deviceId(), d -> {
|
||||
d.setGcmId(null);
|
||||
d.setFetchesMessages(false);
|
||||
d.setUserAgent("OWA");
|
||||
@@ -148,15 +141,9 @@ public class AccountController {
|
||||
public void setApnRegistrationId(@Auth AuthenticatedDevice auth,
|
||||
@NotNull @Valid ApnRegistrationId registrationId) {
|
||||
|
||||
final Account account = accounts.getByAccountIdentifier(auth.accountIdentifier())
|
||||
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
|
||||
|
||||
final Device device = account.getDevice(auth.deviceId())
|
||||
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
|
||||
|
||||
// Unlike FCM tokens, we need current "last updated" timestamps for APNs tokens and so update device records
|
||||
// unconditionally
|
||||
accounts.updateDevice(account, device.getId(), d -> {
|
||||
accounts.updateDevice(auth.accountIdentifier(), auth.deviceId(), d -> {
|
||||
d.setApnId(registrationId.apnRegistrationId());
|
||||
d.setGcmId(null);
|
||||
d.setFetchesMessages(false);
|
||||
@@ -166,20 +153,10 @@ public class AccountController {
|
||||
@DELETE
|
||||
@Path("/apn/")
|
||||
public void deleteApnRegistrationId(@Auth AuthenticatedDevice auth) {
|
||||
final Account account = accounts.getByAccountIdentifier(auth.accountIdentifier())
|
||||
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
|
||||
|
||||
final Device device = account.getDevice(auth.deviceId())
|
||||
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
|
||||
|
||||
accounts.updateDevice(account, device.getId(), d -> {
|
||||
accounts.updateDevice(auth.accountIdentifier(), auth.deviceId(), d -> {
|
||||
d.setApnId(null);
|
||||
d.setFetchesMessages(false);
|
||||
if (d.getId() == 1) {
|
||||
d.setUserAgent("OWI");
|
||||
} else {
|
||||
d.setUserAgent("OWP");
|
||||
}
|
||||
d.setUserAgent(d.isPrimary() ? "OWI" : "OWP");
|
||||
});
|
||||
}
|
||||
|
||||
@@ -189,20 +166,14 @@ public class AccountController {
|
||||
public void setRegistrationLock(@Auth AuthenticatedDevice auth, @NotNull @Valid RegistrationLock accountLock) {
|
||||
final SaltedTokenHash credentials = SaltedTokenHash.generateFor(accountLock.registrationLock());
|
||||
|
||||
final Account account = accounts.getByAccountIdentifier(auth.accountIdentifier())
|
||||
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
|
||||
|
||||
accounts.update(account,
|
||||
accounts.update(auth.accountIdentifier(),
|
||||
a -> a.setRegistrationLock(credentials.hash(), credentials.salt()));
|
||||
}
|
||||
|
||||
@DELETE
|
||||
@Path("/registration_lock")
|
||||
public void removeRegistrationLock(@Auth AuthenticatedDevice auth) {
|
||||
final Account account = accounts.getByAccountIdentifier(auth.accountIdentifier())
|
||||
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
|
||||
|
||||
accounts.update(account, a -> a.setRegistrationLock(null, null));
|
||||
accounts.update(auth.accountIdentifier(), a -> a.setRegistrationLock(null, null));
|
||||
}
|
||||
|
||||
@PUT
|
||||
@@ -240,7 +211,7 @@ public class AccountController {
|
||||
throw new ForbiddenException();
|
||||
}
|
||||
|
||||
accounts.updateDevice(account, targetDeviceId, d -> d.setName(deviceName.deviceName()));
|
||||
accounts.updateDevice(account.getIdentifier(IdentityType.ACI), targetDeviceId, d -> d.setName(deviceName.deviceName()));
|
||||
}
|
||||
|
||||
@PUT
|
||||
@@ -252,10 +223,8 @@ public class AccountController {
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) String userAgent,
|
||||
@HeaderParam(HeaderUtils.X_SIGNAL_AGENT) String signalAgent,
|
||||
@NotNull @Valid AccountAttributes attributes) {
|
||||
final Account account = accounts.getByAccountIdentifier(auth.accountIdentifier())
|
||||
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
|
||||
|
||||
final Account updatedAccount = accounts.update(account, a -> {
|
||||
final Account updatedAccount = accounts.update(auth.accountIdentifier(), a -> {
|
||||
a.getDevice(auth.deviceId()).ifPresent(d -> {
|
||||
d.setFetchesMessages(attributes.getFetchesMessages());
|
||||
d.setName(attributes.getName());
|
||||
@@ -306,10 +275,7 @@ public class AccountController {
|
||||
@ApiResponse(responseCode = "204", description = "Username successfully deleted.", useReturnTypeSchema = true)
|
||||
@ApiResponse(responseCode = "401", description = "Account authentication check failed.")
|
||||
public void deleteUsernameHash(@Auth final AuthenticatedDevice auth) {
|
||||
final Account account = accounts.getByAccountIdentifier(auth.accountIdentifier())
|
||||
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
|
||||
|
||||
accounts.clearUsernameHash(account);
|
||||
accounts.clearUsernameHash(auth.accountIdentifier());
|
||||
}
|
||||
|
||||
@PUT
|
||||
@@ -332,9 +298,6 @@ public class AccountController {
|
||||
@Auth final AuthenticatedDevice auth,
|
||||
@NotNull @Valid final ReserveUsernameHashRequest usernameRequest) throws RateLimitExceededException {
|
||||
|
||||
final Account account = accounts.getByAccountIdentifier(auth.accountIdentifier())
|
||||
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
|
||||
|
||||
rateLimiters.getUsernameReserveLimiter().validate(auth.accountIdentifier());
|
||||
|
||||
for (final byte[] hash : usernameRequest.usernameHashes()) {
|
||||
@@ -345,7 +308,7 @@ public class AccountController {
|
||||
|
||||
try {
|
||||
final AccountsManager.UsernameReservation reservation =
|
||||
accounts.reserveUsernameHash(account, usernameRequest.usernameHashes());
|
||||
accounts.reserveUsernameHash(auth.accountIdentifier(), usernameRequest.usernameHashes());
|
||||
|
||||
return new ReserveUsernameHashResponse(reservation.reservedUsernameHash());
|
||||
} catch (final UsernameHashNotAvailableException e) {
|
||||
@@ -374,20 +337,17 @@ public class AccountController {
|
||||
@Auth final AuthenticatedDevice auth,
|
||||
@NotNull @Valid final ConfirmUsernameHashRequest confirmRequest) throws RateLimitExceededException {
|
||||
|
||||
final Account account = accounts.getByAccountIdentifier(auth.accountIdentifier())
|
||||
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
|
||||
|
||||
try {
|
||||
usernameHashZkProofVerifier.verifyProof(confirmRequest.zkProof(), confirmRequest.usernameHash());
|
||||
} catch (final BaseUsernameException e) {
|
||||
throw new WebApplicationException(Response.status(422).build());
|
||||
}
|
||||
|
||||
rateLimiters.getUsernameSetLimiter().validate(account.getUuid());
|
||||
rateLimiters.getUsernameSetLimiter().validate(auth.accountIdentifier());
|
||||
|
||||
try {
|
||||
final Account updatedAccount = accounts.confirmReservedUsernameHash(
|
||||
account,
|
||||
auth.accountIdentifier(),
|
||||
confirmRequest.usernameHash(),
|
||||
confirmRequest.encryptedUsername());
|
||||
|
||||
@@ -474,7 +434,7 @@ public class AccountController {
|
||||
} else {
|
||||
usernameLinkHandle = UUID.randomUUID();
|
||||
}
|
||||
updateUsernameLink(account, usernameLinkHandle, encryptedUsername.usernameLinkEncryptedValue());
|
||||
updateUsernameLink(account.getIdentifier(IdentityType.ACI), usernameLinkHandle, encryptedUsername.usernameLinkEncryptedValue());
|
||||
return new UsernameLinkHandle(usernameLinkHandle);
|
||||
}
|
||||
|
||||
@@ -494,10 +454,7 @@ public class AccountController {
|
||||
// check ratelimiter for username link operations
|
||||
rateLimiters.forDescriptor(RateLimiters.For.USERNAME_LINK_OPERATION).validate(auth.accountIdentifier());
|
||||
|
||||
final Account account = accounts.getByAccountIdentifier(auth.accountIdentifier())
|
||||
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
|
||||
|
||||
clearUsernameLink(account);
|
||||
clearUsernameLink(auth.accountIdentifier());
|
||||
}
|
||||
|
||||
@GET
|
||||
@@ -559,24 +516,21 @@ public class AccountController {
|
||||
@DELETE
|
||||
@Path("/me")
|
||||
public void deleteAccount(@Auth AuthenticatedDevice auth) {
|
||||
final Account account = accounts.getByAccountIdentifier(auth.accountIdentifier())
|
||||
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
|
||||
|
||||
accounts.delete(account, AccountsManager.DeletionReason.USER_REQUEST);
|
||||
accounts.delete(auth.accountIdentifier(), AccountsManager.DeletionReason.USER_REQUEST);
|
||||
}
|
||||
|
||||
private void clearUsernameLink(final Account account) {
|
||||
updateUsernameLink(account, null, null);
|
||||
private void clearUsernameLink(final UUID accountIdentifier) {
|
||||
updateUsernameLink(accountIdentifier, null, null);
|
||||
}
|
||||
|
||||
private void updateUsernameLink(
|
||||
final Account account,
|
||||
final UUID accountIdentifier,
|
||||
@Nullable final UUID usernameLinkHandle,
|
||||
@Nullable final byte[] encryptedUsername) {
|
||||
if ((encryptedUsername == null) ^ (usernameLinkHandle == null)) {
|
||||
throw new IllegalStateException("Both or neither arguments must be null");
|
||||
}
|
||||
accounts.update(account, a -> a.setUsernameLinkDetails(usernameLinkHandle, encryptedUsername));
|
||||
accounts.update(accountIdentifier, a -> a.setUsernameLinkDetails(usernameLinkHandle, encryptedUsername));
|
||||
}
|
||||
|
||||
private void requireNotAuthenticated(final Optional<AuthenticatedDevice> authenticatedAccount) {
|
||||
|
||||
+1
-4
@@ -179,10 +179,7 @@ public class AccountControllerV2 {
|
||||
@Auth AuthenticatedDevice auth,
|
||||
@NotNull @Valid PhoneNumberDiscoverabilityRequest phoneNumberDiscoverability) {
|
||||
|
||||
final Account account = accountsManager.getByAccountIdentifier(auth.accountIdentifier())
|
||||
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
|
||||
|
||||
accountsManager.update(account, a -> a.setDiscoverableByPhoneNumber(
|
||||
accountsManager.update(auth.accountIdentifier(), a -> a.setDiscoverableByPhoneNumber(
|
||||
phoneNumberDiscoverability.discoverableByPhoneNumber()));
|
||||
}
|
||||
|
||||
|
||||
+18
-27
@@ -159,10 +159,7 @@ public class DeviceController {
|
||||
throw new ForbiddenException();
|
||||
}
|
||||
|
||||
final Account account = accounts.getByAccountIdentifier(auth.accountIdentifier())
|
||||
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
|
||||
|
||||
accounts.removeDevice(account, deviceId);
|
||||
accounts.removeDevice(auth.accountIdentifier(), deviceId);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -282,20 +279,21 @@ public class DeviceController {
|
||||
}
|
||||
|
||||
try {
|
||||
final Pair<Account, Device> accountAndDevice = accounts.addDevice(account, new DeviceSpec(deviceAttributes.name(),
|
||||
authorizationHeader.getPassword(),
|
||||
signalAgent,
|
||||
capabilities,
|
||||
deviceAttributes.registrationId(),
|
||||
deviceAttributes.phoneNumberIdentityRegistrationId(),
|
||||
deviceAttributes.fetchesMessages(),
|
||||
deviceActivationRequest.apnToken(),
|
||||
deviceActivationRequest.gcmToken(),
|
||||
deviceActivationRequest.aciSignedPreKey(),
|
||||
deviceActivationRequest.pniSignedPreKey(),
|
||||
deviceActivationRequest.aciPqLastResortPreKey(),
|
||||
deviceActivationRequest.pniPqLastResortPreKey()),
|
||||
linkDeviceRequest.verificationCode());
|
||||
final Pair<Account, Device> accountAndDevice = accounts.addDevice(account.getIdentifier(IdentityType.ACI),
|
||||
new DeviceSpec(deviceAttributes.name(),
|
||||
authorizationHeader.getPassword(),
|
||||
signalAgent,
|
||||
capabilities,
|
||||
deviceAttributes.registrationId(),
|
||||
deviceAttributes.phoneNumberIdentityRegistrationId(),
|
||||
deviceAttributes.fetchesMessages(),
|
||||
deviceActivationRequest.apnToken(),
|
||||
deviceActivationRequest.gcmToken(),
|
||||
deviceActivationRequest.aciSignedPreKey(),
|
||||
deviceActivationRequest.pniSignedPreKey(),
|
||||
deviceActivationRequest.aciPqLastResortPreKey(),
|
||||
deviceActivationRequest.pniPqLastResortPreKey()),
|
||||
linkDeviceRequest.verificationCode());
|
||||
|
||||
return new LinkDeviceResponse(
|
||||
accountAndDevice.first().getIdentifier(IdentityType.ACI),
|
||||
@@ -384,15 +382,8 @@ public class DeviceController {
|
||||
@PUT
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/capabilities")
|
||||
public void setCapabilities(@Auth final AuthenticatedDevice auth,
|
||||
|
||||
@NotNull
|
||||
final Map<String, Boolean> capabilities) {
|
||||
|
||||
final Account account = accounts.getByAccountIdentifier(auth.accountIdentifier())
|
||||
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
|
||||
|
||||
accounts.updateDevice(account, auth.deviceId(),
|
||||
public void setCapabilities(@Auth final AuthenticatedDevice auth, @NotNull final Map<String, Boolean> capabilities) {
|
||||
accounts.updateDevice(auth.accountIdentifier(), auth.deviceId(),
|
||||
d -> d.setCapabilities(DeviceCapabilityAdapter.mapToSet(capabilities)));
|
||||
}
|
||||
|
||||
|
||||
+1
-9
@@ -15,16 +15,12 @@ import jakarta.ws.rs.Consumes;
|
||||
import jakarta.ws.rs.POST;
|
||||
import jakarta.ws.rs.Path;
|
||||
import jakarta.ws.rs.Produces;
|
||||
import jakarta.ws.rs.WebApplicationException;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import jakarta.ws.rs.core.Response.Status;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
import java.util.function.Function;
|
||||
import javax.annotation.Nonnull;
|
||||
import org.glassfish.jersey.server.ManagedAsync;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
@@ -35,7 +31,6 @@ import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.configuration.BadgesConfiguration;
|
||||
import org.whispersystems.textsecuregcm.entities.RedeemReceiptRequest;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountBadge;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.RedeemedReceiptsManager;
|
||||
@@ -121,9 +116,6 @@ public class DonationController {
|
||||
.build();
|
||||
}
|
||||
|
||||
final Account account = accountsManager.getByAccountIdentifier(auth.accountIdentifier())
|
||||
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
|
||||
|
||||
final boolean receiptMatched = redeemedReceiptsManager.put(
|
||||
receiptSerial, receiptExpiration.getEpochSecond(), receiptLevel, auth.accountIdentifier()).join();
|
||||
if (!receiptMatched) {
|
||||
@@ -133,7 +125,7 @@ public class DonationController {
|
||||
.build();
|
||||
}
|
||||
|
||||
accountsManager.update(account, a -> {
|
||||
accountsManager.update(auth.accountIdentifier(), a -> {
|
||||
a.addBadge(clock, new AccountBadge(badgeId, receiptExpiration, request.isVisible()));
|
||||
if (request.isPrimary()) {
|
||||
a.makeBadgePrimaryIfExists(clock, badgeId);
|
||||
|
||||
+1
-1
@@ -215,7 +215,7 @@ public class ProfileController {
|
||||
currentAvatar.ifPresent(profilesManager::deleteAvatar);
|
||||
}
|
||||
|
||||
accountsManager.update(account, a -> {
|
||||
accountsManager.update(account.getIdentifier(IdentityType.ACI), a -> {
|
||||
|
||||
final List<AccountBadge> updatedBadges = request.badges()
|
||||
.map(badges -> ProfileHelper.mergeBadgeIdsWithExistingAccountBadges(clock, badgeConfigurationMap, badges, a.getBadges()))
|
||||
|
||||
+13
-14
@@ -97,8 +97,8 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
|
||||
|
||||
@Override
|
||||
public DeleteAccountResponse deleteAccount(final DeleteAccountRequest request) {
|
||||
accountsManager.delete(getAuthenticatedAccount(AuthenticationUtil.requireAuthenticatedPrimaryDevice()),
|
||||
AccountsManager.DeletionReason.USER_REQUEST);
|
||||
accountsManager.delete(AuthenticationUtil.requireAuthenticatedPrimaryDevice().accountIdentifier(),
|
||||
AccountsManager.DeletionReason.USER_REQUEST);
|
||||
|
||||
return DeleteAccountResponse.getDefaultInstance();
|
||||
}
|
||||
@@ -110,7 +110,7 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
|
||||
final SaltedTokenHash credentials =
|
||||
SaltedTokenHash.generateFor(HexFormat.of().withLowerCase().formatHex(request.getRegistrationLock().toByteArray()));
|
||||
|
||||
accountsManager.update(getAuthenticatedAccount(AuthenticationUtil.requireAuthenticatedPrimaryDevice()),
|
||||
accountsManager.update(AuthenticationUtil.requireAuthenticatedPrimaryDevice().accountIdentifier(),
|
||||
account -> account.setRegistrationLock(credentials.hash(), credentials.salt()));
|
||||
|
||||
return SetRegistrationLockResponse.getDefaultInstance();
|
||||
@@ -118,7 +118,7 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
|
||||
|
||||
@Override
|
||||
public ClearRegistrationLockResponse clearRegistrationLock(final ClearRegistrationLockRequest request) {
|
||||
accountsManager.update(getAuthenticatedAccount(AuthenticationUtil.requireAuthenticatedPrimaryDevice()),
|
||||
accountsManager.update(AuthenticationUtil.requireAuthenticatedPrimaryDevice().accountIdentifier(),
|
||||
account -> account.setRegistrationLock(null, null));
|
||||
|
||||
return ClearRegistrationLockResponse.getDefaultInstance();
|
||||
@@ -142,11 +142,9 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
|
||||
|
||||
rateLimiters.getUsernameReserveLimiter().validate(authenticatedDevice.accountIdentifier());
|
||||
|
||||
final Account account = getAuthenticatedAccount();
|
||||
|
||||
try {
|
||||
final AccountsManager.UsernameReservation usernameReservation =
|
||||
accountsManager.reserveUsernameHash(account, usernameHashes);
|
||||
accountsManager.reserveUsernameHash(authenticatedDevice.accountIdentifier(), usernameHashes);
|
||||
|
||||
return ReserveUsernameHashResponse.newBuilder()
|
||||
.setUsernameHash(ByteString.copyFrom(usernameReservation.reservedUsernameHash()))
|
||||
@@ -172,7 +170,7 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
|
||||
rateLimiters.getUsernameSetLimiter().validate(authenticatedDevice.accountIdentifier());
|
||||
|
||||
try {
|
||||
final Account updatedAccount = accountsManager.confirmReservedUsernameHash(getAuthenticatedAccount(),
|
||||
final Account updatedAccount = accountsManager.confirmReservedUsernameHash(authenticatedDevice.accountIdentifier(),
|
||||
request.getUsernameHash().toByteArray(),
|
||||
request.getUsernameCiphertext().toByteArray());
|
||||
|
||||
@@ -196,7 +194,7 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
|
||||
|
||||
@Override
|
||||
public DeleteUsernameHashResponse deleteUsernameHash(final DeleteUsernameHashRequest request) {
|
||||
accountsManager.clearUsernameHash(getAuthenticatedAccount());
|
||||
accountsManager.clearUsernameHash(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier());
|
||||
|
||||
return DeleteUsernameHashResponse.getDefaultInstance();
|
||||
}
|
||||
@@ -220,7 +218,8 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
|
||||
? account.getUsernameLinkHandle()
|
||||
: UUID.randomUUID();
|
||||
|
||||
accountsManager.update(account, a -> a.setUsernameLinkDetails(linkHandle, request.getUsernameCiphertext().toByteArray()));
|
||||
accountsManager.update(account.getIdentifier(IdentityType.ACI),
|
||||
a -> a.setUsernameLinkDetails(linkHandle, request.getUsernameCiphertext().toByteArray()));
|
||||
|
||||
return responseBuilder.setUsernameLinkHandle(UUIDUtil.toByteString(linkHandle)).build();
|
||||
}
|
||||
@@ -232,7 +231,7 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
|
||||
|
||||
rateLimiters.getUsernameLinkOperationLimiter().validate(authenticatedDevice.accountIdentifier());
|
||||
|
||||
accountsManager.update(getAuthenticatedAccount(), a -> a.setUsernameLinkDetails(null, null));
|
||||
accountsManager.update(authenticatedDevice.accountIdentifier(), a -> a.setUsernameLinkDetails(null, null));
|
||||
|
||||
return DeleteUsernameLinkResponse.getDefaultInstance();
|
||||
}
|
||||
@@ -245,7 +244,7 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
|
||||
UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH, request.getUnidentifiedAccessKey().size()));
|
||||
}
|
||||
|
||||
accountsManager.update(getAuthenticatedAccount(), account -> {
|
||||
accountsManager.update(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier(), account -> {
|
||||
account.setUnrestrictedUnidentifiedAccess(request.getAllowUnrestrictedUnidentifiedAccess());
|
||||
account.setUnidentifiedAccessKey(request.getAllowUnrestrictedUnidentifiedAccess() ? null : request.getUnidentifiedAccessKey().toByteArray());
|
||||
});
|
||||
@@ -255,7 +254,7 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
|
||||
|
||||
@Override
|
||||
public SetDiscoverableByPhoneNumberResponse setDiscoverableByPhoneNumber(final SetDiscoverableByPhoneNumberRequest request) {
|
||||
accountsManager.update(getAuthenticatedAccount(),
|
||||
accountsManager.update(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier(),
|
||||
account -> account.setDiscoverableByPhoneNumber(request.getDiscoverableByPhoneNumber()));
|
||||
|
||||
return SetDiscoverableByPhoneNumberResponse.getDefaultInstance();
|
||||
@@ -283,7 +282,7 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
|
||||
|
||||
rateLimiters.getSetZkCredentialKeyLimiter().validate(authenticatedDevice.accountIdentifier());
|
||||
|
||||
accountsManager.update(authenticatedAccount, account -> account.setZkCredentialKey(zkCredentialKey));
|
||||
accountsManager.update(authenticatedDevice.accountIdentifier(), account -> account.setZkCredentialKey(zkCredentialKey));
|
||||
|
||||
return SetZkCredentialKeyResponse.getDefaultInstance();
|
||||
}
|
||||
|
||||
@@ -80,9 +80,7 @@ public class DevicesGrpcService extends SimpleDevicesGrpc.DevicesImplBase {
|
||||
throw GrpcExceptions.badAuthentication("linked devices cannot remove devices other than themselves");
|
||||
}
|
||||
|
||||
final byte deviceId = DeviceIdUtil.validate(request.getId());
|
||||
|
||||
accountsManager.removeDevice(getAuthenticatedAccount(), deviceId);
|
||||
accountsManager.removeDevice(authenticatedDevice.accountIdentifier(), DeviceIdUtil.validate(request.getId()));
|
||||
|
||||
return RemoveDeviceResponse.getDefaultInstance();
|
||||
}
|
||||
@@ -106,7 +104,7 @@ public class DevicesGrpcService extends SimpleDevicesGrpc.DevicesImplBase {
|
||||
return SetDeviceNameResponse.newBuilder().setTargetDeviceNotFound(NotFound.getDefaultInstance()).build();
|
||||
}
|
||||
|
||||
accountsManager.updateDevice(account, deviceId, device -> device.setName(request.getName().toByteArray()));
|
||||
accountsManager.updateDevice(account.getIdentifier(IdentityType.ACI), deviceId, device -> device.setName(request.getName().toByteArray()));
|
||||
|
||||
return SetDeviceNameResponse.newBuilder().setSuccess(Empty.getDefaultInstance()).build();
|
||||
}
|
||||
@@ -141,7 +139,7 @@ public class DevicesGrpcService extends SimpleDevicesGrpc.DevicesImplBase {
|
||||
.orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials"));
|
||||
|
||||
if (!Objects.equals(device.getApnId(), apnsToken) || !Objects.equals(device.getGcmId(), fcmToken)) {
|
||||
accountsManager.updateDevice(account, authenticatedDevice.deviceId(), d -> {
|
||||
accountsManager.updateDevice(account.getIdentifier(IdentityType.ACI), authenticatedDevice.deviceId(), d -> {
|
||||
d.setApnId(apnsToken);
|
||||
d.setGcmId(fcmToken);
|
||||
d.setFetchesMessages(false);
|
||||
@@ -154,9 +152,8 @@ public class DevicesGrpcService extends SimpleDevicesGrpc.DevicesImplBase {
|
||||
@Override
|
||||
public ClearPushTokenResponse clearPushToken(final ClearPushTokenRequest request) {
|
||||
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
|
||||
final Account account = getAuthenticatedAccount();
|
||||
|
||||
accountsManager.updateDevice(account, authenticatedDevice.deviceId(), device -> {
|
||||
accountsManager.updateDevice(authenticatedDevice.accountIdentifier(), authenticatedDevice.deviceId(), device -> {
|
||||
if (StringUtils.isNotBlank(device.getApnId())) {
|
||||
device.setUserAgent(device.isPrimary() ? "OWI" : "OWP");
|
||||
} else if (StringUtils.isNotBlank(device.getGcmId())) {
|
||||
@@ -179,7 +176,7 @@ public class DevicesGrpcService extends SimpleDevicesGrpc.DevicesImplBase {
|
||||
.map(DeviceCapabilityUtil::fromGrpcDeviceCapability)
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
accountsManager.updateDevice(getAuthenticatedAccount(), authenticatedDevice.deviceId(),
|
||||
accountsManager.updateDevice(authenticatedDevice.accountIdentifier(), authenticatedDevice.deviceId(),
|
||||
device -> device.setCapabilities(capabilities));
|
||||
|
||||
return SetCapabilitiesResponse.getDefaultInstance();
|
||||
|
||||
@@ -124,7 +124,7 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
|
||||
}
|
||||
};
|
||||
|
||||
profilesManager.set(account.getUuid(),
|
||||
profilesManager.set(account.getIdentifier(IdentityType.ACI),
|
||||
new VersionedProfile(
|
||||
request.getVersion(),
|
||||
request.getName().toByteArray(),
|
||||
@@ -135,7 +135,7 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
|
||||
request.getPhoneNumberSharing().toByteArray(),
|
||||
request.getCommitment().toByteArray()));
|
||||
|
||||
accountsManager.update(account, a -> {
|
||||
accountsManager.update(account.getIdentifier(IdentityType.ACI), a -> {
|
||||
|
||||
final List<AccountBadge> updatedBadges = Optional.of(request.getBadgeIdsList())
|
||||
.map(badges -> ProfileHelper.mergeBadgeIdsWithExistingAccountBadges(clock, badgeConfigurationMap, badges,
|
||||
|
||||
+2
-1
@@ -17,6 +17,7 @@ import java.util.function.BiConsumer;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
@@ -195,7 +196,7 @@ public class PushNotificationManager {
|
||||
// updating an uninstalled feedback timestamp though.
|
||||
accountsManager.getByAccountIdentifier(account.getUuid()).ifPresent(rereadAccount ->
|
||||
rereadAccount.getDevice(device.getId()).ifPresent(rereadDevice ->
|
||||
accountsManager.updateDevice(rereadAccount, device.getId(), d -> {
|
||||
accountsManager.updateDevice(rereadAccount.getIdentifier(IdentityType.ACI), device.getId(), d -> {
|
||||
// Don't clear the token if it's already changed
|
||||
if (originalToken.equals(getPushToken(d, tokenType))) {
|
||||
switch (tokenType) {
|
||||
|
||||
+79
-76
@@ -433,11 +433,15 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
return account;
|
||||
}
|
||||
|
||||
public Pair<Account, Device> addDevice(final Account account, final DeviceSpec deviceSpec, final String linkDeviceToken)
|
||||
public Pair<Account, Device> addDevice(final UUID accountIdentifier, final DeviceSpec deviceSpec, final String linkDeviceToken)
|
||||
throws LinkDeviceTokenAlreadyUsedException {
|
||||
|
||||
return accountLockManager.withLock(Set.of(account.getPhoneNumberIdentifier()),
|
||||
() -> addDevice(account.getIdentifier(IdentityType.ACI), deviceSpec, linkDeviceToken, MAX_UPDATE_ATTEMPTS),
|
||||
final UUID phoneNumberIdentifier = accounts.getByAccountIdentifier(accountIdentifier)
|
||||
.map(account -> account.getIdentifier(IdentityType.PNI))
|
||||
.orElseThrow(() -> new IllegalArgumentException("Account not found: " + accountIdentifier));
|
||||
|
||||
return accountLockManager.withLock(Set.of(phoneNumberIdentifier),
|
||||
() -> addDevice(accountIdentifier, deviceSpec, linkDeviceToken, MAX_UPDATE_ATTEMPTS),
|
||||
accountLockExecutor);
|
||||
}
|
||||
|
||||
@@ -622,13 +626,18 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
*
|
||||
* @return the updated Account
|
||||
*/
|
||||
public Account removeDevice(final Account account, final byte deviceId) {
|
||||
public Account removeDevice(final UUID accountIdentifier, final byte deviceId) {
|
||||
if (deviceId == Device.PRIMARY_ID) {
|
||||
throw new IllegalArgumentException("Cannot remove primary device");
|
||||
}
|
||||
|
||||
return accountLockManager.withLock(Set.of(account.getPhoneNumberIdentifier()),
|
||||
() -> removeDevice(account.getIdentifier(IdentityType.ACI), deviceId, MAX_UPDATE_ATTEMPTS),
|
||||
// Always fetch a fresh, non-cached copy of the account before making modifications
|
||||
final UUID phoneNumberIdentifier = accounts.getByAccountIdentifier(accountIdentifier)
|
||||
.map(account -> account.getIdentifier(IdentityType.PNI))
|
||||
.orElseThrow(() -> new IllegalArgumentException("Account not found: " + accountIdentifier));
|
||||
|
||||
return accountLockManager.withLock(Set.of(phoneNumberIdentifier),
|
||||
() -> removeDevice(accountIdentifier, deviceId, MAX_UPDATE_ATTEMPTS),
|
||||
accountLockExecutor);
|
||||
}
|
||||
|
||||
@@ -672,13 +681,17 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
}
|
||||
}
|
||||
|
||||
public Account changeNumber(final Account account,
|
||||
public Account changeNumber(final UUID accountIdentifier,
|
||||
final String targetNumber,
|
||||
final IdentityKey pniIdentityKey,
|
||||
final Map<Byte, ECSignedPreKey> pniSignedPreKeys,
|
||||
final Map<Byte, KEMSignedPreKey> pniPqLastResortPreKeys,
|
||||
final Map<Byte, Integer> pniRegistrationIds) throws InterruptedException, MismatchedDevicesException {
|
||||
|
||||
// Always fetch a fresh, non-cached copy of the account before making modifications
|
||||
final Account account = accounts.getByAccountIdentifier(accountIdentifier)
|
||||
.orElseThrow(() -> new IllegalArgumentException("Account not found: " + accountIdentifier));
|
||||
|
||||
final UUID targetPhoneNumberIdentifier = phoneNumberIdentifiers.getPhoneNumberIdentifier(targetNumber).join();
|
||||
|
||||
try {
|
||||
@@ -743,7 +756,6 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
buildPniKeyWriteItems(targetPhoneNumberIdentifier, pniSignedPreKeys, pniPqLastResortPreKeys);
|
||||
|
||||
return updateWithRetries(
|
||||
account,
|
||||
a -> {
|
||||
setPniKeys(a, pniIdentityKey, pniRegistrationIds);
|
||||
return true;
|
||||
@@ -815,18 +827,23 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
|
||||
/// Reserve a username hash so that no other accounts may take it.
|
||||
///
|
||||
/// The reserved hash can later be set with [#confirmReservedUsernameHash(Account, byte\[\], byte\[\])]. The
|
||||
/// The reserved hash can later be set with [#confirmReservedUsernameHash(UUID, byte\[\], byte\[\])]. The
|
||||
/// reservation will eventually expire, after which point confirmReservedUsernameHash may fail if another account has
|
||||
/// taken the username hash.
|
||||
///
|
||||
/// @param account the account to update
|
||||
/// @param accountIdentifier the unique identifier of the account to update
|
||||
/// @param requestedUsernameHashes the list of username hashes to attempt to reserve
|
||||
///
|
||||
/// @return the reserved username hash
|
||||
///
|
||||
/// @throws UsernameHashNotAvailableException if none of the given username hashes are available
|
||||
public UsernameReservation reserveUsernameHash(final Account account, final List<byte[]> requestedUsernameHashes)
|
||||
public UsernameReservation reserveUsernameHash(final UUID accountIdentifier, final List<byte[]> requestedUsernameHashes)
|
||||
throws UsernameHashNotAvailableException {
|
||||
|
||||
// Always fetch a fresh, non-cached copy of the account before making modifications
|
||||
final Account account = accounts.getByAccountIdentifier(accountIdentifier)
|
||||
.orElseThrow(() -> new IllegalArgumentException("Account not found: " + accountIdentifier));
|
||||
|
||||
if (account.getUsernameHash().filter(
|
||||
oldHash -> requestedUsernameHashes.stream().anyMatch(hash -> Arrays.equals(oldHash, hash)))
|
||||
.isPresent()) {
|
||||
@@ -844,7 +861,6 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
redisDelete(account);
|
||||
|
||||
final Account updatedAccount = updateWithRetries(
|
||||
account,
|
||||
_ -> true,
|
||||
a -> reservedUsernameHash.set(
|
||||
checkAndReserveNextUsernameHash(a, new ArrayDeque<>(requestedUsernameHashes))),
|
||||
@@ -873,9 +889,9 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
}
|
||||
}
|
||||
|
||||
/// Set a username hash previously reserved with {@link #reserveUsernameHash(Account, List)}
|
||||
/// Set a username hash previously reserved with {@link #reserveUsernameHash(UUID, List)}
|
||||
///
|
||||
/// @param account the account to update
|
||||
/// @param accountIdentifier identifier of the account to update
|
||||
/// @param reservedUsernameHash the previously reserved username hash
|
||||
/// @param encryptedUsername the encrypted form of the previously reserved username for the username link
|
||||
///
|
||||
@@ -884,9 +900,13 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
/// @throws UsernameHashNotAvailableException if the reserved username hash has been taken (because the reservation
|
||||
/// expired)
|
||||
/// @throws UsernameReservationNotFoundException if `reservedUsernameHash` was not reserved for the account
|
||||
public Account confirmReservedUsernameHash(final Account account, final byte[] reservedUsernameHash, @Nullable final byte[] encryptedUsername)
|
||||
public Account confirmReservedUsernameHash(final UUID accountIdentifier, final byte[] reservedUsernameHash, @Nullable final byte[] encryptedUsername)
|
||||
throws UsernameReservationNotFoundException, UsernameHashNotAvailableException {
|
||||
|
||||
// Always fetch a fresh, non-cached copy of the account before making modifications
|
||||
final Account account = accounts.getByAccountIdentifier(accountIdentifier)
|
||||
.orElseThrow(() -> new IllegalArgumentException("Account not found: " + accountIdentifier));
|
||||
|
||||
if (account.getUsernameHash().map(currentUsernameHash -> Arrays.equals(currentUsernameHash, reservedUsernameHash)).orElse(false)) {
|
||||
// the client likely already succeeded and is retrying
|
||||
return account;
|
||||
@@ -900,7 +920,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
|
||||
redisDelete(account);
|
||||
|
||||
final Account updatedAccount = updateWithRetries(account,
|
||||
final Account updatedAccount = updateWithRetries(
|
||||
_ -> true,
|
||||
a -> accounts.confirmUsernameHash(a, reservedUsernameHash, encryptedUsername),
|
||||
() -> accounts.getByAccountIdentifier(account.getUuid()).orElseThrow(),
|
||||
@@ -911,13 +931,10 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
return updatedAccount;
|
||||
}
|
||||
|
||||
public Account clearUsernameHash(final Account account) {
|
||||
redisDelete(account);
|
||||
|
||||
final Account updatedAccount = updateWithRetries(account,
|
||||
_ -> true,
|
||||
public Account clearUsernameHash(final UUID accountIdentifier) {
|
||||
final Account updatedAccount = updateWithRetries(_ -> true,
|
||||
accounts::clearUsernameHash,
|
||||
() -> accounts.getByAccountIdentifier(account.getUuid()).orElseThrow(),
|
||||
() -> accounts.getByAccountIdentifier(accountIdentifier).orElseThrow(),
|
||||
AccountChangeValidator.USERNAME_CHANGE_VALIDATOR);
|
||||
|
||||
redisDelete(updatedAccount);
|
||||
@@ -925,8 +942,15 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
return updatedAccount;
|
||||
}
|
||||
|
||||
public Account update(Account account, Consumer<Account> updater) {
|
||||
return update(account, a -> {
|
||||
public Account update(final Account account, final Consumer<Account> updater) {
|
||||
final Account updatedAccount = update(account.getIdentifier(IdentityType.ACI), updater);
|
||||
account.markStale();
|
||||
|
||||
return updatedAccount;
|
||||
}
|
||||
|
||||
public Account update(final UUID accountIdentifier, final Consumer<Account> updater) {
|
||||
return update(accountIdentifier, a -> {
|
||||
updater.accept(a);
|
||||
// assume that all updaters passed to the public method actually modify the account
|
||||
return true;
|
||||
@@ -934,11 +958,11 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
}
|
||||
|
||||
/**
|
||||
* Specialized version of {@link #updateDevice(Account, byte, Consumer)} that minimizes potentially contentious and
|
||||
* Specialized version of {@link #updateDevice(UUID, byte, Consumer)} that minimizes potentially contentious and
|
||||
* redundant updates of {@code device.lastSeen}
|
||||
*/
|
||||
public Account updateDeviceLastSeen(Account account, Device device, final long lastSeen) {
|
||||
return update(account, a -> {
|
||||
public Account updateDeviceLastSeen(UUID accountIdentifier, Device device, final long lastSeen) {
|
||||
return update(accountIdentifier, a -> {
|
||||
|
||||
final Optional<Device> maybeDevice = a.getDevice(device.getId());
|
||||
|
||||
@@ -956,21 +980,16 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
}
|
||||
|
||||
/**
|
||||
* @param account account to update
|
||||
* @param accountIdentifier identifier of account to update
|
||||
* @param updater must return {@code true} if the account was actually updated
|
||||
*/
|
||||
private Account update(Account account, Function<Account, Boolean> updater) {
|
||||
private Account update(UUID accountIdentifier, Function<Account, Boolean> updater) {
|
||||
|
||||
return updateTimer.record(() -> {
|
||||
|
||||
redisDelete(account);
|
||||
|
||||
final UUID uuid = account.getUuid();
|
||||
|
||||
final Account updatedAccount = updateWithRetries(account,
|
||||
updater,
|
||||
final Account updatedAccount = updateWithRetries(updater,
|
||||
accounts::update,
|
||||
() -> accounts.getByAccountIdentifier(uuid).orElseThrow(),
|
||||
() -> accounts.getByAccountIdentifier(accountIdentifier).orElseThrow(),
|
||||
AccountChangeValidator.GENERAL_CHANGE_VALIDATOR);
|
||||
|
||||
redisSet(updatedAccount);
|
||||
@@ -979,49 +998,38 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
});
|
||||
}
|
||||
|
||||
private <E extends Exception> Account updateWithRetries(Account account,
|
||||
final Function<Account, Boolean> updater,
|
||||
private <E extends Exception> Account updateWithRetries(final Function<Account, Boolean> updater,
|
||||
final ThrowingConsumer<Account, E> persister,
|
||||
final Supplier<Account> retriever,
|
||||
final AccountChangeValidator changeValidator) throws E {
|
||||
|
||||
Account originalAccount = AccountUtil.cloneAccountAsNotStale(account);
|
||||
|
||||
if (!updater.apply(account)) {
|
||||
return account;
|
||||
}
|
||||
|
||||
final int maxTries = 10;
|
||||
int tries = 0;
|
||||
|
||||
while (tries < maxTries) {
|
||||
|
||||
try {
|
||||
persister.accept(account);
|
||||
|
||||
final Account updatedAccount = AccountUtil.cloneAccountAsNotStale(account);
|
||||
account.markStale();
|
||||
|
||||
changeValidator.validateChange(originalAccount, updatedAccount);
|
||||
|
||||
return updatedAccount;
|
||||
} catch (final ContestedOptimisticLockException e) {
|
||||
tries++;
|
||||
|
||||
account = retriever.get();
|
||||
originalAccount = AccountUtil.cloneAccountAsNotStale(account);
|
||||
final Account account = retriever.get();
|
||||
final Account originalAccount = AccountUtil.cloneAccountAsNotStale(account);
|
||||
|
||||
if (!updater.apply(account)) {
|
||||
return account;
|
||||
}
|
||||
|
||||
persister.accept(account);
|
||||
|
||||
changeValidator.validateChange(originalAccount, account);
|
||||
|
||||
return account;
|
||||
} catch (final ContestedOptimisticLockException e) {
|
||||
tries++;
|
||||
}
|
||||
}
|
||||
|
||||
throw new OptimisticLockRetryLimitExceededException();
|
||||
}
|
||||
|
||||
public Account updateDevice(Account account, byte deviceId, Consumer<Device> deviceUpdater) {
|
||||
return update(account, a -> {
|
||||
public Account updateDevice(final UUID accountIdentifier, byte deviceId, Consumer<Device> deviceUpdater) {
|
||||
return update(accountIdentifier, a -> {
|
||||
a.getDevice(deviceId).ifPresent(deviceUpdater);
|
||||
// assume that all updaters passed to the public method actually modify the device
|
||||
return true;
|
||||
@@ -1106,9 +1114,19 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
return accounts.getAll(segments, scheduler);
|
||||
}
|
||||
|
||||
public void delete(final Account account, final DeletionReason deletionReason) {
|
||||
public void delete(final UUID accountIdentifier, final DeletionReason deletionReason) {
|
||||
final Timer.Sample sample = Timer.start();
|
||||
|
||||
final Optional<Account> maybeAccount = accounts.getByAccountIdentifier(accountIdentifier);
|
||||
|
||||
if (maybeAccount.isEmpty()) {
|
||||
// In most cases, failing to find an account would be an error, but in this case, it's probably a sign that we've
|
||||
// already succeeded in deleting the account and this is a spurious retry.
|
||||
return;
|
||||
}
|
||||
|
||||
final Account account = maybeAccount.get();
|
||||
|
||||
try {
|
||||
accountLockManager.withLock(Set.of(account.getPhoneNumberIdentifier()), () -> {
|
||||
delete(account);
|
||||
@@ -1328,21 +1346,6 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
getAccountEntityKey(account.getUuid())))));
|
||||
}
|
||||
|
||||
private CompletableFuture<Void> redisDeleteAsync(final Account account) {
|
||||
final Timer.Sample sample = Timer.start();
|
||||
|
||||
final String[] keysToDelete = new String[]{
|
||||
getAccountMapKey(account.getPhoneNumberIdentifier().toString()),
|
||||
getAccountEntityKey(account.getUuid())
|
||||
};
|
||||
|
||||
return ResilienceUtil.getGeneralRedisRetry(RETRY_NAME).executeCompletionStage(retryExecutor,
|
||||
() -> cacheCluster.withCluster(connection -> connection.async().del(keysToDelete))
|
||||
.thenRun(Util.NOOP))
|
||||
.toCompletableFuture()
|
||||
.whenComplete((_, _) -> sample.stop(redisDeleteTimer));
|
||||
}
|
||||
|
||||
public CompletableFuture<Optional<DeviceInfo>> waitForNewLinkedDevice(
|
||||
final UUID accountIdentifier,
|
||||
final Device linkingDevice,
|
||||
|
||||
+1
-1
@@ -80,7 +80,7 @@ public class ChangeNumberManager {
|
||||
}
|
||||
|
||||
final Account updatedAccount = accountsManager.changeNumber(
|
||||
account, number, pniIdentityKey, deviceSignedPreKeys, devicePqLastResortPreKeys, pniRegistrationIds);
|
||||
account.getIdentifier(IdentityType.ACI), number, pniIdentityKey, deviceSignedPreKeys, devicePqLastResortPreKeys, pniRegistrationIds);
|
||||
|
||||
try {
|
||||
// Now that we've actually updated the account, populate the "updated PNI" field on all envelopes
|
||||
|
||||
+1
-1
@@ -311,7 +311,7 @@ public class MessagePersister implements Managed {
|
||||
} else {
|
||||
logger.warn("Failed to persist queue {}::{} due to overfull queue; will unlink device", accountUuid, deviceId);
|
||||
|
||||
return Mono.fromRunnable(() -> accountsManager.removeDevice(account, deviceId))
|
||||
return Mono.fromRunnable(() -> accountsManager.removeDevice(accountUuid, deviceId))
|
||||
.subscribeOn(persistQueueScheduler)
|
||||
.then(Mono.empty());
|
||||
}
|
||||
|
||||
+2
-1
@@ -13,6 +13,7 @@ import net.sourceforge.argparse4j.inf.Subparser;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager.DeletionReason;
|
||||
@@ -51,7 +52,7 @@ public class DeleteUserCommand extends AbstractCommandWithDependencies {
|
||||
Optional<Account> account = accountsManager.getByE164(user);
|
||||
|
||||
if (account.isPresent()) {
|
||||
accountsManager.delete(account.get(), DeletionReason.ADMIN_DELETED);
|
||||
accountsManager.delete(account.get().getIdentifier(IdentityType.ACI), DeletionReason.ADMIN_DELETED);
|
||||
logger.warn("Removed " + account.get().getNumber());
|
||||
} else {
|
||||
logger.warn("Account not found");
|
||||
|
||||
+2
-1
@@ -16,6 +16,7 @@ import java.time.Instant;
|
||||
import net.sourceforge.argparse4j.inf.Subparser;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import reactor.core.publisher.Mono;
|
||||
@@ -67,7 +68,7 @@ public class RemoveExpiredAccountsCommand extends AbstractSinglePassCrawlAccount
|
||||
.flatMap(expiredAccount -> {
|
||||
final Mono<Void> deleteAccountMono = isDryRun
|
||||
? Mono.empty()
|
||||
: Mono.fromRunnable(() -> getCommandDependencies().accountsManager().delete(expiredAccount, AccountsManager.DeletionReason.EXPIRED))
|
||||
: Mono.fromRunnable(() -> getCommandDependencies().accountsManager().delete(expiredAccount.getIdentifier(IdentityType.ACI), AccountsManager.DeletionReason.EXPIRED))
|
||||
.subscribeOn(Schedulers.boundedElastic())
|
||||
.then();
|
||||
|
||||
|
||||
+2
-1
@@ -21,6 +21,7 @@ import java.util.stream.Collectors;
|
||||
import net.sourceforge.argparse4j.inf.Subparser;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import reactor.core.publisher.Flux;
|
||||
@@ -130,7 +131,7 @@ public class RemoveExpiredLinkedDevicesCommand extends AbstractSinglePassCrawlAc
|
||||
|
||||
return Flux.fromIterable(expiredDevices)
|
||||
.flatMap(deviceId ->
|
||||
Mono.fromRunnable(() -> getCommandDependencies().accountsManager().removeDevice(account, deviceId))
|
||||
Mono.fromRunnable(() -> getCommandDependencies().accountsManager().removeDevice(account.getIdentifier(IdentityType.ACI), deviceId))
|
||||
.retryWhen(Retry.backoff(maxRetries, Duration.ofSeconds(1))
|
||||
.doAfterRetry(ignored -> retryCounter.increment())
|
||||
.onRetryExhaustedThrow((spec, rs) -> rs.failure()))
|
||||
|
||||
+2
-1
@@ -20,6 +20,7 @@ import java.util.concurrent.atomic.AtomicLong;
|
||||
import net.sourceforge.argparse4j.inf.Subparser;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import reactor.core.publisher.Flux;
|
||||
@@ -85,7 +86,7 @@ public class RemoveExpiredUsernameHoldsCommand extends AbstractSinglePassCrawlAc
|
||||
final int holdsToRemove = removeExpired(holds);
|
||||
final Mono<Void> purgeMono = isDryRun || holdsToRemove == 0
|
||||
? Mono.empty()
|
||||
: Mono.fromRunnable(() -> accountManager.update(account, a -> a.setUsernameHolds(holds)))
|
||||
: Mono.fromRunnable(() -> accountManager.update(account.getIdentifier(IdentityType.ACI), a -> a.setUsernameHolds(holds)))
|
||||
.subscribeOn(Schedulers.boundedElastic())
|
||||
.then();
|
||||
Metrics.counter(INSPECTED_ACCOUNTS_COUNTER_NAME,
|
||||
|
||||
+2
-1
@@ -12,6 +12,7 @@ import java.util.UUID;
|
||||
import net.sourceforge.argparse4j.inf.Namespace;
|
||||
import net.sourceforge.argparse4j.inf.Subparser;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
|
||||
@@ -61,7 +62,7 @@ public class SetUserDiscoverabilityCommand extends AbstractCommandWithDependenci
|
||||
|
||||
maybeAccount.ifPresentOrElse(account -> {
|
||||
final boolean initiallyDiscoverable = account.isDiscoverableByPhoneNumber();
|
||||
accountsManager.update(account, a -> a.setDiscoverableByPhoneNumber(namespace.getBoolean("discoverable")));
|
||||
accountsManager.update(account.getIdentifier(IdentityType.ACI), a -> a.setDiscoverableByPhoneNumber(namespace.getBoolean("discoverable")));
|
||||
|
||||
System.out.format("Set discoverability flag for %s to %s (was previously %s)\n",
|
||||
namespace.getString("user"),
|
||||
|
||||
+2
-4
@@ -13,6 +13,7 @@ import net.sourceforge.argparse4j.impl.Arguments;
|
||||
import net.sourceforge.argparse4j.inf.Namespace;
|
||||
import net.sourceforge.argparse4j.inf.Subparser;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
|
||||
@@ -51,9 +52,6 @@ public class UnlinkDeviceCommand extends AbstractCommandWithDependencies {
|
||||
final UUID aci = UUID.fromString(namespace.getString("uuid").trim());
|
||||
final List<Byte> deviceIds = namespace.getList("deviceIds");
|
||||
|
||||
Account account = deps.accountsManager().getByAccountIdentifier(aci)
|
||||
.orElseThrow(() -> new IllegalArgumentException("account id " + aci + " does not exist"));
|
||||
|
||||
if (deviceIds.contains(Device.PRIMARY_ID)) {
|
||||
throw new IllegalArgumentException("cannot delete primary device");
|
||||
}
|
||||
@@ -61,7 +59,7 @@ public class UnlinkDeviceCommand extends AbstractCommandWithDependencies {
|
||||
for (byte deviceId : deviceIds) {
|
||||
/** see {@link org.whispersystems.textsecuregcm.controllers.DeviceController#removeDevice} */
|
||||
System.out.format("Removing device %s::%d\n", aci, deviceId);
|
||||
deps.accountsManager().removeDevice(account, deviceId);
|
||||
deps.accountsManager().removeDevice(aci, deviceId);
|
||||
}
|
||||
}
|
||||
}
|
||||
+2
-3
@@ -93,7 +93,7 @@ public class UnlinkDevicesWithIdlePrimaryCommand extends AbstractSinglePassCrawl
|
||||
.filter(account -> isPrimaryDeviceIdle(account, currentTime, idleDurationThreshold))
|
||||
.flatMap(accountWithIdlePrimaryDevice -> Flux.fromIterable(accountWithIdlePrimaryDevice.getDevices())
|
||||
.filter(device -> !device.isPrimary())
|
||||
.map(linkedDevice -> Tuples.of(accountWithIdlePrimaryDevice, linkedDevice.getId())))
|
||||
.map(linkedDevice -> Tuples.of(accountWithIdlePrimaryDevice.getIdentifier(IdentityType.ACI), linkedDevice.getId())))
|
||||
.flatMap(accountAndLinkedDeviceId -> {
|
||||
final Mono<Account> unlinkDeviceMono = isDryRun
|
||||
? Mono.empty()
|
||||
@@ -104,8 +104,7 @@ public class UnlinkDevicesWithIdlePrimaryCommand extends AbstractSinglePassCrawl
|
||||
.doOnSuccess(ignored -> unlinkDeviceCounter.increment())
|
||||
.retryWhen(Retry.backoff(3, Duration.ofSeconds(1)).maxBackoff(Duration.ofSeconds(4)))
|
||||
.onErrorResume(throwable -> {
|
||||
logger.warn("Failed to unlink device to delete account {}:{}", accountAndLinkedDeviceId.getT1().getIdentifier(
|
||||
IdentityType.ACI), accountAndLinkedDeviceId.getT2(), throwable);
|
||||
logger.warn("Failed to unlink device to delete account {}:{}", accountAndLinkedDeviceId.getT1(), accountAndLinkedDeviceId.getT2(), throwable);
|
||||
|
||||
return Mono.empty();
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user