Compare commits

..
Author SHA1 Message Date
Jon Chambers 569f4f31e8 Update to the latest version of the spam filter 2026-06-17 08:46:11 -04:00
Ravi Khadiwala 06519ce9d1 Use uint64 for backups.proto object length 2026-06-17 08:45:43 -04:00
Jon Chambers 024fa9ce5f Move "active epoch" configuration from dynamic to static configuration 2026-06-17 08:35:07 -04:00
Jon Chambers 7c9e3d029b Remove an unused availableProcessors variable 2026-06-17 08:33:29 -04:00
Jon Chambers cc6ef53f91 Retire unused methods in MessagesManager 2026-06-17 08:33:29 -04:00
Ravi Khadiwala 4c0f454209 Add a generic STREAM_CLOSED status 2026-06-17 08:32:47 -04:00
Chris Eager 9c393972e9 Update to the latest version of the spam filter 2026-06-16 20:02:56 -05:00
Jon Chambers 31c1bb8940 Support multiple "configuration epochs" of the FoundationDB message store 2026-06-16 09:06:18 -04:00
Jon Chambers c3b2b43813 Port CallLinkController to gRPC 2026-06-16 09:02:24 -04:00
Jon Chambers 19f2574799 Update to the latest version of the spam filter 2026-06-16 09:02:03 -04:00
Ravi Khadiwala adb5b6a4ea Check message type before deserializing source serviceId 2026-06-11 13:16:20 -05:00
Ravi Khadiwala e79eb9904d Update to the latest version of the spam filter 2026-06-11 11:36:07 -05:00
ravi-signal fcdc0bbd74 Generate grpc api documentation 2026-06-11 11:35:20 -05:00
Ravi Khadiwala b6317a1b43 Add gRPC message retrieval 2026-06-11 11:34:07 -05:00
Ravi Khadiwala 329d229ac7 Revert "Remove unused ClosableEpoch"
This reverts commit d0e022c23b.
2026-06-11 11:34:07 -05:00
Ravi Khadiwala c50b4e52b0 Move some message retrieval metrics to MessageMetrics 2026-06-11 11:34:07 -05:00
Ravi Khadiwala 660011017d Throw checked exceptions from CaptchaChecker 2026-06-11 11:33:56 -04:00
Jon Chambers 82e3c16fba Port CallRoutingControllerV2 to gRPC 2026-06-11 11:31:57 -04:00
Jon Chambers ae9f43bb3c Don't include IOException messages in gRPC error responses 2026-06-11 11:31:57 -04:00
Jonathan Klabunde Tomer ab4b5a1298 ignore disconnects from already-disconnected message listeners 2026-06-11 11:31:24 -04:00
Katherine Yen 97a77ce23e Remove duplicate constructor for invalid argument gRPC exception with no details 2026-06-11 11:30:56 -04:00
Ameya Lokare 50ef5272f7 Fix handling write conflicts when redeeming subscription receipt
credentials
2026-06-11 11:30:16 -04:00
Chris Eager d6c7c5e7bf Use ProfileHelper.isPaymentAddressUpdateForbidden for both REST and gRPC 2026-06-11 10:29:14 -05:00
Ameya Lokare 32befd7c9a Port DonationController to gRPC 2026-06-11 11:28:23 -04:00
Jon Chambers dd93833324 Avoid retaining messages while waiting for acknowledgement 2026-06-11 11:14:02 -04:00
Jon Chambers 5d624b463a Acknowledge messages by ID rather than by passing the whole message around 2026-06-11 11:14:02 -04:00
Jon Chambers f524d9fb25 Retire string-based service identifiers/UUIDs in Envelope entities 2026-06-10 14:28:30 -04:00
Jon Chambers 4a9302033a Remove the additional callback executor from FoundationDbMessageStore 2026-06-10 13:12:40 -04:00
Jon Chambers 292f03586b Add an IP-based rate limiter for adding payment methods for subscriptions 2026-06-10 11:29:51 -04:00
Jon Chambers 8257859834 Add an IP-based rate limiter for creating one-time donations 2026-06-10 11:29:51 -04:00
Katherine Yen 2c5210e7c4 Fix a flaky test by waiting for the async insert to complete before attempting to remove the message 2026-06-08 17:42:35 -04:00
Katherine b93da1323b Discard ephemeral messages from the finite publisher in FoundationDB 2026-06-08 17:23:21 -04:00
Ravi Khadiwala d9c39cc12b Update messages integration test to use websocket 2026-06-08 16:01:23 -05:00
Ravi Khadiwala d69027ce5c Remove REST message retrieval entities 2026-06-08 16:01:23 -05:00
Jon Chambers a4381a2617 Parse FoundationDB envelopes at load time and add GUIDs later 2026-06-08 16:56:53 -04:00
Jon Chambers 3e4ad32fce Introduce AcknowledgedMessageBuffer 2026-06-08 16:56:15 -04:00
Jon Chambers c3a48fd08b Port CertificateController to gRPC 2026-06-08 16:55:53 -04:00
Ravi Khadiwala 7471a21fee Update to the latest version of the spam filter 2026-06-05 12:41:26 -05:00
Ameya Lokare 13a5458344 Port ChallengeController to gRPC 2026-06-05 12:32:46 -05:00
Ravi Khadiwala 704b53aa79 Close responses in WhisperServerServiceTest 2026-06-05 12:30:09 -05:00
Jon Chambers 5774ffdeab Wait for test message insertion to complete before attempting to read 2026-06-05 10:22:34 -04:00
Ravi Khadiwala fac7dbbeb7 Add a timeout to WhisperServerServiceTest 2026-06-04 18:06:27 -05:00
Ravi Khadiwala 29b1ec694b Update to the latest version of the spam filter 2026-06-03 11:39:07 -05:00
dependabot[bot] 181004f031 Bump the minor-actions-dependencies group with 2 updates
Bumps the minor-actions-dependencies group with 2 updates: [actions/checkout](https://github.com/actions/checkout) and [aws-actions/configure-aws-credentials](https://github.com/aws-actions/configure-aws-credentials).


Updates `actions/checkout` from 6.0.2 to 6.0.3
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/de0fac2e4500dabe0009e67214ff5f5447ce83dd...df4cb1c069e1874edd31b4311f1884172cec0e10)

Updates `aws-actions/configure-aws-credentials` from 6.1.0 to 6.2.0
- [Release notes](https://github.com/aws-actions/configure-aws-credentials/releases)
- [Changelog](https://github.com/aws-actions/configure-aws-credentials/blob/main/CHANGELOG.md)
- [Commits](https://github.com/aws-actions/configure-aws-credentials/compare/ec61189d14ec14c8efccab744f656cffd0e33f37...e7f100cf4c008499ea8adda475de1042d6975c7b)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-version: 6.0.3
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-actions-dependencies
- dependency-name: aws-actions/configure-aws-credentials
  dependency-version: 6.2.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-actions-dependencies
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-06-03 12:03:36 -04:00
Jon Chambers bb18a84808 Add an experiment to recompress messages just before delivery 2026-06-03 12:00:34 -04:00
Jon Chambers 27fb4f227d Revert "Add an experiment to skip envelope expansion"
This reverts commit 0d32ca120d.
2026-06-03 12:00:34 -04:00
Ravi Khadiwala 324c4eafb6 Retire REST message retrieval
Remove `GET /v1/messages`
2026-06-03 10:59:41 -05:00
Jon Chambers 0d32ca120d Add an experiment to skip envelope expansion 2026-06-02 16:01:06 -04:00
Katherine 69a954e889 Discard stale ephemeral messages in FoundationDB 2026-06-02 16:00:25 -04:00
Jon Chambers d57ed3133c Avoid spurious padding 2026-06-01 16:51:56 -05:00
Jon Chambers 4a9f44b88c Use an all-zero IV and the parameter block as the first plaintext block 2026-06-01 16:51:56 -05:00
Jon Chambers 264897656b Actually make the "copy to S3" command available 2026-05-29 10:03:47 -04:00
Chris Eager f8f60c92ff Use getByPhoneNumberIdentifier in getAccountsForChangeNumber 2026-05-29 10:00:17 -04:00
Jon Chambers e6c24c373d Update to the latest version of the spam filter 2026-05-29 09:59:17 -04:00
Jon Chambers ab34e7c10e Update to the latest version of the spam filter 2026-05-28 16:50:48 -04:00
Jon Chambers c32d15617b Add a command for copying files from the open internet to S3 2026-05-28 16:17:37 -04:00
Jon Chambers 11136868ac Update to the latest version of the spam filter 2026-05-28 10:37:58 -04:00
Katherine 81167a8ae5 Add a device capability for username change sync messages 2026-05-27 15:34:01 -04:00
ameya-signal a6bf60e4cb Fix flaky test FoundationDbMessageStoreTest#getMessagesPublishMoreAfterQueueEmpty 2026-05-27 15:33:07 -04:00
Jon Chambers 15698aee46 Wire PaymentsGrpcService up as an authenticated service 2026-05-27 15:32:49 -04:00
Katherine b2942a8dbd Limit the number of unacknowledged FoundationDB messages 2026-05-27 15:32:27 -04:00
Jon Chambers f10cc26144 Include optional call ID hashes in call quality survey responses 2026-05-27 15:31:53 -04:00
Katherine Yen d4581931ff Update to the latest version of the spam filter 2026-05-27 15:31:32 -04:00
Chris Eager 41b953f5a1 Add rotation_id to ZK Credential key 2026-05-27 14:23:20 -05:00
Jon Chambers 3f1df3032f Update to the latest version of the spam filter 2026-05-26 09:17:49 -04:00
Jon Chambers cb6123125f Only send verification code push notifications to primary devices 2026-05-26 09:17:32 -04:00
Jon Chambers 9f6d80cb39 Update to the latest version of the spam filter 2026-05-21 14:33:55 -04:00
Jon Chambers da439e7144 Guard against NullPointerExceptions when getting details from a GoogleJsonResponseException 2026-05-21 13:10:44 -04:00
Jonathan Klabunde Tomer 22656396dc serialize account current profile version as base64 2026-05-21 13:10:03 -04:00
Chris Eager 90b280d6a0 Convert Subscriptions to sync DynamoDB client 2026-05-21 13:09:31 -04:00
Chris Eager 482a1b7bb5 Convert RedeemedReceiptsManager to sync DynamoDB client 2026-05-21 13:09:31 -04:00
Chris Eager fea4300d7d Convert RegistrationRecoveryPasswords to sync DynamoDB client 2026-05-21 13:08:49 -04:00
Chris Eager 66b0ed16d1 Convert VerificationSessions to sync DynamoDB client 2026-05-21 13:08:49 -04:00
Ameya Lokare defbc1c853 Implement FoundationDbMessageStream#acknowledgeMessage 2026-05-21 13:07:50 -04:00
198 changed files with 6483 additions and 2830 deletions

No files matched your search

+18 -6
View File
@@ -11,23 +11,35 @@ jobs:
contents: write
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
- uses: actions/setup-java@be666c2fcd27ec809703dec50e508c2fdc7f6654 # v5.2.0
with:
distribution: 'temurin'
java-version-file: .java-version
cache: 'maven'
- name: Compile and Build OpenAPI file
- name: Install gRPC documentation tooling
run: |
sudo apt-get update
sudo apt-get install -y protobuf-compiler
pip install sabledocs
- name: Generate OpenAPI documentation
run: ./mvnw compile
- name: Update Documentation
- name: Generate gRPC documentation
run: |
protoc -I service/src/main/proto service/src/main/proto/org/signal/chat/*.proto \
-o api-doc/grpc/descriptor.pb --include_source_info
cd api-doc/grpc && sabledocs
- name: Push documentation to gh-pages
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
cp -r api-doc/target/openapi/signal-server-openapi.yaml /tmp/
git config user.email "github@signal.org"
git config user.name "Documentation Updater"
git fetch origin gh-pages
git checkout gh-pages
cp /tmp/signal-server-openapi.yaml .
git diff --quiet || git commit -a -m "Updating documentation"
cp api-doc/target/openapi/signal-server-openapi.yaml .
rm -rf grpc
cp -r api-doc/grpc/sabledocs_output grpc
git add -A signal-server-openapi.yaml grpc
git diff --cached --quiet || git commit -m "Updating documentation"
git push origin gh-pages -q
+2 -2
View File
@@ -18,13 +18,13 @@ jobs:
id-token: write
contents: read
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
- uses: actions/setup-java@be666c2fcd27ec809703dec50e508c2fdc7f6654 # v5.2.0
with:
distribution: 'temurin'
java-version-file: .java-version
cache: 'maven'
- uses: aws-actions/configure-aws-credentials@ec61189d14ec14c8efccab744f656cffd0e33f37 # v6.1.0
- uses: aws-actions/configure-aws-credentials@e7f100cf4c008499ea8adda475de1042d6975c7b # v6.2.0
name: Configure AWS credentials from Test account
with:
role-to-assume: ${{ vars.AWS_ROLE }}
+1 -1
View File
@@ -25,7 +25,7 @@ jobs:
options: --name foundationdb1
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
- name: Set up JDK
uses: actions/setup-java@be666c2fcd27ec809703dec50e508c2fdc7f6654 # v5.2.0
with:
+4
View File
@@ -29,3 +29,7 @@ deployer.log
.classpath
.settings
.DS_Store
# Generated gRPC documentation build artifacts
/api-doc/grpc/descriptor.pb
/api-doc/grpc/sabledocs_output/
+2
View File
@@ -0,0 +1,2 @@
main-page-content-file = "../../service/src/main/proto/org/signal/chat/README.md"
markdown-extensions = ["fenced_code", "tables"]
+20
View File
@@ -10,6 +10,10 @@
<modelVersion>4.0.0</modelVersion>
<artifactId>integration-tests</artifactId>
<properties>
<jetty.http2-client.version>12.1.5</jetty.http2-client.version>
</properties>
<dependencies>
<dependency>
<groupId>org.whispersystems.textsecure</groupId>
@@ -21,6 +25,22 @@
<groupId>software.amazon.awssdk</groupId>
<artifactId>dynamodb</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.jetty.websocket</groupId>
<artifactId>jetty-websocket-jetty-api</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.jetty.websocket</groupId>
<artifactId>jetty-websocket-jetty-client</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.jetty.http2</groupId>
<artifactId>jetty-http2-client-transport</artifactId>
<version>${jetty.http2-client.version}</version>
</dependency>
</dependencies>
<build>
@@ -8,7 +8,10 @@ package org.signal.integration;
import java.time.Clock;
import java.time.Duration;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.signal.integration.config.Config;
import org.whispersystems.textsecuregcm.metrics.NoopAwsSdkMetricPublisher;
import org.whispersystems.textsecuregcm.registration.VerificationSession;
@@ -18,7 +21,6 @@ import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswords;
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
import org.whispersystems.textsecuregcm.storage.VerificationSessionManager;
import org.whispersystems.textsecuregcm.storage.VerificationSessions;
import org.whispersystems.textsecuregcm.util.Util;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
@@ -44,10 +46,10 @@ public class IntegrationTools {
config.dynamoDbClient().buildSyncClient(credentialsProvider, new NoopAwsSdkMetricPublisher());
final RegistrationRecoveryPasswords registrationRecoveryPasswords = new RegistrationRecoveryPasswords(
config.dynamoDbTables().registrationRecovery(), Duration.ofDays(1), dynamoDbAsyncClient, Clock.systemUTC());
config.dynamoDbTables().registrationRecovery(), Duration.ofDays(1), dynamoDbClient, Clock.systemUTC());
final VerificationSessions verificationSessions = new VerificationSessions(
dynamoDbAsyncClient, config.dynamoDbTables().verificationSessions(), Clock.systemUTC());
dynamoDbClient, config.dynamoDbTables().verificationSessions(), Clock.systemUTC());
return new IntegrationTools(
new RegistrationRecoveryPasswordsManager(registrationRecoveryPasswords),
@@ -68,16 +70,18 @@ public class IntegrationTools {
this.changeNumberWaitingPeriods = changeNumberWaitingPeriods;
}
public CompletableFuture<Void> populateRecoveryPassword(final String phoneNumber, final byte[] password) {
return phoneNumberIdentifiers
.getPhoneNumberIdentifier(phoneNumber)
.thenCompose(pni -> registrationRecoveryPasswordsManager.store(pni, password))
.thenRun(Util.NOOP);
public void populateRecoveryPassword(final String phoneNumber, final byte[] password) {
try {
final UUID pni = phoneNumberIdentifiers
.getPhoneNumberIdentifier(phoneNumber).get(5, TimeUnit.SECONDS);
registrationRecoveryPasswordsManager.store(pni, password);
} catch (ExecutionException | InterruptedException | TimeoutException e) {
throw new RuntimeException("failed to get pni", e);
}
}
public CompletableFuture<Optional<String>> peekVerificationSessionPushChallenge(final String sessionId) {
return verificationSessionManager.findForId(sessionId)
.thenApply(maybeSession -> maybeSession.map(VerificationSession::pushChallenge));
public Optional<String> peekVerificationSessionPushChallenge(final String sessionId) {
return verificationSessionManager.findForId(sessionId).map(VerificationSession::pushChallenge);
}
public void clearChangeNumberWaitingPeriod(TestUser user) {
@@ -20,18 +20,28 @@ import java.net.URL;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import org.apache.commons.lang3.tuple.Pair;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.http2.client.HTTP2Client;
import org.eclipse.jetty.http2.client.transport.HttpClientTransportOverHTTP2;
import org.eclipse.jetty.io.ClientConnector;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.eclipse.jetty.websocket.client.ClientUpgradeRequest;
import org.eclipse.jetty.websocket.client.WebSocketClient;
import org.signal.integration.config.Config;
import org.signal.libsignal.protocol.IdentityKey;
import org.signal.libsignal.protocol.ecc.ECKeyPair;
@@ -49,6 +59,7 @@ import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
import org.whispersystems.textsecuregcm.entities.RegistrationRequest;
import org.whispersystems.textsecuregcm.http.FaultTolerantHttpClient;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.util.CertificateUtil;
import org.whispersystems.textsecuregcm.util.HeaderUtils;
import org.whispersystems.textsecuregcm.util.HttpUtils;
import org.whispersystems.textsecuregcm.util.SystemMapper;
@@ -65,6 +76,8 @@ public final class Operations {
private static final FaultTolerantHttpClient CLIENT = buildClient();
private static final WebSocketClient WEB_SOCKET_CLIENT = buildWebSocketClient();
private Operations() {
// utility class
@@ -117,13 +130,13 @@ public final class Operations {
}
public static String peekVerificationSessionPushChallenge(final String sessionId) {
return INTEGRATION_TOOLS.peekVerificationSessionPushChallenge(sessionId).join()
return INTEGRATION_TOOLS.peekVerificationSessionPushChallenge(sessionId)
.orElseThrow(() -> new RuntimeException("push challenge not found for the verification session"));
}
public static byte[] populateRandomRecoveryPassword(final String number) {
final byte[] recoveryPassword = randomBytes(32);
INTEGRATION_TOOLS.populateRecoveryPassword(number, recoveryPassword).join();
INTEGRATION_TOOLS.populateRecoveryPassword(number, recoveryPassword);
return recoveryPassword;
}
@@ -218,14 +231,10 @@ public final class Operations {
}
private static <R> RequestBuilder withJsonBody(final String endpoint, final String method, final R input) {
try {
final byte[] body = SystemMapper.jsonMapper().writeValueAsBytes(input);
return new RequestBuilder(HttpRequest.newBuilder()
.header(HttpHeaders.CONTENT_TYPE, "application/json")
.method(method, HttpRequest.BodyPublishers.ofByteArray(body)), endpoint);
} catch (final JsonProcessingException e) {
throw new RuntimeException(e);
}
final byte[] body = encodeJsonBody(input);
return new RequestBuilder(HttpRequest.newBuilder()
.header(HttpHeaders.CONTENT_TYPE, "application/json")
.method(method, HttpRequest.BodyPublishers.ofByteArray(body)), endpoint);
}
public RequestBuilder authorized(final TestUser user) {
@@ -305,6 +314,7 @@ public final class Operations {
})
.join();
}
}
private static FaultTolerantHttpClient buildClient() {
@@ -317,6 +327,53 @@ public final class Operations {
}
}
private static WebSocketClient buildWebSocketClient() {
try {
final KeyStore trustStore = CertificateUtil.buildKeyStoreForPem(CONFIG.rootCert());
final SslContextFactory.Client sslContextFactory = new SslContextFactory.Client();
sslContextFactory.setTrustStore(trustStore);
final ClientConnector connector = new ClientConnector();
connector.setSslContextFactory(sslContextFactory);
final HTTP2Client http2Client = new HTTP2Client(connector);
final HttpClient httpClient = new HttpClient(new HttpClientTransportOverHTTP2(http2Client));
final WebSocketClient wsClient = new WebSocketClient(httpClient);
wsClient.start();
return wsClient;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static WebsocketClientSession authenticatedWebsocket(final TestUser user, final byte deviceId) throws IOException {
final String username = "%s.%d".formatted(user.aciUuid().toString(), deviceId);
return connect("/v1/websocket/", Map.of(HttpHeaders.AUTHORIZATION, HeaderUtils.basicAuthHeader(username, user.accountPassword())));
}
public static WebsocketClientSession anonymousWebsocket() throws IOException {
return connect("/v1/websocket/", Collections.emptyMap());
}
private static WebsocketClientSession connect(
final String path,
final Map<String, String> headers) throws IOException {
final URI uri = URI.create("wss://grpc." + CONFIG.domain() + path);
final ClientUpgradeRequest request = new ClientUpgradeRequest(uri);
headers.forEach(request::setHeader);
final WebsocketClientSession listener = new WebsocketClientSession();
try {
WEB_SOCKET_CLIENT.connect(listener, request).get(5, TimeUnit.SECONDS);
} catch (Exception e) {
throw new IOException(e);
}
logger.info("Successfully connected to websocket on {}", uri);
return listener;
}
private static Config loadConfigFromClasspath(final String filename) {
try {
final URL configFileUrl = Resources.getResource(filename);
@@ -345,4 +402,12 @@ public final class Operations {
final byte[] signature = identityKeyPair.getPrivateKey().calculateSignature(pubKey.serialize());
return new KEMSignedPreKey(id, pubKey, signature);
}
public static <R> byte[] encodeJsonBody(final R input) {
try {
return SystemMapper.jsonMapper().writeValueAsBytes(input);
} catch (final JsonProcessingException e) {
throw new RuntimeException(e);
}
}
}
@@ -0,0 +1,150 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.signal.integration;
import com.google.protobuf.InvalidProtocolBufferException;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.ByteBuffer;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicLong;
import org.eclipse.jetty.websocket.api.Callback;
import org.eclipse.jetty.websocket.api.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.util.SystemMapper;
import org.whispersystems.websocket.messages.WebSocketMessage;
import org.whispersystems.websocket.messages.WebSocketMessageFactory;
import org.whispersystems.websocket.messages.WebSocketRequestMessage;
import org.whispersystems.websocket.messages.WebSocketResponseMessage;
import org.whispersystems.websocket.messages.protobuf.ProtobufWebSocketMessageFactory;
public class WebsocketClientSession implements Session.Listener.AutoDemanding {
private static final Logger log = LoggerFactory.getLogger(WebsocketClientSession.class);
private final WebSocketMessageFactory messageFactory = new ProtobufWebSocketMessageFactory();
private final AtomicLong requestId = new AtomicLong();
private final ConcurrentHashMap<Long, CompletableFuture<WebSocketResponseMessage>> responseFutures = new ConcurrentHashMap<>();
private final List<MessageProtos.Envelope> receivedEnvelopes = new CopyOnWriteArrayList<>();
private final CompletableFuture<Session> opened = new CompletableFuture<>();
private final CompletableFuture<Void> queueEmpty = new CompletableFuture<>();
private final CompletableFuture<Integer> closed = new CompletableFuture<>();
@Override
public void onWebSocketOpen(final Session session) {
opened.complete(session);
}
@Override
public void onWebSocketBinary(final ByteBuffer payload, final Callback callback) {
try {
final WebSocketMessage message = messageFactory.parseMessage(payload);
switch (message.getType()) {
case REQUEST_MESSAGE -> {
log.info("received request message {} {}", message.getRequestMessage().getVerb(), message.getRequestMessage().getPath());
switch (message.getRequestMessage().getPath()) {
case "/api/v1/message" -> acknowledge(message.getRequestMessage());
case "/api/v1/queue/empty" -> queueEmpty.complete(null);
default -> throw new IllegalStateException("Unexpected path: " + message.getRequestMessage().getPath());
}
}
case RESPONSE_MESSAGE -> {
final WebSocketResponseMessage response = message.getResponseMessage();
log.info("received response message {}", response.getStatus());
final CompletableFuture<WebSocketResponseMessage> future = responseFutures.remove(response.getRequestId());
if (future == null) {
throw new IllegalArgumentException("Received response with no matching request: {}" + response.getRequestId());
}
future.complete(response);
}
default -> throw new IllegalStateException("Unexpected message type: " + message.getType());
}
callback.succeed();
} catch (final Exception e) {
log.warn("Failed to process message received over the websocket", e);
callback.fail(e);
opened.join().close(1006, e.getMessage(), Callback.NOOP);
}
}
@Override
public void onWebSocketClose(final int statusCode, final String reason, final Callback callback) {
log.info("Received websocket close: {}", statusCode);
closed.complete(statusCode);
final IOException exception = new IOException("WebSocket closed: " + statusCode + " " + reason);
responseFutures.values()
.forEach(f -> f.completeExceptionally(exception));
responseFutures.clear();
if (!queueEmpty.isDone()) {
queueEmpty.completeExceptionally(exception);
}
callback.succeed();
}
public <T> WebSocketResponseMessage sendRequest(
final String verb,
final String path,
final List<String> headers,
final T body) {
final Session session = opened.join();
final long id = requestId.incrementAndGet();
final CompletableFuture<WebSocketResponseMessage> future = new CompletableFuture<>();
responseFutures.put(id, future);
final Optional<byte[]> maybeBody = Optional.ofNullable(body).map(Operations::encodeJsonBody);
final byte[] bytes = messageFactory.createRequest(Optional.of(id), verb, path, headers, maybeBody).toByteArray();
session.sendBinary(ByteBuffer.wrap(bytes), Callback.from(() -> {}, throwable -> {
if (responseFutures.remove(id) != null) {
future.completeExceptionally(throwable);
}
}));
return future.join();
}
public List<MessageProtos.Envelope> getReceivedEnvelopes() {
return receivedEnvelopes;
}
public void waitForQueueEmpty() {
queueEmpty.join();
}
public void close(final int closeCode) {
final Session session = opened.join();
session.close(closeCode, "client close", Callback.NOOP);
closed.join();
}
private void acknowledge(WebSocketRequestMessage message) {
final byte[] envelopeBytes = message.getBody()
.orElseThrow(() -> new IllegalStateException("Messages should have a response body"));
try {
final MessageProtos.Envelope envelope = MessageProtos.Envelope.parseFrom(envelopeBytes);
receivedEnvelopes.add(envelope);
final Session session = opened.join();
final WebSocketMessage response = messageFactory.createResponse(message.getRequestId(), 200, "",
Collections.emptyList(), Optional.empty());
session.sendBinary(ByteBuffer.wrap(response.toByteArray()), Callback.NOOP);
} catch (InvalidProtocolBufferException e) {
throw new IllegalStateException(e);
}
}
public static <R> R decode(Class<R> expectedType, WebSocketResponseMessage message) {
try {
return SystemMapper.jsonMapper()
.readValue(message.getBody().orElseThrow(() -> new IllegalStateException("No response body")), expectedType);
} catch (final IOException e) {
throw new UncheckedIOException(e);
}
}
}
@@ -6,43 +6,72 @@
package org.signal.integration;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
import com.google.common.net.HttpHeaders;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.List;
import org.apache.commons.lang3.tuple.Pair;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import jakarta.ws.rs.core.MediaType;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.entities.IncomingMessage;
import org.whispersystems.textsecuregcm.entities.IncomingMessageList;
import org.whispersystems.textsecuregcm.entities.OutgoingMessageEntityList;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.entities.SendMessageResponse;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.websocket.messages.WebSocketResponseMessage;
@Timeout(value = 1, unit = TimeUnit.MINUTES, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
public class MessagingTest {
TestUser userA;
TestUser userB;
@BeforeEach
public void setup() {
userA = Operations.newRegisteredUser("+19995550102");
userB = Operations.newRegisteredUser("+19995550103");
}
@AfterEach
public void teardown() {
Operations.deleteUser(userA);
Operations.deleteUser(userB);
}
@Test
public void testSendMessageUnsealed() {
final TestUser userA = Operations.newRegisteredUser("+19995550102");
final TestUser userB = Operations.newRegisteredUser("+19995550103");
try {
public void testSendMessageUnsealed() throws IOException {
final byte[] expectedContent = "Hello, World!".getBytes(StandardCharsets.UTF_8);
final IncomingMessage message = new IncomingMessage(1, Device.PRIMARY_ID, userB.registrationId(), expectedContent);
final IncomingMessageList messages = new IncomingMessageList(List.of(message), false, true, System.currentTimeMillis());
Operations
.apiPut("/v1/messages/%s".formatted(userB.aciUuid().toString()), messages)
.authorized(userA)
.execute(SendMessageResponse.class);
final WebsocketClientSession websocketA = Operations.authenticatedWebsocket(userA, Device.PRIMARY_ID);
final WebSocketResponseMessage responseMessage = websocketA.sendRequest(
"PUT",
"/v1/messages/%s".formatted(userB.aciUuid().toString()),
List.of(HttpHeaders.CONTENT_TYPE + ":" + MediaType.APPLICATION_JSON),
messages);
assertEquals(200, responseMessage.getStatus());
assertDoesNotThrow(() -> WebsocketClientSession.decode(SendMessageResponse.class, responseMessage));
final Pair<Integer, OutgoingMessageEntityList> receiveMessages = Operations.apiGet("/v1/messages")
.authorized(userB)
.execute(OutgoingMessageEntityList.class);
final WebsocketClientSession websocketB = Operations.authenticatedWebsocket(userB, Device.PRIMARY_ID);
assertTimeoutPreemptively(Duration.ofSeconds(5), websocketB::waitForQueueEmpty);
final byte[] actualContent = receiveMessages.getRight().messages().getFirst().content();
assertArrayEquals(expectedContent, actualContent);
} finally {
Operations.deleteUser(userA);
Operations.deleteUser(userB);
}
assertEquals(1, websocketB.getReceivedEnvelopes().size());
final MessageProtos.Envelope envelope = websocketB.getReceivedEnvelopes().getFirst();
assertArrayEquals(expectedContent, envelope.getContent().toByteArray());
websocketB.close(1000);
websocketA.close(1000);
}
}
@@ -152,15 +152,20 @@ import org.whispersystems.textsecuregcm.grpc.AttachmentsGrpcService;
import org.whispersystems.textsecuregcm.grpc.BackupsAnonymousGrpcService;
import org.whispersystems.textsecuregcm.grpc.BackupsGrpcService;
import org.whispersystems.textsecuregcm.grpc.CallQualitySurveyGrpcService;
import org.whispersystems.textsecuregcm.grpc.CallingGrpcService;
import org.whispersystems.textsecuregcm.grpc.ChallengeGrpcService;
import org.whispersystems.textsecuregcm.grpc.CredentialsAnonymousGrpcService;
import org.whispersystems.textsecuregcm.grpc.CredentialsGrpcService;
import org.whispersystems.textsecuregcm.grpc.DevicesGrpcService;
import org.whispersystems.textsecuregcm.grpc.DonationsGrpcService;
import org.whispersystems.textsecuregcm.grpc.ErrorConformanceInterceptor;
import org.whispersystems.textsecuregcm.grpc.ErrorMappingInterceptor;
import org.whispersystems.textsecuregcm.grpc.ExternalServiceCredentialsAnonymousGrpcService;
import org.whispersystems.textsecuregcm.grpc.ExternalServiceCredentialsGrpcService;
import org.whispersystems.textsecuregcm.grpc.ExternalServiceDefinitions;
import org.whispersystems.textsecuregcm.grpc.GroupSendTokenUtil;
import org.whispersystems.textsecuregcm.grpc.GrpcAllowListInterceptor;
import org.whispersystems.textsecuregcm.grpc.KeysAnonymousGrpcService;
import org.whispersystems.textsecuregcm.grpc.KeysGrpcService;
import org.whispersystems.textsecuregcm.grpc.MessageDispatcher;
import org.whispersystems.textsecuregcm.grpc.MessagesAnonymousGrpcService;
import org.whispersystems.textsecuregcm.grpc.MessagesGrpcService;
import org.whispersystems.textsecuregcm.grpc.MetricServerInterceptor;
@@ -298,6 +303,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 +377,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",
@@ -393,7 +400,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
@Override
public void run(WhisperServerConfiguration config, Environment environment) throws Exception {
final Clock clock = Clock.systemUTC();
final int availableProcessors = Runtime.getRuntime().availableProcessors();
final AwsCredentialsProvider awsCredentialsProvider = config.getAwsCredentialsConfiguration().build();
@@ -505,7 +511,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
MessagesDynamoDb messagesDynamoDb = new MessagesDynamoDb(dynamoDbClient, dynamoDbAsyncClient,
config.getDynamoDbTables().getMessages().getTableName(),
config.getDynamoDbTables().getMessages().getExpiration(),
messageDeletionAsyncExecutor, experimentEnrollmentManager);
messageDeletionAsyncExecutor);
RemoteConfigs remoteConfigs = new RemoteConfigs(dynamoDbClient,
config.getDynamoDbTables().getRemoteConfig().getTableName());
PushChallengeDynamoDb pushChallengeDynamoDb = new PushChallengeDynamoDb(dynamoDbClient,
@@ -516,10 +522,10 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
RegistrationRecoveryPasswords registrationRecoveryPasswords = new RegistrationRecoveryPasswords(
config.getDynamoDbTables().getRegistrationRecovery().getTableName(),
config.getDynamoDbTables().getRegistrationRecovery().getExpiration(),
dynamoDbAsyncClient,
dynamoDbClient,
clock);
final VerificationSessions verificationSessions = new VerificationSessions(dynamoDbAsyncClient,
final VerificationSessions verificationSessions = new VerificationSessions(dynamoDbClient,
config.getDynamoDbTables().getVerificationSessions().getTableName(), clock);
final ClientResources sharedClientResources = ClientResources.builder()
@@ -696,7 +702,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
ProfilesManager profilesManager = new ProfilesManager(profilesV1, profiles, cacheCluster, retryExecutor, asyncCdnS3Client,
config.getCdnConfiguration().bucket());
MessagesCache messagesCache = new MessagesCache(messagesCluster, messageDeliveryScheduler,
messageDeletionAsyncExecutor, retryExecutor, clock, experimentEnrollmentManager);
messageDeletionAsyncExecutor, retryExecutor, clock);
ClientReleaseManager clientReleaseManager = new ClientReleaseManager(clientReleases,
recurringJobExecutor,
config.getClientReleaseConfiguration().refreshInterval(),
@@ -730,17 +736,17 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
IssuedReceiptsManager issuedReceiptsManager = new IssuedReceiptsManager(
config.getDynamoDbTables().getIssuedReceipts().getTableName(),
config.getDynamoDbTables().getIssuedReceipts().getExpiration(),
dynamoDbAsyncClient,
dynamoDbClient,
config.getDynamoDbTables().getIssuedReceipts().getGenerator(),
config.getDynamoDbTables().getIssuedReceipts().getmaxIssuedReceiptsPerPaymentId());
OneTimeDonationsManager oneTimeDonationsManager = new OneTimeDonationsManager(
config.getDynamoDbTables().getOnetimeDonations().getTableName(), config.getDynamoDbTables().getOnetimeDonations().getExpiration(), dynamoDbAsyncClient);
config.getDynamoDbTables().getOnetimeDonations().getTableName(), config.getDynamoDbTables().getOnetimeDonations().getExpiration(), dynamoDbClient);
RedeemedReceiptsManager redeemedReceiptsManager = new RedeemedReceiptsManager(clock,
config.getDynamoDbTables().getRedeemedReceipts().getTableName(),
dynamoDbAsyncClient,
dynamoDbClient,
config.getDynamoDbTables().getRedeemedReceipts().getExpiration());
Subscriptions subscriptions = new Subscriptions(
config.getDynamoDbTables().getSubscriptions().getTableName(), dynamoDbAsyncClient);
config.getDynamoDbTables().getSubscriptions().getTableName(), dynamoDbClient);
MessageDeliveryLoopMonitor messageDeliveryLoopMonitor =
config.logMessageDeliveryLoops() ? new RedisMessageDeliveryLoopMonitor(rateLimitersCluster) : new NoopMessageDeliveryLoopMonitor();
CallQualitySurveyManager callQualitySurveyManager = new CallQualitySurveyManager(asnInfoProviderSupplier,
@@ -982,17 +988,31 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
final RequireAuthenticationInterceptor requireAuthenticationInterceptor = new RequireAuthenticationInterceptor(accountAuthenticator);
final ProhibitAuthenticationInterceptor prohibitAuthenticationInterceptor = new ProhibitAuthenticationInterceptor();
final GroupSendTokenUtil groupSendTokenUtil = new GroupSendTokenUtil(zkSecretParams, Clock.systemUTC());
final MessageMetrics messageMetrics = new MessageMetrics();
final MessageDispatcher messageDispatcher = new MessageDispatcher(receiptSender, messagesManager, messageMetrics,
pushNotificationManager, pushNotificationScheduler, messageDeliveryLoopMonitor, disconnectionRequestManager,
clientReleaseManager);
final CertificateGenerator certificateGenerator =
new CertificateGenerator(config.getDeliveryCertificate().certificate(),
config.getDeliveryCertificate().ecPrivateKey(),
config.getDeliveryCertificate().expiresDays(),
config.getDeliveryCertificate().embedSigner());
final List<ServerServiceDefinition> authenticatedServices = Stream.of(
new AccountsGrpcService(accountsManager, rateLimiters, usernameHashZkProofVerifier, registrationRecoveryPasswordsManager),
ExternalServiceCredentialsGrpcService.createForAllExternalServices(config, rateLimiters),
new CallingGrpcService(cloudflareTurnCredentialsManager, rateLimiters),
new CredentialsGrpcService(accountsManager, certificateGenerator, zkAuthOperations, callingGenericZkSecretParams, rateLimiters, Clock.systemUTC(), ExternalServiceDefinitions.createExternalServiceList(config, Clock.systemUTC())),
new KeysGrpcService(accountsManager, keysManager, rateLimiters),
new ProfileGrpcService(clock, accountsManager, profilesManager, dynamicConfigurationManager, config.getBadges(), profileCdnPolicyGenerator, profileCdnPolicySigner, profileBadgeConverter, rateLimiters),
new MessagesGrpcService(accountsManager, rateLimiters, messageSender, messageByteLimitCardinalityEstimator, spamChecker, Clock.systemUTC()),
new MessagesGrpcService(accountsManager, rateLimiters, messageSender, messageByteLimitCardinalityEstimator, spamChecker, messageDispatcher, Clock.systemUTC()),
new BackupsGrpcService(accountsManager, backupAuthManager, backupMetrics),
new DevicesGrpcService(accountsManager),
new AttachmentsGrpcService(experimentEnrollmentManager, rateLimiters,
gcsAttachmentGenerator, tusAttachmentGenerator, config.getAttachments().maxAttachmentUploadSizeInBytes()))
gcsAttachmentGenerator, tusAttachmentGenerator, config.getAttachments().maxAttachmentUploadSizeInBytes()),
new PaymentsGrpcService(currencyManager),
new ChallengeGrpcService(accountsManager, rateLimitChallengeManager, challengeConstraintChecker),
new DonationsGrpcService(clock, zkReceiptOperations, redeemedReceiptsManager, accountsManager, config.getBadges(), ReceiptCredentialPresentation::new))
.map(bindableService -> ServerInterceptors.intercept(bindableService,
// Note: interceptors run in the reverse order they are added; the remote deprecation filter
// depends on the user-agent context so it has to come first here!
@@ -1010,10 +1030,9 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new CallQualitySurveyGrpcService(callQualitySurveyManager, rateLimiters),
new KeysAnonymousGrpcService(accountsManager, keysManager, zkSecretParams, Clock.systemUTC()),
new ProfileAnonymousGrpcService(accountsManager, profilesManager, profileBadgeConverter, zkSecretParams),
new PaymentsGrpcService(currencyManager),
new MessagesAnonymousGrpcService(accountsManager, rateLimiters, messageSender, groupSendTokenUtil, messageByteLimitCardinalityEstimator, spamChecker, Clock.systemUTC()),
new BackupsAnonymousGrpcService(backupManager, backupMetrics, config.getAttachments().maxAttachmentUploadSizeInBytes(), config.getAttachments().maxMessageBackupUploadSizeInBytes()),
ExternalServiceCredentialsAnonymousGrpcService.create(accountsManager, config))
new CredentialsAnonymousGrpcService(accountsManager, ExternalServiceDefinitions.SVR.generatorFactory().apply(config, Clock.systemUTC())))
.map(bindableService -> ServerInterceptors.intercept(bindableService,
// Note: interceptors run in the reverse order they are added; the remote deprecation filter
// depends on the user-agent context so it has to come first here!
@@ -1078,7 +1097,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
final String provisioningWebsocketServletPath = "/v1/websocket/provisioning/";
MetricsHttpEventHandler.configure(environment, Metrics.globalRegistry, clientReleaseManager, Set.of(websocketServletPath, provisioningWebsocketServletPath, "/health-check"));
final MessageMetrics messageMetrics = new MessageMetrics();
// BufferingInterceptor is needed on the base environment but not the WebSocketEnvironment,
// because we handle serialization of http responses on the websocket on our own and can
@@ -1136,9 +1154,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new CallRoutingControllerV2(rateLimiters, cloudflareTurnCredentialsManager),
new CallLinkController(rateLimiters, callingGenericZkSecretParams),
new CallQualitySurveyController(callQualitySurveyManager),
new CertificateController(accountsManager, new CertificateGenerator(config.getDeliveryCertificate().certificate(),
config.getDeliveryCertificate().ecPrivateKey(), config.getDeliveryCertificate().expiresDays(), config.getDeliveryCertificate().embedSigner()),
zkAuthOperations, callingGenericZkSecretParams, clock),
new CertificateController(accountsManager, certificateGenerator, zkAuthOperations, callingGenericZkSecretParams, clock),
new ChallengeController(accountsManager, rateLimitChallengeManager, challengeConstraintChecker),
new DeviceController(accountsManager, rateLimiters, persistentTimer),
new DeviceCheckController(clock, accountsManager, backupAuthManager, appleDeviceCheckManager, rateLimiters,
@@ -1149,11 +1165,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
ReceiptCredentialPresentation::new),
new KeysController(rateLimiters, keysManager, accountsManager, zkSecretParams, Clock.systemUTC()),
new KeyTransparencyController(keyTransparencyServiceClient),
new MessageController(rateLimiters, messageByteLimitCardinalityEstimator, messageSender,
accountsManager, messagesManager, phoneNumberIdentifiers, pushNotificationManager, pushNotificationScheduler,
reportMessageManager, messageDeliveryScheduler, clientReleaseManager,
zkSecretParams, spamChecker, messageMetrics, messageDeliveryLoopMonitor,
Clock.systemUTC()),
new MessageController(rateLimiters, messageByteLimitCardinalityEstimator, messageSender, accountsManager,
phoneNumberIdentifiers, reportMessageManager, zkSecretParams, spamChecker, Clock.systemUTC()),
new PaymentsController(currencyManager, paymentsCredentialsGenerator),
new ProfileController(clock, rateLimiters, accountsManager, profilesManager, dynamicConfigurationManager,
profileBadgeConverter, config.getBadges(), profileCdnPolicyGenerator, profileCdnPolicySigner,
@@ -15,6 +15,7 @@ import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.core.Response;
import java.security.MessageDigest;
import java.time.Duration;
import java.util.UUID;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
@@ -129,10 +130,11 @@ public class PhoneVerificationTokenManager {
}
try {
final boolean verified = phoneNumberIdentifiers.getPhoneNumberIdentifier(number)
.thenCompose(phoneNumberIdentifier -> registrationRecoveryPasswordsManager.verify(phoneNumberIdentifier, recoveryPassword))
final UUID phoneNumberIdentifier = phoneNumberIdentifiers.getPhoneNumberIdentifier(number)
.get(VERIFICATION_TIMEOUT_SECONDS, TimeUnit.SECONDS);
final boolean verified = registrationRecoveryPasswordsManager.verify(phoneNumberIdentifier, recoveryPassword);
if (!verified) {
throw new ForbiddenException("recoveryPassword couldn't be verified");
}
@@ -152,7 +152,7 @@ public class RegistrationLockVerificationManager {
// This allows users to re-register via registration recovery password
// instead of always being forced to fall back to SMS verification.
if (!phoneVerificationType.equals(PhoneVerificationRequest.VerificationType.RECOVERY_PASSWORD) || clientRegistrationLock != null) {
registrationRecoveryPasswordsManager.remove(updatedAccount.getIdentifier(IdentityType.PNI)).join();
registrationRecoveryPasswordsManager.remove(updatedAccount.getIdentifier(IdentityType.PNI));
}
final List<Byte> deviceIds = updatedAccount.getDevices().stream().map(Device::getId).toList();
@@ -266,8 +266,7 @@ public class BackupAuthManager {
}
boolean receiptAllowed = redeemedReceiptsManager
.put(receiptSerial, receiptExpiration.getEpochSecond(), receiptLevel, account.getUuid())
.join();
.put(receiptSerial, receiptExpiration.getEpochSecond(), receiptLevel, account.getUuid());
if (!receiptAllowed) {
throw new BackupBadReceiptException("receipt serial is already redeemed");
}
@@ -86,7 +86,7 @@ public class Cdn3RemoteStorageManager implements RemoteStorageManager {
public CompletionStage<Void> copy(
final int sourceCdn,
final String sourceKey,
final int expectedSourceLength,
final long expectedSourceLength,
final MediaEncryptionParameters encryptionParameters,
final String destinationKey) {
final String sourceScheme = this.sourceSchemes.get(sourceCdn);
@@ -132,10 +132,10 @@ public class Cdn3RemoteStorageManager implements RemoteStorageManager {
*/
record Cdn3CopyRequest(
String encryptionKey, String hmacKey,
SourceDescriptor source, int expectedSourceLength,
SourceDescriptor source, long expectedSourceLength,
String dst) {
Cdn3CopyRequest(MediaEncryptionParameters parameters, SourceDescriptor source, int expectedSourceLength,
Cdn3CopyRequest(MediaEncryptionParameters parameters, SourceDescriptor source, long expectedSourceLength,
String dst) {
this(Base64.getEncoder().encodeToString(parameters.aesEncryptionKey().getEncoded()),
Base64.getEncoder().encodeToString(parameters.hmacSHA256Key().getEncoded()),
@@ -18,7 +18,7 @@ import com.google.common.annotations.VisibleForTesting;
public record CopyParameters(
int sourceCdn,
String sourceKey,
int sourceLength,
long sourceLength,
MediaEncryptionParameters encryptionParameters,
byte[] destinationMediaId) {
@@ -35,16 +35,17 @@ public record CopyParameters(
///
/// @return the size, in bytes, of the ciphertext of a media object with the given `inputSize`
@VisibleForTesting
static long destinationObjectSize(final int inputSize) {
static long destinationObjectSize(final long inputSize) {
if (inputSize < 0) {
throw new IllegalArgumentException("Size must be non-negative, but was " + inputSize);
}
// AES-256 has 16-byte block size, and always adds a block if the plaintext is a multiple of the block size
final long numBlocks = ((long) inputSize + 16) / 16;
final long numBlocks = Math.addExact(inputSize, 16L) / 16;
final long cipherTextLength = Math.multiplyExact(numBlocks, 16);
// 16-byte IV will be generated and prepended to the ciphertext
// 16-byte IV will be generated and prepended to the ciphertext.
// IV + AES-256 encrypted data + HmacSHA256
return 16 + (numBlocks * 16) + 32;
return Math.addExact(cipherTextLength, 16L + 32);
}
}
@@ -35,7 +35,7 @@ public interface RemoteStorageManager {
CompletionStage<Void> copy(
int sourceCdn,
String sourceKey,
int expectedSourceLength,
long expectedSourceLength,
MediaEncryptionParameters encryptionParameters,
String dstKey);
@@ -16,6 +16,7 @@ import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.function.Function;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -52,20 +53,20 @@ public class CaptchaChecker {
* @param userAgent User-Agent of the solver
* @return An {@link AssessmentResult} indicating whether the solution should be accepted, and a score that can be
* used for metrics
* @throws IOException if there is an error validating the captcha with the underlying service
* @throws BadRequestException if input is not in the expected format
* @throws IOException if there is an error validating the captcha with the underlying service
* @throws InvalidCaptchaArgumentException if input is not in the expected format
*/
public AssessmentResult verify(
final Optional<UUID> maybeAci,
final Action expectedAction,
final String input,
final String ip,
final String userAgent) throws IOException {
@Nullable final String userAgent) throws IOException, InvalidCaptchaArgumentException {
final String[] parts = input.split("\\" + SEPARATOR, 4);
// we allow missing actions, if we're missing 1 part, assume it's the action
if (parts.length < 4) {
throw new BadRequestException("too few parts");
throw new InvalidCaptchaArgumentException("too few parts");
}
final String prefix = parts[0];
@@ -78,30 +79,30 @@ public class CaptchaChecker {
// This is a "short" solution that points to the actual solution. We need to fetch the
// full solution before proceeding
provider = prefix.substring(0, prefix.length() - SHORT_SUFFIX.length());
token = shortCodeExpander.retrieve(token).orElseThrow(() -> new BadRequestException("invalid shortcode"));
token = shortCodeExpander.retrieve(token).orElseThrow(() -> new InvalidCaptchaArgumentException("invalid shortcode"));
}
final CaptchaClient client = this.captchaClientSupplier.apply(provider);
if (client == null) {
throw new BadRequestException("invalid captcha scheme");
throw new InvalidCaptchaArgumentException("invalid captcha scheme");
}
final Action parsedAction = Action.parse(action)
.orElseThrow(() -> {
Metrics.counter(INVALID_ACTION_COUNTER_NAME, "action", action).increment();
return new BadRequestException("invalid captcha action");
Metrics.counter(INVALID_ACTION_COUNTER_NAME).increment();
return new InvalidCaptchaArgumentException("invalid captcha action");
});
if (!parsedAction.equals(expectedAction)) {
Metrics.counter(INVALID_ACTION_COUNTER_NAME, "action", action).increment();
throw new BadRequestException("invalid captcha action");
throw new InvalidCaptchaArgumentException("invalid captcha action");
}
final Set<String> allowedSiteKeys = client.validSiteKeys(parsedAction);
if (!allowedSiteKeys.contains(siteKey)) {
logger.debug("invalid site-key {}, action={}, token={}", siteKey, action, token);
Metrics.counter(INVALID_SITEKEY_COUNTER_NAME, "action", action).increment();
throw new BadRequestException("invalid captcha site-key");
throw new InvalidCaptchaArgumentException("invalid captcha site-key");
}
final AssessmentResult result = client.verify(maybeAci, siteKey, parsedAction, token, ip, userAgent);
@@ -5,6 +5,7 @@
package org.whispersystems.textsecuregcm.captcha;
import javax.annotation.Nullable;
import java.io.IOException;
import java.util.Optional;
import java.util.Set;
@@ -42,7 +43,7 @@ public interface CaptchaClient {
final Action action,
final String token,
final String ip,
final String userAgent) throws IOException;
@Nullable final String userAgent) throws IOException;
static CaptchaClient noop() {
return new CaptchaClient() {
@@ -58,7 +59,7 @@ public interface CaptchaClient {
@Override
public AssessmentResult verify(final Optional<UUID> maybeAci, final String siteKey, final Action action, final String token, final String ip,
final String userAgent) throws IOException {
@Nullable final String userAgent) throws IOException {
return AssessmentResult.alwaysValid();
}
};
@@ -0,0 +1,15 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.captcha;
/**
* Indicates that a captcha solution was malformed
*/
public class InvalidCaptchaArgumentException extends Exception {
public InvalidCaptchaArgumentException(String message) {
super(message);
}
}
@@ -19,7 +19,7 @@ public class RegistrationCaptchaManager {
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
public Optional<AssessmentResult> assessCaptcha(final Optional<UUID> aci, final Optional<String> captcha, final String sourceHost, final String userAgent)
throws IOException {
throws IOException, InvalidCaptchaArgumentException{
return captcha.isPresent()
? Optional.of(captchaChecker.verify(aci, Action.REGISTRATION, captcha.get(), sourceHost, userAgent))
: Optional.empty();
@@ -0,0 +1,19 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration;
import jakarta.validation.constraints.AssertTrue;
import org.apache.commons.lang3.StringUtils;
import javax.annotation.Nullable;
public record FoundationDbClusterConfiguration(@Nullable String clusterFileUrl,
@Nullable String clusterFileContents) {
@AssertTrue
public boolean isSingleClusterFileSourceSpecified() {
return StringUtils.isBlank(clusterFileUrl) ^ StringUtils.isBlank(clusterFileContents);
}
}
@@ -0,0 +1,51 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration;
import jakarta.validation.Valid;
import jakarta.validation.constraints.AssertTrue;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.PositiveOrZero;
import jakarta.validation.constraints.Size;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStore;
public record FoundationDbMessagesConfiguration(@NotEmpty Map<String, @Valid FoundationDbClusterConfiguration> clusters,
@NotEmpty Map<@PositiveOrZero @Max(FoundationDbMessageStore.MAX_EPOCHS - 1) Integer, @Size(min = 1, max = FoundationDbMessageStore.MAX_SHARDS - 1) List<String>> epochs,
@PositiveOrZero @Max(FoundationDbMessageStore.MAX_EPOCHS - 1) int activeEpoch) {
@AssertTrue
boolean isEveryEpochClusterConfigured() {
for (final List<String> clustersInEpoch : epochs().values()) {
for (final String cluster : clustersInEpoch) {
if (!clusters.containsKey(cluster)) {
return false;
}
}
}
return true;
}
@AssertTrue
boolean isEveryEpochFreeOfDuplicates() {
for (final List<String> clustersInEpoch : epochs().values()) {
if (new HashSet<>(clustersInEpoch).size() != clustersInEpoch.size()) {
return false;
}
}
return true;
}
@AssertTrue
boolean isActiveEpochConfigured() {
return epochs().containsKey(activeEpoch());
}
}
@@ -244,8 +244,7 @@ public class AccountController {
// if registration recovery password was sent to us, store it (or refresh its expiration)
attributes.recoveryPassword().ifPresent(registrationRecoveryPassword -> {
final boolean rrpCreated = registrationRecoveryPasswordsManager
.store(updatedAccount.getIdentifier(IdentityType.PNI), registrationRecoveryPassword)
.join();
.store(updatedAccount.getIdentifier(IdentityType.PNI), registrationRecoveryPassword);
Metrics.counter(RECOVERY_PASSWORD_SET_COUNTER_NAME, Tags.of(
UserAgentTagUtil.getPlatformTag(userAgent),
Tag.of("outcome", rrpCreated ? "created" : "updated")))
@@ -20,7 +20,6 @@ import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import java.security.InvalidKeyException;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
@@ -76,8 +75,7 @@ public class CertificateController {
@Produces(MediaType.APPLICATION_JSON)
@Path("/delivery")
public DeliveryCertificate getDeliveryCertificate(@Auth AuthenticatedDevice auth,
@QueryParam("includeE164") @DefaultValue("true") boolean includeE164)
throws InvalidKeyException {
@QueryParam("includeE164") @DefaultValue("true") boolean includeE164) {
Metrics.counter(GENERATE_DELIVERY_CERTIFICATE_COUNTER_NAME, INCLUDE_E164_TAG_NAME, String.valueOf(includeE164))
.increment();
@@ -34,6 +34,7 @@ import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.captcha.InvalidCaptchaArgumentException;
import org.whispersystems.textsecuregcm.entities.AnswerCaptchaChallengeRequest;
import org.whispersystems.textsecuregcm.entities.AnswerChallengeRequest;
import org.whispersystems.textsecuregcm.entities.AnswerPushChallengeRequest;
@@ -97,7 +98,7 @@ public class ChallengeController {
Tags tags = Tags.of(UserAgentTagUtil.getPlatformTag(userAgent));
final ChallengeConstraints constraints = challengeConstraintChecker.challengeConstraints(
final ChallengeConstraints constraints = challengeConstraintChecker.challengeConstraintsHttp(
requestContext, account);
try {
if (answerRequest instanceof final AnswerPushChallengeRequest pushChallengeRequest) {
@@ -126,6 +127,8 @@ public class ChallengeController {
} else {
tags = tags.and(CHALLENGE_TYPE_TAG, "unrecognized");
}
} catch (final InvalidCaptchaArgumentException e) {
return Response.status(Response.Status.BAD_REQUEST.getStatusCode(), e.getMessage()).build();
} catch (final IOException e) {
logger.error("error assessing captcha during challenge response handling", e);
return Response.status(Response.Status.SERVICE_UNAVAILABLE).build();
@@ -185,7 +188,7 @@ public class ChallengeController {
final Account account = accountsManager.getByAccountIdentifier(auth.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
final ChallengeConstraints constraints = challengeConstraintChecker.challengeConstraints(requestContext, account);
final ChallengeConstraints constraints = challengeConstraintChecker.challengeConstraintsHttp(requestContext, account);
if (!constraints.pushPermitted()) {
return Response.status(429).build();
}
@@ -34,15 +34,12 @@ import org.whispersystems.textsecuregcm.entities.RedeemReceiptRequest;
import org.whispersystems.textsecuregcm.storage.AccountBadge;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.RedeemedReceiptsManager;
import org.whispersystems.textsecuregcm.subscriptions.ReceiptCredentialPresentationFactory;
@Path("/v1/donation")
@Tag(name = "Donations")
public class DonationController {
public interface ReceiptCredentialPresentationFactory {
ReceiptCredentialPresentation build(byte[] bytes) throws InvalidInputException;
}
private final Clock clock;
private final ServerZkReceiptOperations serverZkReceiptOperations;
private final RedeemedReceiptsManager redeemedReceiptsManager;
@@ -117,7 +114,7 @@ public class DonationController {
}
final boolean receiptMatched = redeemedReceiptsManager.put(
receiptSerial, receiptExpiration.getEpochSecond(), receiptLevel, auth.accountIdentifier()).join();
receiptSerial, receiptExpiration.getEpochSecond(), receiptLevel, auth.accountIdentifier());
if (!receiptMatched) {
return Response.status(Status.BAD_REQUEST)
.entity("receipt serial is already redeemed")
@@ -4,8 +4,6 @@
*/
package org.whispersystems.textsecuregcm.controllers;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import com.google.common.net.HttpHeaders;
import io.dropwizard.auth.Auth;
import io.micrometer.core.instrument.Metrics;
@@ -22,7 +20,6 @@ import jakarta.validation.constraints.NotNull;
import jakarta.ws.rs.BadRequestException;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.DefaultValue;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.HeaderParam;
import jakarta.ws.rs.InternalServerErrorException;
import jakarta.ws.rs.NotAuthorizedException;
@@ -41,7 +38,6 @@ import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.Response.Status;
import java.time.Clock;
import java.time.Duration;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
@@ -52,7 +48,6 @@ import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import org.glassfish.jersey.server.ManagedAsync;
import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage;
@@ -75,8 +70,6 @@ import org.whispersystems.textsecuregcm.entities.IncomingMessage;
import org.whispersystems.textsecuregcm.entities.IncomingMessageList;
import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
import org.whispersystems.textsecuregcm.entities.MismatchedDevicesResponse;
import org.whispersystems.textsecuregcm.entities.OutgoingMessageEntity;
import org.whispersystems.textsecuregcm.entities.OutgoingMessageEntityList;
import org.whispersystems.textsecuregcm.entities.SendMessageResponse;
import org.whispersystems.textsecuregcm.entities.SendMultiRecipientMessageResponse;
import org.whispersystems.textsecuregcm.entities.SpamReport;
@@ -85,31 +78,22 @@ import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.limits.CardinalityEstimator;
import org.whispersystems.textsecuregcm.limits.MessageDeliveryLoopMonitor;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.MessageMetrics;
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.MessageTooLargeException;
import org.whispersystems.textsecuregcm.push.MessageUtil;
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
import org.whispersystems.textsecuregcm.push.PushNotificationScheduler;
import org.whispersystems.textsecuregcm.spam.MessageType;
import org.whispersystems.textsecuregcm.spam.SpamCheckResult;
import org.whispersystems.textsecuregcm.spam.SpamChecker;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.MessagesManager;
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
import org.whispersystems.textsecuregcm.storage.ReportMessageManager;
import org.whispersystems.textsecuregcm.util.HeaderUtils;
import org.whispersystems.textsecuregcm.util.Util;
import org.whispersystems.websocket.WebsocketHeaders;
import reactor.core.scheduler.Scheduler;
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
@Path("/v1/messages")
@@ -122,23 +106,14 @@ public class MessageController {
private final CardinalityEstimator messageByteLimitEstimator;
private final MessageSender messageSender;
private final AccountsManager accountsManager;
private final MessagesManager messagesManager;
private final PhoneNumberIdentifiers phoneNumberIdentifiers;
private final PushNotificationManager pushNotificationManager;
private final PushNotificationScheduler pushNotificationScheduler;
private final ReportMessageManager reportMessageManager;
private final Scheduler messageDeliveryScheduler;
private final ClientReleaseManager clientReleaseManager;
private final ServerSecretParams serverSecretParams;
private final SpamChecker spamChecker;
private final MessageMetrics messageMetrics;
private final MessageDeliveryLoopMonitor messageDeliveryLoopMonitor;
private final Clock clock;
private static final CompletableFuture<?>[] EMPTY_FUTURE_ARRAY = new CompletableFuture<?>[0];
private static final String OUTGOING_MESSAGE_LIST_SIZE_BYTES_DISTRIBUTION_NAME = name(MessageController.class, "outgoingMessageListSizeBytes");
private static final Timer INDIVIDUAL_MESSAGE_LATENCY_TIMER;
private static final Timer MULTI_RECIPIENT_MESSAGE_LATENCY_TIMER;
@@ -166,8 +141,6 @@ public class MessageController {
// for additional details.
public static final long MAX_TIMESTAMP = 86_400_000L * 100_000_000L;
private static final Duration NOTIFY_FOR_REMAINING_MESSAGES_DELAY = Duration.ofMinutes(1);
private static final SendMultiRecipientMessageResponse SEND_STORY_RESPONSE =
new SendMultiRecipientMessageResponse(Collections.emptyList());
@@ -176,33 +149,19 @@ public class MessageController {
CardinalityEstimator messageByteLimitEstimator,
MessageSender messageSender,
AccountsManager accountsManager,
MessagesManager messagesManager,
PhoneNumberIdentifiers phoneNumberIdentifiers,
PushNotificationManager pushNotificationManager,
PushNotificationScheduler pushNotificationScheduler,
ReportMessageManager reportMessageManager,
Scheduler messageDeliveryScheduler,
final ClientReleaseManager clientReleaseManager,
final ServerSecretParams serverSecretParams,
final SpamChecker spamChecker,
final MessageMetrics messageMetrics,
final MessageDeliveryLoopMonitor messageDeliveryLoopMonitor,
final Clock clock) {
this.rateLimiters = rateLimiters;
this.messageByteLimitEstimator = messageByteLimitEstimator;
this.messageSender = messageSender;
this.accountsManager = accountsManager;
this.messagesManager = messagesManager;
this.phoneNumberIdentifiers = phoneNumberIdentifiers;
this.pushNotificationManager = pushNotificationManager;
this.pushNotificationScheduler = pushNotificationScheduler;
this.reportMessageManager = reportMessageManager;
this.messageDeliveryScheduler = messageDeliveryScheduler;
this.clientReleaseManager = clientReleaseManager;
this.serverSecretParams = serverSecretParams;
this.spamChecker = spamChecker;
this.messageMetrics = messageMetrics;
this.messageDeliveryLoopMonitor = messageDeliveryLoopMonitor;
this.clock = clock;
}
@@ -767,84 +726,6 @@ public class MessageController {
}
}
@GET
@Produces(MediaType.APPLICATION_JSON)
public CompletableFuture<OutgoingMessageEntityList> getPendingMessages(@Auth AuthenticatedDevice auth,
@HeaderParam(WebsocketHeaders.X_SIGNAL_RECEIVE_STORIES) String receiveStoriesHeader,
@HeaderParam(HttpHeaders.USER_AGENT) String userAgent) {
return accountsManager.getByAccountIdentifierAsync(auth.accountIdentifier())
.thenCompose(maybeAccount -> {
final Account account = maybeAccount.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
final Device device = account.getDevice(auth.deviceId())
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
final boolean shouldReceiveStories = WebsocketHeaders.parseReceiveStoriesHeader(receiveStoriesHeader);
pushNotificationManager.handleMessagesRetrieved(account, device, userAgent);
return messagesManager.getMessagesForDevice(
auth.accountIdentifier(),
device,
false)
.map(messagesAndHasMore -> {
Stream<Envelope> envelopes = messagesAndHasMore.first().stream();
if (!shouldReceiveStories) {
envelopes = envelopes.filter(e -> !e.getStory());
}
final OutgoingMessageEntityList messages = new OutgoingMessageEntityList(envelopes
.map(OutgoingMessageEntity::fromEnvelope)
.peek(outgoingMessageEntity -> {
messageMetrics.measureAccountOutgoingMessageUuidMismatches(account, outgoingMessageEntity);
messageMetrics.measureOutgoingMessageLatency(outgoingMessageEntity.serverTimestamp(),
"rest",
auth.deviceId() == Device.PRIMARY_ID,
outgoingMessageEntity.urgent(),
// Messages fetched via this endpoint (as opposed to WebSocketConnection) are never ephemeral
// because, by definition, the client doesn't have a "live" connection via which to receive
// ephemeral messages.
false,
userAgent,
clientReleaseManager);
})
.collect(Collectors.toList()),
messagesAndHasMore.second());
Metrics.summary(OUTGOING_MESSAGE_LIST_SIZE_BYTES_DISTRIBUTION_NAME, Tags.of(UserAgentTagUtil.getPlatformTag(userAgent)))
.record(estimateMessageListSizeBytes(messages));
if (!messages.messages().isEmpty()) {
messageDeliveryLoopMonitor.recordDeliveryAttempt(auth.accountIdentifier(),
auth.deviceId(),
messages.messages().getFirst().guid(),
userAgent,
"rest");
}
if (messagesAndHasMore.second()) {
pushNotificationScheduler.scheduleDelayedNotification(account, device, NOTIFY_FOR_REMAINING_MESSAGES_DELAY);
}
return messages;
})
.timeout(Duration.ofSeconds(5))
.subscribeOn(messageDeliveryScheduler)
.toFuture();
});
}
private static long estimateMessageListSizeBytes(final OutgoingMessageEntityList messageList) {
long size = 0;
for (final OutgoingMessageEntity message : messageList.messages()) {
size += message.content() == null ? 0 : message.content().length;
size += message.sourceUuid() == null ? 0 : 36;
}
return size;
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Path("/report/{source}/{messageGuid}")
@@ -53,9 +53,12 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration;
import org.whispersystems.textsecuregcm.limits.RateLimitedByIp;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.storage.IssuedReceiptsManager;
import org.whispersystems.textsecuregcm.storage.OneTimeDonationsManager;
import org.whispersystems.textsecuregcm.storage.WriteConflictException;
import org.whispersystems.textsecuregcm.subscriptions.BraintreeManager;
import org.whispersystems.textsecuregcm.subscriptions.ChargeFailure;
import org.whispersystems.textsecuregcm.subscriptions.CustomerAwareSubscriptionPaymentProcessor;
@@ -161,6 +164,7 @@ public class OneTimeDonationController {
properties = {
@StringToClassMapItem(key = "error", value = String.class)
})))
@RateLimitedByIp(RateLimiters.For.ONE_TIME_DONATION)
public CompletableFuture<Response> createBoostPaymentIntent(
@Auth Optional<AuthenticatedDevice> authenticatedAccount,
@NotNull @Valid CreateBoostRequest request,
@@ -306,10 +310,11 @@ public class OneTimeDonationController {
validateRequestCurrencyAmount(request, BigDecimal.valueOf(request.amount), braintreeManager))
.thenCompose(_ -> braintreeManager.captureOneTimePayment(request.payerId, request.paymentId,
request.paymentToken, request.currency, request.amount, request.level, getClientPlatform(userAgent)))
.thenCompose(
chargeSuccessDetails -> oneTimeDonationsManager.putPaidAt(chargeSuccessDetails.paymentId(), Instant.now()))
.thenApply(paymentId -> Response.ok(
new ConfirmPayPalBoostResponse(paymentId)).build());
.thenApply(chargeSuccessDetails -> {
oneTimeDonationsManager.putPaidAt(chargeSuccessDetails.paymentId(), Instant.now());
return Response.ok(
new ConfirmPayPalBoostResponse(chargeSuccessDetails.paymentId())).build();
});
}
public static class CreateBoostReceiptCredentialsRequest {
@@ -352,11 +357,11 @@ public class OneTimeDonationController {
case APPLE_APP_STORE -> throw new BadRequestException("cannot use app store purchases for one-time donations");
};
return paymentDetailsFut.thenCompose(paymentDetails -> {
return paymentDetailsFut.thenApply(paymentDetails -> {
if (paymentDetails == null) {
throw new WebApplicationException(Response.Status.NOT_FOUND);
} else if (paymentDetails.status() == PaymentStatus.PROCESSING) {
return CompletableFuture.completedFuture(Response.noContent().build());
return Response.noContent().build();
} else if (paymentDetails.status() != PaymentStatus.SUCCEEDED) {
throw new WebApplicationException(Response.status(Response.Status.PAYMENT_REQUIRED)
.entity(new CreateBoostReceiptCredentialsErrorResponse(paymentDetails.chargeFailure())).build());
@@ -392,31 +397,33 @@ public class OneTimeDonationController {
throw new BadRequestException("invalid receipt credential request", e);
}
final long finalLevel = level;
return issuedReceiptsManager.recordIssuance(paymentDetails.id(), request.processor,
receiptCredentialRequest, clock.instant())
.thenCompose(_ -> oneTimeDonationsManager.getPaidAt(paymentDetails.id(), paymentDetails.created()))
.thenApply(paidAt -> {
Instant expiration = paidAt
.plus(levelExpiration)
.truncatedTo(ChronoUnit.DAYS)
.plus(1, ChronoUnit.DAYS);
ReceiptCredentialResponse receiptCredentialResponse;
try {
receiptCredentialResponse = zkReceiptOperations.issueReceiptCredential(
receiptCredentialRequest, expiration.getEpochSecond(), finalLevel);
} catch (VerificationFailedException e) {
throw new BadRequestException("receipt credential request failed verification", e);
}
Metrics.counter(SubscriptionController.RECEIPT_ISSUED_COUNTER_NAME,
Tags.of(
Tag.of(SubscriptionController.PROCESSOR_TAG_NAME, request.processor.toString()),
Tag.of(SubscriptionController.TYPE_TAG_NAME, "boost"),
UserAgentTagUtil.getPlatformTag(userAgent)))
.increment();
return Response.ok(
new CreateBoostReceiptCredentialsSuccessResponse(receiptCredentialResponse.serialize()))
.build();
});
try {
issuedReceiptsManager.recordIssuance(paymentDetails.id(), request.processor,
receiptCredentialRequest, clock.instant());
} catch (final WriteConflictException _) {
throw new WebApplicationException(Response.Status.CONFLICT);
}
final Instant paidAt = oneTimeDonationsManager.getPaidAt(paymentDetails.id(), paymentDetails.created());
final Instant expiration = paidAt
.plus(levelExpiration)
.truncatedTo(ChronoUnit.DAYS)
.plus(1, ChronoUnit.DAYS);
final ReceiptCredentialResponse receiptCredentialResponse;
try {
receiptCredentialResponse = zkReceiptOperations.issueReceiptCredential(
receiptCredentialRequest, expiration.getEpochSecond(), finalLevel);
} catch (final VerificationFailedException e) {
throw new BadRequestException("receipt credential request failed verification", e);
}
Metrics.counter(SubscriptionController.RECEIPT_ISSUED_COUNTER_NAME,
Tags.of(
Tag.of(SubscriptionController.PROCESSOR_TAG_NAME, request.processor.toString()),
Tag.of(SubscriptionController.TYPE_TAG_NAME, "boost"),
UserAgentTagUtil.getPlatformTag(userAgent)))
.increment();
return Response.ok(
new CreateBoostReceiptCredentialsSuccessResponse(receiptCredentialResponse.serialize()))
.build();
});
}
@@ -181,14 +181,8 @@ public class ProfileController {
final Optional<VersionedProfileV1> currentProfile =
profilesManager.getV1(auth.accountIdentifier(), request.version());
if (request.paymentAddress() != null && request.paymentAddress().length != 0) {
final boolean hasDisallowedPrefix =
dynamicConfigurationManager.getConfiguration().getPaymentsConfiguration().getDisallowedPrefixes().stream()
.anyMatch(prefix -> account.getNumber().startsWith(prefix));
if (hasDisallowedPrefix && currentProfile.map(VersionedProfileV1::paymentAddress).isEmpty()) {
return Response.status(Response.Status.FORBIDDEN).build();
}
if (request.paymentAddress() != null && request.paymentAddress().length != 0 && ProfileHelper.isPaymentAddressUpdateForbidden(account, Optional.empty(), currentProfile, dynamicConfigurationManager)) {
return Response.status(Response.Status.FORBIDDEN).build();
}
final Optional<String> currentAvatar = ProfileHelper.getCurrentAvatar(currentProfile);
@@ -67,6 +67,8 @@ import org.whispersystems.textsecuregcm.configuration.SubscriptionLevelConfigura
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.entities.Badge;
import org.whispersystems.textsecuregcm.entities.PurchasableBadge;
import org.whispersystems.textsecuregcm.limits.RateLimitedByIp;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.mappers.SubscriptionExceptionMapper;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
@@ -286,6 +288,7 @@ public class SubscriptionController {
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@ManagedAsync
@RateLimitedByIp(RateLimiters.For.ADD_SUBSCRIPTION_PAYMENT_METHOD)
public CreatePaymentMethodResponse createPaymentMethod(
@Auth Optional<AuthenticatedDevice> authenticatedAccount,
@PathParam("subscriberId") String subscriberId,
@@ -323,6 +326,7 @@ public class SubscriptionController {
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@ManagedAsync
@RateLimitedByIp(RateLimiters.For.ADD_SUBSCRIPTION_PAYMENT_METHOD)
public CreatePayPalBillingAgreementResponse createPayPalPaymentMethod(
@Auth Optional<AuthenticatedDevice> authenticatedAccount,
@PathParam("subscriberId") String subscriberId,
@@ -61,12 +61,12 @@ import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletionException;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang3.Strings;
import org.apache.http.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.captcha.AssessmentResult;
import org.whispersystems.textsecuregcm.captcha.InvalidCaptchaArgumentException;
import org.whispersystems.textsecuregcm.captcha.RegistrationCaptchaManager;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.entities.CreateVerificationSessionRequest;
@@ -83,6 +83,7 @@ import org.whispersystems.textsecuregcm.mappers.RegistrationServiceSenderExcepti
import org.whispersystems.textsecuregcm.metrics.CaptchaMetrics;
import org.whispersystems.textsecuregcm.metrics.DevicePlatformUtil;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.push.NotPushRegisteredException;
import org.whispersystems.textsecuregcm.push.PushNotification;
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
import org.whispersystems.textsecuregcm.registration.ClientType;
@@ -116,7 +117,6 @@ public class VerificationController {
private static final Logger logger = LoggerFactory.getLogger(VerificationController.class);
private static final Duration REGISTRATION_RPC_TIMEOUT = Duration.ofSeconds(15);
private static final Duration DYNAMODB_TIMEOUT = Duration.ofSeconds(5);
private static final SecureRandom RANDOM = new SecureRandom();
@@ -264,7 +264,7 @@ public class VerificationController {
// if a push challenge sent in `handlePushToken` doesn't arrive in time
verificationSession.requestedInformation().add(VerificationSession.Information.CAPTCHA);
storeVerificationSession(verificationSession);
verificationSessionManager.insert(verificationSession);
return buildResponse(registrationServiceSession, verificationSession);
}
@@ -337,24 +337,12 @@ public class VerificationController {
} finally {
// Each of the handle* methods may update requestedInformation, submittedInformation, and allowedToRequestCode,
// and we want to be sure to store a changes, even if a later method throws
updateStoredVerificationSession(verificationSession);
verificationSessionManager.update(verificationSession);
}
return buildResponse(registrationServiceSession, verificationSession);
}
private void storeVerificationSession(final VerificationSession verificationSession) {
verificationSessionManager.insert(verificationSession)
.orTimeout(DYNAMODB_TIMEOUT.toSeconds(), TimeUnit.SECONDS)
.join();
}
private void updateStoredVerificationSession(final VerificationSession verificationSession) {
verificationSessionManager.update(verificationSession)
.orTimeout(DYNAMODB_TIMEOUT.toSeconds(), TimeUnit.SECONDS)
.join();
}
/**
* If {@code pushTokenAndType} values are not {@code null}, sends a push challenge. If there is no existing push
* challenge in the session, one will be created, set on the returned session record, and
@@ -510,6 +498,8 @@ public class VerificationController {
} catch (final IOException e) {
logger.error("error assessing captcha during registration verification", e);
throw new ServerErrorException(Response.Status.SERVICE_UNAVAILABLE, e);
} catch (InvalidCaptchaArgumentException e) {
throw new BadRequestException(e);
}
if (assessmentResult.isValid(captchaScoreThreshold)) {
@@ -669,8 +659,12 @@ public class VerificationController {
accountsManager.getByE164(registrationServiceSession.number())
.filter(existingAccount ->
experimentEnrollmentManager.isEnrolled(existingAccount.getIdentifier(IdentityType.ACI), VERIFICATION_CODE_PUSH_NOTIFICATION_EXPERIMENT_NAME))
.ifPresent(existingAccount ->
pushNotificationManager.trySendVerificationCodeRequestedNotifications(existingAccount, clock.instant()));
.ifPresent(existingAccount -> {
try {
pushNotificationManager.sendVerificationCodeRequestedNotifications(existingAccount, clock.instant());
} catch (final NotPushRegisteredException _) {
}
});
} catch (final CancellationException e) {
throw new ServerErrorException("registration service unavailable", Response.Status.SERVICE_UNAVAILABLE);
} catch (final CompletionException e) {
@@ -807,7 +801,7 @@ public class VerificationController {
// the RRP. It's possible the client will not actually be able to register (e.g. failed reglock challenge), and
// so we will have removed the RRP unnecessarily. The impact of this is low, since the owner of the RRP
// can always just fallback to session-based verification.
existingRRP = registrationRecoveryPasswordsManager.remove(phoneNumberIdentifiers.getPhoneNumberIdentifier(registrationServiceSession.number()).join()).join();
existingRRP = registrationRecoveryPasswordsManager.remove(phoneNumberIdentifiers.getPhoneNumberIdentifier(registrationServiceSession.number()).join());
}
Optional<Account> maybeExistingAccount;
@@ -883,7 +877,7 @@ public class VerificationController {
// the RRP. It's possible the client will not actually be able to register (e.g. failed reglock challenge), and
// so we will have removed the RRP unnecessarily. The impact of this is low, since the owner of the RRP
// can always just fallback to session-based verification.
registrationRecoveryPasswordsManager.remove(phoneNumberIdentifiers.getPhoneNumberIdentifier(registrationServiceSession.number()).join()).join();
registrationRecoveryPasswordsManager.remove(phoneNumberIdentifiers.getPhoneNumberIdentifier(registrationServiceSession.number()).join());
}
return registrationServiceSession;
@@ -907,8 +901,7 @@ public class VerificationController {
private VerificationSession retrieveVerificationSession(final RegistrationServiceSession registrationServiceSession) {
return verificationSessionManager.findForId(registrationServiceSession.encodedSessionId())
.orTimeout(5, TimeUnit.SECONDS)
.join().orElseThrow(NotFoundException::new);
.orElseThrow(NotFoundException::new);
}
/**
@@ -50,7 +50,7 @@ public record IncomingMessage(int type,
.setType(MessageProtos.Envelope.Type.forNumber(type))
.setClientTimestamp(timestamp)
.setServerTimestamp(clock.millis())
.setDestinationServiceId(destinationIdentifier.toServiceIdentifierString())
.setDestinationServiceId(destinationIdentifier.toCompactByteString())
.setEphemeral(ephemeral)
.setUrgent(urgent);
@@ -61,7 +61,7 @@ public record IncomingMessage(int type,
if (sourceServiceIdentifier != null && sourceDeviceId != null) {
envelopeBuilder
.setSourceServiceId(sourceServiceIdentifier.toServiceIdentifierString())
.setSourceServiceId(sourceServiceIdentifier.toCompactByteString())
.setSourceDevice(sourceDeviceId.intValue());
}
@@ -1,124 +0,0 @@
/*
* Copyright 2013-2020 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.entities;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.google.common.annotations.VisibleForTesting;
import com.google.protobuf.ByteString;
import java.util.Arrays;
import java.util.Objects;
import java.util.UUID;
import javax.annotation.Nullable;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.util.ServiceIdentifierAdapter;
public record OutgoingMessageEntity(UUID guid,
int type,
long timestamp,
@JsonSerialize(using = ServiceIdentifierAdapter.ServiceIdentifierSerializer.class)
@JsonDeserialize(using = ServiceIdentifierAdapter.ServiceIdentifierDeserializer.class)
@Nullable
ServiceIdentifier sourceUuid,
int sourceDevice,
@JsonSerialize(using = ServiceIdentifierAdapter.ServiceIdentifierSerializer.class)
@JsonDeserialize(using = ServiceIdentifierAdapter.ServiceIdentifierDeserializer.class)
ServiceIdentifier destinationUuid,
@Nullable UUID updatedPni,
byte[] content,
long serverTimestamp,
boolean urgent,
boolean story,
@Nullable byte[] reportSpamToken) {
@VisibleForTesting
MessageProtos.Envelope toEnvelope() {
final MessageProtos.Envelope.Builder builder = MessageProtos.Envelope.newBuilder()
.setType(MessageProtos.Envelope.Type.forNumber(type()))
.setClientTimestamp(timestamp())
.setServerTimestamp(serverTimestamp())
.setDestinationServiceId(destinationUuid().toServiceIdentifierString())
.setServerGuid(guid().toString())
.setUrgent(urgent);
if (story) {
// Avoid sending this field if it's false.
builder.setStory(true);
}
if (sourceUuid() != null) {
builder.setSourceServiceId(sourceUuid().toServiceIdentifierString());
builder.setSourceDevice(sourceDevice());
}
if (content() != null) {
builder.setContent(ByteString.copyFrom(content()));
}
if (updatedPni() != null) {
builder.setUpdatedPni(updatedPni().toString());
}
if (reportSpamToken != null) {
builder.setReportSpamToken(ByteString.copyFrom(reportSpamToken));
}
return builder.build();
}
public static OutgoingMessageEntity fromEnvelope(final MessageProtos.Envelope envelope) {
ByteString token = envelope.getReportSpamToken();
return new OutgoingMessageEntity(
UUID.fromString(envelope.getServerGuid()),
envelope.getType().getNumber(),
envelope.getClientTimestamp(),
envelope.hasSourceServiceId() ? ServiceIdentifier.valueOf(envelope.getSourceServiceId()) : null,
envelope.getSourceDevice(),
envelope.hasDestinationServiceId() ? ServiceIdentifier.valueOf(envelope.getDestinationServiceId()) : null,
envelope.hasUpdatedPni() ? UUID.fromString(envelope.getUpdatedPni()) : null,
envelope.getContent().toByteArray(),
envelope.getServerTimestamp(),
envelope.getUrgent(),
envelope.getStory(),
token.isEmpty() ? null : token.toByteArray());
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final OutgoingMessageEntity that = (OutgoingMessageEntity) o;
return guid.equals(that.guid) &&
type == that.type &&
timestamp == that.timestamp &&
Objects.equals(sourceUuid, that.sourceUuid) &&
sourceDevice == that.sourceDevice &&
destinationUuid.equals(that.destinationUuid) &&
Objects.equals(updatedPni, that.updatedPni) &&
Arrays.equals(content, that.content) &&
serverTimestamp == that.serverTimestamp &&
urgent == that.urgent &&
story == that.story &&
Arrays.equals(reportSpamToken, that.reportSpamToken);
}
@Override
public int hashCode() {
int result = Objects.hash(
guid, type, timestamp, sourceUuid, sourceDevice, destinationUuid, updatedPni, serverTimestamp, urgent, story);
result = 31 * result + Arrays.hashCode(content);
result = 71 * result + Arrays.hashCode(reportSpamToken);
return result;
}
}
@@ -1,11 +0,0 @@
/*
* Copyright 2013-2020 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.entities;
import java.util.List;
public record OutgoingMessageEntityList(List<OutgoingMessageEntity> messages, boolean more) {
}
@@ -38,7 +38,7 @@ public class AccountsAnonymousGrpcService extends SimpleAccountsAnonymousGrpc.Ac
throws RateLimitExceededException {
final ServiceIdentifier serviceIdentifier =
ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getServiceIdentifier());
GrpcServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getServiceIdentifier());
RateLimitUtil.rateLimitByRemoteAddress(rateLimiters.getCheckAccountExistenceLimiter());
@@ -55,7 +55,7 @@ public class AccountsAnonymousGrpcService extends SimpleAccountsAnonymousGrpc.Ac
return accountsManager.getByUsernameHash(request.getUsernameHash().toByteArray()).join()
.map(account -> LookupUsernameHashResponse.newBuilder()
.setServiceIdentifier(ServiceIdentifierUtil.toGrpcServiceIdentifier(new AciServiceIdentifier(account.getUuid())))
.setServiceIdentifier(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(new AciServiceIdentifier(account.getUuid())))
.build())
.orElseGet(() -> LookupUsernameHashResponse.newBuilder().setNotFound(NotFound.getDefaultInstance()).build());
}
@@ -6,10 +6,12 @@
package org.whispersystems.textsecuregcm.grpc;
import com.google.protobuf.ByteString;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HexFormat;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import org.signal.chat.account.ClearRegistrationLockRequest;
import org.signal.chat.account.ClearRegistrationLockResponse;
@@ -62,6 +64,8 @@ import org.whispersystems.textsecuregcm.util.UsernameHashZkProofVerifier;
public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
private static final SecureRandom SECURE_RANDOM = new SecureRandom();
private final AccountsManager accountsManager;
private final RateLimiters rateLimiters;
private final UsernameHashZkProofVerifier usernameHashZkProofVerifier;
@@ -83,8 +87,8 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
final Account account = getAuthenticatedAccount();
final AccountIdentifiers.Builder accountIdentifiersBuilder = AccountIdentifiers.newBuilder()
.addServiceIdentifiers(ServiceIdentifierUtil.toGrpcServiceIdentifier(new AciServiceIdentifier(account.getUuid())))
.addServiceIdentifiers(ServiceIdentifierUtil.toGrpcServiceIdentifier(new PniServiceIdentifier(account.getPhoneNumberIdentifier())))
.addServiceIdentifiers(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(new AciServiceIdentifier(account.getUuid())))
.addServiceIdentifiers(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(new PniServiceIdentifier(account.getPhoneNumberIdentifier())))
.setE164(account.getNumber());
account.getUsernameHash().ifPresent(usernameHash ->
@@ -164,7 +168,7 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
try {
usernameHashZkProofVerifier.verifyProof(request.getZkProof().toByteArray(), request.getUsernameHash().toByteArray());
} catch (final BaseUsernameException e) {
throw GrpcExceptions.constraintViolation("Could not verify proof");
throw GrpcExceptions.invalidArguments("Could not verify proof");
}
rateLimiters.getUsernameSetLimiter().validate(authenticatedDevice.accountIdentifier());
@@ -263,8 +267,7 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
@Override
public SetRegistrationRecoveryPasswordResponse setRegistrationRecoveryPassword(final SetRegistrationRecoveryPasswordRequest request) {
registrationRecoveryPasswordsManager.store(getAuthenticatedAccount().getIdentifier(IdentityType.PNI),
request.getRegistrationRecoveryPassword().toByteArray())
.join();
request.getRegistrationRecoveryPassword().toByteArray());
return SetRegistrationRecoveryPasswordResponse.getDefaultInstance();
}
@@ -277,14 +280,24 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
final byte[] zkCredentialKey = request.getPublicKey().toByteArray();
if (Arrays.equals(authenticatedAccount.getZkCredentialKey(), zkCredentialKey)) {
return SetZkCredentialKeyResponse.getDefaultInstance();
return SetZkCredentialKeyResponse.newBuilder()
.setRotationId(Objects.requireNonNull(authenticatedAccount.getZkCredentialKeyRotationId()))
.build();
}
rateLimiters.getSetZkCredentialKeyLimiter().validate(authenticatedDevice.accountIdentifier());
accountsManager.update(authenticatedDevice.accountIdentifier(), account -> account.setZkCredentialKey(zkCredentialKey));
// It is technically fine from the credential's perspective if it is zero, but it's clearer to never have the default value
final long rotationId = SECURE_RANDOM.nextLong(1, Long.MAX_VALUE);
return SetZkCredentialKeyResponse.getDefaultInstance();
accountsManager.update(authenticatedDevice.accountIdentifier(), account -> {
account.setZkCredentialKey(zkCredentialKey);
account.setZkCredentialKeyRotationId(rotationId);
});
return SetZkCredentialKeyResponse.newBuilder()
.setRotationId(rotationId)
.build();
}
private Account getAuthenticatedAccount() {
@@ -8,6 +8,7 @@ import com.google.protobuf.ByteString;
import com.google.protobuf.Empty;
import java.util.Optional;
import java.util.concurrent.Flow;
import org.signal.chat.backup.BackupStreamClosed;
import org.signal.chat.backup.CopyMediaRequest;
import org.signal.chat.backup.CopyMediaResponse;
import org.signal.chat.backup.DeleteAllRequest;
@@ -223,15 +224,16 @@ public class BackupsAnonymousGrpcService extends SimpleBackupsAnonymousGrpc.Back
copyQuota = backupManager.getCopyQuota(backupUser,
request.getItemsList().stream().map(item -> new CopyParameters(
item.getSourceAttachmentCdn(), item.getSourceKey(),
// uint32 in proto, make sure it fits in a signed int
fromUnsignedExact(item.getObjectLength()),
item.getObjectLength(),
new MediaEncryptionParameters(item.getEncryptionKey().toByteArray(), item.getHmacKey().toByteArray()),
item.getMediaId().toByteArray())).toList(), maxAttachmentSize);
} catch (BackupFailedZkAuthenticationException e) {
return JdkFlowAdapter.publisherToFlowPublisher(Mono.just(CopyMediaResponse
.newBuilder()
.setFailedAuthentication(FailedZkAuthentication.newBuilder().setDescription(e.getMessage()))
.build()));
return JdkFlowAdapter.publisherToFlowPublisher(
Mono.error(GrpcExceptions.streamClosed(BackupStreamClosed.newBuilder()
.setFailedAuthentication(FailedZkAuthentication.newBuilder()
.setDescription(e.getMessage())
.build())
.build())));
}
return JdkFlowAdapter.publisherToFlowPublisher(backupManager.copyToBackup(copyQuota)
.doOnNext(result -> backupMetrics.updateCopyCounter(
@@ -308,10 +310,12 @@ public class BackupsAnonymousGrpcService extends SimpleBackupsAnonymousGrpc.Back
.map(item -> new BackupManager.StorageDescriptor(item.getCdn(), item.getMediaId().toByteArray()))
.toList());
} catch (BackupFailedZkAuthenticationException e) {
return JdkFlowAdapter.publisherToFlowPublisher(Mono.just(DeleteMediaResponse
.newBuilder()
.setFailedAuthentication(FailedZkAuthentication.newBuilder().setDescription(e.getMessage()))
.build()));
return JdkFlowAdapter.publisherToFlowPublisher(
Mono.error(GrpcExceptions.streamClosed(BackupStreamClosed.newBuilder()
.setFailedAuthentication(FailedZkAuthentication.newBuilder()
.setDescription(e.getMessage())
.build())
.build())));
}
return JdkFlowAdapter.publisherToFlowPublisher(deleteItems
.map(storageDescriptor -> DeleteMediaResponse.newBuilder()
@@ -346,17 +350,6 @@ public class BackupsAnonymousGrpcService extends SimpleBackupsAnonymousGrpc.Back
}
}
/**
* Convert an int from a proto uint32 to a signed positive integer, throwing if the value exceeds
* {@link Integer#MAX_VALUE}. To convert to a long, see {@link Integer#toUnsignedLong(int)}
*/
private static int fromUnsignedExact(final int i) {
if (i < 0) {
throw GrpcExceptions.invalidArguments("integer length too large");
}
return i;
}
private interface Deserializer<T> {
T deserialize(byte[] bytes) throws InvalidInputException, InvalidKeyException;
@@ -0,0 +1,74 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc;
import java.io.IOException;
import org.apache.commons.lang3.StringUtils;
import org.signal.chat.calling.GetCallingRelaysRequest;
import org.signal.chat.calling.GetCallingRelaysResponse;
import org.signal.chat.calling.SimpleCallingGrpc;
import org.whispersystems.textsecuregcm.auth.CloudflareTurnCredentialsManager;
import org.whispersystems.textsecuregcm.auth.TurnToken;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
public class CallingGrpcService extends SimpleCallingGrpc.CallingImplBase {
private final CloudflareTurnCredentialsManager cloudflareTurnCredentialsManager;
private final RateLimiters rateLimiters;
public CallingGrpcService(final CloudflareTurnCredentialsManager cloudflareTurnCredentialsManager,
final RateLimiters rateLimiters) {
this.cloudflareTurnCredentialsManager = cloudflareTurnCredentialsManager;
this.rateLimiters = rateLimiters;
}
@Override
public GetCallingRelaysResponse getCallingRelays(final GetCallingRelaysRequest request)
throws RateLimitExceededException, IOException {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
rateLimiters.getCallEndpointLimiter().validate(authenticatedDevice.accountIdentifier());
final TurnToken turnToken =
cloudflareTurnCredentialsManager.retrieveFromCloudflare(authenticatedDevice.accountIdentifier());
final GetCallingRelaysResponse.Relay.Builder relayBuilder = GetCallingRelaysResponse.Relay.newBuilder()
.setUsername(turnToken.username())
.setPassword(turnToken.password())
.setCredentialTtlSeconds(turnToken.ttlSeconds());
if (!turnToken.urls().isEmpty()) {
relayBuilder.setHostnameUrls(turnToken.urls().stream()
.collect(GetCallingRelaysResponse.HostnameUrlList::newBuilder,
GetCallingRelaysResponse.HostnameUrlList.Builder::addUrls,
(a, b) -> a.mergeFrom(b.build())));
}
if (!turnToken.urlsWithIps().isEmpty()) {
relayBuilder.setIpUrls(turnToken.urlsWithIps().stream()
.collect(() -> {
final GetCallingRelaysResponse.IpUrlList.Builder builder =
GetCallingRelaysResponse.IpUrlList.newBuilder();
if (StringUtils.isNotBlank(turnToken.hostname())) {
builder.setHostname(turnToken.hostname());
}
return builder;
},
GetCallingRelaysResponse.IpUrlList.Builder::addUrls,
(a, b) -> a.mergeFrom(b.build())));
}
return GetCallingRelaysResponse.newBuilder()
.addRelays(relayBuilder.build())
.build();
}
}
@@ -0,0 +1,63 @@
package org.whispersystems.textsecuregcm.grpc;
import java.io.IOException;
import org.signal.chat.challenge.AnswerChallengeRequest;
import org.signal.chat.challenge.AnswerChallengeResponse;
import org.signal.chat.challenge.SimpleChallengeGrpc;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
import org.whispersystems.textsecuregcm.captcha.InvalidCaptchaArgumentException;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.limits.RateLimitChallengeManager;
import org.whispersystems.textsecuregcm.spam.ChallengeConstraintChecker;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
public class ChallengeGrpcService extends SimpleChallengeGrpc.ChallengeImplBase {
private final AccountsManager accountsManager;
private final RateLimitChallengeManager rateLimitChallengeManager;
private final ChallengeConstraintChecker challengeConstraintChecker;
public ChallengeGrpcService(final AccountsManager accountsManager,
final RateLimitChallengeManager rateLimitChallengeManager,
final ChallengeConstraintChecker challengeConstraintChecker) {
this.accountsManager = accountsManager;
this.rateLimitChallengeManager = rateLimitChallengeManager;
this.challengeConstraintChecker = challengeConstraintChecker;
}
@Override
public AnswerChallengeResponse handleChallengeResponse(final AnswerChallengeRequest request)
throws RateLimitExceededException, IOException {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
final Account account = accountsManager.getByAccountIdentifier(authenticatedDevice.accountIdentifier())
.orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials"));
final ChallengeConstraintChecker.ChallengeConstraints constraints = challengeConstraintChecker.challengeConstraintsGrpc(
account);
final boolean success = switch (request.getRequestCase()) {
case PUSH -> constraints.pushPermitted() && rateLimitChallengeManager.answerPushChallenge(account,
request.getPush().getChallenge());
case CAPTCHA -> {
try {
yield rateLimitChallengeManager.answerCaptchaChallenge(
account,
request.getCaptcha().getCaptcha(),
RequestAttributesUtil.getRemoteAddress().getHostAddress(),
RequestAttributesUtil.getUserAgent().orElse(null),
constraints.captchaScoreThreshold());
} catch (InvalidCaptchaArgumentException e) {
throw GrpcExceptions.invalidArguments(e.getMessage());
}
}
case REQUEST_NOT_SET -> throw GrpcExceptions.fieldViolation("request", "Must set request type");
};
return AnswerChallengeResponse.newBuilder()
.setSuccess(success)
.build();
}
}
@@ -1,53 +1,35 @@
/*
* Copyright 2023 Signal Messenger, LLC
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc;
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.VisibleForTesting;
import java.time.Clock;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import org.signal.chat.credentials.AuthCheckResult;
import org.signal.chat.credentials.CheckSvrCredentialsRequest;
import org.signal.chat.credentials.CheckSvrCredentialsResponse;
import org.signal.chat.credentials.SimpleExternalServiceCredentialsAnonymousGrpc;
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
import org.signal.chat.credentials.SimpleCredentialsAnonymousGrpc;
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsSelector;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
public class ExternalServiceCredentialsAnonymousGrpcService extends
SimpleExternalServiceCredentialsAnonymousGrpc.ExternalServiceCredentialsAnonymousImplBase {
public class CredentialsAnonymousGrpcService extends SimpleCredentialsAnonymousGrpc.CredentialsAnonymousImplBase {
private final AccountsManager accountsManager;
private final ExternalServiceCredentialsGenerator svrCredentialsGenerator;
private static final long MAX_SVR_PASSWORD_AGE_SECONDS = TimeUnit.DAYS.toSeconds(30);
private final ExternalServiceCredentialsGenerator svrCredentialsGenerator;
private final AccountsManager accountsManager;
public static ExternalServiceCredentialsAnonymousGrpcService create(
final AccountsManager accountsManager,
final WhisperServerConfiguration chatConfiguration) {
return new ExternalServiceCredentialsAnonymousGrpcService(
accountsManager,
ExternalServiceDefinitions.SVR.generatorFactory().apply(chatConfiguration, Clock.systemUTC())
);
}
@VisibleForTesting
ExternalServiceCredentialsAnonymousGrpcService(
final AccountsManager accountsManager,
public CredentialsAnonymousGrpcService(final AccountsManager accountsManager,
final ExternalServiceCredentialsGenerator svrCredentialsGenerator) {
this.accountsManager = requireNonNull(accountsManager);
this.svrCredentialsGenerator = requireNonNull(svrCredentialsGenerator);
this.svrCredentialsGenerator = svrCredentialsGenerator;
this.accountsManager = accountsManager;
}
@Override
@@ -57,14 +39,18 @@ public class ExternalServiceCredentialsAnonymousGrpcService extends
tokens,
svrCredentialsGenerator,
MAX_SVR_PASSWORD_AGE_SECONDS);
// the username associated with the provided number
final Optional<String> maybeUsername = accountsManager.getByE164(request.getNumber())
.map(Account::getUuid)
.map(svrCredentialsGenerator::generateForUuid)
.map(ExternalServiceCredentials::username);
final CheckSvrCredentialsResponse.Builder builder = CheckSvrCredentialsResponse.newBuilder();
for (ExternalServiceCredentialsSelector.CredentialInfo credentialInfo : credentials) {
final AuthCheckResult authCheckResult;
if (!credentialInfo.valid()) {
authCheckResult = AuthCheckResult.AUTH_CHECK_RESULT_INVALID;
} else {
@@ -74,8 +60,10 @@ public class ExternalServiceCredentialsAnonymousGrpcService extends
? AuthCheckResult.AUTH_CHECK_RESULT_MATCH
: AuthCheckResult.AUTH_CHECK_RESULT_NO_MATCH;
}
builder.putMatches(credentialInfo.token(), authCheckResult);
}
return builder.build();
}
}
@@ -0,0 +1,168 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc;
import com.google.protobuf.ByteString;
import java.time.Clock;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Map;
import java.util.UUID;
import org.signal.chat.credentials.ExternalServiceType;
import org.signal.chat.credentials.GetCreateCallLinkCredentialsRequest;
import org.signal.chat.credentials.GetCreateCallLinkCredentialsResponse;
import org.signal.chat.credentials.GetDeliveryCertificateRequest;
import org.signal.chat.credentials.GetDeliveryCertificateResponse;
import org.signal.chat.credentials.GetExternalServiceCredentialsRequest;
import org.signal.chat.credentials.GetExternalServiceCredentialsResponse;
import org.signal.chat.credentials.GetGroupCredentialsRequest;
import org.signal.chat.credentials.GetGroupCredentialsResponse;
import org.signal.chat.credentials.SimpleCredentialsGrpc;
import org.signal.libsignal.protocol.ServiceId;
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.auth.ServerZkAuthOperations;
import org.signal.libsignal.zkgroup.calllinks.CallLinkAuthCredentialResponse;
import org.signal.libsignal.zkgroup.calllinks.CreateCallLinkCredentialRequest;
import org.whispersystems.textsecuregcm.auth.CertificateGenerator;
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
import org.whispersystems.textsecuregcm.auth.RedemptionRange;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
public class CredentialsGrpcService extends SimpleCredentialsGrpc.CredentialsImplBase {
private final AccountsManager accountsManager;
private final CertificateGenerator certificateGenerator;
private final ServerZkAuthOperations serverZkAuthOperations;
private final GenericServerSecretParams serverSecretParams;
private final RateLimiters rateLimiters;
private final Clock clock;
private final Map<ExternalServiceType, ExternalServiceCredentialsGenerator> credentialsGeneratorByType;
public CredentialsGrpcService(final AccountsManager accountsManager,
final CertificateGenerator certificateGenerator,
final ServerZkAuthOperations serverZkAuthOperations,
final GenericServerSecretParams serverSecretParams,
final RateLimiters rateLimiters,
final Clock clock,
final Map<ExternalServiceType, ExternalServiceCredentialsGenerator> credentialsGeneratorByType) {
this.accountsManager = accountsManager;
this.certificateGenerator = certificateGenerator;
this.serverZkAuthOperations = serverZkAuthOperations;
this.serverSecretParams = serverSecretParams;
this.rateLimiters = rateLimiters;
this.clock = clock;
this.credentialsGeneratorByType = credentialsGeneratorByType;
}
@Override
public GetExternalServiceCredentialsResponse getExternalServiceCredentials(final GetExternalServiceCredentialsRequest request)
throws RateLimitExceededException {
final ExternalServiceCredentialsGenerator credentialsGenerator = this.credentialsGeneratorByType
.get(request.getExternalService());
if (credentialsGenerator == null) {
throw GrpcExceptions.fieldViolation("externalService", "Invalid external service type");
}
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
rateLimiters.forDescriptor(RateLimiters.For.EXTERNAL_SERVICE_CREDENTIALS).validate(authenticatedDevice.accountIdentifier());
final ExternalServiceCredentials externalServiceCredentials = credentialsGenerator
.generateForUuid(authenticatedDevice.accountIdentifier());
return GetExternalServiceCredentialsResponse.newBuilder()
.setUsername(externalServiceCredentials.username())
.setPassword(externalServiceCredentials.password())
.build();
}
@Override
public GetDeliveryCertificateResponse getDeliveryCertificate(final GetDeliveryCertificateRequest request) {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
final Account account = accountsManager.getByAccountIdentifier(authenticatedDevice.accountIdentifier())
.orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials"));
return GetDeliveryCertificateResponse.newBuilder()
.setCertificateWithE164(ByteString.copyFrom(
certificateGenerator.createFor(account, authenticatedDevice.deviceId(), true)))
.setCertificateWithoutE164(ByteString.copyFrom(
certificateGenerator.createFor(account, authenticatedDevice.deviceId(), false)))
.build();
}
@Override
public GetGroupCredentialsResponse getGroupCredentials(final GetGroupCredentialsRequest request) {
final RedemptionRange redemptionRange;
try {
redemptionRange = RedemptionRange.inclusive(clock,
Instant.ofEpochSecond(request.getRedemptionStartSeconds()),
Instant.ofEpochSecond(request.getRedemptionEndSeconds()));
} catch (final IllegalArgumentException e) {
throw GrpcExceptions.invalidArguments(e.getMessage());
}
final Account account =
accountsManager.getByAccountIdentifier(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier())
.orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials"));
final ServiceId.Aci aci = new ServiceId.Aci(account.getIdentifier(IdentityType.ACI));
final ServiceId.Pni pni = new ServiceId.Pni(account.getIdentifier(IdentityType.PNI));
final GetGroupCredentialsResponse.Builder responseBuilder = GetGroupCredentialsResponse.newBuilder()
.setPni(UUIDUtil.toByteString(pni.getRawUUID()));
for (final Instant redemption : redemptionRange) {
responseBuilder.addGroupCredentials(GetGroupCredentialsResponse.CredentialAndRedemptionTime.newBuilder()
.setRedemptionTimeSeconds(redemption.getEpochSecond())
.setCredential(ByteString.copyFrom(
serverZkAuthOperations.issueAuthCredentialWithPniZkc(aci, pni, redemption).serialize()))
.build());
responseBuilder.addCallLinkAuthCredentials(GetGroupCredentialsResponse.CredentialAndRedemptionTime.newBuilder()
.setRedemptionTimeSeconds(redemption.getEpochSecond())
.setCredential(ByteString.copyFrom(
CallLinkAuthCredentialResponse.issueCredential(aci, redemption, serverSecretParams).serialize()))
.build());
}
return responseBuilder.build();
}
@Override
public GetCreateCallLinkCredentialsResponse getCreateCallLinkCredentials(final GetCreateCallLinkCredentialsRequest request)
throws RateLimitExceededException {
final UUID accountIdentifier = AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier();
rateLimiters.getCreateCallLinkLimiter().validate(accountIdentifier);
final Instant truncatedDayTimestamp = clock.instant().truncatedTo(ChronoUnit.DAYS);
try {
final CreateCallLinkCredentialRequest createCallLinkCredentialRequest =
new CreateCallLinkCredentialRequest(request.getCredentialRequest().toByteArray());
return GetCreateCallLinkCredentialsResponse.newBuilder()
.setRedemptionTimeSeconds(truncatedDayTimestamp.getEpochSecond())
.setCredential(ByteString.copyFrom(createCallLinkCredentialRequest.issueCredential(
new ServiceId.Aci(accountIdentifier),
truncatedDayTimestamp,
serverSecretParams)
.serialize()))
.build();
} catch (final InvalidInputException e) {
throw GrpcExceptions.invalidArguments("Invalid 'create call link credential' request");
}
}
}
@@ -19,6 +19,7 @@ public class DeviceCapabilityUtil {
case DEVICE_CAPABILITY_ATTACHMENT_BACKFILL -> DeviceCapability.ATTACHMENT_BACKFILL;
case DEVICE_CAPABILITY_SPARSE_POST_QUANTUM_RATCHET -> DeviceCapability.SPARSE_POST_QUANTUM_RATCHET;
case DEVICE_CAPABILITY_PROFILES_V2 -> DeviceCapability.PROFILES_V2;
case DEVICE_CAPABILITY_USERNAME_CHANGE_SYNC_MESSAGE -> DeviceCapability.USERNAME_CHANGE_SYNC_MESSAGE;
case DEVICE_CAPABILITY_UNSPECIFIED, UNRECOGNIZED ->
throw GrpcExceptions.invalidArguments("unrecognized device capability");
};
@@ -31,6 +32,7 @@ public class DeviceCapabilityUtil {
case ATTACHMENT_BACKFILL -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_ATTACHMENT_BACKFILL;
case SPARSE_POST_QUANTUM_RATCHET -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_SPARSE_POST_QUANTUM_RATCHET;
case PROFILES_V2 -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_PROFILES_V2;
case USERNAME_CHANGE_SYNC_MESSAGE -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_USERNAME_CHANGE_SYNC_MESSAGE;
};
}
}
@@ -0,0 +1,104 @@
package org.whispersystems.textsecuregcm.grpc;
import com.google.protobuf.Empty;
import java.time.Clock;
import java.time.Instant;
import org.signal.chat.donations.RedeemReceiptRequest;
import org.signal.chat.donations.RedeemReceiptResponse;
import org.signal.chat.donations.SimpleDonationsGrpc;
import org.signal.chat.errors.FailedPrecondition;
import org.signal.chat.errors.FailedZkAuthentication;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.VerificationFailedException;
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialPresentation;
import org.signal.libsignal.zkgroup.receipts.ReceiptSerial;
import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
import org.whispersystems.textsecuregcm.configuration.BadgesConfiguration;
import org.whispersystems.textsecuregcm.storage.AccountBadge;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.RedeemedReceiptsManager;
import org.whispersystems.textsecuregcm.subscriptions.ReceiptCredentialPresentationFactory;
public class DonationsGrpcService extends SimpleDonationsGrpc.DonationsImplBase {
private final Clock clock;
private final ServerZkReceiptOperations serverZkReceiptOperations;
private final RedeemedReceiptsManager redeemedReceiptsManager;
private final AccountsManager accountsManager;
private final BadgesConfiguration badgesConfiguration;
private final ReceiptCredentialPresentationFactory receiptCredentialPresentationFactory;
private static final Logger LOGGER = LoggerFactory.getLogger(DonationsGrpcService.class);
public DonationsGrpcService(
final Clock clock,
final ServerZkReceiptOperations serverZkReceiptOperations,
final RedeemedReceiptsManager redeemedReceiptsManager,
final AccountsManager accountsManager,
final BadgesConfiguration badgesConfiguration,
final ReceiptCredentialPresentationFactory receiptCredentialPresentationFactory) {
this.clock = clock;
this.serverZkReceiptOperations = serverZkReceiptOperations;
this.redeemedReceiptsManager = redeemedReceiptsManager;
this.accountsManager = accountsManager;
this.badgesConfiguration = badgesConfiguration;
this.receiptCredentialPresentationFactory = receiptCredentialPresentationFactory;
}
@Override
public RedeemReceiptResponse redeemReceipt(final RedeemReceiptRequest request) {
try {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
final ReceiptCredentialPresentation receiptCredentialPresentation = receiptCredentialPresentationFactory
.build(request.getReceiptCredentialPresentation().toByteArray());
serverZkReceiptOperations.verifyReceiptCredentialPresentation(receiptCredentialPresentation);
final ReceiptSerial receiptSerial = receiptCredentialPresentation.getReceiptSerial();
final Instant receiptExpiration = Instant.ofEpochSecond(receiptCredentialPresentation.getReceiptExpirationTime());
final long receiptLevel = receiptCredentialPresentation.getReceiptLevel();
final String badgeId = badgesConfiguration.getReceiptLevels().get(receiptLevel);
if (badgeId == null) {
// Since the receipt presentation checked out, the server messed up because it doesn't recognize a receipt level it previously issued.
LOGGER.error("Server doesn't recognize previously issued receipt level; please check badgesConfiguration for issues");
throw GrpcExceptions.unavailable("server does not recognize the requested receipt level");
}
final boolean receiptMatched = redeemedReceiptsManager.put(
receiptSerial, receiptExpiration.getEpochSecond(), receiptLevel, authenticatedDevice.accountIdentifier());
if (!receiptMatched) {
return RedeemReceiptResponse.newBuilder()
.setAlreadyRedeemed(FailedPrecondition.newBuilder()
.setDescription("receipt has already been redeemed")
.build())
.build();
}
accountsManager.update(authenticatedDevice.accountIdentifier(), a -> {
a.addBadge(clock, new AccountBadge(badgeId, receiptExpiration, request.getVisible()));
if (request.getPrimary()) {
a.makeBadgePrimaryIfExists(clock, badgeId);
}
});
return RedeemReceiptResponse.newBuilder()
.setSuccess(Empty.getDefaultInstance())
.build();
} catch (final InvalidInputException e) {
return RedeemReceiptResponse.newBuilder()
.setFailedAuthentication(FailedZkAuthentication.newBuilder()
.setDescription("invalid receipt credential presentation")
.build())
.build();
} catch (final VerificationFailedException e) {
return RedeemReceiptResponse.newBuilder()
.setFailedAuthentication(FailedZkAuthentication.newBuilder()
.setDescription("receipt credential presentation verification failed")
.build())
.build();
}
}
}
@@ -39,7 +39,7 @@ public class ErrorConformanceInterceptor implements ServerInterceptor {
}
switch (status.getCode()) {
case UNAUTHENTICATED, UNAVAILABLE, INVALID_ARGUMENT, RESOURCE_EXHAUSTED -> {
case UNAUTHENTICATED, UNAVAILABLE, INVALID_ARGUMENT, RESOURCE_EXHAUSTED, ABORTED -> {
}
default -> {
log.error("Intercepted call {} returned illegal application status {}: {}",
@@ -53,11 +53,11 @@ public class ErrorMappingInterceptor implements ServerInterceptor {
case ConvertibleToGrpcStatus e -> e.toStatusRuntimeException();
case UncheckedIOException e -> {
log.warn("RPC {} encountered UncheckedIOException", call.getMethodDescriptor().getFullMethodName(), e.getCause());
yield GrpcExceptions.unavailable(e.getCause().getMessage());
yield GrpcExceptions.unavailable();
}
case IOException e -> {
log.warn("RPC {} encountered IOException", call.getMethodDescriptor().getFullMethodName(), e);
yield GrpcExceptions.unavailable(e.getMessage());
yield GrpcExceptions.unavailable();
}
case null -> {
log.error("RPC {} finished with status UNKNOWN: {}",
@@ -1,66 +0,0 @@
/*
* Copyright 2023 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc;
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.VisibleForTesting;
import java.time.Clock;
import java.util.Map;
import org.signal.chat.credentials.ExternalServiceType;
import org.signal.chat.credentials.GetExternalServiceCredentialsRequest;
import org.signal.chat.credentials.GetExternalServiceCredentialsResponse;
import org.signal.chat.credentials.SimpleExternalServiceCredentialsGrpc;
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
public class ExternalServiceCredentialsGrpcService extends SimpleExternalServiceCredentialsGrpc.ExternalServiceCredentialsImplBase {
private final Map<ExternalServiceType, ExternalServiceCredentialsGenerator> credentialsGeneratorByType;
private final RateLimiters rateLimiters;
public static ExternalServiceCredentialsGrpcService createForAllExternalServices(
final WhisperServerConfiguration chatConfiguration,
final RateLimiters rateLimiters) {
return new ExternalServiceCredentialsGrpcService(
ExternalServiceDefinitions.createExternalServiceList(chatConfiguration, Clock.systemUTC()),
rateLimiters
);
}
@VisibleForTesting
ExternalServiceCredentialsGrpcService(
final Map<ExternalServiceType, ExternalServiceCredentialsGenerator> credentialsGeneratorByType,
final RateLimiters rateLimiters) {
this.credentialsGeneratorByType = requireNonNull(credentialsGeneratorByType);
this.rateLimiters = requireNonNull(rateLimiters);
}
@Override
public GetExternalServiceCredentialsResponse getExternalServiceCredentials(final GetExternalServiceCredentialsRequest request)
throws RateLimitExceededException {
final ExternalServiceCredentialsGenerator credentialsGenerator = this.credentialsGeneratorByType
.get(request.getExternalService());
if (credentialsGenerator == null) {
throw GrpcExceptions.fieldViolation("externalService", "Invalid external service type");
}
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
rateLimiters.forDescriptor(RateLimiters.For.EXTERNAL_SERVICE_CREDENTIALS).validate(authenticatedDevice.accountIdentifier());
final ExternalServiceCredentials externalServiceCredentials = credentialsGenerator
.generateForUuid(authenticatedDevice.accountIdentifier());
return GetExternalServiceCredentialsResponse.newBuilder()
.setUsername(externalServiceCredentials.username())
.setPassword(externalServiceCredentials.password())
.build();
}
}
@@ -20,7 +20,7 @@ import org.whispersystems.textsecuregcm.configuration.DirectoryV2ClientConfigura
import org.whispersystems.textsecuregcm.configuration.PaymentsServiceConfiguration;
import org.whispersystems.textsecuregcm.configuration.SecureValueRecoveryConfiguration;
enum ExternalServiceDefinitions {
public enum ExternalServiceDefinitions {
DIRECTORY(ExternalServiceType.EXTERNAL_SERVICE_TYPE_DIRECTORY, (chatConfig, clock) -> {
final DirectoryV2ClientConfiguration cfg = chatConfig.getDirectoryV2Configuration().getDirectoryV2ClientConfiguration();
return ExternalServiceCredentialsGenerator
@@ -30,7 +30,7 @@ enum ExternalServiceDefinitions {
.withClock(clock)
.build();
}),
PAYMENTS(ExternalServiceType.EXTERNAL_SERVICE_TYPE_PAYMENTS, (chatConfig, clock) -> {
PAYMENTS(ExternalServiceType.EXTERNAL_SERVICE_TYPE_PAYMENTS, (chatConfig, _) -> {
final PaymentsServiceConfiguration cfg = chatConfig.getPaymentsServiceConfiguration();
return ExternalServiceCredentialsGenerator
.builder(cfg.userAuthenticationTokenSharedSecret())
@@ -47,7 +47,7 @@ enum ExternalServiceDefinitions {
.withClock(clock)
.build();
}),
STORAGE(ExternalServiceType.EXTERNAL_SERVICE_TYPE_STORAGE, (chatConfig, clock) -> {
STORAGE(ExternalServiceType.EXTERNAL_SERVICE_TYPE_STORAGE, (chatConfig, _) -> {
final PaymentsServiceConfiguration cfg = chatConfig.getPaymentsServiceConfiguration();
return ExternalServiceCredentialsGenerator
.builder(cfg.userAuthenticationTokenSharedSecret())
@@ -39,6 +39,11 @@ public class GrpcExceptions {
.setReason("BAD_AUTHENTICATION")
.build());
private static final Any ERROR_INFO_STREAM_CLOSED = Any.pack(ErrorInfo.newBuilder()
.setDomain(DOMAIN)
.setReason("STREAM_CLOSED")
.build());
private static final com.google.rpc.Status UPGRADE_REQUIRED = com.google.rpc.Status.newBuilder()
.setCode(Status.Code.INVALID_ARGUMENT.value())
.setMessage("Upgrade required")
@@ -93,20 +98,6 @@ public class GrpcExceptions {
.build());
}
/// The RPC argument violated a constraint that was annotated or documented in the service definition. It is always
/// possible to check this constraint without communicating with the chat server. This always represents a client bug
/// or out of date client.
///
/// @param message Additional context about the constraint violation
/// @return A [StatusRuntimeException] encoding the error
public static StatusRuntimeException constraintViolation(@Nullable final String message) {
return StatusProto.toStatusRuntimeException(com.google.rpc.Status.newBuilder()
.setCode(Status.Code.INVALID_ARGUMENT.value())
.setMessage(messageOrDefault(message, Status.Code.INVALID_ARGUMENT))
.addDetails(ERROR_INFO_CONSTRAINT_VIOLATED)
.build());
}
/// The request has incorrectly set authentication credentials for the RPC. This represents a client bug where the
/// authorization header is not correct for the RPC. For example,
///
@@ -158,6 +149,20 @@ public class GrpcExceptions {
return StatusProto.toStatusRuntimeException(builder.build());
}
/// The server terminated the stream non-successfully for a reason specific to the RPC. The server must provide
/// additional information about the stream closure reason via the `streamClosedMessage`.
///
/// @param streamClosedMessage The additional domain-specific proto message that indicates the closure reason
/// @return A [StatusRuntimeException] encoding the error
public static <T extends com.google.protobuf.Message> StatusRuntimeException streamClosed(
final T streamClosedMessage) {
return StatusProto.toStatusRuntimeException(com.google.rpc.Status.newBuilder()
.setCode(Status.Code.ABORTED.value())
.addDetails(ERROR_INFO_STREAM_CLOSED)
.addDetails(Any.pack(streamClosedMessage))
.build());
}
public static StatusRuntimeException unavailable() {
return unavailable(null);
}
@@ -5,17 +5,15 @@
package org.whispersystems.textsecuregcm.grpc;
import com.google.protobuf.ByteString;
import io.grpc.Status;
import java.util.UUID;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
public class ServiceIdentifierUtil {
public class GrpcServiceIdentifierUtil {
private ServiceIdentifierUtil() {
private GrpcServiceIdentifierUtil() {
}
public static ServiceIdentifier fromGrpcServiceIdentifier(final org.signal.chat.common.ServiceIdentifier serviceIdentifier) {
@@ -42,12 +40,4 @@ public class ServiceIdentifierUtil {
.setUuid(UUIDUtil.toByteString(serviceIdentifier.uuid()))
.build();
}
public static ByteString toCompactByteString(final ServiceIdentifier serviceIdentifier) {
return ByteString.copyFrom(serviceIdentifier.toCompactByteArray());
}
public static ServiceIdentifier fromByteString(final ByteString byteString) {
return ServiceIdentifier.fromBytes(byteString.toByteArray());
}
}
@@ -13,7 +13,6 @@ import java.util.Arrays;
import java.util.concurrent.Flow;
import org.signal.chat.errors.FailedUnidentifiedAuthorization;
import org.signal.chat.errors.NotFound;
import org.signal.chat.keys.AccountPreKeyBundles;
import org.signal.chat.keys.CheckIdentityKeyRequest;
import org.signal.chat.keys.CheckIdentityKeyResponse;
import org.signal.chat.keys.GetPreKeysAnonymousRequest;
@@ -46,7 +45,7 @@ public class KeysAnonymousGrpcService extends SimpleKeysAnonymousGrpc.KeysAnonym
@Override
public GetPreKeysAnonymousResponse getPreKeys(final GetPreKeysAnonymousRequest request) {
final ServiceIdentifier serviceIdentifier =
ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getRequest().getTargetIdentifier());
GrpcServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getRequest().getTargetIdentifier());
final byte deviceId = request.getRequest().hasDeviceId()
? DeviceIdUtil.validate(request.getRequest().getDeviceId())
@@ -91,7 +90,7 @@ public class KeysAnonymousGrpcService extends SimpleKeysAnonymousGrpc.KeysAnonym
@Override
public Flow.Publisher<CheckIdentityKeyResponse> checkIdentityKeys(final Flow.Publisher<CheckIdentityKeyRequest> requests) {
return JdkFlowAdapter.publisherToFlowPublisher(JdkFlowAdapter.flowPublisherToFlux(requests)
.map(request -> Tuples.of(ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getTargetIdentifier()),
.map(request -> Tuples.of(GrpcServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getTargetIdentifier()),
request.getFingerprint().toByteArray()))
.flatMap(serviceIdentifierAndFingerprint -> Mono.fromFuture(
() -> accountsManager.getByServiceIdentifierAsync(serviceIdentifierAndFingerprint.getT1()))
@@ -100,7 +99,7 @@ public class KeysAnonymousGrpcService extends SimpleKeysAnonymousGrpc.KeysAnonym
.identityType()), serviceIdentifierAndFingerprint.getT2()))
.map(account -> CheckIdentityKeyResponse.newBuilder()
.setTargetIdentifier(
ServiceIdentifierUtil.toGrpcServiceIdentifier(serviceIdentifierAndFingerprint.getT1()))
GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(serviceIdentifierAndFingerprint.getT1()))
.setIdentityKey(ByteString.copyFrom(account.getIdentityKey(serviceIdentifierAndFingerprint.getT1()
.identityType()).serialize()))
.build())));
@@ -96,7 +96,7 @@ public class KeysGrpcService extends SimpleKeysGrpc.KeysImplBase {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
final ServiceIdentifier targetIdentifier =
ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getTargetIdentifier());
GrpcServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getTargetIdentifier());
final Optional<Account> maybeTargetAccount = accountsManager.getByServiceIdentifier(targetIdentifier);
@@ -0,0 +1,268 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc;
import com.google.common.annotations.VisibleForTesting;
import com.google.protobuf.Empty;
import io.grpc.StatusRuntimeException;
import io.micrometer.core.instrument.Metrics;
import java.time.Duration;
import java.util.UUID;
import javax.annotation.Nullable;
import org.signal.chat.messages.GetMessagesResponse;
import org.signal.chat.messages.GetMessagesStreamClosed;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestListener;
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestManager;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.limits.MessageDeliveryLoopMonitor;
import org.whispersystems.textsecuregcm.metrics.MessageMetrics;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
import org.whispersystems.textsecuregcm.push.PushNotificationScheduler;
import org.whispersystems.textsecuregcm.push.ReceiptSender;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
import org.whispersystems.textsecuregcm.storage.ConflictingMessageConsumerException;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.MessageStream;
import org.whispersystems.textsecuregcm.storage.MessageStreamEntry;
import org.whispersystems.textsecuregcm.storage.MessagesManager;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
import org.whispersystems.textsecuregcm.util.ua.UserAgent;
import org.whispersystems.textsecuregcm.util.ua.UserAgentUtil;
import reactor.adapter.JdkFlowAdapter;
import reactor.core.observability.micrometer.Micrometer;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.publisher.Signal;
import reactor.core.publisher.Sinks;
/// A MessageDispatcher is used to stream messages to an authenticated device and coordinates message acknowledgement,
/// backpressure, disconnection signals, and receipts.
public class MessageDispatcher {
private static final Logger log = LoggerFactory.getLogger(MessageDispatcher.class);
@VisibleForTesting
static final int MAX_UNACKED_MESSAGES = 256;
@VisibleForTesting
static final Duration CLOSE_WITH_PENDING_MESSAGES_NOTIFICATION_DELAY = Duration.ofMinutes(1);
private static final int MESSAGE_PUBLISHER_LIMIT_RATE = 100;
public static final GetMessagesResponse QUEUE_EMPTY_RESPONSE =
GetMessagesResponse.newBuilder().setQueueEmpty(Empty.getDefaultInstance()).build();
private static final StatusRuntimeException CONFLICTING_STREAM_EXCEPTION =
GrpcExceptions.streamClosed(GetMessagesStreamClosed.newBuilder()
.setConflictingStream(Empty.getDefaultInstance())
.build());
private static final String SEND_MESSAGES_FLUX_NAME = MetricsUtil.name(MessageDispatcher.class, "sendMessages");
private final ReceiptSender receiptSender;
private final MessagesManager messagesManager;
private final MessageMetrics messageMetrics;
private final PushNotificationManager pushNotificationManager;
private final PushNotificationScheduler pushNotificationScheduler;
private final ClientReleaseManager clientReleaseManager;
private final MessageDeliveryLoopMonitor messageDeliveryLoopMonitor;
private final DisconnectionRequestManager disconnectionRequestManager;
public MessageDispatcher(final ReceiptSender receiptSender,
final MessagesManager messagesManager,
final MessageMetrics messageMetrics,
final PushNotificationManager pushNotificationManager,
final PushNotificationScheduler pushNotificationScheduler,
final MessageDeliveryLoopMonitor messageDeliveryLoopMonitor,
final DisconnectionRequestManager disconnectionRequestManager,
final ClientReleaseManager clientReleaseManager) {
this.receiptSender = receiptSender;
this.messagesManager = messagesManager;
this.messageMetrics = messageMetrics;
this.pushNotificationManager = pushNotificationManager;
this.pushNotificationScheduler = pushNotificationScheduler;
this.messageDeliveryLoopMonitor = messageDeliveryLoopMonitor;
this.disconnectionRequestManager = disconnectionRequestManager;
this.clientReleaseManager = clientReleaseManager;
}
/// Retrieve messages for the device.
///
/// ## Termination
/// The returned message stream is potentially infinite. It will terminate if the device acknowledgement stream
/// terminates for any reason. The error from the client will be propagated to the returned flux. The stream may also
/// terminate with any other error encountered retrieving messages or processing acknowledgements.
///
/// The returned flux will error with a [GrpcExceptions#streamClosed] non-ok status exception if:
/// - A disconnection request (typically indicating a change in authorization credentials) is received
/// - A client requests messages for the same account/device while this stream is still active
///
/// When the stream terminates for any reason and the client has messages remaining in their queue, a push
/// notification is scheduled to encourage the client to wake up and try again after a delay.
///
/// ## Queue Empty
/// The returned flux will emit a queue empty indicator when the device has successfully drained their waiting queue
/// and acknowledged all of them. A queue empty response guarantees all messages that were waiting for the client when
/// they first connected have been delivered and removed from storage, though it's possible the queue empty response
/// also waits for messages that arrived in the intervening period.
///
/// ## Acknowledgement
/// When the device acknowledges a message GUID it is removed from storage. If applicable, a delivery receipt is sent
/// to the original sender of the message.
///
///
/// @param shouldDropStories if true, stories will not be delivered in the response stream (and will be
/// removed from persistent storage)
/// @param userAgentString the userAgent of the requesting device
/// @param account the account to retrieve messages for
/// @param device the device to retrieve messages for
/// @param acknowledgedMessageGuids A flux that should emit the server guid of messages when they have been
/// acknowledged by the device
/// @return The message stream
public Flux<GetMessagesResponse> getMessages(
final boolean shouldDropStories,
@Nullable final String userAgentString,
final Account account,
final Device device,
final Flux<UUID> acknowledgedMessageGuids) {
final MessageStream messageStream = messagesManager.getMessages(account.getIdentifier(IdentityType.ACI), device);
@Nullable final UserAgent userAgent = UserAgentUtil.maybeParseUserAgentString(userAgentString);
final PendingAcknowledgementTracker pendingAcknowledgementTracker = new PendingAcknowledgementTracker(messageMetrics, userAgent);
pushNotificationManager.handleMessagesRetrieved(account, device, userAgentString);
final Flux<GetMessagesResponse> messages = JdkFlowAdapter.flowPublisherToFlux(messageStream.getMessages())
.name(SEND_MESSAGES_FLUX_NAME)
.tap(Micrometer.metrics(Metrics.globalRegistry))
.limitRate(MESSAGE_PUBLISHER_LIMIT_RATE)
// Check the first message we send for message-delivery loops
.switchOnFirst((firstEntry, flux) -> {
recordDeliveryAttempt(account, device, userAgentString, firstEntry);
return flux;
})
.flatMapSequential(entry -> switch (entry) {
case MessageStreamEntry.Envelope(final MessageProtos.Envelope envelope) -> {
final UUID serverGuid = UUIDUtil.fromByteString(envelope.getServerGuid());
if (envelope.getStory() && shouldDropStories) {
// Just immediately delete stories if the device doesn't want them
yield Mono.fromFuture(() -> messageStream.acknowledgeMessage(serverGuid, envelope.getServerTimestamp()))
.then(Mono.empty());
}
pendingAcknowledgementTracker.addUnacknowledgedEnvelope(envelope);
final MessageProtos.Envelope stripped = envelope.toBuilder().clearEphemeral().build();
messageMetrics.measureAccountEnvelopeUuidMismatches(account, envelope);
messageMetrics.measureMessageSent(stripped.getSerializedSize());
yield Mono.just(GetMessagesResponse.newBuilder().setEnvelope(stripped).build());
}
case MessageStreamEntry.QueueEmpty _ -> {
pendingAcknowledgementTracker.markEndOfQueue();
yield Mono.empty();
}
}, MAX_UNACKED_MESSAGES)
.onErrorMap(ConflictingMessageConsumerException.class, _ -> {
messageMetrics.measureMessageStreamDisplaced(MessageMetrics.GRPC_CHANNEL, userAgent, true);
return CONFLICTING_STREAM_EXCEPTION;
});
// Only emit envelopes when the permit flux emits a value. Initially it is seeded MAX_UNACKED_MESSAGES permits,
// after that a permit is emitted every time we receive an ack.
final Sinks.Many<Boolean> ackPermits = Sinks.many().unicast().onBackpressureBuffer();
final Flux<Boolean> permits = Flux.range(0, MAX_UNACKED_MESSAGES)
.map(_ -> true)
.concatWith(ackPermits.asFlux());
final Mono<GetMessagesResponse> ackCompletions = acknowledgedMessageGuids
.flatMap(guid -> {
final PendingAcknowledgementTracker.UnacknowledgedEnvelope unacked = pendingAcknowledgementTracker.takeUnacknowledgedEnvelope(guid);
if (unacked == null) {
// This is fine, the client may have sent a duplicate-ack
return Mono.empty();
}
messageMetrics.measureOutgoingMessageLatency(
unacked.getServerTimestamp(), MessageMetrics.GRPC_CHANNEL, device.isPrimary(),
unacked.isUrgent(), unacked.isEphemeral(), userAgent, clientReleaseManager);
maybeSendDeliveryReceipt(device, unacked);
return Mono.fromFuture(() -> messageStream.acknowledgeMessage(unacked.getServerGuid(), unacked.getServerTimestamp()))
.doOnSuccess(_ -> unacked.handleMessageAcknowledged())
// Just have to emit some value that indicates we can release a permit
.thenReturn(true);
}, MAX_UNACKED_MESSAGES)
.doOnNext(_ -> ackPermits.tryEmitNext(true))
.ignoreElements()
.cast(GetMessagesResponse.class);
return Flux.merge(
// Emit messages, but only when a permit is available
messages.zipWith(permits, (resp, _) -> resp),
// Will only emit errors, but those should terminate the stream
ackCompletions,
// Emits a queue empty once all messages prior to the queueEmpty signal have been acked
pendingAcknowledgementTracker.queueDrained(),
// Emit an invalid credentials error if we receive a disconnection request
disconnectionSignal(account, device, userAgent))
.doFinally(_ -> maybeSchedulePush(account, device));
}
/// If the device potentially has more messages available, schedule a push notification.
private void maybeSchedulePush(final Account account, final Device device) {
messagesManager.mayHaveMessages(account.getIdentifier(IdentityType.ACI), device)
.thenAccept(mayHaveMessages -> {
if (mayHaveMessages) {
pushNotificationScheduler.scheduleDelayedNotification(account, device,
CLOSE_WITH_PENDING_MESSAGES_NOTIFICATION_DELAY);
}
});
}
/// Watch for a disconnection signal from the [DisconnectionRequestManager]
///
/// @return Mono that completes with an `InvalidCredentials` status if the
/// device receives a disconnection request
private Mono<GetMessagesResponse> disconnectionSignal(final Account account, final Device device, final UserAgent userAgent) {
return Mono.create(sink -> {
final DisconnectionRequestListener listener = () -> {
messageMetrics.measureMessageStreamDisplaced(MessageMetrics.GRPC_CHANNEL, userAgent, false);
sink.error(GrpcExceptions.invalidCredentials("reauthentication required"));
};
disconnectionRequestManager.addListener(account.getUuid(), device.getId(), listener);
sink.onDispose(() -> disconnectionRequestManager.removeListener(account.getUuid(), device.getId(), listener));
});
}
private void recordDeliveryAttempt(final Account account, final Device device, final String userAgent,
final Signal<? extends MessageStreamEntry> firstEntry) {
if (firstEntry.get() instanceof MessageStreamEntry.Envelope(final MessageProtos.Envelope message)) {
messageDeliveryLoopMonitor.recordDeliveryAttempt(account.getIdentifier(IdentityType.ACI),
device.getId(),
UUIDUtil.fromByteString(message.getServerGuid()),
userAgent,
MessageMetrics.GRPC_CHANNEL);
}
}
private void maybeSendDeliveryReceipt(
final Device device,
final PendingAcknowledgementTracker.UnacknowledgedEnvelope unacknowledgedEnvelope) {
if (unacknowledgedEnvelope.getSourceServiceId() == null) {
return;
}
try {
receiptSender.sendReceipt(
unacknowledgedEnvelope.getDestinationServiceId(),
device.getId(),
unacknowledgedEnvelope.getSourceServiceId(),
unacknowledgedEnvelope.getClientTimestamp());
} catch (final Exception e) {
log.warn("Failed to send receipt", e);
}
}
}
@@ -6,19 +6,18 @@
package org.whispersystems.textsecuregcm.grpc;
import com.google.protobuf.ByteString;
import com.google.protobuf.Empty;
import java.time.Clock;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import com.google.protobuf.Empty;
import io.grpc.Status;
import org.signal.chat.errors.FailedUnidentifiedAuthorization;
import org.signal.chat.errors.NotFound;
import org.signal.chat.messages.IndividualRecipientMessageBundle;
import org.signal.chat.messages.SendMessageType;
import org.signal.chat.messages.MultiRecipientMismatchedDevices;
import org.signal.chat.messages.MultiRecipientSuccess;
import org.signal.chat.messages.SendMessageResponse;
import org.signal.chat.messages.SendMessageType;
import org.signal.chat.messages.SendMultiRecipientMessageRequest;
import org.signal.chat.messages.SendMultiRecipientMessageResponse;
import org.signal.chat.messages.SendMultiRecipientStoryRequest;
@@ -85,7 +84,7 @@ public class MessagesAnonymousGrpcService extends SimpleMessagesAnonymousGrpc.Me
throws RateLimitExceededException {
final ServiceIdentifier destinationServiceIdentifier =
ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getDestination());
GrpcServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getDestination());
final Optional<Account> maybeDestination = accountsManager.getByServiceIdentifier(destinationServiceIdentifier);
@@ -133,7 +132,7 @@ public class MessagesAnonymousGrpcService extends SimpleMessagesAnonymousGrpc.Me
throws RateLimitExceededException {
final ServiceIdentifier destinationServiceIdentifier =
ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getDestination());
GrpcServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getDestination());
final Optional<Account> maybeDestination = accountsManager.getByServiceIdentifier(destinationServiceIdentifier);
@@ -194,7 +193,7 @@ public class MessagesAnonymousGrpcService extends SimpleMessagesAnonymousGrpc.Me
.setType(MessageProtos.Envelope.Type.UNIDENTIFIED_SENDER)
.setClientTimestamp(messages.getTimestamp())
.setServerTimestamp(clock.millis())
.setDestinationServiceId(destinationServiceIdentifier.toServiceIdentifierString())
.setDestinationServiceId(destinationServiceIdentifier.toCompactByteString())
.setEphemeral(ephemeral)
.setUrgent(urgent)
.setContent(entry.getValue().getPayload());
@@ -313,7 +312,7 @@ public class MessagesAnonymousGrpcService extends SimpleMessagesAnonymousGrpc.Me
final MultiRecipientSuccess.Builder responseBuilder = MultiRecipientSuccess.newBuilder();
MessageUtil.getUnresolvedRecipients(multiRecipientMessage, resolvedRecipients).stream()
.map(ServiceIdentifierUtil::toGrpcServiceIdentifier)
.map(GrpcServiceIdentifierUtil::toGrpcServiceIdentifier)
.forEach(responseBuilder::addUnresolvedRecipients);
return SendMultiRecipientMessageResponse.newBuilder().setSuccess(responseBuilder).build();
@@ -23,7 +23,7 @@ public class MessagesGrpcHelper {
final org.whispersystems.textsecuregcm.controllers.MismatchedDevices mismatchedDevices) {
final MismatchedDevices.Builder mismatchedDevicesBuilder = MismatchedDevices.newBuilder()
.setServiceIdentifier(ServiceIdentifierUtil.toGrpcServiceIdentifier(serviceIdentifier));
.setServiceIdentifier(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(serviceIdentifier));
mismatchedDevices.missingDeviceIds().forEach(mismatchedDevicesBuilder::addMissingDevices);
mismatchedDevices.extraDeviceIds().forEach(mismatchedDevicesBuilder::addExtraDevices);
@@ -12,8 +12,13 @@ import com.google.protobuf.Empty;
import java.time.Clock;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.Flow;
import java.util.stream.Collectors;
import io.grpc.StatusRuntimeException;
import org.signal.chat.errors.NotFound;
import org.signal.chat.messages.GetMessagesRequest;
import org.signal.chat.messages.GetMessagesResponse;
import org.signal.chat.messages.IndividualRecipientMessageBundle;
import org.signal.chat.messages.SendAuthenticatedSenderMessageRequest;
import org.signal.chat.messages.SendMessageAuthenticatedSenderResponse;
@@ -38,6 +43,11 @@ import org.whispersystems.textsecuregcm.spam.SpamCheckResult;
import org.whispersystems.textsecuregcm.spam.SpamChecker;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
import reactor.adapter.JdkFlowAdapter;
import reactor.core.publisher.Flux;
import javax.annotation.Nullable;
public class MessagesGrpcService extends SimpleMessagesGrpc.MessagesImplBase {
@@ -46,6 +56,7 @@ public class MessagesGrpcService extends SimpleMessagesGrpc.MessagesImplBase {
private final MessageSender messageSender;
private final CardinalityEstimator messageByteLimitEstimator;
private final SpamChecker spamChecker;
private final MessageDispatcher messageDispatcher;
private final Clock clock;
private static final SendMessageAuthenticatedSenderResponse SEND_MESSAGE_SUCCESS_RESPONSE =
@@ -56,6 +67,7 @@ public class MessagesGrpcService extends SimpleMessagesGrpc.MessagesImplBase {
final MessageSender messageSender,
final CardinalityEstimator messageByteLimitEstimator,
final SpamChecker spamChecker,
final MessageDispatcher messageDispatcher,
final Clock clock) {
this.accountsManager = accountsManager;
@@ -63,9 +75,49 @@ public class MessagesGrpcService extends SimpleMessagesGrpc.MessagesImplBase {
this.messageSender = messageSender;
this.messageByteLimitEstimator = messageByteLimitEstimator;
this.spamChecker = spamChecker;
this.messageDispatcher = messageDispatcher;
this.clock = clock;
}
@Override
public Flow.Publisher<GetMessagesResponse> getMessages(final Flow.Publisher<GetMessagesRequest> request) throws Exception {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
final Account account = accountsManager
.getByAccountIdentifier(authenticatedDevice.accountIdentifier())
.orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials"));
final Device device = account.getDevice(authenticatedDevice.deviceId())
.orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials"));
final String userAgent = RequestAttributesUtil.getUserAgent().orElse(null);
final Flux<GetMessagesRequest> requestFlux = JdkFlowAdapter.flowPublisherToFlux(request);
return JdkFlowAdapter.publisherToFlowPublisher(requestFlux.switchOnFirst((firstSignal, flux) -> {
@Nullable final GetMessagesRequest streamRequest = firstSignal.get();
if (streamRequest == null) {
// Just forward the error or completion signal
return flux.then().cast(GetMessagesResponse.class);
}
if (!streamRequest.hasOptions()) {
throw GrpcExceptions.fieldViolation("request", "the first request must be GetMessageOptions");
}
final boolean dropStories = streamRequest.getOptions().getDropStories();
return messageDispatcher.getMessages(dropStories, userAgent, account, device,
flux.skip(1).map(MessagesGrpcService::extractAckGuid));
}));
}
private static UUID extractAckGuid(final GetMessagesRequest ack) throws StatusRuntimeException {
if (!ack.hasServerGuidAck()) {
throw GrpcExceptions.fieldViolation("request", "All non-initial GetMessageRequests must contain a server_guid_ack");
}
try {
return UUIDUtil.fromByteString(ack.getServerGuidAck());
} catch (final IllegalArgumentException e) {
throw GrpcExceptions.fieldViolation("server_guid_ack", "invalid server_guid_ack");
}
}
@Override
public SendMessageAuthenticatedSenderResponse sendMessage(final SendAuthenticatedSenderMessageRequest request)
throws RateLimitExceededException {
@@ -76,7 +128,7 @@ public class MessagesGrpcService extends SimpleMessagesGrpc.MessagesImplBase {
.orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials"));
final ServiceIdentifier destinationServiceIdentifier =
ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getDestination());
GrpcServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getDestination());
if (sender.isIdentifiedBy(destinationServiceIdentifier)) {
throw GrpcExceptions.invalidArguments("use `sendSyncMessage` to send messages to own account");
@@ -159,8 +211,8 @@ public class MessagesGrpcService extends SimpleMessagesGrpc.MessagesImplBase {
.setType(getEnvelopeType(entry.getValue().getType()))
.setClientTimestamp(messages.getTimestamp())
.setServerTimestamp(clock.millis())
.setDestinationServiceId(destinationServiceIdentifier.toServiceIdentifierString())
.setSourceServiceId(new AciServiceIdentifier(sender.accountIdentifier()).toServiceIdentifierString())
.setDestinationServiceId(destinationServiceIdentifier.toCompactByteString())
.setSourceServiceId(new AciServiceIdentifier(sender.accountIdentifier()).toCompactByteString())
.setSourceDevice(sender.deviceId())
.setEphemeral(ephemeral)
.setUrgent(urgent)
@@ -0,0 +1,171 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc;
import io.micrometer.core.instrument.Timer;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import javax.annotation.Nullable;
import org.signal.chat.messages.GetMessagesResponse;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.metrics.MessageMetrics;
import org.whispersystems.textsecuregcm.util.ClosableEpoch;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
import org.whispersystems.textsecuregcm.util.ua.UserAgent;
import reactor.core.publisher.Mono;
import reactor.core.publisher.Sinks;
/// Track messages while they are in-flight so they can later be retrieved for acknowledgement, as well as when
/// acknowledgement completes.
///
/// # Example Usage
/// ```java
/// PendingAcknowledgement tracker = new PendingAcknowledgementTracker(...);
/// tracker.addUnacknowledgedEnvelope(envelope);
/// sendEnvelopeToDevice(envelope);
///
/// // Later, when the device acklowedges the envelope
/// UnacknowledgedEnvelope envelope = takeUnacknowledgedEnvelope(uuid);
/// removeFromStorage(envelope);
/// envelope.handleMessageAcknowledged();
/// ```
class PendingAcknowledgementTracker {
private final ConcurrentHashMap<UUID, UnacknowledgedEnvelope> unacknowledgedEnvelopes = new ConcurrentHashMap<>();
private final AtomicLong sentMessageCounter = new AtomicLong();
private final Sinks.One<GetMessagesResponse> queueDrained = Sinks.one();
private final ClosableEpoch queueDrainEpoch = new ClosableEpoch(() ->
queueDrained.tryEmitValue(MessageDispatcher.QUEUE_EMPTY_RESPONSE));
private final Timer.Sample queueDrainStart = Timer.start();
private final MessageMetrics messageMetrics;
@Nullable private final UserAgent userAgent;
PendingAcknowledgementTracker(final MessageMetrics messageMetrics, @Nullable final UserAgent userAgent) {
this.messageMetrics = messageMetrics;
this.userAgent = userAgent;
}
/// Store an envelope so it can be retrieved later via [#takeUnacknowledgedEnvelope].
///
/// @param envelope An envelope that has been sent to a device and is waiting to be acknowledged
void addUnacknowledgedEnvelope(final MessageProtos.Envelope envelope) {
sentMessageCounter.incrementAndGet();
final UUID messageGuid = UUIDUtil.fromByteString(envelope.getServerGuid());
// If the envelope has a source, and it is not a server delivery receipt, it will be an ACI.
final AciServiceIdentifier sourceId = envelope.hasSourceServiceId() && envelope.getType() != MessageProtos.Envelope.Type.SERVER_DELIVERY_RECEIPT
? AciServiceIdentifier.fromByteString(envelope.getSourceServiceId())
: null;
final ServiceIdentifier destinationId = ServiceIdentifier.fromByteString(envelope.getDestinationServiceId());
final UnacknowledgedEnvelope unacknowledgedEnvelope = new UnacknowledgedEnvelope(messageGuid,
envelope.getServerTimestamp(), envelope.getClientTimestamp(),
envelope.getUrgent(), envelope.getEphemeral(),
destinationId, sourceId);
unacknowledgedEnvelopes.put(messageGuid, unacknowledgedEnvelope);
}
/// Take a previously stored envelope so it can be acknowledged. When the message is successfully removed from
/// storage, call [UnacknowledgedEnvelope#handleMessageAcknowledged()].
///
/// @param guid The server GUID of the envelope previously stored with [#addUnacknowledgedEnvelope(MessageProtos.Envelope)].
/// @return The previously stored envelope, or null if no envelope with the provided guid was stored
@Nullable
UnacknowledgedEnvelope takeUnacknowledgedEnvelope(final UUID guid) {
return unacknowledgedEnvelopes.remove(guid);
}
/// Signal that we've observed the end of the initial message queue. The Mono returned by [#queueDrained] will emit a
/// value when all current envelopes tracked with [#addUnacknowledgedEnvelope] have been marked [UnacknowledgedEnvelope#handleMessageAcknowledged()]
void markEndOfQueue() {
messageMetrics
.measureQueueDrain(MessageMetrics.GRPC_CHANNEL, userAgent, sentMessageCounter.get(), queueDrainStart);
queueDrainEpoch.close();
}
/// Determine when a queue has been drained.
///
/// @return A mono that completes with a QueueEmpty response when all messages tracked before [#markEndOfQueue] have
/// been acknowledged.
Mono<GetMessagesResponse> queueDrained() {
return queueDrained.asMono();
}
class UnacknowledgedEnvelope {
private final UUID serverGuid;
private final long serverTimestamp;
private final Timer.Sample sample;
private final boolean inDrainEpoch;
private final long clientTimestamp;
private final boolean urgent;
private final boolean ephemeral;
private final ServiceIdentifier destinationServiceId;
@Nullable private final AciServiceIdentifier sourceServiceId;
private UnacknowledgedEnvelope(
final UUID serverGuid,
final long serverTimestamp,
final long clientTimestamp,
final boolean urgent,
final boolean ephemeral,
final ServiceIdentifier destinationServiceId,
@Nullable final AciServiceIdentifier sourceServiceId) {
this.serverGuid = serverGuid;
this.serverTimestamp = serverTimestamp;
this.clientTimestamp = clientTimestamp;
this.urgent = urgent;
this.ephemeral = ephemeral;
this.destinationServiceId = destinationServiceId;
this.sample = Timer.start();
this.inDrainEpoch = queueDrainEpoch.tryArrive();
this.sourceServiceId = sourceServiceId;
}
void handleMessageAcknowledged() {
messageMetrics.measureSendMessageDuration(MessageMetrics.GRPC_CHANNEL, userAgent, sample);
if (inDrainEpoch) {
queueDrainEpoch.depart();
}
}
public UUID getServerGuid() {
return serverGuid;
}
public long getServerTimestamp() {
return serverTimestamp;
}
public long getClientTimestamp() {
return clientTimestamp;
}
public boolean isUrgent() {
return urgent;
}
public boolean isEphemeral() {
return ephemeral;
}
public ServiceIdentifier getDestinationServiceId() {
return destinationServiceId;
}
/// Get the sender of this message
///
/// @return the ServiceIdentifier of the source of this message. `null` if the message sender was not identified or
/// if the envelope was for a server delivery receipt
@Nullable
public AciServiceIdentifier getSourceServiceId() {
return sourceServiceId;
}
}
}
@@ -63,7 +63,7 @@ public class ProfileAnonymousGrpcService extends SimpleProfileAnonymousGrpc.Prof
@Override
public GetUnversionedProfileAnonymousResponse getUnversionedProfile(final GetUnversionedProfileAnonymousRequest request) {
final ServiceIdentifier targetIdentifier =
ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getRequest().getServiceIdentifier());
GrpcServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getRequest().getServiceIdentifier());
// Callers must be authenticated to request unversioned profiles by PNI
if (targetIdentifier.identityType() == IdentityType.PNI) {
@@ -77,7 +77,7 @@ public class ProfileAnonymousGrpcService extends SimpleProfileAnonymousGrpc.Prof
case UNIDENTIFIED_ACCESS_KEY ->
targetAccount.map(a -> UnidentifiedAccessUtil.checkUnidentifiedAccess(a, request.getUnidentifiedAccessKey().toByteArray()))
.orElse(false);
default -> throw GrpcExceptions.constraintViolation("invalid authentication");
default -> throw GrpcExceptions.invalidArguments("invalid authentication");
};
if (!authorized) {
@@ -100,7 +100,7 @@ public class ProfileAnonymousGrpcService extends SimpleProfileAnonymousGrpc.Prof
@Override
public GetVersionedProfileAnonymousResponse getVersionedProfile(final GetVersionedProfileAnonymousRequest request) {
final ServiceIdentifier targetIdentifier = ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getRequest().getAccountIdentifier());
final ServiceIdentifier targetIdentifier = GrpcServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getRequest().getAccountIdentifier());
final Optional<Account> targetAccount = getTargetAccountAndValidateUnidentifiedAccess(targetIdentifier, request.getUnidentifiedAccessKey().toByteArray());
@@ -123,10 +123,10 @@ public class ProfileAnonymousGrpcService extends SimpleProfileAnonymousGrpc.Prof
@Override
public GetExpiringProfileKeyCredentialAnonymousResponse getExpiringProfileKeyCredential(
final GetExpiringProfileKeyCredentialAnonymousRequest request) {
final ServiceIdentifier targetIdentifier = ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getRequest().getAccountIdentifier());
final ServiceIdentifier targetIdentifier = GrpcServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getRequest().getAccountIdentifier());
if (request.getRequest().getCredentialType() != CredentialType.CREDENTIAL_TYPE_EXPIRING_PROFILE_KEY) {
throw GrpcExceptions.constraintViolation("invalid credential type");
throw GrpcExceptions.invalidArguments("invalid credential type");
}
final Optional<Account> maybeAccount = getTargetAccountAndValidateUnidentifiedAccess(
@@ -208,7 +208,7 @@ public class ProfileGrpcHelper {
profileKeyCredentialResponse = ProfileHelper.getExpiringProfileKeyCredential(new ProfileKeyCredentialRequest(encodedCredentialRequest),
new ProfileKeyCommitment(commitment), new ServiceId.Aci(account.getUuid()), zkProfileOperations);
} catch (VerificationFailedException | InvalidInputException e) {
throw GrpcExceptions.constraintViolation("invalid credential request");
throw GrpcExceptions.invalidArguments("invalid credential request");
}
return GetExpiringProfileKeyCredentialResult.newBuilder()
@@ -152,7 +152,7 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
avatarData.finalAvatar().orElse(null),
request.getV1Request().getAboutEmoji().toByteArray(),
request.getV1Request().getAbout().toByteArray(),
request.getPaymentAddress().toByteArray(),
request.getPaymentAddress().isEmpty() ? null : request.getPaymentAddress().toByteArray(),
request.getV1Request().getPhoneNumberSharing().toByteArray(),
commitment);
@@ -211,7 +211,7 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
public GetUnversionedProfileResponse getUnversionedProfile(final GetUnversionedProfileRequest request) throws RateLimitExceededException {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
final ServiceIdentifier targetIdentifier =
ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getServiceIdentifier());
GrpcServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getServiceIdentifier());
final Optional<Account> maybeAccount = validateRateLimitAndGetAccount(authenticatedDevice.accountIdentifier(), targetIdentifier);
return maybeAccount.map(account -> GetUnversionedProfileResponse.newBuilder()
@@ -228,7 +228,7 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
public GetVersionedProfileResponse getVersionedProfile(final GetVersionedProfileRequest request) throws RateLimitExceededException {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
final ServiceIdentifier targetIdentifier =
ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getAccountIdentifier());
GrpcServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getAccountIdentifier());
final Optional<Account> maybeAccount = validateRateLimitAndGetAccount(authenticatedDevice.accountIdentifier(), targetIdentifier);
@@ -257,12 +257,12 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
private void validateRequest(final SetProfileRequest request) {
if (request.getExpectedCurrentDataHash().isEmpty() && request.getCommitment().isEmpty()) {
throw GrpcExceptions.constraintViolation("At least one of expected current data hash and commitment is required");
throw GrpcExceptions.invalidArguments("At least one of expected current data hash and commitment is required");
}
// v1 -> v2 migration
if (request.getCommitment().isEmpty()) {
throw GrpcExceptions.constraintViolation("Request must include commitment during migration");
throw GrpcExceptions.invalidArguments("Request must include commitment during migration");
}
}
@@ -5,6 +5,7 @@
package org.whispersystems.textsecuregcm.identity;
import com.google.protobuf.ByteString;
import io.micrometer.core.instrument.Metrics;
import io.swagger.v3.oas.annotations.media.Schema;
import java.nio.ByteBuffer;
@@ -62,6 +63,10 @@ public record AciServiceIdentifier(UUID uuid) implements ServiceIdentifier {
return new AciServiceIdentifier(UUID.fromString(string));
}
public static AciServiceIdentifier fromByteString(final ByteString byteString) {
return fromBytes(byteString.toByteArray());
}
public static AciServiceIdentifier fromBytes(final byte[] bytes) {
final UUID uuid;
@@ -5,6 +5,7 @@
package org.whispersystems.textsecuregcm.identity;
import com.google.protobuf.ByteString;
import io.swagger.v3.oas.annotations.media.Schema;
import java.util.UUID;
import org.signal.libsignal.protocol.ServiceId;
@@ -49,6 +50,15 @@ public sealed interface ServiceIdentifier permits AciServiceIdentifier, PniServi
*/
byte[] toCompactByteArray();
/**
* Returns a compact binary representation of this account identifier as a {@link ByteString}.
*
* @return a binary representation of this account identifier
*/
default ByteString toCompactByteString() {
return ByteString.copyFrom(toCompactByteArray());
}
/**
* Returns a fixed-width binary representation of this account identifier.
*
@@ -56,11 +66,20 @@ public sealed interface ServiceIdentifier permits AciServiceIdentifier, PniServi
*/
byte[] toFixedWidthByteArray();
/**
* Returns a fixed-width binary representation of this account identifier as a {@link ByteString}.
*
* @return a binary representation of this account identifier
*/
default ByteString toFixedWidthByteString() {
return ByteString.copyFrom(toFixedWidthByteArray());
}
/**
* Parse a service identifier string, which should be a plain UUID string for ACIs and a prefixed UUID string for PNIs
*
* @param string A service identifier string
* @return The parsed {@link ServiceIdentifier}
* @param string a service identifier string
* @return the parsed service identifier
*/
static ServiceIdentifier valueOf(final String string) {
try {
@@ -70,6 +89,12 @@ public sealed interface ServiceIdentifier permits AciServiceIdentifier, PniServi
}
}
/**
* Parse a service identifier from a byte array.
*
* @param bytes the byte array from which to parse a service identifier
* @return the parsed service identifier
*/
static ServiceIdentifier fromBytes(final byte[] bytes) {
try {
return AciServiceIdentifier.fromBytes(bytes);
@@ -78,6 +103,16 @@ public sealed interface ServiceIdentifier permits AciServiceIdentifier, PniServi
}
}
/**
* Parse a service identifier from a byte string.
*
* @param byteString the byte string from which to parse a service identifier
* @return the parsed service identifier
*/
static ServiceIdentifier fromByteString(final ByteString byteString) {
return fromBytes(byteString.toByteArray());
}
static ServiceIdentifier fromLibsignal(final ServiceId libsignalServiceId) {
if (libsignalServiceId instanceof ServiceId.Aci) {
return new AciServiceIdentifier(libsignalServiceId.getRawUUID());
@@ -16,6 +16,7 @@ import java.util.Optional;
import org.whispersystems.textsecuregcm.captcha.Action;
import org.whispersystems.textsecuregcm.captcha.AssessmentResult;
import org.whispersystems.textsecuregcm.captcha.CaptchaChecker;
import org.whispersystems.textsecuregcm.captcha.InvalidCaptchaArgumentException;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.metrics.CaptchaMetrics;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
@@ -24,6 +25,7 @@ import org.whispersystems.textsecuregcm.spam.ChallengeType;
import org.whispersystems.textsecuregcm.spam.RateLimitChallengeListener;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.util.Util;
import javax.annotation.Nullable;
public class RateLimitChallengeManager {
@@ -52,7 +54,7 @@ public class RateLimitChallengeManager {
this.rateLimitChallengeListeners = rateLimitChallengeListeners;
}
public void answerPushChallenge(final Account account, final String challenge) throws RateLimitExceededException {
public boolean answerPushChallenge(final Account account, final String challenge) throws RateLimitExceededException {
rateLimiters.getPushChallengeAttemptLimiter().validate(account.getUuid());
final boolean challengeSuccess = pushChallengeManager.answerChallenge(account, challenge);
@@ -61,13 +63,15 @@ public class RateLimitChallengeManager {
rateLimiters.getPushChallengeSuccessLimiter().validate(account.getUuid());
resetRateLimits(account, ChallengeType.PUSH);
}
return challengeSuccess;
}
public boolean answerCaptchaChallenge(final Account account,
final String captcha,
final String mostRecentProxyIp,
final String userAgent,
final Optional<Float> scoreThreshold) throws RateLimitExceededException, IOException {
@Nullable final String userAgent,
final Optional<Float> scoreThreshold)
throws RateLimitExceededException, IOException, InvalidCaptchaArgumentException {
rateLimiters.getCaptchaChallengeAttemptLimiter().validate(account.getUuid());
@@ -61,6 +61,8 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
DEVICE_CHECK_CHALLENGE("deviceCheckChallenge", new RateLimiterConfig(10, Duration.ofMinutes(1), false)),
SUBMIT_CALL_QUALITY_SURVEY("submitCallQualitySurvey", new RateLimiterConfig(100, Duration.ofMinutes(1), true)),
BATCH_IDENTITY_CHECK("batchIdentityCheck", new RateLimiterConfig(100, Duration.ofMinutes(1), true)),
ONE_TIME_DONATION("oneTimeDonation", new RateLimiterConfig(5, Duration.ofMinutes(1), true)),
ADD_SUBSCRIPTION_PAYMENT_METHOD("addSubscriptionPaymentMethod", new RateLimiterConfig(10, Duration.ofMinutes(1), true)),
;
private final String id;
@@ -22,6 +22,7 @@ import org.whispersystems.textsecuregcm.subscriptions.SubscriptionNotFoundExcept
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentRequiredException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorConflictException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptAlreadyRedeemedException;
public class SubscriptionExceptionMapper implements ExceptionMapper<SubscriptionException> {
@VisibleForTesting
@@ -56,11 +57,12 @@ public class SubscriptionExceptionMapper implements ExceptionMapper<Subscription
// Otherwise, we'll return a generic error message WebApplicationException, with a detailed error if one is provided
final Response.Status status = (switch (exception) {
case SubscriptionNotFoundException e -> Response.Status.NOT_FOUND;
case SubscriptionForbiddenException e -> Response.Status.FORBIDDEN;
case SubscriptionInvalidArgumentsException e -> Response.Status.BAD_REQUEST;
case SubscriptionProcessorConflictException e -> Response.Status.CONFLICT;
case SubscriptionPaymentRequiredException e -> Response.Status.PAYMENT_REQUIRED;
case SubscriptionNotFoundException _ -> Response.Status.NOT_FOUND;
case SubscriptionForbiddenException _ -> Response.Status.FORBIDDEN;
case SubscriptionInvalidArgumentsException _ -> Response.Status.BAD_REQUEST;
case SubscriptionProcessorConflictException _ -> Response.Status.CONFLICT;
case SubscriptionPaymentRequiredException _ -> Response.Status.PAYMENT_REQUIRED;
case SubscriptionReceiptAlreadyRedeemedException _ -> Response.Status.CONFLICT;
default -> Response.Status.INTERNAL_SERVER_ERROR;
});
@@ -138,6 +138,10 @@ public class CallQualitySurveyManager {
pubSubMessageBuilder.setCallTelemetry(submitCallQualitySurveyRequest.getCallTelemetry());
}
if (submitCallQualitySurveyRequest.hasCallIdHash()) {
pubSubMessageBuilder.setCallIdHash(submitCallQualitySurveyRequest.getCallIdHash());
}
GoogleApiUtil.toCompletableFuture(pubSubPublisher.publish(PubsubMessage.newBuilder()
.setData(pubSubMessageBuilder.build().toByteString())
.build()), pubSubCallbackExecutor)
@@ -8,53 +8,71 @@ package org.whispersystems.textsecuregcm.metrics;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import com.google.common.annotations.VisibleForTesting;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import io.micrometer.core.instrument.Timer;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.HexFormat;
import java.util.List;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.entities.OutgoingMessageEntity;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
import org.whispersystems.textsecuregcm.util.ua.UserAgent;
import org.whispersystems.textsecuregcm.websocket.WebSocketConnection;
public final class MessageMetrics {
private static final Logger logger = LoggerFactory.getLogger(MessageMetrics.class);
public static String GRPC_CHANNEL = "grpc";
public static String WEBSOCKET_CHANNEL = "websocket";
@VisibleForTesting
static final String MISMATCHED_ACCOUNT_ENVELOPE_UUID_COUNTER_NAME = name(MessageMetrics.class,
"mismatchedAccountEnvelopeUuid");
public static final String DELIVERY_LATENCY_TIMER_NAME = name(MessageMetrics.class, "deliveryLatency");
// Uses [WebSocketConnection] for backwards compatibility
private static final String SEND_MESSAGE_DURATION_TIMER_NAME = name(WebSocketConnection.class, "sendMessageDuration");
private static final String INITIAL_QUEUE_LENGTH_DISTRIBUTION_NAME = name(WebSocketConnection.class, "initialQueueLength");
private static final String INITIAL_QUEUE_DRAIN_TIMER_NAME = name(WebSocketConnection.class, "drainInitialQueue");
private static final String SLOW_QUEUE_DRAIN_COUNTER_NAME = name(WebSocketConnection.class, "slowQueueDrain");
private static final String DISPLACEMENT_COUNTER_NAME = name(WebSocketConnection.class, "displacement");
private static final Duration SLOW_DRAIN_THRESHOLD = Duration.ofSeconds(10);
private final MeterRegistry metricRegistry;
private final Counter sendMessageCounter;
private final Counter bytesSentCounter;
@VisibleForTesting
MessageMetrics(final MeterRegistry metricRegistry) {
this.metricRegistry = metricRegistry;
sendMessageCounter = metricRegistry.counter(name(WebSocketConnection.class, "sendMessage"));
bytesSentCounter = metricRegistry.counter(name(WebSocketConnection.class, "bytesSent"));
}
public MessageMetrics() {
this(Metrics.globalRegistry);
}
public void measureAccountOutgoingMessageUuidMismatches(final Account account,
final OutgoingMessageEntity outgoingMessage) {
measureAccountDestinationUuidMismatches(account, outgoingMessage.destinationUuid());
}
public void measureAccountEnvelopeUuidMismatches(final Account account,
final MessageProtos.Envelope envelope) {
if (envelope.hasDestinationServiceId()) {
try {
measureAccountDestinationUuidMismatches(account, ServiceIdentifier.valueOf(envelope.getDestinationServiceId()));
measureAccountDestinationUuidMismatches(account, ServiceIdentifier.fromByteString(envelope.getDestinationServiceId()));
} catch (final IllegalArgumentException ignored) {
logger.warn("Envelope had invalid destination UUID: {}", envelope.getDestinationServiceId());
logger.warn("Envelope had invalid destination service ID: {}",
HexFormat.of().formatHex(envelope.getDestinationServiceId().toByteArray()));
}
}
}
@@ -73,7 +91,7 @@ public final class MessageMetrics {
final boolean isPrimaryDevice,
final boolean isUrgent,
final boolean isEphemeral,
final String userAgent,
@Nullable final UserAgent userAgent,
final ClientReleaseManager clientReleaseManager) {
final List<Tag> tags = new ArrayList<>();
@@ -90,4 +108,40 @@ public final class MessageMetrics {
.register(metricRegistry)
.record(Duration.between(Instant.ofEpochMilli(serverTimestamp), Instant.now()));
}
public void measureMessageStreamDisplaced(
final String channel,
@Nullable final UserAgent userAgent,
final boolean connectedElsewhere) {
metricRegistry.counter(
DISPLACEMENT_COUNTER_NAME,
Tags.of(UserAgentTagUtil.getPlatformTag(userAgent),
Tag.of("connectedElsewhere", Boolean.toString(connectedElsewhere)),
Tag.of("channel", channel)))
.increment();
}
public void measureQueueDrain(
final String channel,
@Nullable final UserAgent userAgent,
final long messagesDrained,
final Timer.Sample drainStart) {
final Tags tags = Tags.of(UserAgentTagUtil.getPlatformTag(userAgent), Tag.of("channel", channel));
metricRegistry.summary(INITIAL_QUEUE_LENGTH_DISTRIBUTION_NAME, tags).record(messagesDrained);
final long drainDurationNanos = drainStart.stop(metricRegistry.timer(INITIAL_QUEUE_DRAIN_TIMER_NAME, tags));
if (Duration.ofNanos(drainDurationNanos).compareTo(SLOW_DRAIN_THRESHOLD) > 0) {
metricRegistry.counter(SLOW_QUEUE_DRAIN_COUNTER_NAME, tags).increment();
}
}
public void measureMessageSent(long messageByteLength) {
sendMessageCounter.increment();
bytesSentCounter.increment(messageByteLength);
}
public void measureSendMessageDuration(final String channel, @Nullable final UserAgent userAgent, final Timer.Sample sample) {
sample.stop(Timer.builder(SEND_MESSAGE_DURATION_TIMER_NAME)
.tags(Tags.of(UserAgentTagUtil.getPlatformTag(userAgent), Tag.of("channel", channel)))
.register(metricRegistry));
}
}
@@ -4,8 +4,8 @@
*/
package org.whispersystems.textsecuregcm.push;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import static org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import com.google.common.annotations.VisibleForTesting;
import io.dropwizard.util.DataSize;
@@ -24,7 +24,6 @@ import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import kotlin.Pair;
import org.apache.commons.lang3.StringUtils;
import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.controllers.MessageDeliveryNotAllowedException;
@@ -327,15 +326,15 @@ public class MessageSender {
final byte excludedDeviceId;
if (syncMessageSenderDeviceId.isPresent()) {
if (messagesByDeviceId.values().stream().anyMatch(message -> StringUtils.isBlank(message.getSourceServiceId()) ||
!destination.isIdentifiedBy(ServiceIdentifier.valueOf(message.getSourceServiceId())))) {
if (messagesByDeviceId.values().stream().anyMatch(message -> !message.hasSourceServiceId() ||
!destination.isIdentifiedBy(ServiceIdentifier.fromByteString(message.getSourceServiceId())))) {
throw new IllegalArgumentException("Sync message sender device ID specified, but one or more messages are not addressed to sender");
}
excludedDeviceId = syncMessageSenderDeviceId.get();
} else {
if (messagesByDeviceId.values().stream().anyMatch(message -> StringUtils.isNotBlank(message.getSourceServiceId()) &&
destination.isIdentifiedBy(ServiceIdentifier.valueOf(message.getSourceServiceId())))) {
if (messagesByDeviceId.values().stream().anyMatch(message -> message.hasSourceServiceId() &&
destination.isIdentifiedBy(ServiceIdentifier.fromByteString(message.getSourceServiceId())))) {
throw new IllegalArgumentException("Sync message sender device ID not specified, but one or more messages are addressed to sender");
}
@@ -87,26 +87,21 @@ public class PushNotificationManager {
.thenApply(maybeResponse -> maybeResponse.orElseThrow(() -> new AssertionError("Responses must be present for urgent notifications")));
}
public CompletableFuture<Void> trySendVerificationCodeRequestedNotifications(final Account destination, final Instant requestTimestamp) {
final List<CompletableFuture<?>> sendNotificationFutures = new ArrayList<>();
public CompletableFuture<SendPushNotificationResult> sendVerificationCodeRequestedNotifications(final Account destination, final Instant requestTimestamp)
throws NotPushRegisteredException {
for (final Device device : destination.getDevices()) {
try {
final Pair<String, PushNotification.TokenType> tokenAndType = getToken(device);
final Pair<String, PushNotification.TokenType> tokenAndType = getToken(destination.getPrimaryDevice());
sendNotificationFutures.add(sendNotification(new PushNotification(tokenAndType.first(),
tokenAndType.second(),
PushNotification.NotificationType.VERIFICATION_CODE_REQUESTED,
new VerificationCodeRequestData(requestTimestamp.toEpochMilli()),
destination,
device,
true,
VERIFICATION_CODE_TTL)));
} catch (final NotPushRegisteredException _) {
}
}
return CompletableFuture.allOf(sendNotificationFutures.toArray(CompletableFuture[]::new));
return sendNotification(new PushNotification(tokenAndType.first(),
tokenAndType.second(),
PushNotification.NotificationType.VERIFICATION_CODE_REQUESTED,
new VerificationCodeRequestData(requestTimestamp.toEpochMilli()),
destination,
destination.getPrimaryDevice(),
true,
VERIFICATION_CODE_TTL))
.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) {
@@ -44,9 +44,9 @@ public class ReceiptSender {
destinationAccount -> {
final Envelope message = Envelope.newBuilder()
.setServerTimestamp(System.currentTimeMillis())
.setSourceServiceId(sourceIdentifier.toServiceIdentifierString())
.setSourceServiceId(sourceIdentifier.toCompactByteString())
.setSourceDevice(sourceDeviceId)
.setDestinationServiceId(destinationIdentifier.toServiceIdentifierString())
.setDestinationServiceId(destinationIdentifier.toCompactByteString())
.setClientTimestamp(messageId)
.setType(Envelope.Type.SERVER_DELIVERY_RECEIPT)
.setUrgent(false)
@@ -192,7 +192,7 @@ public class RedisMessageAvailabilityManager extends RedisClusterPubSubAdapter<b
}
/**
* Removes the "presence" and event listener for the given device. Callers should call this method when the client's
* Removes a "presence" and event listener for the given device if it is still the active listener. Callers should call this method when the client's
* underlying network connection has closed.
*
* @param accountIdentifier the identifier of the account for the disconnected device
@@ -200,12 +200,12 @@ public class RedisMessageAvailabilityManager extends RedisClusterPubSubAdapter<b
*
* @return a future that completes when the presence and event listener have been removed
*/
public CompletionStage<Void> handleClientDisconnected(final UUID accountIdentifier, final byte deviceId) {
public CompletionStage<Void> handleClientDisconnected(final UUID accountIdentifier, final byte deviceId, final MessageAvailabilityListener listener) {
if (pubSubConnection == null) {
throw new IllegalStateException("WebSocket connection event manager not started");
}
final AtomicReference<CompletionStage<Void>> unsubscribeFuture = new AtomicReference<>();
final AtomicReference<CompletionStage<Void>> unsubscribeFuture = new AtomicReference<>(CompletableFuture.completedFuture(null));
// Note that we're relying on some specific implementation details of `ConcurrentHashMap#compute(...)`. In
// particular, the behavioral contract for `ConcurrentHashMap#compute(...)` says:
@@ -219,6 +219,11 @@ public class RedisMessageAvailabilityManager extends RedisClusterPubSubAdapter<b
// operation is asynchronous; we're not blocking on it in the scope of the `compute` operation.
listenersByAccountAndDeviceIdentifier.compute(new AccountAndDeviceIdentifier(accountIdentifier, deviceId),
(ignored, existingListener) -> {
if (listener != existingListener) {
// the listener was already replaced, ignore this event completely
return existingListener;
}
unsubscribeFuture.set(CompletableFuture.supplyAsync(() -> pubSubConnection.withPubSubConnection(connection ->
connection.async().sunsubscribe(getClientEventChannel(accountIdentifier, deviceId)))
.thenRun(Util.NOOP), asyncOperationQueueingExecutor)
@@ -10,7 +10,9 @@ import org.whispersystems.textsecuregcm.storage.Account;
public interface ChallengeConstraintChecker {
record ChallengeConstraints(boolean pushPermitted, Optional<Float> captchaScoreThreshold) {}
record ChallengeConstraints(boolean pushPermitted, Optional<Float> captchaScoreThreshold) {
static final ChallengeConstraints ALL_PERMITTED = new ChallengeConstraints(true, Optional.empty());
}
/**
* Retrieve constraints for captcha and push challenges
@@ -18,9 +20,29 @@ public interface ChallengeConstraintChecker {
* @param authenticatedAccount The authenticated account attempting to request or solve a challenge
* @return ChallengeConstraints indicating what constraints should be applied to challenges
*/
ChallengeConstraints challengeConstraints(ContainerRequestContext requestContext, Account authenticatedAccount);
ChallengeConstraints challengeConstraintsHttp(ContainerRequestContext requestContext, Account authenticatedAccount);
/**
* Retrieve constraints for captcha and push challenges
*
* @param authenticatedAccount The authenticated account attempting to request or solve a challenge
* @return ChallengeConstraints indicating what constraints should be applied to challenges
*/
ChallengeConstraints challengeConstraintsGrpc(Account authenticatedAccount);
static ChallengeConstraintChecker noop() {
return (account, ctx) -> new ChallengeConstraints(true, Optional.empty());
return new ChallengeConstraintChecker() {
@Override
public ChallengeConstraints challengeConstraintsHttp(final ContainerRequestContext requestContext,
final Account authenticatedAccount) {
return ChallengeConstraints.ALL_PERMITTED;
}
@Override
public ChallengeConstraints challengeConstraintsGrpc(final Account authenticatedAccount) {
return ChallengeConstraints.ALL_PERMITTED;
}
};
}
}
@@ -17,7 +17,6 @@ import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tags;
import java.io.IOException;
@@ -93,7 +92,6 @@ public class Account {
private IdentityKey phoneNumberIdentityKey;
@JsonProperty("cpv")
@JsonSerialize(using = ProfileVersionAdapter.Serializing.class)
@JsonDeserialize(using = ProfileVersionAdapter.Deserializing.class)
private byte[] currentProfileVersion;
@@ -132,6 +130,10 @@ public class Account {
@Nullable
private byte[] zkCredentialKey;
@JsonProperty("zckr")
@Nullable
private Long zkCredentialKeyRotationId;
@JsonProperty
private int version;
@@ -567,6 +569,15 @@ public class Account {
this.zkCredentialKey = zkCredentialKey;
}
@Nullable
public Long getZkCredentialKeyRotationId() {
return zkCredentialKeyRotationId;
}
public void setZkCredentialKeyRotationId(@Nullable final Long zkCredentialKeyRotationId) {
this.zkCredentialKeyRotationId = zkCredentialKeyRotationId;
}
public void markStale() {
stale = true;
}
@@ -595,13 +606,5 @@ public class Account {
}
}
}
// after deploying this once we can get rid of it in favor of the default base64
private static class Serializing extends JsonSerializer<byte[]> {
@Override
public void serialize(byte[] bytes, JsonGenerator jsonGenerator, SerializerProvider serializaterProvider) throws IOException {
jsonGenerator.writeString(HexFormat.of().formatHex(bytes));
}
}
}
}
@@ -413,8 +413,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
final boolean rrpCreated = accountAttributes.recoveryPassword().map(registrationRecoveryPassword ->
registrationRecoveryPasswordsManager
.store(account.getIdentifier(IdentityType.PNI), registrationRecoveryPassword)
.join())
.store(account.getIdentifier(IdentityType.PNI), registrationRecoveryPassword))
.orElse(false);
changeNumberWaitingPeriodManager.handleAccountCreated(account.getUuid(), clock.instant());
@@ -1149,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) {
@@ -1214,10 +1213,11 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
keysManager.deleteSingleUsePreKeys(account.getUuid()),
keysManager.deleteSingleUsePreKeys(account.getPhoneNumberIdentifier()),
messagesManager.clear(account.getUuid()),
profilesManager.deleteAll(account.getUuid(), true),
registrationRecoveryPasswordsManager.remove(account.getIdentifier(IdentityType.PNI)))
profilesManager.deleteAll(account.getUuid(), true))
.join();
registrationRecoveryPasswordsManager.remove(account.getIdentifier(IdentityType.PNI));
accounts.delete(account.getUuid(), additionalWriteItems);
redisDelete(account);
@@ -40,6 +40,7 @@ import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.push.MessageSender;
import org.whispersystems.textsecuregcm.push.MessageTooLargeException;
import org.whispersystems.textsecuregcm.util.Pair;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
public class ChangeNumberManager {
@@ -159,10 +160,9 @@ public class ChangeNumberManager {
try {
// Now that we've actually updated the account, populate the "updated PNI" field on all envelopes
final String updatedPniString = updatedAccount.getIdentifier(IdentityType.PNI).toString();
messagesByDeviceId.replaceAll((_, envelope) ->
envelope.toBuilder().setUpdatedPni(updatedPniString).build());
envelope.toBuilder().setUpdatedPni(UUIDUtil.toByteString(updatedAccount.getIdentifier(IdentityType.PNI)))
.build());
messageSender.sendMessages(updatedAccount,
serviceIdentifier,
@@ -16,7 +16,8 @@ public enum DeviceCapability {
TRANSFER("transfer", AccountCapabilityMode.PRIMARY_DEVICE, false, false, false),
ATTACHMENT_BACKFILL("attachmentBackfill", AccountCapabilityMode.PRIMARY_DEVICE, false, true, false),
SPARSE_POST_QUANTUM_RATCHET("spqr", AccountCapabilityMode.ALL_DEVICES, true, true, true),
PROFILES_V2("profiles_v2", AccountCapabilityMode.ALL_DEVICES, false, true, false);
PROFILES_V2("profiles_v2", AccountCapabilityMode.ALL_DEVICES, false, true, false),
USERNAME_CHANGE_SYNC_MESSAGE("usernameChangeSyncMessage", AccountCapabilityMode.ALL_DEVICES, true, true, false);
public enum AccountCapabilityMode {
/**
@@ -1,135 +0,0 @@
/*
* Copyright 2025 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage;
import java.util.UUID;
import com.google.common.annotations.VisibleForTesting;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.grpc.ServiceIdentifierUtil;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
/**
* Provides utility methods for "compressing" and "expanding" envelopes. Historically UUID-like fields in envelopes have
* been represented as strings (e.g. "c15f1dfb-ae2c-43a8-9bb9-baba97ac416c"), but <em>could</em> be represented as more
* compact byte arrays instead. Existing clients generally expect string representations (though that should change in
* the near future), but we can use the more compressed forms at rest for more efficient storage and transfer.
*/
public class EnvelopeUtil {
@VisibleForTesting
static final String INCLUDE_BINARY_SERVICE_ID_EXPERIMENT_NAME = "envelopeIncludeBinaryServiceIdentifier";
/**
* Converts all "compressible" UUID-like fields in the given envelope to more compact binary representations.
*
* @param envelope the envelope to compress
*
* @return an envelope with string-based UUID-like fields compressed to binary representations
*/
public static MessageProtos.Envelope compress(final MessageProtos.Envelope envelope) {
final MessageProtos.Envelope.Builder builder = envelope.toBuilder();
if (builder.hasSourceServiceId()) {
final ServiceIdentifier sourceServiceId = ServiceIdentifier.valueOf(builder.getSourceServiceId());
builder.setSourceServiceIdBinary(ServiceIdentifierUtil.toCompactByteString(sourceServiceId));
builder.clearSourceServiceId();
}
if (builder.hasDestinationServiceId()) {
final ServiceIdentifier destinationServiceId = ServiceIdentifier.valueOf(builder.getDestinationServiceId());
builder.setDestinationServiceIdBinary(ServiceIdentifierUtil.toCompactByteString(destinationServiceId));
builder.clearDestinationServiceId();
}
if (builder.hasServerGuid()) {
final UUID serverGuid = UUID.fromString(builder.getServerGuid());
builder.setServerGuidBinary(UUIDUtil.toByteString(serverGuid));
builder.clearServerGuid();
}
if (builder.hasUpdatedPni()) {
final UUID updatedPni = UUID.fromString(builder.getUpdatedPni());
builder.setUpdatedPniBinary(UUIDUtil.toByteString(updatedPni));
builder.clearUpdatedPni();
}
return builder.build();
}
/**
* "Expands" all binary representations of UUID-like fields to string representations to meet current client
* expectations.
*
* @param envelope the envelope to expand
*
* @return an envelope with binary representations of UUID-like fields expanded to string representations
*/
public static MessageProtos.Envelope expand(final MessageProtos.Envelope envelope,
final ExperimentEnrollmentManager experimentEnrollmentManager) {
final boolean includeBinaryServiceIdentifiers;
if (envelope.hasDestinationServiceIdBinary() || envelope.hasDestinationServiceId()) {
final ServiceIdentifier destinationIdentifier = envelope.hasDestinationServiceIdBinary()
? ServiceIdentifier.fromBytes(envelope.getDestinationServiceIdBinary().toByteArray())
: ServiceIdentifier.valueOf(envelope.getDestinationServiceId());
includeBinaryServiceIdentifiers =
experimentEnrollmentManager.isEnrolled(destinationIdentifier.uuid(), INCLUDE_BINARY_SERVICE_ID_EXPERIMENT_NAME);
} else {
includeBinaryServiceIdentifiers = false;
}
final MessageProtos.Envelope.Builder builder = envelope.toBuilder();
if (builder.hasSourceServiceIdBinary()) {
final ServiceIdentifier sourceServiceId =
ServiceIdentifierUtil.fromByteString(builder.getSourceServiceIdBinary());
builder.setSourceServiceId(sourceServiceId.toServiceIdentifierString());
if (!includeBinaryServiceIdentifiers) {
builder.clearSourceServiceIdBinary();
}
}
if (builder.hasDestinationServiceIdBinary()) {
final ServiceIdentifier destinationServiceId =
ServiceIdentifierUtil.fromByteString(builder.getDestinationServiceIdBinary());
builder.setDestinationServiceId(destinationServiceId.toServiceIdentifierString());
if (!includeBinaryServiceIdentifiers) {
builder.clearDestinationServiceIdBinary();
}
}
if (builder.hasServerGuidBinary()) {
final UUID serverGuid = UUIDUtil.fromByteString(builder.getServerGuidBinary());
builder.setServerGuid(serverGuid.toString());
if (!includeBinaryServiceIdentifiers) {
builder.clearServerGuidBinary();
}
}
if (builder.hasUpdatedPniBinary()) {
final UUID updatedPni = UUIDUtil.fromByteString(builder.getUpdatedPniBinary());
// Note that expanded envelopes include BOTH forms of the `updatedPni` field
builder.setUpdatedPni(updatedPni.toString());
}
return builder.build();
}
}
@@ -10,9 +10,6 @@ import static org.whispersystems.textsecuregcm.util.AttributeValues.n;
import static org.whispersystems.textsecuregcm.util.AttributeValues.s;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Throwables;
import jakarta.ws.rs.ClientErrorException;
import jakarta.ws.rs.core.Response.Status;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
@@ -22,8 +19,6 @@ import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.function.Consumer;
import javax.annotation.Nonnull;
import javax.crypto.Mac;
@@ -31,10 +26,11 @@ import javax.crypto.spec.SecretKeySpec;
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialRequest;
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.ConditionalCheckFailedException;
import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest;
import software.amazon.awssdk.services.dynamodb.model.DeleteItemResponse;
import software.amazon.awssdk.services.dynamodb.model.ReturnValue;
import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;
@@ -46,42 +42,40 @@ public class IssuedReceiptsManager {
private final String table;
private final Duration expiration;
private final DynamoDbAsyncClient dynamoDbAsyncClient;
private final DynamoDbClient dynamoDbClient;
private final byte[] receiptTagGenerator;
private final EnumMap<PaymentProvider, Integer> maxIssuedReceiptsPerPaymentId;
public IssuedReceiptsManager(
@Nonnull String table,
@Nonnull Duration expiration,
@Nonnull DynamoDbAsyncClient dynamoDbAsyncClient,
@Nonnull byte[] receiptTagGenerator,
@Nonnull EnumMap<PaymentProvider, Integer> maxIssuedReceiptsPerPaymentId) {
@Nonnull final String table,
@Nonnull final Duration expiration,
@Nonnull final DynamoDbClient dynamoDbClient,
@Nonnull final byte[] receiptTagGenerator,
@Nonnull final EnumMap<PaymentProvider, Integer> maxIssuedReceiptsPerPaymentId) {
this.table = Objects.requireNonNull(table);
this.expiration = Objects.requireNonNull(expiration);
this.dynamoDbAsyncClient = Objects.requireNonNull(dynamoDbAsyncClient);
this.dynamoDbClient = Objects.requireNonNull(dynamoDbClient);
this.receiptTagGenerator = Objects.requireNonNull(receiptTagGenerator);
this.maxIssuedReceiptsPerPaymentId = Objects.requireNonNull(maxIssuedReceiptsPerPaymentId);
}
/**
* Returns a future that completes normally if either this processor item was never issued a receipt credential
* previously OR if it was issued a receipt credential previously for the exact same receipt credential request
* enabling clients to retry in case they missed the original response.
* <p>
* If this item has already been used to issue another receipt, throws a 409 conflict web application exception.
* <p>
* For {@link PaymentProvider#STRIPE}, item is expected to refer to an invoice line item (subscriptions) or a
* payment intent (one-time).
*/
public CompletableFuture<Void> recordIssuance(
String processorItemId,
PaymentProvider processor,
ReceiptCredentialRequest request,
Instant now) {
/// Returns normally if either this processor item was never issued a receipt credential
/// previously OR if it was issued a receipt credential previously for the exact same receipt credential request
/// enabling clients to retry in case they missed the original response.
///
/// If this item has already been used to issue another receipt, throws [WriteConflictException].
///
/// For [PaymentProvider#STRIPE], item is expected to refer to an invoice line item (subscriptions) or a
/// payment intent (one-time).
public void recordIssuance(
final String processorItemId,
final PaymentProvider processor,
final ReceiptCredentialRequest request,
final Instant now) throws WriteConflictException {
final AttributeValue key = dynamoDbKey(processor, processorItemId);
final byte[] tag = generateIssuedReceiptTag(request);
UpdateItemRequest updateItemRequest = UpdateItemRequest.builder()
final UpdateItemRequest updateItemRequest = UpdateItemRequest.builder()
.tableName(table)
.key(Map.of(KEY_PROCESSOR_ITEM_ID, key))
.conditionExpression("attribute_not_exists(#key) OR contains(#tags, :tag) OR size(#tags) < :maxTags")
@@ -97,39 +91,31 @@ public class IssuedReceiptsManager {
":exp", n(now.plus(expiration).getEpochSecond()),
":maxTags", n(maxIssuedReceiptsPerPaymentId.get(processor))))
.build();
return dynamoDbAsyncClient.updateItem(updateItemRequest).handle((updateItemResponse, throwable) -> {
if (throwable != null) {
Throwable rootCause = Throwables.getRootCause(throwable);
if (rootCause instanceof ConditionalCheckFailedException) {
throw new ClientErrorException(Status.CONFLICT, rootCause);
}
Throwables.throwIfUnchecked(throwable);
throw new CompletionException(throwable);
}
return null;
});
try {
dynamoDbClient.updateItem(updateItemRequest);
} catch (final ConditionalCheckFailedException _) {
throw new WriteConflictException();
}
}
/**
* Clear the recorded issuances for a particular item
*
* @param processorItemId The itemId within the processor to clear
* @param processor The processor
* @return a future that yields true if the item was deleted, false if the item already did not exist
*/
public CompletableFuture<Boolean> clearIssuance(String processorItemId, PaymentProvider processor) {
/// Clear the recorded issuances for a particular item
///
/// @param processorItemId The itemId within the processor to clear
/// @param processor The processor
/// @return true if the item was deleted, false if the item did not exist
public boolean clearIssuance(final String processorItemId, final PaymentProvider processor) {
final AttributeValue key = dynamoDbKey(processor, processorItemId);
final DeleteItemRequest deleteItemRequest = DeleteItemRequest.builder()
.tableName(table)
.key(Map.of(KEY_PROCESSOR_ITEM_ID, key))
.returnValues(ReturnValue.ALL_OLD)
.build();
return dynamoDbAsyncClient.deleteItem(deleteItemRequest)
.thenApply(item -> item.hasAttributes() && !item.attributes().isEmpty());
final DeleteItemResponse item = dynamoDbClient.deleteItem(deleteItemRequest);
return item.hasAttributes() && !item.attributes().isEmpty();
}
@VisibleForTesting
static AttributeValue dynamoDbKey(final PaymentProvider processor, String processorItemId) {
static AttributeValue dynamoDbKey(final PaymentProvider processor, final String processorItemId) {
if (processor == PaymentProvider.STRIPE) {
// As the first processor, Stripe’s IDs were not prefixed. Its item IDs have documented prefixes (`il_`, `pi_`)
// that will not collide with `SubscriptionProcessor` names
@@ -141,18 +127,18 @@ public class IssuedReceiptsManager {
@VisibleForTesting
byte[] generateIssuedReceiptTag(ReceiptCredentialRequest request) {
byte[] generateIssuedReceiptTag(final ReceiptCredentialRequest request) {
return generateHmac("issuedReceiptTag", mac -> mac.update(request.serialize()));
}
private byte[] generateHmac(String type, Consumer<Mac> byteConsumer) {
private byte[] generateHmac(final String type, final Consumer<Mac> byteConsumer) {
try {
Mac mac = Mac.getInstance("HmacSHA256");
final Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(receiptTagGenerator, "HmacSHA256"));
mac.update(type.getBytes(StandardCharsets.UTF_8));
byteConsumer.accept(mac);
return mac.doFinal();
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
} catch (final NoSuchAlgorithmException | InvalidKeyException e) {
throw new AssertionError(e);
}
}
@@ -32,6 +32,7 @@ import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfigurati
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.metrics.DevicePlatformUtil;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
import org.whispersystems.textsecuregcm.util.Util;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@@ -349,7 +350,7 @@ public class MessagePersister implements Managed {
cachedMessageBytes.set(estimatedPersistedQueueSize);
targetDeleteBytes.set(Math.round(estimatedPersistedQueueSize * extraRoomRatio));
return Flux.from(messagesManager.getMessagesForDeviceReactive(aci, device, false))
return Flux.from(messagesManager.getMessagesForDevice(aci, device))
.concatMap(envelope -> {
if (bytesDeleted.getAndAdd(envelope.getSerializedSize()) >= targetDeleteBytes.get()) {
return Mono.just(Optional.<MessageProtos.Envelope>empty());
@@ -366,7 +367,7 @@ public class MessagePersister implements Managed {
TRIMMED_MESSAGE_BYTES_COUNTER.increment(envelope.getSerializedSize());
return Mono
.fromCompletionStage(() -> messagesManager
.delete(aci, device, UUID.fromString(envelope.getServerGuid()), envelope.getServerTimestamp()))
.delete(aci, device, UUIDUtil.fromByteString(envelope.getServerGuid()), envelope.getServerTimestamp()))
.retryWhen(retryBackoffSpec)
.map(Optional::isPresent);
})
@@ -5,6 +5,7 @@
package org.whispersystems.textsecuregcm.storage;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Flow;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
@@ -22,8 +23,9 @@ public interface MessageStream {
/// Acknowledges receipt of the given message. Implementations may delete the message immediately or defer deletion for
/// inclusion in a more efficient batch deletion.
///
/// @param message the message to acknowledge
/// @param messageGuid the identifier of the message to acknowledge
/// @param serverTimestamp the server-issued timestamp of the message to acknowledge
///
/// @return a future that completes when the message stream has processed the acknowledgement
CompletableFuture<Void> acknowledgeMessage(MessageProtos.Envelope message);
CompletableFuture<Void> acknowledgeMessage(UUID messageGuid, long serverTimestamp);
}
@@ -48,12 +48,12 @@ import org.signal.libsignal.protocol.ServiceId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
import org.whispersystems.textsecuregcm.util.Pair;
import org.whispersystems.textsecuregcm.util.ResilienceUtil;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
import reactor.core.observability.micrometer.Micrometer;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@@ -121,7 +121,6 @@ public class MessagesCache {
private final ExecutorService messageDeletionExecutorService;
// messageDeletionExecutorService wrapped into a reactor Scheduler
private final Scheduler messageDeletionScheduler;
private final ExperimentEnrollmentManager experimentEnrollmentManager;
private final MessagesCacheInsertScript insertScript;
private final MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript insertMrmScript;
@@ -175,16 +174,13 @@ public class MessagesCache {
final Scheduler messageDeliveryScheduler,
final ExecutorService messageDeletionExecutorService,
final ScheduledExecutorService retryExecutor,
final Clock clock,
final ExperimentEnrollmentManager experimentEnrollmentManager)
throws IOException {
final Clock clock) throws IOException {
this(
redisCluster,
messageDeliveryScheduler,
messageDeletionExecutorService,
clock,
experimentEnrollmentManager,
new MessagesCacheInsertScript(redisCluster, retryExecutor),
new MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript(redisCluster, retryExecutor),
new MessagesCacheGetItemsScript(redisCluster),
@@ -200,7 +196,6 @@ public class MessagesCache {
MessagesCache(final FaultTolerantRedisClusterClient redisCluster,
final Scheduler messageDeliveryScheduler,
final ExecutorService messageDeletionExecutorService, final Clock clock,
final ExperimentEnrollmentManager experimentEnrollmentManager,
final MessagesCacheInsertScript insertScript,
final MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript insertMrmScript,
final MessagesCacheGetItemsScript getItemsScript,
@@ -216,7 +211,6 @@ public class MessagesCache {
this.messageDeliveryScheduler = messageDeliveryScheduler;
this.messageDeletionExecutorService = messageDeletionExecutorService;
this.messageDeletionScheduler = Schedulers.fromExecutorService(messageDeletionExecutorService, "messageDeletion");
this.experimentEnrollmentManager = experimentEnrollmentManager;
this.insertScript = insertScript;
this.insertMrmScript = insertMrmScript;
@@ -233,7 +227,7 @@ public class MessagesCache {
final byte destinationDeviceId,
final MessageProtos.Envelope message) {
final MessageProtos.Envelope messageWithGuid = message.toBuilder().setServerGuid(messageGuid.toString()).build();
final MessageProtos.Envelope messageWithGuid = message.toBuilder().setServerGuid(UUIDUtil.toByteString(messageGuid)).build();
final Timer.Sample sample = Timer.start();
return insertScript.executeAsync(destinationAccountIdentifier, destinationDeviceId, messageWithGuid)
@@ -278,7 +272,7 @@ public class MessagesCache {
removedMessages.add(RemovedMessage.fromEnvelope(envelope));
if (envelope.hasSharedMrmKey()) {
serviceIdentifierToMrmKeys.computeIfAbsent(
ServiceIdentifier.valueOf(envelope.getDestinationServiceId()), _ -> new ArrayList<>())
ServiceIdentifier.fromByteString(envelope.getDestinationServiceId()), _ -> new ArrayList<>())
.add(envelope.getSharedMrmKey().toByteArray());
}
} catch (final InvalidProtocolBufferException e) {
@@ -398,7 +392,7 @@ public class MessagesCache {
private void discardStaleMessages(final UUID destinationUuid, final byte destinationDevice,
Flux<MessageProtos.Envelope> staleMessages, final Counter counter, final String context) {
staleMessages
.map(e -> UUID.fromString(e.getServerGuid()))
.map(e -> UUIDUtil.fromByteString(e.getServerGuid()))
.buffer(PAGE_SIZE)
.subscribeOn(messageDeletionScheduler)
.subscribe(messageGuids ->
@@ -479,7 +473,7 @@ public class MessagesCache {
final byte[] key = mrmMessage.getSharedMrmKey().toByteArray();
final byte[] sharedMrmViewKey = MessagesCache.getSharedMrmViewKey(
// the message might be addressed to the account's PNI, so use the service ID from the envelope
ServiceIdentifier.valueOf(mrmMessage.getDestinationServiceId()), destinationDevice);
ServiceIdentifier.fromByteString(mrmMessage.getDestinationServiceId()), destinationDevice);
return Mono.from(redisCluster.withBinaryCluster(
conn -> conn.reactive().hmget(key, "data".getBytes(StandardCharsets.UTF_8), sharedMrmViewKey)
@@ -670,10 +664,10 @@ public class MessagesCache {
try {
final MessageProtos.Envelope message = parseEnvelope(serialized);
processedMessages.add(message.getServerGuid());
processedMessages.add(UUIDUtil.fromByteString(message.getServerGuid()).toString());
if (message.hasSharedMrmKey()) {
serviceIdentifierToMrmKeys.computeIfAbsent(ServiceIdentifier.valueOf(message.getDestinationServiceId()),
serviceIdentifierToMrmKeys.computeIfAbsent(ServiceIdentifier.fromByteString(message.getDestinationServiceId()),
_ -> new ArrayList<>())
.add(message.getSharedMrmKey().toByteArray());
}
@@ -782,6 +776,6 @@ public class MessagesCache {
private MessageProtos.Envelope parseEnvelope(final byte[] envelopeBytes)
throws InvalidProtocolBufferException {
return EnvelopeUtil.expand(MessageProtos.Envelope.parseFrom(envelopeBytes), experimentEnrollmentManager);
return MessageProtos.Envelope.parseFrom(envelopeBytes);
}
}
@@ -21,6 +21,7 @@ import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager;
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
import org.whispersystems.textsecuregcm.util.ResilienceUtil;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
/**
* Inserts an envelope into the message queue for a destination device and publishes a "new message available" event.
@@ -62,8 +63,8 @@ class MessagesCacheInsertScript {
);
final List<byte[]> args = new ArrayList<>(Arrays.asList(
EnvelopeUtil.compress(envelope).toByteArray(), // message
envelope.getServerGuid().getBytes(StandardCharsets.UTF_8), // guid
envelope.toByteArray(), // message
UUIDUtil.fromByteString(envelope.getServerGuid()).toString().getBytes(StandardCharsets.UTF_8), // guid
NEW_MESSAGE_EVENT_BYTES // eventPayload
));
@@ -27,8 +27,8 @@ import org.reactivestreams.Publisher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.util.AttributeValues;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
import reactor.core.publisher.Flux;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
@@ -63,13 +63,11 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
private final String tableName;
private final Duration timeToLive;
private final ExecutorService messageDeletionExecutor;
private final ExperimentEnrollmentManager experimentEnrollmentManager;
private static final Logger logger = LoggerFactory.getLogger(MessagesDynamoDb.class);
public MessagesDynamoDb(DynamoDbClient dynamoDb, DynamoDbAsyncClient dynamoDbAsyncClient, String tableName,
Duration timeToLive, ExecutorService messageDeletionExecutor,
final ExperimentEnrollmentManager experimentEnrollmentManager) {
Duration timeToLive, ExecutorService messageDeletionExecutor) {
super(dynamoDb);
this.dbAsyncClient = dynamoDbAsyncClient;
@@ -77,7 +75,6 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
this.timeToLive = timeToLive;
this.messageDeletionExecutor = messageDeletionExecutor;
this.experimentEnrollmentManager = experimentEnrollmentManager;
}
public void store(final List<MessageProtos.Envelope> messages, final UUID destinationAccountUuid,
@@ -94,14 +91,14 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
final AttributeValue partitionKey = convertPartitionKey(destinationAccountUuid, destinationDevice);
List<WriteRequest> writeItems = new ArrayList<>();
for (MessageProtos.Envelope message : messages) {
final UUID messageUuid = UUID.fromString(message.getServerGuid());
final UUID messageUuid = UUIDUtil.fromByteString(message.getServerGuid());
final ImmutableMap.Builder<String, AttributeValue> item = ImmutableMap.<String, AttributeValue>builder()
.put(KEY_PARTITION, partitionKey)
.put(KEY_SORT, convertSortKey(message.getServerTimestamp(), messageUuid))
.put(LOCAL_INDEX_MESSAGE_UUID_KEY_SORT, convertLocalIndexMessageUuidSortKey(messageUuid))
.put(KEY_TTL, AttributeValues.fromLong(getTtlForMessage(message)))
.put(KEY_ENVELOPE_BYTES, AttributeValue.builder().b(SdkBytes.fromByteArray(EnvelopeUtil.compress(message).toByteArray())).build());
.put(KEY_ENVELOPE_BYTES, AttributeValue.builder().b(SdkBytes.fromByteArray(message.toByteArray())).build());
writeItems.add(WriteRequest.builder().putRequest(PutRequest.builder()
.item(item.build())
@@ -147,7 +144,7 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
return dbAsyncClient.queryPaginator(queryRequest).items()
.map(message -> {
try {
return convertItemToEnvelope(message, experimentEnrollmentManager);
return convertItemToEnvelope(message);
} catch (final InvalidProtocolBufferException e) {
logger.error("Failed to parse envelope", e);
return null;
@@ -167,7 +164,7 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
.thenApplyAsync(deleteItemResponse -> {
if (deleteItemResponse.attributes() != null && deleteItemResponse.attributes().containsKey(KEY_PARTITION)) {
try {
return Optional.of(convertItemToEnvelope(deleteItemResponse.attributes(), experimentEnrollmentManager));
return Optional.of(convertItemToEnvelope(deleteItemResponse.attributes()));
} catch (final InvalidProtocolBufferException e) {
logger.error("Failed to parse envelope", e);
}
@@ -178,11 +175,10 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
}
@VisibleForTesting
static MessageProtos.Envelope convertItemToEnvelope(final Map<String, AttributeValue> item,
final ExperimentEnrollmentManager experimentEnrollmentManager) throws InvalidProtocolBufferException {
static MessageProtos.Envelope convertItemToEnvelope(final Map<String, AttributeValue> item)
throws InvalidProtocolBufferException {
return EnvelopeUtil.expand(MessageProtos.Envelope.parseFrom(item.get(KEY_ENVELOPE_BYTES).b().asByteArray()),
experimentEnrollmentManager);
return MessageProtos.Envelope.parseFrom(item.get(KEY_ENVELOPE_BYTES).b().asByteArray());
}
private long getTtlForMessage(MessageProtos.Envelope message) {
@@ -23,7 +23,6 @@ import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import javax.annotation.Nullable;
import org.reactivestreams.Publisher;
import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage;
import org.slf4j.Logger;
@@ -33,14 +32,13 @@ import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager;
import org.whispersystems.textsecuregcm.util.Pair;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
import reactor.core.observability.micrometer.Micrometer;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
public class MessagesManager {
private static final int RESULT_SET_CHUNK_SIZE = 100;
final String GET_MESSAGES_FOR_DEVICE_FLUX_NAME = name(MessagesManager.class, "getMessagesForDevice");
private static final Logger logger = LoggerFactory.getLogger(MessagesManager.class);
@@ -102,10 +100,14 @@ public class MessagesManager {
return messagesCache.insert(messageGuid, accountIdentifier, deviceId, message)
.thenAccept(present -> {
if (message.hasSourceServiceId() && !accountIdentifier.toString()
.equals(message.getSourceServiceId())) {
// Note that this is an asynchronous, best-effort, fire-and-forget operation
reportMessageManager.store(message.getSourceServiceId(), messageGuid);
if (message.hasSourceServiceId()) {
final ServiceIdentifier sourceServiceIdentifier =
ServiceIdentifier.fromByteString(message.getSourceServiceId());
if (!accountIdentifier.equals(sourceServiceIdentifier.uuid())) {
// Note that this is an asynchronous, best-effort, fire-and-forget operation
reportMessageManager.store(sourceServiceIdentifier.toServiceIdentifierString(), messageGuid);
}
}
devicePresenceById.put(deviceId, present);
@@ -170,8 +172,8 @@ public class MessagesManager {
return insertAsync(resolvedRecipients.get(recipient).getIdentifier(IdentityType.ACI),
IntStream.range(0, devices.length).mapToObj(i -> devices[i])
.collect(Collectors.toMap(deviceId -> deviceId, deviceId -> prototypeMessage.toBuilder()
.setDestinationServiceId(serviceIdentifier.toServiceIdentifierString())
.collect(Collectors.toMap(deviceId -> deviceId, _ -> prototypeMessage.toBuilder()
.setDestinationServiceId(serviceIdentifier.toCompactByteString())
.build())))
.thenAccept(clientPresenceByDeviceId ->
clientPresenceByAccountAndDevice.put(resolvedRecipients.get(recipient),
@@ -212,34 +214,14 @@ public class MessagesManager {
return messagesDynamoDb.mayHaveUrgentMessages(destinationUuid, destinationDevice);
}
public Mono<Pair<List<Envelope>, Boolean>> getMessagesForDevice(UUID destinationUuid, Device destinationDevice,
boolean cachedMessagesOnly) {
return Flux.from(
getMessagesForDevice(destinationUuid, destinationDevice, RESULT_SET_CHUNK_SIZE, cachedMessagesOnly))
.take(RESULT_SET_CHUNK_SIZE)
.collectList()
.map(envelopes -> new Pair<>(envelopes, envelopes.size() >= RESULT_SET_CHUNK_SIZE));
}
public Publisher<Envelope> getMessagesForDeviceReactive(UUID destinationUuid, Device destinationDevice,
final boolean cachedMessagesOnly) {
return getMessagesForDevice(destinationUuid, destinationDevice, null, cachedMessagesOnly);
}
public MessageStream getMessages(final UUID destinationUuid, final Device destinationDevice) {
return new RedisDynamoDbMessageStream(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, destinationUuid, destinationDevice);
}
private Publisher<Envelope> getMessagesForDevice(UUID destinationUuid, Device destinationDevice,
@Nullable Integer limit, final boolean cachedMessagesOnly) {
final Publisher<Envelope> dynamoPublisher =
cachedMessagesOnly ? Flux.empty() : messagesDynamoDb.load(destinationUuid, destinationDevice, limit);
final Publisher<Envelope> cachePublisher = messagesCache.get(destinationUuid, destinationDevice.getId());
return Flux.concat(dynamoPublisher, cachePublisher)
Publisher<Envelope> getMessagesForDevice(final UUID destinationUuid, final Device destinationDevice) {
return Flux.concat(
messagesDynamoDb.load(destinationUuid, destinationDevice, null),
messagesCache.get(destinationUuid, destinationDevice.getId()))
.name(GET_MESSAGES_FOR_DEVICE_FLUX_NAME)
.tap(Micrometer.metrics(Metrics.globalRegistry));
}
@@ -275,7 +257,7 @@ public class MessagesManager {
messagesDynamoDb.store(messages, destinationUuid, destinationDevice);
final List<UUID> messageGuids = messages.stream().map(message -> UUID.fromString(message.getServerGuid()))
final List<UUID> messageGuids = messages.stream().map(message -> UUIDUtil.fromByteString(message.getServerGuid()))
.collect(Collectors.toList());
int messagesRemovedFromCache = 0;
try {
@@ -12,11 +12,11 @@ import java.time.Duration;
import java.time.Instant;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import javax.annotation.Nonnull;
import org.whispersystems.textsecuregcm.util.AttributeValues;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
import software.amazon.awssdk.services.dynamodb.model.GetItemResponse;
import software.amazon.awssdk.services.dynamodb.model.PutItemRequest;
public class OneTimeDonationsManager {
@@ -27,18 +27,18 @@ public class OneTimeDonationsManager {
private static final String ONETIME_DONATION_NOT_FOUND_COUNTER_NAME = name(OneTimeDonationsManager.class, "onetimeDonationNotFound");
private final String table;
private final Duration ttl;
private final DynamoDbAsyncClient dynamoDbAsyncClient;
private final DynamoDbClient dynamoDbClient;
public OneTimeDonationsManager(
@Nonnull String table,
@Nonnull Duration ttl,
@Nonnull DynamoDbAsyncClient dynamoDbAsyncClient) {
@Nonnull final String table,
@Nonnull final Duration ttl,
@Nonnull final DynamoDbClient dynamoDbClient) {
this.table = Objects.requireNonNull(table);
this.ttl = Objects.requireNonNull(ttl);
this.dynamoDbAsyncClient = Objects.requireNonNull(dynamoDbAsyncClient);
this.dynamoDbClient = Objects.requireNonNull(dynamoDbClient);
}
public CompletableFuture<Instant> getPaidAt(final String paymentId, final Instant fallbackTimestamp) {
public Instant getPaidAt(final String paymentId, final Instant fallbackTimestamp) {
final GetItemRequest getItemRequest = GetItemRequest.builder()
.consistentRead(Boolean.TRUE)
.tableName(table)
@@ -46,24 +46,22 @@ public class OneTimeDonationsManager {
.projectionExpression(ATTR_PAID_AT)
.build();
return dynamoDbAsyncClient.getItem(getItemRequest).thenApply(getItemResponse -> {
if (!getItemResponse.hasItem()) {
Metrics.counter(ONETIME_DONATION_NOT_FOUND_COUNTER_NAME).increment();
return fallbackTimestamp;
}
final GetItemResponse getItemResponse = dynamoDbClient.getItem(getItemRequest);
if (!getItemResponse.hasItem()) {
Metrics.counter(ONETIME_DONATION_NOT_FOUND_COUNTER_NAME).increment();
return fallbackTimestamp;
}
return Instant.ofEpochSecond(AttributeValues.getLong(getItemResponse.item(), ATTR_PAID_AT, fallbackTimestamp.getEpochSecond()));
});
return Instant.ofEpochSecond(AttributeValues.getLong(getItemResponse.item(), ATTR_PAID_AT, fallbackTimestamp.getEpochSecond()));
}
public CompletableFuture<String> putPaidAt(final String paymentId, final Instant paidAt) {
return dynamoDbAsyncClient.putItem(PutItemRequest.builder()
public void putPaidAt(final String paymentId, final Instant paidAt) {
dynamoDbClient.putItem(PutItemRequest.builder()
.tableName(table)
.item(Map.of(
KEY_PAYMENT_ID, AttributeValues.fromString(paymentId),
ATTR_PAID_AT, AttributeValues.fromLong(paidAt.getEpochSecond()),
ATTR_TTL, AttributeValues.fromLong(paidAt.plus(ttl).getEpochSecond())))
.build())
.thenApply(unused -> paymentId);
.build());
}
}
@@ -11,15 +11,15 @@ import java.time.Instant;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import javax.annotation.Nonnull;
import org.signal.libsignal.zkgroup.receipts.ReceiptSerial;
import org.whispersystems.textsecuregcm.util.AttributeValues;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.ReturnValue;
import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;
import software.amazon.awssdk.services.dynamodb.model.UpdateItemResponse;
public class RedeemedReceiptsManager {
@@ -32,13 +32,13 @@ public class RedeemedReceiptsManager {
private final Clock clock;
private final String table;
private final DynamoDbAsyncClient client;
private final DynamoDbClient client;
private final Duration expirationTime;
public RedeemedReceiptsManager(
@Nonnull final Clock clock,
@Nonnull final String table,
@Nonnull final DynamoDbAsyncClient client,
@Nonnull final DynamoDbClient client,
@Nonnull final Duration expirationTime) {
this.clock = Objects.requireNonNull(clock);
this.table = Objects.requireNonNull(table);
@@ -51,7 +51,7 @@ public class RedeemedReceiptsManager {
* receiptLevel}, and {@code accountUuid} provided or if an existing entry already exists with the same values thereby
* allowing idempotent request processing.
*/
public CompletableFuture<Boolean> put(
public boolean put(
@Nonnull final ReceiptSerial receiptSerial,
final long receiptExpiration,
final long receiptLevel,
@@ -87,13 +87,13 @@ public class RedeemedReceiptsManager {
":account_uuid", AttributeValues.b(accountUuid),
":redemption_time", AttributeValues.n(now.getEpochSecond())))
.build();
return client.updateItem(updateItemRequest).thenApply(updateItemResponse -> {
final UpdateItemResponse updateItemResponse = client.updateItem(updateItemRequest);
final Map<String, AttributeValue> attributes = updateItemResponse.attributes();
final long ddbReceiptExpiration = Long.parseLong(attributes.get(KEY_RECEIPT_EXPIRATION).n());
final long ddbReceiptLevel = Long.parseLong(attributes.get(KEY_RECEIPT_LEVEL).n());
final UUID ddbAccountUuid = UUIDUtil.fromByteBuffer(attributes.get(KEY_ACCOUNT_UUID).b().asByteBuffer());
return ddbReceiptExpiration == receiptExpiration && ddbReceiptLevel == receiptLevel &&
Objects.equals(ddbAccountUuid, accountUuid);
});
}
}
@@ -368,7 +368,7 @@ class RedisDynamoDbMessagePublisher implements MessageAvailabilityListener, Flow
}
// Stop receiving signals about new messages/conflicting consumers
redisMessageAvailabilityManager.handleClientDisconnected(accountIdentifier, device.getId());
redisMessageAvailabilityManager.handleClientDisconnected(accountIdentifier, device.getId(), this);
}
}
}
@@ -11,6 +11,7 @@ import java.util.concurrent.Flow;
import com.google.common.annotations.VisibleForTesting;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
import org.whispersystems.textsecuregcm.util.Util;
/// A [MessageStream] implementation that produces message from a joint DynamoDB/Redis message store.
@@ -57,13 +58,11 @@ public class RedisDynamoDbMessageStream implements MessageStream {
}
@Override
public CompletableFuture<Void> acknowledgeMessage(final MessageProtos.Envelope message) {
final UUID guid = UUID.fromString(message.getServerGuid());
return messagesCache.remove(accountIdentifier, device.getId(), guid)
public CompletableFuture<Void> acknowledgeMessage(final UUID messageGuid, final long serverTimestamp) {
return messagesCache.remove(accountIdentifier, device.getId(), messageGuid)
.thenCompose(removed -> removed.map(_ -> CompletableFuture.<Void>completedFuture(null))
.orElseGet(() ->
messagesDynamoDb.deleteMessage(accountIdentifier, device, guid, message.getServerTimestamp())
messagesDynamoDb.deleteMessage(accountIdentifier, device, messageGuid, serverTimestamp)
.thenRun(Util.NOOP)))
.whenComplete((_, _) -> messagePublisher.handleMessageAcknowledged());
}
@@ -13,15 +13,16 @@ import java.time.Duration;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
import org.whispersystems.textsecuregcm.util.AttributeValues;
import org.whispersystems.textsecuregcm.util.Util;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest;
import software.amazon.awssdk.services.dynamodb.model.DeleteItemResponse;
import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
import software.amazon.awssdk.services.dynamodb.model.GetItemResponse;
import software.amazon.awssdk.services.dynamodb.model.PutItemRequest;
import software.amazon.awssdk.services.dynamodb.model.PutItemResponse;
import software.amazon.awssdk.services.dynamodb.model.ReturnValue;
public class RegistrationRecoveryPasswords {
@@ -36,31 +37,32 @@ public class RegistrationRecoveryPasswords {
private final Duration expiration;
private final DynamoDbAsyncClient asyncClient;
private final DynamoDbClient dynamoDbClient;
private final Clock clock;
public RegistrationRecoveryPasswords(
final String tableName,
final Duration expiration,
final DynamoDbAsyncClient asyncClient,
final DynamoDbClient dynamoDbClient,
final Clock clock) {
this.tableName = requireNonNull(tableName);
this.expiration = requireNonNull(expiration);
this.asyncClient = requireNonNull(asyncClient);
this.dynamoDbClient = requireNonNull(dynamoDbClient);
this.clock = requireNonNull(clock);
}
public CompletableFuture<Optional<SaltedTokenHash>> lookup(final UUID phoneNumberIdentifier) {
return asyncClient.getItem(GetItemRequest.builder()
.tableName(tableName)
.key(Map.of(KEY_PNI, AttributeValues.fromString(phoneNumberIdentifier.toString())))
.consistentRead(true)
.build())
.thenApply(getItemResponse -> Optional.ofNullable(getItemResponse.item())
.filter(item -> item.containsKey(ATTR_SALT))
.filter(item -> item.containsKey(ATTR_HASH))
.map(RegistrationRecoveryPasswords::saltedTokenHashFromItem));
public Optional<SaltedTokenHash> lookup(final UUID phoneNumberIdentifier) {
final GetItemResponse getItemResponse = dynamoDbClient.getItem(GetItemRequest.builder()
.tableName(tableName)
.key(Map.of(KEY_PNI, AttributeValues.fromString(phoneNumberIdentifier.toString())))
.consistentRead(true)
.build());
return Optional.ofNullable(getItemResponse.item())
.filter(item -> item.containsKey(ATTR_SALT))
.filter(item -> item.containsKey(ATTR_HASH))
.map(RegistrationRecoveryPasswords::saltedTokenHashFromItem);
}
/// Add a PNI -> RRP mapping, or replace the current one if it already exists
@@ -68,31 +70,33 @@ public class RegistrationRecoveryPasswords {
/// @param phoneNumberIdentifier The PNI to associate the salted RRP with
/// @param data The salted registration recovery password
/// @return true if a new mapping was added, false if an existing mapping was updated
public CompletableFuture<Boolean> addOrReplace(final UUID phoneNumberIdentifier, final SaltedTokenHash data) {
public boolean addOrReplace(final UUID phoneNumberIdentifier, final SaltedTokenHash data) {
final long expirationSeconds = expirationSeconds();
return asyncClient.putItem(PutItemRequest.builder()
.tableName(tableName)
.returnValues(ReturnValue.ALL_OLD)
.item(Map.of(
KEY_PNI, AttributeValues.fromString(phoneNumberIdentifier.toString()),
ATTR_EXP, AttributeValues.fromLong(expirationSeconds),
ATTR_SALT, AttributeValues.fromString(data.salt()),
ATTR_HASH, AttributeValues.fromString(data.hash())))
.build())
.thenApply(response -> response.attributes() == null || response.attributes().isEmpty());
final PutItemResponse response = dynamoDbClient.putItem(PutItemRequest.builder()
.tableName(tableName)
.returnValues(ReturnValue.ALL_OLD)
.item(Map.of(
KEY_PNI, AttributeValues.fromString(phoneNumberIdentifier.toString()),
ATTR_EXP, AttributeValues.fromLong(expirationSeconds),
ATTR_SALT, AttributeValues.fromString(data.salt()),
ATTR_HASH, AttributeValues.fromString(data.hash())))
.build());
return response.attributes() == null || response.attributes().isEmpty();
}
/// Remove the entry associated with the provided PNI
///
/// @return true if an entry was removed, false if no entry existed
public CompletableFuture<Boolean> removeEntry(final UUID phoneNumberIdentifier) {
return asyncClient.deleteItem(DeleteItemRequest.builder()
.tableName(tableName)
.returnValues(ReturnValue.ALL_OLD)
.key(Map.of(KEY_PNI, AttributeValues.fromString(phoneNumberIdentifier.toString())))
.build())
.thenApply(response -> response.attributes() != null && !response.attributes().isEmpty());
public boolean removeEntry(final UUID phoneNumberIdentifier) {
final DeleteItemResponse response = dynamoDbClient.deleteItem(DeleteItemRequest.builder()
.tableName(tableName)
.returnValues(ReturnValue.ALL_OLD)
.key(Map.of(KEY_PNI, AttributeValues.fromString(phoneNumberIdentifier.toString())))
.build());
return response.attributes() != null && !response.attributes().isEmpty();
}
@VisibleForTesting
@@ -7,56 +7,32 @@ package org.whispersystems.textsecuregcm.storage;
import static java.util.Objects.requireNonNull;
import java.lang.invoke.MethodHandles;
import java.util.HexFormat;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException;
public class RegistrationRecoveryPasswordsManager {
private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
private final RegistrationRecoveryPasswords registrationRecoveryPasswords;
public RegistrationRecoveryPasswordsManager(final RegistrationRecoveryPasswords registrationRecoveryPasswords) {
this.registrationRecoveryPasswords = requireNonNull(registrationRecoveryPasswords);
}
public CompletableFuture<Boolean> verify(final UUID phoneNumberIdentifier, final byte[] password) {
public boolean verify(final UUID phoneNumberIdentifier, final byte[] password) {
return registrationRecoveryPasswords.lookup(phoneNumberIdentifier)
.thenApply(maybeHash -> maybeHash.filter(hash -> hash.verify(bytesToString(password))))
.whenComplete((_, error) -> {
if (error != null) {
logger.warn("Failed to lookup Registration Recovery Password", error);
}
})
.thenApply(Optional::isPresent);
.filter(hash -> hash.verify(bytesToString(password))).isPresent();
}
public CompletableFuture<Boolean> store(final UUID phoneNumberIdentifier, final byte[] password) {
public boolean store(final UUID phoneNumberIdentifier, final byte[] password) {
final String token = bytesToString(password);
final SaltedTokenHash tokenHash = SaltedTokenHash.generateFor(token);
return registrationRecoveryPasswords.addOrReplace(phoneNumberIdentifier, tokenHash)
.whenComplete((_, error) -> {
if (error != null) {
logger.warn("Failed to store Registration Recovery Password", error);
}
});
return registrationRecoveryPasswords.addOrReplace(phoneNumberIdentifier, tokenHash);
}
public CompletableFuture<Boolean> remove(final UUID phoneNumberIdentifier) {
return registrationRecoveryPasswords.removeEntry(phoneNumberIdentifier)
.whenComplete((_, error) -> {
if (error != null) {
logger.warn("Failed to remove Registration Recovery Password", error);
}
});
public boolean remove(final UUID phoneNumberIdentifier) {
return registrationRecoveryPasswords.removeEntry(phoneNumberIdentifier);
}
private static String bytesToString(final byte[] bytes) {
@@ -10,6 +10,7 @@ import java.util.Optional;
import java.util.UUID;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
public record RemovedMessage(Optional<ServiceIdentifier> sourceServiceId, ServiceIdentifier destinationServiceId,
@VisibleForTesting UUID serverGuid, long serverTimestamp, long clientTimestamp,
@@ -18,10 +19,10 @@ public record RemovedMessage(Optional<ServiceIdentifier> sourceServiceId, Servic
public static RemovedMessage fromEnvelope(MessageProtos.Envelope envelope) {
return new RemovedMessage(
envelope.hasSourceServiceId()
? Optional.of(ServiceIdentifier.valueOf(envelope.getSourceServiceId()))
? Optional.of(ServiceIdentifier.fromByteString(envelope.getSourceServiceId()))
: Optional.empty(),
ServiceIdentifier.valueOf(envelope.getDestinationServiceId()),
UUID.fromString(envelope.getServerGuid()),
ServiceIdentifier.fromByteString(envelope.getDestinationServiceId()),
UUIDUtil.fromByteString(envelope.getServerGuid()),
envelope.getServerTimestamp(),
envelope.getClientTimestamp(),
envelope.getType()
@@ -14,16 +14,16 @@ import java.time.Clock;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.util.AttributeValues;
import org.whispersystems.textsecuregcm.util.SystemMapper;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest;
import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
import software.amazon.awssdk.services.dynamodb.model.GetItemResponse;
import software.amazon.awssdk.services.dynamodb.model.PutItemRequest;
public abstract class SerializedExpireableJsonDynamoStore<T> {
@@ -34,7 +34,7 @@ public abstract class SerializedExpireableJsonDynamoStore<T> {
long getExpirationEpochSeconds();
}
private final DynamoDbAsyncClient dynamoDbClient;
private final DynamoDbClient dynamoDbClient;
private final String tableName;
private final Clock clock;
private final Class<T> deserializationTargetClass;
@@ -47,7 +47,7 @@ public abstract class SerializedExpireableJsonDynamoStore<T> {
private final Logger log = LoggerFactory.getLogger(getClass());
public SerializedExpireableJsonDynamoStore(final DynamoDbAsyncClient dynamoDbClient, final String tableName,
public SerializedExpireableJsonDynamoStore(final DynamoDbClient dynamoDbClient, final String tableName,
final Clock clock) {
this.dynamoDbClient = dynamoDbClient;
this.tableName = tableName;
@@ -67,18 +67,16 @@ public abstract class SerializedExpireableJsonDynamoStore<T> {
}
}
public CompletableFuture<Void> insert(final String key, final T v) {
return put(key, v, builder -> builder.expressionAttributeNames(Map.of(
"#key", KEY_KEY
)).conditionExpression("attribute_not_exists(#key)"));
public void insert(final String key, final T v) {
put(key, v, builder -> builder.expressionAttributeNames(Map.of("#key", KEY_KEY))
.conditionExpression("attribute_not_exists(#key)"));
}
public CompletableFuture<Void> update(final String key, final T v) {
return put(key, v, ignored -> {
});
public void update(final String key, final T v) {
put(key, v, _ -> {});
}
private CompletableFuture<Void> put(final String key, final T v,
private void put(final String key, final T v,
final Consumer<PutItemRequest.Builder> putRequestCustomizer) {
try {
final Map<String, AttributeValue> attributeValueMap = new HashMap<>(Map.of(
@@ -93,9 +91,7 @@ public abstract class SerializedExpireableJsonDynamoStore<T> {
.item(attributeValueMap);
putRequestCustomizer.accept(builder);
return dynamoDbClient.putItem(builder.build())
.thenRun(() -> {
});
dynamoDbClient.putItem(builder.build());
} catch (final JsonProcessingException e) {
// This should never happen when writing directly to a string except in cases of serious misconfiguration, which
// would be caught by tests.
@@ -107,24 +103,23 @@ public abstract class SerializedExpireableJsonDynamoStore<T> {
return v.getExpirationEpochSeconds();
}
public CompletableFuture<Optional<T>> findForKey(final String key) {
return dynamoDbClient.getItem(GetItemRequest.builder()
public Optional<T> findForKey(final String key) {
final GetItemResponse response = dynamoDbClient.getItem(GetItemRequest.builder()
.tableName(tableName)
.consistentRead(true)
.key(Map.of(KEY_KEY, AttributeValues.fromString(key)))
.build())
.thenApply(response -> {
try {
return response.hasItem()
? filterMaybeExpiredValue(
SystemMapper.jsonMapper()
.readValue(response.item().get(ATTR_SERIALIZED_VALUE).s(), deserializationTargetClass))
: Optional.empty();
} catch (final JsonProcessingException e) {
log.error("Failed to parse stored value", e);
return Optional.empty();
}
});
.build());
try {
return response.hasItem()
? filterMaybeExpiredValue(
SystemMapper.jsonMapper()
.readValue(response.item().get(ATTR_SERIALIZED_VALUE).s(), deserializationTargetClass))
: Optional.empty();
} catch (final JsonProcessingException e) {
log.error("Failed to parse stored value", e);
return Optional.empty();
}
}
private Optional<T> filterMaybeExpiredValue(T v) {
@@ -139,13 +134,11 @@ public abstract class SerializedExpireableJsonDynamoStore<T> {
return Optional.of(v);
}
public CompletableFuture<Void> remove(final String key) {
return dynamoDbClient.deleteItem(DeleteItemRequest.builder()
public void remove(final String key) {
dynamoDbClient.deleteItem(DeleteItemRequest.builder()
.tableName(tableName)
.key(Map.of(KEY_KEY, AttributeValues.fromString(key)))
.build())
.thenRun(() -> {
});
.build());
}
}
@@ -12,6 +12,7 @@ import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.CompletionException;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.stream.Collectors;
@@ -37,7 +38,9 @@ import org.whispersystems.textsecuregcm.subscriptions.SubscriptionNotFoundExcept
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentRequiredException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorConflictException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptAlreadyRedeemedException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptRequestedForOpenPaymentException;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
/**
@@ -79,7 +82,7 @@ public class SubscriptionManager {
public void deleteSubscriber(final SubscriberCredentials subscriberCredentials)
throws SubscriptionNotFoundException, SubscriptionInvalidArgumentsException, RateLimitExceededException {
final Subscriptions.GetResult getResult =
subscriptions.get(subscriberCredentials.subscriberUser(), subscriberCredentials.hmac()).join();
subscriptions.get(subscriberCredentials.subscriberUser(), subscriberCredentials.hmac());
if (getResult == Subscriptions.GetResult.NOT_STORED
|| getResult == Subscriptions.GetResult.PASSWORD_MISMATCH) {
throw new SubscriptionNotFoundException();
@@ -90,7 +93,7 @@ public class SubscriptionManager {
final ProcessorCustomer processorCustomer = getResult.record.getProcessorCustomer().get();
getProcessor(processorCustomer.processor()).cancelAllActiveSubscriptions(processorCustomer.customerId());
}
subscriptions.setCanceledAt(subscriberCredentials.subscriberUser(), subscriberCredentials.now()).join();
subscriptions.setCanceledAt(subscriberCredentials.subscriberUser(), subscriberCredentials.now());
}
/**
@@ -105,7 +108,7 @@ public class SubscriptionManager {
public void updateSubscriber(final SubscriberCredentials subscriberCredentials)
throws SubscriptionForbiddenException {
final Subscriptions.GetResult getResult =
subscriptions.get(subscriberCredentials.subscriberUser(), subscriberCredentials.hmac()).join();
subscriptions.get(subscriberCredentials.subscriberUser(), subscriberCredentials.hmac());
if (getResult == Subscriptions.GetResult.PASSWORD_MISMATCH) {
throw new SubscriptionForbiddenException("subscriberId mismatch");
@@ -113,13 +116,13 @@ public class SubscriptionManager {
// create a customer and write it to ddb
final Subscriptions.Record updatedRecord = subscriptions.create(subscriberCredentials.subscriberUser(),
subscriberCredentials.hmac(),
subscriberCredentials.now()).join();
subscriberCredentials.now());
if (updatedRecord == null) {
throw new SubscriptionForbiddenException("subscriberId mismatch");
}
} else {
// already exists so just touch access time and return
subscriptions.accessedAt(subscriberCredentials.subscriberUser(), subscriberCredentials.now()).join();
subscriptions.accessedAt(subscriberCredentials.subscriberUser(), subscriberCredentials.now());
}
}
@@ -144,7 +147,7 @@ public class SubscriptionManager {
public Subscriptions.Record getSubscriber(final SubscriberCredentials subscriberCredentials)
throws SubscriptionForbiddenException, SubscriptionNotFoundException {
final Subscriptions.GetResult getResult =
subscriptions.get(subscriberCredentials.subscriberUser(), subscriberCredentials.hmac()).join();
subscriptions.get(subscriberCredentials.subscriberUser(), subscriberCredentials.hmac());
if (getResult == Subscriptions.GetResult.PASSWORD_MISMATCH) {
throw new SubscriptionForbiddenException("subscriberId mismatch");
} else if (getResult == Subscriptions.GetResult.NOT_STORED) {
@@ -175,39 +178,41 @@ public class SubscriptionManager {
* user an entitlement
* @throws SubscriptionReceiptRequestedForOpenPaymentException if a receipt was requested while a payment transaction
* was still open
* @throws SubscriptionReceiptAlreadyRedeemedException if the receipt was already redeemed by a different request
* @throws RateLimitExceededException if rate-limited
*/
public ReceiptResult createReceiptCredentials(
final SubscriberCredentials subscriberCredentials,
final SubscriptionController.GetReceiptCredentialsRequest request,
final Function<CustomerAwareSubscriptionPaymentProcessor.ReceiptItem, Instant> expiration)
throws SubscriptionForbiddenException, SubscriptionNotFoundException, SubscriptionInvalidArgumentsException, SubscriptionPaymentRequiredException, RateLimitExceededException, SubscriptionReceiptRequestedForOpenPaymentException {
throws SubscriptionForbiddenException, SubscriptionNotFoundException, SubscriptionInvalidArgumentsException, SubscriptionPaymentRequiredException, RateLimitExceededException, SubscriptionReceiptRequestedForOpenPaymentException, SubscriptionReceiptAlreadyRedeemedException {
final Subscriptions.Record record = getSubscriber(subscriberCredentials);
if (record.subscriptionId == null) {
throw new SubscriptionNotFoundException();
}
ReceiptCredentialRequest receiptCredentialRequest;
final ReceiptCredentialRequest receiptCredentialRequest;
try {
receiptCredentialRequest = new ReceiptCredentialRequest(request.receiptCredentialRequest());
} catch (InvalidInputException e) {
} catch (final InvalidInputException e) {
throw new SubscriptionInvalidArgumentsException("invalid receipt credential request", e);
}
final PaymentProvider processor = record.getProcessorCustomer().orElseThrow().processor();
final SubscriptionPaymentProcessor manager = getProcessor(processor);
final SubscriptionPaymentProcessor.ReceiptItem receipt = manager.getReceiptItem(record.subscriptionId);
issuedReceiptsManager
.recordIssuance(receipt.itemId(), manager.getProvider(), receiptCredentialRequest, subscriberCredentials.now())
.join();
ReceiptCredentialResponse receiptCredentialResponse;
final ReceiptCredentialResponse receiptCredentialResponse;
try {
issuedReceiptsManager
.recordIssuance(receipt.itemId(), manager.getProvider(), receiptCredentialRequest, subscriberCredentials.now());
receiptCredentialResponse = zkReceiptOperations.issueReceiptCredential(
receiptCredentialRequest,
expiration.apply(receipt).getEpochSecond(),
receipt.level());
} catch (VerificationFailedException e) {
} catch (final VerificationFailedException e) {
throw new SubscriptionInvalidArgumentsException("receipt credential request failed verification", e);
} catch (final WriteConflictException _) {
throw new SubscriptionReceiptAlreadyRedeemedException();
}
return new ReceiptResult(receiptCredentialResponse, receipt, processor);
}
@@ -250,7 +255,7 @@ public class SubscriptionManager {
.createCustomer(subscriberCredentials.subscriberUser(), clientPlatform);
record = subscriptions.setProcessorAndCustomerId(record,
new ProcessorCustomer(pc.customerId(), subscriptionPaymentProcessor.getProvider()),
Instant.now()).join();
Instant.now());
}
final ProcessorCustomer processorCustomer = record.getProcessorCustomer()
.orElseThrow(() -> new UncheckedIOException(new IOException("processor must now exist")));
@@ -330,7 +335,7 @@ public class SubscriptionManager {
subscriptions.subscriptionLevelChanged(subscriberCredentials.subscriberUser(),
subscriberCredentials.now(),
level,
updatedSubscriptionId.id()).join();
updatedSubscriptionId.id());
} else {
// Otherwise, we don't have a subscription yet so create it and then record the subscription id
long lastSubscriptionCreatedAt = record.subscriptionCreatedAt != null
@@ -437,7 +442,7 @@ public class SubscriptionManager {
final ProcessorCustomer pc = new ProcessorCustomer(originalTransactionId, PaymentProvider.APPLE_APP_STORE);
final Long level = appleAppStoreManager.validateTransaction(originalTransactionId);
subscriptions.setIapPurchase(record, pc, originalTransactionId, level, subscriberCredentials.now()).join();
subscriptions.setIapPurchase(record, pc, originalTransactionId, level, subscriberCredentials.now());
return level;
}
@@ -10,7 +10,6 @@ import static org.whispersystems.textsecuregcm.util.AttributeValues.n;
import static org.whispersystems.textsecuregcm.util.AttributeValues.s;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Throwables;
import jakarta.ws.rs.ClientErrorException;
import jakarta.ws.rs.core.Response;
import java.nio.charset.StandardCharsets;
@@ -19,8 +18,6 @@ import java.time.Instant;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.slf4j.Logger;
@@ -28,15 +25,16 @@ import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
import org.whispersystems.textsecuregcm.subscriptions.ProcessorCustomer;
import org.whispersystems.textsecuregcm.util.Pair;
import org.whispersystems.textsecuregcm.util.Util;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.ConditionalCheckFailedException;
import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
import software.amazon.awssdk.services.dynamodb.model.GetItemResponse;
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
import software.amazon.awssdk.services.dynamodb.model.QueryResponse;
import software.amazon.awssdk.services.dynamodb.model.ReturnValue;
import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;
import software.amazon.awssdk.services.dynamodb.model.UpdateItemResponse;
public class Subscriptions {
@@ -161,11 +159,11 @@ public class Subscriptions {
}
private final String table;
private final DynamoDbAsyncClient client;
private final DynamoDbClient client;
public Subscriptions(
@Nonnull String table,
@Nonnull DynamoDbAsyncClient client) {
@Nonnull DynamoDbClient client) {
this.table = Objects.requireNonNull(table);
this.client = Objects.requireNonNull(client);
}
@@ -173,7 +171,7 @@ public class Subscriptions {
/**
* Looks in the GSI for a record with the given customer id and returns the user id.
*/
public CompletableFuture<byte[]> getSubscriberUserByProcessorCustomer(ProcessorCustomer processorCustomer) {
public byte[] getSubscriberUserByProcessorCustomer(ProcessorCustomer processorCustomer) {
QueryRequest query = QueryRequest.builder()
.tableName(table)
.indexName(INDEX_NAME)
@@ -185,20 +183,20 @@ public class Subscriptions {
.expressionAttributeValues(Map.of(
":processor_customer_id", b(processorCustomer.toDynamoBytes())))
.build();
return client.query(query).thenApply(queryResponse -> {
int count = queryResponse.count();
if (count == 0) {
return null;
} else if (count > 1) {
logger.error("expected invariant of 1-1 subscriber-customer violated for customer {} ({})",
processorCustomer.customerId(), processorCustomer.processor());
throw new IllegalStateException(
"expected invariant of 1-1 subscriber-customer violated for customer " + processorCustomer);
} else {
Map<String, AttributeValue> result = queryResponse.items().getFirst();
return result.get(KEY_USER).b().asByteArray();
}
});
final QueryResponse queryResponse = client.query(query);
int count = queryResponse.count();
if (count == 0) {
return null;
} else if (count > 1) {
logger.error("expected invariant of 1-1 subscriber-customer violated for customer {} ({})",
processorCustomer.customerId(), processorCustomer.processor());
throw new IllegalStateException(
"expected invariant of 1-1 subscriber-customer violated for customer " + processorCustomer);
} else {
Map<String, AttributeValue> result = queryResponse.items().getFirst();
return result.get(KEY_USER).b().asByteArray();
}
}
public static class GetResult {
@@ -228,21 +226,22 @@ public class Subscriptions {
/**
* Looks up a record with the given {@code user} and validates the {@code hmac} before returning it.
*/
public CompletableFuture<GetResult> get(byte[] user, byte[] hmac) {
return getUser(user).thenApply(getItemResponse -> {
if (!getItemResponse.hasItem()) {
return GetResult.NOT_STORED;
}
public GetResult get(byte[] user, byte[] hmac) {
final GetItemResponse getItemResponse = getUser(user);
Record record = Record.from(user, getItemResponse.item());
if (!MessageDigest.isEqual(hmac, record.password)) {
return GetResult.PASSWORD_MISMATCH;
}
return GetResult.found(record);
});
if (!getItemResponse.hasItem()) {
return GetResult.NOT_STORED;
}
Record record = Record.from(user, getItemResponse.item());
if (!MessageDigest.isEqual(hmac, record.password)) {
return GetResult.PASSWORD_MISMATCH;
}
return GetResult.found(record);
}
private CompletableFuture<GetItemResponse> getUser(byte[] user) {
private GetItemResponse getUser(byte[] user) {
checkUserLength(user);
GetItemRequest request = GetItemRequest.builder()
@@ -254,10 +253,11 @@ public class Subscriptions {
return client.getItem(request);
}
public CompletableFuture<Record> create(byte[] user, byte[] password, Instant createdAt) {
@Nullable
public Record create(byte[] user, byte[] password, Instant createdAt) {
checkUserLength(user);
UpdateItemRequest request = UpdateItemRequest.builder()
final UpdateItemRequest request = UpdateItemRequest.builder()
.tableName(table)
.key(Map.of(KEY_USER, b(user)))
.returnValues(ReturnValue.ALL_NEW)
@@ -279,17 +279,13 @@ public class Subscriptions {
":accessed_at", n(createdAt.getEpochSecond()))
)
.build();
return client.updateItem(request).handle((updateItemResponse, throwable) -> {
if (throwable != null) {
if (Throwables.getRootCause(throwable) instanceof ConditionalCheckFailedException) {
return null;
}
Throwables.throwIfUnchecked(throwable);
throw new CompletionException(throwable);
}
try {
final UpdateItemResponse updateItemResponse = client.updateItem(request);
return Record.from(user, updateItemResponse.attributes());
});
} catch (ConditionalCheckFailedException _) {
return null;
}
}
/**
@@ -297,10 +293,10 @@ public class Subscriptions {
*
* @return the user record.
*/
public CompletableFuture<Record> setProcessorAndCustomerId(Record userRecord,
public Record setProcessorAndCustomerId(Record userRecord,
ProcessorCustomer activeProcessorCustomer, Instant updatedAt) {
UpdateItemRequest request = UpdateItemRequest.builder()
final UpdateItemRequest request = UpdateItemRequest.builder()
.tableName(table)
.key(Map.of(KEY_USER, b(userRecord.user)))
.returnValues(ReturnValue.ALL_NEW)
@@ -318,15 +314,13 @@ public class Subscriptions {
":processor_customer_id", b(activeProcessorCustomer.toDynamoBytes())
)).build();
return client.updateItem(request)
.thenApply(updateItemResponse -> Record.from(userRecord.user, updateItemResponse.attributes()))
.exceptionallyCompose(throwable -> {
if (Throwables.getRootCause(throwable) instanceof ConditionalCheckFailedException) {
throw new ClientErrorException(Response.Status.CONFLICT);
}
Throwables.throwIfUnchecked(throwable);
throw new CompletionException(throwable);
});
try {
final UpdateItemResponse updateItemResponse = client.updateItem(request);
return Record.from(userRecord.user, updateItemResponse.attributes());
} catch (ConditionalCheckFailedException _) {
throw new ClientErrorException(Response.Status.CONFLICT);
}
}
/**
@@ -345,7 +339,7 @@ public class Subscriptions {
* @param updatedAt The time of this update
* @return A stage that completes once the record has been updated
*/
public CompletableFuture<Void> setIapPurchase(
public void setIapPurchase(
final Record record,
final ProcessorCustomer processorCustomer,
final String subscriptionId,
@@ -390,21 +384,17 @@ public class Subscriptions {
":subscription_level_changed_at", n(updatedAt.getEpochSecond())))
.build();
return client.updateItem(request)
.exceptionallyCompose(throwable -> {
if (Throwables.getRootCause(throwable) instanceof ConditionalCheckFailedException) {
throw new ClientErrorException(Response.Status.CONFLICT);
}
Throwables.throwIfUnchecked(throwable);
throw new CompletionException(throwable);
})
.thenRun(Util.NOOP);
try {
client.updateItem(request);
} catch (ConditionalCheckFailedException _) {
throw new ClientErrorException(Response.Status.CONFLICT);
}
}
public CompletableFuture<Void> accessedAt(byte[] user, Instant accessedAt) {
public void accessedAt(byte[] user, Instant accessedAt) {
checkUserLength(user);
UpdateItemRequest request = UpdateItemRequest.builder()
final UpdateItemRequest request = UpdateItemRequest.builder()
.tableName(table)
.key(Map.of(KEY_USER, b(user)))
.returnValues(ReturnValue.NONE)
@@ -412,13 +402,13 @@ public class Subscriptions {
.expressionAttributeNames(Map.of("#accessed_at", KEY_ACCESSED_AT))
.expressionAttributeValues(Map.of(":accessed_at", n(accessedAt.getEpochSecond())))
.build();
return client.updateItem(request).thenApply(updateItemResponse -> null);
client.updateItem(request);
}
public CompletableFuture<Void> setCanceledAt(byte[] user, Instant canceledAt) {
public void setCanceledAt(byte[] user, Instant canceledAt) {
checkUserLength(user);
UpdateItemRequest request = UpdateItemRequest.builder()
final UpdateItemRequest request = UpdateItemRequest.builder()
.tableName(table)
.key(Map.of(KEY_USER, b(user)))
.returnValues(ReturnValue.NONE)
@@ -434,14 +424,14 @@ public class Subscriptions {
":accessed_at", n(canceledAt.getEpochSecond()),
":canceled_at", n(canceledAt.getEpochSecond())))
.build();
return client.updateItem(request).thenApply(updateItemResponse -> null);
client.updateItem(request);
}
public CompletableFuture<Void> subscriptionCreated(
public void subscriptionCreated(
byte[] user, String subscriptionId, Instant subscriptionCreatedAt, long level) {
checkUserLength(user);
UpdateItemRequest request = UpdateItemRequest.builder()
final UpdateItemRequest request = UpdateItemRequest.builder()
.tableName(table)
.key(Map.of(KEY_USER, b(user)))
.returnValues(ReturnValue.NONE)
@@ -466,14 +456,14 @@ public class Subscriptions {
":subscription_level", n(level),
":subscription_level_changed_at", n(subscriptionCreatedAt.getEpochSecond())))
.build();
return client.updateItem(request).thenApply(updateItemResponse -> null);
client.updateItem(request);
}
public CompletableFuture<Void> subscriptionLevelChanged(
public void subscriptionLevelChanged(
byte[] user, Instant subscriptionLevelChangedAt, long level, String subscriptionId) {
checkUserLength(user);
UpdateItemRequest request = UpdateItemRequest.builder()
final UpdateItemRequest request = UpdateItemRequest.builder()
.tableName(table)
.key(Map.of(KEY_USER, b(user)))
.returnValues(ReturnValue.NONE)
@@ -495,7 +485,7 @@ public class Subscriptions {
":subscription_level", n(level),
":subscription_level_changed_at", n(subscriptionLevelChangedAt.getEpochSecond())))
.build();
return client.updateItem(request).thenApply(updateItemResponse -> null);
client.updateItem(request);
}
private static byte[] checkUserLength(final byte[] user) {
@@ -6,7 +6,6 @@
package org.whispersystems.textsecuregcm.storage;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import org.whispersystems.textsecuregcm.registration.VerificationSession;
public class VerificationSessionManager {
@@ -17,15 +16,15 @@ public class VerificationSessionManager {
this.verificationSessions = verificationSessions;
}
public CompletableFuture<Void> insert(final VerificationSession verificationSession) {
return verificationSessions.insert(verificationSession.sessionId(), verificationSession);
public void insert(final VerificationSession verificationSession) {
verificationSessions.insert(verificationSession.sessionId(), verificationSession);
}
public CompletableFuture<Void> update(final VerificationSession verificationSession) {
return verificationSessions.update(verificationSession.sessionId(), verificationSession);
public void update(final VerificationSession verificationSession) {
verificationSessions.update(verificationSession.sessionId(), verificationSession);
}
public CompletableFuture<Optional<VerificationSession>> findForId(final String encodedSessionId) {
public Optional<VerificationSession> findForId(final String encodedSessionId) {
return verificationSessions.findForKey(encodedSessionId);
}
@@ -7,11 +7,11 @@ package org.whispersystems.textsecuregcm.storage;
import java.time.Clock;
import org.whispersystems.textsecuregcm.registration.VerificationSession;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
public class VerificationSessions extends SerializedExpireableJsonDynamoStore<VerificationSession> {
public VerificationSessions(final DynamoDbAsyncClient dynamoDbClient, final String tableName, final Clock clock) {
public VerificationSessions(final DynamoDbClient dynamoDbClient, final String tableName, final Clock clock) {
super(dynamoDbClient, tableName, clock);
}
}
@@ -0,0 +1,113 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage.foundationdb;
import com.apple.foundationdb.tuple.Versionstamp;
import com.google.common.annotations.VisibleForTesting;
import org.whispersystems.textsecuregcm.util.Pair;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.NavigableMap;
import java.util.TreeMap;
/// An acknowledged message buffer keeps track of messages that have been sent, whether they have been acknowledged by
/// the recipient, and whether those acknowledgements have been flushed to the underlying data store. It also batches
/// acknowledgements into contiguous ranges in the interest of efficiency.
class AcknowledgedMessageBuffer {
/// The maximum number of unacknowledged messages we will send before closing the stream with an error
private final int maxUnacknowledgedMessages;
/// 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;
AcknowledgedMessageBuffer(final int maxUnacknowledgedMessages) {
this.maxUnacknowledgedMessages = maxUnacknowledgedMessages;
}
public synchronized void addUnacknowledgedMessage(final Versionstamp versionstamp) throws TooManyUnacknowledgedMessagesException {
if (++unacknowledgedMessages > maxUnacknowledgedMessages) {
throw new TooManyUnacknowledgedMessagesException();
}
sentVersionstamps.put(versionstamp, false);
}
public synchronized void acknowledgeMessage(final Versionstamp versionstamp) {
// If we don't know about this versionstamp, or it's already acknowledged, there's nothing to do
if (!sentVersionstamps.containsKey(versionstamp) || sentVersionstamps.get(versionstamp)) {
return;
}
unacknowledgedMessages--;
sentVersionstamps.put(versionstamp, true);
}
@VisibleForTesting
int getUnacknowledgedMessageCount() {
return unacknowledgedMessages;
}
/// Computes a list of acknowledged contiguous versionstamp ranges that can be cleared from the database and removes
/// them from ths unacknowledged mesage buffer.
///
/// @return a list of acknowledged contiguous versionstamp ranges that can be cleared from the database.
public synchronized List<Pair<Versionstamp, Versionstamp>> takeFlushableRanges() {
final List<Pair<Versionstamp, Versionstamp>> flushableRanges = computeFlushableRanges();
flushableRanges.forEach(range -> sentVersionstamps.subMap(range.first(), true, range.second(), true).clear());
return flushableRanges;
}
/// Computes a list of acknowledged contiguous versionstamp ranges that can be cleared from the database.
///
/// @return a list of acknowledged contiguous versionstamp ranges that can be cleared from the database.
@VisibleForTesting
synchronized List<Pair<Versionstamp, Versionstamp>> computeFlushableRanges() {
final List<Pair<Versionstamp, Versionstamp>> flushableRanges = new ArrayList<>();
Versionstamp startInclusive = null;
Versionstamp endInclusive = null;
for (final Map.Entry<Versionstamp, Boolean> entry : sentVersionstamps.entrySet()) {
if (entry.getValue()) {
// Message is acknowledged, so we can either start tracking a new range if we aren't already, or extend our
// current range
if (startInclusive == null) {
startInclusive = entry.getKey();
}
endInclusive = entry.getKey();
} else {
// Message is un-acknowledged, which means either it is a "range-breaker" or we never started tracking an
// acknowledged range. Mark the currently tracked range flushable, if it exists.
if (startInclusive != null) {
assert endInclusive != null;
flushableRanges.add(new Pair<>(startInclusive, endInclusive));
startInclusive = null;
}
}
}
if (startInclusive != null) {
assert endInclusive != null;
flushableRanges.add(new Pair<>(startInclusive, endInclusive));
}
return flushableRanges;
}
/// Acknowledges a stale ephemeral message for cleanup from FoundationDB.
/// Ephemeral messages are only delivered when the recipient has an active message stream, so any ephemeral message
/// read from the finite publisher is stale by definition and can be immediately acknowledged and discarded.
///
/// @param versionstamp The versionstamp to acknowledge
public synchronized void acknowledgeStaleEphemeralMessage(final Versionstamp versionstamp) {
sentVersionstamps.put(versionstamp, true);
}
}
@@ -4,13 +4,12 @@ import com.apple.foundationdb.Database;
import com.apple.foundationdb.KeySelector;
import com.apple.foundationdb.StreamingMode;
import com.apple.foundationdb.Transaction;
import com.apple.foundationdb.tuple.Versionstamp;
import com.google.protobuf.InvalidProtocolBufferException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.storage.MessageStreamEntry;
import org.whispersystems.textsecuregcm.util.Pair;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
import reactor.core.publisher.Flux;
import reactor.core.publisher.FluxSink;
@@ -20,13 +19,14 @@ import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Supplier;
/// Publishes a message stream from a device queue in FoundationDB. Capable of publishing both a finite stream for
/// catching up to end-of-queue,and an infinite stream for live updates.
class FoundationDbMessagePublisher {
private final Database database;
private final MessageGuidCodec messageGuidCodec;
/// The maximum number of messages we will fetch per range query operation to avoid excessive memory consumption
private final int maxMessagesPerScan;
/// The end key at which we stop reading messages. For finite publisher, this is just past the end-of-queue key at the
@@ -76,14 +76,17 @@ class FoundationDbMessagePublisher {
@Nullable private final byte[] messagesAvailableWatchKey;
/// Listener to watch for state machine transitions; used for testing.
private final BiConsumer<State, State> stateChangeListener;
private final Flux<MessageStreamEntry.Envelope> messagePublisher;
private final Flux<FoundationDbMessageStreamEntry.Message> messagePublisher;
/// Whether the publisher is finite or infinite.
private final boolean terminateOnQueueEmpty;
/// A supplier that returns a function to execute before we begin fetching a page; it is passed the transaction that
/// is started for the page fetch operations.
private final Supplier<Consumer<Transaction>> beforePageFetch;
/// Tracks the current state of the publisher state machine. Initial state presumes that messages are available in the queue.
private State state = State.MESSAGES_AVAILABLE;
/// Reference to the sink we publishes messages to.
private volatile FluxSink<MessageStreamEntry.Envelope> emitter;
private volatile FluxSink<FoundationDbMessageStreamEntry.Message> emitter;
/// Future that completes when the watch for {@link #messagesAvailableWatchKey} triggers.
private CompletableFuture<Void> watchFuture;
@@ -93,19 +96,19 @@ class FoundationDbMessagePublisher {
final KeySelector beginKeyInclusive,
final KeySelector endKeyExclusive,
final Database database,
final MessageGuidCodec messageGuidCodec,
final int maxMessagesPerScan,
@Nullable final byte[] messagesAvailableWatchKey,
@Nullable final BiConsumer<State, State> stateChangeListener) {
@Nullable final BiConsumer<State, State> stateChangeListener,
final Supplier<Consumer<Transaction>> beforePageFetch) {
this.beginKeyCursor = beginKeyInclusive;
this.endKeyExclusive = endKeyExclusive;
this.database = database;
this.messageGuidCodec = messageGuidCodec;
this.maxMessagesPerScan = maxMessagesPerScan;
this.messagesAvailableWatchKey = messagesAvailableWatchKey;
this.terminateOnQueueEmpty = messagesAvailableWatchKey == null;
this.stateChangeListener = stateChangeListener != null ? stateChangeListener : (_, _) -> {};
this.beforePageFetch = beforePageFetch;
this.messagePublisher = Flux.create(emitter -> {
this.emitter = emitter;
emitter.onRequest(_ -> transitionStateOnEvent(Event.DEMAND_REQUESTED));
@@ -121,16 +124,16 @@ class FoundationDbMessagePublisher {
final KeySelector beginKeyInclusive,
final KeySelector endKeyExclusive,
final Database database,
final MessageGuidCodec messageGuidCodec,
final int maxMessagesPerScan) {
final int maxMessagesPerScan,
final Supplier<Consumer<Transaction>> beforePageFetch) {
return new FoundationDbMessagePublisher(beginKeyInclusive,
endKeyExclusive,
database,
messageGuidCodec,
maxMessagesPerScan,
null,
null);
null,
beforePageFetch);
}
/// Creates a [FoundationDbMessagePublisher] that publishes a non-terminating stream of messages from a device queue.
@@ -140,17 +143,17 @@ class FoundationDbMessagePublisher {
final KeySelector beginKeyInclusive,
final KeySelector endKeyExclusive,
final Database database,
final MessageGuidCodec messageGuidCodec,
final int maxMessagesPerScan,
final byte[] messagesAvailableWatchKey) {
final byte[] messagesAvailableWatchKey,
final Supplier<Consumer<Transaction>> beforePageFetch) {
return new FoundationDbMessagePublisher(beginKeyInclusive,
endKeyExclusive,
database,
messageGuidCodec,
maxMessagesPerScan,
messagesAvailableWatchKey,
null);
null,
beforePageFetch);
}
private synchronized void setState(final State newState, final Event event) {
@@ -238,25 +241,32 @@ class FoundationDbMessagePublisher {
/// Fetch messages using a range query limiting batch size to [#maxMessagesPerScan]. If the query returns fewer than
/// [#maxMessagesPerScan], emit [Event#FETCHED_ALL_AVAILABLE_MESSAGES]. In the case of an infinite publisher, also set
/// a watch for new messages. Additionally, the cursor is updated so that we begin fetching from the right key on
/// a watch for new messages. Execute the function supplied by [#beforePageFetch] in the context of the transaction.
/// Additionally, the cursor is updated so that we begin fetching from the right key on
/// subsequent scans
///
/// @return a future of a list of [MessageStreamEntry] with a max size of [#maxMessagesPerScan]
private CompletableFuture<List<MessageStreamEntry.Envelope>> getMessagesBatch() {
return database.runAsync(transaction -> getItemsInRange(transaction, messageGuidCodec, beginKeyCursor, endKeyExclusive, maxMessagesPerScan)
.thenApply(lastKeyReadAndItems -> {
// Set our beginning key to just past the last key read so that we're ready for our next fetch
lastKeyReadAndItems.first().ifPresent(lastKeyRead -> beginKeyCursor = KeySelector.firstGreaterThan(lastKeyRead));
/// @return a future of a list of [FoundationDbMessageStreamEntry.Message] with a max size of [#maxMessagesPerScan]
private CompletableFuture<List<FoundationDbMessageStreamEntry.Message>> getMessagesBatch() {
final Consumer<Transaction> doBeforePageFetch = beforePageFetch.get();
return database.runAsync(transaction -> {
doBeforePageFetch.accept(transaction);
return getItemsInRange(transaction, beginKeyCursor, endKeyExclusive, maxMessagesPerScan)
.thenApply(lastKeyReadAndItems -> {
// Set our beginning key to just past the last key read so that we're ready for our next fetch
lastKeyReadAndItems.first()
.ifPresent(lastKeyRead -> beginKeyCursor = KeySelector.firstGreaterThan(lastKeyRead));
final List<MessageStreamEntry.Envelope> items = lastKeyReadAndItems.second();
if (items.size() < maxMessagesPerScan) {
transitionStateOnEvent(Event.FETCHED_ALL_AVAILABLE_MESSAGES);
if (!terminateOnQueueEmpty) {
setWatch(transaction);
}
}
return items;
})
final List<FoundationDbMessageStreamEntry.Message> items = lastKeyReadAndItems.second();
if (items.size() < maxMessagesPerScan) {
transitionStateOnEvent(Event.FETCHED_ALL_AVAILABLE_MESSAGES);
if (!terminateOnQueueEmpty) {
setWatch(transaction);
}
}
return items;
});
}
);
}
@@ -267,9 +277,8 @@ class FoundationDbMessagePublisher {
/// @param endExclusive the range end key (exclusive)
/// @param maxMessagesPerScan maximum number of messages to return in the fetch query
/// @return the last key read (if there were non-zero number of messages read) and the list of messages read
private static CompletableFuture<Pair<Optional<byte[]>, List<MessageStreamEntry.Envelope>>> getItemsInRange(
private CompletableFuture<Pair<Optional<byte[]>, List<FoundationDbMessageStreamEntry.Message>>> getItemsInRange(
final Transaction transaction,
final MessageGuidCodec messageGuidCodec,
final KeySelector beginInclusive,
final KeySelector endExclusive,
final int maxMessagesPerScan) {
@@ -278,13 +287,12 @@ class FoundationDbMessagePublisher {
final Optional<byte[]> lastKeyRead = keyValues.isEmpty()
? Optional.empty()
: Optional.of(keyValues.getLast().getKey());
final List<MessageStreamEntry.Envelope> messages = keyValues.stream()
final List<FoundationDbMessageStreamEntry.Message> messages = keyValues.stream()
.map(keyValue -> {
final Versionstamp versionstamp = FoundationDbMessageStore.getVersionstamp(keyValue.getKey());
try {
return new MessageStreamEntry.Envelope(MessageProtos.Envelope.parseFrom(keyValue.getValue())
.toBuilder()
.setServerGuidBinary(UUIDUtil.toByteString(messageGuidCodec.encodeMessageGuid(FoundationDbMessageStore.getVersionstamp(keyValue.getKey()))))
.build());
return new FoundationDbMessageStreamEntry.Message(versionstamp, MessageProtos.Envelope.parseFrom(keyValue.getValue()));
} catch (final InvalidProtocolBufferException e) {
throw new UncheckedIOException(e);
}
@@ -317,7 +325,7 @@ class FoundationDbMessagePublisher {
/// Get the stream of messages.
///
/// @return [Flux] of messages
public Flux<MessageStreamEntry.Envelope> getMessages() {
public Flux<FoundationDbMessageStreamEntry.Message> getMessages() {
return this.messagePublisher;
}
@@ -17,7 +17,6 @@ import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
@@ -25,6 +24,7 @@ import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.MessageStream;
import org.whispersystems.textsecuregcm.util.Conversions;
import org.whispersystems.textsecuregcm.util.Util;
/// An implementation of a message store backed by FoundationDB.
///
@@ -39,9 +39,9 @@ import org.whispersystems.textsecuregcm.util.Conversions;
/// * {versionstamp_2} => envelope_2
public class FoundationDbMessageStore {
private final Database[] databases;
private final Database[][] databasesByEpoch;
private final int activeEpoch;
private final VersionstampUUIDCipher versionstampUUIDCipher;
private final Executor executor;
private final Clock clock;
private static final Subspace MESSAGES_SUBSPACE = new Subspace(Tuple.from("M"));
@@ -53,6 +53,11 @@ public class FoundationDbMessageStore {
/// suggest a limit of 1MB to avoid performance issues, although the hard limit is 10MB
private static final long MAX_MESSAGE_CHUNK_SIZE = DataSize.megabytes(1).toBytes();
// We pack the current configuration epoch and shard ID into a single byte of "user data" in each message
// versionstamp. We use two bits for the epoch and six for the shard ID.
public static final int MAX_EPOCHS = 4;
public static final int MAX_SHARDS = 64;
/// Result of inserting a message for a particular device
///
/// @param versionstamp the versionstamp of the transaction in which this device's message was inserted, empty
@@ -61,14 +66,19 @@ public class FoundationDbMessageStore {
public record InsertResult(Optional<Versionstamp> versionstamp, boolean present) {
}
public FoundationDbMessageStore(final Database[] databases,
public FoundationDbMessageStore(final Map<Integer, List<Database>> databasesByEpoch,
final int activeEpoch,
final VersionstampUUIDCipher versionstampUUIDCipher,
final Executor executor,
final Clock clock) {
this.databases = databases;
final Database[][] databasesByEpochArray = new Database[MAX_EPOCHS][];
databasesByEpoch.forEach((epoch, databases) ->
databasesByEpochArray[epoch] = databases.toArray(Database[]::new));
this.databasesByEpoch = databasesByEpochArray;
this.activeEpoch = activeEpoch;
this.versionstampUUIDCipher = versionstampUUIDCipher;
this.executor = executor;
this.clock = clock;
}
@@ -81,7 +91,15 @@ public class FoundationDbMessageStore {
public CompletableFuture<Map<Byte, InsertResult>> insert(final AciServiceIdentifier aciServiceIdentifier,
final Map<Byte, MessageProtos.Envelope> messagesByDeviceId) {
return insert(Map.of(aciServiceIdentifier, messagesByDeviceId))
return insert(aciServiceIdentifier, messagesByDeviceId, activeEpoch);
}
@VisibleForTesting
CompletableFuture<Map<Byte, InsertResult>> insert(final AciServiceIdentifier aciServiceIdentifier,
final Map<Byte, MessageProtos.Envelope> messagesByDeviceId,
final int epoch) {
return insert(Map.of(aciServiceIdentifier, messagesByDeviceId), epoch)
.thenApply(resultsByServiceIdentifier -> {
assert resultsByServiceIdentifier.size() == 1;
@@ -103,6 +121,14 @@ public class FoundationDbMessageStore {
public CompletableFuture<Map<AciServiceIdentifier, Map<Byte, InsertResult>>> insert(
final Map<AciServiceIdentifier, Map<Byte, MessageProtos.Envelope>> messagesByServiceIdentifier) {
return insert(messagesByServiceIdentifier, activeEpoch);
}
@VisibleForTesting
CompletableFuture<Map<AciServiceIdentifier, Map<Byte, InsertResult>>> insert(
final Map<AciServiceIdentifier, Map<Byte, MessageProtos.Envelope>> messagesByServiceIdentifier,
final int epoch) {
if (messagesByServiceIdentifier.entrySet()
.stream()
.anyMatch(entry -> entry.getValue().isEmpty())) {
@@ -119,7 +145,7 @@ public class FoundationDbMessageStore {
final Map<Integer, List<Map.Entry<AciServiceIdentifier, Map<Byte, MessageProtos.Envelope>>>> messagesByShardId =
messagesByServiceIdentifier.entrySet().stream()
.collect(Collectors.groupingBy(entry -> hashAciToShardNumber(entry.getKey())));
.collect(Collectors.groupingBy(entry -> hashAciToShardNumber(entry.getKey(), epoch)));
final List<CompletableFuture<Map<AciServiceIdentifier, Map<Byte, InsertResult>>>> chunkFutures =
new ArrayList<>();
@@ -135,7 +161,7 @@ public class FoundationDbMessageStore {
.sum();
if (estimatedTransactionSize > MAX_MESSAGE_CHUNK_SIZE) {
chunkFutures.add(insertChunk(shardId, messagesForShard.subList(start, current)));
chunkFutures.add(insertChunk(shardId, epoch, messagesForShard.subList(start, current)));
start = current;
estimatedTransactionSize = 0;
@@ -145,7 +171,7 @@ public class FoundationDbMessageStore {
}
assert start < messagesForShard.size();
chunkFutures.add(insertChunk(shardId, messagesForShard.subList(start, messagesForShard.size())));
chunkFutures.add(insertChunk(shardId, epoch, messagesForShard.subList(start, messagesForShard.size())));
});
return CompletableFuture.allOf(chunkFutures.toArray(CompletableFuture[]::new))
@@ -159,6 +185,7 @@ public class FoundationDbMessageStore {
private CompletableFuture<Map<AciServiceIdentifier, Map<Byte, InsertResult>>> insertChunk(
final int shardId,
final int epoch,
final List<Map.Entry<AciServiceIdentifier, Map<Byte, MessageProtos.Envelope>>> messagesByAccountIdentifier) {
final Map<AciServiceIdentifier, CompletableFuture<Map<Byte, Boolean>>> insertFuturesByAci = new HashMap<>();
@@ -170,9 +197,9 @@ public class FoundationDbMessageStore {
.map(MessageProtos.Envelope::getEphemeral)
.orElseThrow(() -> new IllegalStateException("One or more bundles is empty"));
return databases[shardId].runAsync(transaction -> {
return getDatabases(epoch)[shardId].runAsync(transaction -> {
messagesByAccountIdentifier.forEach(entry ->
insertFuturesByAci.put(entry.getKey(), insert(entry.getKey(), entry.getValue(), transaction)));
insertFuturesByAci.put(entry.getKey(), insert(entry.getKey(), entry.getValue(), epoch, shardId, transaction)));
return CompletableFuture.allOf(insertFuturesByAci.values().toArray(CompletableFuture[]::new))
.thenApply(_ -> {
@@ -183,7 +210,8 @@ public class FoundationDbMessageStore {
.anyMatch(isPresent -> isPresent);
if (anyClientPresent || !ephemeral) {
return transaction.getVersionstamp()
.thenApply(versionstampBytes -> Optional.of(Versionstamp.complete(versionstampBytes, shardId)));
.thenApply(versionstampBytes -> Optional.of(Versionstamp.complete(versionstampBytes,
packUserData(epoch, shardId))));
}
return CompletableFuture.completedFuture(Optional.<Versionstamp>empty());
});
@@ -219,6 +247,8 @@ public class FoundationDbMessageStore {
/// @return a future that yields the presence state of each destination device
private CompletableFuture<Map<Byte, Boolean>> insert(final AciServiceIdentifier aci,
final Map<Byte, MessageProtos.Envelope> messagesByDeviceId,
final int epoch,
final int shardId,
final Transaction transaction) {
final Map<Byte, CompletableFuture<Boolean>> messageInsertFuturesByDeviceId = messagesByDeviceId.entrySet()
@@ -234,7 +264,7 @@ public class FoundationDbMessageStore {
if (isPresent || !message.getEphemeral()) {
transaction.mutate(MutationType.SET_VERSIONSTAMPED_KEY,
getDeviceQueueSubspace(aci, deviceId)
.packWithVersionstamp(Tuple.from(Versionstamp.incomplete(hashAciToShardNumber(aci)))), message.toByteArray());
.packWithVersionstamp(Tuple.from(Versionstamp.incomplete(packUserData(epoch, shardId)))), message.toByteArray());
}
return isPresent;
@@ -242,7 +272,7 @@ public class FoundationDbMessageStore {
}));
return CompletableFuture.allOf(messageInsertFuturesByDeviceId.values().toArray(CompletableFuture[]::new))
.thenApplyAsync(_ -> {
.thenApply(_ -> {
final Map<Byte, Boolean> presenceByDeviceId = messageInsertFuturesByDeviceId.entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey, entry -> {
assert entry.getValue().isDone();
@@ -253,24 +283,41 @@ public class FoundationDbMessageStore {
if (anyClientPresent) {
transaction.mutate(MutationType.SET_VERSIONSTAMPED_VALUE, getMessagesAvailableWatchKey(aci),
Tuple.from(Versionstamp.incomplete(hashAciToShardNumber(aci))).packWithVersionstamp());
Tuple.from(Versionstamp.incomplete(packUserData(epoch, shardId))).packWithVersionstamp());
}
return presenceByDeviceId;
}, executor);
});
}
public MessageStream getMessages(final AciServiceIdentifier aci, final Device destinationDevice) {
return getMessages(aci, destinationDevice, FoundationDbMessageStream.DEFAULT_MAX_MESSAGES_PER_SCAN);
return getMessages(aci, destinationDevice, FoundationDbMessageStream.DEFAULT_MAX_MESSAGES_PER_SCAN,
FoundationDbMessageStream.DEFAULT_MAX_UNACKNOWLEDGED_MESSAGES, Util.NOOP);
}
@VisibleForTesting
MessageStream getMessages(final AciServiceIdentifier aci, final Device destinationDevice, final int maxMessagesPerScan) {
MessageStream getMessages(final AciServiceIdentifier aci,
final Device destinationDevice,
final int maxMessagesPerScan,
final int maxUnacknowledgedMessages,
final Runnable doAfterCleanup) {
// For each configured database epoch, which database held (or holds) the messages for this ACI/device pair?
final Database[] databasesForQueueByEpoch = new Database[databasesByEpoch.length];
for (int epoch = 0; epoch < databasesByEpoch.length; epoch++) {
databasesForQueueByEpoch[epoch] = databasesByEpoch[epoch] != null
? getDatabases(epoch)[hashAciToShardNumber(aci, epoch)]
: null;
}
return new FoundationDbMessageStream(getDeviceQueueSubspace(aci, destinationDevice.getId()),
getMessagesAvailableWatchKey(aci),
getShardForAci(aci),
databasesForQueueByEpoch,
new MessageGuidCodec(aci.uuid(), destinationDevice.getId(), versionstampUUIDCipher),
maxMessagesPerScan);
maxMessagesPerScan,
maxUnacknowledgedMessages,
doAfterCleanup);
}
static Versionstamp getVersionstamp(final byte[] messageKey) {
@@ -278,14 +325,46 @@ public class FoundationDbMessageStore {
}
@VisibleForTesting
Database getShardForAci(final AciServiceIdentifier aci) {
return databases[hashAciToShardNumber(aci)];
Database getShardForAci(final AciServiceIdentifier aci, final int epoch) {
return getDatabases(epoch)[hashAciToShardNumber(aci, epoch)];
}
private Database[] getDatabases(final int epoch) {
if (databasesByEpoch[epoch] == null) {
throw new IllegalStateException("Epoch (%d) not in static configuration".formatted(epoch));
}
return databasesByEpoch[epoch];
}
@VisibleForTesting
int hashAciToShardNumber(final AciServiceIdentifier aci) {
int hashAciToShardNumber(final AciServiceIdentifier aci, final int epoch) {
// We use a consistent hash here to reduce the number of key remappings if we increase the number of shards
return Hashing.consistentHash(aci.uuid().getLeastSignificantBits(), databases.length);
return Hashing.consistentHash(aci.uuid().getLeastSignificantBits(), getDatabases(epoch).length);
}
@VisibleForTesting
static int packUserData(final int epoch, final int shardId) {
if (epoch < 0 || epoch >= MAX_EPOCHS) {
throw new IllegalArgumentException("Epoch (%d) outside of allowable range (0 to %d, exclusive)".formatted(
epoch, MAX_EPOCHS));
}
if (shardId < 0 || shardId >= MAX_SHARDS) {
throw new IllegalArgumentException("Shard ID (%d) outside of allowable range (0 to %d, exclusive)".formatted(
epoch, MAX_SHARDS));
}
return epoch << 6 | shardId;
}
static int getConfigurationEpoch(final Versionstamp versionstamp) {
return versionstamp.getUserVersion() >> 6 & 0x03;
}
@VisibleForTesting
static int getShardId(final Versionstamp versionstamp) {
return versionstamp.getUserVersion() & 0x3f;
}
@VisibleForTesting
@@ -1,45 +1,94 @@
package org.whispersystems.textsecuregcm.storage.foundationdb;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import com.apple.foundationdb.Database;
import com.apple.foundationdb.KeySelector;
import com.apple.foundationdb.StreamingMode;
import com.apple.foundationdb.Transaction;
import com.apple.foundationdb.subspace.Subspace;
import com.apple.foundationdb.tuple.ByteArrayUtil;
import com.apple.foundationdb.tuple.Tuple;
import com.apple.foundationdb.tuple.Versionstamp;
import com.google.common.annotations.VisibleForTesting;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Metrics;
import java.util.Arrays;
import java.util.Comparator;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Flow;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.storage.MessageStream;
import org.whispersystems.textsecuregcm.storage.MessageStreamEntry;
import org.whispersystems.textsecuregcm.util.Pair;
import reactor.adapter.JdkFlowAdapter;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.util.function.Tuple2;
import reactor.util.function.Tuples;
/// A [MessageStream] implementation that fetches messages from FoundationDB
public class FoundationDbMessageStream implements MessageStream {
private final Subspace deviceQueueSubspace;
private final byte[] messagesAvailableWatchKey;
private final Database database;
private final Database[] databasesByEpoch;
private final MessageGuidCodec messageGuidCodec;
/// The maximum number of messages we will fetch per range query operation to avoid excessive memory consumption
private final int maxMessagesPerScan;
private final Flow.Publisher<MessageStreamEntry> messageStreamPublisher;
private final Runnable doAfterCleanup;
private final Map<Database, AcknowledgedMessageBuffer> acknowledgedMessageBuffersByDatabase;
private final Counter staleEphemeralMessagesCounter = Metrics.counter(
name(FoundationDbMessageStream.class, "staleEphemeralMessages"));
static final int DEFAULT_MAX_MESSAGES_PER_SCAN = 1024;
@VisibleForTesting
static final int DEFAULT_MAX_UNACKNOWLEDGED_MESSAGES = 16_384;
private static final Comparator<FoundationDbMessageStreamEntry.Message> STREAM_ENTRY_TIMESTAMP_COMPARATOR =
Comparator.comparingLong(streamEntry -> streamEntry.partialEnvelope().getServerTimestamp());
private static final Logger LOGGER = LoggerFactory.getLogger(FoundationDbMessageStream.class);
FoundationDbMessageStream(final Subspace deviceQueueSubspace,
final byte[] messagesAvailableWatchKey,
final Database database,
final Database[] databasesByEpoch,
final MessageGuidCodec messageGuidCodec,
final int maxMessagesPerScan) {
final int maxMessagesPerScan,
final int maxUnacknowledgedMessages,
final Runnable doAfterCleanup) {
this.deviceQueueSubspace = deviceQueueSubspace;
this.messagesAvailableWatchKey = messagesAvailableWatchKey;
this.database = database;
this.databasesByEpoch = databasesByEpoch;
this.messageGuidCodec = messageGuidCodec;
this.maxMessagesPerScan = maxMessagesPerScan;
this.messageStreamPublisher = JdkFlowAdapter.publisherToFlowPublisher(createMessagePublisher());
this.doAfterCleanup = doAfterCleanup;
// Not all epochs may be in use (this is true most of the time) and if we DO have multiple epochs in play, it's
// possible/likely that a given queue will be on the same shard in multiple epochs. We only want acknowledgement
// buffer per distinct shard, so find the distinct shards for this queue and create a buffer for each.
this.acknowledgedMessageBuffersByDatabase = Arrays.stream(databasesByEpoch)
.filter(Objects::nonNull)
.distinct()
.collect(Collectors.toMap(database -> database,
_ -> new AcknowledgedMessageBuffer(maxUnacknowledgedMessages),
(_, _) -> {
throw new AssertionError("Duplicate database in distinct stream");
},
IdentityHashMap::new));
}
@Override
@@ -47,44 +96,119 @@ public class FoundationDbMessageStream implements MessageStream {
return this.messageStreamPublisher;
}
/// Create a message publisher
///
/// @return a Flux of {@link MessageStreamEntry} fetched from FoundationDB
/// @implNote The message publisher is stitched together by concatenating:
/// 1. **A finite message publisher**: On initial request, we record the current end-of-queue key in the device mailbox.
/// Then, we fetch all messages in order until the recorded key and finally complete the stream
/// 2. **A queue-empty signal** is emitted
/// 3. **An infinite message publisher**: We start reading from where the finite publisher left off. When all messages
/// are read, we wait for new messages, publish them, then wait again in a loop forever (until the flux is canceled
/// explicitly or due to an error). This is accomplished by setting a FoundationDB [watch](https://github.com/apple/foundationdb/wiki/An-Overview-how-Watches-Work)
/// on [#messagesAvailableWatchKey] which is updated when a new message is available.
/// See [FoundationDbMessageStore] for more details on the message insert process.
private Flux<MessageStreamEntry> createMessagePublisher() {
return Mono.fromFuture(this::getEndOfQueueKeyExclusive)
.flatMapMany(maybeEndOfQueueKeyExclusive -> {
final Flux<MessageStreamEntry.Envelope> finitePublisher = maybeEndOfQueueKeyExclusive
.map(endOfQueueKeyExclusive -> FoundationDbMessagePublisher.createFinitePublisher(
KeySelector.firstGreaterOrEqual(deviceQueueSubspace.range().begin),
endOfQueueKeyExclusive, database, messageGuidCodec, maxMessagesPerScan).getMessages())
.orElseGet(Flux::empty);
final KeySelector infinitePublisherBeginKey = maybeEndOfQueueKeyExclusive.orElseGet(
() -> KeySelector.firstGreaterOrEqual(deviceQueueSubspace.range().begin));
final Flux<MessageStreamEntry.Envelope> infinitePublisher = FoundationDbMessagePublisher.createInfinitePublisher(
infinitePublisherBeginKey, KeySelector.firstGreaterThan(deviceQueueSubspace.range().end),
database, messageGuidCodec, maxMessagesPerScan, messagesAvailableWatchKey).getMessages();
/// Create a message publisher
///
/// @return a Flux of {@link MessageStreamEntry} fetched from FoundationDB
/// @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() {
return createFoundationDbMessagePublisher()
.<FoundationDbMessageStreamEntry>handle((messageStreamEntry, sink) -> {
if (messageStreamEntry instanceof final FoundationDbMessageStreamEntry.Message message) {
try {
getAcknowledgedMessageBuffer(message.versionstamp()).addUnacknowledgedMessage(message.versionstamp());
} catch (final TooManyUnacknowledgedMessagesException e) {
sink.error(e);
return;
}
}
sink.next(messageStreamEntry);
})
.map(fdbMessageStreamEntry -> fdbMessageStreamEntry.toMessageStreamEntry(messageGuidCodec))
.doFinally(_ -> flushAllAcknowledgedMessages().thenRun(doAfterCleanup));
}
/// Create a message publisher that fetches messages from FoundationDB
///
/// @return a Flux of [FoundationDbMessageStreamEntry] fetched from FoundationDB
/// @implNote The message publisher is stitched together by concatenating:
/// 1. **A finite message publisher**: On initial request, we record the current end-of-queue key in the device mailbox.
/// Then, we fetch all messages in order until the recorded key and finally complete the stream
/// 2. **A queue-empty signal** is emitted
/// 3. **An infinite message publisher**: We start reading from where the finite publisher left off. When all messages
/// are read, we wait for new messages, publish them, then wait again in a loop forever (until the flux is canceled
/// explicitly or due to an error). This is accomplished by setting a FoundationDB [watch](https://github.com/apple/foundationdb/wiki/An-Overview-how-Watches-Work)
/// on [#messagesAvailableWatchKey] which is updated when a new message is available.
/// See [FoundationDbMessageStore] for more details on the message insert process.
private Flux<FoundationDbMessageStreamEntry> createFoundationDbMessagePublisher() {
// This may seem like an odd construction since it looks like we could also just do `Flux#fromArray`, but
// `Flux#fromArray` cannot handle `null` elements
final List<Database> databases = Arrays.stream(databasesByEpoch).filter(Objects::nonNull).distinct().toList();
return Flux.fromIterable(databases)
.flatMap(database -> Mono.fromFuture(getEndOfQueueKeyExclusive(database))
.map(maybeEndOfQueueKeyExclusive -> Tuples.of(database, maybeEndOfQueueKeyExclusive)))
.collectMap(Tuple2::getT1, Tuple2::getT2)
.flatMapMany(endOfQueueKeysByDatabase -> {
@SuppressWarnings("unchecked") final Flux<FoundationDbMessageStreamEntry.Message>[] finitePublishers =
endOfQueueKeysByDatabase.entrySet().stream()
.map(entry -> {
final Database database = entry.getKey();
final Optional<KeySelector> maybeEndOfQueueKeyExclusive = entry.getValue();
return maybeEndOfQueueKeyExclusive
.map(endOfQueueKeyExclusive -> FoundationDbMessagePublisher.createFinitePublisher(
KeySelector.firstGreaterOrEqual(deviceQueueSubspace.range().begin),
endOfQueueKeyExclusive,
database,
maxMessagesPerScan,
() -> this.clearAcknowledgedMessages(database))
.getMessages())
.orElseGet(Flux::empty)
.handle((fdbMessageStreamEntry, sink) -> {
// Ephemeral messages from the finite stream are considered stale and automatically discarded
if (fdbMessageStreamEntry.partialEnvelope().getEphemeral()) {
acknowledgedMessageBuffersByDatabase.get(database).acknowledgeStaleEphemeralMessage(fdbMessageStreamEntry.versionstamp());
staleEphemeralMessagesCounter.increment();
return;
}
sink.next(fdbMessageStreamEntry);
});
})
.toArray(Flux[]::new);
@SuppressWarnings("unchecked") final Flux<FoundationDbMessageStreamEntry.Message>[] infinitePublishers =
endOfQueueKeysByDatabase.entrySet().stream()
.map(entry -> {
final Database database = entry.getKey();
final Optional<KeySelector> maybeEndOfQueueKeyExclusive = entry.getValue();
final KeySelector infinitePublisherBeginKey = maybeEndOfQueueKeyExclusive
.orElseGet(() -> KeySelector.firstGreaterOrEqual(deviceQueueSubspace.range().begin));
return FoundationDbMessagePublisher.createInfinitePublisher(
infinitePublisherBeginKey,
KeySelector.firstGreaterThan(deviceQueueSubspace.range().end),
database,
maxMessagesPerScan,
messagesAvailableWatchKey,
() -> clearAcknowledgedMessages(database)).getMessages();
})
.toArray(Flux[]::new);
return Flux.concat(
finitePublisher,
Mono.just(new MessageStreamEntry.QueueEmpty()),
infinitePublisher
);
Flux.mergeComparing(maxMessagesPerScan, STREAM_ENTRY_TIMESTAMP_COMPARATOR, finitePublishers),
Mono.just(new FoundationDbMessageStreamEntry.QueueEmpty()),
// Note that we use `mergePriority` instead of `mergeComparing` for the "live"/non-terminating publishers
// because `mergePriority` sorts messages _as they arrive._ If we used `mergeComparing` for the live
// streams and one of the streams had no new messages (which will be true most of the time), then the
// merged publisher would never emit any signals because it'd be waiting to have something to compare
// against. This does mean that we risk some slightly out-of-order messages in the exceedingly rare cases
// where messages arrive at different servers while somebody is connected and a migration is in progress,
// but that should be (again) exceedingly rare and also minimally-disruptive (i.e. it would self-correct
// so quickly that end users would likely never even notice).
Flux.mergePriority(maxMessagesPerScan, STREAM_ENTRY_TIMESTAMP_COMPARATOR, infinitePublishers));
});
}
/// Gets a [KeySelector] for the first key greater than the current greatest key in the device queue. This allows
/// us to query keys up to and including the greatest key, and sets us up to begin reading from the next key in
/// a subsequent scan.
/// @return a [KeySelector] for the first key greater than the current greatest key in the device queue.
private CompletableFuture<Optional<KeySelector>> getEndOfQueueKeyExclusive() {
/// Gets a [KeySelector] for the first key greater than the current greatest key in the device queue. This allows us
/// to query keys up to and including the greatest key, and sets us up to begin reading from the next key in a
/// subsequent scan.
///
/// @return a [KeySelector] for the first key greater than the current greatest key in the device queue.
private CompletableFuture<Optional<KeySelector>> getEndOfQueueKeyExclusive(final Database database) {
return database.runAsync(
transaction -> transaction.getRange(deviceQueueSubspace.range(), 1, true, StreamingMode.EXACT).asList()
.thenApply(items -> {
@@ -97,7 +221,60 @@ public class FoundationDbMessageStream implements MessageStream {
}
@Override
public CompletableFuture<Void> acknowledgeMessage(final MessageProtos.Envelope message) {
throw new UnsupportedOperationException("Not implemented");
public CompletableFuture<Void> acknowledgeMessage(final UUID messageGuid, final long serverTimestamp) {
final Versionstamp versionstamp = messageGuidCodec.decodeMessageGuid(messageGuid);
getAcknowledgedMessageBuffer(versionstamp).acknowledgeMessage(versionstamp);
return CompletableFuture.completedFuture(null);
}
/// Clear the versionstamp range (startInclusive, endInclusive) in a single FoundationDB operation.
///
/// @param transaction The FoundationDB transaction in which to perform the range clear
/// @param startInclusive The starting versionstamp of the range to be cleared (inclusive)
/// @param endInclusive The ending versionstamp of the range to be cleared (inclusive)
private void clearRange(final Transaction transaction, final Versionstamp startInclusive, final Versionstamp endInclusive) {
final byte[] startKeyInclusive = deviceQueueSubspace.pack(Tuple.from(startInclusive));
final byte[] endKeyExclusive = ByteArrayUtil.keyAfter(deviceQueueSubspace.pack(Tuple.from(endInclusive)));
transaction.clear(startKeyInclusive, endKeyExclusive);
}
/// Clear all outstanding acknowledged messages. Called when the stream ends
private CompletableFuture<Void> flushAllAcknowledgedMessages() {
return CompletableFuture.allOf(Arrays.stream(databasesByEpoch)
.filter(Objects::nonNull)
.distinct()
.map(database -> {
final Consumer<Transaction> clearAllAcknowlegedMessagedConsumer = clearAcknowledgedMessages(database);
return database.runAsync(transaction -> {
clearAllAcknowlegedMessagedConsumer.accept(transaction);
return CompletableFuture.completedFuture((Void) null);
})
.whenComplete((_, throwable) -> {
if (throwable != null) {
LOGGER.warn("Failed to clear acknowledged messages", throwable);
}
});
})
.toArray(CompletableFuture[]::new));
}
private AcknowledgedMessageBuffer getAcknowledgedMessageBuffer(final Versionstamp versionstamp) {
final int epoch = FoundationDbMessageStore.getConfigurationEpoch(versionstamp);
final Database database = databasesByEpoch[epoch];
if (database == null) {
throw new IllegalStateException("Read message for unrecognized epoch");
}
return acknowledgedMessageBuffersByDatabase.get(database);
}
private synchronized Consumer<Transaction> clearAcknowledgedMessages(final Database database) {
final List<Pair<Versionstamp, Versionstamp>> flushableRanges =
acknowledgedMessageBuffersByDatabase.get(database).takeFlushableRanges();
return transaction -> flushableRanges.forEach(range -> clearRange(transaction, range.first(), range.second()));
}
}
Loaded 100 of 198 files, more files were not shown because too many files have changed in this diff. Show more