Allow differing TTLs by notification type

This commit is contained in:
Jon Chambers authored and Jon Chambers committed 2026-05-20 12:20:00 -04:00
1 parent 539a84d0d0
commit 51f6e57bbd
10 files changed
+71 -36

No files matched your search

@@ -719,7 +719,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
registrationRecoveryPasswordsManager, accountLockExecutor, messagePollExecutor,
retryExecutor, clock, config.getLinkDeviceSecretConfiguration().secret().value());
RemoteConfigsManager remoteConfigsManager = new RemoteConfigsManager(remoteConfigs);
APNSender apnSender = new APNSender(apnSenderExecutor, config.getApnConfiguration());
APNSender apnSender = new APNSender(apnSenderExecutor, Clock.systemUTC(), config.getApnConfiguration());
FcmSender fcmSender = new FcmSender(fcmSenderExecutor, config.getFcmConfiguration().credentials().value());
PushNotificationScheduler pushNotificationScheduler = new PushNotificationScheduler(pushSchedulerCluster,
apnSender, fcmSender, accountsManager, 0, 0, retryExecutor);
@@ -21,6 +21,7 @@ import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.Optional;
@@ -31,6 +32,8 @@ import org.whispersystems.textsecuregcm.configuration.ApnConfiguration;
public class APNSender implements Managed, PushNotificationSender {
private final ExecutorService executor;
private final Clock clock;
private final String bundleId;
private final ApnsClient apnsClient;
@@ -45,17 +48,19 @@ public class APNSender implements Managed, PushNotificationSender {
.setContentAvailable(true)
.build();
// See https://developer.apple.com/documentation/usernotifications/sending-notification-requests-to-apns
@VisibleForTesting
static final Instant MAX_EXPIRATION = Instant.ofEpochMilli(Integer.MAX_VALUE * 1000L);
static final Duration DEFAULT_TTL = Duration.ofDays(30);
private static final String APNS_CA_FILENAME = "apns-certificates.pem";
private static final Timer SEND_NOTIFICATION_TIMER = Metrics.timer(name(APNSender.class, "sendNotification"));
public APNSender(ExecutorService executor, ApnConfiguration configuration)
public APNSender(final ExecutorService executor, final Clock clock, final ApnConfiguration configuration)
throws IOException, NoSuchAlgorithmException, InvalidKeyException
{
this.executor = executor;
this.clock = clock;
this.bundleId = configuration.bundleId();
this.apnsClient = new ApnsClientBuilder().setSigningKey(
ApnsSigningKey.loadFromInputStream(new ByteArrayInputStream(configuration.signingKey().value().getBytes()),
@@ -66,8 +71,9 @@ public class APNSender implements Managed, PushNotificationSender {
}
@VisibleForTesting
public APNSender(ExecutorService executor, ApnsClient apnsClient, String bundleId) {
public APNSender(final ExecutorService executor, final ApnsClient apnsClient, final String bundleId, final Clock clock) {
this.executor = executor;
this.clock = clock;
this.apnsClient = apnsClient;
this.bundleId = bundleId;
}
@@ -117,7 +123,7 @@ public class APNSender implements Managed, PushNotificationSender {
return apnsClient.sendNotification(new SimpleApnsPushNotification(notification.deviceToken(),
bundleId,
payload,
MAX_EXPIRATION,
clock.instant().plus(notification.ttl() != null ? notification.ttl() : DEFAULT_TTL),
deliveryPriority,
pushType,
collapseId))
@@ -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.time.Duration;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
@@ -37,6 +38,9 @@ public class FcmSender implements PushNotificationSender {
private final ExecutorService executor;
private final FirebaseMessaging firebaseMessagingClient;
// See https://firebase.google.com/docs/cloud-messaging/customize-messages/setting-message-lifespan
private static final long DEFAULT_TTL_MILLIS = Duration.ofDays(28).toMillis();
private static final Timer SEND_NOTIFICATION_TIMER = Metrics.timer(name(FcmSender.class, "sendNotification"));
private static final Logger logger = LoggerFactory.getLogger(FcmSender.class);
@@ -82,6 +86,7 @@ public class FcmSender implements PushNotificationSender {
.setToken(pushNotification.deviceToken())
.setAndroidConfig(AndroidConfig.builder()
.setPriority(pushNotification.urgent() ? AndroidConfig.Priority.HIGH : AndroidConfig.Priority.NORMAL)
.setTtl(pushNotification.ttl() != null ? pushNotification.ttl().toMillis() : DEFAULT_TTL_MILLIS)
.build());
final String key = switch (pushNotification.notificationType()) {
@@ -5,9 +5,10 @@
package org.whispersystems.textsecuregcm.push;
import java.time.Duration;
import javax.annotation.Nullable;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.Device;
import javax.annotation.Nullable;
public record PushNotification(String deviceToken,
TokenType tokenType,
@@ -15,7 +16,14 @@ public record PushNotification(String deviceToken,
@Nullable Object data,
@Nullable Account destination,
@Nullable Device destinationDevice,
boolean urgent) {
boolean urgent,
@Nullable Duration ttl) {
// APNs allows up to 30 days, but FCM allows a max of 28. See:
//
// - https://developer.apple.com/documentation/usernotifications/sending-notification-requests-to-apns
// - https://firebase.google.com/docs/cloud-messaging/customize-messages/setting-message-lifespan
private static final Duration MAX_TTL = Duration.ofDays(28);
public enum NotificationType {
NOTIFICATION,
@@ -28,4 +36,10 @@ public record PushNotification(String deviceToken,
FCM,
APN
}
public PushNotification {
if (ttl != null && ttl.compareTo(MAX_TTL) > 0) {
throw new IllegalArgumentException("TTL must not be longer than " + MAX_TTL);
}
}
}
@@ -52,11 +52,12 @@ public class PushNotificationManager {
final Pair<String, PushNotification.TokenType> tokenAndType = getToken(device);
return sendNotification(new PushNotification(tokenAndType.first(), tokenAndType.second(),
PushNotification.NotificationType.NOTIFICATION, null, destination, device, urgent));
PushNotification.NotificationType.NOTIFICATION, null, destination, device, urgent, null));
}
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))
return sendNotification(new PushNotification(deviceToken, tokenType, PushNotification.NotificationType.CHALLENGE, challengeToken, null, null, true,
null))
.thenApply(maybeResponse -> maybeResponse.orElseThrow(() -> new AssertionError("Responses must be present for urgent notifications")));
}
@@ -67,7 +68,7 @@ public class PushNotificationManager {
final Pair<String, PushNotification.TokenType> tokenAndType = getToken(device);
return sendNotification(new PushNotification(tokenAndType.first(), tokenAndType.second(),
PushNotification.NotificationType.RATE_LIMIT_CHALLENGE, challengeToken, destination, device, true))
PushNotification.NotificationType.RATE_LIMIT_CHALLENGE, challengeToken, destination, device, true, null))
.thenApply(maybeResponse -> maybeResponse.orElseThrow(() -> new AssertionError("Responses must be present for urgent notifications")));
}
@@ -77,7 +78,7 @@ public class PushNotificationManager {
return sendNotification(new PushNotification(tokenAndType.first(), tokenAndType.second(),
PushNotification.NotificationType.ATTEMPT_LOGIN_NOTIFICATION_HIGH_PRIORITY,
context, destination, device, true))
context, destination, device, true, null))
.thenApply(maybeResponse -> maybeResponse.orElseThrow(() -> new AssertionError("Responses must be present for urgent notifications")));
}
@@ -311,7 +311,7 @@ public class PushNotificationScheduler implements Managed {
return pushSchedulingCluster.withCluster(connection -> connection.async().set(
getLastBackgroundNotificationTimestampKey(account, device),
String.valueOf(clock.millis()), new SetArgs().ex(BACKGROUND_NOTIFICATION_PERIOD)))
.thenCompose(ignored -> sender.sendNotification(new PushNotification(pushToken, tokenType, PushNotification.NotificationType.NOTIFICATION, null, account, device, false)))
.thenCompose(ignored -> sender.sendNotification(new PushNotification(pushToken, tokenType, PushNotification.NotificationType.NOTIFICATION, null, account, device, false, null)))
.thenAccept(response -> Metrics.counter(BACKGROUND_NOTIFICATION_SENT_COUNTER_NAME,
ACCEPTED_TAG, String.valueOf(response.accepted()))
.increment())
@@ -333,7 +333,7 @@ public class PushNotificationScheduler implements Managed {
null,
account,
device,
true);
true, null);
final PushNotificationSender pushNotificationSender = isApnsDevice ? apnSender : fcmSender;
@@ -349,7 +349,7 @@ public record CommandDependencies(
zkReceiptOperations,
issuedReceiptsManager);
APNSender apnSender = new APNSender(apnSenderExecutor, configuration.getApnConfiguration());
APNSender apnSender = new APNSender(apnSenderExecutor, Clock.systemUTC(), configuration.getApnConfiguration());
FcmSender fcmSender = new FcmSender(fcmSenderExecutor, configuration.getFcmConfiguration().credentials().value());
PushNotificationScheduler pushNotificationScheduler = new PushNotificationScheduler(pushSchedulerCluster,
apnSender, fcmSender, accountsManager, 0, 0, retryExecutor);
@@ -21,6 +21,8 @@ import com.eatthepath.pushy.apns.PushType;
import com.eatthepath.pushy.apns.util.SimpleApnsPushNotification;
import com.eatthepath.pushy.apns.util.concurrent.PushNotificationFuture;
import java.io.IOException;
import java.time.Clock;
import java.time.Instant;
import java.util.Optional;
import java.util.concurrent.CompletionException;
import java.util.concurrent.TimeUnit;
@@ -34,12 +36,15 @@ import org.mockito.stubbing.Answer;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.tests.util.SynchronousExecutorService;
import org.whispersystems.textsecuregcm.util.TestClock;
class APNSenderTest {
private static final String DESTINATION_DEVICE_TOKEN = RandomStringUtils.secure().nextAlphanumeric(32);
private static final String BUNDLE_ID = "org.signal.test";
private static final Clock CLOCK = TestClock.pinned(Instant.now());
private Account destinationAccount;
private Device destinationDevice;
@@ -52,7 +57,7 @@ class APNSenderTest {
destinationDevice = mock(Device.class);
apnsClient = mock(ApnsClient.class);
apnSender = new APNSender(new SynchronousExecutorService(), apnsClient, BUNDLE_ID);
apnSender = new APNSender(new SynchronousExecutorService(), apnsClient, BUNDLE_ID, CLOCK);
when(destinationAccount.getDevice(Device.PRIMARY_ID)).thenReturn(Optional.of(destinationDevice));
when(destinationDevice.getApnId()).thenReturn(DESTINATION_DEVICE_TOKEN);
@@ -69,7 +74,7 @@ class APNSenderTest {
(Answer) invocationOnMock -> new MockPushNotificationFuture<>(invocationOnMock.getArgument(0), response));
PushNotification pushNotification = new PushNotification(DESTINATION_DEVICE_TOKEN, PushNotification.TokenType.APN,
PushNotification.NotificationType.NOTIFICATION, null, destinationAccount, destinationDevice, urgent);
PushNotification.NotificationType.NOTIFICATION, null, destinationAccount, destinationDevice, urgent, null);
final SendPushNotificationResult result = apnSender.sendNotification(pushNotification).join();
@@ -77,7 +82,7 @@ class APNSenderTest {
verify(apnsClient).sendNotification(notification.capture());
assertThat(notification.getValue().getToken()).isEqualTo(DESTINATION_DEVICE_TOKEN);
assertThat(notification.getValue().getExpiration()).isEqualTo(APNSender.MAX_EXPIRATION);
assertThat(notification.getValue().getExpiration()).isEqualTo(CLOCK.instant().plus(APNSender.DEFAULT_TTL));
assertThat(notification.getValue().getPayload())
.isEqualTo(urgent ? APNSender.APN_NSE_NOTIFICATION_PAYLOAD : APNSender.APN_BACKGROUND_PAYLOAD);
@@ -113,7 +118,7 @@ class APNSenderTest {
(Answer) invocationOnMock -> new MockPushNotificationFuture<>(invocationOnMock.getArgument(0), response));
PushNotification pushNotification = new PushNotification(DESTINATION_DEVICE_TOKEN, PushNotification.TokenType.APN,
PushNotification.NotificationType.NOTIFICATION, null, destinationAccount, destinationDevice, true);
PushNotification.NotificationType.NOTIFICATION, null, destinationAccount, destinationDevice, true, null);
when(destinationDevice.getApnId()).thenReturn(DESTINATION_DEVICE_TOKEN);
when(destinationDevice.getPushTimestamp()).thenReturn(System.currentTimeMillis() - TimeUnit.SECONDS.toMillis(11));
@@ -124,7 +129,7 @@ class APNSenderTest {
verify(apnsClient).sendNotification(notification.capture());
assertThat(notification.getValue().getToken()).isEqualTo(DESTINATION_DEVICE_TOKEN);
assertThat(notification.getValue().getExpiration()).isEqualTo(APNSender.MAX_EXPIRATION);
assertThat(notification.getValue().getExpiration()).isEqualTo(CLOCK.instant().plus(APNSender.DEFAULT_TTL));
assertThat(notification.getValue().getPayload()).isEqualTo(APNSender.APN_NSE_NOTIFICATION_PAYLOAD);
assertThat(notification.getValue().getPriority()).isEqualTo(DeliveryPriority.IMMEDIATE);
@@ -144,7 +149,7 @@ class APNSenderTest {
(Answer) invocationOnMock -> new MockPushNotificationFuture<>(invocationOnMock.getArgument(0), response));
PushNotification pushNotification = new PushNotification(DESTINATION_DEVICE_TOKEN, PushNotification.TokenType.APN,
PushNotification.NotificationType.NOTIFICATION, null, destinationAccount, destinationDevice, true);
PushNotification.NotificationType.NOTIFICATION, null, destinationAccount, destinationDevice, true, null);
final SendPushNotificationResult result = apnSender.sendNotification(pushNotification).join();
@@ -152,7 +157,7 @@ class APNSenderTest {
verify(apnsClient).sendNotification(notification.capture());
assertThat(notification.getValue().getToken()).isEqualTo(DESTINATION_DEVICE_TOKEN);
assertThat(notification.getValue().getExpiration()).isEqualTo(APNSender.MAX_EXPIRATION);
assertThat(notification.getValue().getExpiration()).isEqualTo(CLOCK.instant().plus(APNSender.DEFAULT_TTL));
assertThat(notification.getValue().getPayload()).isEqualTo(APNSender.APN_NSE_NOTIFICATION_PAYLOAD);
assertThat(notification.getValue().getPriority()).isEqualTo(DeliveryPriority.IMMEDIATE);
@@ -171,7 +176,7 @@ class APNSenderTest {
new IOException("lost connection")));
PushNotification pushNotification = new PushNotification(DESTINATION_DEVICE_TOKEN, PushNotification.TokenType.APN,
PushNotification.NotificationType.NOTIFICATION, null, destinationAccount, destinationDevice, true);
PushNotification.NotificationType.NOTIFICATION, null, destinationAccount, destinationDevice, true, null);
assertThatThrownBy(() -> apnSender.sendNotification(pushNotification).join())
.isInstanceOf(CompletionException.class)
@@ -54,7 +54,8 @@ class FcmSenderTest {
@Test
void testSendMessage() {
final PushNotification pushNotification = new PushNotification("foo", PushNotification.TokenType.FCM, PushNotification.NotificationType.NOTIFICATION, null, null, null, true);
final PushNotification pushNotification = new PushNotification("foo", PushNotification.TokenType.FCM, PushNotification.NotificationType.NOTIFICATION, null, null, null, true,
null);
final SettableApiFuture<String> sendFuture = SettableApiFuture.create();
sendFuture.set("message-id");
@@ -71,7 +72,8 @@ class FcmSenderTest {
@Test
void testSendMessageRejected() {
final PushNotification pushNotification = new PushNotification("foo", PushNotification.TokenType.FCM, PushNotification.NotificationType.NOTIFICATION, null, null, null, true);
final PushNotification pushNotification = new PushNotification("foo", PushNotification.TokenType.FCM, PushNotification.NotificationType.NOTIFICATION, null, null, null, true,
null);
final FirebaseMessagingException invalidArgumentException = mock(FirebaseMessagingException.class);
when(invalidArgumentException.getMessagingErrorCode()).thenReturn(MessagingErrorCode.INVALID_ARGUMENT);
@@ -91,7 +93,8 @@ class FcmSenderTest {
@Test
void testSendMessageUnregistered() {
final PushNotification pushNotification = new PushNotification("foo", PushNotification.TokenType.FCM, PushNotification.NotificationType.NOTIFICATION, null, null, null, true);
final PushNotification pushNotification = new PushNotification("foo", PushNotification.TokenType.FCM, PushNotification.NotificationType.NOTIFICATION, null, null, null, true,
null);
final FirebaseMessagingException unregisteredException = mock(FirebaseMessagingException.class);
when(unregisteredException.getMessagingErrorCode()).thenReturn(MessagingErrorCode.UNREGISTERED);
@@ -111,7 +114,8 @@ class FcmSenderTest {
@Test
void testSendMessageException() {
final PushNotification pushNotification = new PushNotification("foo", PushNotification.TokenType.FCM, PushNotification.NotificationType.NOTIFICATION, null, null, null, true);
final PushNotification pushNotification = new PushNotification("foo", PushNotification.TokenType.FCM, PushNotification.NotificationType.NOTIFICATION, null, null, null, true,
null);
final SettableApiFuture<String> sendFuture = SettableApiFuture.create();
sendFuture.setException(new IOException());
@@ -66,7 +66,7 @@ class PushNotificationManagerTest {
when(fcmSender.sendNotification(any()))
.thenReturn(CompletableFuture.completedFuture(new SendPushNotificationResult(true, Optional.empty(), false, Optional.empty())));
pushNotificationManager.sendNewMessageNotification(account, Device.PRIMARY_ID, true);
verify(fcmSender).sendNotification(new PushNotification(deviceToken, PushNotification.TokenType.FCM, PushNotification.NotificationType.NOTIFICATION, null, account, device, true));
verify(fcmSender).sendNotification(new PushNotification(deviceToken, PushNotification.TokenType.FCM, PushNotification.NotificationType.NOTIFICATION, null, account, device, true, null));
}
@Test
@@ -96,7 +96,7 @@ class PushNotificationManagerTest {
.thenReturn(CompletableFuture.completedFuture(new SendPushNotificationResult(true, Optional.empty(), false, Optional.empty())));
pushNotificationManager.sendRegistrationChallengeNotification(deviceToken, PushNotification.TokenType.APN, challengeToken);
verify(apnSender).sendNotification(new PushNotification(deviceToken, PushNotification.TokenType.APN, PushNotification.NotificationType.CHALLENGE, challengeToken, null, null, true));
verify(apnSender).sendNotification(new PushNotification(deviceToken, PushNotification.TokenType.APN, PushNotification.NotificationType.CHALLENGE, challengeToken, null, null, true, null));
}
@Test
@@ -115,7 +115,7 @@ class PushNotificationManagerTest {
.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));
verify(apnSender).sendNotification(new PushNotification(deviceToken, PushNotification.TokenType.APN, PushNotification.NotificationType.RATE_LIMIT_CHALLENGE, challengeToken, account, device, true, null));
}
@ParameterizedTest
@@ -142,10 +142,10 @@ class PushNotificationManagerTest {
if (isApn){
verify(apnSender).sendNotification(new PushNotification(deviceToken, PushNotification.TokenType.APN,
PushNotification.NotificationType.ATTEMPT_LOGIN_NOTIFICATION_HIGH_PRIORITY, "someContext", account, device, true));
PushNotification.NotificationType.ATTEMPT_LOGIN_NOTIFICATION_HIGH_PRIORITY, "someContext", account, device, true, null));
} else {
verify(fcmSender, times(1)).sendNotification(new PushNotification(deviceToken, PushNotification.TokenType.FCM,
PushNotification.NotificationType.ATTEMPT_LOGIN_NOTIFICATION_HIGH_PRIORITY, "someContext", account, device, true));
PushNotification.NotificationType.ATTEMPT_LOGIN_NOTIFICATION_HIGH_PRIORITY, "someContext", account, device, true, null));
}
}
@@ -163,7 +163,7 @@ class PushNotificationManagerTest {
AccountsHelper.setupMockGet(accountsManager, account);
final PushNotification pushNotification = new PushNotification(
"token", PushNotification.TokenType.FCM, PushNotification.NotificationType.NOTIFICATION, null, account, device, true);
"token", PushNotification.TokenType.FCM, PushNotification.NotificationType.NOTIFICATION, null, account, device, true, null);
when(fcmSender.sendNotification(pushNotification))
.thenReturn(CompletableFuture.completedFuture(new SendPushNotificationResult(true, Optional.empty(), false, Optional.empty())));
@@ -193,7 +193,7 @@ class PushNotificationManagerTest {
when(account.getUuid()).thenReturn(aci);
final PushNotification pushNotification = new PushNotification(
"token", tokenType, PushNotification.NotificationType.NOTIFICATION, null, account, device, urgent);
"token", tokenType, PushNotification.NotificationType.NOTIFICATION, null, account, device, urgent, null);
final PushNotificationSender sender = switch (tokenType) {
case FCM -> fcmSender;
@@ -231,7 +231,7 @@ class PushNotificationManagerTest {
when(accountsManager.getByAccountIdentifier(aci)).thenReturn(Optional.of(account));
final PushNotification pushNotification = new PushNotification(
"token", PushNotification.TokenType.FCM, PushNotification.NotificationType.NOTIFICATION, null, account, device, true);
"token", PushNotification.TokenType.FCM, PushNotification.NotificationType.NOTIFICATION, null, account, device, true, null);
when(fcmSender.sendNotification(pushNotification))
.thenReturn(CompletableFuture.completedFuture(new SendPushNotificationResult(false, Optional.empty(), true, Optional.empty())));
@@ -257,7 +257,7 @@ class PushNotificationManagerTest {
when(accountsManager.getByAccountIdentifier(aci)).thenReturn(Optional.of(account));
final PushNotification pushNotification = new PushNotification(
"token", PushNotification.TokenType.APN, PushNotification.NotificationType.NOTIFICATION, null, account, device, true);
"token", PushNotification.TokenType.APN, PushNotification.NotificationType.NOTIFICATION, null, account, device, true, null);
when(apnSender.sendNotification(pushNotification))
.thenReturn(CompletableFuture.completedFuture(new SendPushNotificationResult(false, Optional.empty(), true, Optional.empty())));
@@ -288,7 +288,7 @@ class PushNotificationManagerTest {
when(accountsManager.getByAccountIdentifier(aci)).thenReturn(Optional.of(account));
final PushNotification pushNotification = new PushNotification(
"token", PushNotification.TokenType.APN, PushNotification.NotificationType.NOTIFICATION, null, account, device, true);
"token", PushNotification.TokenType.APN, PushNotification.NotificationType.NOTIFICATION, null, account, device, true, null);
when(apnSender.sendNotification(pushNotification))
.thenReturn(CompletableFuture.completedFuture(new SendPushNotificationResult(false, Optional.empty(), true, Optional.of(tokenTimestamp.minusSeconds(60)))));