Compare commits

...
33 Commits
Author SHA1 Message Date
Chris Eager 6eed458ceb Use server timestamp for delivery duration metrics 2024-07-18 12:22:59 -05:00
Jon Chambers 54fb0a6acb Add a general job scheduler 2024-07-18 13:22:31 -04:00
Jon Chambers 5147d9cb6d Mark old attachment endpoints as @Deprecated 2024-07-17 15:01:44 -04:00
Jon Chambers 37369929f3 Retire PushLatencyManager 2024-07-17 15:01:23 -04:00
Jon Chambers 4f10014902 Add an "is primary" dimension to message latency measurements 2024-07-17 15:01:08 -04:00
Ravi Khadiwala 0ef3e00ba7 Use non-legacy rate limit error in BackupAuthManager 2024-07-11 16:39:11 -05:00
Chris Eager 2408590430 Update GitHub Actions 2024-07-11 16:38:15 -05:00
Chris Eager b7f4fe4d73 Update various dependencies 2024-07-11 16:38:15 -05:00
Chris Eager b811492acd Update maven-wrapper.properties 2024-07-11 16:38:15 -05:00
Chris Eager a63e0e0390 Remove unused RateLimiters 2024-07-11 16:37:55 -05:00
Jon Chambers 5e8a0b2cfa Introduce a utility class for finding reasonable times to send push notifications 2024-07-11 17:36:54 -04:00
Chris Eager eac75aad03 Add distribution of multi-recipient message recipient counts 2024-07-09 15:04:47 -05:00
Chris Eager b05fbc2102 Add metric for group send token adoption 2024-07-09 15:04:12 -05:00
Jon Chambers 6d166fdfc5 Return futures from "send push notification" operations 2024-07-08 15:36:17 -04:00
Ravi Khadiwala 2e36673702 Add warn log if changeNumber messages fail 2024-07-08 15:28:08 -04:00
ravi-signal 0c81ffe8b7 Count unregistered APNS tokens with a recent update 2024-07-08 15:27:48 -04:00
Jon Chambers 02b9ceb4c7 Discard APNs tokens if the APNs server reports that the token is expired 2024-07-08 15:27:23 -04:00
Chris Eager 775889c0b6 Remove deprecated PUT /v2/keys/signed endpoint 2024-07-08 15:26:26 -04:00
Chris Eager 98f2cdaf5a Reduce DynamoDB test client API timeouts 2024-07-08 15:26:11 -04:00
Jon Chambers ff5cc3cb4f Avoid duplicate metric registry configuration in commands 2024-07-08 15:25:16 -04:00
Jon Chambers ebecb1caec Throw an exception if metric registries are configured more than once 2024-07-08 15:25:16 -04:00
Jon Chambers 73e0aea85c Retire Device#hasMessageDeliveryChannel() 2024-06-26 14:46:39 -04:00
Ameya Lokare 1a09f5807b Update to the latest version of the spam filter 2024-06-26 11:45:58 -07:00
Ameya Lokare ec009a2bba Pass AccountAndAuthenticatedDeviceHolder to spam filter 2024-06-26 11:32:49 -07:00
Jon Chambers f52c40a492 Update to the latest version of the spam filter 2024-06-25 11:57:37 -04:00
Jon Chambers 1959c059ed Rename AuthEnablementRefreshRequirementProvider to LinkedDeviceRefreshRequirementProvider 2024-06-25 11:57:25 -04:00
Jon Chambers 2d1610b075 Stop monitoring device "enabled" state changes from auth enablement refresh requirement provider
Device enabled states no longer affect anything at an authentication level
2024-06-25 11:57:25 -04:00
Jon Chambers 2f76738b50 Expire APNs tokens if they haven't been updated since the expiration timestamp 2024-06-25 11:53:23 -04:00
Jon Chambers 1cf174a613 Include "token invalidation timestamp" in push notification responses 2024-06-25 11:53:23 -04:00
Jon Chambers d743454d07 Store updated APNs tokens unconditionally 2024-06-25 11:53:23 -04:00
Jon Chambers 1cd16eaa08 Delete FCM tokens immediately if FCM reports that they're no longer active 2024-06-25 11:53:23 -04:00
Jon Chambers 90e622b307 Require that message bundles include all linked devices 2024-06-25 11:51:09 -04:00
Jon Chambers cb5cd64c05 Gracefully handle NotPushRegisteredException 2024-06-25 11:23:16 -04:00
79 changed files with 1244 additions and 1486 deletions

No files matched your search

+2 -2
View File
@@ -11,8 +11,8 @@ jobs:
contents: write
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1
- uses: actions/setup-java@9704b39bf258b59bc04b50fa2dd55e9ed76b47a8 # v4.1.0
- uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7
- uses: actions/setup-java@99b8673ff64fbf99d8d325f52d9a5bdedb8483e9 # v4.2.1
with:
distribution: 'temurin'
java-version: '21'
+3 -3
View File
@@ -13,13 +13,13 @@ jobs:
id-token: write
contents: read
steps:
- uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1
- uses: actions/setup-java@9704b39bf258b59bc04b50fa2dd55e9ed76b47a8 # v4.1.0
- uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7
- uses: actions/setup-java@99b8673ff64fbf99d8d325f52d9a5bdedb8483e9 # v4.2.1
with:
distribution: 'temurin'
java-version: '21'
cache: 'maven'
- uses: aws-actions/configure-aws-credentials@e3dd6a429d7300a6a4c196c26e071d42e0343502 #v4.0.2
- uses: aws-actions/configure-aws-credentials@5579c002bb4778aa43395ef1df492868a9a1c83f # v4.0.2
name: Configure AWS credentials from Test account
with:
role-to-assume: ${{ vars.AWS_ROLE }}
+2 -2
View File
@@ -11,9 +11,9 @@ jobs:
container: ubuntu:22.04
steps:
- uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1
- uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7
- name: Set up JDK 21
uses: actions/setup-java@9704b39bf258b59bc04b50fa2dd55e9ed76b47a8 # v4.1.0
uses: actions/setup-java@99b8673ff64fbf99d8d325f52d9a5bdedb8483e9 # v4.2.1
with:
distribution: 'temurin'
java-version: 21
BIN
View File
Binary file not shown.
+4 -4
View File
@@ -14,7 +14,7 @@
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.4/apache-maven-3.9.4-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar
distributionSha256Sum=e896b60329a71b719d77bb4388b251a50aebcd73c62f69d510c858ce360afe0f
wrapperSha256Sum=e63a53cfb9c4d291ebe3c2b0edacb7622bbc480326beaa5a0456e412f52f066a
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.8/apache-maven-3.9.8-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.3.2/maven-wrapper-3.3.2.jar
distributionSha256Sum=8351955a9acf2f83c136c4eee0f6db894ab6265fdbe0a94b32a380307dbaa3e1
wrapperSha256Sum=3d8f20ce6103913be8b52aef6d994e0c54705fb527324ceb9b835b338739c7a8
+4 -4
View File
@@ -50,24 +50,24 @@
<!-- several libraries (AWS, Google Cloud) use Apache http components transitively, and we need to align them -->
<httpcore.version>4.4.16</httpcore.version>
<httpclient.version>4.5.14</httpclient.version>
<jackson.version>2.17.1</jackson.version>
<jackson.version>2.17.2</jackson.version>
<jaxb.version>2.3.1</jaxb.version>
<junit-pioneer.version>2.2.0</junit-pioneer.version>
<jsr305.version>3.0.2</jsr305.version>
<kotlin.version>1.9.24</kotlin.version>
<kotlinx-serialization.version>1.5.1</kotlinx-serialization.version>
<lettuce.version>6.3.2.RELEASE</lettuce.version>
<libphonenumber.version>8.13.39</libphonenumber.version>
<libphonenumber.version>8.13.40</libphonenumber.version>
<logstash.logback.version>7.3</logstash.logback.version>
<log4j-bom.version>2.23.1</log4j-bom.version>
<luajava.version>3.4.0</luajava.version>
<micrometer.version>1.13.1</micrometer.version>
<micrometer.version>1.13.2</micrometer.version>
<netty.version>4.1.111.Final</netty.version>
<opentest4j.version>1.3.0</opentest4j.version>
<protobuf.version>3.25.2</protobuf.version> <!-- should be kept in sync with the value from Google libraries-bom -->
<pushy.version>0.15.4</pushy.version>
<reactive.grpc.version>1.2.4</reactive.grpc.version>
<reactor-bom.version>2023.0.7</reactor-bom.version> <!-- 3.6.x, see https://github.com/reactor/reactor#bom-versioning-scheme -->
<reactor-bom.version>2023.0.8</reactor-bom.version> <!-- 3.6.x, see https://github.com/reactor/reactor#bom-versioning-scheme -->
<resilience4j.version>2.2.0</resilience4j.version>
<semver4j.version>3.1.0</semver4j.version>
<slf4j.version>2.0.13</slf4j.version>
+3
View File
@@ -126,6 +126,9 @@ dynamoDbTables:
tableName: Example_RemoteConfig
reportMessage:
tableName: Example_ReportMessage
scheduledJobs:
tableName: Example_ScheduledJobs
expiration: P7D
subscriptions:
tableName: Example_Subscriptions
clientPublicKeys:
+8
View File
@@ -393,6 +393,14 @@
<artifactId>libphonenumber</artifactId>
</dependency>
<!-- Provides tools for mapping phone numbers to time zones, which is helpful for scheduling push notifications
during waking hours -->
<dependency>
<groupId>com.googlecode.libphonenumber</groupId>
<artifactId>geocoder</artifactId>
<version>2.234</version>
</dependency>
<dependency>
<groupId>net.sourceforge.argparse4j</groupId>
<artifactId>argparse4j</artifactId>
@@ -189,7 +189,6 @@ import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
import org.whispersystems.textsecuregcm.push.FcmSender;
import org.whispersystems.textsecuregcm.push.MessageSender;
import org.whispersystems.textsecuregcm.push.ProvisioningManager;
import org.whispersystems.textsecuregcm.push.PushLatencyManager;
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
import org.whispersystems.textsecuregcm.push.ReceiptSender;
import org.whispersystems.textsecuregcm.redis.ConnectionEventLogger;
@@ -253,7 +252,6 @@ import org.whispersystems.textsecuregcm.workers.CertificateCommand;
import org.whispersystems.textsecuregcm.workers.CheckDynamicConfigurationCommand;
import org.whispersystems.textsecuregcm.workers.DeleteUserCommand;
import org.whispersystems.textsecuregcm.workers.MessagePersisterServiceCommand;
import org.whispersystems.textsecuregcm.workers.ProcessPushNotificationFeedbackCommand;
import org.whispersystems.textsecuregcm.workers.RemoveExpiredAccountsCommand;
import org.whispersystems.textsecuregcm.workers.RemoveExpiredBackupsCommand;
import org.whispersystems.textsecuregcm.workers.RemoveExpiredLinkedDevicesCommand;
@@ -314,7 +312,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
bootstrap.addCommand(new RemoveExpiredUsernameHoldsCommand(Clock.systemUTC()));
bootstrap.addCommand(new RemoveExpiredBackupsCommand(Clock.systemUTC()));
bootstrap.addCommand(new BackupMetricsCommand(Clock.systemUTC()));
bootstrap.addCommand(new ProcessPushNotificationFeedbackCommand(Clock.systemUTC()));
bootstrap.addCommand(new RemoveExpiredLinkedDevicesCommand());
}
@@ -598,7 +595,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
recurringJobExecutor,
config.getClientReleaseConfiguration().refreshInterval(),
Clock.systemUTC());
PushLatencyManager pushLatencyManager = new PushLatencyManager(metricsCluster, clientReleaseManager);
ReportMessageManager reportMessageManager = new ReportMessageManager(reportMessageDynamoDb, rateLimitersCluster,
config.getReportMessageConfiguration().getCounterTtl());
MessagesManager messagesManager = new MessagesManager(messagesDynamoDb, messagesCache, reportMessageManager,
@@ -618,8 +614,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
FcmSender fcmSender = new FcmSender(fcmSenderExecutor, config.getFcmConfiguration().credentials().value());
ApnPushNotificationScheduler apnPushNotificationScheduler = new ApnPushNotificationScheduler(pushSchedulerCluster,
apnSender, accountsManager, 0);
PushNotificationManager pushNotificationManager = new PushNotificationManager(accountsManager, apnSender, fcmSender,
apnPushNotificationScheduler, pushLatencyManager);
PushNotificationManager pushNotificationManager =
new PushNotificationManager(accountsManager, apnSender, fcmSender, apnPushNotificationScheduler);
RateLimiters rateLimiters = RateLimiters.createAndValidate(config.getLimitsConfiguration(),
dynamicConfigurationManager, rateLimitersCluster);
ProvisioningManager provisioningManager = new ProvisioningManager(
@@ -651,9 +647,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
final AccountAuthenticator accountAuthenticator = new AccountAuthenticator(accountsManager);
final MessageSender messageSender = new MessageSender(clientPresenceManager, messagesManager,
pushNotificationManager,
pushLatencyManager);
final MessageSender messageSender =
new MessageSender(clientPresenceManager, messagesManager, pushNotificationManager);
final ReceiptSender receiptSender = new ReceiptSender(accountsManager, messageSender, receiptSenderExecutor);
final TurnTokenGenerator turnTokenGenerator = new TurnTokenGenerator(dynamicConfigurationManager,
config.getTurnConfiguration().secret().value());
@@ -16,5 +16,5 @@ import java.lang.annotation.Target;
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ChangesDeviceEnabledState {
public @interface ChangesLinkedDevices {
}
@@ -11,26 +11,23 @@ import org.whispersystems.textsecuregcm.storage.Device;
import javax.ws.rs.core.SecurityContext;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
class ContainerRequestUtil {
private static Map<Byte, Boolean> buildDevicesEnabledMap(final Account account) {
return account.getDevices().stream().collect(Collectors.toMap(Device::getId, Device::hasMessageDeliveryChannel));
}
/**
* A read-only subset of the authenticated Account object, to enforce that filter-based consumers do not perform
* account modifying operations.
*/
record AccountInfo(UUID accountId, String e164, Map<Byte, Boolean> devicesEnabled) {
record AccountInfo(UUID accountId, String e164, Set<Byte> deviceIds) {
static AccountInfo fromAccount(final Account account) {
return new AccountInfo(
account.getUuid(),
account.getNumber(),
buildDevicesEnabledMap(account));
account.getDevices().stream().map(Device::getId).collect(Collectors.toSet()));
}
}
@@ -8,7 +8,6 @@ package org.whispersystems.textsecuregcm.auth;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
@@ -18,75 +17,73 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.util.Pair;
/**
* This {@link WebsocketRefreshRequirementProvider} observes intra-request changes in
* {@link Device#hasMessageDeliveryChannel()}.
* <p>
* If a change in any associated {@link Device#hasMessageDeliveryChannel()} is observed, then any active WebSocket
* connections for the account must be closed in order for clients to get a refreshed {@link io.dropwizard.auth.Auth}
* object with a current device list.
* This {@link WebsocketRefreshRequirementProvider} observes intra-request changes in devices linked to an
* {@link Account} and triggers a WebSocket refresh if that set changes. If a change in linked devices is observed, then
* any active WebSocket connections for the account must be closed in order for clients to get a refreshed
* {@link io.dropwizard.auth.Auth} object with a current device list.
*
* @see AuthenticatedAccount
*/
public class AuthEnablementRefreshRequirementProvider implements WebsocketRefreshRequirementProvider {
public class LinkedDeviceRefreshRequirementProvider implements WebsocketRefreshRequirementProvider {
private final AccountsManager accountsManager;
private static final Logger logger = LoggerFactory.getLogger(AuthEnablementRefreshRequirementProvider.class);
private static final Logger logger = LoggerFactory.getLogger(LinkedDeviceRefreshRequirementProvider.class);
private static final String ACCOUNT_UUID = AuthEnablementRefreshRequirementProvider.class.getName() + ".accountUuid";
private static final String DEVICES_ENABLED = AuthEnablementRefreshRequirementProvider.class.getName() + ".devicesEnabled";
private static final String ACCOUNT_UUID = LinkedDeviceRefreshRequirementProvider.class.getName() + ".accountUuid";
private static final String LINKED_DEVICE_IDS = LinkedDeviceRefreshRequirementProvider.class.getName() + ".deviceIds";
public AuthEnablementRefreshRequirementProvider(final AccountsManager accountsManager) {
public LinkedDeviceRefreshRequirementProvider(final AccountsManager accountsManager) {
this.accountsManager = accountsManager;
}
@Override
public void handleRequestFiltered(final RequestEvent requestEvent) {
if (requestEvent.getUriInfo().getMatchedResourceMethod().getInvocable().getHandlingMethod().getAnnotation(ChangesDeviceEnabledState.class) != null) {
if (requestEvent.getUriInfo().getMatchedResourceMethod().getInvocable().getHandlingMethod().getAnnotation(
ChangesLinkedDevices.class) != null) {
// The authenticated principal, if any, will be available after filters have run. Now that the account is known,
// capture a snapshot of the account's devices before carrying out the request’s business logic.
ContainerRequestUtil.getAuthenticatedAccount(requestEvent.getContainerRequest()).ifPresent(account ->
setAccount(requestEvent.getContainerRequest(), account));
// capture a snapshot of the account's linked devices before carrying out the request’s business logic.
ContainerRequestUtil.getAuthenticatedAccount(requestEvent.getContainerRequest())
.ifPresent(account -> setAccount(requestEvent.getContainerRequest(), account));
}
}
public static void setAccount(final ContainerRequest containerRequest, final Account account) {
setAccount(containerRequest, ContainerRequestUtil.AccountInfo.fromAccount(account));
}
private static void setAccount(final ContainerRequest containerRequest, final ContainerRequestUtil.AccountInfo info) {
containerRequest.setProperty(ACCOUNT_UUID, info.accountId());
containerRequest.setProperty(DEVICES_ENABLED, info.devicesEnabled());
containerRequest.setProperty(LINKED_DEVICE_IDS, info.deviceIds());
}
@Override
public List<Pair<UUID, Byte>> handleRequestFinished(final RequestEvent requestEvent) {
// Now that the request is finished, check whether `hasMessageDeliveryChannel` changed for any of the devices. If
// the value did change or if a devices was added or removed, all devices must disconnect and reauthenticate.
if (requestEvent.getContainerRequest().getProperty(DEVICES_ENABLED) != null) {
// Now that the request is finished, check whether the set of linked devices has changed. If the value did change or
// if a devices was added or removed, all devices must disconnect and reauthenticate.
if (requestEvent.getContainerRequest().getProperty(LINKED_DEVICE_IDS) != null) {
@SuppressWarnings("unchecked") final Map<Byte, Boolean> initialDevicesEnabled =
(Map<Byte, Boolean>) requestEvent.getContainerRequest().getProperty(DEVICES_ENABLED);
@SuppressWarnings("unchecked") final Set<Byte> initialLinkedDeviceIds =
(Set<Byte>) requestEvent.getContainerRequest().getProperty(LINKED_DEVICE_IDS);
return accountsManager.getByAccountIdentifier((UUID) requestEvent.getContainerRequest().getProperty(ACCOUNT_UUID))
.map(ContainerRequestUtil.AccountInfo::fromAccount)
.map(account -> {
.map(accountInfo -> {
final Set<Byte> deviceIdsToDisplace;
final Map<Byte, Boolean> currentDevicesEnabled = account.devicesEnabled();
final Set<Byte> currentLinkedDeviceIds = accountInfo.deviceIds();
if (!initialDevicesEnabled.equals(currentDevicesEnabled)) {
deviceIdsToDisplace = new HashSet<>(initialDevicesEnabled.keySet());
deviceIdsToDisplace.addAll(currentDevicesEnabled.keySet());
if (!initialLinkedDeviceIds.equals(currentLinkedDeviceIds)) {
deviceIdsToDisplace = new HashSet<>(initialLinkedDeviceIds);
deviceIdsToDisplace.addAll(currentLinkedDeviceIds);
} else {
deviceIdsToDisplace = Collections.emptySet();
}
return deviceIdsToDisplace.stream()
.map(deviceId -> new Pair<>(account.accountId(), deviceId))
.map(deviceId -> new Pair<>(accountInfo.accountId(), deviceId))
.collect(Collectors.toList());
}).orElseGet(() -> {
logger.error("Request had account, but it is no longer present");
@@ -23,7 +23,7 @@ public class WebsocketRefreshApplicationEventListener implements ApplicationEven
final ClientPresenceManager clientPresenceManager) {
this.websocketRefreshRequestEventListener = new WebsocketRefreshRequestEventListener(clientPresenceManager,
new AuthEnablementRefreshRequirementProvider(accountsManager),
new LinkedDeviceRefreshRequirementProvider(accountsManager),
new PhoneNumberChangeRefreshRequirementProvider(accountsManager));
}
@@ -15,6 +15,7 @@ import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.VerificationFailedException;
@@ -28,12 +29,12 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.limits.RateLimiter;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.RedeemedReceiptsManager;
import org.whispersystems.textsecuregcm.util.Util;
import javax.annotation.Nullable;
/**
* Issues ZK backup auth credentials for authenticated accounts
@@ -101,8 +102,9 @@ public class BackupAuthManager {
return CompletableFuture.completedFuture(null);
}
return rateLimiters.forDescriptor(RateLimiters.For.SET_BACKUP_ID)
.validateAsync(account.getUuid())
return RateLimiter.adaptLegacyException(rateLimiters
.forDescriptor(RateLimiters.For.SET_BACKUP_ID)
.validateAsync(account.getUuid()))
.thenCompose(ignored -> this.accountsManager
.updateAsync(account, acc -> acc.setBackupCredentialRequest(serializedRequest))
.thenRun(Util.NOOP))
@@ -67,6 +67,7 @@ public class DynamoDbTables {
private final TableWithExpiration registrationRecovery;
private final Table remoteConfig;
private final Table reportMessage;
private final TableWithExpiration scheduledJobs;
private final Table subscriptions;
private final Table verificationSessions;
@@ -91,6 +92,7 @@ public class DynamoDbTables {
@JsonProperty("registrationRecovery") final TableWithExpiration registrationRecovery,
@JsonProperty("remoteConfig") final Table remoteConfig,
@JsonProperty("reportMessage") final Table reportMessage,
@JsonProperty("scheduledJobs") final TableWithExpiration scheduledJobs,
@JsonProperty("subscriptions") final Table subscriptions,
@JsonProperty("verificationSessions") final Table verificationSessions) {
@@ -114,6 +116,7 @@ public class DynamoDbTables {
this.registrationRecovery = registrationRecovery;
this.remoteConfig = remoteConfig;
this.reportMessage = reportMessage;
this.scheduledJobs = scheduledJobs;
this.subscriptions = subscriptions;
this.verificationSessions = verificationSessions;
}
@@ -238,6 +241,12 @@ public class DynamoDbTables {
return reportMessage;
}
@NotNull
@Valid
public TableWithExpiration getScheduledJobs() {
return scheduledJobs;
}
@NotNull
@Valid
public Table getSubscriptions() {
@@ -34,7 +34,6 @@ import javax.ws.rs.core.Response.Status;
import org.signal.libsignal.usernames.BaseUsernameException;
import org.whispersystems.textsecuregcm.auth.AccountAndAuthenticatedDeviceHolder;
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
import org.whispersystems.textsecuregcm.auth.ChangesDeviceEnabledState;
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
import org.whispersystems.textsecuregcm.auth.TurnToken;
import org.whispersystems.textsecuregcm.auth.TurnTokenGenerator;
@@ -109,7 +108,6 @@ public class AccountController {
@Path("/gcm/")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@ChangesDeviceEnabledState
public void setGcmRegistrationId(@Mutable @Auth AuthenticatedAccount auth,
@NotNull @Valid GcmRegistrationId registrationId) {
@@ -130,7 +128,6 @@ public class AccountController {
@DELETE
@Path("/gcm/")
@ChangesDeviceEnabledState
public void deleteGcmRegistrationId(@Mutable @Auth AuthenticatedAccount auth) {
Account account = auth.getAccount();
Device device = auth.getAuthenticatedDevice();
@@ -146,19 +143,14 @@ public class AccountController {
@Path("/apn/")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@ChangesDeviceEnabledState
public void setApnRegistrationId(@Mutable @Auth AuthenticatedAccount auth,
@NotNull @Valid ApnRegistrationId registrationId) {
final Account account = auth.getAccount();
final Device device = auth.getAuthenticatedDevice();
if (Objects.equals(device.getApnId(), registrationId.apnRegistrationId()) &&
Objects.equals(device.getVoipApnId(), registrationId.voipRegistrationId())) {
return;
}
// Unlike FCM tokens, we need current "last updated" timestamps for APNs tokens and so update device records
// unconditionally
accounts.updateDevice(account, device.getId(), d -> {
d.setApnId(registrationId.apnRegistrationId());
d.setVoipApnId(registrationId.voipRegistrationId());
@@ -169,7 +161,6 @@ public class AccountController {
@DELETE
@Path("/apn/")
@ChangesDeviceEnabledState
public void deleteApnRegistrationId(@Mutable @Auth AuthenticatedAccount auth) {
Account account = auth.getAccount();
Device device = auth.getAuthenticatedDevice();
@@ -214,7 +205,6 @@ public class AccountController {
@Path("/attributes/")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@ChangesDeviceEnabledState
public void setAccountAttributes(
@Mutable @Auth AuthenticatedAccount auth,
@HeaderParam(HeaderUtils.X_SIGNAL_AGENT) String userAgent,
@@ -31,6 +31,8 @@ import org.whispersystems.textsecuregcm.util.Conversions;
import org.whispersystems.textsecuregcm.util.Pair;
import org.whispersystems.websocket.auth.ReadOnly;
// To be removed when Android 7.12 reaches saturation, likely some time toward the end of October 2024
@Deprecated(forRemoval = true)
@Path("/v2/attachments")
@Tag(name = "Attachments")
public class AttachmentControllerV2 {
@@ -25,6 +25,8 @@ import org.whispersystems.textsecuregcm.limits.RateLimiter;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.websocket.auth.ReadOnly;
// To be removed when Desktop 7.17 reaches saturation, likely some time toward the end of October 2024
@Deprecated(forRemoval = true)
@Path("/v3/attachments")
@Tag(name = "Attachments")
public class AttachmentControllerV3 {
@@ -46,10 +46,10 @@ import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.glassfish.jersey.server.ContainerRequest;
import org.whispersystems.textsecuregcm.auth.AuthEnablementRefreshRequirementProvider;
import org.whispersystems.textsecuregcm.auth.LinkedDeviceRefreshRequirementProvider;
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
import org.whispersystems.textsecuregcm.auth.BasicAuthorizationHeader;
import org.whispersystems.textsecuregcm.auth.ChangesDeviceEnabledState;
import org.whispersystems.textsecuregcm.auth.ChangesLinkedDevices;
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
import org.whispersystems.textsecuregcm.entities.DeviceActivationRequest;
import org.whispersystems.textsecuregcm.entities.DeviceInfo;
@@ -132,7 +132,7 @@ public class DeviceController {
@DELETE
@Produces(MediaType.APPLICATION_JSON)
@Path("/{device_id}")
@ChangesDeviceEnabledState
@ChangesLinkedDevices
public void removeDevice(@Mutable @Auth AuthenticatedAccount auth, @PathParam("device_id") byte deviceId) {
if (auth.getAuthenticatedDevice().getId() != Device.PRIMARY_ID) {
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
@@ -176,7 +176,7 @@ public class DeviceController {
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Path("/link")
@ChangesDeviceEnabledState
@ChangesLinkedDevices
@Operation(summary = "Link a device to an account",
description = """
Links a device to an account identified by a given phone number.
@@ -221,7 +221,7 @@ public class DeviceController {
// Normally, the "do we need to refresh somebody's websockets" listener can do this on its own. In this case,
// we're not using the conventional authentication system, and so we need to give it a hint so it knows who the
// active user is and what their device states look like.
AuthEnablementRefreshRequirementProvider.setAccount(containerRequest, account);
LinkedDeviceRefreshRequirementProvider.setAccount(containerRequest, account);
final int maxDeviceLimit = maxDeviceConfiguration.getOrDefault(account.getNumber(), MAX_DEVICES);
@@ -409,35 +409,6 @@ public class KeysController {
return new PreKeyResponse(identityKey, responseItems);
}
@PUT
@Path("/signed")
@Consumes(MediaType.APPLICATION_JSON)
@Operation(summary = "Upload a new signed prekey",
description = """
Upload a new signed elliptic-curve prekey for this device. Deprecated; use PUT /v2/keys instead.
""")
@ApiResponse(responseCode = "200", description = "Indicates that new prekey was successfully stored.")
@ApiResponse(responseCode = "401", description = "Account authentication check failed.")
@ApiResponse(responseCode = "422", description = "Invalid request format.")
// TODO Remove this endpoint on or after 2024-05-24
@Deprecated(forRemoval = true)
public CompletableFuture<Response> setSignedKey(
@ReadOnly @Auth final AuthenticatedAccount auth,
@HeaderParam(HttpHeaders.USER_AGENT) @Nullable final String userAgent,
@Valid final ECSignedPreKey signedPreKey,
@QueryParam("identity") @DefaultValue("aci") final IdentityType identityType) {
final UUID identifier = auth.getAccount().getIdentifier(identityType);
final byte deviceId = auth.getAuthenticatedDevice().getId();
if (!PreKeySignatureValidator.validatePreKeySignatures(auth.getAccount().getIdentityKey(identityType), List.of(signedPreKey), userAgent, "set-signed-pre-key")) {
throw new WebApplicationException("Invalid signature", 422);
}
return keysManager.storeEcSignedPreKeys(identifier, deviceId, signedPreKey)
.thenApply(Util.ASYNC_EMPTY_RESPONSE);
}
private List<Device> parseDeviceId(String deviceId, Account account) {
if (deviceId.equals("*")) {
return account.getDevices();
@@ -112,7 +112,6 @@ import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.providers.MultiRecipientMessageProvider;
import org.whispersystems.textsecuregcm.push.MessageSender;
import org.whispersystems.textsecuregcm.push.NotPushRegisteredException;
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
import org.whispersystems.textsecuregcm.push.ReceiptSender;
import org.whispersystems.textsecuregcm.spam.ReportSpamTokenProvider;
@@ -180,7 +179,6 @@ public class MessageController {
private static final String RATE_LIMITED_MESSAGE_COUNTER_NAME = name(MessageController.class, "rateLimitedMessage");
private static final String REJECT_INVALID_ENVELOPE_TYPE = name(MessageController.class, "rejectInvalidEnvelopeType");
private static final String UNEXPECTED_MISSING_USER_COUNTER_NAME = name(MessageController.class, "unexpectedMissingDestinationForMultiRecipientMessage");
private static final Timer SEND_MESSAGE_LATENCY_TIMER =
Timer.builder(MetricsUtil.name(MessageController.class, "sendMessageLatency"))
.publishPercentileHistogram(true)
@@ -188,6 +186,7 @@ public class MessageController {
private static final String EPHEMERAL_TAG_NAME = "ephemeral";
private static final String SENDER_TYPE_TAG_NAME = "senderType";
private static final String AUTH_TYPE_TAG_NAME = "authType";
private static final String SENDER_COUNTRY_TAG_NAME = "senderCountry";
private static final String RATE_LIMIT_REASON_TAG_NAME = "rateLimitReason";
private static final String ENVELOPE_TYPE_TAG_NAME = "envelopeType";
@@ -197,6 +196,10 @@ public class MessageController {
private static final String SENDER_TYPE_UNIDENTIFIED = "unidentified";
private static final String SENDER_TYPE_SELF = "self";
private static final String AUTH_TYPE_IDENTIFIED = "identified";
private static final String AUTH_TYPE_ACCESS_KEY = "accessKey";
private static final String AUTH_TYPE_GROUP_SEND_TOKEN = "groupSendToken";
@VisibleForTesting
static final long MAX_MESSAGE_SIZE = DataSize.kibibytes(256).toBytes();
@@ -329,7 +332,7 @@ public class MessageController {
final Optional<byte[]> spamReportToken = switch (senderType) {
case SENDER_TYPE_IDENTIFIED ->
reportSpamTokenProvider.makeReportSpamToken(context, source.get().getAccount(), destination);
reportSpamTokenProvider.makeReportSpamToken(context, source.get(), destination);
default -> Optional.empty();
};
@@ -408,9 +411,19 @@ public class MessageController {
IncomingMessage::destinationRegistrationId,
destination.get().getPhoneNumberIdentifier().equals(destinationIdentifier.uuid()));
final String authType;
if (SENDER_TYPE_IDENTIFIED.equals(senderType)) {
authType = AUTH_TYPE_IDENTIFIED;
} else if (groupSendToken != null) {
authType = AUTH_TYPE_GROUP_SEND_TOKEN;
} else {
authType = AUTH_TYPE_ACCESS_KEY;
}
final List<Tag> tags = List.of(UserAgentTagUtil.getPlatformTag(userAgent),
Tag.of(EPHEMERAL_TAG_NAME, String.valueOf(messages.online())),
Tag.of(SENDER_TYPE_TAG_NAME, senderType),
Tag.of(AUTH_TYPE_TAG_NAME, authType),
Tag.of(IDENTITY_TYPE_TAG_NAME, destinationIdentifier.identityType().name()));
for (IncomingMessage incomingMessage : messages.messages()) {
@@ -434,8 +447,6 @@ public class MessageController {
}
return Response.ok(new SendMessageResponse(needsSync)).build();
} catch (NoSuchUserException e) {
throw new WebApplicationException(Response.status(404).build());
} catch (MismatchedDevicesException e) {
throw new WebApplicationException(Response.status(409)
.type(MediaType.APPLICATION_JSON_TYPE)
@@ -627,8 +638,6 @@ public class MessageController {
.build();
}
List<ServiceIdentifier> uuids404 = Collections.synchronizedList(new ArrayList<>());
try {
CompletableFuture.allOf(
recipients.values().stream()
@@ -637,6 +646,8 @@ public class MessageController {
UserAgentTagUtil.getPlatformTag(userAgent),
Tag.of(EPHEMERAL_TAG_NAME, String.valueOf(online)),
Tag.of(SENDER_TYPE_TAG_NAME, SENDER_TYPE_UNIDENTIFIED),
Tag.of(AUTH_TYPE_TAG_NAME,
groupSendToken != null ? AUTH_TYPE_GROUP_SEND_TOKEN : AUTH_TYPE_ACCESS_KEY),
Tag.of(IDENTITY_TYPE_TAG_NAME, recipientData.serviceIdentifier().identityType().name())));
validateContentLength(multiRecipientMessage.messageSizeForRecipient(recipientData.recipient()), true, userAgent);
@@ -649,19 +660,12 @@ public class MessageController {
// we asserted this must exist in validateCompleteDeviceList
final Device destinationDevice = destinationAccount.getDevice(deviceId).orElseThrow();
try {
sentMessageCounter.increment();
sendCommonPayloadMessage(
destinationAccount, destinationDevice, recipientData.serviceIdentifier(), timestamp,
online,
isStory, isUrgent, payload);
} catch (NoSuchUserException e) {
// this should never happen, because we already asserted the device is present and enabled
Metrics.counter(
UNEXPECTED_MISSING_USER_COUNTER_NAME,
Tags.of("isPrimary", String.valueOf(destinationDevice.isPrimary()))).increment();
uuids404.add(recipientData.serviceIdentifier());
}
sentMessageCounter.increment();
sendCommonPayloadMessage(
destinationAccount, destinationDevice, recipientData.serviceIdentifier(), timestamp,
online,
isStory, isUrgent, payload);
},
multiRecipientMessageExecutor));
})
@@ -677,7 +681,7 @@ public class MessageController {
logger.error("partial failure while delivering multi-recipient messages", e.getCause());
return Response.serverError().entity("failure during delivery").build();
}
return Response.ok(new SendMultiRecipientMessageResponse(uuids404)).build();
return Response.ok(new SendMultiRecipientMessageResponse(Collections.emptyList())).build();
}
private void checkGroupSendToken(
@@ -738,7 +742,11 @@ public class MessageController {
.map(OutgoingMessageEntity::fromEnvelope)
.peek(outgoingMessageEntity -> {
messageMetrics.measureAccountOutgoingMessageUuidMismatches(auth.getAccount(), outgoingMessageEntity);
messageMetrics.measureOutgoingMessageLatency(outgoingMessageEntity.serverTimestamp(), "rest", userAgent, clientReleaseManager);
messageMetrics.measureOutgoingMessageLatency(outgoingMessageEntity.serverTimestamp(),
"rest",
auth.getAuthenticatedDevice().isPrimary(),
userAgent,
clientReleaseManager);
})
.collect(Collectors.toList()),
messagesAndHasMore.second());
@@ -776,7 +784,7 @@ public class MessageController {
.thenAccept(maybeDeletedMessage -> {
maybeDeletedMessage.ifPresent(deletedMessage -> {
WebSocketConnection.recordMessageDeliveryDuration(deletedMessage.getTimestamp(),
WebSocketConnection.recordMessageDeliveryDuration(deletedMessage.getServerTimestamp(),
auth.getAuthenticatedDevice());
if (deletedMessage.hasSourceUuid() && deletedMessage.getType() != Type.SERVER_DELIVERY_RECEIPT) {
@@ -858,32 +866,27 @@ public class MessageController {
boolean urgent,
IncomingMessage incomingMessage,
String userAgentString,
Optional<byte[]> spamReportToken)
throws NoSuchUserException {
Optional<byte[]> spamReportToken) {
final Envelope envelope;
try {
final Envelope envelope;
try {
Account sourceAccount = source.map(AuthenticatedAccount::getAccount).orElse(null);
Byte sourceDeviceId = source.map(account -> account.getAuthenticatedDevice().getId()).orElse(null);
envelope = incomingMessage.toEnvelope(
destinationIdentifier,
sourceAccount,
sourceDeviceId,
timestamp == 0 ? System.currentTimeMillis() : timestamp,
story,
urgent,
spamReportToken.orElse(null));
} catch (final IllegalArgumentException e) {
logger.warn("Received bad envelope type {} from {}", incomingMessage.type(), userAgentString);
throw new BadRequestException(e);
}
messageSender.sendMessage(destinationAccount, destinationDevice, envelope, online);
} catch (NotPushRegisteredException e) {
if (destinationDevice.isPrimary()) throw new NoSuchUserException(e);
else logger.debug("Not registered", e);
final Account sourceAccount = source.map(AuthenticatedAccount::getAccount).orElse(null);
final Byte sourceDeviceId = source.map(account -> account.getAuthenticatedDevice().getId()).orElse(null);
envelope = incomingMessage.toEnvelope(
destinationIdentifier,
sourceAccount,
sourceDeviceId,
timestamp == 0 ? System.currentTimeMillis() : timestamp,
story,
urgent,
spamReportToken.orElse(null));
} catch (final IllegalArgumentException e) {
logger.warn("Received bad envelope type {} from {}", incomingMessage.type(), userAgentString);
throw new BadRequestException(e);
}
messageSender.sendMessage(destinationAccount, destinationDevice, envelope, online);
}
private void sendCommonPayloadMessage(Account destinationAccount,
@@ -893,28 +896,21 @@ public class MessageController {
boolean online,
boolean story,
boolean urgent,
byte[] payload) throws NoSuchUserException {
try {
Envelope.Builder messageBuilder = Envelope.newBuilder();
long serverTimestamp = System.currentTimeMillis();
byte[] payload) {
messageBuilder
.setType(Type.UNIDENTIFIED_SENDER)
.setTimestamp(timestamp == 0 ? serverTimestamp : timestamp)
.setServerTimestamp(serverTimestamp)
.setContent(ByteString.copyFrom(payload))
.setStory(story)
.setUrgent(urgent)
.setDestinationUuid(serviceIdentifier.toServiceIdentifierString());
final Envelope.Builder messageBuilder = Envelope.newBuilder();
final long serverTimestamp = System.currentTimeMillis();
messageSender.sendMessage(destinationAccount, destinationDevice, messageBuilder.build(), online);
} catch (NotPushRegisteredException e) {
if (destinationDevice.isPrimary()) {
throw new NoSuchUserException(e);
} else {
logger.debug("Not registered", e);
}
}
messageBuilder
.setType(Type.UNIDENTIFIED_SENDER)
.setTimestamp(timestamp == 0 ? serverTimestamp : timestamp)
.setServerTimestamp(serverTimestamp)
.setContent(ByteString.copyFrom(payload))
.setStory(story)
.setUrgent(urgent)
.setDestinationUuid(serviceIdentifier.toServiceIdentifierString());
messageSender.sendMessage(destinationAccount, destinationDevice, messageBuilder.build(), online);
}
private void checkMessageRateLimit(AuthenticatedAccount source, Account destination, String userAgent)
@@ -1,18 +0,0 @@
/*
* Copyright 2013-2020 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.controllers;
import java.util.UUID;
public class NoSuchUserException extends Exception {
public NoSuchUserException(final UUID uuid) {
super(uuid.toString());
}
public NoSuchUserException(Exception e) {
super(e);
}
}
@@ -18,8 +18,6 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
public enum For implements RateLimiterDescriptor {
BACKUP_AUTH_CHECK("backupAuthCheck", false, new RateLimiterConfig(100, Duration.ofMinutes(15))),
SMS_DESTINATION("smsDestination", false, new RateLimiterConfig(2, Duration.ofSeconds(30))),
VERIFY("verify", false, new RateLimiterConfig(6, Duration.ofSeconds(30))),
PIN("pin", false, new RateLimiterConfig(10, Duration.ofDays(1))),
ATTACHMENT("attachmentCreate", false, new RateLimiterConfig(50, Duration.ofMillis(1200))),
BACKUP_ATTACHMENT("backupAttachmentCreate", true, new RateLimiterConfig(10_000, Duration.ofSeconds(1))),
@@ -118,14 +116,6 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
return forDescriptor(For.ATTACHMENT);
}
public RateLimiter getSmsDestinationLimiter() {
return forDescriptor(For.SMS_DESTINATION);
}
public RateLimiter getVerifyLimiter() {
return forDescriptor(For.VERIFY);
}
public RateLimiter getPinLimiter() {
return forDescriptor(For.PIN);
}
@@ -70,12 +70,14 @@ public final class MessageMetrics {
public void measureOutgoingMessageLatency(final long serverTimestamp,
final String channel,
final boolean isPrimaryDevice,
final String userAgent,
final ClientReleaseManager clientReleaseManager) {
final List<Tag> tags = new ArrayList<>(3);
final List<Tag> tags = new ArrayList<>(4);
tags.add(UserAgentTagUtil.getPlatformTag(userAgent));
tags.add(Tag.of("channel", channel));
tags.add(Tag.of("isPrimary", String.valueOf(isPrimaryDevice)));
UserAgentTagUtil.getClientVersionTag(userAgent, clientReleaseManager).ifPresent(tags::add);
@@ -22,7 +22,6 @@ import io.micrometer.statsd.StatsdMeterRegistry;
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
import org.whispersystems.textsecuregcm.WhisperServerVersion;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.push.PushLatencyManager;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.util.Constants;
@@ -30,6 +29,8 @@ public class MetricsUtil {
public static final String PREFIX = "chat";
private static volatile boolean registeredMetrics = false;
/**
* Returns a dot-separated ('.') name for the given class and name parts
*/
@@ -48,6 +49,13 @@ public class MetricsUtil {
public static void configureRegistries(final WhisperServerConfiguration config, final Environment environment,
DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
if (registeredMetrics) {
throw new IllegalStateException("Metric registries configured more than once");
}
registeredMetrics = true;
SharedMetricRegistries.add(Constants.METRICS_NAME, environment.metrics());
{
@@ -100,7 +108,6 @@ public class MetricsUtil {
return MeterFilter.super.map(id);
}
})
.meterFilter(MeterFilter.denyNameStartsWith(PushLatencyManager.TIMER_NAME + ".percentile"))
.meterFilter(MeterFilter.denyNameStartsWith(MessageMetrics.DELIVERY_LATENCY_TIMER_NAME + ".percentile"));
}
@@ -5,7 +5,11 @@
package org.whispersystems.textsecuregcm.providers;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import io.dropwizard.util.DataSizeUnit;
import io.micrometer.core.instrument.DistributionSummary;
import io.micrometer.core.instrument.Metrics;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
@@ -18,9 +22,9 @@ import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.NoContentException;
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.Provider;
import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage;
import org.signal.libsignal.protocol.InvalidMessageException;
import org.signal.libsignal.protocol.InvalidVersionException;
import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage;
@Provider
@Consumes(MultiRecipientMessageProvider.MEDIA_TYPE)
@@ -30,6 +34,11 @@ public class MultiRecipientMessageProvider implements MessageBodyReader<SealedSe
public static final int MAX_RECIPIENT_COUNT = 5000;
public static final int MAX_MESSAGE_SIZE = Math.toIntExact(32 + DataSizeUnit.KIBIBYTES.toBytes(256));
private static final DistributionSummary RECIPIENT_COUNT_DISTRIBUTION = DistributionSummary
.builder(name(MultiRecipientMessageProvider.class, "recipients"))
.publishPercentileHistogram(true)
.register(Metrics.globalRegistry);
@Override
public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
return MEDIA_TYPE.equals(mediaType.toString()) && SealedSenderMultiRecipientMessage.class.isAssignableFrom(type);
@@ -46,6 +55,8 @@ public class MultiRecipientMessageProvider implements MessageBodyReader<SealedSe
try {
final SealedSenderMultiRecipientMessage message = SealedSenderMultiRecipientMessage.parse(fullMessage);
RECIPIENT_COUNT_DISTRIBUTION.record(message.getRecipients().keySet().size());
if (message.getRecipients().values().stream().anyMatch(r -> message.messageSizeForRecipient(r) > MAX_MESSAGE_SIZE)) {
throw new BadRequestException("message payload too large");
}
@@ -23,6 +23,7 @@ import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.Duration;
import java.time.Instant;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import org.whispersystems.textsecuregcm.configuration.ApnConfiguration;
@@ -156,20 +157,21 @@ public class APNSender implements Managed, PushNotificationSender {
})
.thenApplyAsync(response -> {
final boolean accepted;
final String rejectionReason;
final Optional<String> rejectionReason;
final boolean unregistered;
if (response.isAccepted()) {
accepted = true;
rejectionReason = null;
rejectionReason = Optional.empty();
unregistered = false;
} else {
accepted = false;
rejectionReason = response.getRejectionReason().orElse("unknown");
unregistered = ("Unregistered".equals(rejectionReason) || "BadDeviceToken".equals(rejectionReason));
rejectionReason = response.getRejectionReason();
unregistered = response.getRejectionReason().map(reason -> "Unregistered".equals(reason) || "BadDeviceToken".equals(reason) || "ExpiredToken".equals(reason))
.orElse(false);
}
return new SendPushNotificationResult(accepted, rejectionReason, unregistered);
return new SendPushNotificationResult(accepted, rejectionReason, unregistered, response.getTokenInvalidationTimestamp());
}, executor);
}
@@ -23,6 +23,7 @@ import io.micrometer.core.instrument.Timer;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadFactory;
@@ -96,7 +97,7 @@ public class FcmSender implements PushNotificationSender {
return GoogleApiUtil.toCompletableFuture(firebaseMessagingClient.sendAsync(builder.build()), executor)
.whenComplete((ignored, throwable) -> sample.stop(SEND_NOTIFICATION_TIMER))
.thenApply(ignored -> new SendPushNotificationResult(true, null, false))
.thenApply(ignored -> new SendPushNotificationResult(true, Optional.empty(), false, Optional.empty()))
.exceptionally(throwable -> {
if (ExceptionUtils.unwrap(throwable) instanceof final FirebaseMessagingException firebaseMessagingException) {
final String errorCode;
@@ -111,7 +112,7 @@ public class FcmSender implements PushNotificationSender {
final boolean unregistered =
firebaseMessagingException.getMessagingErrorCode() == MessagingErrorCode.UNREGISTERED;
return new SendPushNotificationResult(false, errorCode, unregistered);
return new SendPushNotificationResult(false, Optional.of(errorCode), unregistered, Optional.empty());
} else {
throw ExceptionUtils.wrap(throwable);
}
@@ -8,8 +8,6 @@ import static com.codahale.metrics.MetricRegistry.name;
import static org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
import io.micrometer.core.instrument.Metrics;
import org.apache.commons.lang3.StringUtils;
import org.whispersystems.textsecuregcm.redis.RedisOperation;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.MessagesManager;
@@ -32,7 +30,6 @@ public class MessageSender {
private final ClientPresenceManager clientPresenceManager;
private final MessagesManager messagesManager;
private final PushNotificationManager pushNotificationManager;
private final PushLatencyManager pushLatencyManager;
private static final String SEND_COUNTER_NAME = name(MessageSender.class, "sendMessage");
private static final String CHANNEL_TAG_NAME = "channel";
@@ -42,18 +39,16 @@ public class MessageSender {
private static final String STORY_TAG_NAME = "story";
private static final String SEALED_SENDER_TAG_NAME = "sealedSender";
public MessageSender(ClientPresenceManager clientPresenceManager,
MessagesManager messagesManager,
PushNotificationManager pushNotificationManager,
PushLatencyManager pushLatencyManager) {
public MessageSender(final ClientPresenceManager clientPresenceManager,
final MessagesManager messagesManager,
final PushNotificationManager pushNotificationManager) {
this.clientPresenceManager = clientPresenceManager;
this.messagesManager = messagesManager;
this.pushNotificationManager = pushNotificationManager;
this.pushLatencyManager = pushLatencyManager;
}
public void sendMessage(final Account account, final Device device, final Envelope message, final boolean online)
throws NotPushRegisteredException {
public void sendMessage(final Account account, final Device device, final Envelope message, final boolean online) {
final String channel;
@@ -64,7 +59,7 @@ public class MessageSender {
} else if (device.getFetchesMessages()) {
channel = "websocket";
} else {
throw new AssertionError();
channel = "none";
}
final boolean clientPresent;
@@ -86,13 +81,7 @@ public class MessageSender {
if (!clientPresent) {
try {
pushNotificationManager.sendNewMessageNotification(account, device.getId(), message.getUrgent());
final boolean useVoip = StringUtils.isNotBlank(device.getVoipApnId());
RedisOperation.unchecked(() -> pushLatencyManager.recordPushSent(account.getUuid(), device.getId(), useVoip, message.getUrgent()));
} catch (final NotPushRegisteredException e) {
if (!device.getFetchesMessages()) {
throw e;
}
} catch (final NotPushRegisteredException ignored) {
}
}
}
@@ -1,147 +0,0 @@
/*
* Copyright 2013 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.push;
import com.codahale.metrics.MetricRegistry;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.annotations.VisibleForTesting;
import io.lettuce.core.SetArgs;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Timer;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
import org.whispersystems.textsecuregcm.util.SystemMapper;
/**
* Measures and records the latency between sending a push notification to a device and that device draining its queue
* of messages.
* <p/>
* When the server sends a push notification to a device, the push latency manager creates a Redis key/value pair
* mapping the current timestamp to the given device if such a mapping doesn't already exist. When a client connects and
* clears its message queue, the push latency manager gets and clears the time of the initial push notification to that
* device and records the time elapsed since the push notification timestamp as a latency observation.
*/
public class PushLatencyManager {
private final FaultTolerantRedisCluster redisCluster;
private final ClientReleaseManager clientReleaseManager;
private final Clock clock;
public static final String TIMER_NAME = MetricRegistry.name(PushLatencyManager.class, "latency");
private static final int TTL = (int) Duration.ofDays(1).toSeconds();
private static final Logger log = LoggerFactory.getLogger(PushLatencyManager.class);
@VisibleForTesting
enum PushType {
STANDARD,
VOIP
}
record PushRecord(Instant timestamp, PushType pushType, Optional<Boolean> urgent) {
}
public PushLatencyManager(final FaultTolerantRedisCluster redisCluster,
final ClientReleaseManager clientReleaseManager) {
this(redisCluster, clientReleaseManager, Clock.systemUTC());
}
@VisibleForTesting
PushLatencyManager(final FaultTolerantRedisCluster redisCluster,
final ClientReleaseManager clientReleaseManager,
final Clock clock) {
this.redisCluster = redisCluster;
this.clientReleaseManager = clientReleaseManager;
this.clock = clock;
}
void recordPushSent(final UUID accountUuid, final byte deviceId, final boolean isVoip, final boolean isUrgent) {
try {
final String recordJson = SystemMapper.jsonMapper().writeValueAsString(
new PushRecord(Instant.now(clock), isVoip ? PushType.VOIP : PushType.STANDARD, Optional.of(isUrgent)));
redisCluster.useCluster(connection ->
connection.async().set(getFirstUnacknowledgedPushKey(accountUuid, deviceId),
recordJson,
SetArgs.Builder.nx().ex(TTL)));
} catch (final JsonProcessingException e) {
// This should never happen
log.error("Failed to write push latency record JSON", e);
}
}
void recordQueueRead(final UUID accountUuid, final byte deviceId, final String userAgentString) {
takePushRecord(accountUuid, deviceId).thenAccept(pushRecord -> {
if (pushRecord != null) {
final Duration latency = Duration.between(pushRecord.timestamp(), Instant.now());
final List<Tag> tags = new ArrayList<>(3);
tags.add(UserAgentTagUtil.getPlatformTag(userAgentString));
tags.add(Tag.of("pushType", pushRecord.pushType().name().toLowerCase()));
UserAgentTagUtil.getClientVersionTag(userAgentString, clientReleaseManager)
.ifPresent(tags::add);
pushRecord.urgent().ifPresent(urgent -> tags.add(Tag.of("urgent", String.valueOf(urgent))));
Timer.builder(TIMER_NAME)
.publishPercentileHistogram(true)
.tags(tags)
.register(Metrics.globalRegistry)
.record(latency);
}
});
}
@VisibleForTesting
CompletableFuture<PushRecord> takePushRecord(final UUID accountUuid, final byte deviceId) {
final String key = getFirstUnacknowledgedPushKey(accountUuid, deviceId);
return redisCluster.withCluster(connection -> {
final CompletableFuture<PushRecord> getFuture = connection.async().get(key).toCompletableFuture()
.thenApply(recordJson -> {
if (StringUtils.isNotEmpty(recordJson)) {
try {
return SystemMapper.jsonMapper().readValue(recordJson, PushRecord.class);
} catch (JsonProcessingException e) {
return null;
}
} else {
return null;
}
});
getFuture.whenComplete((record, cause) -> {
if (cause == null) {
connection.async().del(key);
}
});
return getFuture;
});
}
private static String getFirstUnacknowledgedPushKey(final UUID accountUuid, final byte deviceId) {
return "push_latency::v2::" + accountUuid.toString() + "::" + deviceId;
}
}
@@ -10,7 +10,9 @@ import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import com.google.common.annotations.VisibleForTesting;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tags;
import java.time.Instant;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.function.BiConsumer;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
@@ -20,7 +22,6 @@ import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.util.Pair;
import org.whispersystems.textsecuregcm.util.Util;
public class PushNotificationManager {
@@ -28,59 +29,59 @@ public class PushNotificationManager {
private final APNSender apnSender;
private final FcmSender fcmSender;
private final ApnPushNotificationScheduler apnPushNotificationScheduler;
private final PushLatencyManager pushLatencyManager;
private static final String SENT_NOTIFICATION_COUNTER_NAME = name(PushNotificationManager.class, "sentPushNotification");
private static final String FAILED_NOTIFICATION_COUNTER_NAME = name(PushNotificationManager.class, "failedPushNotification");
private static final String DEVICE_TOKEN_UNREGISTERED_COUNTER_NAME = name(PushNotificationManager.class, "deviceTokenUnregistered");
private static final Logger logger = LoggerFactory.getLogger(PushNotificationManager.class);
public PushNotificationManager(final AccountsManager accountsManager,
final APNSender apnSender,
final FcmSender fcmSender,
final ApnPushNotificationScheduler apnPushNotificationScheduler,
final PushLatencyManager pushLatencyManager) {
final ApnPushNotificationScheduler apnPushNotificationScheduler) {
this.accountsManager = accountsManager;
this.apnSender = apnSender;
this.fcmSender = fcmSender;
this.apnPushNotificationScheduler = apnPushNotificationScheduler;
this.pushLatencyManager = pushLatencyManager;
}
public void sendNewMessageNotification(final Account destination, final byte destinationDeviceId, final boolean urgent) throws NotPushRegisteredException {
public CompletableFuture<Optional<SendPushNotificationResult>> sendNewMessageNotification(final Account destination, final byte destinationDeviceId, final boolean urgent) throws NotPushRegisteredException {
final Device device = destination.getDevice(destinationDeviceId).orElseThrow(NotPushRegisteredException::new);
final Pair<String, PushNotification.TokenType> tokenAndType = getToken(device);
sendNotification(new PushNotification(tokenAndType.first(), tokenAndType.second(),
return sendNotification(new PushNotification(tokenAndType.first(), tokenAndType.second(),
PushNotification.NotificationType.NOTIFICATION, null, destination, device, urgent));
}
public void sendRegistrationChallengeNotification(final String deviceToken, final PushNotification.TokenType tokenType, final String challengeToken) {
sendNotification(new PushNotification(deviceToken, tokenType, PushNotification.NotificationType.CHALLENGE, challengeToken, null, null, true));
public CompletableFuture<SendPushNotificationResult> sendRegistrationChallengeNotification(final String deviceToken, final PushNotification.TokenType tokenType, final String challengeToken) {
return sendNotification(new PushNotification(deviceToken, tokenType, PushNotification.NotificationType.CHALLENGE, challengeToken, null, null, true))
.thenApply(maybeResponse -> maybeResponse.orElseThrow(() -> new AssertionError("Responses must be present for urgent notifications")));
}
public void sendRateLimitChallengeNotification(final Account destination, final String challengeToken)
public CompletableFuture<SendPushNotificationResult> sendRateLimitChallengeNotification(final Account destination, final String challengeToken)
throws NotPushRegisteredException {
final Device device = destination.getPrimaryDevice();
final Pair<String, PushNotification.TokenType> tokenAndType = getToken(device);
sendNotification(new PushNotification(tokenAndType.first(), tokenAndType.second(),
PushNotification.NotificationType.RATE_LIMIT_CHALLENGE, challengeToken, destination, device, true));
return sendNotification(new PushNotification(tokenAndType.first(), tokenAndType.second(),
PushNotification.NotificationType.RATE_LIMIT_CHALLENGE, challengeToken, destination, device, true))
.thenApply(maybeResponse -> maybeResponse.orElseThrow(() -> new AssertionError("Responses must be present for urgent notifications")));
}
public void sendAttemptLoginNotification(final Account destination, final String context) throws NotPushRegisteredException {
public CompletableFuture<SendPushNotificationResult> sendAttemptLoginNotification(final Account destination, final String context) throws NotPushRegisteredException {
final Device device = destination.getDevice(Device.PRIMARY_ID).orElseThrow(NotPushRegisteredException::new);
final Pair<String, PushNotification.TokenType> tokenAndType = getToken(device);
sendNotification(new PushNotification(tokenAndType.first(), tokenAndType.second(),
return sendNotification(new PushNotification(tokenAndType.first(), tokenAndType.second(),
PushNotification.NotificationType.ATTEMPT_LOGIN_NOTIFICATION_HIGH_PRIORITY,
context, destination, device, true));
context, destination, device, true))
.thenApply(maybeResponse -> maybeResponse.orElseThrow(() -> new AssertionError("Responses must be present for urgent notifications")));
}
public void handleMessagesRetrieved(final Account account, final Device device, final String userAgent) {
RedisOperation.unchecked(() -> pushLatencyManager.recordQueueRead(account.getUuid(), device.getId(), userAgent));
apnPushNotificationScheduler.cancelScheduledNotifications(account, device).whenComplete(logErrors());
}
@@ -102,59 +103,66 @@ public class PushNotificationManager {
}
@VisibleForTesting
void sendNotification(final PushNotification pushNotification) {
CompletableFuture<Optional<SendPushNotificationResult>> sendNotification(final PushNotification pushNotification) {
if (pushNotification.tokenType() == PushNotification.TokenType.APN && !pushNotification.urgent()) {
// APNs imposes a per-device limit on background push notifications; schedule a notification for some time in the
// future (possibly even now!) rather than sending a notification directly
apnPushNotificationScheduler
return apnPushNotificationScheduler
.scheduleBackgroundNotification(pushNotification.destination(), pushNotification.destinationDevice())
.whenComplete(logErrors());
} else {
final PushNotificationSender sender = switch (pushNotification.tokenType()) {
case FCM -> fcmSender;
case APN, APN_VOIP -> apnSender;
};
sender.sendNotification(pushNotification).whenComplete((result, throwable) -> {
if (throwable == null) {
Tags tags = Tags.of("tokenType", pushNotification.tokenType().name(),
"notificationType", pushNotification.notificationType().name(),
"urgent", String.valueOf(pushNotification.urgent()),
"accepted", String.valueOf(result.accepted()),
"unregistered", String.valueOf(result.unregistered()));
if (StringUtils.isNotBlank(result.errorCode())) {
tags = tags.and("errorCode", result.errorCode());
}
Metrics.counter(SENT_NOTIFICATION_COUNTER_NAME, tags).increment();
if (result.unregistered() && pushNotification.destination() != null
&& pushNotification.destinationDevice() != null) {
handleDeviceUnregistered(pushNotification.destination(), pushNotification.destinationDevice());
}
if (result.accepted() &&
pushNotification.tokenType() == PushNotification.TokenType.APN_VOIP &&
pushNotification.notificationType() == PushNotification.NotificationType.NOTIFICATION &&
pushNotification.destination() != null &&
pushNotification.destinationDevice() != null) {
apnPushNotificationScheduler.scheduleRecurringVoipNotification(
pushNotification.destination(),
pushNotification.destinationDevice())
.whenComplete(logErrors());
}
} else {
logger.debug("Failed to deliver {} push notification to {} ({})",
pushNotification.notificationType(), pushNotification.deviceToken(), pushNotification.tokenType(),
throwable);
Metrics.counter(FAILED_NOTIFICATION_COUNTER_NAME, "cause", throwable.getClass().getSimpleName()).increment();
}
});
.whenComplete(logErrors())
.thenApply(ignored -> Optional.<SendPushNotificationResult>empty())
.toCompletableFuture();
}
final PushNotificationSender sender = switch (pushNotification.tokenType()) {
case FCM -> fcmSender;
case APN, APN_VOIP -> apnSender;
};
return sender.sendNotification(pushNotification).whenComplete((result, throwable) -> {
if (throwable == null) {
Tags tags = Tags.of("tokenType", pushNotification.tokenType().name(),
"notificationType", pushNotification.notificationType().name(),
"urgent", String.valueOf(pushNotification.urgent()),
"accepted", String.valueOf(result.accepted()),
"unregistered", String.valueOf(result.unregistered()));
if (result.errorCode().isPresent()) {
tags = tags.and("errorCode", result.errorCode().get());
}
Metrics.counter(SENT_NOTIFICATION_COUNTER_NAME, tags).increment();
if (result.unregistered() && pushNotification.destination() != null
&& pushNotification.destinationDevice() != null) {
handleDeviceUnregistered(pushNotification.destination(),
pushNotification.destinationDevice(),
pushNotification.tokenType(),
result.errorCode(),
result.unregisteredTimestamp());
}
if (result.accepted() &&
pushNotification.tokenType() == PushNotification.TokenType.APN_VOIP &&
pushNotification.notificationType() == PushNotification.NotificationType.NOTIFICATION &&
pushNotification.destination() != null &&
pushNotification.destinationDevice() != null) {
apnPushNotificationScheduler.scheduleRecurringVoipNotification(
pushNotification.destination(),
pushNotification.destinationDevice())
.whenComplete(logErrors());
}
} else {
logger.debug("Failed to deliver {} push notification to {} ({})",
pushNotification.notificationType(), pushNotification.deviceToken(), pushNotification.tokenType(),
throwable);
Metrics.counter(FAILED_NOTIFICATION_COUNTER_NAME, "cause", throwable.getClass().getSimpleName()).increment();
}
})
.thenApply(Optional::of);
}
private static <T> BiConsumer<T, Throwable> logErrors() {
@@ -165,27 +173,60 @@ public class PushNotificationManager {
};
}
private void handleDeviceUnregistered(final Account account, final Device device) {
if (StringUtils.isNotBlank(device.getGcmId())) {
if (device.getUninstalledFeedbackTimestamp() == 0) {
// Reread the account to avoid marking the caller's account as stale. The consumers of this class tend to
// promise not to modify accounts. There's no need to force the caller to be considered mutable just for
// updating an uninstalled feedback timestamp though.
final Optional<Account> rereadAccount = accountsManager.getByAccountIdentifier(account.getUuid());
if (rereadAccount.isEmpty()) {
// don't bother adding the uninstalled timestamp, the account is gone
return;
}
final Optional<Device> rereadDevice = rereadAccount.get().getDevice(device.getId());
if (rereadDevice.map(Device::getUninstalledFeedbackTimestamp).orElse(-1L) != 0) {
// don't bother adding the uninstalled timestamp, the device is gone or already updated
return;
}
accountsManager.updateDevice(rereadAccount.get(), device.getId(), d ->
d.setUninstalledFeedbackTimestamp(Util.todayInMillis()));
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
private void handleDeviceUnregistered(final Account account,
final Device device,
final PushNotification.TokenType tokenType,
final Optional<String> maybeErrorCode,
final Optional<Instant> maybeTokenInvalidationTimestamp) {
final boolean tokenExpired = maybeTokenInvalidationTimestamp.map(tokenInvalidationTimestamp ->
tokenInvalidationTimestamp.isAfter(Instant.ofEpochMilli(device.getPushTimestamp()))).orElse(true);
if (tokenExpired) {
if (tokenType == PushNotification.TokenType.APN || tokenType == PushNotification.TokenType.APN_VOIP) {
apnPushNotificationScheduler.cancelScheduledNotifications(account, device).whenComplete(logErrors());
}
} else {
apnPushNotificationScheduler.cancelScheduledNotifications(account, device).whenComplete(logErrors());
clearPushToken(account, device, tokenType);
}
Metrics.counter(DEVICE_TOKEN_UNREGISTERED_COUNTER_NAME,
"errorCode", maybeErrorCode.orElse("unknown"),
"isPrimary", String.valueOf(device.isPrimary()),
"hasUnregisteredTimestamp", String.valueOf(maybeTokenInvalidationTimestamp.isPresent()),
"tokenType", tokenType.name(),
"tokenExpired", String.valueOf(tokenExpired)).increment();
}
private void clearPushToken(final Account account, final Device device, final PushNotification.TokenType tokenType) {
final String originalToken = getPushToken(device, tokenType);
if (originalToken == null) {
return;
}
// Reread the account to avoid marking the caller's account as stale. The consumers of this class tend to
// promise not to modify accounts. There's no need to force the caller to be considered mutable just for
// updating an uninstalled feedback timestamp though.
accountsManager.getByAccountIdentifier(account.getUuid()).ifPresent(rereadAccount ->
rereadAccount.getDevice(device.getId()).ifPresent(rereadDevice ->
accountsManager.updateDevice(rereadAccount, device.getId(), d -> {
// Don't clear the token if it's already changed
if (originalToken.equals(getPushToken(d, tokenType))) {
switch (tokenType) {
case FCM -> d.setGcmId(null);
case APN -> d.setApnId(null);
case APN_VOIP -> d.setVoipApnId(null);
}
}
})));
}
private static String getPushToken(final Device device, final PushNotification.TokenType tokenType) {
return switch (tokenType) {
case FCM -> device.getGcmId();
case APN -> device.getApnId();
case APN_VOIP -> device.getVoipApnId();
};
}
}
@@ -55,8 +55,6 @@ public class ReceiptSender {
for (final Device destinationDevice : destinationAccount.getDevices()) {
try {
messageSender.sendMessage(destinationAccount, destinationDevice, message.build(), false);
} catch (final NotPushRegisteredException e) {
logger.debug("User no longer push registered for delivery receipt: {}", e.getMessage());
} catch (final Exception e) {
logger.warn("Could not send delivery receipt", e);
}
@@ -5,7 +5,11 @@
package org.whispersystems.textsecuregcm.push;
import javax.annotation.Nullable;
import java.time.Instant;
import java.util.Optional;
public record SendPushNotificationResult(boolean accepted, @Nullable String errorCode, boolean unregistered) {
public record SendPushNotificationResult(boolean accepted,
Optional<String> errorCode,
boolean unregistered,
Optional<Instant> unregisteredTimestamp) {
}
@@ -0,0 +1,222 @@
package org.whispersystems.textsecuregcm.scheduler;
import com.google.common.annotations.VisibleForTesting;
import io.micrometer.core.instrument.Metrics;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.util.Util;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.util.retry.Retry;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest;
import software.amazon.awssdk.services.dynamodb.model.PutItemRequest;
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
import javax.annotation.Nullable;
import java.nio.ByteBuffer;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadLocalRandom;
/**
* A job scheduler maintains a delay queue of tasks to be run at some time in the future. Callers schedule jobs with
* the {@link #scheduleJob(Instant, byte[])} method, and concrete subclasses actually execute jobs by implementing the
* {@link #processJob(byte[])} method. Some entity must call {@link #processAvailableJobs()} to actually find and
* process jobs that are ready for execution.
*/
public abstract class JobScheduler {
private final DynamoDbAsyncClient dynamoDbAsyncClient;
private final String tableName;
private final Duration jobExpiration;
private final Clock clock;
private final Logger logger = LoggerFactory.getLogger(getClass());
// The name of this scheduler (DynamoDB string)
@VisibleForTesting
public static final String KEY_SCHEDULER_NAME = "S";
// The timestamp (and additional random data; please see #buildRunAtAttribute for details) for the job
// (DynamoDB byte array)
@VisibleForTesting
public static final String ATTR_RUN_AT = "T";
// Additional application-specific data for the job (DynamoDB byte array)
private static final String ATTR_JOB_DATA = "D";
// The time at which this job should be garbage-collected if not already deleted (DynamoDB number;
// seconds from the epoch)
private static final String ATTR_TTL = "E";
private static final String SCHEDULE_JOB_COUNTER_NAME = MetricsUtil.name(JobScheduler.class, "scheduleJob");
private static final String PROCESS_JOB_COUNTER_NAME = MetricsUtil.name(JobScheduler.class, "processJob");
private static final String SCHEDULER_NAME_TAG = "schedulerName";
private static final String OUTCOME_TAG = "outcome";
private static final int MAX_CONCURRENCY = 16;
protected JobScheduler(final DynamoDbAsyncClient dynamoDbAsyncClient,
final String tableName,
final Duration jobExpiration,
final Clock clock) {
this.dynamoDbAsyncClient = dynamoDbAsyncClient;
this.tableName = tableName;
this.jobExpiration = jobExpiration;
this.clock = clock;
}
/**
* Returns the unique name of this scheduler. Scheduler names are used to "namespace" jobs.
*
* @return the unique name of this scheduler
*/
public abstract String getSchedulerName();
/**
* Processes a previously-scheduled job.
*
* @param jobData opaque, application-specific data provided at the time the job was scheduled
*
* @return A future that yields a brief, human-readable status code when the job has been fully processed. On
* successful completion, the job will be deleted. The job will not be deleted if the future completes exceptionally.
*/
protected abstract CompletableFuture<String> processJob(@Nullable byte[] jobData);
/**
* Schedules a job to run at or after the given {@code runAt} time. Concrete implementations must override this method
* to expose it publicly, or provide some more application-appropriate method for public callers.
*
* @param runAt the time at or after which to run the job
* @param jobData application-specific data describing the job; may be {@code null}
*
* @return a future that completes when the job has been scheduled
*/
protected CompletableFuture<Void> scheduleJob(final Instant runAt, @Nullable final byte[] jobData) {
return Mono.fromFuture(() -> scheduleJob(buildRunAtAttribute(runAt), runAt.plus(jobExpiration), jobData))
.retryWhen(Retry.backoff(8, Duration.ofSeconds(1)).maxBackoff(Duration.ofSeconds(4)))
.toFuture()
.thenRun(() -> Metrics.counter(SCHEDULE_JOB_COUNTER_NAME, SCHEDULER_NAME_TAG, getSchedulerName()).increment());
}
@VisibleForTesting
CompletableFuture<Void> scheduleJob(final AttributeValue runAt, final Instant expiration, @Nullable final byte[] jobData) {
final Map<String, AttributeValue> item = new HashMap<>(Map.of(
KEY_SCHEDULER_NAME, AttributeValue.fromS(getSchedulerName()),
ATTR_RUN_AT, runAt,
ATTR_TTL, AttributeValue.fromN(String.valueOf(expiration.getEpochSecond()))));
if (jobData != null) {
item.put(ATTR_JOB_DATA, AttributeValue.fromB(SdkBytes.fromByteArray(jobData)));
}
return dynamoDbAsyncClient.putItem(PutItemRequest.builder()
.tableName(tableName)
.item(item)
.conditionExpression("attribute_not_exists(#schedulerName)")
.expressionAttributeNames(Map.of("#schedulerName", KEY_SCHEDULER_NAME))
.build())
.thenRun(Util.NOOP);
}
/**
* Finds and processes all jobs whose {@code runAt} time is less than or equal to the current time. Scheduled jobs
* will be deleted once they have been processed successfully.
*
* @return a future that completes when all available jobs have been processed
*
* @see #processJob(byte[])
*/
public CompletableFuture<Void> processAvailableJobs() {
return Flux.from(dynamoDbAsyncClient.queryPaginator(QueryRequest.builder()
.tableName(tableName)
.keyConditionExpression("#schedulerName = :schedulerName AND #runAt <= :maxRunAt")
.expressionAttributeNames(Map.of(
"#schedulerName", KEY_SCHEDULER_NAME,
"#runAt", ATTR_RUN_AT))
.expressionAttributeValues(Map.of(
":schedulerName", AttributeValue.fromS(getSchedulerName()),
":maxRunAt", buildMaxRunAtAttribute(clock.instant())))
.build())
.items())
.flatMap(item -> {
final byte[] jobData = item.containsKey(ATTR_JOB_DATA)
? item.get(ATTR_JOB_DATA).b().asByteArray()
: null;
return Mono.fromFuture(processJob(jobData))
.doOnNext(outcome -> Metrics.counter(PROCESS_JOB_COUNTER_NAME,
SCHEDULER_NAME_TAG, getSchedulerName(),
OUTCOME_TAG, outcome)
.increment())
.then(Mono.fromFuture(() -> deleteJob(item.get(KEY_SCHEDULER_NAME), item.get(ATTR_RUN_AT))))
.onErrorResume(throwable -> {
logger.warn("Failed to process job", throwable);
return Mono.empty();
});
}, MAX_CONCURRENCY)
.then()
.toFuture();
}
private CompletableFuture<Void> deleteJob(final AttributeValue schedulerName, final AttributeValue runAt) {
return dynamoDbAsyncClient.deleteItem(DeleteItemRequest.builder()
.tableName(tableName)
.key(Map.of(
KEY_SCHEDULER_NAME, schedulerName,
ATTR_RUN_AT, runAt))
.build())
.thenRun(Util.NOOP);
}
/**
* Constructs an attribute value that contains a sort key that will be greater than any sort key generated for an
* earlier {@code runAt} time and less than a sort key generated for a later {@code runAt} time. The returned value
* begins with the 8-byte, big-endian representation of the given {@code runAt} time in milliseconds since the epoch
* and ends with a random 8-byte suffix. The random suffix ensures that multiple jobs scheduled for the same
* {@code runAt} time will have distinct primary keys; the order in which jobs scheduled at the same time will be
* executed is also random as a result.
*
* @param runAt the time for which to generate a sort key
*
* @return a probably-unique sort key for the given {@code runAt} time
*/
AttributeValue buildRunAtAttribute(final Instant runAt) {
return buildRunAtAttribute(runAt, ThreadLocalRandom.current().nextLong());
}
@VisibleForTesting
AttributeValue buildRunAtAttribute(final Instant runAt, final long salt) {
return AttributeValue.fromB(SdkBytes.fromByteBuffer(ByteBuffer.allocate(24)
.putLong(runAt.toEpochMilli())
.putLong(clock.millis())
.putLong(salt)
.flip()));
}
/**
* Constructs a sort key value that is greater than or equal to all other sort keys for jobs with the same or earlier
* {@code runAt} time.
*
* @param runAt the maximum scheduled time for jobs to match
*
* @return an attribute value for a sort key that is greater than or equal to the sort key for all other jobs
* scheduled to run at or before the given {@code runAt} time
*/
static AttributeValue buildMaxRunAtAttribute(final Instant runAt) {
return AttributeValue.fromB(SdkBytes.fromByteBuffer(ByteBuffer.allocate(24)
.putLong(runAt.toEpochMilli())
.putLong(0xfffffffffffffffL)
.putLong(0xfffffffffffffffL)
.flip()));
}
}
@@ -0,0 +1,94 @@
package org.whispersystems.textsecuregcm.scheduler;
import com.google.common.annotations.VisibleForTesting;
import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberToTimeZonesMapper;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber;
import org.whispersystems.textsecuregcm.storage.Account;
import java.time.Clock;
import java.time.Instant;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
public class SchedulingUtil {
/**
* Gets a present or future time at which to send a notification to a device associated with the given account. This
* is mainly intended to facilitate scheduling notifications such that they arrive during a recipient's waking hours.
* <p/>
* This method will attempt to use a timezone derived from the account's phone number to choose an appropriate time
* to send a notification. If a timezone cannot be derived from the account's phone number, then this method will use
* the account's creation time as a hint. As an example, if the account was created at 07:17 in the server's local
* time, we can assume that the account holder was awake at that time of day, and it's likely a safe time to send a
* notification in the absence of other hints.
*
* @param account the account that will receive the notification
* @param preferredTime the preferred local time (e.g. "noon") at which to deliver the notification
* @param clock a source of the current time
*
* @return the next time in the present or future at which to send a notification for the target account
*/
public static Instant getNextRecommendedNotificationTime(final Account account,
final LocalTime preferredTime,
final Clock clock) {
final ZonedDateTime candidateNotificationTime = getZoneOffset(account, clock)
.map(zoneOffset -> ZonedDateTime.now(zoneOffset).with(preferredTime))
.orElseGet(() -> {
// We couldn't find a reasonable timezone for the account for some reason, so make an educated guess at a
// reasonable time to send a notification based on the account's creation time.
final Instant accountCreation = Instant.ofEpochMilli(account.getPrimaryDevice().getCreated());
final LocalTime accountCreationLocalTime = LocalTime.ofInstant(accountCreation, ZoneId.systemDefault());
return ZonedDateTime.now(ZoneId.systemDefault()).with(accountCreationLocalTime);
});
if (candidateNotificationTime.toInstant().isBefore(clock.instant())) {
// We've missed our opportunity today, so go for the same time tomorrow
return candidateNotificationTime.plusDays(1).toInstant();
} else {
// The best time to send a notification hasn't happened yet today
return candidateNotificationTime.toInstant();
}
}
@VisibleForTesting
static Optional<ZoneOffset> getZoneOffset(final Account account, final Clock clock) {
try {
final Phonenumber.PhoneNumber phoneNumber = PhoneNumberUtil.getInstance().parse(account.getNumber(), null);
final List<String> timeZonesForNumber =
PhoneNumberToTimeZonesMapper.getInstance().getTimeZonesForNumber(phoneNumber);
if (timeZonesForNumber.equals(List.of(PhoneNumberToTimeZonesMapper.getUnknownTimeZone()))) {
return Optional.empty();
}
final List<ZoneOffset> sortedZoneOffsets = timeZonesForNumber
.stream()
.map(id -> {
try {
return ZoneId.of(id);
} catch (final Exception e) {
return null;
}
})
.filter(Objects::nonNull)
.map(ZoneId::getRules)
.distinct()
.map(zoneRules -> zoneRules.getOffset(clock.instant()))
.sorted()
.toList();
return Optional.of(sortedZoneOffsets.get(sortedZoneOffsets.size() / 2));
} catch (final NumberParseException e) {
return Optional.empty();
}
}
}
@@ -1,9 +1,9 @@
package org.whispersystems.textsecuregcm.spam;
import org.whispersystems.textsecuregcm.auth.AccountAndAuthenticatedDeviceHolder;
import org.whispersystems.textsecuregcm.storage.Account;
import javax.ws.rs.container.ContainerRequestContext;
import java.util.Optional;
import java.util.function.Function;
/**
* Generates ReportSpamTokens to be used for spam reports.
@@ -18,7 +18,7 @@ public interface ReportSpamTokenProvider {
* @param maybeDestination the intended recepient of the message if available
* @return either a generated token or nothing
*/
Optional<byte[]> makeReportSpamToken(ContainerRequestContext context, final Account sender,
Optional<byte[]> makeReportSpamToken(ContainerRequestContext context, final AccountAndAuthenticatedDeviceHolder sender,
final Optional<Account> maybeDestination);
/**
@@ -115,8 +115,13 @@ public class ChangeNumberManager {
}
private void sendDeviceMessages(final Account account, final List<IncomingMessage> deviceMessages) {
deviceMessages.forEach(message ->
sendMessageToSelf(account, account.getDevice(message.destinationDeviceId()), message));
try {
deviceMessages.forEach(message ->
sendMessageToSelf(account, account.getDevice(message.destinationDeviceId()), message));
} catch (RuntimeException e) {
logger.warn("Changed number but could not send all device messages on {}", account.getUuid(), e);
throw e;
}
}
@VisibleForTesting
@@ -130,23 +135,20 @@ public class ChangeNumberManager {
logger.debug("destination device not present");
return;
}
try {
long serverTimestamp = System.currentTimeMillis();
Envelope envelope = Envelope.newBuilder()
.setType(Envelope.Type.forNumber(message.type()))
.setTimestamp(serverTimestamp)
.setServerTimestamp(serverTimestamp)
.setDestinationUuid(new AciServiceIdentifier(sourceAndDestinationAccount.getUuid()).toServiceIdentifierString())
.setContent(ByteString.copyFrom(contents.get()))
.setSourceUuid(new AciServiceIdentifier(sourceAndDestinationAccount.getUuid()).toServiceIdentifierString())
.setSourceDevice((int) Device.PRIMARY_ID)
.setUpdatedPni(sourceAndDestinationAccount.getPhoneNumberIdentifier().toString())
.setUrgent(true)
.build();
messageSender.sendMessage(sourceAndDestinationAccount, destinationDevice.get(), envelope, false);
} catch (NotPushRegisteredException e) {
logger.debug("Not registered", e);
}
final long serverTimestamp = System.currentTimeMillis();
final Envelope envelope = Envelope.newBuilder()
.setType(Envelope.Type.forNumber(message.type()))
.setTimestamp(serverTimestamp)
.setServerTimestamp(serverTimestamp)
.setDestinationUuid(new AciServiceIdentifier(sourceAndDestinationAccount.getUuid()).toServiceIdentifierString())
.setContent(ByteString.copyFrom(contents.get()))
.setSourceUuid(new AciServiceIdentifier(sourceAndDestinationAccount.getUuid()).toServiceIdentifierString())
.setSourceDevice((int) Device.PRIMARY_ID)
.setUpdatedPni(sourceAndDestinationAccount.getPhoneNumberIdentifier().toString())
.setUrgent(true)
.build();
messageSender.sendMessage(sourceAndDestinationAccount, destinationDevice.get(), envelope, false);
}
}
@@ -14,7 +14,6 @@ import java.util.OptionalInt;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import javax.annotation.Nullable;
import org.apache.commons.lang3.StringUtils;
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
import org.whispersystems.textsecuregcm.util.DeviceNameByteArrayAdapter;
@@ -56,9 +55,6 @@ public class Device {
@JsonProperty
private long pushTimestamp;
@JsonProperty
private long uninstalledFeedback;
@JsonProperty
private boolean fetchesMessages;
@@ -101,14 +97,6 @@ public class Device {
this.voipApnId = voipApnId;
}
public void setUninstalledFeedbackTimestamp(long uninstalledFeedback) {
this.uninstalledFeedback = uninstalledFeedback;
}
public long getUninstalledFeedbackTimestamp() {
return uninstalledFeedback;
}
public void setLastSeen(long lastSeen) {
this.lastSeen = lastSeen;
}
@@ -198,10 +186,6 @@ public class Device {
this.capabilities = capabilities;
}
public boolean hasMessageDeliveryChannel() {
return fetchesMessages || StringUtils.isNotEmpty(getApnId()) || StringUtils.isNotEmpty(getGcmId());
}
public boolean isExpired() {
return isPrimary()
? lastSeen < (System.currentTimeMillis() - ALLOWED_PRIMARY_IDLE_MILLIS)
@@ -22,6 +22,7 @@ import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
@@ -245,7 +246,7 @@ public class MessagePersister implements Managed {
// its messages) is unlinked
final Device deviceToDelete = account.getDevices()
.stream()
.filter(d -> !d.isPrimary() && !d.hasMessageDeliveryChannel())
.filter(d -> !d.isPrimary() && !deviceHasMessageDeliveryChannel(d))
.min(Comparator.comparing(Device::getLastSeen))
.or(() ->
Flux.fromIterable(account.getDevices())
@@ -288,4 +289,8 @@ public class MessagePersister implements Managed {
}
});
}
private static boolean deviceHasMessageDeliveryChannel(final Device device) {
return device.getFetchesMessages() || StringUtils.isNotEmpty(device.getApnId()) || StringUtils.isNotEmpty(device.getGcmId());
}
}
@@ -96,12 +96,6 @@ public class DestinationDeviceValidator {
final Set<Byte> missingDeviceIds = new HashSet<>(accountDeviceIds);
missingDeviceIds.removeAll(messageDeviceIds);
// Temporarily "excuse" missing devices if they're missing a message delivery channel as a transitional measure
missingDeviceIds.removeAll(account.getDevices().stream()
.filter(device -> !device.hasMessageDeliveryChannel())
.map(Device::getId)
.collect(Collectors.toSet()));
final Set<Byte> extraDeviceIds = new HashSet<>(messageDeviceIds);
extraDeviceIds.removeAll(accountDeviceIds);
@@ -222,7 +222,11 @@ public class WebSocketConnection implements MessageAvailabilityListener, Displac
if (throwable != null) {
sendFailuresCounter.increment();
} else {
messageMetrics.measureOutgoingMessageLatency(message.getServerTimestamp(), "websocket", client.getUserAgent(), clientReleaseManager);
messageMetrics.measureOutgoingMessageLatency(message.getServerTimestamp(),
"websocket",
device.isPrimary(),
client.getUserAgent(),
clientReleaseManager);
}
}).thenCompose(response -> {
final CompletableFuture<Void> result;
@@ -233,7 +237,7 @@ public class WebSocketConnection implements MessageAvailabilityListener, Displac
.thenApply(ignored -> null);
if (message.getType() != Envelope.Type.SERVER_DELIVERY_RECEIPT) {
recordMessageDeliveryDuration(message.getTimestamp(), device);
recordMessageDeliveryDuration(message.getServerTimestamp(), device);
sendDeliveryReceiptFor(message);
}
} else {
@@ -29,7 +29,6 @@ import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfigurati
import org.whispersystems.textsecuregcm.controllers.SecureStorageController;
import org.whispersystems.textsecuregcm.controllers.SecureValueRecovery2Controller;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
@@ -91,8 +90,6 @@ record CommandDependencies(
DynamicConfiguration.class, dynamicConfigurationExecutor, awsCredentialsProvider);
dynamicConfigurationManager.start();
MetricsUtil.configureRegistries(configuration, environment, dynamicConfigurationManager);
final ClientResources.Builder redisClientResourcesBuilder = ClientResources.builder();
FaultTolerantRedisCluster cacheCluster = configuration.getCacheClusterConfiguration().build("main_cache",
@@ -0,0 +1,9 @@
package org.whispersystems.textsecuregcm.workers;
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
import org.whispersystems.textsecuregcm.scheduler.JobScheduler;
public interface JobSchedulerFactory {
JobScheduler buildJobScheduler(CommandDependencies commandDependencies, WhisperServerConfiguration configuration);
}
@@ -49,6 +49,7 @@ public class MessagePersisterServiceCommand extends ServerCommand<WhisperServerC
UncaughtExceptionHandler.register();
final CommandDependencies deps = CommandDependencies.build("message-persister-service", environment, configuration);
MetricsUtil.configureRegistries(configuration, environment, deps.dynamicConfigurationManager());
if (configuration.getServerFactory() instanceof DefaultServerFactory defaultServerFactory) {
defaultServerFactory.getApplicationConnectors()
@@ -1,160 +0,0 @@
/*
* Copyright 2023 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.workers;
import com.google.common.annotations.VisibleForTesting;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tags;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.Optional;
import net.sourceforge.argparse4j.inf.Subparser;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.Device;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
public class ProcessPushNotificationFeedbackCommand extends AbstractSinglePassCrawlAccountsCommand {
private final Clock clock;
@VisibleForTesting
static final Duration MAX_TOKEN_REFRESH_DELAY = Duration.ofDays(14);
@VisibleForTesting
static final String DRY_RUN_ARGUMENT = "dry-run";
private static final int MAX_CONCURRENCY = 16;
private static final String EXPIRED_DEVICE_COUNTER_NAME =
MetricsUtil.name(ProcessPushNotificationFeedbackCommand.class, "expiredDevice");
private static final String RECOVERED_DEVICE_COUNTER_NAME =
MetricsUtil.name(ProcessPushNotificationFeedbackCommand.class, "recoveredDevice");
private static final Logger log = LoggerFactory.getLogger(ProcessPushNotificationFeedbackCommand.class);
public ProcessPushNotificationFeedbackCommand(final Clock clock) {
super("process-push-notification-feedback", "");
this.clock = clock;
}
@Override
public void configure(final Subparser subparser) {
super.configure(subparser);
subparser.addArgument("--dry-run")
.type(Boolean.class)
.dest(DRY_RUN_ARGUMENT)
.required(false)
.setDefault(true)
.help("If true, don't actually modify accounts with stale devices");
}
@Override
protected void crawlAccounts(final Flux<Account> accounts) {
final boolean isDryRun = getNamespace().getBoolean(DRY_RUN_ARGUMENT);
accounts
.filter(account -> account.getDevices().stream().anyMatch(this::deviceNeedsUpdate))
.flatMap(account -> {
account.getDevices().stream()
.filter(this::deviceNeedsUpdate)
.forEach(device -> {
final Tags tags = Tags.of(
UserAgentTagUtil.PLATFORM_TAG, getPlatform(device),
"dryRun", String.valueOf(isDryRun));
if (deviceExpired(device)) {
Metrics.counter(EXPIRED_DEVICE_COUNTER_NAME, tags).increment();
} else {
Metrics.counter(RECOVERED_DEVICE_COUNTER_NAME, tags).increment();
}
});
if (isDryRun) {
return Mono.just(account);
} else {
return Mono.fromFuture(() -> getCommandDependencies().accountsManager().updateAsync(account,
a -> a.getDevices().stream()
.filter(this::deviceNeedsUpdate)
.forEach(device -> {
if (deviceExpired(device)) {
getUserAgent(device).ifPresent(device::setUserAgent);
device.setGcmId(null);
device.setApnId(null);
device.setVoipApnId(null);
device.setFetchesMessages(false);
} else {
device.setUninstalledFeedbackTimestamp(0);
}
})))
.onErrorResume(throwable -> {
log.warn("Failed to process push notification feedback for account {}", account.getUuid(), throwable);
return Mono.empty();
});
}
}, MAX_CONCURRENCY)
.then()
.block();
}
@VisibleForTesting
boolean pushFeedbackIntervalElapsed(final Device device) {
// After we get an indication that a device may have uninstalled the Signal app (`uninstalledFeedbackTimestamp` is
// non-zero), check back in after a few days to see what ultimately happened.
return device.getUninstalledFeedbackTimestamp() != 0 &&
Instant.ofEpochMilli(device.getUninstalledFeedbackTimestamp()).plus(MAX_TOKEN_REFRESH_DELAY)
.isBefore(clock.instant());
}
@VisibleForTesting
boolean deviceExpired(final Device device) {
// If we received an indication that a device may have uninstalled the Signal app and we haven't seen that device in
// a few days since that event, we consider the device "expired" and should clean up its push tokens. If we have
// seen the device recently, though, we assume that the "uninstalled" hint was either incorrect or the device has
// since reinstalled the app and provided new push tokens.
return Instant.ofEpochMilli(device.getLastSeen()).plus(MAX_TOKEN_REFRESH_DELAY).isBefore(clock.instant());
}
@VisibleForTesting
boolean deviceNeedsUpdate(final Device device) {
return pushFeedbackIntervalElapsed(device) && (device.hasMessageDeliveryChannel() || device.getLastSeen() > device.getUninstalledFeedbackTimestamp());
}
@VisibleForTesting
static Optional<String> getUserAgent(final Device device) {
if (StringUtils.isNotBlank(device.getApnId())) {
if (device.isPrimary()) {
return Optional.of("OWI");
} else {
return Optional.of("OWP");
}
} else if (StringUtils.isNotBlank(device.getGcmId())) {
return Optional.of("OWA");
}
return Optional.empty();
}
private static String getPlatform(final Device device) {
if (StringUtils.isNotBlank(device.getApnId())) {
return "ios";
} else if (StringUtils.isNotBlank(device.getGcmId())) {
return "android";
}
return "unrecognized";
}
}
@@ -0,0 +1,133 @@
package org.whispersystems.textsecuregcm.workers;
import io.dropwizard.core.Application;
import io.dropwizard.core.cli.ServerCommand;
import io.dropwizard.core.server.DefaultServerFactory;
import io.dropwizard.core.setup.Environment;
import io.dropwizard.jetty.HttpsConnectorFactory;
import io.dropwizard.lifecycle.Managed;
import net.sourceforge.argparse4j.inf.Namespace;
import net.sourceforge.argparse4j.inf.Subparser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.scheduler.JobScheduler;
import org.whispersystems.textsecuregcm.util.logging.UncaughtExceptionHandler;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
public class ProcessScheduledJobsServiceCommand extends ServerCommand<WhisperServerConfiguration> {
private final String name;
private final JobSchedulerFactory jobSchedulerFactory;
private static final String FIXED_DELAY_SECONDS_ARGUMENT = "fixedDelay";
private static final int DEFAULT_FIXED_DELAY_SECONDS = 60;
private static final Logger log = LoggerFactory.getLogger(ProcessScheduledJobsServiceCommand.class);
private static class ScheduledJobProcessor implements Managed {
private final JobScheduler jobScheduler;
private final ScheduledExecutorService scheduledExecutorService;
private final int fixedDelaySeconds;
private ScheduledFuture<?> processJobsFuture;
private ScheduledJobProcessor(final JobScheduler jobScheduler,
final ScheduledExecutorService scheduledExecutorService,
final int fixedDelaySeconds) {
this.jobScheduler = jobScheduler;
this.scheduledExecutorService = scheduledExecutorService;
this.fixedDelaySeconds = fixedDelaySeconds;
}
@Override
public void start() {
processJobsFuture = scheduledExecutorService.scheduleWithFixedDelay(() -> {
try {
jobScheduler.processAvailableJobs().join();
} catch (final Exception e) {
log.warn("Failed to process available jobs for scheduler: {}", jobScheduler.getSchedulerName(), e);
}
}, 0, fixedDelaySeconds, TimeUnit.SECONDS);
}
@Override
public void stop() {
if (processJobsFuture != null) {
processJobsFuture.cancel(false);
}
processJobsFuture = null;
}
}
public ProcessScheduledJobsServiceCommand(final String name,
final String description,
final JobSchedulerFactory jobSchedulerFactory) {
super(new Application<>() {
@Override
public void run(WhisperServerConfiguration configuration, Environment environment) {
}
}, name,
description);
this.name = name;
this.jobSchedulerFactory = jobSchedulerFactory;
}
@Override
public void configure(final Subparser subparser) {
super.configure(subparser);
subparser.addArgument("--fixed-delay")
.type(Integer.class)
.dest(FIXED_DELAY_SECONDS_ARGUMENT)
.setDefault(DEFAULT_FIXED_DELAY_SECONDS)
.help("The delay, in seconds, between queries for jobs to process");
}
@Override
protected void run(final Environment environment,
final Namespace namespace,
final WhisperServerConfiguration configuration)
throws Exception {
UncaughtExceptionHandler.register();
final CommandDependencies commandDependencies = CommandDependencies.build(name, environment, configuration);
final int fixedDelaySeconds = namespace.getInt(FIXED_DELAY_SECONDS_ARGUMENT);
MetricsUtil.configureRegistries(configuration, environment, commandDependencies.dynamicConfigurationManager());
// Even though we're not actually serving traffic, `ServerCommand` subclasses need a valid server configuration, and
// that means they need to be able to decrypt the TLS keystore.
if (configuration.getServerFactory() instanceof DefaultServerFactory defaultServerFactory) {
defaultServerFactory.getApplicationConnectors()
.forEach(connectorFactory -> {
if (connectorFactory instanceof HttpsConnectorFactory h) {
h.setKeyStorePassword(configuration.getTlsKeyStoreConfiguration().password().value());
}
});
}
final ScheduledExecutorService scheduledExecutorService =
environment.lifecycle().scheduledExecutorService("scheduled-job-processor-%d", false)
.build();
final JobScheduler jobScheduler = jobSchedulerFactory.buildJobScheduler(commandDependencies, configuration);
environment.lifecycle().manage(new ScheduledJobProcessor(jobScheduler, scheduledExecutorService, fixedDelaySeconds));
MetricsUtil.registerSystemResourceMetrics(environment);
super.run(environment, namespace, configuration);
}
}
@@ -53,6 +53,7 @@ public class ScheduledApnPushNotificationSenderServiceCommand extends ServerComm
UncaughtExceptionHandler.register();
final CommandDependencies deps = CommandDependencies.build("scheduled-apn-sender", environment, configuration);
MetricsUtil.configureRegistries(configuration, environment, deps.dynamicConfigurationManager());
if (configuration.getServerFactory() instanceof DefaultServerFactory defaultServerFactory) {
defaultServerFactory.getApplicationConnectors()
@@ -162,7 +162,6 @@ class AccountAuthenticatorTest {
when(account.getUuid()).thenReturn(uuid);
when(account.getDevice(deviceId)).thenReturn(Optional.of(device));
when(device.getId()).thenReturn(deviceId);
when(device.hasMessageDeliveryChannel()).thenReturn(true);
when(device.getAuthTokenHash()).thenReturn(credentials);
when(credentials.verify(password)).thenReturn(true);
when(credentials.getVersion()).thenReturn(SaltedTokenHash.CURRENT_VERSION);
@@ -191,7 +190,6 @@ class AccountAuthenticatorTest {
when(account.getUuid()).thenReturn(uuid);
when(account.getDevice(deviceId)).thenReturn(Optional.of(device));
when(device.getId()).thenReturn(deviceId);
when(device.hasMessageDeliveryChannel()).thenReturn(true);
when(device.getAuthTokenHash()).thenReturn(credentials);
when(credentials.verify(password)).thenReturn(true);
when(credentials.getVersion()).thenReturn(SaltedTokenHash.CURRENT_VERSION);
@@ -223,7 +221,6 @@ class AccountAuthenticatorTest {
when(account.getUuid()).thenReturn(uuid);
when(account.getDevice(deviceId)).thenReturn(Optional.of(authenticatedDevice));
when(authenticatedDevice.getId()).thenReturn(deviceId);
when(authenticatedDevice.hasMessageDeliveryChannel()).thenReturn(deviceEnabled);
when(authenticatedDevice.getAuthTokenHash()).thenReturn(credentials);
when(credentials.verify(password)).thenReturn(true);
when(credentials.getVersion()).thenReturn(SaltedTokenHash.CURRENT_VERSION);
@@ -258,7 +255,6 @@ class AccountAuthenticatorTest {
when(account.getUuid()).thenReturn(uuid);
when(account.getDevice(deviceId)).thenReturn(Optional.of(device));
when(device.getId()).thenReturn(deviceId);
when(device.hasMessageDeliveryChannel()).thenReturn(true);
when(device.getAuthTokenHash()).thenReturn(credentials);
when(credentials.verify(password)).thenReturn(true);
when(credentials.getVersion()).thenReturn(SaltedTokenHash.Version.V1);
@@ -294,7 +290,6 @@ class AccountAuthenticatorTest {
when(account.getUuid()).thenReturn(uuid);
when(account.getDevice(deviceId)).thenReturn(Optional.of(device));
when(device.getId()).thenReturn(deviceId);
when(device.hasMessageDeliveryChannel()).thenReturn(true);
when(device.getAuthTokenHash()).thenReturn(credentials);
when(credentials.verify(password)).thenReturn(true);
when(credentials.getVersion()).thenReturn(SaltedTokenHash.CURRENT_VERSION);
@@ -321,7 +316,6 @@ class AccountAuthenticatorTest {
when(account.getUuid()).thenReturn(uuid);
when(account.getDevice(deviceId)).thenReturn(Optional.of(device));
when(device.getId()).thenReturn(deviceId);
when(device.hasMessageDeliveryChannel()).thenReturn(true);
when(device.getAuthTokenHash()).thenReturn(credentials);
when(credentials.verify(password)).thenReturn(true);
when(credentials.getVersion()).thenReturn(SaltedTokenHash.CURRENT_VERSION);
@@ -1,55 +0,0 @@
/*
* Copyright 2024 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.auth;
import org.junit.jupiter.api.Test;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.Device;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.IntStream;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class ContainerRequestUtilTest {
@Test
void testBuildDevicesEnabled() {
final byte disabledDeviceId = 3;
final Account account = mock(Account.class);
final List<Device> devices = new ArrayList<>();
when(account.getDevices()).thenReturn(devices);
IntStream.range(1, 5)
.forEach(id -> {
final Device device = mock(Device.class);
when(device.getId()).thenReturn((byte) id);
when(device.hasMessageDeliveryChannel()).thenReturn(id != disabledDeviceId);
devices.add(device);
});
final Map<Byte, Boolean> devicesEnabled = ContainerRequestUtil.AccountInfo.fromAccount(account).devicesEnabled();
assertEquals(4, devicesEnabled.size());
assertAll(devicesEnabled.entrySet().stream()
.map(deviceAndEnabled -> () -> {
if (deviceAndEnabled.getKey().equals(disabledDeviceId)) {
assertFalse(deviceAndEnabled.getValue());
} else {
assertTrue(deviceAndEnabled.getValue());
}
}));
}
}
@@ -10,7 +10,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
@@ -32,17 +31,13 @@ import java.util.Arrays;
import java.util.Base64;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.UUID;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
@@ -62,8 +57,6 @@ import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.ArgumentCaptor;
import org.whispersystems.textsecuregcm.filters.RemoteAddressFilter;
@@ -83,7 +76,7 @@ import org.whispersystems.websocket.messages.protobuf.SubProtocol;
import org.whispersystems.websocket.session.WebSocketSessionContextValueFactoryProvider;
@ExtendWith(DropwizardExtensionsSupport.class)
class AuthEnablementRefreshRequirementProviderTest {
class LinkedDeviceRefreshRequirementProviderTest {
private final ApplicationEventListener applicationEventListener = mock(ApplicationEventListener.class);
@@ -105,14 +98,14 @@ class AuthEnablementRefreshRequirementProviderTest {
private AccountsManager accountsManager;
private ClientPresenceManager clientPresenceManager;
private AuthEnablementRefreshRequirementProvider provider;
private LinkedDeviceRefreshRequirementProvider provider;
@BeforeEach
void setup() {
accountsManager = mock(AccountsManager.class);
clientPresenceManager = mock(ClientPresenceManager.class);
provider = new AuthEnablementRefreshRequirementProvider(accountsManager);
provider = new LinkedDeviceRefreshRequirementProvider(accountsManager);
final WebsocketRefreshRequestEventListener listener =
new WebsocketRefreshRequestEventListener(clientPresenceManager, provider);
@@ -131,54 +124,8 @@ class AuthEnablementRefreshRequirementProviderTest {
.forEach(device -> when(clientPresenceManager.isPresent(uuid, device.getId())).thenReturn(true));
}
@ParameterizedTest
@MethodSource
void testDeviceEnabledChanged(final Map<Byte, Boolean> initialEnabled, final Map<Byte, Boolean> finalEnabled) {
assert initialEnabled.size() == finalEnabled.size();
assert account.getPrimaryDevice().hasMessageDeliveryChannel();
initialEnabled.forEach((deviceId, enabled) ->
DevicesHelper.setEnabled(account.getDevice(deviceId).orElseThrow(), enabled));
final Response response = resources.getJerseyTest()
.target("/v1/test/account/devices/enabled")
.request()
.header("Authorization",
"Basic " + Base64.getEncoder().encodeToString("user:pass".getBytes(StandardCharsets.UTF_8)))
.post(Entity.entity(finalEnabled, MediaType.APPLICATION_JSON));
assertEquals(200, response.getStatus());
final boolean expectDisplacedPresence = !initialEnabled.equals(finalEnabled);
assertAll(
initialEnabled.keySet().stream()
.map(deviceId -> () -> verify(clientPresenceManager, times(expectDisplacedPresence ? 1 : 0))
.disconnectPresence(account.getUuid(), deviceId)));
assertAll(
finalEnabled.keySet().stream()
.map(deviceId -> () -> verify(clientPresenceManager, times(expectDisplacedPresence ? 1 : 0))
.disconnectPresence(account.getUuid(), deviceId)));
}
static Stream<Arguments> testDeviceEnabledChanged() {
final byte deviceId2 = 2;
final byte deviceId3 = 3;
return Stream.of(
Arguments.of(Map.of(deviceId2, false, deviceId3, false), Map.of(deviceId2, true, deviceId3, true)),
Arguments.of(Map.of(deviceId2, true, deviceId3, true), Map.of(deviceId2, false, deviceId3, false)),
Arguments.of(Map.of(deviceId2, true, deviceId3, true), Map.of(deviceId2, true, deviceId3, true)),
Arguments.of(Map.of(deviceId2, false, deviceId3, true), Map.of(deviceId2, true, deviceId3, true)),
Arguments.of(Map.of(deviceId2, true, deviceId3, false), Map.of(deviceId2, true, deviceId3, true))
);
}
@Test
void testDeviceAdded() {
assert account.getPrimaryDevice().hasMessageDeliveryChannel();
final int initialDeviceCount = account.getDevices().size();
final List<String> addedDeviceNames = List.of(
@@ -204,8 +151,6 @@ class AuthEnablementRefreshRequirementProviderTest {
@ParameterizedTest
@ValueSource(ints = {1, 2})
void testDeviceRemoved(final int removedDeviceCount) {
assert account.getPrimaryDevice().hasMessageDeliveryChannel();
final List<Byte> initialDeviceIds = account.getDevices().stream().map(Device::getId).toList();
final List<Byte> deletedDeviceIds = account.getDevices().stream()
@@ -358,40 +303,9 @@ class AuthEnablementRefreshRequirementProviderTest {
return "You’re in!";
}
@PUT
@Path("/account/enabled/{enabled}")
@ChangesDeviceEnabledState
public String setAccountEnabled(@Auth TestPrincipal principal, @PathParam("enabled") final boolean enabled) {
final Device device = principal.getAccount().getPrimaryDevice();
DevicesHelper.setEnabled(device, enabled);
assert device.hasMessageDeliveryChannel() == enabled;
return String.format("Set account to %s", enabled);
}
@POST
@Path("/account/devices/enabled")
@ChangesDeviceEnabledState
public String setEnabled(@Auth TestPrincipal principal, Map<Byte, Boolean> deviceIdsEnabled) {
final StringBuilder response = new StringBuilder();
for (Entry<Byte, Boolean> deviceIdEnabled : deviceIdsEnabled.entrySet()) {
final Device device = principal.getAccount().getDevice(deviceIdEnabled.getKey()).orElseThrow();
DevicesHelper.setEnabled(device, deviceIdEnabled.getValue());
response.append(String.format("Set device enabled %s", deviceIdEnabled));
}
return response.toString();
}
@PUT
@Path("/account/devices")
@ChangesDeviceEnabledState
@ChangesLinkedDevices
public String addDevices(@Auth TestPrincipal auth, List<byte[]> deviceNames) {
deviceNames.forEach(name -> {
@@ -406,7 +320,7 @@ class AuthEnablementRefreshRequirementProviderTest {
@DELETE
@Path("/account/devices/{deviceIds}")
@ChangesDeviceEnabledState
@ChangesLinkedDevices
public String removeDevices(@Auth TestPrincipal auth, @PathParam("deviceIds") String deviceIds) {
Arrays.stream(deviceIds.split(","))
@@ -415,17 +329,5 @@ class AuthEnablementRefreshRequirementProviderTest {
return "Removed device(s) " + deviceIds;
}
@POST
@Path("/account/disablePrimaryDeviceAndDeleteDevice/{deviceId}")
@ChangesDeviceEnabledState
public String disablePrimaryDeviceAndRemoveDevice(@Auth TestPrincipal auth, @PathParam("deviceId") byte deviceId) {
DevicesHelper.setEnabled(auth.getAccount().getPrimaryDevice(), false);
auth.getAccount().removeDevice(deviceId);
return "Removed device " + deviceId;
}
}
}
@@ -406,9 +406,10 @@ public class BackupAuthManagerTest {
when(accountsManager.updateAsync(any(), any())).thenReturn(CompletableFuture.completedFuture(account));
// Should be rate limited
CompletableFutureTestUtil.assertFailsWithCause(
final RateLimitExceededException ex = CompletableFutureTestUtil.assertFailsWithCause(
RateLimitExceededException.class,
authManager.commitBackupId(account, credentialRequest));
assertThat(ex.isLegacy()).isFalse();
// If we don't change the request, shouldn't be rate limited
when(account.getBackupCredentialRequest()).thenReturn(credentialRequest.serialize());
@@ -132,8 +132,6 @@ class DeviceControllerTest {
@BeforeEach
void setup() {
when(rateLimiters.getSmsDestinationLimiter()).thenReturn(rateLimiter);
when(rateLimiters.getVerifyLimiter()).thenReturn(rateLimiter);
when(rateLimiters.getAllocateDeviceLimiter()).thenReturn(rateLimiter);
when(rateLimiters.getVerifyDeviceLimiter()).thenReturn(rateLimiter);
@@ -221,10 +221,6 @@ class KeysControllerTest {
when(sampleDevice3.getRegistrationId()).thenReturn(SAMPLE_REGISTRATION_ID2);
when(sampleDevice4.getRegistrationId()).thenReturn(SAMPLE_REGISTRATION_ID4);
when(sampleDevice.getPhoneNumberIdentityRegistrationId()).thenReturn(OptionalInt.of(SAMPLE_PNI_REGISTRATION_ID));
when(sampleDevice.hasMessageDeliveryChannel()).thenReturn(true);
when(sampleDevice2.hasMessageDeliveryChannel()).thenReturn(true);
when(sampleDevice3.hasMessageDeliveryChannel()).thenReturn(false);
when(sampleDevice4.hasMessageDeliveryChannel()).thenReturn(true);
when(sampleDevice.getId()).thenReturn(sampleDeviceId);
when(sampleDevice2.getId()).thenReturn(sampleDevice2Id);
when(sampleDevice3.getId()).thenReturn(sampleDevice3Id);
@@ -330,54 +326,6 @@ class KeysControllerTest {
verify(KEYS).getPqCount(AuthHelper.VALID_UUID, SAMPLE_DEVICE_ID);
}
@Test
void putSignedPreKeyV2() {
final ECSignedPreKey signedPreKey = KeysHelper.signedECPreKey(9998, AuthHelper.VALID_IDENTITY_KEY_PAIR);
try (final Response response = resources.getJerseyTest()
.target("/v2/keys/signed")
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.put(Entity.entity(signedPreKey, MediaType.APPLICATION_JSON_TYPE))) {
assertThat(response.getStatus()).isEqualTo(204);
verify(KEYS).storeEcSignedPreKeys(AuthHelper.VALID_UUID, AuthHelper.VALID_DEVICE.getId(), signedPreKey);
}
}
@Test
void putPhoneNumberIdentitySignedPreKeyV2() {
final ECSignedPreKey pniSignedPreKey = KeysHelper.signedECPreKey(9998, AuthHelper.VALID_PNI_IDENTITY_KEY_PAIR);
try (final Response response = resources.getJerseyTest()
.target("/v2/keys/signed")
.queryParam("identity", "pni")
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.put(Entity.entity(pniSignedPreKey, MediaType.APPLICATION_JSON_TYPE))) {
assertThat(response.getStatus()).isEqualTo(204);
verify(KEYS).storeEcSignedPreKeys(AuthHelper.VALID_PNI, AuthHelper.VALID_DEVICE.getId(), pniSignedPreKey);
}
}
@ParameterizedTest
@EnumSource(IdentityType.class)
void putSignedPreKeyV2BadSignature(final IdentityType identityType) {
final ECSignedPreKey signedPreKey = KeysHelper.signedECPreKey(9998, Curve.generateKeyPair());
try (final Response response = resources.getJerseyTest()
.target("/v2/keys/signed")
.queryParam("identity", identityType.name().toLowerCase())
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.put(Entity.entity(signedPreKey, MediaType.APPLICATION_JSON_TYPE))) {
assertThat(response.getStatus()).isEqualTo(422);
verify(KEYS, never()).storeEcSignedPreKeys(any(), anyByte(), any());
}
}
@Test
void validSingleRequestTestV2() {
PreKeyResponse result = resources.getJerseyTest()
@@ -20,7 +20,6 @@ import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.anyBoolean;
import static org.mockito.Mockito.anyString;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset;
@@ -109,7 +108,6 @@ import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper
import org.whispersystems.textsecuregcm.metrics.MessageMetrics;
import org.whispersystems.textsecuregcm.providers.MultiRecipientMessageProvider;
import org.whispersystems.textsecuregcm.push.MessageSender;
import org.whispersystems.textsecuregcm.push.NotPushRegisteredException;
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
import org.whispersystems.textsecuregcm.push.ReceiptSender;
import org.whispersystems.textsecuregcm.spam.ReportSpamTokenProvider;
@@ -564,7 +562,7 @@ class MessageControllerTest {
final ArgumentCaptor<Envelope> envelopeCaptor = ArgumentCaptor.forClass(Envelope.class);
verify(messageSender, times(2))
verify(messageSender, times(3))
.sendMessage(any(Account.class), any(Device.class), envelopeCaptor.capture(), eq(false));
envelopeCaptor.getAllValues().forEach(envelope -> assertTrue(envelope.getUrgent()));
@@ -586,7 +584,7 @@ class MessageControllerTest {
final ArgumentCaptor<Envelope> envelopeCaptor = ArgumentCaptor.forClass(Envelope.class);
verify(messageSender, times(2))
verify(messageSender, times(3))
.sendMessage(any(Account.class), any(Device.class), envelopeCaptor.capture(), eq(false));
envelopeCaptor.getAllValues().forEach(envelope -> assertFalse(envelope.getUrgent()));
@@ -606,7 +604,7 @@ class MessageControllerTest {
assertThat("Good Response Code", response.getStatus(), is(equalTo(200)));
verify(messageSender, times(2))
verify(messageSender, times(3))
.sendMessage(any(Account.class), any(Device.class), any(Envelope.class), eq(false));
}
}
@@ -1222,21 +1220,22 @@ class MessageControllerTest {
}
private static Map<ServiceIdentifier, Map<Byte, Integer>> multiRecipientTargetMap() {
return
return Map.of(
SINGLE_DEVICE_ACI_ID, Map.of(SINGLE_DEVICE_ID1, SINGLE_DEVICE_REG_ID1),
SINGLE_DEVICE_PNI_ID, Map.of(SINGLE_DEVICE_ID1, SINGLE_DEVICE_PNI_REG_ID1),
MULTI_DEVICE_ACI_ID,
Map.of(
SINGLE_DEVICE_ACI_ID, Map.of(SINGLE_DEVICE_ID1, SINGLE_DEVICE_REG_ID1),
SINGLE_DEVICE_PNI_ID, Map.of(SINGLE_DEVICE_ID1, SINGLE_DEVICE_PNI_REG_ID1),
MULTI_DEVICE_ACI_ID,
Map.of(
MULTI_DEVICE_ID1, MULTI_DEVICE_REG_ID1,
MULTI_DEVICE_ID2, MULTI_DEVICE_REG_ID2),
MULTI_DEVICE_PNI_ID,
Map.of(
MULTI_DEVICE_ID1, MULTI_DEVICE_PNI_REG_ID1,
MULTI_DEVICE_ID2, MULTI_DEVICE_PNI_REG_ID2),
NONEXISTENT_ACI_ID, Map.of(SINGLE_DEVICE_ID1, SINGLE_DEVICE_REG_ID1),
NONEXISTENT_PNI_ID, Map.of(SINGLE_DEVICE_ID1, SINGLE_DEVICE_PNI_REG_ID1)
);
MULTI_DEVICE_ID1, MULTI_DEVICE_REG_ID1,
MULTI_DEVICE_ID2, MULTI_DEVICE_REG_ID2,
MULTI_DEVICE_ID3, MULTI_DEVICE_REG_ID3),
MULTI_DEVICE_PNI_ID,
Map.of(
MULTI_DEVICE_ID1, MULTI_DEVICE_PNI_REG_ID1,
MULTI_DEVICE_ID2, MULTI_DEVICE_PNI_REG_ID2,
MULTI_DEVICE_ID3, MULTI_DEVICE_PNI_REG_ID3),
NONEXISTENT_ACI_ID, Map.of(SINGLE_DEVICE_ID1, SINGLE_DEVICE_REG_ID1),
NONEXISTENT_PNI_ID, Map.of(SINGLE_DEVICE_ID1, SINGLE_DEVICE_PNI_REG_ID1)
);
}
private record MultiRecipientMessageTestCase(
@@ -1275,9 +1274,9 @@ class MessageControllerTest {
return ArgumentSets
.argumentsForFirstParameter(
new MultiRecipientMessageTestCase(singleDeviceAci, unauth, story, 200, 1),
new MultiRecipientMessageTestCase(multiDeviceAci, unauth, story, 200, 2),
new MultiRecipientMessageTestCase(bothAccountsAci, unauth, story, 200, 3),
new MultiRecipientMessageTestCase(realAndFakeAci, unauth, story, 200, 3),
new MultiRecipientMessageTestCase(multiDeviceAci, unauth, story, 200, 3),
new MultiRecipientMessageTestCase(bothAccountsAci, unauth, story, 200, 4),
new MultiRecipientMessageTestCase(realAndFakeAci, unauth, story, 200, 4),
new MultiRecipientMessageTestCase(singleDeviceAci, unauth, notStory, 401, 0),
new MultiRecipientMessageTestCase(multiDeviceAci, unauth, notStory, 401, 0),
@@ -1285,13 +1284,13 @@ class MessageControllerTest {
new MultiRecipientMessageTestCase(realAndFakeAci, unauth, notStory, 404, 0),
new MultiRecipientMessageTestCase(singleDeviceAci, auth, story, 200, 1),
new MultiRecipientMessageTestCase(multiDeviceAci, auth, story, 200, 2),
new MultiRecipientMessageTestCase(bothAccountsAci, auth, story, 200, 3),
new MultiRecipientMessageTestCase(realAndFakeAci, auth, story, 200, 3),
new MultiRecipientMessageTestCase(multiDeviceAci, auth, story, 200, 3),
new MultiRecipientMessageTestCase(bothAccountsAci, auth, story, 200, 4),
new MultiRecipientMessageTestCase(realAndFakeAci, auth, story, 200, 4),
new MultiRecipientMessageTestCase(singleDeviceAci, auth, notStory, 200, 1),
new MultiRecipientMessageTestCase(multiDeviceAci, auth, notStory, 200, 2),
new MultiRecipientMessageTestCase(bothAccountsAci, auth, notStory, 200, 3),
new MultiRecipientMessageTestCase(multiDeviceAci, auth, notStory, 200, 3),
new MultiRecipientMessageTestCase(bothAccountsAci, auth, notStory, 200, 4),
new MultiRecipientMessageTestCase(realAndFakeAci, auth, notStory, 404, 0))
.argumentsForNextParameter(false, true) // urgent
.argumentsForNextParameter(false, true); // explicitIdentifiers
@@ -1328,9 +1327,9 @@ class MessageControllerTest {
.argumentsForFirstParameter(
new MultiRecipientMessageTestCase(singleDevicePni, unauth, story, 200, 1),
new MultiRecipientMessageTestCase(singleDeviceAciAndPni, unauth, story, 200, 2),
new MultiRecipientMessageTestCase(multiDevicePni, unauth, story, 200, 2),
new MultiRecipientMessageTestCase(bothAccountsMixed, unauth, story, 200, 3),
new MultiRecipientMessageTestCase(realAndFakeMixed, unauth, story, 200, 3),
new MultiRecipientMessageTestCase(multiDevicePni, unauth, story, 200, 3),
new MultiRecipientMessageTestCase(bothAccountsMixed, unauth, story, 200, 4),
new MultiRecipientMessageTestCase(realAndFakeMixed, unauth, story, 200, 4),
new MultiRecipientMessageTestCase(singleDevicePni, unauth, notStory, 401, 0),
new MultiRecipientMessageTestCase(singleDeviceAciAndPni, unauth, notStory, 401, 0),
@@ -1340,14 +1339,14 @@ class MessageControllerTest {
new MultiRecipientMessageTestCase(singleDevicePni, auth, story, 200, 1),
new MultiRecipientMessageTestCase(singleDeviceAciAndPni, auth, story, 200, 2),
new MultiRecipientMessageTestCase(multiDevicePni, auth, story, 200, 2),
new MultiRecipientMessageTestCase(bothAccountsMixed, auth, story, 200, 3),
new MultiRecipientMessageTestCase(realAndFakeMixed, auth, story, 200, 3),
new MultiRecipientMessageTestCase(multiDevicePni, auth, story, 200, 3),
new MultiRecipientMessageTestCase(bothAccountsMixed, auth, story, 200, 4),
new MultiRecipientMessageTestCase(realAndFakeMixed, auth, story, 200, 4),
new MultiRecipientMessageTestCase(singleDevicePni, auth, notStory, 200, 1),
new MultiRecipientMessageTestCase(singleDeviceAciAndPni, unauth, story, 200, 2),
new MultiRecipientMessageTestCase(multiDevicePni, auth, notStory, 200, 2),
new MultiRecipientMessageTestCase(bothAccountsMixed, auth, notStory, 200, 3),
new MultiRecipientMessageTestCase(multiDevicePni, auth, notStory, 200, 3),
new MultiRecipientMessageTestCase(bothAccountsMixed, auth, notStory, 200, 4),
new MultiRecipientMessageTestCase(realAndFakeMixed, auth, notStory, 404, 0))
.argumentsForNextParameter(false, true); // urgent
}
@@ -1357,7 +1356,8 @@ class MessageControllerTest {
final List<Recipient> recipients = List.of(
new Recipient(SINGLE_DEVICE_ACI_ID, SINGLE_DEVICE_ID1, SINGLE_DEVICE_REG_ID1, new byte[48]),
new Recipient(MULTI_DEVICE_ACI_ID, MULTI_DEVICE_ID1, MULTI_DEVICE_REG_ID1, new byte[48]),
new Recipient(MULTI_DEVICE_ACI_ID, MULTI_DEVICE_ID2, MULTI_DEVICE_REG_ID2, new byte[48]));
new Recipient(MULTI_DEVICE_ACI_ID, MULTI_DEVICE_ID2, MULTI_DEVICE_REG_ID2, new byte[48]),
new Recipient(MULTI_DEVICE_ACI_ID, MULTI_DEVICE_ID3, MULTI_DEVICE_REG_ID3, new byte[48]));
// initialize our binary payload and create an input stream
byte[] buffer = new byte[2048];
@@ -1380,7 +1380,7 @@ class MessageControllerTest {
assertThat("Unexpected response", response.getStatus(), is(equalTo(200)));
verify(messageSender,
exactly(3))
exactly(4))
.sendMessage(
any(),
any(),
@@ -1529,8 +1529,9 @@ class MessageControllerTest {
Recipient r2 = new Recipient(MULTI_DEVICE_ACI_ID, MULTI_DEVICE_ID1, MULTI_DEVICE_REG_ID1, new byte[48]);
Recipient r3 = new Recipient(MULTI_DEVICE_ACI_ID, MULTI_DEVICE_ID2, MULTI_DEVICE_REG_ID2, new byte[48]);
Recipient r4 = new Recipient(MULTI_DEVICE_ACI_ID, MULTI_DEVICE_ID3, MULTI_DEVICE_REG_ID3, new byte[48]);
List<Recipient> recipients = List.of(r1, r2, r3);
List<Recipient> recipients = List.of(r1, r2, r3, r4);
byte[] buffer = new byte[2048];
InputStream stream = initializeMultiPayload(recipients, buffer, useExplicitIdentifier);
@@ -1637,7 +1638,8 @@ class MessageControllerTest {
void sendMultiRecipientMessageStaleDevices(final ServiceIdentifier serviceIdentifier) throws JsonProcessingException {
final List<Recipient> recipients = List.of(
new Recipient(serviceIdentifier, MULTI_DEVICE_ID1, MULTI_DEVICE_REG_ID1 + 1, new byte[48]),
new Recipient(serviceIdentifier, MULTI_DEVICE_ID2, MULTI_DEVICE_REG_ID2 + 1, new byte[48]));
new Recipient(serviceIdentifier, MULTI_DEVICE_ID2, MULTI_DEVICE_REG_ID2 + 1, new byte[48]),
new Recipient(serviceIdentifier, MULTI_DEVICE_ID3, MULTI_DEVICE_REG_ID3 + 1, new byte[48]));
// initialize our binary payload and create an input stream
byte[] buffer = new byte[2048];
@@ -1670,7 +1672,7 @@ class MessageControllerTest {
assertEquals(1, staleDevices.size());
assertEquals(serviceIdentifier, staleDevices.getFirst().uuid());
assertEquals(Set.of(MULTI_DEVICE_ID1, MULTI_DEVICE_ID2),
assertEquals(Set.of(MULTI_DEVICE_ID1, MULTI_DEVICE_ID2, MULTI_DEVICE_ID3),
new HashSet<>(staleDevices.getFirst().devices().staleDevices()));
}
}
@@ -1681,50 +1683,6 @@ class MessageControllerTest {
Arguments.of(MULTI_DEVICE_PNI_ID));
}
@ParameterizedTest
@MethodSource
void sendMultiRecipientMessage404(final ServiceIdentifier serviceIdentifier, final int regId1, final int regId2)
throws NotPushRegisteredException {
final List<Recipient> recipients = List.of(
new Recipient(serviceIdentifier, MULTI_DEVICE_ID1, regId1, new byte[48]),
new Recipient(serviceIdentifier, MULTI_DEVICE_ID2, regId2, new byte[48]));
// initialize our binary payload and create an input stream
byte[] buffer = new byte[2048];
// InputStream stream = initializeMultiPayload(recipientUUID, buffer);
InputStream stream = initializeMultiPayload(recipients, buffer, true);
// set up the entity to use in our PUT request
Entity<InputStream> entity = Entity.entity(stream, MultiRecipientMessageProvider.MEDIA_TYPE);
// start building the request
final Invocation.Builder invocationBuilder = resources
.getJerseyTest()
.target("/v1/messages/multi_recipient")
.queryParam("online", false)
.queryParam("ts", System.currentTimeMillis())
.queryParam("story", true)
.queryParam("urgent", true)
.request()
.header(HttpHeaders.USER_AGENT, "FIXME")
.header(HeaderUtils.UNIDENTIFIED_ACCESS_KEY, Base64.getEncoder().encodeToString(UNIDENTIFIED_ACCESS_BYTES));
doThrow(NotPushRegisteredException.class)
.when(messageSender).sendMessage(any(), any(), any(), anyBoolean());
// make the PUT request
final SendMultiRecipientMessageResponse response = invocationBuilder.put(entity, SendMultiRecipientMessageResponse.class);
assertEquals(List.of(serviceIdentifier), response.uuids404());
}
private static Stream<Arguments> sendMultiRecipientMessage404() {
return Stream.of(
Arguments.of(MULTI_DEVICE_ACI_ID, MULTI_DEVICE_REG_ID1, MULTI_DEVICE_REG_ID2),
Arguments.of(MULTI_DEVICE_PNI_ID, MULTI_DEVICE_PNI_REG_ID1, MULTI_DEVICE_PNI_REG_ID2));
}
@Test
void sendMultiRecipientMessageStoryRateLimited() {
final List<Recipient> recipients = List.of(new Recipient(SINGLE_DEVICE_ACI_ID, SINGLE_DEVICE_ID1, SINGLE_DEVICE_REG_ID1, new byte[48]));
@@ -489,7 +489,6 @@ class KeysGrpcServiceTest extends SimpleBaseGrpcTest<KeysGrpcService, KeysGrpc.K
final Device device = mock(Device.class);
when(device.getId()).thenReturn(deviceId);
when(device.hasMessageDeliveryChannel()).thenReturn(true);
devices.put(deviceId, device);
when(targetAccount.getDevice(deviceId)).thenReturn(Optional.of(device));
@@ -84,7 +84,7 @@ class APNSenderTest {
assertThat(notification.getValue().getTopic()).isEqualTo(BUNDLE_ID + ".voip");
assertThat(result.accepted()).isTrue();
assertThat(result.errorCode()).isNull();
assertThat(result.errorCode()).isEmpty();
assertThat(result.unregistered()).isFalse();
verifyNoMoreInteractions(apnsClient);
@@ -127,17 +127,18 @@ class APNSenderTest {
}
assertThat(result.accepted()).isTrue();
assertThat(result.errorCode()).isNull();
assertThat(result.errorCode()).isEmpty();
assertThat(result.unregistered()).isFalse();
verifyNoMoreInteractions(apnsClient);
}
@Test
void testUnregisteredUser() {
@ParameterizedTest
@ValueSource(strings = {"Unregistered", "BadDeviceToken", "ExpiredToken"})
void testUnregisteredUser(final String rejectionReason) {
PushNotificationResponse<SimpleApnsPushNotification> response = mock(PushNotificationResponse.class);
when(response.isAccepted()).thenReturn(false);
when(response.getRejectionReason()).thenReturn(Optional.of("Unregistered"));
when(response.getRejectionReason()).thenReturn(Optional.of(rejectionReason));
when(apnsClient.sendNotification(any(SimpleApnsPushNotification.class)))
.thenAnswer(
@@ -160,7 +161,7 @@ class APNSenderTest {
assertThat(notification.getValue().getPriority()).isEqualTo(DeliveryPriority.IMMEDIATE);
assertThat(result.accepted()).isFalse();
assertThat(result.errorCode()).isEqualTo("Unregistered");
assertThat(result.errorCode()).hasValue(rejectionReason);
assertThat(result.unregistered()).isTrue();
}
@@ -188,7 +189,7 @@ class APNSenderTest {
assertThat(notification.getValue().getPriority()).isEqualTo(DeliveryPriority.IMMEDIATE);
assertThat(result.accepted()).isFalse();
assertThat(result.errorCode()).isEqualTo("BadTopic");
assertThat(result.errorCode()).hasValue("BadTopic");
assertThat(result.unregistered()).isFalse();
}
@@ -7,7 +7,6 @@ package org.whispersystems.textsecuregcm.push;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
@@ -21,6 +20,7 @@ import com.google.firebase.messaging.FirebaseMessagingException;
import com.google.firebase.messaging.Message;
import com.google.firebase.messaging.MessagingErrorCode;
import java.io.IOException;
import java.util.Optional;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
@@ -65,7 +65,7 @@ class FcmSenderTest {
verify(firebaseMessaging).sendAsync(any(Message.class));
assertTrue(result.accepted());
assertNull(result.errorCode());
assertTrue(result.errorCode().isEmpty());
assertFalse(result.unregistered());
}
@@ -85,7 +85,7 @@ class FcmSenderTest {
verify(firebaseMessaging).sendAsync(any(Message.class));
assertFalse(result.accepted());
assertEquals("INVALID_ARGUMENT", result.errorCode());
assertEquals(Optional.of("INVALID_ARGUMENT"), result.errorCode());
assertFalse(result.unregistered());
}
@@ -105,7 +105,7 @@ class FcmSenderTest {
verify(firebaseMessaging).sendAsync(any(Message.class));
assertFalse(result.accepted());
assertEquals("UNREGISTERED", result.errorCode());
assertEquals(Optional.of("UNREGISTERED"), result.errorCode());
assertTrue(result.unregistered());
}
@@ -54,10 +54,7 @@ class MessageSenderTest {
clientPresenceManager = mock(ClientPresenceManager.class);
messagesManager = mock(MessagesManager.class);
pushNotificationManager = mock(PushNotificationManager.class);
messageSender = new MessageSender(clientPresenceManager,
messagesManager,
pushNotificationManager,
mock(PushLatencyManager.class));
messageSender = new MessageSender(clientPresenceManager, messagesManager, pushNotificationManager);
when(account.getUuid()).thenReturn(ACCOUNT_UUID);
when(device.getId()).thenReturn(DEVICE_ID);
@@ -142,6 +139,16 @@ class MessageSenderTest {
verify(messagesManager).insert(ACCOUNT_UUID, DEVICE_ID, message);
}
@Test
void testSendMessageNoChannel() {
when(device.getGcmId()).thenReturn(null);
when(device.getApnId()).thenReturn(null);
when(device.getFetchesMessages()).thenReturn(false);
assertDoesNotThrow(() -> messageSender.sendMessage(account, device, message, false));
verify(messagesManager).insert(ACCOUNT_UUID, DEVICE_ID, message);
}
private MessageProtos.Envelope generateRandomMessage() {
return MessageProtos.Envelope.newBuilder()
.setTimestamp(System.currentTimeMillis())
@@ -1,67 +0,0 @@
/*
* Copyright 2013-2022 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.push;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.Mockito.mock;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneId;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.stream.Stream;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.whispersystems.textsecuregcm.push.PushLatencyManager.PushRecord;
import org.whispersystems.textsecuregcm.push.PushLatencyManager.PushType;
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
class PushLatencyManagerTest {
@RegisterExtension
static final RedisClusterExtension REDIS_CLUSTER_EXTENSION = RedisClusterExtension.builder().build();
@ParameterizedTest
@MethodSource
void testTakeRecord(final boolean isVoip, final boolean isUrgent) throws ExecutionException, InterruptedException {
final UUID accountUuid = UUID.randomUUID();
final byte deviceId = 1;
final Instant pushTimestamp = Instant.now();
final PushLatencyManager pushLatencyManager = new PushLatencyManager(REDIS_CLUSTER_EXTENSION.getRedisCluster(),
mock(ClientReleaseManager.class), Clock.fixed(pushTimestamp, ZoneId.systemDefault()));
assertNull(pushLatencyManager.takePushRecord(accountUuid, deviceId).get());
pushLatencyManager.recordPushSent(accountUuid, deviceId, isVoip, isUrgent);
final PushRecord pushRecord = pushLatencyManager.takePushRecord(accountUuid, deviceId).get();
assertNotNull(pushRecord);
assertEquals(pushTimestamp, pushRecord.timestamp());
assertEquals(isVoip ? PushType.VOIP : PushType.STANDARD, pushRecord.pushType());
assertEquals(Optional.of(isUrgent), pushRecord.urgent());
assertNull(pushLatencyManager.takePushRecord(accountUuid, deviceId).get());
}
private static Stream<Arguments> testTakeRecord() {
return Stream.of(
Arguments.of(true, true),
Arguments.of(true, false),
Arguments.of(false, true),
Arguments.of(false, false)
);
}
}
@@ -15,6 +15,7 @@ import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import com.google.common.net.HttpHeaders;
import java.time.Instant;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
@@ -26,7 +27,6 @@ import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.tests.util.AccountsHelper;
import org.whispersystems.textsecuregcm.util.Util;
class PushNotificationManagerTest {
@@ -34,7 +34,6 @@ class PushNotificationManagerTest {
private APNSender apnSender;
private FcmSender fcmSender;
private ApnPushNotificationScheduler apnPushNotificationScheduler;
private PushLatencyManager pushLatencyManager;
private PushNotificationManager pushNotificationManager;
@@ -44,12 +43,11 @@ class PushNotificationManagerTest {
apnSender = mock(APNSender.class);
fcmSender = mock(FcmSender.class);
apnPushNotificationScheduler = mock(ApnPushNotificationScheduler.class);
pushLatencyManager = mock(PushLatencyManager.class);
AccountsHelper.setupMockUpdate(accountsManager);
pushNotificationManager = new PushNotificationManager(accountsManager, apnSender, fcmSender,
apnPushNotificationScheduler, pushLatencyManager);
pushNotificationManager =
new PushNotificationManager(accountsManager, apnSender, fcmSender, apnPushNotificationScheduler);
}
@ParameterizedTest
@@ -65,7 +63,7 @@ class PushNotificationManagerTest {
when(account.getDevice(Device.PRIMARY_ID)).thenReturn(Optional.of(device));
when(fcmSender.sendNotification(any()))
.thenReturn(CompletableFuture.completedFuture(new SendPushNotificationResult(true, null, false)));
.thenReturn(CompletableFuture.completedFuture(new SendPushNotificationResult(true, Optional.empty(), false, Optional.empty())));
pushNotificationManager.sendNewMessageNotification(account, Device.PRIMARY_ID, urgent);
verify(fcmSender).sendNotification(new PushNotification(deviceToken, PushNotification.TokenType.FCM, PushNotification.NotificationType.NOTIFICATION, null, account, device, urgent));
@@ -77,7 +75,7 @@ class PushNotificationManagerTest {
final String challengeToken = "challenge";
when(apnSender.sendNotification(any()))
.thenReturn(CompletableFuture.completedFuture(new SendPushNotificationResult(true, null, false)));
.thenReturn(CompletableFuture.completedFuture(new SendPushNotificationResult(true, Optional.empty(), false, Optional.empty())));
pushNotificationManager.sendRegistrationChallengeNotification(deviceToken, PushNotification.TokenType.APN_VOIP, challengeToken);
verify(apnSender).sendNotification(new PushNotification(deviceToken, PushNotification.TokenType.APN_VOIP, PushNotification.NotificationType.CHALLENGE, challengeToken, null, null, true));
@@ -96,7 +94,7 @@ class PushNotificationManagerTest {
when(account.getPrimaryDevice()).thenReturn(device);
when(apnSender.sendNotification(any()))
.thenReturn(CompletableFuture.completedFuture(new SendPushNotificationResult(true, null, false)));
.thenReturn(CompletableFuture.completedFuture(new SendPushNotificationResult(true, Optional.empty(), false, Optional.empty())));
pushNotificationManager.sendRateLimitChallengeNotification(account, challengeToken);
verify(apnSender).sendNotification(new PushNotification(deviceToken, PushNotification.TokenType.APN, PushNotification.NotificationType.RATE_LIMIT_CHALLENGE, challengeToken, account, device, true));
@@ -114,11 +112,11 @@ class PushNotificationManagerTest {
if (isApn) {
when(device.getApnId()).thenReturn(deviceToken);
when(apnSender.sendNotification(any()))
.thenReturn(CompletableFuture.completedFuture(new SendPushNotificationResult(true, null, false)));
.thenReturn(CompletableFuture.completedFuture(new SendPushNotificationResult(true, Optional.empty(), false, Optional.empty())));
} else {
when(device.getGcmId()).thenReturn(deviceToken);
when(fcmSender.sendNotification(any()))
.thenReturn(CompletableFuture.completedFuture(new SendPushNotificationResult(true, null, false)));
.thenReturn(CompletableFuture.completedFuture(new SendPushNotificationResult(true, Optional.empty(), false, Optional.empty())));
}
when(account.getDevice(Device.PRIMARY_ID)).thenReturn(Optional.of(device));
@@ -146,14 +144,14 @@ class PushNotificationManagerTest {
"token", PushNotification.TokenType.FCM, PushNotification.NotificationType.NOTIFICATION, null, account, device, urgent);
when(fcmSender.sendNotification(pushNotification))
.thenReturn(CompletableFuture.completedFuture(new SendPushNotificationResult(true, null, false)));
.thenReturn(CompletableFuture.completedFuture(new SendPushNotificationResult(true, Optional.empty(), false, Optional.empty())));
pushNotificationManager.sendNotification(pushNotification);
verify(fcmSender).sendNotification(pushNotification);
verifyNoInteractions(apnSender);
verify(accountsManager, never()).updateDevice(eq(account), eq(Device.PRIMARY_ID), any());
verify(device, never()).setUninstalledFeedbackTimestamp(Util.todayInMillis());
verify(device, never()).setGcmId(any());
verifyNoInteractions(apnPushNotificationScheduler);
}
@@ -170,7 +168,7 @@ class PushNotificationManagerTest {
"token", PushNotification.TokenType.APN, PushNotification.NotificationType.NOTIFICATION, null, account, device, urgent);
when(apnSender.sendNotification(pushNotification))
.thenReturn(CompletableFuture.completedFuture(new SendPushNotificationResult(true, null, false)));
.thenReturn(CompletableFuture.completedFuture(new SendPushNotificationResult(true, Optional.empty(), false, Optional.empty())));
if (!urgent) {
when(apnPushNotificationScheduler.scheduleBackgroundNotification(account, device))
@@ -203,7 +201,7 @@ class PushNotificationManagerTest {
"token", PushNotification.TokenType.APN_VOIP, PushNotification.NotificationType.NOTIFICATION, null, account, device, urgent);
when(apnSender.sendNotification(pushNotification))
.thenReturn(CompletableFuture.completedFuture(new SendPushNotificationResult(true, null, false)));
.thenReturn(CompletableFuture.completedFuture(new SendPushNotificationResult(true, Optional.empty(), false, Optional.empty())));
pushNotificationManager.sendNotification(pushNotification);
@@ -211,7 +209,7 @@ class PushNotificationManagerTest {
verifyNoInteractions(fcmSender);
verify(accountsManager, never()).updateDevice(eq(account), eq(Device.PRIMARY_ID), any());
verify(device, never()).setUninstalledFeedbackTimestamp(Util.todayInMillis());
verify(device, never()).setGcmId(any());
verify(apnPushNotificationScheduler).scheduleRecurringVoipNotification(account, device);
verify(apnPushNotificationScheduler, never()).scheduleBackgroundNotification(any(), any());
}
@@ -231,12 +229,12 @@ class PushNotificationManagerTest {
"token", PushNotification.TokenType.FCM, PushNotification.NotificationType.NOTIFICATION, null, account, device, true);
when(fcmSender.sendNotification(pushNotification))
.thenReturn(CompletableFuture.completedFuture(new SendPushNotificationResult(false, null, true)));
.thenReturn(CompletableFuture.completedFuture(new SendPushNotificationResult(false, Optional.empty(), true, Optional.empty())));
pushNotificationManager.sendNotification(pushNotification);
verify(accountsManager).updateDevice(eq(account), eq(Device.PRIMARY_ID), any());
verify(device).setUninstalledFeedbackTimestamp(Util.todayInMillis());
verify(device).setGcmId(null);
verifyNoInteractions(apnSender);
verifyNoInteractions(apnPushNotificationScheduler);
}
@@ -245,15 +243,52 @@ class PushNotificationManagerTest {
void testSendNotificationUnregisteredApn() {
final Account account = mock(Account.class);
final Device device = mock(Device.class);
final UUID aci = UUID.randomUUID();
when(device.getId()).thenReturn(Device.PRIMARY_ID);
when(device.getApnId()).thenReturn("apns-token");
when(device.getVoipApnId()).thenReturn("apns-voip-token");
when(account.getDevice(Device.PRIMARY_ID)).thenReturn(Optional.of(device));
when(account.getUuid()).thenReturn(aci);
when(accountsManager.getByAccountIdentifier(aci)).thenReturn(Optional.of(account));
final PushNotification pushNotification = new PushNotification(
"token", PushNotification.TokenType.APN_VOIP, PushNotification.NotificationType.NOTIFICATION, null, account, device, true);
when(apnSender.sendNotification(pushNotification))
.thenReturn(CompletableFuture.completedFuture(new SendPushNotificationResult(false, null, true)));
.thenReturn(CompletableFuture.completedFuture(new SendPushNotificationResult(false, Optional.empty(), true, Optional.empty())));
when(apnPushNotificationScheduler.cancelScheduledNotifications(account, device))
.thenReturn(CompletableFuture.completedFuture(null));
pushNotificationManager.sendNotification(pushNotification);
verifyNoInteractions(fcmSender);
verify(accountsManager).updateDevice(eq(account), eq(Device.PRIMARY_ID), any());
verify(device).setVoipApnId(null);
verify(device, never()).setApnId(any());
verify(apnPushNotificationScheduler).cancelScheduledNotifications(account, device);
}
@Test
void testSendNotificationUnregisteredApnTokenUpdated() {
final Instant tokenTimestamp = Instant.now();
final Account account = mock(Account.class);
final Device device = mock(Device.class);
final UUID aci = UUID.randomUUID();
when(device.getId()).thenReturn(Device.PRIMARY_ID);
when(device.getApnId()).thenReturn("apns-token");
when(device.getVoipApnId()).thenReturn("apns-voip-token");
when(device.getPushTimestamp()).thenReturn(tokenTimestamp.toEpochMilli());
when(account.getDevice(Device.PRIMARY_ID)).thenReturn(Optional.of(device));
when(account.getUuid()).thenReturn(aci);
when(accountsManager.getByAccountIdentifier(aci)).thenReturn(Optional.of(account));
final PushNotification pushNotification = new PushNotification(
"token", PushNotification.TokenType.APN_VOIP, PushNotification.NotificationType.NOTIFICATION, null, account, device, true);
when(apnSender.sendNotification(pushNotification))
.thenReturn(CompletableFuture.completedFuture(new SendPushNotificationResult(false, Optional.empty(), true, Optional.of(tokenTimestamp.minusSeconds(60)))));
when(apnPushNotificationScheduler.cancelScheduledNotifications(account, device))
.thenReturn(CompletableFuture.completedFuture(null));
@@ -262,8 +297,9 @@ class PushNotificationManagerTest {
verifyNoInteractions(fcmSender);
verify(accountsManager, never()).updateDevice(eq(account), eq(Device.PRIMARY_ID), any());
verify(device, never()).setUninstalledFeedbackTimestamp(Util.todayInMillis());
verify(apnPushNotificationScheduler).cancelScheduledNotifications(account, device);
verify(device, never()).setVoipApnId(any());
verify(device, never()).setApnId(any());
verify(apnPushNotificationScheduler, never()).cancelScheduledNotifications(account, device);
}
@Test
@@ -281,7 +317,6 @@ class PushNotificationManagerTest {
pushNotificationManager.handleMessagesRetrieved(account, device, userAgent);
verify(pushLatencyManager).recordQueueRead(accountIdentifier, Device.PRIMARY_ID, userAgent);
verify(apnPushNotificationScheduler).cancelScheduledNotifications(account, device);
}
}
@@ -0,0 +1,122 @@
package org.whispersystems.textsecuregcm.scheduler;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.whispersystems.textsecuregcm.storage.DynamoDbExtension;
import org.whispersystems.textsecuregcm.storage.DynamoDbExtensionSchema;
import org.whispersystems.textsecuregcm.util.TestClock;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import software.amazon.awssdk.services.dynamodb.model.ConditionalCheckFailedException;
import javax.annotation.Nullable;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneId;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.*;
class JobSchedulerTest {
private static final Instant CURRENT_TIME = Instant.now();
@RegisterExtension
static final DynamoDbExtension DYNAMO_DB_EXTENSION =
new DynamoDbExtension(DynamoDbExtensionSchema.Tables.SCHEDULED_JOBS);
private static class TestJobScheduler extends JobScheduler {
private final AtomicInteger jobsProcessed = new AtomicInteger(0);
protected TestJobScheduler(final DynamoDbAsyncClient dynamoDbAsyncClient,
final String tableName,
final Clock clock) {
super(dynamoDbAsyncClient, tableName, Duration.ofDays(7), clock);
}
@Override
public String getSchedulerName() {
return "test";
}
@Override
protected CompletableFuture<String> processJob(@Nullable final byte[] jobData) {
jobsProcessed.incrementAndGet();
return CompletableFuture.completedFuture("test");
}
}
@Test
void scheduleJob() {
final TestJobScheduler scheduler = new TestJobScheduler(DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(),
DynamoDbExtensionSchema.Tables.SCHEDULED_JOBS.tableName(),
Clock.fixed(CURRENT_TIME, ZoneId.systemDefault()));
assertDoesNotThrow(() ->
scheduler.scheduleJob(scheduler.buildRunAtAttribute(CURRENT_TIME, 0L), CURRENT_TIME, null).join());
final CompletionException completionException = assertThrows(CompletionException.class, () ->
scheduler.scheduleJob(scheduler.buildRunAtAttribute(CURRENT_TIME, 0L), CURRENT_TIME, null).join(),
"Scheduling multiple jobs with identical sort keys should fail");
assertInstanceOf(ConditionalCheckFailedException.class, completionException.getCause());
}
@Test
void processAvailableJobs() {
final TestClock testClock = TestClock.pinned(CURRENT_TIME);
final TestJobScheduler scheduler = new TestJobScheduler(DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(),
DynamoDbExtensionSchema.Tables.SCHEDULED_JOBS.tableName(),
testClock);
scheduler.scheduleJob(scheduler.buildRunAtAttribute(CURRENT_TIME, 0L), CURRENT_TIME, null).join();
// Clock time is before scheduled job time
testClock.pin(CURRENT_TIME.minusMillis(1));
scheduler.processAvailableJobs().join();
assertEquals(0, scheduler.jobsProcessed.get());
// Clock time is after scheduled job time
testClock.pin(CURRENT_TIME.plusMillis(1));
scheduler.processAvailableJobs().join();
assertEquals(1, scheduler.jobsProcessed.get());
scheduler.processAvailableJobs().join();
assertEquals(1, scheduler.jobsProcessed.get(),
"Jobs should be cleared after successful processing; job counter should not increment on second run");
}
@Test
void processAvailableJobsWithError() {
final AtomicInteger jobsEncountered = new AtomicInteger(0);
final TestJobScheduler scheduler = new TestJobScheduler(DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(),
DynamoDbExtensionSchema.Tables.SCHEDULED_JOBS.tableName(),
Clock.fixed(CURRENT_TIME, ZoneId.systemDefault())) {
@Override
protected CompletableFuture<String> processJob(@Nullable final byte[] jobData) {
jobsEncountered.incrementAndGet();
return CompletableFuture.failedFuture(new RuntimeException("OH NO"));
}
};
scheduler.scheduleJob(scheduler.buildRunAtAttribute(CURRENT_TIME, 0L), CURRENT_TIME, null).join();
scheduler.processAvailableJobs().join();
assertEquals(1, jobsEncountered.get());
scheduler.processAvailableJobs().join();
assertEquals(2, jobsEncountered.get(),
"Jobs should not be cleared after failed processing; encountered job counter should increment on second run");
}
}
@@ -0,0 +1,68 @@
package org.whispersystems.textsecuregcm.scheduler;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import java.time.Clock;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import org.junit.jupiter.api.Test;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.Device;
class SchedulingUtilTest {
@Test
void getNextRecommendedNotificationTime() {
{
final Account account = mock(Account.class);
// The account has a phone number that can be resolved to a region with known timezones
when(account.getNumber()).thenReturn(PhoneNumberUtil.getInstance().format(
PhoneNumberUtil.getInstance().getExampleNumber("DE"), PhoneNumberUtil.PhoneNumberFormat.E164));
final ZoneId berlinZoneId = ZoneId.of("Europe/Berlin");
final ZonedDateTime beforeNotificationTime = ZonedDateTime.now(berlinZoneId).with(LocalTime.of(13, 0));
assertEquals(
beforeNotificationTime.with(LocalTime.of(14, 0)).toInstant(),
SchedulingUtil.getNextRecommendedNotificationTime(account, LocalTime.of(14, 0),
Clock.fixed(beforeNotificationTime.toInstant(), berlinZoneId)));
final ZonedDateTime afterNotificationTime = ZonedDateTime.now(berlinZoneId).with(LocalTime.of(15, 0));
assertEquals(
afterNotificationTime.with(LocalTime.of(14, 0)).plusDays(1).toInstant(),
SchedulingUtil.getNextRecommendedNotificationTime(account, LocalTime.of(14, 0),
Clock.fixed(afterNotificationTime.toInstant(), berlinZoneId)));
}
{
final Account account = mock(Account.class);
final Device primaryDevice = mock(Device.class);
// The account does not have a phone number that can be connected to a region/time zone
when(account.getNumber()).thenReturn("Not a parseable number");
when(account.getPrimaryDevice()).thenReturn(primaryDevice);
when(primaryDevice.getCreated())
.thenReturn(ZonedDateTime.of(2024, 7, 10, 9, 53, 12, 0, ZoneId.systemDefault()).toInstant().toEpochMilli());
final ZonedDateTime beforeNotificationTime = ZonedDateTime.now(ZoneId.systemDefault()).with(LocalTime.of(9, 0));
assertEquals(
beforeNotificationTime.with(LocalTime.of(9, 53, 12)).toInstant(),
SchedulingUtil.getNextRecommendedNotificationTime(account, LocalTime.of(14, 0),
Clock.fixed(beforeNotificationTime.toInstant(), ZoneId.systemDefault())));
final ZonedDateTime afterNotificationTime = ZonedDateTime.now(ZoneId.systemDefault()).with(LocalTime.of(10, 0));
assertEquals(
afterNotificationTime.with(LocalTime.of(9, 53, 12)).plusDays(1).toInstant(),
SchedulingUtil.getNextRecommendedNotificationTime(account, LocalTime.of(14, 0),
Clock.fixed(afterNotificationTime.toInstant(), ZoneId.systemDefault())));
}
}
}
@@ -15,7 +15,6 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.whispersystems.textsecuregcm.tests.util.DevicesHelper.createDevice;
import static org.whispersystems.textsecuregcm.tests.util.DevicesHelper.setEnabled;
import com.fasterxml.jackson.annotation.JsonFilter;
import java.lang.annotation.Annotation;
@@ -28,12 +27,8 @@ import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.whispersystems.textsecuregcm.storage.Device.DeviceCapabilities;
import org.whispersystems.textsecuregcm.tests.util.AccountsHelper;
import org.whispersystems.textsecuregcm.util.TestClock;
@@ -55,44 +50,35 @@ class AccountTest {
@BeforeEach
void setup() {
when(oldPrimaryDevice.getLastSeen()).thenReturn(System.currentTimeMillis() - TimeUnit.DAYS.toMillis(366));
when(oldPrimaryDevice.hasMessageDeliveryChannel()).thenReturn(true);
when(oldPrimaryDevice.getId()).thenReturn(Device.PRIMARY_ID);
when(recentPrimaryDevice.getLastSeen()).thenReturn(System.currentTimeMillis() - TimeUnit.DAYS.toMillis(1));
when(recentPrimaryDevice.hasMessageDeliveryChannel()).thenReturn(true);
when(recentPrimaryDevice.getId()).thenReturn(Device.PRIMARY_ID);
when(agingSecondaryDevice.getLastSeen()).thenReturn(System.currentTimeMillis() - TimeUnit.DAYS.toMillis(31));
when(agingSecondaryDevice.hasMessageDeliveryChannel()).thenReturn(false);
final byte deviceId2 = 2;
when(agingSecondaryDevice.getId()).thenReturn(deviceId2);
when(recentSecondaryDevice.getLastSeen()).thenReturn(System.currentTimeMillis() - TimeUnit.DAYS.toMillis(1));
when(recentSecondaryDevice.hasMessageDeliveryChannel()).thenReturn(true);
when(recentSecondaryDevice.getId()).thenReturn(deviceId2);
when(oldSecondaryDevice.getLastSeen()).thenReturn(System.currentTimeMillis() - TimeUnit.DAYS.toMillis(366));
when(oldSecondaryDevice.hasMessageDeliveryChannel()).thenReturn(false);
when(oldSecondaryDevice.getId()).thenReturn(deviceId2);
when(paymentActivationCapableDevice.getCapabilities()).thenReturn(
new DeviceCapabilities(true, true, true, false));
when(paymentActivationCapableDevice.hasMessageDeliveryChannel()).thenReturn(true);
when(paymentActivationIncapableDevice.getCapabilities()).thenReturn(
new DeviceCapabilities(true, true, false, false));
when(paymentActivationIncapableDevice.hasMessageDeliveryChannel()).thenReturn(true);
when(paymentActivationIncapableDeviceWithoutDeliveryChannel.getCapabilities()).thenReturn(
new DeviceCapabilities(true, true, false, false));
when(paymentActivationIncapableDeviceWithoutDeliveryChannel.hasMessageDeliveryChannel()).thenReturn(false);
when(paymentActivationCapableDevice.getCapabilities())
.thenReturn(new DeviceCapabilities(true, true, true, false));
when(deleteSyncCapableDevice.getCapabilities()).thenReturn(
new DeviceCapabilities(true, true, true, true)
);
when(deleteSyncCapableDevice.hasMessageDeliveryChannel()).thenReturn(true);
when(deleteSyncIncapableDevice.getCapabilities()).thenReturn(
new DeviceCapabilities(true, true, true, false)
);
when(deleteSyncIncapableDevice.hasMessageDeliveryChannel()).thenReturn(true);
when(paymentActivationIncapableDevice.getCapabilities())
.thenReturn(new DeviceCapabilities(true, true, false, false));
when(paymentActivationIncapableDeviceWithoutDeliveryChannel.getCapabilities())
.thenReturn(new DeviceCapabilities(true, true, false, false));
when(deleteSyncCapableDevice.getCapabilities())
.thenReturn(new DeviceCapabilities(true, true, true, true));
when(deleteSyncIncapableDevice.getCapabilities())
.thenReturn(new DeviceCapabilities(true, true, true, false));
}
@@ -207,12 +193,6 @@ class AccountTest {
final byte deviceId3 = 3;
assertThat(account.getNextDeviceId()).isEqualTo(deviceId3);
account.addDevice(createDevice(deviceId3));
setEnabled(account.getDevice(deviceId2).orElseThrow(), false);
assertThat(account.getNextDeviceId()).isEqualTo((byte) 4);
account.removeDevice(deviceId2);
assertThat(account.getNextDeviceId()).isEqualTo(deviceId2);
@@ -134,7 +134,6 @@ public class ChangeNumberManagerTest {
when(account.getPhoneNumberIdentifier()).thenReturn(pni);
final Device d2 = mock(Device.class);
when(d2.hasMessageDeliveryChannel()).thenReturn(true);
final byte deviceId2 = 2;
when(d2.getId()).thenReturn(deviceId2);
@@ -181,7 +180,6 @@ public class ChangeNumberManagerTest {
when(account.getPhoneNumberIdentifier()).thenReturn(pni);
final Device d2 = mock(Device.class);
when(d2.hasMessageDeliveryChannel()).thenReturn(true);
final byte deviceId2 = 2;
when(d2.getId()).thenReturn(deviceId2);
@@ -228,7 +226,6 @@ public class ChangeNumberManagerTest {
when(account.getPhoneNumberIdentifier()).thenReturn(pni);
final Device d2 = mock(Device.class);
when(d2.hasMessageDeliveryChannel()).thenReturn(true);
final byte deviceId2 = 2;
when(d2.getId()).thenReturn(deviceId2);
@@ -273,7 +270,6 @@ public class ChangeNumberManagerTest {
when(account.getPhoneNumberIdentifier()).thenReturn(pni);
final Device d2 = mock(Device.class);
when(d2.hasMessageDeliveryChannel()).thenReturn(true);
final byte deviceId2 = 2;
when(d2.getId()).thenReturn(deviceId2);
@@ -316,7 +312,6 @@ public class ChangeNumberManagerTest {
when(account.getPhoneNumberIdentifier()).thenReturn(pni);
final Device d2 = mock(Device.class);
when(d2.hasMessageDeliveryChannel()).thenReturn(true);
final byte deviceId2 = 2;
when(d2.getId()).thenReturn(deviceId2);
@@ -361,7 +356,6 @@ public class ChangeNumberManagerTest {
for (byte i = 1; i <= 3; i++) {
final Device device = mock(Device.class);
when(device.getId()).thenReturn(i);
when(device.hasMessageDeliveryChannel()).thenReturn(true);
when(device.getRegistrationId()).thenReturn((int) i);
devices.add(device);
@@ -400,7 +394,6 @@ public class ChangeNumberManagerTest {
for (byte i = 1; i <= 3; i++) {
final Device device = mock(Device.class);
when(device.getId()).thenReturn(i);
when(device.hasMessageDeliveryChannel()).thenReturn(true);
when(device.getRegistrationId()).thenReturn((int) i);
devices.add(device);
@@ -439,7 +432,6 @@ public class ChangeNumberManagerTest {
for (byte i = 1; i <= 3; i++) {
final Device device = mock(Device.class);
when(device.getId()).thenReturn(i);
when(device.hasMessageDeliveryChannel()).thenReturn(true);
when(device.getRegistrationId()).thenReturn((int) i);
devices.add(device);
@@ -9,35 +9,11 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import java.time.Duration;
import java.time.Instant;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.MethodSource;
class DeviceTest {
@ParameterizedTest
@MethodSource
void testHasMessageDeliveryChannel(final boolean fetchesMessages, final String apnId, final String gcmId, final boolean expectEnabled) {
final Device device = new Device();
device.setFetchesMessages(fetchesMessages);
device.setApnId(apnId);
device.setGcmId(gcmId);
assertEquals(expectEnabled, device.hasMessageDeliveryChannel());
}
private static Stream<Arguments> testHasMessageDeliveryChannel() {
return Stream.of(
Arguments.of(false, null, null, false),
Arguments.of(false, null, "gcm-id", true),
Arguments.of(false, "apn-id", null, true),
Arguments.of(true, null, null, true)
);
}
@ParameterizedTest
@CsvSource({
"true, P1D, false",
@@ -10,6 +10,7 @@ import com.amazonaws.services.dynamodbv2.local.main.ServerRunner;
import com.amazonaws.services.dynamodbv2.local.server.DynamoDBProxyServer;
import java.net.ServerSocket;
import java.net.URI;
import java.time.Duration;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicBoolean;
@@ -161,12 +162,18 @@ public class DynamoDbExtension implements BeforeEachCallback, AfterEachCallback
.region(Region.of("local-test-region"))
.credentialsProvider(StaticCredentialsProvider.create(
AwsBasicCredentials.create("accessKey", "secretKey")))
.overrideConfiguration(builder ->
builder.apiCallTimeout(Duration.ofSeconds(1))
.apiCallAttemptTimeout(Duration.ofSeconds(1)))
.build();
dynamoAsyncDB2 = DynamoDbAsyncClient.builder()
.endpointOverride(URI.create("http://localhost:" + port))
.region(Region.of("local-test-region"))
.credentialsProvider(StaticCredentialsProvider.create(
AwsBasicCredentials.create("accessKey", "secretKey")))
.overrideConfiguration(builder ->
builder.apiCallTimeout(Duration.ofSeconds(1))
.apiCallAttemptTimeout(Duration.ofSeconds(1)))
.build();
}
@@ -8,6 +8,7 @@ package org.whispersystems.textsecuregcm.storage;
import java.util.Collections;
import java.util.List;
import org.whispersystems.textsecuregcm.backup.BackupsDb;
import org.whispersystems.textsecuregcm.scheduler.JobScheduler;
import software.amazon.awssdk.services.dynamodb.model.AttributeDefinition;
import software.amazon.awssdk.services.dynamodb.model.GlobalSecondaryIndex;
import software.amazon.awssdk.services.dynamodb.model.KeySchemaElement;
@@ -298,6 +299,21 @@ public final class DynamoDbExtensionSchema {
.build()),
List.of(), List.of()),
SCHEDULED_JOBS("scheduled_jobs_test",
JobScheduler.KEY_SCHEDULER_NAME,
JobScheduler.ATTR_RUN_AT,
List.of(AttributeDefinition.builder()
.attributeName(JobScheduler.KEY_SCHEDULER_NAME)
.attributeType(ScalarAttributeType.S)
.build(),
AttributeDefinition.builder()
.attributeName(JobScheduler.ATTR_RUN_AT)
.attributeType(ScalarAttributeType.B)
.build()),
List.of(),
List.of()),
SUBSCRIPTIONS("subscriptions_test",
SubscriptionManager.KEY_USER,
null,
@@ -81,8 +81,8 @@ class MessagePersisterTest {
void setUp() throws Exception {
messagesManager = mock(MessagesManager.class);
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager = mock(
DynamicConfigurationManager.class);
@SuppressWarnings("unchecked") final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager =
mock(DynamicConfigurationManager.class);
messagesDynamoDb = mock(MessagesDynamoDb.class);
accountsManager = mock(AccountsManager.class);
@@ -107,6 +107,9 @@ class MessagePersisterTest {
messagePersister = new MessagePersister(messagesCache, messagesManager, accountsManager, clientPresenceManager,
keysManager, dynamicConfigurationManager, PERSIST_DELAY, 1, MoreExecutors.newDirectExecutorService());
when(messagesManager.clear(any(UUID.class), anyByte())).thenReturn(CompletableFuture.completedFuture(null));
when(keysManager.deleteSingleUsePreKeys(any(), anyByte())).thenReturn(CompletableFuture.completedFuture(null));
when(messagesManager.persistMessages(any(UUID.class), any(), any())).thenAnswer(invocation -> {
final UUID destinationUuid = invocation.getArgument(0);
final Device destinationDevice = invocation.getArgument(1);
@@ -258,29 +261,29 @@ class MessagePersisterTest {
final Device primary = mock(Device.class);
when(primary.getId()).thenReturn((byte) 1);
when(primary.isPrimary()).thenReturn(true);
when(primary.hasMessageDeliveryChannel()).thenReturn(true);
when(primary.getFetchesMessages()).thenReturn(true);
final Device activeA = mock(Device.class);
when(activeA.getId()).thenReturn((byte) 2);
when(activeA.hasMessageDeliveryChannel()).thenReturn(true);
when(activeA.getFetchesMessages()).thenReturn(true);
final Device inactiveB = mock(Device.class);
final byte inactiveId = 3;
when(inactiveB.getId()).thenReturn(inactiveId);
when(inactiveB.hasMessageDeliveryChannel()).thenReturn(false);
final Device inactiveC = mock(Device.class);
when(inactiveC.getId()).thenReturn((byte) 4);
when(inactiveC.hasMessageDeliveryChannel()).thenReturn(false);
final Device activeD = mock(Device.class);
when(activeD.getId()).thenReturn((byte) 5);
when(activeD.hasMessageDeliveryChannel()).thenReturn(true);
when(activeD.getFetchesMessages()).thenReturn(true);
final Device destination = mock(Device.class);
when(destination.getId()).thenReturn(DESTINATION_DEVICE_ID);
when(destination.hasMessageDeliveryChannel()).thenReturn(true);
when(destinationAccount.getDevices()).thenReturn(List.of(primary, activeA, inactiveB, inactiveC, activeD, destination));
when(messagesManager.persistMessages(any(UUID.class), any(), anyList())).thenThrow(ItemCollectionSizeLimitExceededException.builder().build());
when(messagesManager.clear(any(UUID.class), anyByte())).thenReturn(CompletableFuture.completedFuture(null));
when(keysManager.deleteSingleUsePreKeys(any(), eq(inactiveId))).thenReturn(CompletableFuture.completedFuture(null));
assertTimeoutPreemptively(Duration.ofSeconds(1), () ->
messagePersister.persistQueue(destinationAccount, DESTINATION_DEVICE));
@@ -302,27 +305,27 @@ class MessagePersisterTest {
final byte primaryId = 1;
when(primary.getId()).thenReturn(primaryId);
when(primary.isPrimary()).thenReturn(true);
when(primary.hasMessageDeliveryChannel()).thenReturn(true);
when(primary.getFetchesMessages()).thenReturn(true);
when(messagesManager.getEarliestUndeliveredTimestampForDevice(any(), eq(primary)))
.thenReturn(Mono.just(4L));
final Device deviceA = mock(Device.class);
final byte deviceIdA = 2;
when(deviceA.getId()).thenReturn(deviceIdA);
when(deviceA.hasMessageDeliveryChannel()).thenReturn(true);
when(deviceA.getFetchesMessages()).thenReturn(true);
when(messagesManager.getEarliestUndeliveredTimestampForDevice(any(), eq(deviceA)))
.thenReturn(Mono.empty());
final Device deviceB = mock(Device.class);
final byte deviceIdB = 3;
when(deviceB.getId()).thenReturn(deviceIdB);
when(deviceB.hasMessageDeliveryChannel()).thenReturn(true);
when(deviceB.getFetchesMessages()).thenReturn(true);
when(messagesManager.getEarliestUndeliveredTimestampForDevice(any(), eq(deviceB)))
.thenReturn(Mono.just(2L));
final Device destination = mock(Device.class);
when(destination.getId()).thenReturn(DESTINATION_DEVICE_ID);
when(destination.hasMessageDeliveryChannel()).thenReturn(true);
when(destination.getFetchesMessages()).thenReturn(true);
when(messagesManager.getEarliestUndeliveredTimestampForDevice(any(), eq(destination)))
.thenReturn(Mono.just(5L));
@@ -352,27 +355,27 @@ class MessagePersisterTest {
final byte primaryId = 1;
when(primary.getId()).thenReturn(primaryId);
when(primary.isPrimary()).thenReturn(true);
when(primary.hasMessageDeliveryChannel()).thenReturn(true);
when(primary.getFetchesMessages()).thenReturn(true);
when(messagesManager.getEarliestUndeliveredTimestampForDevice(any(), eq(primary)))
.thenReturn(Mono.just(1L));
final Device deviceA = mock(Device.class);
final byte deviceIdA = 2;
when(deviceA.getId()).thenReturn(deviceIdA);
when(deviceA.hasMessageDeliveryChannel()).thenReturn(true);
when(deviceA.getFetchesMessages()).thenReturn(true);
when(messagesManager.getEarliestUndeliveredTimestampForDevice(any(), eq(deviceA)))
.thenReturn(Mono.just(3L));
final Device deviceB = mock(Device.class);
final byte deviceIdB = 2;
when(deviceB.getId()).thenReturn(deviceIdB);
when(deviceB.hasMessageDeliveryChannel()).thenReturn(true);
when(deviceB.getFetchesMessages()).thenReturn(true);
when(messagesManager.getEarliestUndeliveredTimestampForDevice(any(), eq(deviceB)))
.thenReturn(Mono.empty());
final Device destination = mock(Device.class);
when(destination.getId()).thenReturn(DESTINATION_DEVICE_ID);
when(destination.hasMessageDeliveryChannel()).thenReturn(true);
when(destination.getFetchesMessages()).thenReturn(true);
when(messagesManager.getEarliestUndeliveredTimestampForDevice(any(), eq(destination)))
.thenReturn(Mono.just(2L));
@@ -138,11 +138,7 @@ public class AuthHelper {
when(VALID_DEVICE_3_PRIMARY.getId()).thenReturn(Device.PRIMARY_ID);
when(VALID_DEVICE_3_LINKED.getId()).thenReturn((byte) 2);
when(VALID_DEVICE.hasMessageDeliveryChannel()).thenReturn(true);
when(VALID_DEVICE_TWO.hasMessageDeliveryChannel()).thenReturn(true);
when(UNDISCOVERABLE_DEVICE.isPrimary()).thenReturn(true);
when(VALID_DEVICE_3_PRIMARY.hasMessageDeliveryChannel()).thenReturn(true);
when(VALID_DEVICE_3_LINKED.hasMessageDeliveryChannel()).thenReturn(true);
when(VALID_ACCOUNT.getDevice(Device.PRIMARY_ID)).thenReturn(Optional.of(VALID_DEVICE));
when(VALID_ACCOUNT.getPrimaryDevice()).thenReturn(VALID_DEVICE);
@@ -272,7 +268,6 @@ public class AuthHelper {
when(device.getAuthTokenHash()).thenReturn(saltedTokenHash);
when(device.isPrimary()).thenReturn(true);
when(device.getId()).thenReturn(Device.PRIMARY_ID);
when(device.hasMessageDeliveryChannel()).thenReturn(true);
when(account.getDevice(Device.PRIMARY_ID)).thenReturn(Optional.of(device));
when(account.getPrimaryDevice()).thenReturn(device);
when(account.getNumber()).thenReturn(number);
@@ -27,8 +27,6 @@ public class DevicesHelper {
device.setUserAgent("OWT");
device.setRegistrationId(registrationId);
setEnabled(device, true);
return device;
}
@@ -38,20 +36,6 @@ public class DevicesHelper {
device.setUserAgent("OWT");
device.setRegistrationId(registrationId);
setEnabled(device, false);
return device;
}
public static void setEnabled(Device device, boolean enabled) {
if (enabled) {
device.setGcmId("testGcmId" + RANDOM.nextLong());
} else {
device.setGcmId(null);
}
// fail fast, to guard against a change to the isEnabled() implementation causing unexpected test behavior
assert enabled == device.hasMessageDeliveryChannel();
}
}
@@ -107,7 +107,6 @@ class DestinationDeviceValidatorTest {
enabledStateByDeviceId.forEach((deviceId, enabled) -> {
final Device device = mock(Device.class);
when(device.hasMessageDeliveryChannel()).thenReturn(enabled);
when(device.getId()).thenReturn(deviceId);
when(account.getDevice(deviceId)).thenReturn(Optional.of(device));
@@ -123,18 +122,21 @@ class DestinationDeviceValidatorTest {
final byte id1 = 1;
final byte id2 = 2;
final byte id3 = 3;
final Account account = mockAccountWithDeviceAndEnabled(Map.of(id1, true, id2, false, id3, true));
return Stream.of(
// Device IDs provided for all enabled devices
arguments(
mockAccountWithDeviceAndEnabled(Map.of(id1, true, id2, false, id3, true)),
account,
Set.of(id1, id3),
null,
Set.of(id2),
null,
Collections.emptySet()),
// Device ID provided for disabled device
arguments(
mockAccountWithDeviceAndEnabled(Map.of(id1, true, id2, false, id3, true)),
account,
Set.of(id1, id2, id3),
null,
null,
@@ -142,15 +144,15 @@ class DestinationDeviceValidatorTest {
// Device ID omitted for enabled device
arguments(
mockAccountWithDeviceAndEnabled(Map.of(id1, true, id2, false, id3, true)),
account,
Set.of(id1),
Set.of(id3),
Set.of(id2, id3),
null,
Collections.emptySet()),
// Device ID included for disabled device, omitted for enabled device
arguments(
mockAccountWithDeviceAndEnabled(Map.of(id1, true, id2, false, id3, true)),
account,
Set.of(id1, id2),
Set.of(id3),
null,
@@ -158,16 +160,16 @@ class DestinationDeviceValidatorTest {
// Device ID omitted for enabled device, included for device in excluded list
arguments(
mockAccountWithDeviceAndEnabled(Map.of(id1, true, id2, false, id3, true)),
account,
Set.of(id1),
Set.of(id3),
Set.of(id2, id3),
Set.of(id1),
Set.of(id1)
),
// Device ID omitted for enabled device, included for disabled device, omitted for excluded device
arguments(
mockAccountWithDeviceAndEnabled(Map.of(id1, true, id2, false, id3, true)),
account,
Set.of(id2),
Set.of(id3),
null,
@@ -176,9 +178,9 @@ class DestinationDeviceValidatorTest {
// Device ID included for enabled device, omitted for excluded device
arguments(
mockAccountWithDeviceAndEnabled(Map.of(id1, true, id2, false, id3, true)),
account,
Set.of(id3),
null,
Set.of(id2),
null,
Set.of(id1)
)
@@ -1,277 +0,0 @@
/*
* Copyright 2023 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.workers;
import net.sourceforge.argparse4j.inf.Namespace;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
import reactor.core.publisher.Flux;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class ProcessPushNotificationFeedbackCommandTest {
private AccountsManager accountsManager;
private Clock clock;
private ProcessPushNotificationFeedbackCommand processPushNotificationFeedbackCommand;
private static final Instant CURRENT_TIME = Instant.now();
private static class TestProcessPushNotificationFeedbackCommand extends ProcessPushNotificationFeedbackCommand {
private final CommandDependencies commandDependencies;
private final Namespace namespace;
public TestProcessPushNotificationFeedbackCommand(final Clock clock, final AccountsManager accountsManager, final boolean isDryRun) {
super(clock);
commandDependencies = mock(CommandDependencies.class);
when(commandDependencies.accountsManager()).thenReturn(accountsManager);
namespace = mock(Namespace.class);
when(namespace.getBoolean(RemoveExpiredAccountsCommand.DRY_RUN_ARGUMENT)).thenReturn(isDryRun);
}
@Override
protected CommandDependencies getCommandDependencies() {
return commandDependencies;
}
@Override
protected Namespace getNamespace() {
return namespace;
}
}
@BeforeEach
void setUpBeforeEach() {
accountsManager = mock(AccountsManager.class);
when(accountsManager.updateAsync(any(), any()))
.thenAnswer(invocation -> {
final Account account = invocation.getArgument(0);
final Consumer<Account> accountUpdater = invocation.getArgument(1);
accountUpdater.accept(account);
return CompletableFuture.completedFuture(account);
});
clock = Clock.fixed(CURRENT_TIME, ZoneId.systemDefault());
processPushNotificationFeedbackCommand =
new TestProcessPushNotificationFeedbackCommand(clock, accountsManager, true);
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void crawlAccounts(final boolean isDryRun) {
processPushNotificationFeedbackCommand =
new TestProcessPushNotificationFeedbackCommand(clock, accountsManager, isDryRun);
final Account accountWithActiveDevice = mock(Account.class);
{
final Device device = mock(Device.class);
when(device.hasMessageDeliveryChannel()).thenReturn(true);
when(accountWithActiveDevice.getDevices()).thenReturn(List.of(device));
}
final Account accountWithUninstalledDevice = mock(Account.class);
{
final Device uninstalledDevice = mock(Device.class);
when(uninstalledDevice.hasMessageDeliveryChannel()).thenReturn(true);
when(uninstalledDevice.getUninstalledFeedbackTimestamp())
.thenReturn(clock.instant().minus(ProcessPushNotificationFeedbackCommand.MAX_TOKEN_REFRESH_DELAY.multipliedBy(2)).toEpochMilli());
when(accountWithUninstalledDevice.getDevices()).thenReturn(List.of(uninstalledDevice));
}
final Account accountWithAlreadyDisabledUninstalledDevice = mock(Account.class);
{
final Device previouslyDisabledUninstalledDevice = mock(Device.class);
when(previouslyDisabledUninstalledDevice.hasMessageDeliveryChannel()).thenReturn(false);
when(previouslyDisabledUninstalledDevice.getUninstalledFeedbackTimestamp())
.thenReturn(clock.instant().minus(ProcessPushNotificationFeedbackCommand.MAX_TOKEN_REFRESH_DELAY.multipliedBy(2)).toEpochMilli());
when(accountWithAlreadyDisabledUninstalledDevice.getDevices()).thenReturn(List.of(previouslyDisabledUninstalledDevice));
}
processPushNotificationFeedbackCommand.crawlAccounts(
Flux.just(accountWithActiveDevice, accountWithUninstalledDevice, accountWithAlreadyDisabledUninstalledDevice));
if (isDryRun) {
verify(accountsManager, never()).updateAsync(any(), any());
} else {
verify(accountsManager, never()).updateAsync(eq(accountWithActiveDevice), any());
verify(accountsManager).updateAsync(eq(accountWithUninstalledDevice), any());
verify(accountsManager, never()).updateAsync(eq(accountWithAlreadyDisabledUninstalledDevice), any());
}
}
@Test
void pushFeedbackIntervalElapsed() {
{
final Device deviceWithMaturePushNotificationFeedback = mock(Device.class);
when(deviceWithMaturePushNotificationFeedback.getUninstalledFeedbackTimestamp())
.thenReturn(clock.instant().minus(ProcessPushNotificationFeedbackCommand.MAX_TOKEN_REFRESH_DELAY.multipliedBy(2)).toEpochMilli());
assertTrue(processPushNotificationFeedbackCommand.pushFeedbackIntervalElapsed(deviceWithMaturePushNotificationFeedback));
}
{
final Device deviceWithRecentPushNotificationFeedback = mock(Device.class);
when(deviceWithRecentPushNotificationFeedback.getUninstalledFeedbackTimestamp())
.thenReturn(clock.instant().minus(ProcessPushNotificationFeedbackCommand.MAX_TOKEN_REFRESH_DELAY.dividedBy(2)).toEpochMilli());
assertFalse(processPushNotificationFeedbackCommand.pushFeedbackIntervalElapsed(deviceWithRecentPushNotificationFeedback));
}
{
final Device deviceWithoutPushNotificationFeedback = mock(Device.class);
assertFalse(processPushNotificationFeedbackCommand.pushFeedbackIntervalElapsed(deviceWithoutPushNotificationFeedback));
}
}
@Test
void deviceExpired() {
{
final Device expiredDevice = mock(Device.class);
when(expiredDevice.getLastSeen())
.thenReturn(
clock.instant().minus(ProcessPushNotificationFeedbackCommand.MAX_TOKEN_REFRESH_DELAY.multipliedBy(2))
.toEpochMilli());
assertTrue(processPushNotificationFeedbackCommand.deviceExpired(expiredDevice));
}
{
final Device activeDevice = mock(Device.class);
when(activeDevice.getLastSeen()).thenReturn(clock.instant().toEpochMilli());
assertFalse(processPushNotificationFeedbackCommand.deviceExpired(activeDevice));
}
}
@ParameterizedTest
@MethodSource
void deviceNeedsUpdate(final Device device, final boolean expectNeedsUpdate) {
assertEquals(expectNeedsUpdate, processPushNotificationFeedbackCommand.deviceNeedsUpdate(device));
}
private static List<Arguments> deviceNeedsUpdate() {
final long maturePushFeedbackTimestamp =
CURRENT_TIME.minus(ProcessPushNotificationFeedbackCommand.MAX_TOKEN_REFRESH_DELAY.multipliedBy(2))
.toEpochMilli();
final List<Arguments> arguments = new ArrayList<>();
{
// Device is active, enabled, and has no push feedback
final Device device = mock(Device.class);
when(device.hasMessageDeliveryChannel()).thenReturn(true);
when(device.getUninstalledFeedbackTimestamp()).thenReturn(0L);
when(device.getLastSeen()).thenReturn(CURRENT_TIME.toEpochMilli());
arguments.add(Arguments.of(device, false));
}
{
// Device is active, but not enabled, and has no push feedback
final Device device = mock(Device.class);
when(device.hasMessageDeliveryChannel()).thenReturn(false);
when(device.getUninstalledFeedbackTimestamp()).thenReturn(0L);
when(device.getLastSeen()).thenReturn(CURRENT_TIME.toEpochMilli());
arguments.add(Arguments.of(device, false));
}
{
// Device is active, enabled, and has "mature" push feedback
final Device device = mock(Device.class);
when(device.hasMessageDeliveryChannel()).thenReturn(true);
when(device.getUninstalledFeedbackTimestamp()).thenReturn(maturePushFeedbackTimestamp);
when(device.getLastSeen()).thenReturn(CURRENT_TIME.toEpochMilli());
arguments.add(Arguments.of(device, true));
}
{
// Device is active, but not enabled, and has "mature" push feedback
final Device device = mock(Device.class);
when(device.hasMessageDeliveryChannel()).thenReturn(false);
when(device.getUninstalledFeedbackTimestamp()).thenReturn(maturePushFeedbackTimestamp);
when(device.getLastSeen()).thenReturn(CURRENT_TIME.toEpochMilli());
arguments.add(Arguments.of(device, true));
}
{
// Device is inactive, not enabled, and has "mature" push feedback
final Device device = mock(Device.class);
when(device.hasMessageDeliveryChannel()).thenReturn(false);
when(device.getUninstalledFeedbackTimestamp()).thenReturn(maturePushFeedbackTimestamp);
when(device.getLastSeen()).thenReturn(maturePushFeedbackTimestamp);
arguments.add(Arguments.of(device, false));
}
return arguments;
}
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
@ParameterizedTest
@MethodSource
void getUserAgent(final Device device, final Optional<String> expectedUserAgentString) {
assertEquals(expectedUserAgentString, ProcessPushNotificationFeedbackCommand.getUserAgent(device));
}
private static List<Arguments> getUserAgent() {
final Device iosPrimaryDevice = mock(Device.class);
when(iosPrimaryDevice.isPrimary()).thenReturn(true);
when(iosPrimaryDevice.getApnId()).thenReturn("apns-token");
final Device iosLinkedDevice = mock(Device.class);
when(iosLinkedDevice.isPrimary()).thenReturn(false);
when(iosLinkedDevice.getApnId()).thenReturn("apns-token");
final Device androidDevice = mock(Device.class);
when(androidDevice.getGcmId()).thenReturn("gcm-id");
final Device deviceWithoutTokens = mock(Device.class);
return List.of(
Arguments.of(iosPrimaryDevice, Optional.of("OWI")),
Arguments.of(iosLinkedDevice, Optional.of("OWP")),
Arguments.of(androidDevice, Optional.of("OWA")),
Arguments.of(deviceWithoutTokens, Optional.empty())
);
}
}
@@ -120,6 +120,9 @@ dynamoDbTables:
tableName: remote_config_test
reportMessage:
tableName: report_messages_test
scheduledJobs:
tableName: scheduled_jobs_test
expiration: P7D
subscriptions:
tableName: subscriptions_test
clientPublicKeys:
@@ -12,5 +12,12 @@
"destinationRegistrationId" : 333,
"content" : "Zm9vYmFyego",
"timestamp" : 1234
}]
},
{
"type" : 1,
"destinationDeviceId" : 3,
"destinationRegistrationId" : 444,
"content" : "Zm9vYmFyego",
"timestamp" : 1234
}]
}
@@ -14,6 +14,13 @@
"destinationRegistrationId": 333,
"content": "Zm9vYmFyego",
"timestamp": 1234
},
{
"type": 1,
"destinationDeviceId": 3,
"destinationRegistrationId": 444,
"content": "Zm9vYmFyego",
"timestamp": 1234
}
]
}
@@ -12,5 +12,12 @@
"destinationRegistrationId" : 3333,
"content" : "Zm9vYmFyego",
"timestamp" : 1234
}]
},
{
"type" : 1,
"destinationDeviceId" : 3,
"destinationRegistrationId" : 4444,
"content" : "Zm9vYmFyego",
"timestamp" : 1234
}]
}
@@ -12,5 +12,12 @@
"destinationRegistrationId" : 999,
"content" : "Zm9vYmFyego",
"timestamp" : 1234
}]
},
{
"type" : 1,
"destinationDeviceId" : 3,
"destinationRegistrationId" : 444,
"content" : "Zm9vYmFyego",
"timestamp" : 1234
}]
}
@@ -1,4 +1,4 @@
{
"missingDevices" : [2],
"missingDevices" : [2, 3],
"extraDevices" : []
}
}