Compare commits

..
11 changed files with 176 additions and 40 deletions

No files matched your search

@@ -298,6 +298,7 @@ import org.whispersystems.textsecuregcm.workers.BackupUsageRecalculationCommand;
import org.whispersystems.textsecuregcm.workers.CertificateCommand;
import org.whispersystems.textsecuregcm.workers.CheckDynamicConfigurationCommand;
import org.whispersystems.textsecuregcm.workers.ClearIssuedReceiptRedemptionsCommand;
import org.whispersystems.textsecuregcm.workers.CopyToS3Command;
import org.whispersystems.textsecuregcm.workers.DeleteUserCommand;
import org.whispersystems.textsecuregcm.workers.IdleDeviceNotificationSchedulerFactory;
import org.whispersystems.textsecuregcm.workers.MessagePersisterServiceCommand;
@@ -371,6 +372,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
bootstrap.addCommand(new UnlinkDevicesWithIdlePrimaryCommand(Clock.systemUTC()));
bootstrap.addCommand(new NotifyIdleDevicesCommand());
bootstrap.addCommand(new ClearIssuedReceiptRedemptionsCommand());
bootstrap.addCommand(new CopyToS3Command());
bootstrap.addCommand(new ProcessScheduledJobsServiceCommand("process-idle-device-notification-jobs",
"Processes scheduled jobs to send notifications to idle devices",
@@ -1148,7 +1148,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
Pair<Account, Optional<Account>> getAccountsForChangeNumber(final UUID accountIdentifier, final String targetNumber) {
return new Pair<>(accounts.getByAccountIdentifier(accountIdentifier)
.orElseThrow(() -> new IllegalArgumentException("Account not found: " + accountIdentifier)),
accounts.getByE164(targetNumber));
accounts.getByPhoneNumberIdentifier(getPhoneNumberIdentifier(targetNumber)));
}
public UUID getPhoneNumberIdentifier(String e164) {
@@ -24,6 +24,9 @@ public class EnvelopeUtil {
@VisibleForTesting
static final String INCLUDE_BINARY_SERVICE_ID_EXPERIMENT_NAME = "envelopeIncludeBinaryServiceIdentifier";
@VisibleForTesting
static final String SKIP_EXPANSION_EXPERIMENT_NAME = "skipEnvelopeExpansion";
/**
* Converts all "compressible" UUID-like fields in the given envelope to more compact binary representations.
*
@@ -77,6 +80,7 @@ public class EnvelopeUtil {
final ExperimentEnrollmentManager experimentEnrollmentManager) {
final boolean includeBinaryServiceIdentifiers;
final boolean skipEnvelopeExpansion;
if (envelope.hasDestinationServiceIdBinary() || envelope.hasDestinationServiceId()) {
final ServiceIdentifier destinationIdentifier = envelope.hasDestinationServiceIdBinary()
@@ -85,8 +89,16 @@ public class EnvelopeUtil {
includeBinaryServiceIdentifiers =
experimentEnrollmentManager.isEnrolled(destinationIdentifier.uuid(), INCLUDE_BINARY_SERVICE_ID_EXPERIMENT_NAME);
skipEnvelopeExpansion =
experimentEnrollmentManager.isEnrolled(destinationIdentifier.uuid(), SKIP_EXPANSION_EXPERIMENT_NAME);
} else {
includeBinaryServiceIdentifiers = false;
skipEnvelopeExpansion = false;
}
if (skipEnvelopeExpansion) {
return envelope;
}
final MessageProtos.Envelope.Builder builder = envelope.toBuilder();
@@ -275,7 +275,8 @@ public class FoundationDbMessageStore {
new MessageGuidCodec(aci.uuid(), destinationDevice.getId(), versionstampUUIDCipher),
maxMessagesPerScan,
maxUnacknowledgedMessages,
doAfterCleanup);
doAfterCleanup,
clock);
}
static Versionstamp getVersionstamp(final byte[] messageKey) {
@@ -5,6 +5,8 @@ import com.apple.foundationdb.KeySelector;
import com.apple.foundationdb.StreamingMode;
import com.apple.foundationdb.Transaction;
import com.apple.foundationdb.subspace.Subspace;
import java.time.Clock;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@@ -43,11 +45,14 @@ public class FoundationDbMessageStream implements MessageStream {
private final int maxUnacknowledgedMessages;
private final Flow.Publisher<MessageStreamEntry> messageStreamPublisher;
private final Runnable doAfterCleanup;
private final Clock clock;
/// Map of versionstamp -> acknowledged? to keep track of acknowledged versionstamp ranges to clear
private final NavigableMap<Versionstamp, Boolean> sentVersionstamps = new TreeMap<>();
private int unacknowledgedMessages = 0;
@VisibleForTesting
static final Duration MAX_EPHEMERAL_MESSAGE_DELAY = Duration.ofSeconds(10);
static final int DEFAULT_MAX_MESSAGES_PER_SCAN = 1024;
@VisibleForTesting
static final int DEFAULT_MAX_UNACKNOWLEDGED_MESSAGES = 16_384;
@@ -60,14 +65,15 @@ public class FoundationDbMessageStream implements MessageStream {
final MessageGuidCodec messageGuidCodec,
final int maxMessagesPerScan,
final int maxUnacknowledgedMessages,
final Runnable doAfterCleanup) {
final Runnable doAfterCleanup,
final Clock clock) {
this.deviceQueueSubspace = deviceQueueSubspace;
this.messagesAvailableWatchKey = messagesAvailableWatchKey;
this.database = database;
this.messageGuidCodec = messageGuidCodec;
this.maxMessagesPerScan = maxMessagesPerScan;
this.maxUnacknowledgedMessages = maxUnacknowledgedMessages;
this.clock = clock;
this.messageStreamPublisher = JdkFlowAdapter.publisherToFlowPublisher(createMessagePublisher());
this.doAfterCleanup = doAfterCleanup;
}
@@ -83,6 +89,7 @@ public class FoundationDbMessageStream implements MessageStream {
/// @implNote turns the stream of [FoundationDbMessageStreamEntry] into [MessageStreamEntry], but taps into the stream
/// first to keep track of versionstamps sent to the client.
private Flux<MessageStreamEntry> createMessagePublisher() {
final long earliestAllowedEphemeralTimestamp = clock.instant().minus(MAX_EPHEMERAL_MESSAGE_DELAY).toEpochMilli();
return createFoundationDbMessagePublisher()
.<FoundationDbMessageStreamEntry>handle((messageStreamEntry, sink) -> {
if (messageStreamEntry instanceof final FoundationDbMessageStreamEntry.Message message) {
@@ -95,6 +102,14 @@ public class FoundationDbMessageStream implements MessageStream {
sink.next(messageStreamEntry);
})
.map(fdbMessageStreamEntry -> fdbMessageStreamEntry.toMessageStreamEntry(messageGuidCodec))
.<MessageStreamEntry>handle((messageStreamEntry, sink) -> {
if (messageStreamEntry instanceof MessageStreamEntry.Envelope(MessageProtos.Envelope message)
&& isStaleEphemeralMessage(message, earliestAllowedEphemeralTimestamp)) {
acknowledgeMessage(message);
return;
}
sink.next(messageStreamEntry);
})
.doFinally(_ -> flushAllAcknowledgedMessages().thenRun(doAfterCleanup));
}
@@ -242,4 +257,9 @@ public class FoundationDbMessageStream implements MessageStream {
return flushableRanges;
}
private static boolean isStaleEphemeralMessage(final MessageProtos.Envelope message,
long earliestAllowableTimestamp) {
return message.getEphemeral() && message.getClientTimestamp() < earliestAllowableTimestamp;
}
}
@@ -12,9 +12,7 @@ import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.ShortBufferException;
@@ -69,7 +67,9 @@ public class VersionstampUUIDCipher {
private static final int TWEAK_LENGTH = 17; // bytes
private static final byte ROUNDS = 10; // from FF1 specification
private static final IvParameterSpec IV_PARAMETERS = new IvParameterSpec(new byte[] {
private static final IvParameterSpec IV_PARAMETERS = new IvParameterSpec(new byte[16]);
private static final byte[] PARAMETERS_BLOCK = new byte[] {
0x01, // static value from FF1 specification
0x02, // static value from FF1 specification
0x01, // static value from FF1 specification
@@ -78,7 +78,7 @@ public class VersionstampUUIDCipher {
(VERSIONSTAMP_LENGTH * 8) / 2,
0x00, 0x00, 0x00, VERSIONSTAMP_LENGTH * 8, // for radix = 2, plaintext/ciphertext length in bits
0x00, 0x00, 0x00, TWEAK_LENGTH, // tweak length in bytes (not bits)
});
};
private static final long LEAST_SIGNIFICANT_SIX_BYTES_MASK = 0x0000_ffff_ffff_ffffL;
private static final byte FORMAT_VERSION_MASK = 0x0f;
@@ -213,26 +213,23 @@ public class VersionstampUUIDCipher {
final long b,
final byte[] bufferArray) {
try {
cipher.init(Cipher.ENCRYPT_MODE, key, IV_PARAMETERS);
} catch (final InvalidKeyException e) {
throw new AssertionError("Previously-valid key now invalid", e);
} catch (final InvalidAlgorithmParameterException e) {
throw new AssertionError("Previously-valid IV now invalid", e);
}
assert (b & ~LEAST_SIGNIFICANT_SIX_BYTES_MASK) == 0;
final ByteBuffer byteBuffer = ByteBuffer.wrap(bufferArray);
// Write the first part of cryptographic "tweak" into the buffer. We have one more byte (the device ID) that will
// "spill" over into the next block, but that's okay! That extra byte falls into the "padding zone" of the next
// block, and doesn't increase the overall block count per round.
byteBuffer
.putLong(0, accountIdentifier.getMostSignificantBits())
.putLong(8, accountIdentifier.getLeastSignificantBits());
try {
cipher.init(Cipher.ENCRYPT_MODE, key, IV_PARAMETERS);
// Every round begins with the parameters block. We haven't written any round-specific input into the provided
// buffer yet, so we can write the output of this update into the buffer without clobbering anything important.
cipher.update(PARAMETERS_BLOCK, 0, bufferArray.length, bufferArray);
// Write the first part of cryptographic "tweak" into the buffer, overwriting the output of the previous block (we
// don't need the output). We have one more byte (the device ID) that will "spill" over into the next block, but
// that's okay! That extra byte falls into the "padding zone" of the next block, and doesn't increase the overall
// block count per round.
final ByteBuffer byteBuffer = ByteBuffer.wrap(bufferArray)
.putLong(0, accountIdentifier.getMostSignificantBits())
.putLong(8, accountIdentifier.getLeastSignificantBits());
// We can overwrite the input buffer here to avoid allocating an additional 16-byte buffer that we'd just
// discard immediately
cipher.update(bufferArray, 0, bufferArray.length, bufferArray);
@@ -248,19 +245,16 @@ public class VersionstampUUIDCipher {
.putLong(8, b)
.put(9, round);
// Again, overwrite the input buffer to avoid an extra buffer allocation…
// Again, overwrite the input buffer to avoid an extra buffer allocation
cipher.update(bufferArray, 0, bufferArray.length, bufferArray);
// …and then overwrite the buffer once more with the cipher's finished output, which is the only AES-CBC output we
// actually use directly.
final int bytesWritten = cipher.doFinal(bufferArray, 0);
assert bytesWritten == 16;
return byteBuffer.getLong(0) & LEAST_SIGNIFICANT_SIX_BYTES_MASK;
} catch (final IllegalBlockSizeException | BadPaddingException e) {
throw new AssertionError("Every implementation of the Java platform is required to support AES/CBC/PKCS5Padding", e);
} catch (final ShortBufferException e) {
throw new AssertionError("Buffer with known length of 16 too short", e);
} catch (final InvalidAlgorithmParameterException e) {
throw new AssertionError("Previously-valid IV now invalid", e);
} catch (final InvalidKeyException e) {
throw new AssertionError("Previously-valid key now invalid", e);
}
}
@@ -269,9 +263,9 @@ public class VersionstampUUIDCipher {
/// @return a `Cipher` instance suitable for use in the core NIST/FF1 loop
private static Cipher getCipher() {
try {
return Cipher.getInstance("AES/CBC/PKCS5Padding");
return Cipher.getInstance("AES/CBC/NoPadding");
} catch (final NoSuchAlgorithmException | NoSuchPaddingException e) {
throw new AssertionError("Every implementation of the Java platform is required to support AES/CBC/PKCS5Padding", e);
throw new AssertionError("Every implementation of the Java platform is required to support AES/CBC/NoPadding", e);
}
}
@@ -118,6 +118,7 @@ class AccountsManagerTest {
private static TestClock CLOCK;
private Accounts accounts;
private PhoneNumberIdentifiers phoneNumberIdentifiers;
private KeysManager keysManager;
private MessagesManager messagesManager;
private ProfilesManager profilesManager;
@@ -179,7 +180,7 @@ class AccountsManagerTest {
svr2Client = mock(SecureValueRecoveryClient.class);
when(svr2Client.removeData(any(UUID.class))).thenReturn(CompletableFuture.completedFuture(null));
final PhoneNumberIdentifiers phoneNumberIdentifiers = mock(PhoneNumberIdentifiers.class);
phoneNumberIdentifiers = mock(PhoneNumberIdentifiers.class);
phoneNumberIdentifiersByE164 = new HashMap<>();
when(phoneNumberIdentifiers.getPhoneNumberIdentifier(anyString())).thenAnswer((Answer<CompletableFuture<UUID>>) invocation -> {
@@ -1479,6 +1480,25 @@ class AccountsManagerTest {
}
}
@Test
void getAccountsForChangeNumber() {
final Account account = AccountsHelper.generateTestAccount("+14152222222", UUID.randomUUID(), UUID.randomUUID(), new ArrayList<>(), new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH]);
final UUID accountIdentifier = account.getIdentifier(IdentityType.ACI);
addRetrievableAccount(account);
final String targetNumber = "+13102222222";
assertFalse(phoneNumberIdentifiersByE164.containsKey(targetNumber));
final Pair<Account, Optional<Account>> accountsForChangeNumber = accountsManager.getAccountsForChangeNumber(
accountIdentifier, targetNumber);
assertEquals(account, accountsForChangeNumber.first());
verify(accounts).getByAccountIdentifier(accountIdentifier);
// getPhoneNumberIdentifier handles alternate forms
verify(phoneNumberIdentifiers).getPhoneNumberIdentifier(targetNumber);
}
static Collection<Arguments> updateCurrentProfileVersion() {
final byte[] empty = new byte[0];
@@ -16,6 +16,7 @@ import static org.mockito.Mockito.when;
import com.google.protobuf.ByteString;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
@@ -116,6 +117,30 @@ class EnvelopeUtilTest {
}
}
@Test
void compressExpandSkipExpansion() {
final ExperimentEnrollmentManager experimentEnrollmentManager = mock(ExperimentEnrollmentManager.class);
when(experimentEnrollmentManager.isEnrolled(any(UUID.class), eq(EnvelopeUtil.SKIP_EXPANSION_EXPERIMENT_NAME)))
.thenReturn(true);
final ServiceIdentifier sourceServiceId = generateRandomServiceIdentifier();
final ServiceIdentifier destinationServiceId = generateRandomServiceIdentifier();
final UUID serverGuid = UUID.randomUUID();
final UUID updatedPni = UUID.randomUUID();
final MessageProtos.Envelope compressed = generateRandomMessageBuilder()
.setSourceServiceIdBinary(ServiceIdentifierUtil.toCompactByteString(sourceServiceId))
.setDestinationServiceIdBinary(ServiceIdentifierUtil.toCompactByteString(destinationServiceId))
.setServerGuidBinary(UUIDUtil.toByteString(serverGuid))
.setUpdatedPniBinary(UUIDUtil.toByteString(updatedPni))
.build();
final MessageProtos.Envelope expanded = EnvelopeUtil.expand(compressed, experimentEnrollmentManager);
assertEquals(compressed, expanded,
"Compressed message should be returned unchanged when enrolled in 'skip expansion' experiment");
}
private static ServiceIdentifier generateRandomServiceIdentifier() {
final IdentityType identityType = ThreadLocalRandom.current().nextBoolean() ? IdentityType.ACI : IdentityType.PNI;
@@ -50,6 +50,7 @@ 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.junitpioneer.jupiter.cartesian.CartesianTest;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.storage.Device;
@@ -648,12 +649,71 @@ class FoundationDbMessageStoreTest {
.verify();
}
static MessageProtos.Envelope generateRandomMessage(final boolean ephemeral) {
return generateRandomMessage(ephemeral, 16);
@CartesianTest
void discardStaleEphemeralMessages(
@CartesianTest.Values(booleans = {true, false}) final boolean isStale,
@CartesianTest.Values(booleans = {true, false}) final boolean ephemeral) {
final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID());
writePresenceKey(aci, Device.PRIMARY_ID, 1, 5L);
final long messageTimestamp;
if (isStale) {
messageTimestamp = CLOCK.instant().minus(FoundationDbMessageStream.MAX_EPHEMERAL_MESSAGE_DELAY.plus(Duration.ofMillis(1))).toEpochMilli();
} else {
messageTimestamp = CLOCK.instant().toEpochMilli();
}
final Versionstamp expectedVersionstamp = foundationDbMessageStore.insert(aci, Map.of(Device.PRIMARY_ID, generateRandomMessage(ephemeral, messageTimestamp)))
.join()
.get(Device.PRIMARY_ID)
.versionstamp()
.orElseThrow();
final Device device = new Device();
device.setId(Device.PRIMARY_ID);
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci, device);
final List<MessageStreamEntry> retrievedEntries = new ArrayList<>();
if (isStale && ephemeral) {
StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messageStream.getMessages()))
.recordWith(() -> retrievedEntries)
.expectNext(new MessageStreamEntry.QueueEmpty())
.verifyTimeout(Duration.ofSeconds(1));
assertEquals(1, retrievedEntries.size());
} else {
StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messageStream.getMessages()))
.recordWith(() -> retrievedEntries)
.expectNextCount(1)
.expectNext(new MessageStreamEntry.QueueEmpty())
.verifyTimeout(Duration.ofSeconds(1));
assertEquals(2, retrievedEntries.size());
final MessageGuidCodec messageGuidCodec =
new MessageGuidCodec(aci.uuid(), Device.PRIMARY_ID, versionstampUUIDCipher);
final MessageStreamEntry.Envelope envelopeEntry =
assertInstanceOf(MessageStreamEntry.Envelope.class, retrievedEntries.getFirst());
assertEquals(expectedVersionstamp,
messageGuidCodec.decodeMessageGuid(UUIDUtil.fromByteString(envelopeEntry.message().getServerGuidBinary())));
}
}
static MessageProtos.Envelope generateRandomMessage(final boolean ephemeral, final long timestamp) {
return generateRandomMessage(ephemeral, 16, timestamp);
}
static MessageProtos.Envelope generateRandomMessage(final boolean ephemeral, final int contentSize) {
return generateRandomMessage(ephemeral, contentSize, CLOCK.millis());
}
static MessageProtos.Envelope generateRandomMessage(final boolean ephemeral) {
return generateRandomMessage(ephemeral, 16, CLOCK.millis());
}
static MessageProtos.Envelope generateRandomMessage(final boolean ephemeral, final int contentSize, final long timestamp) {
return MessageProtos.Envelope.newBuilder()
.setClientTimestamp(timestamp)
.setServerTimestamp(timestamp)
.setContent(ByteString.copyFrom(TestRandomUtil.nextBytes(contentSize)))
.setEphemeral(ephemeral)
.build();
@@ -8,6 +8,7 @@ import com.apple.foundationdb.subspace.Subspace;
import com.apple.foundationdb.tuple.Versionstamp;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.time.Clock;
import java.util.Collections;
import java.util.List;
import java.util.stream.Stream;
@@ -30,7 +31,8 @@ class FoundationDbMessageStreamTest {
mock(MessageGuidCodec.class),
100,
FoundationDbMessageStream.DEFAULT_MAX_UNACKNOWLEDGED_MESSAGES,
Util.NOOP
Util.NOOP,
Clock.systemUTC()
);
versionstampsSent.forEach(