Compare commits

..
Author SHA1 Message Date
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
149 changed files with 4710 additions and 1986 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>
@@ -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
@@ -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",
@@ -505,7 +512,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,
@@ -696,7 +703,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,11 +737,11 @@ 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(),
dynamoDbClient,
@@ -982,18 +989,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()),
new PaymentsGrpcService(currencyManager))
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!
@@ -1013,7 +1033,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new ProfileAnonymousGrpcService(accountsManager, profilesManager, profileBadgeConverter, zkSecretParams),
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 +1098,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 +1155,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 +1166,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,
@@ -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();
@@ -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;
@@ -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,
@@ -66,6 +66,7 @@ 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;
@@ -497,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)) {
@@ -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());
}
@@ -13,7 +13,6 @@ import java.util.HexFormat;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;
import org.signal.chat.account.ClearRegistrationLockRequest;
import org.signal.chat.account.ClearRegistrationLockResponse;
import org.signal.chat.account.ConfigureUnidentifiedAccessRequest;
@@ -88,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 ->
@@ -169,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());
@@ -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,136 @@
/*
* 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.util.Map;
import org.signal.chat.credentials.ExternalServiceType;
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.auth.ServerZkAuthOperations;
import org.signal.libsignal.zkgroup.calllinks.CallLinkAuthCredentialResponse;
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();
}
}
@@ -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();
}
}
}
@@ -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())
@@ -93,20 +93,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,
///
@@ -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,273 @@
/*
* 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.micrometer.core.instrument.Metrics;
import java.time.Duration;
import java.util.UUID;
import javax.annotation.Nullable;
import org.signal.chat.messages.GetMessagesResponse;
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 GetMessagesResponse CONFLICTING_STREAM_RESPONSE = GetMessagesResponse.newBuilder()
.setTerminated(GetMessagesResponse.Terminated.newBuilder()
.setConflictingStream(Empty.getDefaultInstance()))
.build();
private static final GetMessagesResponse REAUTHENTICATION_REQUIRED_RESPONSE = GetMessagesResponse.newBuilder()
.setTerminated(GetMessagesResponse.Terminated.newBuilder()
.setReauthenticationRequired(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 emit a [GetMessagesResponse.Terminated] and then complete 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);
// 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 a Terminated response if we receive a disconnection request
disconnectionSignal(account, device))
.onErrorResume(ConflictingMessageConsumerException.class, _ -> Mono.just(CONFLICTING_STREAM_RESPONSE))
.takeUntil(response -> switch (response.getResponseCase()) {
case ENVELOPE, QUEUE_EMPTY -> false;
case TERMINATED -> {
messageMetrics.measureMessageStreamDisplaced(MessageMetrics.GRPC_CHANNEL, userAgent,
response.getTerminated().hasConflictingStream());
yield true;
}
case RESPONSE_NOT_SET -> throw new IllegalStateException("tried to return an invalid GetMessagesResponse");
})
.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 a [org.signal.chat.messages.GetMessagesResponse.Terminated] response if the
/// device receives a disconnection request
private Mono<GetMessagesResponse> disconnectionSignal(final Account account, final Device device) {
return Mono.create(sink -> {
final DisconnectionRequestListener listener = () -> sink.success(REAUTHENTICATION_REQUIRED_RESPONSE);
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;
});
@@ -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");
}
@@ -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;
}
};
}
}
@@ -1148,7 +1148,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
Pair<Account, Optional<Account>> getAccountsForChangeNumber(final UUID accountIdentifier, final String targetNumber) {
return new Pair<>(accounts.getByAccountIdentifier(accountIdentifier)
.orElseThrow(() -> new IllegalArgumentException("Account not found: " + accountIdentifier)),
accounts.getByE164(targetNumber));
accounts.getByPhoneNumberIdentifier(getPhoneNumberIdentifier(targetNumber)));
}
public UUID getPhoneNumberIdentifier(String e164) {
@@ -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,
@@ -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;
@@ -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) {
@@ -34,6 +34,7 @@ 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;
@@ -102,10 +103,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 +175,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),
@@ -275,7 +280,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());
}
}
@@ -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());
}
@@ -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()
@@ -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;
/**
@@ -175,38 +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());
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);
}
@@ -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);
}
}
@@ -5,13 +5,16 @@ 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.util.Pair;
import reactor.core.publisher.Flux;
import reactor.core.publisher.FluxSink;
import javax.annotation.Nullable;
import java.io.UncheckedIOException;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
@@ -287,7 +290,12 @@ class FoundationDbMessagePublisher {
final List<FoundationDbMessageStreamEntry.Message> messages = keyValues.stream()
.map(keyValue -> {
final Versionstamp versionstamp = FoundationDbMessageStore.getVersionstamp(keyValue.getKey());
return new FoundationDbMessageStreamEntry.Message(versionstamp, keyValue.getValue());
try {
return new FoundationDbMessageStreamEntry.Message(versionstamp, MessageProtos.Envelope.parseFrom(keyValue.getValue()));
} catch (final InvalidProtocolBufferException e) {
throw new UncheckedIOException(e);
}
})
.toList();
return new Pair<>(lastKeyRead, messages);
@@ -42,7 +42,6 @@ public class FoundationDbMessageStore {
private final Database[] databases;
private final VersionstampUUIDCipher versionstampUUIDCipher;
private final Executor executor;
private final Clock clock;
private static final Subspace MESSAGES_SUBSPACE = new Subspace(Tuple.from("M"));
@@ -64,12 +63,10 @@ public class FoundationDbMessageStore {
public FoundationDbMessageStore(final Database[] databases,
final VersionstampUUIDCipher versionstampUUIDCipher,
final Executor executor,
final Clock clock) {
this.databases = databases;
this.versionstampUUIDCipher = versionstampUUIDCipher;
this.executor = executor;
this.clock = clock;
}
@@ -243,7 +240,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();
@@ -258,7 +255,7 @@ public class FoundationDbMessageStore {
}
return presenceByDeviceId;
}, executor);
});
}
public MessageStream getMessages(final AciServiceIdentifier aci, final Device destinationDevice) {
@@ -1,31 +1,29 @@
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 java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.NavigableMap;
import java.util.Optional;
import java.util.TreeMap;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Flow;
import java.util.function.Consumer;
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.List;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Flow;
import java.util.function.Consumer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.storage.MessageStream;
import org.whispersystems.textsecuregcm.storage.MessageStreamEntry;
import org.whispersystems.textsecuregcm.util.Pair;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
import reactor.adapter.JdkFlowAdapter;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@@ -39,15 +37,11 @@ public class FoundationDbMessageStream implements MessageStream {
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 maximum number of unacknowledged messages we will send before closing the stream with an error
private final int maxUnacknowledgedMessages;
private final Flow.Publisher<MessageStreamEntry> messageStreamPublisher;
private final Runnable doAfterCleanup;
/// 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;
private final AcknowledgedMessageBuffer acknowledgedMessageBuffer;
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;
@@ -61,15 +55,15 @@ public class FoundationDbMessageStream implements MessageStream {
final int maxMessagesPerScan,
final int maxUnacknowledgedMessages,
final Runnable doAfterCleanup) {
this.deviceQueueSubspace = deviceQueueSubspace;
this.messagesAvailableWatchKey = messagesAvailableWatchKey;
this.database = database;
this.messageGuidCodec = messageGuidCodec;
this.maxMessagesPerScan = maxMessagesPerScan;
this.maxUnacknowledgedMessages = maxUnacknowledgedMessages;
this.messageStreamPublisher = JdkFlowAdapter.publisherToFlowPublisher(createMessagePublisher());
this.doAfterCleanup = doAfterCleanup;
this.acknowledgedMessageBuffer = new AcknowledgedMessageBuffer(maxUnacknowledgedMessages);
}
@Override
@@ -86,12 +80,14 @@ public class FoundationDbMessageStream implements MessageStream {
return createFoundationDbMessagePublisher()
.<FoundationDbMessageStreamEntry>handle((messageStreamEntry, sink) -> {
if (messageStreamEntry instanceof final FoundationDbMessageStreamEntry.Message message) {
final int numUnacknowledgedMessages = onVersionstampSent(message.versionstamp());
if (numUnacknowledgedMessages > maxUnacknowledgedMessages) {
sink.error(new TooManyUnacknowledgedMessagesException());
try {
acknowledgedMessageBuffer.addUnacknowledgedMessage(message.versionstamp());
} catch (final TooManyUnacknowledgedMessagesException e) {
sink.error(e);
return;
}
}
sink.next(messageStreamEntry);
})
.map(fdbMessageStreamEntry -> fdbMessageStreamEntry.toMessageStreamEntry(messageGuidCodec))
@@ -117,7 +113,16 @@ public class FoundationDbMessageStream implements MessageStream {
.map(endOfQueueKeyExclusive -> FoundationDbMessagePublisher.createFinitePublisher(
KeySelector.firstGreaterOrEqual(deviceQueueSubspace.range().begin),
endOfQueueKeyExclusive, database, maxMessagesPerScan, this::clearAcknowledgedMessages).getMessages())
.orElseGet(Flux::empty);
.orElseGet(Flux::empty)
.handle((fdbMessageStreamEntry, sink) -> {
// Ephemeral messages from the finite stream are considered stale and automatically discarded
if (fdbMessageStreamEntry.partialEnvelope().getEphemeral()) {
acknowledgedMessageBuffer.acknowledgeStaleEphemeralMessage(fdbMessageStreamEntry.versionstamp());
staleEphemeralMessagesCounter.increment();
return;
}
sink.next(fdbMessageStreamEntry);
});
final KeySelector infinitePublisherBeginKey = maybeEndOfQueueKeyExclusive.orElseGet(
() -> KeySelector.firstGreaterOrEqual(deviceQueueSubspace.range().begin));
final Flux<FoundationDbMessageStreamEntry.Message> infinitePublisher = FoundationDbMessagePublisher.createInfinitePublisher(
@@ -150,31 +155,12 @@ public class FoundationDbMessageStream implements MessageStream {
}
@Override
public CompletableFuture<Void> acknowledgeMessage(final MessageProtos.Envelope message) {
handleAcknowledged(messageGuidCodec.decodeMessageGuid(UUIDUtil.fromByteString(message.getServerGuidBinary())));
public CompletableFuture<Void> acknowledgeMessage(final UUID messageGuid, final long serverTimestamp) {
acknowledgedMessageBuffer.acknowledgeMessage(messageGuidCodec.decodeMessageGuid(messageGuid));
return CompletableFuture.completedFuture(null);
}
@VisibleForTesting
synchronized void handleAcknowledged(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);
}
/// Returns the number of unacknowledged messages after sending the provided versionstamp
///
/// @param versionstamp The versionstamp being sent
@VisibleForTesting
synchronized int onVersionstampSent(final Versionstamp versionstamp) {
sentVersionstamps.put(versionstamp, false);
return ++unacknowledgedMessages;
}
/// Clear the versionstamp range (startInclusive, endInclusive) in a single FoundationDB operation.
///
/// @param transaction The FoundationDB transaction in which to perform the range clear
@@ -201,45 +187,8 @@ public class FoundationDbMessageStream implements MessageStream {
}
private synchronized Consumer<Transaction> clearAcknowledgedMessages() {
final List<Pair<Versionstamp, Versionstamp>> flushableRanges = computeFlushableRanges();
flushableRanges.forEach(range -> sentVersionstamps.subMap(range.first(), true, range.second(), true).clear());
final List<Pair<Versionstamp, Versionstamp>> flushableRanges = acknowledgedMessageBuffer.takeFlushableRanges();
return transaction -> flushableRanges.forEach(range -> clearRange(transaction, range.first(), range.second()));
}
/// 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;
}
}
@@ -1,8 +1,6 @@
package org.whispersystems.textsecuregcm.storage.foundationdb;
import com.apple.foundationdb.tuple.Versionstamp;
import com.google.protobuf.InvalidProtocolBufferException;
import java.io.UncheckedIOException;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.storage.MessageStreamEntry;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
@@ -10,21 +8,16 @@ import org.whispersystems.textsecuregcm.util.UUIDUtil;
sealed interface FoundationDbMessageStreamEntry permits FoundationDbMessageStreamEntry.Message,
FoundationDbMessageStreamEntry.QueueEmpty {
record Message(Versionstamp versionstamp, byte[] payload) implements FoundationDbMessageStreamEntry {}
record Message(Versionstamp versionstamp, MessageProtos.Envelope partialEnvelope) implements FoundationDbMessageStreamEntry {}
record QueueEmpty() implements FoundationDbMessageStreamEntry {}
default MessageStreamEntry toMessageStreamEntry(final MessageGuidCodec messageGuidCodec) {
return switch (this) {
case Message(final Versionstamp versionstamp, final byte[] payload): {
try {
yield new MessageStreamEntry.Envelope(MessageProtos.Envelope.parseFrom(payload)
.toBuilder()
.setServerGuidBinary(UUIDUtil.toByteString(messageGuidCodec.encodeMessageGuid(versionstamp)))
.build());
} catch (final InvalidProtocolBufferException e) {
throw new UncheckedIOException(e);
}
case Message(final Versionstamp versionstamp, final MessageProtos.Envelope partialEnvelope): {
yield new MessageStreamEntry.Envelope(partialEnvelope.toBuilder()
.setServerGuid(UUIDUtil.toByteString(messageGuidCodec.encodeMessageGuid(versionstamp)))
.build());
}
case QueueEmpty():
yield new MessageStreamEntry.QueueEmpty();
@@ -5,5 +5,7 @@
package org.whispersystems.textsecuregcm.storage.foundationdb;
public class TooManyUnacknowledgedMessagesException extends RuntimeException {
import org.whispersystems.textsecuregcm.util.NoStackTraceException;
class TooManyUnacknowledgedMessagesException extends NoStackTraceException {
}
@@ -12,9 +12,7 @@ import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.ShortBufferException;
@@ -69,7 +67,9 @@ public class VersionstampUUIDCipher {
private static final int TWEAK_LENGTH = 17; // bytes
private static final byte ROUNDS = 10; // from FF1 specification
private static final IvParameterSpec IV_PARAMETERS = new IvParameterSpec(new byte[] {
private static final IvParameterSpec IV_PARAMETERS = new IvParameterSpec(new byte[16]);
private static final byte[] PARAMETERS_BLOCK = new byte[] {
0x01, // static value from FF1 specification
0x02, // static value from FF1 specification
0x01, // static value from FF1 specification
@@ -78,7 +78,7 @@ public class VersionstampUUIDCipher {
(VERSIONSTAMP_LENGTH * 8) / 2,
0x00, 0x00, 0x00, VERSIONSTAMP_LENGTH * 8, // for radix = 2, plaintext/ciphertext length in bits
0x00, 0x00, 0x00, TWEAK_LENGTH, // tweak length in bytes (not bits)
});
};
private static final long LEAST_SIGNIFICANT_SIX_BYTES_MASK = 0x0000_ffff_ffff_ffffL;
private static final byte FORMAT_VERSION_MASK = 0x0f;
@@ -213,26 +213,23 @@ public class VersionstampUUIDCipher {
final long b,
final byte[] bufferArray) {
try {
cipher.init(Cipher.ENCRYPT_MODE, key, IV_PARAMETERS);
} catch (final InvalidKeyException e) {
throw new AssertionError("Previously-valid key now invalid", e);
} catch (final InvalidAlgorithmParameterException e) {
throw new AssertionError("Previously-valid IV now invalid", e);
}
assert (b & ~LEAST_SIGNIFICANT_SIX_BYTES_MASK) == 0;
final ByteBuffer byteBuffer = ByteBuffer.wrap(bufferArray);
// Write the first part of cryptographic "tweak" into the buffer. We have one more byte (the device ID) that will
// "spill" over into the next block, but that's okay! That extra byte falls into the "padding zone" of the next
// block, and doesn't increase the overall block count per round.
byteBuffer
.putLong(0, accountIdentifier.getMostSignificantBits())
.putLong(8, accountIdentifier.getLeastSignificantBits());
try {
cipher.init(Cipher.ENCRYPT_MODE, key, IV_PARAMETERS);
// Every round begins with the parameters block. We haven't written any round-specific input into the provided
// buffer yet, so we can write the output of this update into the buffer without clobbering anything important.
cipher.update(PARAMETERS_BLOCK, 0, bufferArray.length, bufferArray);
// Write the first part of cryptographic "tweak" into the buffer, overwriting the output of the previous block (we
// don't need the output). We have one more byte (the device ID) that will "spill" over into the next block, but
// that's okay! That extra byte falls into the "padding zone" of the next block, and doesn't increase the overall
// block count per round.
final ByteBuffer byteBuffer = ByteBuffer.wrap(bufferArray)
.putLong(0, accountIdentifier.getMostSignificantBits())
.putLong(8, accountIdentifier.getLeastSignificantBits());
// We can overwrite the input buffer here to avoid allocating an additional 16-byte buffer that we'd just
// discard immediately
cipher.update(bufferArray, 0, bufferArray.length, bufferArray);
@@ -248,19 +245,16 @@ public class VersionstampUUIDCipher {
.putLong(8, b)
.put(9, round);
// Again, overwrite the input buffer to avoid an extra buffer allocation…
// Again, overwrite the input buffer to avoid an extra buffer allocation
cipher.update(bufferArray, 0, bufferArray.length, bufferArray);
// …and then overwrite the buffer once more with the cipher's finished output, which is the only AES-CBC output we
// actually use directly.
final int bytesWritten = cipher.doFinal(bufferArray, 0);
assert bytesWritten == 16;
return byteBuffer.getLong(0) & LEAST_SIGNIFICANT_SIX_BYTES_MASK;
} catch (final IllegalBlockSizeException | BadPaddingException e) {
throw new AssertionError("Every implementation of the Java platform is required to support AES/CBC/PKCS5Padding", e);
} catch (final ShortBufferException e) {
throw new AssertionError("Buffer with known length of 16 too short", e);
} catch (final InvalidAlgorithmParameterException e) {
throw new AssertionError("Previously-valid IV now invalid", e);
} catch (final InvalidKeyException e) {
throw new AssertionError("Previously-valid key now invalid", e);
}
}
@@ -269,9 +263,9 @@ public class VersionstampUUIDCipher {
/// @return a `Cipher` instance suitable for use in the core NIST/FF1 loop
private static Cipher getCipher() {
try {
return Cipher.getInstance("AES/CBC/PKCS5Padding");
return Cipher.getInstance("AES/CBC/NoPadding");
} catch (final NoSuchAlgorithmException | NoSuchPaddingException e) {
throw new AssertionError("Every implementation of the Java platform is required to support AES/CBC/PKCS5Padding", e);
throw new AssertionError("Every implementation of the Java platform is required to support AES/CBC/NoPadding", e);
}
}
@@ -0,0 +1,9 @@
package org.whispersystems.textsecuregcm.subscriptions;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialPresentation;
public interface ReceiptCredentialPresentationFactory {
ReceiptCredentialPresentation build(byte[] bytes) throws InvalidInputException;
}
@@ -0,0 +1,16 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.subscriptions;
public class SubscriptionReceiptAlreadyRedeemedException extends SubscriptionException {
public SubscriptionReceiptAlreadyRedeemedException() {
super(null, null);
}
public SubscriptionReceiptAlreadyRedeemedException(final String message) {
super(null, message);
}
}
@@ -0,0 +1,92 @@
/*
* Copyright 2025 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.util;
import com.google.common.annotations.VisibleForTesting;
import java.util.concurrent.atomic.AtomicInteger;
/**
* A closable epoch is a concurrency construct that measures the number of callers in some critical section. A closable
* epoch can be closed to prevent new callers from entering the critical section, and takes a specific action when the
* critical section is empty after closure.
*/
public class ClosableEpoch {
private final Runnable onCloseHandler;
private final AtomicInteger state = new AtomicInteger();
private static final int CLOSING_BIT_MASK = 0x00000001;
/**
* Constructs a new closable epoch that will execute the given handler when the epoch is closed and all callers have
* departed the critical section. The handler will be executed on the thread that calls {@link #close()} if the
* critical section is empty at the time of the call or on the last thread to call {@link #depart()} otherwise.
* Callers should provide handlers that delegate execution to a specific thread/executor if more precise control over
* which thread runs the handler is required.
*
* @param onCloseHandler a handler to run when the epoch is closed and all callers have departed the critical section
*/
public ClosableEpoch(final Runnable onCloseHandler) {
this.onCloseHandler = onCloseHandler;
}
/**
* Announces the arrival of a caller at the start of the critical section. If the caller is allowed to enter the
* critical section, the epoch's internal caller counter is incremented accordingly.
*
* @return {@code true} if the caller is allowed to enter the critical section or {@code false} if it is not allowed
* to enter the critical section because this epoch is closing
*/
public boolean tryArrive() {
// Increment the number of active callers if and only if we're not closing. We add 2 because the lowest bit encodes
// the "closing" state, and the bits above it encode the actual call count. More verbosely, we're doing
// `state += (1 << 1)` to avoid overwriting the closing state bit.
return !isClosing(state.updateAndGet(state -> isClosing(state) ? state : state + 2));
}
/**
* Announces the departure of a caller from the critical section. If the epoch is closing and the caller is the last
* to depart the critical section, then the epoch will fire its {@code onCloseHandler}.
*/
public void depart() {
// Decrement the active caller count unconditionally. As with `tryActive`, we work in increments of 2 to "dodge" the
// "is closing" bit. If the call count is zero and we're closing then `state` will just have the "closing" bit set.
if (state.addAndGet(-2) == CLOSING_BIT_MASK) {
onCloseHandler.run();
}
}
/**
* Closes this epoch, preventing new callers from entering the critical section. If the critical section is empty when
* this method is called, it will trigger the {@code onCloseHandler} immediately. Otherwise, the
* {@code onCloseHandler} will fire when the last caller departs the critical section.
*
* @throws IllegalStateException if this epoch is already closed; note that this exception is thrown on a
* "best-effort" basis to help callers detect bugs
*/
public void close() {
// Note that this is not airtight and is a "best-effort" check
if (isClosing(state.get())) {
throw new IllegalStateException("Epoch already closed");
}
// Set the "closing" bit. If the closing bit is the only bit set, then the call count is zero and we can call the
// "on close" handler.
if (state.updateAndGet(state -> state | CLOSING_BIT_MASK) == CLOSING_BIT_MASK) {
onCloseHandler.run();
}
}
@VisibleForTesting
int getActiveCallers() {
return state.get() >> 1;
}
private static boolean isClosing(final int state) {
return (state & CLOSING_BIT_MASK) != 0;
}
}
@@ -114,7 +114,7 @@ public class ProfileHelper {
.getDisallowedPrefixes().stream()
.anyMatch(prefix -> account.getNumber().startsWith(prefix));
return hasDisallowedPrefix && currentPaymentAddress.isEmpty();
return hasDisallowedPrefix && currentPaymentAddress.filter(a -> a.length != 0).isEmpty();
}
@Nullable
@@ -6,9 +6,11 @@
package org.whispersystems.textsecuregcm.util.ua;
import com.vdurmont.semver4j.Semver;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import javax.annotation.Nullable;
public class UserAgentUtil {
@@ -31,4 +33,12 @@ public class UserAgentUtil {
throw new UnrecognizedUserAgentException();
}
public static @Nullable UserAgent maybeParseUserAgentString(final String userAgentString) {
try {
return parseUserAgentString(userAgentString);
} catch (UnrecognizedUserAgentException e) {
return null;
}
}
}
@@ -15,6 +15,7 @@ import io.micrometer.core.instrument.Tags;
import io.micrometer.core.instrument.Timer;
import java.time.Duration;
import java.util.Collections;
import java.util.HexFormat;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
@@ -23,6 +24,7 @@ import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.LongAdder;
import javax.annotation.Nullable;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.jetty.util.StaticException;
import org.slf4j.Logger;
@@ -48,6 +50,9 @@ import org.whispersystems.textsecuregcm.storage.MessageStream;
import org.whispersystems.textsecuregcm.storage.MessageStreamEntry;
import org.whispersystems.textsecuregcm.storage.MessagesManager;
import org.whispersystems.textsecuregcm.util.HeaderUtils;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
import org.whispersystems.textsecuregcm.util.ua.UserAgent;
import org.whispersystems.textsecuregcm.util.ua.UserAgentUtil;
import org.whispersystems.websocket.WebSocketClient;
import org.whispersystems.websocket.WebSocketResourceProvider;
import org.whispersystems.websocket.messages.WebSocketResponseMessage;
@@ -59,30 +64,19 @@ import reactor.core.scheduler.Scheduler;
public class WebSocketConnection implements DisconnectionRequestListener {
private static final Counter sendMessageCounter = Metrics.counter(name(WebSocketConnection.class, "sendMessage"));
private static final Counter bytesSentCounter = Metrics.counter(name(WebSocketConnection.class, "bytesSent"));
private static final Counter sendFailuresCounter = Metrics.counter(name(WebSocketConnection.class, "sendFailures"));
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 String NON_SUCCESS_RESPONSE_COUNTER_NAME = name(WebSocketConnection.class,
"clientNonSuccessResponse");
private static final String SEND_MESSAGES_FLUX_NAME = MetricsUtil.name(WebSocketConnection.class,
"sendMessages");
private static final String SEND_MESSAGE_ERROR_COUNTER = MetricsUtil.name(WebSocketConnection.class,
"sendMessageError");
private static final String SEND_MESSAGE_DURATION_TIMER_NAME = name(WebSocketConnection.class, "sendMessageDuration");
private static final String STATUS_CODE_TAG = "status";
private static final String STATUS_MESSAGE_TAG = "message";
private static final String ERROR_TYPE_TAG = "errorType";
private static final String EXCEPTION_TYPE_TAG = "exceptionType";
private static final String CONNECTED_ELSEWHERE_TAG = "connectedElsewhere";
private static final Duration SLOW_DRAIN_THRESHOLD = Duration.ofSeconds(10);
@VisibleForTesting
static final int MESSAGE_PUBLISHER_LIMIT_RATE = 100;
@@ -106,7 +100,7 @@ public class WebSocketConnection implements DisconnectionRequestListener {
private final Device authenticatedDevice;
private final MessageStream messageStream;
private final WebSocketClient client;
private final Tags platformTag;
private final @Nullable UserAgent userAgent;
private final LongAdder sentMessageCounter = new LongAdder();
private final AtomicReference<Disposable> messageSubscription = new AtomicReference<>();
@@ -115,7 +109,8 @@ public class WebSocketConnection implements DisconnectionRequestListener {
private final ClientReleaseManager clientReleaseManager;
public WebSocketConnection(final ReceiptSender receiptSender,
public WebSocketConnection(
final ReceiptSender receiptSender,
final MessagesManager messagesManager,
final MessageMetrics messageMetrics,
final PushNotificationManager pushNotificationManager,
@@ -144,13 +139,13 @@ public class WebSocketConnection implements DisconnectionRequestListener {
this.messageStream =
messagesManager.getMessages(authenticatedAccount.getIdentifier(IdentityType.ACI), authenticatedDevice);
this.platformTag = Tags.of(UserAgentTagUtil.getPlatformTag(client.getUserAgent()));
this.userAgent = UserAgentUtil.maybeParseUserAgentString(client.getUserAgent());
}
public void start() {
pushNotificationManager.handleMessagesRetrieved(authenticatedAccount, authenticatedDevice, client.getUserAgent());
final long queueDrainStartNanos = System.nanoTime();
final Timer.Sample queueDrainStart = Timer.start();
final AtomicBoolean hasSentFirstMessage = new AtomicBoolean();
messageSubscription.set(JdkFlowAdapter.flowPublisherToFlux(messageStream.getMessages())
@@ -162,7 +157,7 @@ public class WebSocketConnection implements DisconnectionRequestListener {
// process messages before sending the "connected elsewhere" signal, and while that's ultimately not harmful,
// it's also not ideal.
.doOnError(ConflictingMessageConsumerException.class, _ -> {
Metrics.counter(DISPLACEMENT_COUNTER_NAME, platformTag.and(CONNECTED_ELSEWHERE_TAG, "true")).increment();
messageMetrics.measureMessageStreamDisplaced(MessageMetrics.WEBSOCKET_CHANNEL, userAgent, true);
client.close(4409, "Connected elsewhere");
})
.doOnNext(entry -> {
@@ -170,9 +165,9 @@ public class WebSocketConnection implements DisconnectionRequestListener {
if (hasSentFirstMessage.compareAndSet(false, true)) {
messageDeliveryLoopMonitor.recordDeliveryAttempt(authenticatedAccount.getIdentifier(IdentityType.ACI),
authenticatedDevice.getId(),
UUID.fromString(message.getServerGuid()),
UUIDUtil.fromByteString(message.getServerGuid()),
client.getUserAgent(),
"websocket");
MessageMetrics.WEBSOCKET_CHANNEL);
}
}
})
@@ -184,15 +179,7 @@ public class WebSocketConnection implements DisconnectionRequestListener {
.subscribe(
entry -> {
if (entry instanceof MessageStreamEntry.QueueEmpty) {
final Duration drainDuration = Duration.ofNanos(System.nanoTime() - queueDrainStartNanos);
Metrics.summary(INITIAL_QUEUE_LENGTH_DISTRIBUTION_NAME, platformTag).record(sentMessageCounter.sum());
Metrics.timer(INITIAL_QUEUE_DRAIN_TIMER_NAME, platformTag).record(drainDuration);
if (drainDuration.compareTo(SLOW_DRAIN_THRESHOLD) > 0) {
Metrics.counter(SLOW_QUEUE_DRAIN_COUNTER_NAME, platformTag).increment();
}
messageMetrics.measureQueueDrain(MessageMetrics.WEBSOCKET_CHANNEL, userAgent, sentMessageCounter.sum(), queueDrainStart);
client.sendRequest("PUT", "/api/v1/queue/empty",
Collections.singletonList(HeaderUtils.getTimestampHeader()), Optional.empty());
}
@@ -235,15 +222,31 @@ public class WebSocketConnection implements DisconnectionRequestListener {
private CompletableFuture<Void> sendMessage(final Envelope message) {
if (message.getStory() && !client.shouldDeliverStories()) {
return messageStream.acknowledgeMessage(message);
return messageStream.acknowledgeMessage(UUIDUtil.fromByteString(message.getServerGuid()), message.getServerTimestamp());
}
final Optional<byte[]> body = Optional.of(serializeMessage(message));
sendMessageCounter.increment();
sentMessageCounter.increment();
bytesSentCounter.increment(body.map(bytes -> bytes.length).orElse(0));
messageMetrics.measureAccountEnvelopeUuidMismatches(authenticatedAccount, message);
messageMetrics.measureMessageSent(body.map(bytes -> bytes.length).orElse(0));
// Retain only the parts of the message we need to avoid retaining the whole `Envelope` in memory longer than
// necessary
final UUID messageGuid = UUIDUtil.fromByteString(message.getServerGuid());
final long serverTimestamp = message.getServerTimestamp();
final long clientTimestamp = message.getClientTimestamp();
final boolean isUrgent = message.getUrgent();
final boolean isEphemeral = message.getEphemeral();
final ServiceIdentifier destinationServiceIdentifier =
ServiceIdentifier.fromByteString(message.getDestinationServiceId());
final boolean shouldSendDeliveryReceipt =
message.hasSourceServiceId() && message.getType() != Envelope.Type.SERVER_DELIVERY_RECEIPT;
// If the envelope has a source, and it is not a server delivery receipt, it will be an ACI.
@Nullable final AciServiceIdentifier sourceServiceIdentifier = shouldSendDeliveryReceipt
? AciServiceIdentifier.fromByteString(message.getSourceServiceId())
: null;
final Timer.Sample sample = Timer.start();
@@ -253,25 +256,32 @@ public class WebSocketConnection implements DisconnectionRequestListener {
if (throwable != null) {
sendFailuresCounter.increment();
} else {
messageMetrics.measureOutgoingMessageLatency(message.getServerTimestamp(),
"websocket",
messageMetrics.measureOutgoingMessageLatency(serverTimestamp,
MessageMetrics.WEBSOCKET_CHANNEL,
authenticatedDevice.isPrimary(),
message.getUrgent(),
message.getEphemeral(),
client.getUserAgent(),
isUrgent,
isEphemeral,
userAgent,
clientReleaseManager);
}
}).thenCompose(response -> {
final CompletableFuture<Void> result;
if (isSuccessResponse(response)) {
result = messageStream.acknowledgeMessage(message);
result = messageStream.acknowledgeMessage(messageGuid, serverTimestamp);
if (message.getType() != Envelope.Type.SERVER_DELIVERY_RECEIPT) {
sendDeliveryReceiptFor(message);
if (shouldSendDeliveryReceipt) {
try {
receiptSender.sendReceipt(destinationServiceIdentifier,
authenticatedDevice.getId(),
sourceServiceIdentifier,
clientTimestamp);
} catch (final Exception e) {
logger.warn("Failed to send receipt", e);
}
}
} else {
Tags tags = platformTag.and(STATUS_CODE_TAG, String.valueOf(response.getStatus()));
Tags tags = Tags.of(UserAgentTagUtil.getPlatformTag(userAgent), Tag.of(STATUS_CODE_TAG, String.valueOf(response.getStatus())));
// TODO Remove this once we've identified the cause of message rejections from desktop clients
if (StringUtils.isNotBlank(response.getMessage())) {
@@ -285,9 +295,7 @@ public class WebSocketConnection implements DisconnectionRequestListener {
return result;
})
.thenRun(() -> sample.stop(Timer.builder(SEND_MESSAGE_DURATION_TIMER_NAME)
.tags(platformTag)
.register(Metrics.globalRegistry)));
.thenRun(() -> messageMetrics.measureSendMessageDuration(MessageMetrics.WEBSOCKET_CHANNEL, userAgent, sample));
}
@VisibleForTesting
@@ -295,22 +303,6 @@ public class WebSocketConnection implements DisconnectionRequestListener {
return message.toBuilder().clearEphemeral().build().toByteArray();
}
private void sendDeliveryReceiptFor(Envelope message) {
if (!message.hasSourceServiceId()) {
return;
}
try {
receiptSender.sendReceipt(ServiceIdentifier.valueOf(message.getDestinationServiceId()),
authenticatedDevice.getId(), AciServiceIdentifier.valueOf(message.getSourceServiceId()),
message.getClientTimestamp());
} catch (final IllegalArgumentException e) {
logger.error("Could not parse UUID: {}", message.getSourceServiceId());
} catch (final Exception e) {
logger.warn("Failed to send receipt", e);
}
}
private static boolean isSuccessResponse(final WebSocketResponseMessage response) {
return response != null && response.getStatus() >= 200 && response.getStatus() < 300;
}
@@ -327,8 +319,10 @@ public class WebSocketConnection implements DisconnectionRequestListener {
errorType = "other";
}
Metrics.counter(SEND_MESSAGE_ERROR_COUNTER,
platformTag.and(ERROR_TYPE_TAG, errorType, EXCEPTION_TYPE_TAG, e.getClass().getSimpleName()))
Metrics.counter(SEND_MESSAGE_ERROR_COUNTER, Tags.of(
UserAgentTagUtil.getPlatformTag(userAgent),
Tag.of(ERROR_TYPE_TAG, errorType),
Tag.of(EXCEPTION_TYPE_TAG, e.getClass().getSimpleName())))
.increment();
}
@@ -342,7 +336,7 @@ public class WebSocketConnection implements DisconnectionRequestListener {
@Override
public void handleDisconnectionRequest() {
Metrics.counter(DISPLACEMENT_COUNTER_NAME, platformTag.and(CONNECTED_ELSEWHERE_TAG, "false")).increment();
messageMetrics.measureMessageStreamDisplaced(MessageMetrics.WEBSOCKET_CHANNEL, userAgent, false);
client.close(4401, "Reauthentication required");
}
}
@@ -68,7 +68,7 @@ public class ClearIssuedReceiptRedemptionsCommand extends AbstractCommandWithDep
throw new IllegalStateException("Cannot clear issued receipts for a non-IAP processor: " + processorType);
};
final SubscriptionPaymentProcessor.ReceiptItem receiptItem = processor.getReceiptItem(subscriber.subscriptionId);
final boolean deleted = issuedReceiptsManager.clearIssuance(receiptItem.itemId(), processorType).join();
final boolean deleted = issuedReceiptsManager.clearIssuance(receiptItem.itemId(), processorType);
logger.info("Deleted issuances for receiptItem: {}, subscriberId: {}, hadExistingIssuances: {}",
receiptItem.itemId(), subscriberId, deleted);
} catch (Exception ex) {
@@ -245,7 +245,7 @@ public record CommandDependencies(
MessagesDynamoDb messagesDynamoDb = new MessagesDynamoDb(dynamoDbClient, dynamoDbAsyncClient,
configuration.getDynamoDbTables().getMessages().getTableName(),
configuration.getDynamoDbTables().getMessages().getExpiration(),
messageDeletionExecutor, experimentEnrollmentManager);
messageDeletionExecutor);
FaultTolerantRedisClusterClient messagesCluster = configuration.getMessageCacheConfiguration()
.getRedisClusterConfiguration().build("messages", redisClientResourcesBuilder);
FaultTolerantRedisClusterClient rateLimitersCluster = configuration.getRateLimitersCluster().build("rate_limiters",
@@ -267,7 +267,7 @@ public record CommandDependencies(
DisconnectionRequestManager disconnectionRequestManager = new DisconnectionRequestManager(pubsubClient,
disconnectionRequestListenerExecutor, retryExecutor);
MessagesCache messagesCache = new MessagesCache(messagesCluster,
messageDeliveryScheduler, messageDeletionExecutor, retryExecutor, Clock.systemUTC(), experimentEnrollmentManager);
messageDeliveryScheduler, messageDeletionExecutor, retryExecutor, Clock.systemUTC());
ProfilesManager profilesManager = new ProfilesManager(profilesV1, profiles, cacheCluster, retryExecutor, asyncCdnS3Client,
configuration.getCdnConfiguration().bucket());
ReportMessageDynamoDb reportMessageDynamoDb = new ReportMessageDynamoDb(dynamoDbClient, dynamoDbAsyncClient,
@@ -320,7 +320,7 @@ public record CommandDependencies(
final IssuedReceiptsManager issuedReceiptsManager = new IssuedReceiptsManager(
configuration.getDynamoDbTables().getIssuedReceipts().getTableName(),
configuration.getDynamoDbTables().getIssuedReceipts().getExpiration(),
dynamoDbAsyncClient,
dynamoDbClient,
configuration.getDynamoDbTables().getIssuedReceipts().getGenerator(),
configuration.getDynamoDbTables().getIssuedReceipts().getmaxIssuedReceiptsPerPaymentId());
@@ -0,0 +1,117 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.workers;
import io.dropwizard.core.cli.Command;
import io.dropwizard.core.setup.Bootstrap;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import net.sourceforge.argparse4j.inf.Namespace;
import net.sourceforge.argparse4j.inf.Subparser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
public class CopyToS3Command extends Command {
private static final String SOURCE_URI_ARGUMENT = "sourceUri";
private static final String DESTINATION_BUCKET_ARGUMENT = "destinationBucket";
private static final String DESTINATION_FILENAME_ARGUMENT = "destinationFilename";
private static final String MINIMUM_EXPECTED_SIZE_ARGUMENT = "minimumExpectedSize";
private static final Logger logger = LoggerFactory.getLogger(CopyToS3Command.class);
public CopyToS3Command() {
super("copy-to-s3", "Copies a file from an HTTP source to an S3 bucket");
}
@Override
public void configure(final Subparser subparser) {
subparser.addArgument("--source")
.dest(SOURCE_URI_ARGUMENT)
.type(String.class)
.required(true)
.help("The source URI to copy");
subparser.addArgument("--destination-bucket")
.dest(DESTINATION_BUCKET_ARGUMENT)
.type(String.class)
.required(true)
.help("The destination S3 bucket");
subparser.addArgument("--destination-filename")
.dest(DESTINATION_FILENAME_ARGUMENT)
.type(String.class)
.required(true)
.help("The name of the destination file within the S3 bucket");
subparser.addArgument("--minimum-size")
.dest(MINIMUM_EXPECTED_SIZE_ARGUMENT)
.type(Integer.class)
.required(true)
.help("The minimum size of the source file in bytes; smaller files will not be copied");
}
@Override
public void run(final Bootstrap<?> bootstrap, final Namespace namespace) throws IOException, InterruptedException {
final URI sourceUri = URI.create(namespace.getString(SOURCE_URI_ARGUMENT));
final String destinationBucket = namespace.getString(DESTINATION_BUCKET_ARGUMENT);
final String destinationFilename = namespace.getString(DESTINATION_FILENAME_ARGUMENT);
final int minimumExpectedSizeInBytes = namespace.getInt(MINIMUM_EXPECTED_SIZE_ARGUMENT);
copyToS3(sourceUri, destinationBucket, destinationFilename, minimumExpectedSizeInBytes);
}
public static void copyToS3(final URI sourceUri,
final String s3Bucket,
final String filename,
final int minimumExpectedSize) throws IOException, InterruptedException {
final HttpRequest httpRequest = HttpRequest.newBuilder()
.uri(sourceUri)
.timeout(Duration.ofMinutes(1))
.GET()
.build();
try (final HttpClient httpClient = HttpClient.newBuilder()
.followRedirects(HttpClient.Redirect.NORMAL)
.build();
final S3Client s3Client = S3Client.builder().build()) {
final HttpResponse<byte[]> httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofByteArray());
if (httpResponse.statusCode() == 200) {
if (httpResponse.body().length < minimumExpectedSize) {
throw new IOException("Response body was below minimum: %d, %d"
.formatted(httpResponse.body().length, minimumExpectedSize));
}
final String contentType = httpResponse.headers().firstValue("Content-Type").orElse("application/octet-stream");
s3Client.putObject(PutObjectRequest.builder()
.bucket(s3Bucket)
.key(filename)
.contentType(contentType)
.contentLength((long) httpResponse.body().length)
.build(), RequestBody.fromBytes(httpResponse.body()));
logger.info("Copied {} bytes from {} to s3://{}/{}",
httpResponse.body().length,
httpRequest.uri(),
s3Bucket,
filename);
} else {
throw new IOException("Got a non-200 reply from source URI: " + httpResponse.statusCode());
}
}
}
}
+10 -9
View File
@@ -21,25 +21,26 @@ message Envelope {
PLAINTEXT_CONTENT = 8; // for decryption error receipts
}
reserved 9; // Formerly string server_guid;
reserved 11; // Formerly string source_service_id
reserved 13; // Formerly string destination_service_id
reserved 15; // Formerly string updated_pni;
optional Type type = 1;
optional string source_service_id = 11;
optional uint32 source_device = 7;
optional uint64 client_timestamp = 5;
optional bytes content = 8; // Contains an encrypted Content
optional string server_guid = 9;
optional uint64 server_timestamp = 10;
optional bool ephemeral = 12; // indicates that the message should not be persisted if the recipient is offline
optional string destination_service_id = 13;
optional bool urgent = 14 [default=true];
optional string updated_pni = 15;
optional bool story = 16; // indicates that the content is a story.
optional bytes report_spam_token = 17; // token sent when reporting spam
optional bytes shared_mrm_key = 18; // indicates content should be fetched from multi-recipient message datastore
optional bytes source_service_id_binary = 19; // service ID binary (i.e. 16 byte UUID for ACI, 1 byte prefix + 16 byte UUID for PNI)
optional bytes destination_service_id_binary = 20; // service ID binary (i.e. 16 byte UUID for ACI, 1 byte prefix + 16 byte UUID for PNI)
optional bytes server_guid_binary = 21; // 16-byte UUID
optional bytes updated_pni_binary = 22; // 16-byte UUID
// next: 22
optional bytes source_service_id = 19; // service ID binary (i.e. 16 byte UUID for ACI, 1 byte prefix + 16 byte UUID for PNI)
optional bytes destination_service_id = 20; // service ID binary (i.e. 16 byte UUID for ACI, 1 byte prefix + 16 byte UUID for PNI)
optional bytes server_guid = 21; // 16-byte UUID
optional bytes updated_pni = 22; // 16-byte UUID
// next: 23
}
message ProvisioningAddress {
@@ -1,11 +1,23 @@
# Chat gRPC API
Eventually, all chat protocol endpoints will be available via gRPC.
## Request metadata
Clients may provide headers for gRPC requests via [gRPC metadata](https://grpc.io/docs/guides/metadata/) which translates directly to HTTP/2 headers.
- Clients should provide a `User-Agent` header on all gRPC requests.
- Clients may provide an `Accept-Language` on any gRPC requests.
## Authentication
To authenticate for a specific signal account + device, clients may provide a [Basic authorization header](https://www.rfc-editor.org/info/rfc7617/)
on the request. The username must be the account identifier encoded in the 8-4-4-4-12 format followed by a '.'
character and then the device id serialized as a string.
All services either require or forbid providing authentication via an Authorization header. If the service is annotated
with the `require.auth` option `AUTH_ONLY_AUTHENTICATED`, all requests to the service must contain valid authentication
headers. If the service is annotated with the option `AUTH_ONLY_ANONYMOUS` the client must not provide an authorization
header. If provided, the request will fail with a `BAD_AUTHENTICATION` error.
## Errors
In the gRPC protocol all errors are at the request level. That is, errors are returned in response to individual requests and do not impact other H2 streams on the same connection nor terminate the connection.
@@ -132,17 +132,19 @@ message GetBackupAuthCredentialsResponse {
// to the account.
//
// To register an anonymous credential:
// 1. Set a backup-id on the authenticated channel via Backups::SetBackupId
// 2. Retrieve BackupAuthCredentials via Backups::GetBackupAuthCredentials
// 3. Generate a key pair and set the public key via
// BackupsAnonymous::SetPublicKey
//
// 1. Set a backup-id on the authenticated channel via Backups::SetBackupId
// 2. Retrieve BackupAuthCredentials via Backups::GetBackupAuthCredentials
// 3. Generate a key pair and set the public key via
// BackupsAnonymous::SetPublicKey
//
// Unless otherwise noted, requests for this service require a
// SignedPresentation, which includes:
// - a presentation generated from a BackupAuthCredential issued by
// GetBackupAuthCredentials
// - a signature of that presentation using the private key of a key pair
// previously set with SetPublicKey.
//
// - a presentation generated from a BackupAuthCredential issued by
// GetBackupAuthCredentials
// - a signature of that presentation using the private key of a key pair
// previously set with SetPublicKey.
service BackupsAnonymous {
option (require.auth) = AUTH_ONLY_ANONYMOUS;
@@ -9,23 +9,53 @@ option java_multiple_files = true;
package org.signal.chat.calling;
// Provides methods for getting credentials for one-on-one and group calls.
// Provides methods for getting credentials and relay options for one-on-one
// calls.
service Calling {
// Generates and returns TURN credentials for the caller.
rpc GetTurnCredentials(GetTurnCredentialsRequest) returns (GetTurnCredentialsResponse) {}
// Retrieves TURN credentials and relay options for one-on-one calls.
rpc GetCallingRelays(GetCallingRelaysRequest) returns (GetCallingRelaysResponse) {}
}
message GetTurnCredentialsRequest {}
message GetCallingRelaysRequest {}
message GetTurnCredentialsResponse {
// A username that can be presented to authenticate with a TURN server.
string username = 1;
message GetCallingRelaysResponse {
message HostnameUrlList {
// A collection of hostname-based TURN, TURNS, or STUN URLs a client can use
// to connect to a relay.
repeated string urls = 1;
}
// A password that can be presented to authenticate with a TURN server.
string password = 2;
message IpUrlList {
// A collection of IP-based TURN, TURNS, or STUN URLs a client can use to
// connect to a relay.
repeated string urls = 1;
// A list of TURN (or TURNS or STUN) servers where the provided credentials
// may be used.
repeated string urls = 3;
// A hostname clients must use to validate the relay's TLS certificate when
// connecting via an IP-based TURNS URL. May not be specified if `urls`
// contains no TURNS URLs.
optional string hostname = 2;
}
message Relay {
// A username that can be presented to authenticate with a TURN server.
string username = 1;
// A password that can be presented to authenticate with a TURN server.
string password = 2;
// The duration, in seconds, after which the included username and password
// will no longer be valid.
uint64 credential_ttl_seconds = 3;
// A collection of hostname-based URLs clients may use to connect to this
// relay.
optional HostnameUrlList hostname_urls = 4;
// A collection of IP-based URLs clients may use to connect to this relay.
optional IpUrlList ip_urls = 5;
}
// A collection of calling relays a client may use for one-on-one calls.
repeated Relay relays = 1;
}
@@ -0,0 +1,52 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
syntax = "proto3";
option java_multiple_files = true;
package org.signal.chat.challenge;
import "org/signal/chat/require.proto";
service Challenge {
option (require.auth) = AUTH_ONLY_AUTHENTICATED;
// Submit proof of a challenge completion
// Some server endpoints (the "send message" endpoint, for example) may return
// a response indicating the client must complete a challenge before continuing.
// Clients may use this endpoint to provide proof of a completed challenge.
// If successful, the client may then continue their original operation.
rpc HandleChallengeResponse(AnswerChallengeRequest) returns (AnswerChallengeResponse) {}
}
message AnswerChallengeRequest {
message AnswerPushChallengeRequest {
// The challenge string provided to the client via a push payload
string challenge = 1 [(require.nonEmpty) = true];
}
message AnswerCaptchaChallengeRequest {
// A string representing a solved captcha
// Example: signal-hcaptcha.30b01b46-d8c9-4c30-bbd7-9719acfe0c10.challenge.abcdefg1345
string captcha = 1 [(require.nonEmpty) = true];
}
// The opaque token id from the ChallengeRequired response returned by the
// server endpoint that requested the challenge
string token = 1 [(require.nonEmpty) = true];
oneof request {
AnswerPushChallengeRequest push = 2;
AnswerCaptchaChallengeRequest captcha = 3;
}
}
message AnswerChallengeResponse {
// Whether the challenge proof was accepted
bool success = 1;
}
@@ -11,20 +11,35 @@ import "org/signal/chat/require.proto";
package org.signal.chat.credentials;
// Provides methods for obtaining and verifying credentials for "external" services
// (i.e. services that are not a part of the chat server deployment).
// All methods of this service require authentication.
service ExternalServiceCredentials {
// Provides methods for obtaining and verifying credentials that allow an
// authenticated user to authenticate in another service or context without
// revealing their identity.
service Credentials {
// Generates and returns an external service credentials for the caller.
rpc GetExternalServiceCredentials(GetExternalServiceCredentialsRequest)
returns (GetExternalServiceCredentialsResponse) {}
// Generates a pair of delivery certificates that the holder can include to
// identify themselves to a message recipient (but not the server) in a
// sealed-sender message.
rpc GetDeliveryCertificate(GetDeliveryCertificateRequest)
returns (GetDeliveryCertificateResponse) {}
// Generates a set of zero-knowledge credentials for various group-related
// actions.
rpc GetGroupCredentials(GetGroupCredentialsRequest)
returns (GetGroupCredentialsResponse) {}
}
service ExternalServiceCredentialsAnonymous {
// Given a list of secure value recovery (SVR) service credentials and a phone number,
// checks, which of the provided credentials were generated by the user with the given phone number
// and have not yet expired.
// Provides methods for working with previously-generated credentials without
// revealing an association between the credentials and the caller's identity to
// the server.
service CredentialsAnonymous {
// Given a list of secure value recovery (SVR) service credentials and a phone
// number, checks and returns which of the provided credentials were generated
// by the user with the given phone number and have not yet expired.
rpc CheckSvrCredentials(CheckSvrCredentialsRequest)
returns (CheckSvrCredentialsResponse) {}
}
@@ -79,3 +94,51 @@ message CheckSvrCredentialsResponse {
map<string, AuthCheckResult> matches = 1;
}
message GetDeliveryCertificateRequest {
}
// A pair of message delivery certificates. The response unconditionally
// includes certificates with and without the caller's phone number so the
// server never learns anything about the caller's intent to share their phone
// number with their contacts.
message GetDeliveryCertificateResponse {
// A delivery receipt that includes the caller's phone number
bytes certificate_with_e164 = 1;
// A delivery receipt that does not include the caller's phone number
bytes certificate_without_e164 = 2;
}
message GetGroupCredentialsRequest {
// The earliest time for which to issue group credentials; must be aligned to
// a UTC day boundary and may be no more than one day in the past at the time
// of the call.
uint64 redemption_start_seconds = 1;
// The latest time for which to issue group credentials; must be aligned to a
// UTC day boundary and no more than seven days in the future at the time of
// the call.
uint64 redemption_end_seconds = 2;
}
message GetGroupCredentialsResponse {
// A zero-knowledge credential that may be redeemed at or up to one day after
// the given redemption time
message CredentialAndRedemptionTime {
bytes credential = 1;
uint64 redemption_time_seconds = 2;
}
// A collection of credentials allowing the holder to anonymously
// authenticate themselves for group-related actions
repeated CredentialAndRedemptionTime group_credentials = 1;
// A collection of credentials allowing the holder to read, update, and delete
// group call links
repeated CredentialAndRedemptionTime call_link_auth_credentials = 2;
// The phone number identifier for which the included credentials were
// generated
bytes pni = 3;
}
@@ -0,0 +1,45 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
syntax = "proto3";
option java_multiple_files = true;
package org.signal.chat.donations;
import "google/protobuf/empty.proto";
import "org/signal/chat/require.proto";
import "org/signal/chat/errors.proto";
import "org/signal/chat/tag.proto";
service Donations {
option (require.auth) = AUTH_ONLY_AUTHENTICATED;
// Redeem a receipt acquired from Subscriptions.CreateSubscriptionReceiptCredentials
// to add a badge to the account. After successful redemption, profile
// responses will include the corresponding badge (if configured as visible)
// until the expiration time on the receipt.
rpc RedeemReceipt(RedeemReceiptRequest) returns (RedeemReceiptResponse) {}
}
message RedeemReceiptRequest {
// Presentation of the ZK receipt acquired when the subscription was created
bytes receiptCredentialPresentation = 1 [(require.exactlySize) = 329];
// If true, the corresponding badge should be visible on the profile
bool visible = 2;
// If true, and the new badge is visible, it should be the primary badge on the profile
bool primary = 3;
}
message RedeemReceiptResponse {
oneof response {
// The receipt was successfully redeemed
google.protobuf.Empty success = 1;
// The provided presentation is invalid
errors.FailedZkAuthentication failed_authentication = 2 [(tag.reason) = "failed_authentication"];
// The receipt was already redeemed for a different account
errors.FailedPrecondition already_redeemed = 3 [(tag.reason) = "already_redeemed"];
}
}
@@ -16,6 +16,8 @@ import "org/signal/chat/require.proto";
import "org/signal/chat/errors.proto";
import "org/signal/chat/tag.proto";
import "TextSecure.proto";
// Provides methods for sending "unsealed sender" messages.
service Messages {
@@ -31,6 +33,69 @@ service Messages {
// Sends a "sync" message to all other devices linked to the authenticated
// sender's account.
rpc SendSyncMessage(SendSyncMessageRequest) returns (SendMessageAuthenticatedSenderResponse) {}
// Retrieve messages for the authenticated device. When the caller receives
// and successfully processes a message returned in a GetMessagesResponse they
// must send a corresponding GetMessagesRequest indicating that the message
// has been processed (an ack). Acks should only be sent for messages
// delivered via the currently open RPC.
//
// Only the first GetMessagesRequest may contain request parameters that
// configure the stream. The first request must not contain an ack.
//
// The server will keep the stream open until the client disconnects or the
// connection is displaced as indicated by a Terminated response.
rpc GetMessages(stream GetMessagesRequest) returns (stream GetMessagesResponse) {}
}
message GetMessagesRequest {
message GetMessageOptions {
// If present and true, the server will not deliver any messages with the
// story flag set. This flag may only be set on the first GetMessagesRequest
// sent from the client to the server in an RPC stream.
bool drop_stories = 1;
}
oneof request {
// Configuration options for the message stream. Required for the first
// request of the stream, forbidden on subsequent reqeusts.
GetMessageOptions options = 1;
// The server_guid of an envelope previously returned in a
// GetMessagesResponse that has been successfully processed by the caller.
// Forbidden on the first request of the stream, required on subsequent
// requests.
bytes server_guid_ack = 2;
}
}
message GetMessagesResponse {
// The reason why a GetMessages RPC is being closed by the server.
message Terminated {
oneof reason {
// The account's credentials have been updated and the caller must reauthenticate.
google.protobuf.Empty reauthentication_required = 1;
// Another caller has opened a GetMessages stream for the same device.
google.protobuf.Empty conflicting_stream = 2;
}
}
oneof response {
// A message. On successful receipt of an envelope the caller should ack
// the envelope by sending a GetMessagesRequest with the envelope's server
// guid. Acks should only be sent for envelopes received on the currently
// open RPC.
textsecure.Envelope envelope = 1;
// An indicator that all outstanding messages for the device have been
// drained and acked by the client. The stream will remain open and continue
// to deliver newly arrived messages.
google.protobuf.Empty queue_empty = 2;
// Indicates that the stream is about to be closed.
Terminated terminated = 3;
}
}
// Provides methods for sending "sealed sender" messages.
@@ -215,8 +215,9 @@ enum Auth {
}
// This is duplicated from common.proto because:
// 1. importing would be a circular dependency
// 2. the canonical declaration belongs there
//
// 1. importing would be a circular dependency
// 2. the canonical declaration belongs there
enum IdentityType {
IDENTITY_TYPE_UNSPECIFIED = 0;
IDENTITY_TYPE_ACI = 1;
@@ -38,6 +38,7 @@ import org.eclipse.jetty.websocket.client.WebSocketClient;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.params.ParameterizedTest;
@@ -63,6 +64,7 @@ import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
import software.amazon.awssdk.services.dynamodb.model.GetItemResponse;
import software.amazon.awssdk.services.dynamodb.model.PutItemRequest;
@Timeout(value = 1, unit = TimeUnit.MINUTES, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
@ExtendWith(DropwizardExtensionsSupport.class)
class WhisperServerServiceTest {
@@ -106,19 +108,20 @@ class WhisperServerServiceTest {
Client client = EXTENSION.client();
final Response ping = client.target(
try (final Response ping = client.target(
String.format("http://localhost:%d%s", EXTENSION.getAdminPort(), "/ping"))
.request("application/json")
.get();
.get()) {
assertEquals(200, ping.getStatus());
}
assertEquals(200, ping.getStatus());
final Response healthCheck = client.target(
try (final Response healthCheck = client.target(
String.format("http://localhost:%d%s", EXTENSION.getLocalPort(), "/health-check"))
.request("application/json")
.get();
assertEquals(200, healthCheck.getStatus());
.get()) {
assertEquals(200, healthCheck.getStatus());
}
}
@ParameterizedTest
@@ -162,15 +165,15 @@ class WhisperServerServiceTest {
// test unauthenticated rest
final long start = System.currentTimeMillis();
final Response whoami = EXTENSION.client().target(
"http://localhost:%d/v1/accounts/whoami".formatted(EXTENSION.getLocalPort())).request().get();
try (final Response whoami = EXTENSION.client().target(
"http://localhost:%d/v1/accounts/whoami".formatted(EXTENSION.getLocalPort())).request().get()) {
assertEquals(401, whoami.getStatus());
final List<Object> timestampValues = whoami.getHeaders().get(HeaderUtils.TIMESTAMP_HEADER.toLowerCase());
assertEquals(1, timestampValues.size());
final long whoamiTimestamp = Long.parseLong(timestampValues.getFirst().toString());
assertTrue(whoamiTimestamp >= start);
}
assertEquals(401, whoami.getStatus());
final List<Object> timestampValues = whoami.getHeaders().get(HeaderUtils.TIMESTAMP_HEADER.toLowerCase());
assertEquals(1, timestampValues.size());
final long whoamiTimestamp = Long.parseLong(timestampValues.getFirst().toString());
assertTrue(whoamiTimestamp >= start);
}
@Test
@@ -79,7 +79,7 @@ public class CaptchaCheckerTest {
final String input,
final String expectedToken,
final String siteKey,
final Action expectedAction) throws IOException {
final Action expectedAction) throws IOException, InvalidCaptchaArgumentException {
final CaptchaClient captchaClient = mockClient(PREFIX);
new CaptchaChecker(null, PREFIX -> captchaClient).verify(Optional.empty(), expectedAction, input, null, USER_AGENT);
verify(captchaClient, times(1)).verify(any(), eq(siteKey), eq(expectedAction), eq(expectedToken), any(), eq(USER_AGENT));
@@ -103,7 +103,7 @@ public class CaptchaCheckerTest {
}
@Test
public void choose() throws IOException {
public void choose() throws IOException, InvalidCaptchaArgumentException {
String ainput = String.join(SEPARATOR, PREFIX_A, CHALLENGE_SITE_KEY, "challenge", TOKEN);
String binput = String.join(SEPARATOR, PREFIX_B, CHALLENGE_SITE_KEY, "challenge", TOKEN);
final CaptchaClient a = mockClient(PREFIX_A);
@@ -134,13 +134,13 @@ public class CaptchaCheckerTest {
@MethodSource
public void badArgs(final String input) throws IOException {
final CaptchaClient cc = mockClient(PREFIX);
assertThrows(BadRequestException.class,
assertThrows(InvalidCaptchaArgumentException.class,
() -> new CaptchaChecker(null, prefix -> PREFIX.equals(prefix) ? cc : null).verify(Optional.of(ACI), Action.CHALLENGE, input, null, USER_AGENT));
}
@Test
public void testShortened() throws IOException {
public void testShortened() throws IOException, InvalidCaptchaArgumentException {
final CaptchaClient captchaClient = mockClient(PREFIX);
final ShortCodeExpander retriever = mock(ShortCodeExpander.class);
when(retriever.retrieve("abc")).thenReturn(Optional.of(TOKEN));
@@ -33,6 +33,7 @@ import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.captcha.InvalidCaptchaArgumentException;
import org.whispersystems.textsecuregcm.limits.RateLimitChallengeManager;
import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper;
import org.whispersystems.textsecuregcm.push.NotPushRegisteredException;
@@ -68,7 +69,7 @@ class ChallengeControllerTest {
when(accountsManager.getByAccountIdentifier(AuthHelper.VALID_UUID)).thenReturn(Optional.of(AuthHelper.VALID_ACCOUNT));
when(accountsManager.getByAccountIdentifier(AuthHelper.VALID_UUID_TWO)).thenReturn(Optional.of(AuthHelper.VALID_ACCOUNT_TWO));
when(challengeConstraintChecker.challengeConstraints(any(), any()))
when(challengeConstraintChecker.challengeConstraintsHttp(any(), any()))
.thenReturn(new ChallengeConstraints(true, Optional.empty()));
}
@@ -119,7 +120,8 @@ class ChallengeControllerTest {
@ParameterizedTest
@ValueSource(booleans = { true, false } )
void testHandleCaptcha(boolean hasThreshold) throws RateLimitExceededException, IOException {
void testHandleCaptcha(boolean hasThreshold)
throws RateLimitExceededException, IOException, InvalidCaptchaArgumentException {
final String captchaChallengeJson = """
{
"type": "captcha",
@@ -133,7 +135,7 @@ class ChallengeControllerTest {
if (hasThreshold) {
when(challengeConstraintChecker.challengeConstraints(any(), any()))
when(challengeConstraintChecker.challengeConstraintsHttp(any(), any()))
.thenReturn(new ChallengeConstraints(true, Optional.of(0.5F)));
}
final Response response = EXTENSION.target("/v1/challenge")
@@ -149,7 +151,7 @@ class ChallengeControllerTest {
}
@Test
void testHandleInvalidCaptcha() throws RateLimitExceededException, IOException {
void testHandleInvalidCaptcha() throws RateLimitExceededException, IOException, InvalidCaptchaArgumentException {
final String captchaChallengeJson = """
{
"type": "captcha",
@@ -170,7 +172,7 @@ class ChallengeControllerTest {
}
@Test
void testHandleCaptchaRateLimited() throws RateLimitExceededException, IOException {
void testHandleCaptchaRateLimited() throws RateLimitExceededException, IOException, InvalidCaptchaArgumentException {
final String captchaChallengeJson = """
{
"type": "captcha",
@@ -236,7 +238,7 @@ class ChallengeControllerTest {
@Test
void testRequestPushChallengeNotPermitted() {
when(challengeConstraintChecker.challengeConstraints(any(), any()))
when(challengeConstraintChecker.challengeConstraintsHttp(any(), any()))
.thenReturn(new ChallengeConstraints(false, Optional.empty()));
final Response response = EXTENSION.target("/v1/challenge/push")
@@ -249,7 +251,7 @@ class ChallengeControllerTest {
@Test
void testAnswerPushChallengeNotPermitted() {
when(challengeConstraintChecker.challengeConstraints(any(), any()))
when(challengeConstraintChecker.challengeConstraintsHttp(any(), any()))
.thenReturn(new ChallengeConstraints(false, Optional.empty()));
final String pushChallengeJson = """
Loaded 100 of 149 files, more files were not shown because too many files have changed in this diff. Show more