mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-11-30 01:26:50 +00:00
Compare commits
71
Commits
v20261021.0.0
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3ec51c1200 | ||
|
|
d0ef28cbfd | ||
|
|
cb8a3fb7d6 | ||
|
|
7ec705e616 | ||
|
|
9dfbb454d1 | ||
|
|
5de899da4b | ||
|
|
cbfc2720d5 | ||
|
|
0100901667 | ||
|
|
b3db95c3ea | ||
|
|
a9f87693ba | ||
|
|
b06709b63b | ||
|
|
99278dcd1f | ||
|
|
2d6eb7951a | ||
|
|
7e26b7fe0a | ||
|
|
2f955582a4 | ||
|
|
31bb5ff621 | ||
|
|
c21ad7a3aa | ||
|
|
4a48066d87 | ||
|
|
a0cdb5d3b6 | ||
|
|
3f1b678095 | ||
|
|
ffb821e344 | ||
|
|
d9bf32dd9c | ||
|
|
2fe70c89fa | ||
|
|
9d6589110e | ||
|
|
e67272033b | ||
|
|
0e7afd9f90 | ||
|
|
cbbfc3966a | ||
|
|
59f5adc934 | ||
|
|
67ab444604 | ||
|
|
5e44fbd4e9 | ||
|
|
8abb61ebe6 | ||
|
|
50634ae07e | ||
|
|
8d426b788d | ||
|
|
a57dd64196 | ||
|
|
451bbf1da9 | ||
|
|
358fb8e58a | ||
|
|
1a36eff391 | ||
|
|
cc487aa2ac | ||
|
|
21be842303 | ||
|
|
7af5bd4d2e | ||
|
|
f8e22ae674 | ||
|
|
a4a5c1bb29 | ||
|
|
2220f750dd | ||
|
|
27980ed25d | ||
|
|
ce75147186 | ||
|
|
9049a63038 | ||
|
|
d083eb0939 | ||
|
|
129cb9e765 | ||
|
|
5ed6c58c6b | ||
|
|
ecd881a280 | ||
|
|
ca7a105f15 | ||
|
|
8e37334d2a | ||
|
|
0e4ac57482 | ||
|
|
7df37fd815 | ||
|
|
db4ad89a5d | ||
|
|
56b7cdb179 | ||
|
|
b9cff94d24 | ||
|
|
685026dd39 | ||
|
|
fbb42763d9 | ||
|
|
d4467a1f6a | ||
|
|
718d5a60b1 | ||
|
|
faf9eff6e2 | ||
|
|
1a7be839cd | ||
|
|
e4c230fb75 | ||
|
|
b18e587093 | ||
|
|
f7e4f4b5db | ||
|
|
335c079f82 | ||
|
|
8edf3488f7 | ||
|
|
ad31cff2a4 | ||
|
|
9f146e6ad1 | ||
|
|
0688bdda6d |
No files matched your search
@@ -26,14 +26,8 @@ updates:
|
||||
# https://github.com/dropwizard/dropwizard/pull/11273
|
||||
- dependency-name: "ch.qos.logback:*"
|
||||
versions: [">=1.6.0"]
|
||||
# https://github.com/jetty/jetty.project/issues/15657
|
||||
- dependency-name: "org.eclipse.jetty:*"
|
||||
versions: ["<=12.1.14"]
|
||||
- dependency-name: "org.eclipse.jetty.ee10:*"
|
||||
versions: ["<=12.1.14"]
|
||||
|
||||
# Dependency convergence sentinels, pinned to specific versions
|
||||
- dependency-name: "tools.jackson.core:jackson-databind"
|
||||
- dependency-name: "com.squareup.okio:okio-jvm"
|
||||
|
||||
groups:
|
||||
|
||||
@@ -18,7 +18,7 @@ jobs:
|
||||
# setup-java requires gpg
|
||||
sudo apt-get install -y protobuf-compiler gpg
|
||||
pip install sabledocs
|
||||
- uses: actions/setup-java@de7274f081f381c8f8158605e0321c36c376e2e6 # v6.0.1
|
||||
- uses: actions/setup-java@d1374f8ac74474200d16ef8ecee22c7ae7a51880 # v6.3.0
|
||||
with:
|
||||
distribution: 'temurin'
|
||||
java-version-file: .java-version
|
||||
|
||||
@@ -25,7 +25,7 @@ jobs:
|
||||
# setup-java requires gpg
|
||||
sudo apt update
|
||||
sudo apt install -y gpg
|
||||
- uses: actions/setup-java@de7274f081f381c8f8158605e0321c36c376e2e6 # v6.0.1
|
||||
- uses: actions/setup-java@d1374f8ac74474200d16ef8ecee22c7ae7a51880 # v6.3.0
|
||||
with:
|
||||
distribution: 'temurin'
|
||||
java-version-file: .java-version
|
||||
|
||||
@@ -50,7 +50,7 @@ jobs:
|
||||
# ca-certificates: required for AWS CRT client
|
||||
apt update && apt install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin ca-certificates
|
||||
- name: Set up JDK
|
||||
uses: actions/setup-java@de7274f081f381c8f8158605e0321c36c376e2e6 # v6.0.1
|
||||
uses: actions/setup-java@d1374f8ac74474200d16ef8ecee22c7ae7a51880 # v6.3.0
|
||||
with:
|
||||
distribution: 'temurin'
|
||||
java-version-file: .java-version
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
temurin-26
|
||||
temurin-27
|
||||
@@ -8,6 +8,7 @@ package org.signal.integration;
|
||||
import static java.util.Objects.requireNonNull;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.google.common.io.Resources;
|
||||
import com.google.common.net.HttpHeaders;
|
||||
import com.webauthn4j.data.AuthenticatorAssertionResponse;
|
||||
@@ -20,6 +21,7 @@ import com.webauthn4j.data.client.challenge.DefaultChallenge;
|
||||
import com.webauthn4j.test.client.ClientPlatform;
|
||||
import io.dropwizard.configuration.ConfigurationValidationException;
|
||||
import io.dropwizard.jersey.validation.Validators;
|
||||
import io.github.resilience4j.retry.Retry;
|
||||
import io.grpc.ChannelCredentials;
|
||||
import io.grpc.ClientInterceptor;
|
||||
import io.grpc.Grpc;
|
||||
@@ -51,11 +53,15 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import javax.annotation.Nullable;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.commons.lang3.Validate;
|
||||
import org.apache.commons.lang3.exception.ExceptionUtils;
|
||||
import org.apache.commons.lang3.tuple.Pair;
|
||||
import org.eclipse.jetty.client.HttpClient;
|
||||
import org.eclipse.jetty.client.Request;
|
||||
@@ -63,6 +69,7 @@ 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.api.exceptions.UpgradeException;
|
||||
import org.eclipse.jetty.websocket.client.ClientUpgradeRequest;
|
||||
import org.eclipse.jetty.websocket.client.WebSocketClient;
|
||||
import org.signal.integration.config.Config;
|
||||
@@ -83,6 +90,7 @@ import org.signal.libsignal.zkgroup.receipts.ReceiptSerial;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.RequireAuthenticationInterceptor;
|
||||
import org.whispersystems.textsecuregcm.configuration.RetryConfiguration;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountIdentityResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.DeviceActivationRequest;
|
||||
@@ -96,6 +104,7 @@ import org.whispersystems.textsecuregcm.storage.TotpManager;
|
||||
import org.whispersystems.textsecuregcm.util.CertificateUtil;
|
||||
import org.whispersystems.textsecuregcm.util.HeaderUtils;
|
||||
import org.whispersystems.textsecuregcm.util.HttpUtils;
|
||||
import org.whispersystems.textsecuregcm.util.ResilienceUtil;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
import org.whispersystems.textsecuregcm.util.ThrowingSupplier;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
@@ -114,14 +123,29 @@ public final class Operations {
|
||||
|
||||
private static final FaultTolerantHttpClient CLIENT = buildClient();
|
||||
|
||||
private static final FaultTolerantHttpClient NO_RETRY_CLIENT = buildNoRetryClient();
|
||||
|
||||
private static final WebSocketClient WEB_SOCKET_CLIENT = buildWebSocketClient();
|
||||
|
||||
private static final ManagedChannel GRPC_CHANNEL = buildGrpcChannel();
|
||||
|
||||
private static final Retry WEBSOCKET_CONNECT_RETRY = Retry.of("integration-test-websocket-connect",
|
||||
new RetryConfiguration().toRetryConfigBuilder()
|
||||
.retryOnException(Operations::isRetryableConnectFailure)
|
||||
.build());
|
||||
private Operations() {
|
||||
// utility class
|
||||
}
|
||||
|
||||
static boolean isRetryableConnectFailure(final Throwable e) {
|
||||
final Throwable cause = e instanceof ExecutionException ? e.getCause() : e;
|
||||
if (cause instanceof UpgradeException upgradeException) {
|
||||
return upgradeException.getResponseStatusCode() >= 500
|
||||
|| ExceptionUtils.getRootCause(upgradeException) instanceof TimeoutException;
|
||||
}
|
||||
return cause instanceof IOException;
|
||||
}
|
||||
|
||||
public record Receipt(ReceiptSerial serial, ReceiptCredential credential) {}
|
||||
|
||||
public static Receipt getPrescribedReceipt() throws InvalidInputException {
|
||||
@@ -237,50 +261,66 @@ public final class Operations {
|
||||
Optional.empty()));
|
||||
|
||||
// we expect (and need) failure with status 441, which will contain the WebAuthn challenge
|
||||
final MfaFailureExceptionMapper.MfaFailureResponse mfaFailureResponse = apiPost("/v1/registration", initialRequest)
|
||||
MfaFailureExceptionMapper.MfaFailureResponse mfaFailureResponse = apiPost("/v1/registration", initialRequest)
|
||||
// For a numberless account recovery, the username is the ACI
|
||||
.authorized(testUser.aciUuid().toString(), testUser.accountPassword())
|
||||
.executeExpectStatusCode(441, MfaFailureExceptionMapper.MfaFailureResponse.class);
|
||||
|
||||
Validate.isTrue(mfaFailureResponse.webAuthnParameters().allowedCredentialIds()
|
||||
.stream()
|
||||
.anyMatch(allowedId -> Arrays.equals(allowedId, credentialId)),
|
||||
"Expected MFA failure to contain credentialId");
|
||||
// Retry a 441 to 3 times. It's possible we burned a challenge on a 500 that actually succeeded, but we didn't see
|
||||
// the response, so we can retry on the new challenge.
|
||||
int attempt = 0;
|
||||
while (true) {
|
||||
attempt++;
|
||||
Validate.isTrue(mfaFailureResponse.webAuthnParameters().allowedCredentialIds()
|
||||
.stream()
|
||||
.anyMatch(allowedId -> Arrays.equals(allowedId, credentialId)),
|
||||
"Expected MFA failure to contain credentialId");
|
||||
|
||||
final PublicKeyCredential<AuthenticatorAssertionResponse, ?> credential =
|
||||
clientPlatform.get(new PublicKeyCredentialRequestOptions(
|
||||
new DefaultChallenge(mfaFailureResponse.webAuthnParameters().challenge()),
|
||||
null,
|
||||
relyingPartyId,
|
||||
List.of(new PublicKeyCredentialDescriptor(PublicKeyCredentialType.PUBLIC_KEY, credentialId, null)),
|
||||
UserVerificationRequirement.DISCOURAGED,
|
||||
null));
|
||||
final PublicKeyCredential<AuthenticatorAssertionResponse, ?> credential =
|
||||
clientPlatform.get(new PublicKeyCredentialRequestOptions(
|
||||
new DefaultChallenge(mfaFailureResponse.webAuthnParameters().challenge()),
|
||||
null,
|
||||
relyingPartyId,
|
||||
List.of(new PublicKeyCredentialDescriptor(PublicKeyCredentialType.PUBLIC_KEY, credentialId, null)),
|
||||
UserVerificationRequirement.DISCOURAGED,
|
||||
null));
|
||||
|
||||
final RegistrationRequest registrationRequest = new RegistrationRequest(null,
|
||||
testUser.registrationPassword(),
|
||||
null,
|
||||
null,
|
||||
webAuthnVerificationResponseJson(credential),
|
||||
recoveredUser.accountAttributes(),
|
||||
true,
|
||||
new IdentityKey(aciIdentityKeyPair.getPublicKey()),
|
||||
new IdentityKey(pniIdentityKeyPair.getPublicKey()),
|
||||
new DeviceActivationRequest(generateSignedECPreKey(1, aciIdentityKeyPair),
|
||||
Optional.of(generateSignedECPreKey(2, pniIdentityKeyPair)),
|
||||
generateSignedKEMPreKey(3, aciIdentityKeyPair),
|
||||
Optional.of(generateSignedKEMPreKey(4, pniIdentityKeyPair)),
|
||||
Optional.empty(),
|
||||
Optional.empty()));
|
||||
final RegistrationRequest registrationRequest = new RegistrationRequest(null,
|
||||
testUser.registrationPassword(),
|
||||
null,
|
||||
null,
|
||||
webAuthnVerificationResponseJson(credential),
|
||||
recoveredUser.accountAttributes(),
|
||||
true,
|
||||
new IdentityKey(aciIdentityKeyPair.getPublicKey()),
|
||||
new IdentityKey(pniIdentityKeyPair.getPublicKey()),
|
||||
new DeviceActivationRequest(generateSignedECPreKey(1, aciIdentityKeyPair),
|
||||
Optional.of(generateSignedECPreKey(2, pniIdentityKeyPair)),
|
||||
generateSignedKEMPreKey(3, aciIdentityKeyPair),
|
||||
Optional.of(generateSignedKEMPreKey(4, pniIdentityKeyPair)),
|
||||
Optional.empty(),
|
||||
Optional.empty()));
|
||||
|
||||
final AccountIdentityResponse registrationResponse = apiPost("/v1/registration", registrationRequest)
|
||||
// For a numberless account recovery, the username is the ACI
|
||||
.authorized(testUser.aciUuid().toString(), testUser.accountPassword())
|
||||
.executeExpectSuccess(AccountIdentityResponse.class);
|
||||
final Pair<Integer, JsonNode> registrationResponse = apiPost("/v1/registration", registrationRequest)
|
||||
// For a numberless account recovery, the username is the ACI
|
||||
.authorized(testUser.aciUuid().toString(), testUser.accountPassword())
|
||||
.execute(JsonNode.class);
|
||||
|
||||
recoveredUser.setAciUuid(registrationResponse.uuid());
|
||||
return recoveredUser;
|
||||
if (registrationResponse.getLeft() == 441 && attempt < 3) {
|
||||
mfaFailureResponse = SystemMapper.jsonMapper()
|
||||
.convertValue(registrationResponse.getRight(), MfaFailureExceptionMapper.MfaFailureResponse.class);
|
||||
continue;
|
||||
}
|
||||
|
||||
Validate.isTrue(HttpUtils.isSuccessfulResponse(registrationResponse.getLeft()),
|
||||
"Unexpected response code: %d, body: %s", registrationResponse.getLeft(), registrationResponse.getRight());
|
||||
recoveredUser.setAciUuid(SystemMapper.jsonMapper()
|
||||
.convertValue(registrationResponse.getRight(), AccountIdentityResponse.class).uuid());
|
||||
return recoveredUser;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static TestUser newRegisteredUser(final String number) {
|
||||
final byte[] registrationPassword = populateRandomRecoveryPassword(number);
|
||||
final String accountPassword = Base64.getEncoder().encodeToString(randomBytes(32));
|
||||
@@ -327,7 +367,24 @@ public final class Operations {
|
||||
}
|
||||
|
||||
public static void deleteUser(final TestUser user) {
|
||||
apiDelete("/v1/accounts/me").authorized(user).executeExpectSuccess();
|
||||
final AtomicInteger attempts = new AtomicInteger();
|
||||
final Retry retry = Retry.of("integration-test-delete-user",
|
||||
new RetryConfiguration().<Integer>toRetryConfigBuilder()
|
||||
.retryOnResult(statusCode -> statusCode >= 500)
|
||||
.build());
|
||||
final int statusCode = retry.executeSupplier(() -> {
|
||||
attempts.incrementAndGet();
|
||||
return apiDelete("/v1/accounts/me")
|
||||
.authorized(user)
|
||||
// disable retries, since this endpoint is not idempotent
|
||||
.withoutRetries()
|
||||
.execute()
|
||||
.getLeft();
|
||||
});
|
||||
|
||||
// If we had to retry a 500 where the account was already deleted, we would fail authorization
|
||||
Validate.isTrue(HttpUtils.isSuccessfulResponse(statusCode) || (attempts.get() > 1 && statusCode == 401),
|
||||
"Unexpected response code: %d", statusCode);
|
||||
}
|
||||
|
||||
public static String peekVerificationSessionPushChallenge(final String sessionId) {
|
||||
@@ -443,6 +500,15 @@ public final class Operations {
|
||||
final ChannelCredentials credentials = TlsChannelCredentials.newBuilder().trustManager(rootCertInputStream).build();
|
||||
return Grpc.newChannelBuilderForAddress(GRPC_DOMAIN, 443, credentials)
|
||||
.userAgent(USER_AGENT)
|
||||
.defaultServiceConfig(Map.of("methodConfig", List.of(Map.of(
|
||||
"name", List.of(Map.of()),
|
||||
"retryPolicy", Map.of(
|
||||
"maxAttempts", 3.0,
|
||||
"initialBackoff", "0.5s",
|
||||
"maxBackoff", "2s",
|
||||
"backoffMultiplier", 2.0,
|
||||
"retryableStatusCodes", List.of("UNAVAILABLE"))))))
|
||||
.enableRetry()
|
||||
.build();
|
||||
} catch (final IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
@@ -457,6 +523,7 @@ public final class Operations {
|
||||
|
||||
private final List<String> queryParams = new ArrayList<>();
|
||||
|
||||
private boolean retryServerErrors = true;
|
||||
|
||||
private RequestBuilder(final HttpRequest.Builder builder, final String endpoint) {
|
||||
this.builder = builder;
|
||||
@@ -494,6 +561,12 @@ public final class Operations {
|
||||
return this;
|
||||
}
|
||||
|
||||
/// Don't automatically retry 5xx responses, for requests that aren't safe to blindly retry
|
||||
public RequestBuilder withoutRetries() {
|
||||
retryServerErrors = false;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Pair<Integer, Void> execute() {
|
||||
return execute(Void.class);
|
||||
}
|
||||
@@ -543,7 +616,8 @@ public final class Operations {
|
||||
private RawResponse executeRaw() {
|
||||
builder.uri(serverUri(endpoint, queryParams))
|
||||
.header(HttpHeaders.USER_AGENT, USER_AGENT);
|
||||
return CLIENT.sendAsync(builder.build(), HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8))
|
||||
return (retryServerErrors ? CLIENT : NO_RETRY_CLIENT)
|
||||
.sendAsync(builder.build(), HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8))
|
||||
.whenComplete((response, error) -> {
|
||||
if (error != null) {
|
||||
logger.error("request error", error);
|
||||
@@ -572,7 +646,23 @@ public final class Operations {
|
||||
|
||||
private static FaultTolerantHttpClient buildClient() {
|
||||
try {
|
||||
return FaultTolerantHttpClient.newBuilder("integration-test", Executors.newFixedThreadPool(16))
|
||||
final FaultTolerantHttpClient client = FaultTolerantHttpClient.newBuilder("integration-test", Executors.newFixedThreadPool(16))
|
||||
.withTrustedServerCertificates(CONFIG.rootCerts().toArray(String[]::new))
|
||||
.withRetry(null, Executors.newSingleThreadScheduledExecutor())
|
||||
.build();
|
||||
// FaultTolerantHttpClient doesn't expose its Retry; it's the only one registered in this JVM
|
||||
ResilienceUtil.getRetryRegistry().getAllRetries().forEach(retry -> retry.getEventPublisher()
|
||||
.onRetry(event -> logger.warn("Retrying {} after {} failed attempt(s)",
|
||||
event.getName(), event.getNumberOfRetryAttempts(), event.getLastThrowable())));
|
||||
return client;
|
||||
} catch (final CertificateException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private static FaultTolerantHttpClient buildNoRetryClient() {
|
||||
try {
|
||||
return FaultTolerantHttpClient.newBuilder("integration-test-no-retry", Executors.newFixedThreadPool(16))
|
||||
.withTrustedServerCertificates(CONFIG.rootCerts().toArray(String[]::new))
|
||||
.build();
|
||||
} catch (final CertificateException e) {
|
||||
@@ -625,16 +715,19 @@ public final class Operations {
|
||||
|
||||
final URI uri = URI.create("wss://" + GRPC_DOMAIN + path);
|
||||
final ClientUpgradeRequest request = new ClientUpgradeRequest(uri);
|
||||
request.setTimeout(5, TimeUnit.SECONDS);
|
||||
headers.forEach(request::setHeader);
|
||||
|
||||
final WebsocketClientSession listener = new WebsocketClientSession();
|
||||
try {
|
||||
WEB_SOCKET_CLIENT.connect(listener, request).get(5, TimeUnit.SECONDS);
|
||||
return WEBSOCKET_CONNECT_RETRY.executeCallable(() -> {
|
||||
final WebsocketClientSession session = new WebsocketClientSession();
|
||||
WEB_SOCKET_CLIENT.connect(session, request).get();
|
||||
logger.info("Successfully connected to websocket on {}", uri);
|
||||
return session;
|
||||
});
|
||||
} catch (Exception e) {
|
||||
throw new IOException(e);
|
||||
}
|
||||
logger.info("Successfully connected to websocket on {}", uri);
|
||||
return listener;
|
||||
}
|
||||
|
||||
private static Config loadConfigFromClasspath(final String filename) {
|
||||
|
||||
+20
-12
@@ -5,6 +5,7 @@
|
||||
package org.signal.integration;
|
||||
|
||||
import com.google.protobuf.InvalidProtocolBufferException;
|
||||
import io.github.resilience4j.retry.Retry;
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.ByteBuffer;
|
||||
@@ -19,6 +20,7 @@ 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.configuration.RetryConfiguration;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
import org.whispersystems.websocket.messages.WebSocketMessage;
|
||||
@@ -30,6 +32,10 @@ import org.whispersystems.websocket.messages.protobuf.ProtobufWebSocketMessageFa
|
||||
public class WebsocketClientSession implements Session.Listener.AutoDemanding {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(WebsocketClientSession.class);
|
||||
private static final Retry REQUEST_RETRY = Retry.of("integration-test-websocket-request",
|
||||
new RetryConfiguration().<WebSocketResponseMessage>toRetryConfigBuilder()
|
||||
.retryOnResult(response -> response.getStatus() >= 500)
|
||||
.build());
|
||||
private final WebSocketMessageFactory messageFactory = new ProtobufWebSocketMessageFactory();
|
||||
private final AtomicLong requestId = new AtomicLong();
|
||||
private final ConcurrentHashMap<Long, CompletableFuture<WebSocketResponseMessage>> responseFutures = new ConcurrentHashMap<>();
|
||||
@@ -95,18 +101,20 @@ public class WebsocketClientSession implements Session.Listener.AutoDemanding {
|
||||
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();
|
||||
return REQUEST_RETRY.executeSupplier(() -> {
|
||||
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() {
|
||||
|
||||
@@ -66,6 +66,7 @@ import org.signal.libsignal.usernames.BaseUsernameException;
|
||||
import org.signal.libsignal.usernames.Username;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.VerificationFailedException;
|
||||
import org.signal.libsignal.zkgroup.internal.ByteArray;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountIdentifierResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountIdentityResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.ChangeNumberRequest;
|
||||
@@ -289,7 +290,10 @@ public class AccountTest {
|
||||
|
||||
// reserve a username
|
||||
final ReserveUsernameHashRequest reserveUsernameHashRequest = new ReserveUsernameHashRequest(
|
||||
candidates.stream().map(Username::getHash).toList());
|
||||
candidates.stream()
|
||||
.map(Username::getHash)
|
||||
.map(ByteArray::serialize)
|
||||
.toList());
|
||||
// try unauthorized
|
||||
Operations
|
||||
.apiPut("/v1/accounts/username_hash/reserve", reserveUsernameHashRequest)
|
||||
@@ -303,13 +307,13 @@ public class AccountTest {
|
||||
// find which one is the reserved username
|
||||
final byte[] reservedHash = reserveUsernameHashResponse.usernameHash();
|
||||
final Username reservedUsername = candidates.stream()
|
||||
.filter(u -> Arrays.equals(u.getHash(), reservedHash))
|
||||
.filter(u -> Arrays.equals(u.getHash().serialize(), reservedHash))
|
||||
.findAny()
|
||||
.orElseThrow();
|
||||
|
||||
// confirm a username
|
||||
final ConfirmUsernameHashRequest confirmUsernameHashRequest = new ConfirmUsernameHashRequest(
|
||||
reservedUsername.getHash(),
|
||||
reservedUsername.getHash().serialize(),
|
||||
reservedUsername.generateProof(),
|
||||
"cluck cluck i'm a parrot".getBytes()
|
||||
);
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
package org.signal.integration;
|
||||
|
||||
import io.micrometer.common.util.StringUtils;
|
||||
import org.apache.commons.lang3.tuple.Pair;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.whispersystems.textsecuregcm.entities.CreateVerificationSessionRequest;
|
||||
@@ -54,8 +55,13 @@ public class RegistrationTest {
|
||||
// verify code
|
||||
final SubmitVerificationCodeRequest submitVerificationCodeRequest = new SubmitVerificationCodeRequest(
|
||||
params.verificationCode());
|
||||
final VerificationSessionResponse codeVerified = Operations
|
||||
final Pair<Integer, VerificationSessionResponse> codeVerified = Operations
|
||||
.apiPut("/v1/verification/session/%s/code".formatted(sessionId), submitVerificationCodeRequest)
|
||||
.executeExpectSuccess(VerificationSessionResponse.class);
|
||||
.execute(VerificationSessionResponse.class);
|
||||
|
||||
// If we succeeded but then retried a 500, we might have submitted a code when we were already verified
|
||||
Assertions.assertTrue(codeVerified.getLeft() == 200 || codeVerified.getLeft() == 409,
|
||||
"Unexpected response code: " + codeVerified.getLeft());
|
||||
Assertions.assertTrue(codeVerified.getRight().verified());
|
||||
}
|
||||
}
|
||||
@@ -45,8 +45,12 @@
|
||||
</modules>
|
||||
|
||||
<properties>
|
||||
<aws.sdk2.version>2.55.14</aws.sdk2.version>
|
||||
<braintree.version>3.54.0</braintree.version>
|
||||
<aws.sdk2.version>2.59.1</aws.sdk2.version>
|
||||
<braintree.version>3.56.0</braintree.version>
|
||||
<!-- Weird stuff happens with parameter annotation counts under Java 27 with versions of Byte Buddy older than
|
||||
1.18.9, so we need to pull in a newer version than we'd get via Dropwizard -> Mockito -> Byte Buddy. We can drop
|
||||
this when Dropwizard updates and pulls in a newer version of Byte Buddy. -->
|
||||
<byte-buddy.version>1.18.17-jdk5</byte-buddy.version>
|
||||
<commons-csv.version>1.14.1</commons-csv.version>
|
||||
<commons-io.version>2.22.0</commons-io.version>
|
||||
<dropwizard.version>5.0.2</dropwizard.version>
|
||||
@@ -55,12 +59,12 @@
|
||||
<foundationdb.version>7.3.76</foundationdb.version>
|
||||
<foundationdb.api-version>730</foundationdb.api-version>
|
||||
<foundationdb.client-library-sha256>af099848721d08904ff9e5d38fade0de24d92e86451ea491d9ab5ce84adcf62a</foundationdb.client-library-sha256>
|
||||
<google-cloud-libraries.version>26.90.0</google-cloud-libraries.version>
|
||||
<google-cloud-libraries.version>26.93.0</google-cloud-libraries.version>
|
||||
<grpc.version>1.76.3</grpc.version> <!-- should be kept in sync with the value from Google libraries-bom -->
|
||||
<guava.version>33.7.2-jre</guava.version>
|
||||
<guava.version>33.8.0-jre</guava.version>
|
||||
<!-- several libraries (AWS, Google Cloud) use Apache httpclient transitively, and we need to align them -->
|
||||
<httpclient.version>4.5.14</httpclient.version>
|
||||
<jackson.version>2.22.3</jackson.version>
|
||||
<jackson.version>2.23.0</jackson.version>
|
||||
<java-otp.version>1.0.0</java-otp.version>
|
||||
<jetty.version>12.1.9</jetty.version>
|
||||
<junit-pioneer.version>2.3.0</junit-pioneer.version>
|
||||
@@ -69,30 +73,29 @@
|
||||
<!-- dropwizard references a constant removed in 1.6. See also: dependabot.yml -->
|
||||
<logback.version>1.5.38</logback.version>
|
||||
<logback-access-common.version>2.0.15</logback-access-common.version>
|
||||
<lettuce.version>7.8.0.RELEASE</lettuce.version>
|
||||
<libphonenumber.version>9.0.41</libphonenumber.version>
|
||||
<logstash.logback.version>9.0</logstash.logback.version>
|
||||
<lettuce.version>7.9.0.RELEASE</lettuce.version>
|
||||
<libphonenumber.version>9.0.43</libphonenumber.version>
|
||||
<log4j-bom.version>2.26.1</log4j-bom.version>
|
||||
<luajava.version>4.1.0</luajava.version>
|
||||
<micrometer.version>1.17.1</micrometer.version>
|
||||
<netty.version>4.2.19.Final</netty.version>
|
||||
<micrometer.version>1.17.2</micrometer.version>
|
||||
<netty.version>4.2.20.Final</netty.version>
|
||||
<!-- netty-bom doesn't manage the BoringSSL uber-jar; keep in sync with netty's tcnative.version -->
|
||||
<netty-tcnative.version>2.0.84.Final</netty-tcnative.version>
|
||||
<netty-tcnative.version>2.0.85.Final</netty-tcnative.version>
|
||||
<!-- Instrumentation releases target upstream opentelemetry versions and include that BOM by reference -->
|
||||
<opentelemetry-instrumentation.version>2.32.0</opentelemetry-instrumentation.version>
|
||||
<opentelemetry-instrumentation.version>2.33.1</opentelemetry-instrumentation.version>
|
||||
<!-- must be greater than or equal to the value from Google libraries-bom, see https://protobuf.dev/support/cross-version-runtime-guarantee/ -->
|
||||
<!-- the latest 4.x should be fine https://central.sonatype.com/artifact/com.google.protobuf/protobuf-java/versions -->
|
||||
<protobuf.version>4.36.2</protobuf.version>
|
||||
<pushy.version>0.15.6</pushy.version>
|
||||
<reactor-bom.version>2025.0.7</reactor-bom.version> <!-- 3.8.4, see https://github.com/reactor/reactor#bom-versioning-scheme -->
|
||||
<reactor-bom.version>2025.0.8</reactor-bom.version> <!-- 3.8.4, see https://github.com/reactor/reactor#bom-versioning-scheme -->
|
||||
<resilience4j.version>2.4.0</resilience4j.version>
|
||||
<semver4j.version>3.1.0</semver4j.version>
|
||||
<simple-grpc.version>0.2.1</simple-grpc.version>
|
||||
<simple-grpc.version>0.3.0</simple-grpc.version>
|
||||
<slf4j.version>2.0.20</slf4j.version>
|
||||
<stripe.version>33.4.2</stripe.version>
|
||||
<stripe.version>34.1.0</stripe.version>
|
||||
<swagger.version>2.2.55</swagger.version>
|
||||
<testcontainers.version>2.0.5</testcontainers.version>
|
||||
<webauthn4j.version>0.31.11.RELEASE</webauthn4j.version>
|
||||
<webauthn4j.version>0.32.0.RELEASE</webauthn4j.version>
|
||||
|
||||
<!-- Images to use in tests via testcontainers. See also: prepull-testcontainers-images <profile> -->
|
||||
<dynamodb.image>amazon/dynamodb-local:3.3.1@sha256:ff89bd48ff32cd8d9be5fee8873b65b8854dc408f1afe881be6eb00247bc0dab</dynamodb.image>
|
||||
@@ -100,7 +103,7 @@
|
||||
<redis.image>redis:7.4-alpine@sha256:6ab0b6e7381779332f97b8ca76193e45b0756f38d4c0dcda72dbb3c32061ab99</redis.image>
|
||||
<redis-cluster.image>docker.io/bitnamilegacy/redis-cluster:7.4.3@sha256:a53d023fdfaf8a8d7ddc58da040d3494e4cb45772644618ffa44c42dcd32b9af</redis-cluster.image>
|
||||
|
||||
<docker.image>eclipse-temurin:26-jre-resolute@sha256:c3b6e31e48772c98e8868654e5f21fb2c3670e67c055ddd76d8cf37e62113eb5</docker.image>
|
||||
<docker.image>eclipse-temurin:27-jre-resolute@sha256:16a0cae9bfb17ab4257ac64e3d7585fc49233e7bdf3d376c4545289eaf193929</docker.image>
|
||||
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
</properties>
|
||||
@@ -176,6 +179,16 @@
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>net.bytebuddy</groupId>
|
||||
<artifactId>byte-buddy</artifactId>
|
||||
<version>${byte-buddy.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>net.bytebuddy</groupId>
|
||||
<artifactId>byte-buddy-agent</artifactId>
|
||||
<version>${byte-buddy.version}</version>
|
||||
</dependency>
|
||||
<!-- Needed for gRPC with Java 9+ -->
|
||||
<dependency>
|
||||
<groupId>org.apache.tomcat</groupId>
|
||||
@@ -253,11 +266,6 @@
|
||||
<artifactId>lettuce-core</artifactId>
|
||||
<version>${lettuce.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>net.logstash.logback</groupId>
|
||||
<artifactId>logstash-logback-encoder</artifactId>
|
||||
<version>${logstash.logback.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-csv</artifactId>
|
||||
@@ -307,13 +315,13 @@
|
||||
<dependency>
|
||||
<groupId>com.redis</groupId>
|
||||
<artifactId>testcontainers-redis</artifactId>
|
||||
<version>3.0.0</version>
|
||||
<version>3.0.1</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.signal</groupId>
|
||||
<artifactId>libsignal-server</artifactId>
|
||||
<version>0.105.0</version>
|
||||
<version>0.108.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.signal</groupId>
|
||||
@@ -490,12 +498,12 @@
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>3.6.0</version>
|
||||
<version>3.6.1</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-failsafe-plugin</artifactId>
|
||||
<version>3.6.0</version>
|
||||
<version>3.6.1</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
@@ -515,12 +523,12 @@
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
<version>3.6.4</version>
|
||||
<version>3.7.0</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>properties-maven-plugin</artifactId>
|
||||
<version>1.3.1</version>
|
||||
<version>1.4.0</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</pluginManagement>
|
||||
@@ -563,7 +571,7 @@
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.16.0</version>
|
||||
<configuration>
|
||||
<release>26</release>
|
||||
<release>27</release>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
@@ -603,7 +611,7 @@
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-enforcer-plugin</artifactId>
|
||||
<version>3.6.3</version>
|
||||
<version>3.7.0</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
|
||||
@@ -255,7 +255,8 @@ fcm: # FCM configuration
|
||||
credentials: secret://fcm.credentials
|
||||
|
||||
cdn:
|
||||
bucket: cdn # S3 Bucket name
|
||||
baseUrl: https://cdn.example.com # Public base URL for objects in the bucket
|
||||
bucket: cdn # S3 Bucket name
|
||||
credentials:
|
||||
accessKeyId: secret://cdn.accessKey
|
||||
secretAccessKey: secret://cdn.accessSecret
|
||||
|
||||
+4
-26
@@ -14,10 +14,10 @@
|
||||
<apollo-api-jvm.version>3.8.6</apollo-api-jvm.version>
|
||||
<commons-compress.version>1.28.0</commons-compress.version>
|
||||
<dynamodb-lock-client.version>1.5.0</dynamodb-lock-client.version>
|
||||
<firebase-admin.version>9.11.0</firebase-admin.version>
|
||||
<libphonenumber-geocoder.version>3.41</libphonenumber-geocoder.version>
|
||||
<firebase-admin.version>9.12.0</firebase-admin.version>
|
||||
<libphonenumber-geocoder.version>3.43</libphonenumber-geocoder.version>
|
||||
<google-androidpublisher.version>v3-rev20250904-2.0.0</google-androidpublisher.version>
|
||||
<java-jwt.version>4.6.1</java-jwt.version>
|
||||
<java-jwt.version>4.6.2</java-jwt.version>
|
||||
<java-uuid-generator.version>5.2.0</java-uuid-generator.version>
|
||||
<!-- *all* opentelemetry-logback-appender versions are "alpha" despite the advanced version number -->
|
||||
<opentelemetry-logback-appender-1.0.version>${opentelemetry-instrumentation.version}-alpha</opentelemetry-logback-appender-1.0.version>
|
||||
@@ -177,25 +177,6 @@
|
||||
<groupId>ch.qos.logback</groupId>
|
||||
<artifactId>logback-classic</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>net.logstash.logback</groupId>
|
||||
<artifactId>logstash-logback-encoder</artifactId>
|
||||
<exclusions>
|
||||
<!-- conflicts with webauthn4j-appattest -->
|
||||
<exclusion>
|
||||
<groupId>tools.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<!-- sentinel for dependency convergence -->
|
||||
<dependency>
|
||||
<groupId>tools.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
<!-- update dependabot.yml when this dependency is removed -->
|
||||
<version>3.2.3</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>io.dropwizard.metrics</groupId>
|
||||
<artifactId>metrics-core</artifactId>
|
||||
@@ -805,9 +786,6 @@
|
||||
<jvmFlag>-XX:MaxRAMPercentage=75</jvmFlag>
|
||||
<jvmFlag>-XX:+HeapDumpOnOutOfMemoryError</jvmFlag>
|
||||
<jvmFlag>-XX:HeapDumpPath=/tmp/heapdump.bin</jvmFlag>
|
||||
<!-- This will likely become the default in a future version of Java, and we can remove this flag when
|
||||
that happens. Please see https://openjdk.org/jeps/534 for details. -->
|
||||
<jvmFlag>-XX:+UseCompactObjectHeaders</jvmFlag>
|
||||
</jvmFlags>
|
||||
<ports>
|
||||
<port>8080</port>
|
||||
@@ -878,7 +856,7 @@
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>templating-maven-plugin</artifactId>
|
||||
<version>3.1.1</version>
|
||||
<version>3.2.0</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>filter-src</id>
|
||||
|
||||
@@ -33,10 +33,11 @@ import io.lettuce.core.metrics.MicrometerOptions;
|
||||
import io.lettuce.core.resource.ClientResources;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.binder.jvm.ExecutorServiceMetrics;
|
||||
import io.netty.channel.DefaultEventLoopGroup;
|
||||
import io.netty.channel.MultiThreadIoEventLoopGroup;
|
||||
import io.netty.channel.local.LocalAddress;
|
||||
import io.netty.channel.local.LocalIoHandler;
|
||||
import io.netty.channel.local.LocalServerChannel;
|
||||
import io.netty.channel.nio.NioEventLoopGroup;
|
||||
import io.netty.channel.nio.NioIoHandler;
|
||||
import io.netty.channel.socket.nio.NioDatagramChannel;
|
||||
import io.netty.channel.socket.nio.NioSocketChannel;
|
||||
import io.netty.handler.ssl.SslContext;
|
||||
@@ -176,6 +177,7 @@ import org.whispersystems.textsecuregcm.grpc.ErrorMappingInterceptor;
|
||||
import org.whispersystems.textsecuregcm.grpc.ExternalServiceDefinitions;
|
||||
import org.whispersystems.textsecuregcm.grpc.GroupSendTokenUtil;
|
||||
import org.whispersystems.textsecuregcm.grpc.GrpcAllowListInterceptor;
|
||||
import org.whispersystems.textsecuregcm.grpc.GrpcCompressionInterceptor;
|
||||
import org.whispersystems.textsecuregcm.grpc.KeyTransparencyGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.KeysAnonymousGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.KeysGrpcService;
|
||||
@@ -184,6 +186,7 @@ import org.whispersystems.textsecuregcm.grpc.MessageDispatcher;
|
||||
import org.whispersystems.textsecuregcm.grpc.MessagesAnonymousGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.MessagesGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.MetricServerInterceptor;
|
||||
import org.whispersystems.textsecuregcm.grpc.MetricServerStreamTracer;
|
||||
import org.whispersystems.textsecuregcm.grpc.OneTimeDonationsGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.PaymentsGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.ProductConfigurationGrpcService;
|
||||
@@ -193,11 +196,14 @@ import org.whispersystems.textsecuregcm.grpc.RemoteConfigurationGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.RequestAttributesInterceptor;
|
||||
import org.whispersystems.textsecuregcm.grpc.SubscriptionsGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.ValidatingInterceptor;
|
||||
import org.whispersystems.textsecuregcm.grpc.net.H2ConnectionFactory;
|
||||
import org.whispersystems.textsecuregcm.grpc.net.ManagedEventLoopGroup;
|
||||
import org.whispersystems.textsecuregcm.grpc.net.ManagedGrpcServer;
|
||||
import org.whispersystems.textsecuregcm.grpc.net.OmnibusH2Server;
|
||||
import org.whispersystems.textsecuregcm.grpc.net.OmnibusRouter;
|
||||
import org.whispersystems.textsecuregcm.grpc.net.PooledH2ConnectionFactory;
|
||||
import org.whispersystems.textsecuregcm.grpc.net.SniMapper;
|
||||
import org.whispersystems.textsecuregcm.grpc.net.UnpooledH2ConnectionFactory;
|
||||
import org.whispersystems.textsecuregcm.grpc.validators.ValidatorUtils;
|
||||
import org.whispersystems.textsecuregcm.jetty.JettyHttpConfigurationCustomizer;
|
||||
import org.whispersystems.textsecuregcm.keytransparency.KeyTransparencyServiceClient;
|
||||
@@ -327,6 +333,7 @@ import org.whispersystems.textsecuregcm.websocket.AuthenticatedConnectListener;
|
||||
import org.whispersystems.textsecuregcm.websocket.NoContextTakeoverPerMessageDeflateExtension;
|
||||
import org.whispersystems.textsecuregcm.websocket.ProvisioningConnectListener;
|
||||
import org.whispersystems.textsecuregcm.websocket.WebSocketAccountAuthenticator;
|
||||
import org.whispersystems.textsecuregcm.websocket.WebSocketConnection;
|
||||
import org.whispersystems.textsecuregcm.workers.BackupMetricsCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.BackupUsageRecalculationCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.CertificateCommand;
|
||||
@@ -725,7 +732,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
ScheduledExecutorService messagePollExecutor = ScheduledExecutorServiceBuilder.of(environment, "messagePollExecutor").threads(1).build();
|
||||
ScheduledExecutorService provisioningWebsocketTimeoutExecutor = ScheduledExecutorServiceBuilder.of(environment, "provisioningWebsocketTimeout").threads(1).build();
|
||||
|
||||
final ManagedEventLoopGroup<NioEventLoopGroup> dnsResolutionEventLoopGroup = new ManagedEventLoopGroup<>(new NioEventLoopGroup());
|
||||
final ManagedEventLoopGroup<MultiThreadIoEventLoopGroup> dnsResolutionEventLoopGroup =
|
||||
new ManagedEventLoopGroup<>(new MultiThreadIoEventLoopGroup(NioIoHandler.newFactory()));
|
||||
final DnsNameResolver cloudflareDnsResolver = new DnsNameResolverBuilder(dnsResolutionEventLoopGroup.getEventLoopGroup().next())
|
||||
.resolvedAddressTypes(ResolvedAddressTypes.IPV6_PREFERRED)
|
||||
.completeOncePreferredResolved(false)
|
||||
@@ -1096,6 +1104,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
final ErrorMappingInterceptor errorMappingInterceptor = new ErrorMappingInterceptor();
|
||||
final ErrorConformanceInterceptor errorConformanceInterceptor = new ErrorConformanceInterceptor();
|
||||
final GrpcAllowListInterceptor grpcAllowListInterceptor = new GrpcAllowListInterceptor(dynamicConfigurationManager);
|
||||
final GrpcCompressionInterceptor grpcCompressionInterceptor = new GrpcCompressionInterceptor(dynamicConfigurationManager);
|
||||
final RequestAttributesInterceptor requestAttributesInterceptor = new RequestAttributesInterceptor();
|
||||
|
||||
final ValidatingInterceptor validatingInterceptor = new ValidatingInterceptor();
|
||||
@@ -1111,7 +1120,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
final GroupSendTokenUtil groupSendTokenUtil = new GroupSendTokenUtil(groupZkSecretParams, Clock.systemUTC());
|
||||
final MessageMetrics messageMetrics = new MessageMetrics();
|
||||
final MessageDispatcher messageDispatcher = new MessageDispatcher(receiptSender, messagesManager, messageMetrics,
|
||||
pushNotificationManager, pushNotificationScheduler, disconnectionRequestManager, clientReleaseManager);
|
||||
pushNotificationManager, pushNotificationScheduler, disconnectionRequestManager, clientReleaseManager, Clock.systemUTC());
|
||||
|
||||
final CertificateGenerator certificateGenerator =
|
||||
new CertificateGenerator(config.getDeliveryCertificate().certificate(),
|
||||
@@ -1132,7 +1141,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
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, asnInfoProviderSupplier, dynamicConfigurationManager, config.getBadges(), profileCdnPolicyGenerator, chatGenericZkSecretParams, profileBadgeConverter, rateLimiters),
|
||||
new ProfileGrpcService(clock, accountsManager, profilesManager, asnInfoProviderSupplier, dynamicConfigurationManager, config.getBadges(), profileCdnPolicyGenerator,
|
||||
config.getCdnConfiguration().baseUrl(), chatGenericZkSecretParams, profileBadgeConverter, rateLimiters),
|
||||
new MessagesGrpcService(accountsManager, reportMessageManager, phoneNumberIdentifiers, rateLimiters, messageSender, messageByteLimitCardinalityEstimator, spamChecker, messageDispatcher, Clock.systemUTC()),
|
||||
new BackupsGrpcService(accountsManager, backupAuthManager, backupMetrics),
|
||||
new DevicesGrpcService(accountsManager),
|
||||
@@ -1152,6 +1162,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
validatingInterceptor,
|
||||
errorMappingInterceptor,
|
||||
errorConformanceInterceptor,
|
||||
grpcCompressionInterceptor,
|
||||
grpcAllowListInterceptor,
|
||||
remoteDeprecationFilter,
|
||||
metricServerInterceptor,
|
||||
@@ -1165,7 +1176,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
new KeysAnonymousGrpcService(accountsManager, keysManager, groupZkSecretParams, Clock.systemUTC()),
|
||||
new KeyTransparencyGrpcService(rateLimiters, keyTransparencyServiceClient),
|
||||
new LoginPurchaseGrpcService(loginPurchaseManager, dynamicConfigurationManager),
|
||||
new ProfileAnonymousGrpcService(accountsManager, profilesManager, profileBadgeConverter, profileCdnPolicyGenerator, chatGenericZkSecretParams, groupZkSecretParams, rateLimiters, clock),
|
||||
new ProfileAnonymousGrpcService(accountsManager, profilesManager, profileBadgeConverter, profileCdnPolicyGenerator,
|
||||
config.getCdnConfiguration().baseUrl(), chatGenericZkSecretParams, groupZkSecretParams, rateLimiters, clock),
|
||||
new MessagesAnonymousGrpcService(accountsManager, rateLimiters, messageSender, groupSendTokenUtil, messageByteLimitCardinalityEstimator, spamChecker, Clock.systemUTC()),
|
||||
new BackupsAnonymousGrpcService(backupManager, backupMetrics, config.getAttachments().maxAttachmentUploadSizeInBytes(), config.getAttachments().maxMessageBackupUploadSizeInBytes()),
|
||||
new CredentialsAnonymousGrpcService(accountsManager, ExternalServiceDefinitions.SVR.generatorFactory().apply(config, Clock.systemUTC()), rateLimiters),
|
||||
@@ -1184,6 +1196,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
validatingInterceptor,
|
||||
errorMappingInterceptor,
|
||||
errorConformanceInterceptor,
|
||||
grpcCompressionInterceptor,
|
||||
grpcAllowListInterceptor,
|
||||
remoteDeprecationFilter,
|
||||
metricServerInterceptor,
|
||||
@@ -1195,15 +1208,18 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
verifyServiceAuth(authenticatedServices, Auth.AUTH_ONLY_AUTHENTICATED);
|
||||
verifyServiceAuth(unauthenticatedServices, Auth.AUTH_ONLY_ANONYMOUS);
|
||||
|
||||
final ManagedEventLoopGroup<DefaultEventLoopGroup> omnibusLocalEventLoopGroup = new ManagedEventLoopGroup<>(new DefaultEventLoopGroup());
|
||||
final ManagedEventLoopGroup<NioEventLoopGroup> omnibusNioEventLoopGroup = new ManagedEventLoopGroup<>(new NioEventLoopGroup());
|
||||
final ManagedEventLoopGroup<MultiThreadIoEventLoopGroup> omnibusLocalEventLoopGroup =
|
||||
new ManagedEventLoopGroup<>(new MultiThreadIoEventLoopGroup(LocalIoHandler.newFactory()));
|
||||
final ManagedEventLoopGroup<MultiThreadIoEventLoopGroup> omnibusNioEventLoopGroup =
|
||||
new ManagedEventLoopGroup<>(new MultiThreadIoEventLoopGroup(NioIoHandler.newFactory()));
|
||||
final LocalAddress grpcLocalAddress = new LocalAddress("grpc");
|
||||
final ServerBuilder<?> serverBuilder = NettyServerBuilder
|
||||
.forAddress(grpcLocalAddress)
|
||||
.channelType(LocalServerChannel.class)
|
||||
.bossEventLoopGroup(omnibusLocalEventLoopGroup.getEventLoopGroup())
|
||||
.workerEventLoopGroup(omnibusLocalEventLoopGroup.getEventLoopGroup())
|
||||
.executor(ManagedExecutors.newVirtualThreadPerTaskExecutor("managed-grpc-virtual-thread", environment));
|
||||
.executor(ManagedExecutors.newVirtualThreadPerTaskExecutor("managed-grpc-virtual-thread", environment))
|
||||
.addStreamTracerFactory(new MetricServerStreamTracer.Factory());
|
||||
authenticatedServices.forEach(serverBuilder::addService);
|
||||
unauthenticatedServices.forEach(serverBuilder::addService);
|
||||
final ManagedGrpcServer localGrpcServer = new ManagedGrpcServer(serverBuilder.build());
|
||||
@@ -1213,10 +1229,13 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
|
||||
final SocketAddress websocketAddress =
|
||||
new InetSocketAddress(config.getGrpc().websocketAddress(), config.getGrpc().websocketPort());
|
||||
final H2ConnectionFactory grpcH2ConnectionFactory = new PooledH2ConnectionFactory(grpcLocalAddress,
|
||||
omnibusLocalEventLoopGroup.getEventLoopGroup());
|
||||
final H2ConnectionFactory websocketH2ConnectionFactory = new UnpooledH2ConnectionFactory(websocketAddress, omnibusNioEventLoopGroup.getEventLoopGroup());
|
||||
final OmnibusRouter omnibusRouter = new OmnibusRouter(Map.of(
|
||||
websocketServletPath, websocketAddress,
|
||||
provisioningWebsocketServletPath, websocketAddress),
|
||||
grpcLocalAddress);
|
||||
websocketServletPath, websocketH2ConnectionFactory,
|
||||
provisioningWebsocketServletPath, websocketH2ConnectionFactory),
|
||||
grpcH2ConnectionFactory);
|
||||
@Nullable final Mapping<String, SslContext> sniMapping = config.getGrpc().h2c()
|
||||
? null
|
||||
: SniMapper.buildSniMapping(config.getTlsKeyStoreConfiguration().path(),
|
||||
@@ -1225,7 +1244,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
final OmnibusH2Server omnibusH2Server = new OmnibusH2Server(
|
||||
sniMapping,
|
||||
omnibusNioEventLoopGroup.getEventLoopGroup(),
|
||||
omnibusLocalEventLoopGroup.getEventLoopGroup(),
|
||||
new InetSocketAddress(config.getGrpc().bindAddress(), config.getGrpc().port()), omnibusRouter,
|
||||
() -> dynamicConfigurationManager.getConfiguration().getOmnibus(),
|
||||
config.getGrpc().idleTimeout());
|
||||
@@ -1278,7 +1296,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
webSocketEnvironment.setConnectListener(
|
||||
new AuthenticatedConnectListener(accountsManager, receiptSender, messagesManager, messageMetrics, pushNotificationManager,
|
||||
pushNotificationScheduler, disconnectionRequestManager,
|
||||
messageDeliveryScheduler, asnInfoProviderSupplier, clientReleaseManager, experimentEnrollmentManager
|
||||
messageDeliveryScheduler, asnInfoProviderSupplier, clientReleaseManager, dynamicConfigurationManager
|
||||
));
|
||||
webSocketEnvironment.jersey().register(new RateLimitByIpFilter(rateLimiters));
|
||||
webSocketEnvironment.jersey().register(new RequestStatisticsFilter(TrafficSource.WEBSOCKET));
|
||||
@@ -1349,6 +1367,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
provisioningEnvironment.jersey().register(new KeepAliveController());
|
||||
provisioningEnvironment.jersey().register(new TimestampResponseFilter());
|
||||
|
||||
WebSocketConnection.registerDroppedErrorHook();
|
||||
|
||||
registerExceptionMappers(environment, webSocketEnvironment, provisioningEnvironment);
|
||||
|
||||
environment.jersey().property(ServerProperties.UNWRAP_COMPLETION_STAGE_IN_WRITER_ENABLE, Boolean.TRUE);
|
||||
|
||||
+1
-1
@@ -15,7 +15,7 @@ public class BulkheadConfiguration {
|
||||
|
||||
@JsonProperty
|
||||
@Min(1)
|
||||
private int maxConcurrentCalls = BulkheadConfig.DEFAULT_MAX_CONCURRENT_CALLS;
|
||||
private int maxConcurrentCalls = 256;
|
||||
|
||||
@JsonProperty
|
||||
@NotNull
|
||||
|
||||
+1
@@ -12,6 +12,7 @@ import javax.annotation.Nullable;
|
||||
import java.net.URI;
|
||||
|
||||
public record CdnConfiguration(@NotNull @Valid StaticAwsCredentialsFactory credentials,
|
||||
@NotBlank String baseUrl,
|
||||
@NotBlank String bucket,
|
||||
@NotBlank String region,
|
||||
@Nullable URI endpointOverride) {
|
||||
|
||||
+4
-2
@@ -14,7 +14,9 @@ import java.time.Duration;
|
||||
/// @param port The port to bind the omnibus server to
|
||||
/// @param websocketAddress The address of a listening websocket server for handling legacy requests
|
||||
/// @param websocketPort The port of a listening websocket server for handling legacy requests
|
||||
/// @param idleTimeout The duration after which an idle connection may be disconnected
|
||||
/// @param idleTimeout The duration after which a connection the client has not written to may be disconnected.
|
||||
/// Clients are expected to send some periodic write traffic (application-level or h2-level
|
||||
/// pings) to keep otherwise idle connections open
|
||||
/// @param h2c If true, listen for plaintext h2c with prior-knowledge
|
||||
/// @param sslProvider The TLS implementation used to terminate TLS. Defaults to `OPENSSL`.
|
||||
public record GrpcConfiguration(
|
||||
@@ -34,7 +36,7 @@ public record GrpcConfiguration(
|
||||
websocketAddress = "localhost";
|
||||
}
|
||||
if (idleTimeout == null) {
|
||||
idleTimeout = Duration.ofMinutes(5);
|
||||
idleTimeout = Duration.ofSeconds(60);
|
||||
}
|
||||
if (sslProvider == null) {
|
||||
sslProvider = SslProvider.OPENSSL;
|
||||
|
||||
+16
@@ -45,6 +45,10 @@ public class DynamicConfiguration {
|
||||
@Valid
|
||||
DynamicMessageDeliveryConfiguration messageDelivery = new DynamicMessageDeliveryConfiguration();
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
DynamicNotificationConfiguration notifications = DynamicNotificationConfiguration.DEFAULT;
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
DynamicRegistrationConfiguration registrationConfiguration = new DynamicRegistrationConfiguration(false);
|
||||
@@ -73,6 +77,10 @@ public class DynamicConfiguration {
|
||||
@Valid
|
||||
private DynamicGrpcAllowListConfiguration grpcAllowList = new DynamicGrpcAllowListConfiguration();
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
private DynamicGrpcCompressionConfiguration grpcCompression = new DynamicGrpcCompressionConfiguration();
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
private DynamicOmnibusConfiguration omnibus = new DynamicOmnibusConfiguration(BigDecimal.ZERO);
|
||||
@@ -115,6 +123,10 @@ public class DynamicConfiguration {
|
||||
return messageDelivery;
|
||||
}
|
||||
|
||||
public DynamicNotificationConfiguration getNotificationConfiguration() {
|
||||
return notifications;
|
||||
}
|
||||
|
||||
public DynamicRegistrationConfiguration getRegistrationConfiguration() {
|
||||
return registrationConfiguration;
|
||||
}
|
||||
@@ -143,6 +155,10 @@ public class DynamicConfiguration {
|
||||
return grpcAllowList;
|
||||
}
|
||||
|
||||
public DynamicGrpcCompressionConfiguration getGrpcCompression() {
|
||||
return grpcCompression;
|
||||
}
|
||||
|
||||
public DynamicOmnibusConfiguration getOmnibus() {
|
||||
return omnibus;
|
||||
}
|
||||
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.configuration.dynamic;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Set;
|
||||
|
||||
/// Configure which gRPC methods may compress their responses
|
||||
///
|
||||
/// @param compressedServices A list of fully qualified service names for which all RPC responses should be compressed.
|
||||
/// For example, `kt_query.KeyTransparencyQueryService` would compress responses for all RPCs
|
||||
/// on that service.
|
||||
/// @param compressedMethods A list of fully qualified method names of RPCs whose responses should be compressed. For
|
||||
/// example, `kt_query.KeyTransparencyQueryService/Search` would compress responses for the
|
||||
/// `Search` RPC method
|
||||
public record DynamicGrpcCompressionConfiguration(
|
||||
Set<String> compressedServices,
|
||||
Set<String> compressedMethods) {
|
||||
|
||||
public DynamicGrpcCompressionConfiguration {
|
||||
if (compressedServices == null) {
|
||||
compressedServices = Collections.emptySet();
|
||||
}
|
||||
if (compressedMethods == null) {
|
||||
compressedMethods = Collections.emptySet();
|
||||
}
|
||||
}
|
||||
|
||||
public DynamicGrpcCompressionConfiguration() {
|
||||
// By default, no gRPC responses are compressed
|
||||
this(Collections.emptySet(), Collections.emptySet());
|
||||
}
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration.dynamic;
|
||||
|
||||
public record DynamicNotificationConfiguration(boolean sendRemainingMessagesNotificationImmediately) {
|
||||
|
||||
public static final DynamicNotificationConfiguration DEFAULT =
|
||||
new DynamicNotificationConfiguration(false);
|
||||
}
|
||||
+2
-1
@@ -40,6 +40,7 @@ import javax.annotation.Nullable;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.glassfish.jersey.server.ManagedAsync;
|
||||
import org.signal.libsignal.usernames.BaseUsernameException;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
|
||||
@@ -356,7 +357,7 @@ public class AccountController {
|
||||
|
||||
try {
|
||||
usernameHashZkProofVerifier.verifyProof(confirmRequest.zkProof(), confirmRequest.usernameHash());
|
||||
} catch (final BaseUsernameException e) {
|
||||
} catch (final BaseUsernameException | InvalidInputException e) {
|
||||
throw new WebApplicationException(Response.status(422).build());
|
||||
}
|
||||
|
||||
|
||||
+10
-16
@@ -9,13 +9,11 @@ import com.google.common.net.HttpHeaders;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.micrometer.core.instrument.DistributionSummary;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.headers.Header;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.Positive;
|
||||
import jakarta.ws.rs.ClientErrorException;
|
||||
import jakarta.ws.rs.GET;
|
||||
@@ -27,7 +25,6 @@ import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import javax.annotation.Nonnull;
|
||||
import javax.annotation.Nullable;
|
||||
import org.glassfish.jersey.server.ManagedAsync;
|
||||
@@ -104,30 +101,27 @@ public class AttachmentControllerV4 {
|
||||
public AttachmentDescriptorV3 getAttachmentUploadForm(
|
||||
@Auth AuthenticatedDevice auth,
|
||||
@Parameter(description = "The size of the attachment to upload in bytes")
|
||||
@QueryParam("uploadLength") final @Valid Optional<@Positive Long> maybeUploadLength,
|
||||
@QueryParam("uploadLength") @Positive final long uploadLength,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) @Nullable final String userAgent)
|
||||
throws RateLimitExceededException {
|
||||
|
||||
final long uploadLength = maybeUploadLength.orElse(maxUploadLength);
|
||||
if (uploadLength > maxUploadLength) {
|
||||
throw new ClientErrorException("exceeded maximum uploadLength", Response.Status.REQUEST_ENTITY_TOO_LARGE);
|
||||
}
|
||||
|
||||
countRateLimiter.validate(auth.accountIdentifier());
|
||||
if (maybeUploadLength.isPresent()) {
|
||||
// Ideally we'd check these two rate limits transactionally and only update them if both permits were acquired.
|
||||
// However, just undoing the first modification if the second one fails is close enough for our purposes
|
||||
try {
|
||||
bytesRateLimiter.validate(auth.accountIdentifier(), maybeUploadLength.get());
|
||||
} catch (RateLimitExceededException e) {
|
||||
countRateLimiter.restorePermits(auth.accountIdentifier(), 1);
|
||||
throw e;
|
||||
}
|
||||
|
||||
// Ideally we'd check these two rate limits transactionally and only update them if both permits were acquired.
|
||||
// However, just undoing the first modification if the second one fails is close enough for our purposes
|
||||
try {
|
||||
bytesRateLimiter.validate(auth.accountIdentifier(), uploadLength);
|
||||
} catch (RateLimitExceededException e) {
|
||||
countRateLimiter.restorePermits(auth.accountIdentifier(), 1);
|
||||
throw e;
|
||||
}
|
||||
|
||||
DistributionSummary.builder(ATTACHMENT_SIZE_NAME)
|
||||
.tags(Tags.of(UserAgentTagUtil.getPlatformTag(userAgent),
|
||||
Tag.of("uploadLengthSupplied", Boolean.toString(maybeUploadLength.isPresent()))))
|
||||
.tags(Tags.of(UserAgentTagUtil.getPlatformTag(userAgent)))
|
||||
.register(Metrics.globalRegistry)
|
||||
.record(uploadLength);
|
||||
|
||||
|
||||
-5
@@ -168,7 +168,6 @@ public class ProfileController {
|
||||
@ApiResponse(responseCode = "400", description = "Invalid create profile request.")
|
||||
@ApiResponse(responseCode = "401", description = "Account authentication check failed.")
|
||||
@ApiResponse(responseCode = "403", description = "The request contained a payment address, but payments are not supported in the region of the account’s phone number or the caller's ASN if the account does not have a phone number.")
|
||||
@ApiResponse(responseCode = "412", description = "The requesting account has the profiles_v2 capability")
|
||||
@ApiResponse(responseCode = "422", description = "Invalid request format")
|
||||
@ManagedAsync
|
||||
public Response setProfile(@Auth AuthenticatedDevice auth,
|
||||
@@ -178,10 +177,6 @@ public class ProfileController {
|
||||
final Account account = accountsManager.getByAccountIdentifier(auth.accountIdentifier())
|
||||
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
|
||||
|
||||
if (account.hasCapability(DeviceCapability.PROFILES_V2)) {
|
||||
return Response.status(Response.Status.PRECONDITION_FAILED).build();
|
||||
}
|
||||
|
||||
final Optional<VersionedProfileV1> currentProfile =
|
||||
profilesManager.getV1(auth.accountIdentifier(), request.version());
|
||||
|
||||
|
||||
+1
-1
@@ -263,7 +263,7 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
|
||||
|
||||
try {
|
||||
usernameHashZkProofVerifier.verifyProof(request.getZkProof().toByteArray(), request.getUsernameHash().toByteArray());
|
||||
} catch (final BaseUsernameException e) {
|
||||
} catch (final BaseUsernameException | InvalidInputException e) {
|
||||
throw GrpcExceptions.invalidArguments("Could not verify proof");
|
||||
}
|
||||
|
||||
|
||||
@@ -73,7 +73,7 @@ public class BackupsGrpcService extends SimpleBackupsGrpc.BackupsImplBase {
|
||||
final Account account = authenticatedAccount();
|
||||
final Device device = account
|
||||
.getDevice(authenticatedDevice.deviceId())
|
||||
.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException);
|
||||
.orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials"));
|
||||
backupAuthManager.commitBackupId(account, device, messagesCredentialRequest, mediaCredentialRequest);
|
||||
return SetBackupIdResponse.getDefaultInstance();
|
||||
}
|
||||
@@ -162,7 +162,7 @@ public class BackupsGrpcService extends SimpleBackupsGrpc.BackupsImplBase {
|
||||
private Account authenticatedAccount() {
|
||||
return accountManager
|
||||
.getByAccountIdentifier(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier())
|
||||
.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException);
|
||||
.orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials"));
|
||||
}
|
||||
|
||||
private interface Deserializer<T> {
|
||||
|
||||
+6
-2
@@ -18,9 +18,11 @@ public class DeviceCapabilityUtil {
|
||||
case DEVICE_CAPABILITY_TRANSFER -> DeviceCapability.TRANSFER;
|
||||
case DEVICE_CAPABILITY_ATTACHMENT_BACKFILL -> DeviceCapability.ATTACHMENT_BACKFILL;
|
||||
case DEVICE_CAPABILITY_SPARSE_POST_QUANTUM_RATCHET -> DeviceCapability.SPARSE_POST_QUANTUM_RATCHET;
|
||||
case DEVICE_CAPABILITY_PROFILES_V2 -> DeviceCapability.PROFILES_V2;
|
||||
case DEVICE_CAPABILITY_USERNAME_CHANGE_SYNC_MESSAGE -> DeviceCapability.USERNAME_CHANGE_SYNC_MESSAGE;
|
||||
case DEVICE_CAPABILITY_OPTIONAL_PHONE_NUMBER -> DeviceCapability.OPTIONAL_PHONE_NUMBER;
|
||||
case DEVICE_CAPABILITY_REPLY_PRIVATELY -> DeviceCapability.REPLY_PRIVATELY;
|
||||
case DEVICE_CAPABILITY_CONTACT_DELETE -> DeviceCapability.CONTACT_DELETE;
|
||||
case DEVICE_CAPABILITY_ADMIN_REMOVE_AND_DELETE -> DeviceCapability.ADMIN_REMOVE_AND_DELETE;
|
||||
case DEVICE_CAPABILITY_UNSPECIFIED, UNRECOGNIZED ->
|
||||
throw GrpcExceptions.invalidArguments("unrecognized device capability");
|
||||
};
|
||||
@@ -32,9 +34,11 @@ public class DeviceCapabilityUtil {
|
||||
case TRANSFER -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_TRANSFER;
|
||||
case ATTACHMENT_BACKFILL -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_ATTACHMENT_BACKFILL;
|
||||
case SPARSE_POST_QUANTUM_RATCHET -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_SPARSE_POST_QUANTUM_RATCHET;
|
||||
case PROFILES_V2 -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_PROFILES_V2;
|
||||
case USERNAME_CHANGE_SYNC_MESSAGE -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_USERNAME_CHANGE_SYNC_MESSAGE;
|
||||
case OPTIONAL_PHONE_NUMBER -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_OPTIONAL_PHONE_NUMBER;
|
||||
case REPLY_PRIVATELY -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_REPLY_PRIVATELY;
|
||||
case CONTACT_DELETE -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_CONTACT_DELETE;
|
||||
case ADMIN_REMOVE_AND_DELETE -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_ADMIN_REMOVE_AND_DELETE;
|
||||
};
|
||||
}
|
||||
}
|
||||
+19
-1
@@ -12,6 +12,8 @@ import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import javax.annotation.Nullable;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.signal.chat.device.ChangeDevicePasswordRequest;
|
||||
import org.signal.chat.device.ChangeDevicePasswordResponse;
|
||||
import org.signal.chat.device.ClearPushTokenRequest;
|
||||
import org.signal.chat.device.ClearPushTokenResponse;
|
||||
import org.signal.chat.device.GetDevicesRequest;
|
||||
@@ -28,7 +30,6 @@ import org.signal.chat.device.SimpleDevicesGrpc;
|
||||
import org.signal.chat.errors.NotFound;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
@@ -184,6 +185,23 @@ public class DevicesGrpcService extends SimpleDevicesGrpc.DevicesImplBase {
|
||||
return SetCapabilitiesResponse.getDefaultInstance();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ChangeDevicePasswordResponse changeDevicePassword(final ChangeDevicePasswordRequest request) {
|
||||
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
|
||||
|
||||
if (request.getNewPassword().isBlank()) {
|
||||
throw GrpcExceptions.fieldViolation("new_password", "password must not be blank");
|
||||
}
|
||||
|
||||
if (!accountsManager.updateDevicePassword(authenticatedDevice.accountIdentifier(), authenticatedDevice.deviceId(),
|
||||
request.getNewPassword())) {
|
||||
|
||||
throw GrpcExceptions.invalidCredentials("invalid credentials");
|
||||
}
|
||||
|
||||
return ChangeDevicePasswordResponse.getDefaultInstance();
|
||||
}
|
||||
|
||||
private Account getAuthenticatedAccount() {
|
||||
return accountsManager.getByAccountIdentifier(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier())
|
||||
.orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials"));
|
||||
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import io.grpc.Metadata;
|
||||
import io.grpc.MethodDescriptor;
|
||||
import io.grpc.ServerCall;
|
||||
import io.grpc.ServerCallHandler;
|
||||
import io.grpc.ServerInterceptor;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicGrpcCompressionConfiguration;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
|
||||
/// Requests gzip compression of responses for configured gRPC methods. Compression is only applied if the client
|
||||
/// advertises gzip in its `grpc-accept-encoding` header; otherwise gRPC falls back to sending uncompressed responses.
|
||||
public class GrpcCompressionInterceptor implements ServerInterceptor {
|
||||
|
||||
private static final String GZIP = "gzip";
|
||||
|
||||
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
|
||||
|
||||
public GrpcCompressionInterceptor(
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
|
||||
this.dynamicConfigurationManager = dynamicConfigurationManager;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(final ServerCall<ReqT, RespT> serverCall,
|
||||
final Metadata metadata, final ServerCallHandler<ReqT, RespT> next) {
|
||||
final DynamicGrpcCompressionConfiguration compressionConfiguration =
|
||||
this.dynamicConfigurationManager.getConfiguration().getGrpcCompression();
|
||||
final MethodDescriptor<ReqT, RespT> methodDescriptor = serverCall.getMethodDescriptor();
|
||||
if (compressionConfiguration.compressedServices().contains(methodDescriptor.getServiceName()) ||
|
||||
compressionConfiguration.compressedMethods().contains(methodDescriptor.getFullMethodName())) {
|
||||
// This does not necessarily enable compression. The implementation will handle negotiation with the client
|
||||
// and may fall back to no compression.
|
||||
serverCall.setCompression(GZIP);
|
||||
}
|
||||
return next.startCall(serverCall, metadata);
|
||||
}
|
||||
}
|
||||
+13
-8
@@ -6,6 +6,7 @@
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import com.google.protobuf.Empty;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.time.Clock;
|
||||
@@ -33,6 +34,8 @@ import reactor.util.function.Tuples;
|
||||
|
||||
public class KeysAnonymousGrpcService extends SimpleKeysAnonymousGrpc.KeysAnonymousImplBase {
|
||||
|
||||
private static final int CHECK_KEYS_MAX_CONCURRENCY = 16;
|
||||
|
||||
private final AccountsManager accountsManager;
|
||||
private final KeysManager keysManager;
|
||||
private final GroupSendTokenUtil groupSendTokenUtil;
|
||||
@@ -99,20 +102,22 @@ public class KeysAnonymousGrpcService extends SimpleKeysAnonymousGrpc.KeysAnonym
|
||||
return JdkFlowAdapter.publisherToFlowPublisher(JdkFlowAdapter.flowPublisherToFlux(requests)
|
||||
.map(request -> Tuples.of(GrpcServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getTargetIdentifier()),
|
||||
request.getFingerprint().toByteArray()))
|
||||
.flatMap(serviceIdentifierAndFingerprint -> Mono.fromFuture(
|
||||
.flatMapSequential(serviceIdentifierAndFingerprint -> Mono.fromFuture(
|
||||
() -> accountsManager.getByServiceIdentifierAsync(serviceIdentifierAndFingerprint.getT1()))
|
||||
.map(maybeAccount -> maybeAccount.flatMap(
|
||||
account -> switch (serviceIdentifierAndFingerprint.getT1().identityType()) {
|
||||
case ACI -> Optional.of(account.getAccountIdentityKey());
|
||||
case PNI -> account.getPhoneNumberIdentityKey();
|
||||
}))
|
||||
.flatMap(Mono::justOrEmpty)
|
||||
.filter(identityKey -> !fingerprintMatches(identityKey, serviceIdentifierAndFingerprint.getT2()))
|
||||
.map(identityKey -> CheckIdentityKeyResponse.newBuilder()
|
||||
.setTargetIdentifier(
|
||||
GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(serviceIdentifierAndFingerprint.getT1()))
|
||||
.setIdentityKey(ByteString.copyFrom(identityKey.serialize()))
|
||||
.build())));
|
||||
.map(maybeIdentityKey -> {
|
||||
final CheckIdentityKeyResponse.Builder builder = CheckIdentityKeyResponse.newBuilder();
|
||||
|
||||
return maybeIdentityKey.map(identityKey ->
|
||||
fingerprintMatches(identityKey, serviceIdentifierAndFingerprint.getT2())
|
||||
? builder.setMatched(Empty.getDefaultInstance()).build()
|
||||
: builder.setIdentityKey(ByteString.copyFrom(identityKey.serialize())).build())
|
||||
.orElseGet(() -> builder.setTargetNotFound(NotFound.getDefaultInstance()).build());
|
||||
}), CHECK_KEYS_MAX_CONCURRENCY));
|
||||
}
|
||||
|
||||
private static boolean fingerprintMatches(final IdentityKey identityKey, final byte[] fingerprint) {
|
||||
|
||||
@@ -104,7 +104,7 @@ class KeysGrpcHelper {
|
||||
.setKeyId(KeyIdUtil.toUnsignedInt(devicePreKeys.ecSignedPreKey().keyId()))
|
||||
.setPublicKey(ByteString.copyFrom(devicePreKeys.ecSignedPreKey().serializedPublicKey()))
|
||||
.setSignature(ByteString.copyFrom(devicePreKeys.ecSignedPreKey().signature())))
|
||||
.setKemOneTimePreKey(KemSignedPreKey.newBuilder()
|
||||
.setKemPreKey(KemSignedPreKey.newBuilder()
|
||||
.setKeyId(KeyIdUtil.toUnsignedInt(devicePreKeys.kemSignedPreKey().keyId()))
|
||||
.setPublicKey(ByteString.copyFrom(devicePreKeys.kemSignedPreKey().serializedPublicKey()))
|
||||
.setSignature(ByteString.copyFrom(devicePreKeys.kemSignedPreKey().signature())))
|
||||
|
||||
+29
-13
@@ -8,8 +8,10 @@ import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.protobuf.Empty;
|
||||
import io.grpc.StatusRuntimeException;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import javax.annotation.Nullable;
|
||||
import org.signal.chat.messages.GetMessagesResponse;
|
||||
import org.signal.chat.messages.GetMessagesStreamClosed;
|
||||
@@ -46,13 +48,12 @@ public class MessageDispatcher {
|
||||
private static final Logger log = LoggerFactory.getLogger(MessageDispatcher.class);
|
||||
|
||||
@VisibleForTesting
|
||||
static final int MAX_UNACKED_MESSAGES = 256;
|
||||
static final int DEFAULT_MAX_UNACKED_MESSAGES = 256;
|
||||
|
||||
@VisibleForTesting
|
||||
static final Duration CLOSE_WITH_PENDING_MESSAGES_NOTIFICATION_DELAY = Duration.ofMinutes(1);
|
||||
private static final int MESSAGE_PUBLISHER_LIMIT_RATE = 100;
|
||||
|
||||
public static final GetMessagesResponse QUEUE_EMPTY_RESPONSE =
|
||||
GetMessagesResponse.newBuilder().setQueueEmpty(Empty.getDefaultInstance()).build();
|
||||
private static final StatusRuntimeException CONFLICTING_STREAM_EXCEPTION =
|
||||
GrpcExceptions.streamClosed(GetMessagesStreamClosed.newBuilder()
|
||||
.setConflictingStream(Empty.getDefaultInstance())
|
||||
@@ -67,6 +68,7 @@ public class MessageDispatcher {
|
||||
private final PushNotificationScheduler pushNotificationScheduler;
|
||||
private final ClientReleaseManager clientReleaseManager;
|
||||
private final DisconnectionRequestManager disconnectionRequestManager;
|
||||
private final Clock clock;
|
||||
|
||||
public MessageDispatcher(final ReceiptSender receiptSender,
|
||||
final MessagesManager messagesManager,
|
||||
@@ -74,7 +76,8 @@ public class MessageDispatcher {
|
||||
final PushNotificationManager pushNotificationManager,
|
||||
final PushNotificationScheduler pushNotificationScheduler,
|
||||
final DisconnectionRequestManager disconnectionRequestManager,
|
||||
final ClientReleaseManager clientReleaseManager) {
|
||||
final ClientReleaseManager clientReleaseManager,
|
||||
final Clock clock) {
|
||||
this.receiptSender = receiptSender;
|
||||
this.messagesManager = messagesManager;
|
||||
this.messageMetrics = messageMetrics;
|
||||
@@ -82,6 +85,7 @@ public class MessageDispatcher {
|
||||
this.pushNotificationScheduler = pushNotificationScheduler;
|
||||
this.disconnectionRequestManager = disconnectionRequestManager;
|
||||
this.clientReleaseManager = clientReleaseManager;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
/// Retrieve messages for the device.
|
||||
@@ -130,10 +134,21 @@ public class MessageDispatcher {
|
||||
|
||||
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)
|
||||
final AtomicInteger maxUnacknowledgedMessages = new AtomicInteger(DEFAULT_MAX_UNACKED_MESSAGES);
|
||||
|
||||
final Flux<GetMessagesResponse> messages = Mono.fromFuture(() -> messagesManager.hasSuspectedDeliveryLoop(account.getAccountIdentifier(), device.getId()))
|
||||
.flatMapMany(hasSuspectedDeliveryLoop -> {
|
||||
if (hasSuspectedDeliveryLoop) {
|
||||
maxUnacknowledgedMessages.set(1);
|
||||
MessageMetrics.recordSuspectedDeliveryLoop(MessageMetrics.GRPC_CHANNEL, userAgent, clientReleaseManager);
|
||||
}
|
||||
|
||||
return JdkFlowAdapter.flowPublisherToFlux(messageStream.getMessages())
|
||||
.name(SEND_MESSAGES_FLUX_NAME)
|
||||
.tag("hasSuspectedDeliveryLoop", String.valueOf(hasSuspectedDeliveryLoop))
|
||||
.tap(Micrometer.metrics(Metrics.globalRegistry))
|
||||
.limitRate(maxUnacknowledgedMessages.get());
|
||||
})
|
||||
.flatMapSequential(entry -> switch (entry) {
|
||||
case MessageStreamEntry.Envelope(final MessageProtos.Envelope envelope) -> {
|
||||
final UUID serverGuid = UUIDUtil.fromByteString(envelope.getServerGuid());
|
||||
@@ -147,13 +162,13 @@ public class MessageDispatcher {
|
||||
final MessageProtos.Envelope stripped = envelope.toBuilder().clearEphemeral().build();
|
||||
messageMetrics.measureAccountEnvelopeUuidMismatches(account, envelope);
|
||||
messageMetrics.measureMessageSent(stripped.getSerializedSize());
|
||||
yield Mono.just(GetMessagesResponse.newBuilder().setEnvelope(stripped).build());
|
||||
yield Mono.just(GetMessagesResponse.newBuilder().setEnvelope(stripped).setServerTimeEpochMillis(clock.millis()).build());
|
||||
}
|
||||
case MessageStreamEntry.QueueEmpty _ -> {
|
||||
pendingAcknowledgementTracker.markEndOfQueue();
|
||||
yield Mono.empty();
|
||||
}
|
||||
}, MAX_UNACKED_MESSAGES)
|
||||
}, maxUnacknowledgedMessages.get())
|
||||
.onErrorMap(ConflictingMessageConsumerException.class, _ -> {
|
||||
messageMetrics.measureMessageStreamDisplaced(MessageMetrics.GRPC_CHANNEL, userAgent, true);
|
||||
return CONFLICTING_STREAM_EXCEPTION;
|
||||
@@ -162,7 +177,7 @@ public class MessageDispatcher {
|
||||
// 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)
|
||||
final Flux<Boolean> permits = Flux.range(0, maxUnacknowledgedMessages.get())
|
||||
.map(_ -> true)
|
||||
.concatWith(ackPermits.asFlux());
|
||||
final Mono<GetMessagesResponse> ackCompletions = acknowledgedMessageGuids
|
||||
@@ -182,7 +197,7 @@ public class MessageDispatcher {
|
||||
.doOnSuccess(_ -> unacked.handleMessageAcknowledged())
|
||||
// Just have to emit some value that indicates we can release a permit
|
||||
.thenReturn(true);
|
||||
}, MAX_UNACKED_MESSAGES)
|
||||
}, maxUnacknowledgedMessages.get())
|
||||
.doOnNext(_ -> ackPermits.tryEmitNext(true))
|
||||
.ignoreElements()
|
||||
.cast(GetMessagesResponse.class);
|
||||
@@ -193,7 +208,8 @@ public class MessageDispatcher {
|
||||
// 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(),
|
||||
pendingAcknowledgementTracker.queueDrained().map(
|
||||
_ -> GetMessagesResponse.newBuilder().setQueueEmpty(Empty.getDefaultInstance()).setServerTimeEpochMillis(clock.millis()).build()),
|
||||
// Emit an invalid credentials error if we receive a disconnection request
|
||||
disconnectionSignal(account, device, userAgent))
|
||||
.doFinally(_ -> maybeSchedulePush(account, device));
|
||||
|
||||
+4
-6
@@ -59,6 +59,7 @@ public class MetricServerInterceptor implements ServerInterceptor {
|
||||
static final String REQUEST_BYTES_COUNTER_NAME = MetricsUtil.name(MetricServerInterceptor.class, "requestBytes");
|
||||
@VisibleForTesting
|
||||
static final String RESPONSE_COUNTER_NAME = MetricsUtil.name(MetricServerInterceptor.class, "responseMessage");
|
||||
/// Response bytes as written to the wire (i.e. after compression), as reported by [MetricServerStreamTracer]
|
||||
@VisibleForTesting
|
||||
static final String RESPONSE_BYTES_COUNTER_NAME = MetricsUtil.name(MetricServerInterceptor.class, "responseBytes");
|
||||
@VisibleForTesting
|
||||
@@ -113,15 +114,16 @@ public class MetricServerInterceptor implements ServerInterceptor {
|
||||
private class MetricServerCall<ReqT, RespT> extends ForwardingServerCall.SimpleForwardingServerCall<ReqT, RespT> {
|
||||
|
||||
private final Counter responseMessageCounter;
|
||||
private final Counter responseBytesCounter;
|
||||
private final Tags tags;
|
||||
private @Nullable String reason = null;
|
||||
|
||||
MetricServerCall(final ServerCall<ReqT, RespT> delegate, final Tags tags) {
|
||||
super(delegate);
|
||||
this.responseMessageCounter = meterRegistry.counter(RESPONSE_COUNTER_NAME, tags);
|
||||
this.responseBytesCounter = meterRegistry.counter(RESPONSE_BYTES_COUNTER_NAME, tags);
|
||||
this.tags = tags;
|
||||
|
||||
MetricServerStreamTracer.current().ifPresent(tracer ->
|
||||
tracer.setResponseBytesCounter(meterRegistry.counter(RESPONSE_BYTES_COUNTER_NAME, tags)));
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -143,10 +145,6 @@ public class MetricServerInterceptor implements ServerInterceptor {
|
||||
public void sendMessage(final RespT responseMessage) {
|
||||
this.responseMessageCounter.increment();
|
||||
|
||||
if (responseMessage instanceof GeneratedMessage generatedMessage) {
|
||||
this.responseBytesCounter.increment(generatedMessage.getSerializedSize());
|
||||
}
|
||||
|
||||
// Extract the annotated reason (if any) from the message
|
||||
final String messageReason = MetricServerCall.reason(responseMessage);
|
||||
|
||||
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import io.grpc.Context;
|
||||
import io.grpc.Metadata;
|
||||
import io.grpc.ServerStreamTracer;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import java.util.Optional;
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
/// Records on-the-wire (i.e. possibly compressed) sizes of response messages.
|
||||
///
|
||||
/// Stream tracers are created before the method being called has been resolved. The tracer makes itself available
|
||||
/// via the call's [Context], and [MetricServerInterceptor] (which only runs for registered methods) supplies the
|
||||
/// counter to increment; without it, nothing is recorded.
|
||||
public class MetricServerStreamTracer extends ServerStreamTracer {
|
||||
|
||||
private static final Context.Key<MetricServerStreamTracer> CONTEXT_KEY = Context.key("metricServerStreamTracer");
|
||||
|
||||
@Nullable
|
||||
private volatile Counter responseBytesCounter;
|
||||
|
||||
public static class Factory extends ServerStreamTracer.Factory {
|
||||
|
||||
@Override
|
||||
public ServerStreamTracer newServerStreamTracer(final String fullMethodName, final Metadata headers) {
|
||||
return new MetricServerStreamTracer();
|
||||
}
|
||||
}
|
||||
|
||||
/// @return the tracer for the current call, if a [Factory] is installed on the server
|
||||
static Optional<MetricServerStreamTracer> current() {
|
||||
return Optional.ofNullable(CONTEXT_KEY.get());
|
||||
}
|
||||
|
||||
void setResponseBytesCounter(final Counter responseBytesCounter) {
|
||||
this.responseBytesCounter = responseBytesCounter;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Context filterContext(final Context context) {
|
||||
return context.withValue(CONTEXT_KEY, this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void outboundWireSize(final long bytes) {
|
||||
final Counter counter = responseBytesCounter;
|
||||
if (counter != null) {
|
||||
counter.increment(bytes);
|
||||
}
|
||||
}
|
||||
}
|
||||
+3
-5
@@ -9,7 +9,6 @@ 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;
|
||||
@@ -39,9 +38,8 @@ 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 Sinks.One<Boolean> queueDrained = Sinks.one();
|
||||
private final ClosableEpoch queueDrainEpoch = new ClosableEpoch(() -> queueDrained.tryEmitValue(true));
|
||||
private final Timer.Sample queueDrainStart = Timer.start();
|
||||
|
||||
private final MessageMetrics messageMetrics;
|
||||
@@ -92,7 +90,7 @@ class PendingAcknowledgementTracker {
|
||||
///
|
||||
/// @return A mono that completes with a QueueEmpty response when all messages tracked before [#markEndOfQueue] have
|
||||
/// been acknowledged.
|
||||
Mono<GetMessagesResponse> queueDrained() {
|
||||
Mono<Boolean> queueDrained() {
|
||||
return queueDrained.asMono();
|
||||
}
|
||||
|
||||
|
||||
+8
-2
@@ -11,6 +11,7 @@ import io.micrometer.core.instrument.Metrics;
|
||||
import java.time.Clock;
|
||||
import java.util.Base64;
|
||||
import java.util.Optional;
|
||||
import org.apache.commons.lang3.Strings;
|
||||
import org.signal.chat.errors.FailedUnidentifiedAuthorization;
|
||||
import org.signal.chat.errors.FailedZkAuthentication;
|
||||
import org.signal.chat.errors.NotFound;
|
||||
@@ -56,6 +57,7 @@ public class ProfileAnonymousGrpcService extends SimpleProfileAnonymousGrpc.Prof
|
||||
private final GroupSendTokenUtil groupSendTokenUtil;
|
||||
|
||||
private final PostPolicyGenerator policyGenerator;
|
||||
private final String cdnBaseUrl;
|
||||
|
||||
private final RateLimiters rateLimiters;
|
||||
|
||||
@@ -66,6 +68,7 @@ public class ProfileAnonymousGrpcService extends SimpleProfileAnonymousGrpc.Prof
|
||||
final ProfilesManager profilesManager,
|
||||
final ProfileBadgeConverter profileBadgeConverter,
|
||||
final PostPolicyGenerator policyGenerator,
|
||||
final String cdnBaseUrl,
|
||||
final GenericServerSecretParams genericServerSecretParams,
|
||||
final ServerSecretParams serverSecretParams,
|
||||
final RateLimiters rateLimiters,
|
||||
@@ -74,6 +77,7 @@ public class ProfileAnonymousGrpcService extends SimpleProfileAnonymousGrpc.Prof
|
||||
profilesManager,
|
||||
profileBadgeConverter,
|
||||
policyGenerator,
|
||||
cdnBaseUrl,
|
||||
genericServerSecretParams,
|
||||
rateLimiters,
|
||||
clock,
|
||||
@@ -86,6 +90,7 @@ public class ProfileAnonymousGrpcService extends SimpleProfileAnonymousGrpc.Prof
|
||||
final ProfilesManager profilesManager,
|
||||
final ProfileBadgeConverter profileBadgeConverter,
|
||||
final PostPolicyGenerator policyGenerator,
|
||||
final String cdnBaseUrl,
|
||||
final GenericServerSecretParams genericServerSecretParams,
|
||||
final RateLimiters rateLimiters,
|
||||
final Clock clock,
|
||||
@@ -95,6 +100,7 @@ public class ProfileAnonymousGrpcService extends SimpleProfileAnonymousGrpc.Prof
|
||||
this.profilesManager = profilesManager;
|
||||
this.profileBadgeConverter = profileBadgeConverter;
|
||||
this.policyGenerator = policyGenerator;
|
||||
this.cdnBaseUrl = Strings.CS.removeEnd(cdnBaseUrl, "/");
|
||||
this.genericServerSecretParams = genericServerSecretParams;
|
||||
this.rateLimiters = rateLimiters;
|
||||
this.clock = clock;
|
||||
@@ -133,7 +139,7 @@ public class ProfileAnonymousGrpcService extends SimpleProfileAnonymousGrpc.Prof
|
||||
|
||||
// If we didn't find a v2 profile, try a v1 profile
|
||||
.or(() -> ProfileGrpcHelper
|
||||
.getProfileV1(account, profilesManager, profileBadgeConverter, version)
|
||||
.getProfileV1(account, profilesManager, profileBadgeConverter, cdnBaseUrl, version)
|
||||
.map(v1Result -> GetProfileAnonymousResponse.newBuilder().setProfileV1(v1Result).build())))
|
||||
.orElseGet(() -> GetProfileAnonymousResponse.newBuilder().setNotFound(NotFound.getDefaultInstance()).build());
|
||||
|
||||
@@ -238,7 +244,7 @@ public class ProfileAnonymousGrpcService extends SimpleProfileAnonymousGrpc.Prof
|
||||
|
||||
return profilesManager.extendAvatarTtlForIdentity(identity)
|
||||
.map(extendedPath -> ExtendAvatarTTLResponse.newBuilder()
|
||||
.setPath(extendedPath)
|
||||
.setUrl(ProfileGrpcHelper.cdnUrl(cdnBaseUrl, extendedPath))
|
||||
.build())
|
||||
.orElseGet(() -> ExtendAvatarTTLResponse.newBuilder()
|
||||
.setNotFound(NotFound.getDefaultInstance())
|
||||
|
||||
+12
-14
@@ -14,6 +14,7 @@ import java.time.Clock;
|
||||
import java.util.Arrays;
|
||||
import java.util.HexFormat;
|
||||
import java.util.Optional;
|
||||
import org.apache.commons.lang3.Strings;
|
||||
import org.bouncycastle.crypto.digests.TupleHash;
|
||||
import org.signal.chat.common.S3UploadForm;
|
||||
import org.signal.chat.profile.AccountInfo;
|
||||
@@ -32,7 +33,6 @@ import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessChecksum;
|
||||
import org.whispersystems.textsecuregcm.badges.ProfileBadgeConverter;
|
||||
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
|
||||
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
|
||||
import org.whispersystems.textsecuregcm.storage.VersionedProfile;
|
||||
import org.whispersystems.textsecuregcm.storage.VersionedProfileV1;
|
||||
@@ -47,9 +47,14 @@ public class ProfileGrpcHelper {
|
||||
.setAlgorithm(PostPolicyGenerator.ALGORITHM)
|
||||
.build();
|
||||
|
||||
static String cdnUrl(final String cdnBaseUrl, final String path) {
|
||||
return Strings.CS.removeEnd(cdnBaseUrl, "/") + "/" + Strings.CS.removeStart(path, "/");
|
||||
}
|
||||
|
||||
static Optional<LegacyProfileResult> getProfileV1(final Account account,
|
||||
final ProfilesManager profilesManager,
|
||||
final ProfileBadgeConverter profileBadgeConverter,
|
||||
final String cdnBaseUrl,
|
||||
final byte[] requestVersion) {
|
||||
final Optional<VersionedProfileV1> maybeV1Profile =
|
||||
profilesManager.getV1(account.getAccountIdentifier(), HexFormat.of().formatHex(requestVersion));
|
||||
@@ -74,7 +79,7 @@ public class ProfileGrpcHelper {
|
||||
builder.setPhoneNumberSharing(ByteString.copyFrom(v1Profile.phoneNumberSharing()));
|
||||
}
|
||||
if (v1Profile.avatar() != null) {
|
||||
builder.setAvatar(v1Profile.avatar());
|
||||
builder.setAvatarUrl(cdnUrl(cdnBaseUrl, v1Profile.avatar()));
|
||||
}
|
||||
|
||||
// If present, include the payment address if the version matches the latest version on Account or the latest
|
||||
@@ -91,9 +96,7 @@ public class ProfileGrpcHelper {
|
||||
final ProfileBadgeConverter profileBadgeConverter,
|
||||
final byte[] requestVersion) {
|
||||
|
||||
final Optional<VersionedProfile> maybeProfile = account.hasCapability(DeviceCapability.PROFILES_V2)
|
||||
? profilesManager.get(account.getAccountIdentifier(), requestVersion)
|
||||
: Optional.empty();
|
||||
final Optional<VersionedProfile> maybeProfile = profilesManager.get(account.getAccountIdentifier(), requestVersion);
|
||||
if (maybeProfile.isEmpty()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
@@ -135,14 +138,8 @@ public class ProfileGrpcHelper {
|
||||
final ProfilesManager profilesManager,
|
||||
final ServerZkProfileOperations zkProfileOperations) {
|
||||
|
||||
final Optional<VersionedProfile> versionedProfile;
|
||||
if (account.hasCapability(DeviceCapability.PROFILES_V2)) {
|
||||
versionedProfile = profilesManager.get(account.getAccountIdentifier(), version);
|
||||
} else {
|
||||
versionedProfile = Optional.empty();
|
||||
}
|
||||
|
||||
return versionedProfile.map(VersionedProfile::commitment)
|
||||
return profilesManager.get(account.getAccountIdentifier(), version)
|
||||
.map(VersionedProfile::commitment)
|
||||
.or(() -> profilesManager.getV1(account.getAccountIdentifier(), HexFormat.of().formatHex(version))
|
||||
.map(VersionedProfileV1::commitment))
|
||||
.map(commitment -> {
|
||||
@@ -151,7 +148,8 @@ public class ProfileGrpcHelper {
|
||||
try {
|
||||
profileKeyCredentialResponse = ProfileHelper.getExpiringProfileKeyCredential(
|
||||
new ProfileKeyCredentialRequest(encodedCredentialRequest),
|
||||
new ProfileKeyCommitment(commitment), new ServiceId.Aci(account.getAccountIdentifier()), zkProfileOperations);
|
||||
new ProfileKeyCommitment(commitment), new ServiceId.Aci(account.getAccountIdentifier()),
|
||||
zkProfileOperations);
|
||||
} catch (VerificationFailedException | InvalidInputException e) {
|
||||
throw GrpcExceptions.invalidArguments("invalid credential request");
|
||||
}
|
||||
|
||||
@@ -18,6 +18,7 @@ import java.util.UUID;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Collectors;
|
||||
import org.apache.commons.lang3.Strings;
|
||||
import org.signal.chat.common.S3UploadForm;
|
||||
import org.signal.chat.errors.FailedPrecondition;
|
||||
import org.signal.chat.errors.NotFound;
|
||||
@@ -73,6 +74,7 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
|
||||
private final GenericServerSecretParams genericServerSecretParams;
|
||||
private final ProfileBadgeConverter profileBadgeConverter;
|
||||
private final RateLimiters rateLimiters;
|
||||
private final String cdnBaseUrl;
|
||||
|
||||
private record AvatarData(Optional<String> currentAvatar,
|
||||
Optional<String> finalAvatar,
|
||||
@@ -86,6 +88,7 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
|
||||
final BadgesConfiguration badgesConfiguration,
|
||||
final PostPolicyGenerator policyGenerator,
|
||||
final String cdnBaseUrl,
|
||||
final GenericServerSecretParams genericServerSecretParams,
|
||||
final ProfileBadgeConverter profileBadgeConverter,
|
||||
final RateLimiters rateLimiters) {
|
||||
@@ -97,6 +100,7 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
|
||||
this.badgeConfigurationMap = badgesConfiguration.getBadges().stream()
|
||||
.collect(Collectors.toMap(BadgeConfiguration::getId, Function.identity()));
|
||||
this.policyGenerator = policyGenerator;
|
||||
this.cdnBaseUrl = Strings.CS.removeEnd(cdnBaseUrl, "/");
|
||||
this.genericServerSecretParams = genericServerSecretParams;
|
||||
this.profileBadgeConverter = profileBadgeConverter;
|
||||
this.rateLimiters = rateLimiters;
|
||||
@@ -268,7 +272,7 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
|
||||
|
||||
// If we didn't find a v2 profile, try a v1 profile
|
||||
.or(() -> ProfileGrpcHelper
|
||||
.getProfileV1(account, profilesManager, profileBadgeConverter, version)
|
||||
.getProfileV1(account, profilesManager, profileBadgeConverter, cdnBaseUrl, version)
|
||||
.map(v1Result -> GetProfileResponse.newBuilder().setLegacyProfile(v1Result).build())))
|
||||
.orElseGet(() -> GetProfileResponse.newBuilder().setNotFound(NotFound.getDefaultInstance()).build());
|
||||
}
|
||||
|
||||
-111
@@ -1,111 +0,0 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.grpc.net;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.netty.handler.ssl.OpenSsl;
|
||||
import java.net.Socket;
|
||||
import java.security.Principal;
|
||||
import java.security.PrivateKey;
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.util.Arrays;
|
||||
import java.util.Optional;
|
||||
import javax.net.ssl.ExtendedSSLSession;
|
||||
import javax.net.ssl.KeyManager;
|
||||
import javax.net.ssl.SSLEngine;
|
||||
import javax.net.ssl.X509ExtendedKeyManager;
|
||||
|
||||
/// A server key manager for netty's BoringSSL provider that uses a client's signature algorithm preferences, enabling
|
||||
/// support for ed25519.
|
||||
///
|
||||
/// This works around [netty#17690](https://github.com/netty/netty/issues/17690):
|
||||
/// netty’s engine only asks the key manager for RSA- and EC-family key types, so it never selects an Ed25519 key.
|
||||
class BoringSslServerKeyManager extends X509ExtendedKeyManager {
|
||||
|
||||
private final X509ExtendedKeyManager delegate;
|
||||
|
||||
@VisibleForTesting
|
||||
BoringSslServerKeyManager(final X509ExtendedKeyManager delegate) {
|
||||
if (!"BoringSSL".equals(OpenSsl.versionString())) {
|
||||
throw new IllegalStateException("BoringSSL required, found " + OpenSsl.versionString());
|
||||
}
|
||||
this.delegate = delegate;
|
||||
}
|
||||
|
||||
/// @throws IllegalArgumentException if `keyManagers` contains no [X509ExtendedKeyManager]
|
||||
static BoringSslServerKeyManager wrap(final KeyManager[] keyManagers) {
|
||||
return Arrays.stream(keyManagers)
|
||||
.filter(X509ExtendedKeyManager.class::isInstance)
|
||||
.map(X509ExtendedKeyManager.class::cast)
|
||||
.findFirst()
|
||||
.map(BoringSslServerKeyManager::new)
|
||||
.orElseThrow(() -> new IllegalArgumentException("No X509ExtendedKeyManager found"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public String chooseEngineServerAlias(final String keyType, final Principal[] issuers, final SSLEngine engine) {
|
||||
if (!(engine.getHandshakeSession() instanceof ExtendedSSLSession session)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Netty will only call this with EC/RSA key types (https://github.com/netty/netty/issues/17690).
|
||||
// We can safely ignore `keyType` and loop through the peer's signature algorithms to find the best matching key.
|
||||
for (final String signatureAlgorithm : session.getPeerSupportedSignatureAlgorithms()) {
|
||||
final Optional<String> maybeAlias = getJdkKeyType(signatureAlgorithm)
|
||||
.map(jdkKeyType -> delegate.chooseEngineServerAlias(jdkKeyType, issuers, engine));
|
||||
|
||||
if (maybeAlias.isPresent()) {
|
||||
return maybeAlias.get();
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// Maps a JDK signature algorithm name to the JDK key type that can produce it
|
||||
@VisibleForTesting
|
||||
static Optional<String> getJdkKeyType(final String signatureAlgorithm) {
|
||||
if (signatureAlgorithm.equals("Ed25519")) {
|
||||
return Optional.of("EdDSA");
|
||||
} else if (signatureAlgorithm.endsWith("withECDSA")) {
|
||||
return Optional.of("EC");
|
||||
} else if (signatureAlgorithm.endsWith("withRSA")) {
|
||||
return Optional.of("RSA");
|
||||
}
|
||||
|
||||
// We don't need to be exhaustive, because we require TLS 1.3 and only use a limited number of key types.
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String chooseServerAlias(final String keyType, final Principal[] issuers, final Socket socket) {
|
||||
return delegate.chooseServerAlias(keyType, issuers, socket);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String[] getServerAliases(final String keyType, final Principal[] issuers) {
|
||||
return delegate.getServerAliases(keyType, issuers);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String chooseClientAlias(final String[] keyTypes, final Principal[] issuers, final Socket socket) {
|
||||
return delegate.chooseClientAlias(keyTypes, issuers, socket);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String[] getClientAliases(final String keyType, final Principal[] issuers) {
|
||||
return delegate.getClientAliases(keyType, issuers);
|
||||
}
|
||||
|
||||
@Override
|
||||
public X509Certificate[] getCertificateChain(final String alias) {
|
||||
return delegate.getCertificateChain(alias);
|
||||
}
|
||||
|
||||
@Override
|
||||
public PrivateKey getPrivateKey(final String alias) {
|
||||
return delegate.getPrivateKey(alias);
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.grpc.net;
|
||||
|
||||
import io.netty.channel.Channel;
|
||||
import io.netty.channel.ChannelFuture;
|
||||
import io.netty.channel.EventLoop;
|
||||
import java.net.SocketAddress;
|
||||
|
||||
/// A factory that creates h2 connections to some configured target address
|
||||
public interface H2ConnectionFactory {
|
||||
|
||||
/// Retrieve a h2 connection to [#address()]
|
||||
///
|
||||
/// @param callerEventLoop The event loop of the channel making this call
|
||||
ChannelFuture getConnectionChannelFuture(final EventLoop callerEventLoop);
|
||||
|
||||
/// Release a connection previously acquired via [#getConnectionChannelFuture]
|
||||
void release(final Channel connection);
|
||||
|
||||
/// @return The [SocketAddress] that this factory targets
|
||||
SocketAddress address();
|
||||
}
|
||||
+8
-12
@@ -14,9 +14,9 @@ import io.netty.channel.ChannelInboundHandlerAdapter;
|
||||
import io.netty.channel.ChannelInitializer;
|
||||
import io.netty.channel.ChannelOption;
|
||||
import io.netty.channel.ChannelPipeline;
|
||||
import io.netty.channel.DefaultEventLoopGroup;
|
||||
import io.netty.channel.EventLoopGroup;
|
||||
import io.netty.channel.SimpleUserEventChannelHandler;
|
||||
import io.netty.channel.nio.NioEventLoopGroup;
|
||||
import io.netty.channel.nio.NioIoHandler;
|
||||
import io.netty.channel.socket.SocketChannel;
|
||||
import io.netty.channel.socket.nio.NioServerSocketChannel;
|
||||
import io.netty.handler.codec.DecoderException;
|
||||
@@ -67,8 +67,7 @@ public class OmnibusH2Server implements Managed {
|
||||
private final OmnibusRouter router;
|
||||
private final Supplier<DynamicOmnibusConfiguration> configurationSupplier;
|
||||
private final Duration idleTimeout;
|
||||
private final DefaultEventLoopGroup localEventLoopGroup;
|
||||
private final NioEventLoopGroup nioEventLoopGroup;
|
||||
private final EventLoopGroup nioEventLoopGroup;
|
||||
private final SocketAddress bindAddress;
|
||||
|
||||
private Channel serverChannel;
|
||||
@@ -77,16 +76,14 @@ public class OmnibusH2Server implements Managed {
|
||||
///
|
||||
/// @param sslContextBySni If not null, a mapping between domain (SNI) and the appropriate SslContext to use for
|
||||
/// that SNI. If null, the server will not include TLS (h2c with prior-knowledge)
|
||||
/// @param nioEventLoopGroup Event loop to use for all NIO channel pipelines
|
||||
/// @param localEventLoopGroup Event loop to use for all local channel pipelines
|
||||
/// @param nioEventLoopGroup An Event loop with a [NioIoHandler#newFactory()] to use for all NIO channel pipelines
|
||||
/// @param bindAddress The address the server should listen on
|
||||
/// @param router How the server should select backends based on request paths
|
||||
/// @param configurationSupplier Dynamic configuration supplier
|
||||
/// @param idleTimeout How long to wait before terminating idle TCP connections
|
||||
/// @param idleTimeout How long to wait since the last data was received from the client before terminating TCP connections
|
||||
public OmnibusH2Server(
|
||||
final @Nullable Mapping<String, SslContext> sslContextBySni,
|
||||
final NioEventLoopGroup nioEventLoopGroup,
|
||||
final DefaultEventLoopGroup localEventLoopGroup,
|
||||
final EventLoopGroup nioEventLoopGroup,
|
||||
final SocketAddress bindAddress,
|
||||
final OmnibusRouter router,
|
||||
final Supplier<DynamicOmnibusConfiguration> configurationSupplier,
|
||||
@@ -94,7 +91,6 @@ public class OmnibusH2Server implements Managed {
|
||||
this.sslContextBySni = sslContextBySni;
|
||||
this.configurationSupplier = configurationSupplier;
|
||||
this.nioEventLoopGroup = nioEventLoopGroup;
|
||||
this.localEventLoopGroup = localEventLoopGroup;
|
||||
this.bindAddress = bindAddress;
|
||||
this.router = router;
|
||||
this.idleTimeout = idleTimeout;
|
||||
@@ -113,7 +109,7 @@ public class OmnibusH2Server implements Managed {
|
||||
.childHandler(new ChannelInitializer<SocketChannel>() {
|
||||
@Override
|
||||
protected void initChannel(final SocketChannel ch) {
|
||||
ch.pipeline().addLast(new IdleStateHandler(0, 0, idleTimeout.toMillis(), TimeUnit.MILLISECONDS));
|
||||
ch.pipeline().addLast(new IdleStateHandler(idleTimeout.toMillis(), 0, 0, TimeUnit.MILLISECONDS));
|
||||
ch.pipeline().addLast(new SimpleUserEventChannelHandler<IdleStateEvent>() {
|
||||
@Override
|
||||
protected void eventReceived(final ChannelHandlerContext ctx, final IdleStateEvent evt) {
|
||||
@@ -184,7 +180,7 @@ public class OmnibusH2Server implements Managed {
|
||||
pipeline.addLast(new Http2MultiplexHandler(new ChannelInitializer<Http2StreamChannel>() {
|
||||
@Override
|
||||
protected void initChannel(final Http2StreamChannel ch) {
|
||||
ch.pipeline().addLast(new OmnibusH2StreamHandler(nioEventLoopGroup, localEventLoopGroup, router));
|
||||
ch.pipeline().addLast(new OmnibusH2StreamHandler(router));
|
||||
}
|
||||
}));
|
||||
pipeline.addLast(SESSION_EXCEPTION_HANDLER);
|
||||
|
||||
+15
-85
@@ -7,36 +7,22 @@ package org.whispersystems.textsecuregcm.grpc.net;
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
import io.netty.bootstrap.Bootstrap;
|
||||
import io.netty.channel.Channel;
|
||||
import io.netty.channel.ChannelFuture;
|
||||
import io.netty.channel.ChannelFutureListener;
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.channel.ChannelInboundHandlerAdapter;
|
||||
import io.netty.channel.ChannelInitializer;
|
||||
import io.netty.channel.DefaultEventLoopGroup;
|
||||
import io.netty.channel.EventLoopGroup;
|
||||
import io.netty.channel.local.LocalAddress;
|
||||
import io.netty.channel.local.LocalChannel;
|
||||
import io.netty.channel.nio.NioEventLoopGroup;
|
||||
import io.netty.channel.socket.nio.NioSocketChannel;
|
||||
import io.netty.handler.codec.http2.DefaultHttp2Headers;
|
||||
import io.netty.handler.codec.http2.DefaultHttp2HeadersFrame;
|
||||
import io.netty.handler.codec.http2.DefaultHttp2ResetFrame;
|
||||
import io.netty.handler.codec.http2.Http2Error;
|
||||
import io.netty.handler.codec.http2.Http2FrameCodecBuilder;
|
||||
import io.netty.handler.codec.http2.Http2HeadersFrame;
|
||||
import io.netty.handler.codec.http2.Http2MultiplexHandler;
|
||||
import io.netty.handler.codec.http2.Http2Settings;
|
||||
import io.netty.handler.codec.http2.Http2StreamChannel;
|
||||
import io.netty.handler.codec.http2.Http2StreamChannelBootstrap;
|
||||
import io.netty.util.ReferenceCountUtil;
|
||||
import io.netty.util.ReferenceCounted;
|
||||
import java.net.InetAddress;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.SocketAddress;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
@@ -46,7 +32,7 @@ import org.slf4j.LoggerFactory;
|
||||
///
|
||||
/// When this handler receives an H2 header for a new stream-id=X on our parent H2 connection it will
|
||||
/// - Receive the stream-id=X header and check the path to determine the correct backend
|
||||
/// - Make a new H2 connection to the backend
|
||||
/// - Get or create an H2 connection to the backend
|
||||
/// - Forward the header with stream-id=Y to the backend
|
||||
/// - Install a [H2FrameProxyHandler] on the backend stream pipeline that forwards the received stream-id=Y frames from
|
||||
/// the backend back to the client on stream-id=X
|
||||
@@ -56,25 +42,13 @@ public class OmnibusH2StreamHandler extends ChannelInboundHandlerAdapter {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(OmnibusH2StreamHandler.class);
|
||||
|
||||
private static final OmnibusExceptionHandler BACKEND_CONNECTION_EXCEPTION_HANDLER =
|
||||
new OmnibusExceptionHandler("backend-connection", List.of());
|
||||
private static final String BACKEND_STREAM_COUNTER_NAME = name(OmnibusH2StreamHandler.class, "backendStream");
|
||||
private static final String BACKEND_CONNECT_DURATION_NAME = name(OmnibusH2StreamHandler.class,
|
||||
"backendConnectDuration");
|
||||
private static final String BACKEND_TAG = "backend";
|
||||
|
||||
private final OmnibusRouter router;
|
||||
|
||||
private final DefaultEventLoopGroup localEventLoopGroup;
|
||||
private final NioEventLoopGroup nioEventLoopGroup;
|
||||
|
||||
public OmnibusH2StreamHandler(
|
||||
final NioEventLoopGroup nioEventLoopGroup,
|
||||
final DefaultEventLoopGroup localEventLoopGroup,
|
||||
final OmnibusRouter router) {
|
||||
public OmnibusH2StreamHandler(final OmnibusRouter router) {
|
||||
this.router = router;
|
||||
this.localEventLoopGroup = localEventLoopGroup;
|
||||
this.nioEventLoopGroup = nioEventLoopGroup;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -96,8 +70,8 @@ public class OmnibusH2StreamHandler extends ChannelInboundHandlerAdapter {
|
||||
|
||||
// Select the target backend based on the path
|
||||
final String path = Optional.ofNullable(headersFrame.headers().path()).map(CharSequence::toString).orElse("");
|
||||
final SocketAddress target = router.match(path);
|
||||
final String backendTag = target.toString();
|
||||
final H2ConnectionFactory connectionFactory = router.match(path);
|
||||
final String backendTag = connectionFactory.address().toString();
|
||||
|
||||
Metrics.counter(BACKEND_STREAM_COUNTER_NAME, BACKEND_TAG, backendTag).increment();
|
||||
|
||||
@@ -109,55 +83,38 @@ public class OmnibusH2StreamHandler extends ChannelInboundHandlerAdapter {
|
||||
? proxyRemoteAddress.getHostAddress()
|
||||
: ((InetSocketAddress) ctx.channel().remoteAddress()).getHostString());
|
||||
|
||||
// Make a new H2 connection to the target backend
|
||||
final Timer.Sample connectSample = Timer.start();
|
||||
new Bootstrap()
|
||||
.group(selectEventLoop(ctx, target))
|
||||
.channel(target instanceof LocalAddress ? LocalChannel.class : NioSocketChannel.class)
|
||||
.handler(new ChannelInitializer<>() {
|
||||
@Override
|
||||
protected void initChannel(final Channel ch) {
|
||||
ch.pipeline()
|
||||
.addLast(Http2FrameCodecBuilder.forClient().initialSettings(Http2Settings.defaultSettings()).build());
|
||||
// Http2MultiplexHandler takes handler that is added to new inbound streams. A client Http2MultiplexHandler
|
||||
// like we're defining here should never receive an inbound H2 stream so we can just pass a noop handler
|
||||
ch.pipeline().addLast(new Http2MultiplexHandler(new NoopInboundStreamHandler()));
|
||||
ch.pipeline().addLast(BACKEND_CONNECTION_EXCEPTION_HANDLER);
|
||||
}
|
||||
})
|
||||
.connect(target)
|
||||
// Make an H2 connection to the target backend
|
||||
connectionFactory.getConnectionChannelFuture(ctx.channel().eventLoop())
|
||||
.addListener((ChannelFuture connectFuture) -> {
|
||||
connectSample.stop(Timer.builder(BACKEND_CONNECT_DURATION_NAME)
|
||||
.tag(BACKEND_TAG, backendTag)
|
||||
.tag("outcome", connectFuture.isSuccess() ? "success" : "failure")
|
||||
.register(Metrics.globalRegistry));
|
||||
|
||||
if (!connectFuture.isSuccess()) {
|
||||
// Close the client stream with a 502: Bad Gateway if the backend wasn't available
|
||||
logger.warn("Failed to connect to backend {}", target, connectFuture.cause());
|
||||
logger.warn("Failed to connect to backend {}", backendTag, connectFuture.cause());
|
||||
ctx.channel()
|
||||
.writeAndFlush(new DefaultHttp2HeadersFrame(
|
||||
new DefaultHttp2Headers().status("502"), true))
|
||||
.addListener(ChannelFutureListener.CLOSE);
|
||||
connectionFactory.release(connectFuture.channel());
|
||||
return;
|
||||
}
|
||||
|
||||
// Connected, open a new H2 stream to the backend so we can proxy the client's frames
|
||||
logger.trace("Opening a HTTP/2 stream to the backend {}", target);
|
||||
logger.trace("Opening a HTTP/2 stream to the backend {}", backendTag);
|
||||
final Channel backendConnection = connectFuture.channel();
|
||||
createBackendProxyStream(ctx, backendConnection, headersFrame, backendTag);
|
||||
createBackendProxyStream(ctx, connectionFactory, backendConnection, headersFrame, backendTag);
|
||||
});
|
||||
}
|
||||
|
||||
/// Create a proxy stream on the provided `backendConnection` that forwards H2 frames to/from the client H2 stream.
|
||||
///
|
||||
/// @param clientStreamCtx The context for a client H2 stream that targets the backend
|
||||
/// @param connectionFactory The factory `backendConnection` came from
|
||||
/// @param backendConnection An established H2 connection [Channel], on which a new h2 stream will be opened
|
||||
/// @param headersFrame The first `headersFrame` from the client h2 stream that should be forwarded to the new
|
||||
/// backend stream
|
||||
/// @param backendTag The backend this stream targets, for metrics
|
||||
private void createBackendProxyStream(
|
||||
final ChannelHandlerContext clientStreamCtx,
|
||||
final H2ConnectionFactory connectionFactory,
|
||||
final Channel backendConnection,
|
||||
final Http2HeadersFrame headersFrame,
|
||||
final String backendTag) {
|
||||
@@ -171,15 +128,13 @@ public class OmnibusH2StreamHandler extends ChannelInboundHandlerAdapter {
|
||||
clientStreamCtx.channel()
|
||||
.writeAndFlush(new DefaultHttp2ResetFrame(Http2Error.INTERNAL_ERROR))
|
||||
.addListener(ChannelFutureListener.CLOSE);
|
||||
backendConnection.close();
|
||||
connectionFactory.release(backendConnection);
|
||||
return;
|
||||
}
|
||||
|
||||
final Http2StreamChannel backendStream = streamFuture.getNow();
|
||||
|
||||
// Close the entire H2 connection whenever the stream we just opened closes. We only plan on using
|
||||
// a single stream on this connection.
|
||||
backendStream.closeFuture().addListener(_ -> backendConnection.close());
|
||||
backendStream.closeFuture().addListener(_ -> connectionFactory.release(backendConnection));
|
||||
|
||||
// We're going to modify the inbound H2 stream channel, which runs on a different eventloop than the
|
||||
// outbound channel we've made to the backend. We have to submit our updates back to the inbound
|
||||
@@ -188,7 +143,7 @@ public class OmnibusH2StreamHandler extends ChannelInboundHandlerAdapter {
|
||||
|
||||
if (!clientStreamCtx.channel().isActive()) {
|
||||
// The client disconnected already and the client pipeline is already torn down.
|
||||
backendConnection.close();
|
||||
backendStream.close();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -204,29 +159,4 @@ public class OmnibusH2StreamHandler extends ChannelInboundHandlerAdapter {
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
private EventLoopGroup selectEventLoop(final ChannelHandlerContext inboundCtx, SocketAddress target) {
|
||||
final boolean localInbound = inboundCtx.channel() instanceof LocalChannel;
|
||||
final boolean localTarget = target instanceof LocalAddress;
|
||||
|
||||
// If the inbound eventloop matches the target type, we can just reuse the inbound's event loop
|
||||
if (localInbound == localTarget) {
|
||||
return inboundCtx.channel().eventLoop();
|
||||
}
|
||||
|
||||
return localTarget ? this.localEventLoopGroup : this.nioEventLoopGroup;
|
||||
}
|
||||
|
||||
private static class NoopInboundStreamHandler extends ChannelInboundHandlerAdapter {
|
||||
@Override
|
||||
public void channelRegistered(final ChannelHandlerContext ctx) {
|
||||
logger.error("Inbound stream handler was registered when no inbound streams expected");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
|
||||
logger.error("Received unexpected message: {} on inbound stream from backend", msg);
|
||||
super.channelRead(ctx, msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,22 +4,21 @@
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.grpc.net;
|
||||
|
||||
import java.net.SocketAddress;
|
||||
import java.util.Map;
|
||||
|
||||
public class OmnibusRouter {
|
||||
|
||||
private final Map<String, SocketAddress> routes;
|
||||
private final SocketAddress defaultBackend;
|
||||
private final Map<String, H2ConnectionFactory> routesByPath;
|
||||
private final H2ConnectionFactory defaultBackend;
|
||||
|
||||
public OmnibusRouter(final Map<String, SocketAddress> routes, final SocketAddress defaultBackend) {
|
||||
this.routes = routes;
|
||||
public OmnibusRouter(final Map<String, H2ConnectionFactory> routesByPath, final H2ConnectionFactory defaultBackend) {
|
||||
this.routesByPath = routesByPath;
|
||||
this.defaultBackend = defaultBackend;
|
||||
}
|
||||
|
||||
SocketAddress match(final String fullPath) {
|
||||
H2ConnectionFactory match(final String fullPath) {
|
||||
final int queryIndex = fullPath.indexOf('?');
|
||||
final String path = queryIndex >= 0 ? fullPath.substring(0, queryIndex) : fullPath;
|
||||
return routes.getOrDefault(path, defaultBackend);
|
||||
return routesByPath.getOrDefault(path, defaultBackend);
|
||||
}
|
||||
}
|
||||
+187
@@ -0,0 +1,187 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.grpc.net;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import io.netty.channel.Channel;
|
||||
import io.netty.channel.ChannelFuture;
|
||||
import io.netty.channel.ChannelHandler;
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.channel.ChannelInboundHandlerAdapter;
|
||||
import io.netty.channel.EventLoop;
|
||||
import io.netty.channel.EventLoopGroup;
|
||||
import io.netty.handler.codec.http2.DefaultHttp2WindowUpdateFrame;
|
||||
import io.netty.handler.codec.http2.Http2CodecUtil;
|
||||
import io.netty.handler.codec.http2.Http2GoAwayFrame;
|
||||
import io.netty.util.AttributeKey;
|
||||
import io.netty.util.ReferenceCountUtil;
|
||||
import java.net.SocketAddress;
|
||||
import java.time.Duration;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import org.whispersystems.textsecuregcm.util.ClosableEpoch;
|
||||
|
||||
/// An [H2ConnectionFactory] that creates one shared h2 connection per calling event loop.
|
||||
///
|
||||
/// A connection is replaced the next time it's requested if it failed to connect, has closed, has received a GOAWAY, or
|
||||
/// is older than `retireAfterNanos`. Retiring connections bounds how many stream IDs a connection uses since eventually
|
||||
/// stream-ids are exhausted.
|
||||
///
|
||||
/// A replaced connection is never handed out again, and is closed once every stream it was handed out for has been
|
||||
/// [#release]ed.
|
||||
public class PooledH2ConnectionFactory implements H2ConnectionFactory {
|
||||
|
||||
private static final AttributeKey<Boolean> GOAWAY_RECEIVED =
|
||||
AttributeKey.valueOf(PooledH2ConnectionFactory.class, "goawayReceived");
|
||||
|
||||
// Key for a [ClosableEpoch] attached to every new connection's channel. When the connection is replaced,
|
||||
// [ClosableEpoch#close] is called, and when all streams are released the underlying netty channel is closed.
|
||||
private static final AttributeKey<ClosableEpoch> CONNECTION_EPOCH =
|
||||
AttributeKey.valueOf(PooledH2ConnectionFactory.class, "connection_epoch");
|
||||
|
||||
private static final PooledConnectionHandler POOLED_CONNECTION_HANDLER = new PooledConnectionHandler();
|
||||
|
||||
private static final String CONNECTION_REPLACED_COUNTER_NAME =
|
||||
name(PooledH2ConnectionFactory.class, "connectionReplaced");
|
||||
private static final String OPEN_CONNECTIONS_GAUGE_NAME = name(PooledH2ConnectionFactory.class, "openConnections");
|
||||
|
||||
// How long to use a pooled connection for
|
||||
private static final Duration RETIRE_AFTER = Duration.ofMinutes(30);
|
||||
|
||||
private final UnpooledH2ConnectionFactory connectionFactory;
|
||||
private final long retireAfterNanos;
|
||||
|
||||
private final ConcurrentHashMap<EventLoop, PooledConnection> connectionsByCallerEventLoop = new ConcurrentHashMap<>();
|
||||
// Count of all open connections (including replaced ones waiting for outstanding streams to terminate)
|
||||
private final AtomicInteger openConnections;
|
||||
|
||||
private record PooledConnection(ChannelFuture connectFuture, long createdNanos) {}
|
||||
|
||||
/// Create a pooled H2 connection factory
|
||||
///
|
||||
/// @param targetAddress The [SocketAddress] connections should target
|
||||
/// @param eventLoopGroup The eventLoopGroup on which connections will be made. Must match the type of the [SocketAddress]
|
||||
public PooledH2ConnectionFactory(final SocketAddress targetAddress, final EventLoopGroup eventLoopGroup) {
|
||||
this(targetAddress, eventLoopGroup, RETIRE_AFTER);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
PooledH2ConnectionFactory(final SocketAddress targetAddress,
|
||||
final EventLoopGroup eventLoopGroup,
|
||||
final Duration retireAfter) {
|
||||
this.connectionFactory = new UnpooledH2ConnectionFactory(targetAddress, eventLoopGroup, POOLED_CONNECTION_HANDLER);
|
||||
this.retireAfterNanos = retireAfter.toNanos();
|
||||
this.openConnections = Metrics.gauge(OPEN_CONNECTIONS_GAUGE_NAME, Tags.of("backend", targetAddress.toString()),
|
||||
new AtomicInteger());
|
||||
}
|
||||
|
||||
@Override
|
||||
public ChannelFuture getConnectionChannelFuture(final EventLoop callerEventLoop) {
|
||||
assert callerEventLoop.inEventLoop();
|
||||
|
||||
final ChannelFuture connection = connectionsByCallerEventLoop.compute(callerEventLoop, (_, existing) -> {
|
||||
if (existing == null) {
|
||||
return newConnection(callerEventLoop);
|
||||
} else if (!isUsable(existing)) {
|
||||
existing.connectFuture().channel().attr(CONNECTION_EPOCH).get().close();
|
||||
return newConnection(callerEventLoop);
|
||||
} else {
|
||||
return existing;
|
||||
}
|
||||
})
|
||||
.connectFuture();
|
||||
|
||||
// Compute always hands us a connection with an open epoch and we can't race with anyone because we're in
|
||||
// callerEventLoop, so we should always be able to enter the epoch
|
||||
final boolean arrived = connection.channel().attr(CONNECTION_EPOCH).get().tryArrive();
|
||||
assert arrived;
|
||||
|
||||
return connection;
|
||||
}
|
||||
|
||||
private PooledConnection newConnection(final EventLoop callerEventLoop) {
|
||||
final ChannelFuture connectFuture = connectionFactory.getConnectionChannelFuture(callerEventLoop);
|
||||
final Channel channel = connectFuture.channel();
|
||||
channel.attr(CONNECTION_EPOCH).set(new ClosableEpoch(channel::close));
|
||||
openConnections.incrementAndGet();
|
||||
channel.closeFuture().addListener(_ -> openConnections.decrementAndGet());
|
||||
return new PooledConnection(connectFuture, System.nanoTime());
|
||||
}
|
||||
|
||||
/// Whether a pooled connection can still be handed out
|
||||
private boolean isUsable(final PooledConnection pooledConnection) {
|
||||
final ChannelFuture connectionFuture = pooledConnection.connectFuture();
|
||||
if (!connectionFuture.isDone()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
final Channel connection = connectionFuture.channel();
|
||||
|
||||
// We know the future is done, see if we actually connected or if we've since disconnected
|
||||
final boolean active = connection.isActive();
|
||||
|
||||
// We might still be connected but have gotten a GOAWAY indicating we shouldn't open new streams
|
||||
final boolean goawayReceived = Boolean.TRUE.equals(connection.attr(GOAWAY_RECEIVED).get());
|
||||
|
||||
// The connection might be fine but old enough that we want a fresh one
|
||||
final boolean retired = System.nanoTime() - pooledConnection.createdNanos() > retireAfterNanos;
|
||||
|
||||
final boolean usable = active && !goawayReceived && !retired;
|
||||
if (!usable) {
|
||||
Metrics.counter(CONNECTION_REPLACED_COUNTER_NAME,
|
||||
"backend", address().toString(),
|
||||
"active", String.valueOf(active),
|
||||
"goaway", String.valueOf(goawayReceived),
|
||||
"retired", String.valueOf(retired))
|
||||
.increment();
|
||||
}
|
||||
return usable;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void release(final Channel connection) {
|
||||
connection.attr(CONNECTION_EPOCH).get().depart();
|
||||
}
|
||||
|
||||
@Override
|
||||
public SocketAddress address() {
|
||||
return connectionFactory.address();
|
||||
}
|
||||
|
||||
/// Initializes the connection with a large window, and marks a connection as draining when the backend sends a GOAWAY
|
||||
@ChannelHandler.Sharable
|
||||
private static class PooledConnectionHandler extends ChannelInboundHandlerAdapter {
|
||||
@Override
|
||||
public void channelActive(final ChannelHandlerContext ctx) {
|
||||
// Every new H2 connection starts with a connection flow-control window of 64K. Each stream on the connection also
|
||||
// starts with a per-stream window of 64K. See https://www.rfc-editor.org/rfc/rfc9113.html#section-6.9.2.
|
||||
//
|
||||
// Because we're pooling many distinct, h2 streams from different remote clients may share this single h2
|
||||
// connection to the backend. So, by default, if a single stream is slow to receive a large response from the
|
||||
// backend, they could consume the entire connection window.
|
||||
//
|
||||
// To avoid this, as soon as we open the connection tell the server we're willing to accept more at the connection
|
||||
// level. We update the connection window to the max value by sending a WINDOW_UPDATE (6.9) to add enough credit
|
||||
// to reach the max connection window size of INT_MAX. The individual streams still retain the default window-size
|
||||
// of 64K.
|
||||
ctx.writeAndFlush(new DefaultHttp2WindowUpdateFrame(Integer.MAX_VALUE - Http2CodecUtil.DEFAULT_WINDOW_SIZE));
|
||||
ctx.fireChannelActive();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void channelRead(final ChannelHandlerContext ctx, final Object msg) {
|
||||
if (msg instanceof Http2GoAwayFrame) {
|
||||
ctx.channel().attr(GOAWAY_RECEIVED).set(true);
|
||||
ReferenceCountUtil.release(msg);
|
||||
return;
|
||||
}
|
||||
ctx.fireChannelRead(msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -100,12 +100,7 @@ public class SniMapper {
|
||||
private static SslContext buildSslContext(final KeyManagerFactory kmf, final SslProvider sslProvider)
|
||||
throws SSLException {
|
||||
|
||||
final SslContextBuilder sslContextBuilder = sslProvider == SslProvider.OPENSSL
|
||||
// work around netty's OpenSSL provider not selecting Ed25519 certificates on its own
|
||||
? SslContextBuilder.forServer(BoringSslServerKeyManager.wrap(kmf.getKeyManagers()))
|
||||
: SslContextBuilder.forServer(kmf);
|
||||
|
||||
return sslContextBuilder
|
||||
return SslContextBuilder.forServer(kmf)
|
||||
.sslProvider(sslProvider)
|
||||
.applicationProtocolConfig(new ApplicationProtocolConfig(
|
||||
ApplicationProtocolConfig.Protocol.ALPN,
|
||||
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.grpc.net;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
import io.netty.bootstrap.Bootstrap;
|
||||
import io.netty.channel.Channel;
|
||||
import io.netty.channel.ChannelFuture;
|
||||
import io.netty.channel.ChannelHandler;
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.channel.ChannelInboundHandlerAdapter;
|
||||
import io.netty.channel.ChannelInitializer;
|
||||
import io.netty.channel.EventLoop;
|
||||
import io.netty.channel.EventLoopGroup;
|
||||
import io.netty.channel.local.LocalAddress;
|
||||
import io.netty.channel.local.LocalChannel;
|
||||
import io.netty.channel.socket.nio.NioSocketChannel;
|
||||
import io.netty.handler.codec.http2.Http2FrameCodecBuilder;
|
||||
import io.netty.handler.codec.http2.Http2MultiplexHandler;
|
||||
import io.netty.handler.codec.http2.Http2Settings;
|
||||
import io.netty.util.concurrent.EventExecutor;
|
||||
import java.net.SocketAddress;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import javax.annotation.Nullable;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class UnpooledH2ConnectionFactory implements H2ConnectionFactory {
|
||||
private static final Logger logger = LoggerFactory.getLogger(UnpooledH2ConnectionFactory.class);
|
||||
|
||||
private static final OmnibusExceptionHandler BACKEND_CONNECTION_EXCEPTION_HANDLER =
|
||||
new OmnibusExceptionHandler("backend-connection", List.of());
|
||||
private static final String BACKEND_CONNECT_TIMER_NAME = name(UnpooledH2ConnectionFactory.class,
|
||||
"backendConnectDuration");
|
||||
private static final String BACKEND_TAG = "backend";
|
||||
|
||||
|
||||
private final SocketAddress targetAddress;
|
||||
private final Class<? extends Channel> channelClass;
|
||||
private final EventLoopGroup eventLoopGroup;
|
||||
private final Set<EventExecutor> eventLoops;
|
||||
@Nullable
|
||||
private final ChannelHandler connectionHandler;
|
||||
|
||||
public UnpooledH2ConnectionFactory(final SocketAddress targetAddress, final EventLoopGroup eventLoopGroup) {
|
||||
this(targetAddress, eventLoopGroup, null);
|
||||
}
|
||||
|
||||
UnpooledH2ConnectionFactory(
|
||||
final SocketAddress targetAddress,
|
||||
final EventLoopGroup eventLoopGroup,
|
||||
@Nullable final ChannelHandler connectionHandler) {
|
||||
this.targetAddress = targetAddress;
|
||||
this.channelClass = targetAddress instanceof LocalAddress ? LocalChannel.class : NioSocketChannel.class;
|
||||
this.eventLoopGroup = eventLoopGroup;
|
||||
this.eventLoops = ImmutableSet.copyOf(eventLoopGroup);
|
||||
this.connectionHandler = connectionHandler;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ChannelFuture getConnectionChannelFuture(final EventLoop callerEventLoop) {
|
||||
// Make a new H2 connection to the target backend
|
||||
final Timer.Sample connectSample = Timer.start();
|
||||
|
||||
return new Bootstrap()
|
||||
// If the caller is already on one of our event loops, connect on that loop so this connection runs on the
|
||||
// caller's thread
|
||||
.group(eventLoops.contains(callerEventLoop) ? callerEventLoop : eventLoopGroup)
|
||||
.channel(channelClass)
|
||||
.handler(new ChannelInitializer<>() {
|
||||
@Override
|
||||
protected void initChannel(final Channel ch) {
|
||||
ch.pipeline()
|
||||
.addLast(Http2FrameCodecBuilder.forClient().initialSettings(Http2Settings.defaultSettings()).build());
|
||||
// Http2MultiplexHandler takes handler that is added to new inbound streams. A client Http2MultiplexHandler
|
||||
// like we're defining here should never receive an inbound H2 stream so we can just pass a noop handler
|
||||
ch.pipeline().addLast(new Http2MultiplexHandler(new NoopInboundStreamHandler()));
|
||||
if (connectionHandler != null) {
|
||||
ch.pipeline().addLast(connectionHandler);
|
||||
}
|
||||
ch.pipeline().addLast(BACKEND_CONNECTION_EXCEPTION_HANDLER);
|
||||
}
|
||||
})
|
||||
.connect(targetAddress)
|
||||
.addListener((ChannelFuture connectFuture) ->
|
||||
connectSample.stop(Timer.builder(BACKEND_CONNECT_TIMER_NAME)
|
||||
.tag(BACKEND_TAG, targetAddress.toString())
|
||||
.tag("outcome", connectFuture.isSuccess() ? "success" : "failure")
|
||||
.register(Metrics.globalRegistry)));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void release(final Channel connection) {
|
||||
// Each connection only ever carries one stream
|
||||
connection.close();
|
||||
}
|
||||
|
||||
@Override
|
||||
public SocketAddress address() {
|
||||
return targetAddress;
|
||||
}
|
||||
|
||||
private static class NoopInboundStreamHandler extends ChannelInboundHandlerAdapter {
|
||||
@Override
|
||||
public void channelRegistered(final ChannelHandlerContext ctx) {
|
||||
logger.error("Inbound stream handler was registered when no inbound streams expected");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
|
||||
logger.error("Received unexpected message: {} on inbound stream from backend", msg);
|
||||
super.channelRead(ctx, msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -184,7 +184,8 @@ public class KeyTransparencyServiceClient implements Managed {
|
||||
channel = Grpc.newChannelBuilderForAddress(host, port, tlsChannelCredentials)
|
||||
.idleTimeout(1, TimeUnit.MINUTES)
|
||||
.build();
|
||||
stub = KeyTransparencyQueryServiceGrpc.newBlockingStub(channel);
|
||||
stub = KeyTransparencyQueryServiceGrpc.newBlockingStub(channel)
|
||||
.withCompression("gzip");
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -51,6 +51,8 @@ public final class MessageMetrics {
|
||||
private static final String DISPLACEMENT_COUNTER_NAME = name(WebSocketConnection.class, "displacement");
|
||||
private static final Duration SLOW_DRAIN_THRESHOLD = Duration.ofSeconds(10);
|
||||
|
||||
private static final String SUSPECTED_DELIVERY_LOOP_COUNTER_NAME = name(MessageMetrics.class, "suspectedDeliveryLoop");
|
||||
|
||||
private final MeterRegistry metricRegistry;
|
||||
private final Counter sendMessageCounter;
|
||||
private final Counter bytesSentCounter;
|
||||
@@ -145,4 +147,16 @@ public final class MessageMetrics {
|
||||
.tags(Tags.of(UserAgentTagUtil.getPlatformTag(userAgent), Tag.of("channel", channel)))
|
||||
.register(metricRegistry));
|
||||
}
|
||||
|
||||
public static void recordSuspectedDeliveryLoop(final String channel,
|
||||
@Nullable final UserAgent userAgent,
|
||||
final ClientReleaseManager clientReleaseManager) {
|
||||
|
||||
final Tags tags = UserAgentTagUtil.getClientVersionTag(userAgent, clientReleaseManager)
|
||||
.map(Tags::of)
|
||||
.orElseGet(Tags::empty)
|
||||
.and(UserAgentTagUtil.getPlatformTag(userAgent));
|
||||
|
||||
Metrics.counter(SUSPECTED_DELIVERY_LOOP_COUNTER_NAME, tags).increment();
|
||||
}
|
||||
}
|
||||
+1
-6
@@ -8,7 +8,6 @@ package org.whispersystems.textsecuregcm.metrics;
|
||||
import ch.qos.logback.classic.LoggerContext;
|
||||
import ch.qos.logback.classic.spi.ILoggingEvent;
|
||||
import ch.qos.logback.core.Appender;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.annotation.JsonTypeName;
|
||||
import io.dropwizard.logging.common.AbstractAppenderFactory;
|
||||
import io.dropwizard.logging.common.async.AsyncAppenderFactory;
|
||||
@@ -19,9 +18,6 @@ import io.opentelemetry.instrumentation.logback.appender.v1_0.OpenTelemetryAppen
|
||||
@JsonTypeName("otlp")
|
||||
public class OpenTelemetryAppenderFactory extends AbstractAppenderFactory<ILoggingEvent> {
|
||||
|
||||
@JsonProperty
|
||||
private String destination;
|
||||
|
||||
@Override
|
||||
public Appender<ILoggingEvent> build(
|
||||
final LoggerContext context,
|
||||
@@ -32,8 +28,7 @@ public class OpenTelemetryAppenderFactory extends AbstractAppenderFactory<ILoggi
|
||||
|
||||
final OpenTelemetryAppender appender = new OpenTelemetryAppender();
|
||||
appender.setCaptureCodeAttributes(true);
|
||||
appender.setCaptureLoggerContext(true);
|
||||
appender.setCaptureLogstashMarkerAttributes(true);
|
||||
appender.setKeyValuePairAttributesIncluded("*");
|
||||
|
||||
// The installation of an OpenTelemetry configuration happens in
|
||||
// WhisperServerService (or CommandDependencies), in order to let us tie
|
||||
|
||||
+4
-6
@@ -8,10 +8,8 @@ package org.whispersystems.textsecuregcm.metrics;
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import net.logstash.logback.marker.Markers;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
@@ -49,10 +47,10 @@ public class ReportedMessageMetricsListener implements ReportedMessageListener {
|
||||
accountsManager.getByAccountIdentifier(reporterUuid).ifPresent(reporter -> {
|
||||
final String destinationCountryCode = Util.getCountryCode(reporter);
|
||||
|
||||
logger.info(Markers.appendEntries(Map.of(
|
||||
"sourceCountry", sourceCountryCode,
|
||||
"destinationCountry", destinationCountryCode)),
|
||||
"Message reported");
|
||||
logger.atInfo()
|
||||
.addKeyValue("sourceCountry", sourceCountryCode)
|
||||
.addKeyValue("destinationCountry", destinationCountryCode)
|
||||
.log("Message reported");
|
||||
|
||||
Metrics.counter(REPORTER_COUNTER_NAME, COUNTRY_CODE_TAG_NAME, destinationCountryCode).increment();
|
||||
});
|
||||
|
||||
@@ -365,7 +365,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor,
|
||||
// since badge redemption is untrackable by design and unrevokable, subscription changes must be immediate and
|
||||
// not prorated
|
||||
.setProrationBehavior(ProrationBehavior.NONE)
|
||||
.setBillingCycleAnchor(BillingCycleAnchor.NOW)
|
||||
.setBillingCycleAnchor(BillingCycleAnchor.builder().setType(BillingCycleAnchor.Type.NOW).build())
|
||||
.setOffSession(true)
|
||||
.setPaymentBehavior(SubscriptionUpdateParams.PaymentBehavior.ERROR_IF_INCOMPLETE)
|
||||
.addAllItem(items)
|
||||
|
||||
+5
-5
@@ -170,22 +170,22 @@ public class RegistrationServiceClient implements Managed {
|
||||
throw new RegistrationServiceException(buildSessionResponseFromMetadata(response.getSessionMetadata()));
|
||||
|
||||
case SEND_VERIFICATION_CODE_ERROR_TYPE_SENDER_REJECTED ->
|
||||
throw RegistrationServiceSenderException.rejected(response.getError().getMayRetry());
|
||||
throw RegistrationServiceSenderException.rejected(!response.getError().getMayRetry());
|
||||
|
||||
case SEND_VERIFICATION_CODE_ERROR_TYPE_SUSPECTED_FRAUD ->
|
||||
throw new RegistrationFraudException(
|
||||
RegistrationServiceSenderException.rejected(response.getError().getMayRetry()));
|
||||
RegistrationServiceSenderException.rejected(!response.getError().getMayRetry()));
|
||||
|
||||
case SEND_VERIFICATION_CODE_ERROR_TYPE_SENDER_ILLEGAL_ARGUMENT ->
|
||||
throw RegistrationServiceSenderException.illegalArgument(response.getError().getMayRetry());
|
||||
throw RegistrationServiceSenderException.illegalArgument(!response.getError().getMayRetry());
|
||||
|
||||
case SEND_VERIFICATION_CODE_ERROR_TYPE_UNSPECIFIED ->
|
||||
throw RegistrationServiceSenderException.unknown(response.getError().getMayRetry());
|
||||
throw RegistrationServiceSenderException.unknown(!response.getError().getMayRetry());
|
||||
|
||||
case SEND_VERIFICATION_CODE_ERROR_TYPE_TRANSPORT_NOT_ALLOWED ->
|
||||
throw new TransportNotAllowedException(buildSessionResponseFromMetadata(response.getSessionMetadata()));
|
||||
case SEND_VERIFICATION_CODE_ERROR_NO_SENDER_AVAILABLE ->
|
||||
throw RegistrationServiceSenderException.unavailable(response.getError().getMayRetry());
|
||||
throw RegistrationServiceSenderException.unavailable(!response.getError().getMayRetry());
|
||||
|
||||
default -> throw new RuntimeException("Failed to send verification code: " + response.getError().getErrorType());
|
||||
}
|
||||
|
||||
@@ -71,6 +71,7 @@ import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialPresentation;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestManager;
|
||||
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
|
||||
import org.whispersystems.textsecuregcm.auth.webauthn.AuthenticationCeremonyParameters;
|
||||
import org.whispersystems.textsecuregcm.auth.webauthn.RegistrationCeremonyParameters;
|
||||
import org.whispersystems.textsecuregcm.auth.webauthn.RegistrationCeremonyResult;
|
||||
@@ -1377,6 +1378,43 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
});
|
||||
}
|
||||
|
||||
/// Sets a new password for the given device and requests disconnection for all authenticated device connections.
|
||||
///
|
||||
///
|
||||
/// @return `true` if the password was changed or `false` if the device no longer exists or its credentials
|
||||
/// have been locked
|
||||
public boolean updateDevicePassword(final UUID accountIdentifier, final byte deviceId, final String newPassword) {
|
||||
|
||||
final SaltedTokenHash newCredentials = SaltedTokenHash.generateFor(newPassword);
|
||||
|
||||
final Account updatedAccount = update(accountIdentifier, a -> {
|
||||
|
||||
final Optional<Device> maybeDevice = a.getDevice(deviceId);
|
||||
|
||||
return maybeDevice.map(d -> {
|
||||
|
||||
if (d.hasLockedCredentials()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
d.setAuthTokenHash(newCredentials);
|
||||
|
||||
return true;
|
||||
|
||||
}).orElse(false);
|
||||
});
|
||||
|
||||
final boolean passwordChanged = updatedAccount.getDevice(deviceId)
|
||||
.map(d -> d.getAuthTokenHash().equals(newCredentials))
|
||||
.orElse(false);
|
||||
|
||||
if (passwordChanged) {
|
||||
disconnectionRequestManager.requestDisconnection(accountIdentifier, List.of(deviceId));
|
||||
}
|
||||
|
||||
return passwordChanged;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param accountIdentifier identifier of account to update
|
||||
* @param updater must return {@code true} if the account was actually updated
|
||||
|
||||
+15
-5
@@ -7,20 +7,23 @@ package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Flow;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStream;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import reactor.adapter.JdkFlowAdapter;
|
||||
import reactor.core.publisher.Flux;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Flow;
|
||||
|
||||
public class ConcatenatingMessageStream implements MessageStream {
|
||||
|
||||
private final DynamoDbMessageStream dynamoDbMessageStream;
|
||||
private final FoundationDbMessageStream foundationDbMessageStream;
|
||||
|
||||
private final AtomicBoolean shouldDeleteFromDynamoDb = new AtomicBoolean(false);
|
||||
|
||||
private static final Counter CONFLICTING_CONSUMER_COUNTER =
|
||||
Metrics.counter(MetricsUtil.name(ConcatenatingMessageStream.class, "conflictingConsumer"));
|
||||
|
||||
@@ -34,7 +37,12 @@ public class ConcatenatingMessageStream implements MessageStream {
|
||||
@Override
|
||||
public Flow.Publisher<MessageStreamEntry> getMessages() {
|
||||
return JdkFlowAdapter.publisherToFlowPublisher(Flux.concat(
|
||||
JdkFlowAdapter.flowPublisherToFlux(dynamoDbMessageStream.getMessages()),
|
||||
JdkFlowAdapter.flowPublisherToFlux(dynamoDbMessageStream.getMessages())
|
||||
.doOnNext(messageStreamEntry -> {
|
||||
if (messageStreamEntry instanceof MessageStreamEntry.Envelope) {
|
||||
shouldDeleteFromDynamoDb.set(true);
|
||||
}
|
||||
}),
|
||||
JdkFlowAdapter.flowPublisherToFlux(foundationDbMessageStream.getMessages()))
|
||||
.doOnError(throwable -> {
|
||||
if (ExceptionUtils.unwrap(throwable) instanceof ConflictingMessageConsumerException) {
|
||||
@@ -46,7 +54,9 @@ public class ConcatenatingMessageStream implements MessageStream {
|
||||
@Override
|
||||
public CompletableFuture<Void> acknowledgeMessage(final UUID messageGuid, final long serverTimestamp) {
|
||||
return CompletableFuture.allOf(
|
||||
dynamoDbMessageStream.acknowledgeMessage(messageGuid, serverTimestamp),
|
||||
shouldDeleteFromDynamoDb.get()
|
||||
? dynamoDbMessageStream.acknowledgeMessage(messageGuid, serverTimestamp)
|
||||
: CompletableFuture.completedFuture(null),
|
||||
messageGuid.version() == 8
|
||||
? foundationDbMessageStream.acknowledgeMessage(messageGuid, serverTimestamp)
|
||||
: CompletableFuture.completedFuture(null));
|
||||
|
||||
+4
-2
@@ -17,9 +17,11 @@ public enum DeviceCapability {
|
||||
TRANSFER("transfer", AccountCapabilityMode.PRIMARY_DEVICE, AccountCapabilityVisibility.SERVER, false, false),
|
||||
ATTACHMENT_BACKFILL("attachmentBackfill", AccountCapabilityMode.PRIMARY_DEVICE, AccountCapabilityVisibility.SELF, false, false),
|
||||
SPARSE_POST_QUANTUM_RATCHET("spqr", AccountCapabilityMode.ALL_DEVICES, AccountCapabilityVisibility.PUBLIC, true, true),
|
||||
PROFILES_V2("profiles_v2", AccountCapabilityMode.ALL_DEVICES, AccountCapabilityVisibility.SELF, false, false),
|
||||
USERNAME_CHANGE_SYNC_MESSAGE("usernameChangeSyncMessage", AccountCapabilityMode.ALL_DEVICES, AccountCapabilityVisibility.SELF, true, false),
|
||||
OPTIONAL_PHONE_NUMBER("optionalPhoneNumber", AccountCapabilityMode.ALL_DEVICES, AccountCapabilityVisibility.SERVER, false, false);
|
||||
OPTIONAL_PHONE_NUMBER("optionalPhoneNumber", AccountCapabilityMode.ALL_DEVICES, AccountCapabilityVisibility.SERVER, false, false),
|
||||
REPLY_PRIVATELY("replyPrivately", AccountCapabilityMode.ALL_DEVICES, AccountCapabilityVisibility.PUBLIC, false, false),
|
||||
CONTACT_DELETE("contactDelete", AccountCapabilityMode.ALL_DEVICES, AccountCapabilityVisibility.PUBLIC, false, false),
|
||||
ADMIN_REMOVE_AND_DELETE("adminRemoveAndDelete", AccountCapabilityMode.ALL_DEVICES, AccountCapabilityVisibility.PUBLIC, false, false);
|
||||
|
||||
public static final List<DeviceCapability> PUBLIC_VISIBLE_CAPABILITIES = Arrays.stream(DeviceCapability.values())
|
||||
.filter(c -> c.accountCapabilityVisibility == AccountCapabilityVisibility.PUBLIC)
|
||||
|
||||
+19
-1
@@ -5,6 +5,7 @@
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import com.apple.foundationdb.FDBException;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.protobuf.ByteString;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
@@ -16,6 +17,7 @@ import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.UnaryOperator;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
@@ -39,6 +41,9 @@ public class MessagesManager {
|
||||
private final ExecutorService messageDeletionExecutor;
|
||||
private final Clock clock;
|
||||
|
||||
@VisibleForTesting
|
||||
static final long DELIVERY_LOOP_READ_THRESHOLD = 10;
|
||||
|
||||
public MessagesManager(
|
||||
final MessagesDynamoDb messagesDynamoDb,
|
||||
final FoundationDbMessageStore foundationDbMessageStore,
|
||||
@@ -222,6 +227,19 @@ public class MessagesManager {
|
||||
.toFuture();
|
||||
}
|
||||
|
||||
/// Checks whether the given device is in a suspected "delivery loop" where it is repeatedly requesting but not
|
||||
/// acknowledging messages.
|
||||
///
|
||||
/// @param accountIdentifier the identifier of the account to check for a delivery loop
|
||||
/// @param deviceId the ID of the device to check for a delivery loop
|
||||
///
|
||||
/// @return a future that yields `true` if the identified device is suspected of being stuck in a message delivery
|
||||
/// loop or `false` otherwise
|
||||
public CompletableFuture<Boolean> hasSuspectedDeliveryLoop(final UUID accountIdentifier, final byte deviceId) {
|
||||
return foundationDbMessageStore.getReadsSinceLastAcknowledgedMessage(new AciServiceIdentifier(accountIdentifier), deviceId)
|
||||
.thenApply(readsSinceLastAcknowledgedMessage -> readsSinceLastAcknowledgedMessage >= DELIVERY_LOOP_READ_THRESHOLD);
|
||||
}
|
||||
|
||||
/// Record versionstamps for the current time in the FoundationDB database(s).
|
||||
public void recordFoundationDbVersionstamps() {
|
||||
foundationDbMessageStore.recordVersionstamps();
|
||||
@@ -263,7 +281,7 @@ public class MessagesManager {
|
||||
final long rangeSplitChunkSizeBytes,
|
||||
final boolean dryRun) {
|
||||
// All trims will be considered successful during a dry run
|
||||
final UnaryOperator<Mono<Boolean>> deleteModifier = dryRun ? _ -> Mono.just(true) : UnaryOperator.identity();
|
||||
final Function<Mono<Boolean>, Mono<Boolean>> deleteModifier = dryRun ? _ -> Mono.just(true) : Function.identity();
|
||||
return foundationDbMessageStore.trimQueue(aci, device, maxQueueSizeBytes, targetQueueSizeBytes, rangeSplitChunkSizeBytes, deleteModifier);
|
||||
}
|
||||
}
|
||||
@@ -102,11 +102,7 @@ public class ProfilesManager {
|
||||
redisSet(uuid, null, versionedProfile);
|
||||
|
||||
try {
|
||||
// until the PROFILES_V2 capability prevents downgrades, if a client sets a v2 profile, and then the account
|
||||
// downgrades to v1, all v2 profiles are stale
|
||||
assert !DeviceCapability.PROFILES_V2.preventDowngrade();
|
||||
|
||||
profilesV2.deleteAll(uuid);
|
||||
profilesV2.deleteAll(uuid).join();
|
||||
} catch (final Exception e) {
|
||||
logger.warn("Failed to delete v2 profile data: {}", uuid, e);
|
||||
}
|
||||
|
||||
-84
@@ -1,84 +0,0 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.storage.devicecheck;
|
||||
|
||||
import com.webauthn4j.appattest.DeviceCheckManager;
|
||||
import com.webauthn4j.appattest.data.DCAssertion;
|
||||
import com.webauthn4j.appattest.data.DCAssertionData;
|
||||
import com.webauthn4j.appattest.data.DCAssertionRequest;
|
||||
import com.webauthn4j.converter.AuthenticatorDataConverter;
|
||||
import com.webauthn4j.converter.exception.DataConversionException;
|
||||
import com.webauthn4j.converter.util.ObjectConverter;
|
||||
import com.webauthn4j.data.attestation.authenticator.AuthenticatorData;
|
||||
import com.webauthn4j.data.extension.authenticator.AuthenticationExtensionAuthenticatorOutput;
|
||||
import tools.jackson.core.JacksonException;
|
||||
import java.util.Arrays;
|
||||
|
||||
/// Parses Apple App Attest assertions
|
||||
///
|
||||
/// App Attest assertions since iOS 27 include an extensions map and don't include attested credential data. They
|
||||
/// set the AT flag which indicates data, so a standards-compliant parser barfs because there's an extensions map where
|
||||
/// the AT data should/ be.
|
||||
///
|
||||
/// If Apple fixes their headers or webauthn4j adopts some workaround, this class should be removed
|
||||
///
|
||||
/// [webauthn4j #1497](https://github.com/webauthn4j/webauthn4j/issues/1497)
|
||||
/// [webauthn4j #1518](https://github.com/webauthn4j/webauthn4j/pull/1518)
|
||||
class AppAttestAssertionConverter {
|
||||
|
||||
// https://www.w3.org/TR/webauthn/#sctn-authenticator-data
|
||||
// rpIdHash(32) || flags(1) || signCount(4) || attestedCredentialData(variable) || extensions(variable)
|
||||
private static final int FLAGS_OFFSET = 32;
|
||||
private static final int HEADER_LENGTH = 37;
|
||||
|
||||
// https://www.rfc-editor.org/info/rfc8949/#section-3.1:~:text=the%20CBOR%20Encoding-,3.1%20Major%20Types,-3.2%20Indefinite%20Lengths
|
||||
// CBOR major type 5 (map), covering both definite and indefinite length maps
|
||||
private static final int CBOR_MAJOR_TYPE_MASK = 0xe0;
|
||||
private static final int CBOR_MAP_MAJOR_TYPE = 0xa0;
|
||||
|
||||
private static final ObjectConverter OBJECT_CONVERTER = DeviceCheckManager.createObjectConverter();
|
||||
private static final AuthenticatorDataConverter AUTHENTICATOR_DATA_CONVERTER = new AuthenticatorDataConverter(OBJECT_CONVERTER);
|
||||
|
||||
/// Parse an assertion request that potentially has misconfigured FLAGS. The returned data must still be verified.
|
||||
static DCAssertionData parseAppleAssertion(final DCAssertionRequest request) throws DataConversionException {
|
||||
final DCAssertion assertion = OBJECT_CONVERTER.getCborMapper().readValue(request.getAssertion(), DCAssertion.class);
|
||||
final byte[] authenticatorDataBytes = assertion == null ? null : assertion.getAuthenticatorData();
|
||||
final AuthenticatorData<AuthenticationExtensionAuthenticatorOutput> authenticatorData =
|
||||
authenticatorDataBytes == null ? null : convertAuthenticatorData(authenticatorDataBytes);
|
||||
return new DCAssertionData(request.getKeyId(), authenticatorData, authenticatorDataBytes,
|
||||
request.getClientDataHash(), assertion == null ? null : assertion.getSignature());
|
||||
}
|
||||
|
||||
private static AuthenticatorData<AuthenticationExtensionAuthenticatorOutput> convertAuthenticatorData(final byte[] original) {
|
||||
if (!hasAppleAssertionExtensions(original)) {
|
||||
return AUTHENTICATOR_DATA_CONVERTER.convert(original);
|
||||
}
|
||||
|
||||
final AuthenticatorData<AuthenticationExtensionAuthenticatorOutput> parsed;
|
||||
try {
|
||||
// Create a copy just for parsing and set the flags as Apple should have set them
|
||||
final byte[] modified = Arrays.copyOf(original, original.length);
|
||||
modified[FLAGS_OFFSET] = (byte) ((original[FLAGS_OFFSET] & ~AuthenticatorData.BIT_AT) | AuthenticatorData.BIT_ED);
|
||||
parsed = AUTHENTICATOR_DATA_CONVERTER.convert(modified);
|
||||
} catch (final JacksonException _) {
|
||||
// Jackson error messages can include the (untrusted) extension contents
|
||||
throw new DataConversionException("Invalid App Attest assertion extension data");
|
||||
}
|
||||
|
||||
// Return the parsed structures but keep the original (incorrect) flags, so signature validation works
|
||||
return new AuthenticatorData<>(parsed.getRpIdHash(), original[FLAGS_OFFSET], parsed.getSignCount(),
|
||||
parsed.getExtensions());
|
||||
}
|
||||
|
||||
private static boolean hasAppleAssertionExtensions(final byte[] data) {
|
||||
// If we don't have AT or Extensions at all, webauthn can handle them being incorrectly set without any conversion
|
||||
return data.length > HEADER_LENGTH
|
||||
// If the data correctly sets the AT flag, webauthn can also handle it
|
||||
&& AuthenticatorData.checkFlagAT(data[FLAGS_OFFSET])
|
||||
// If the first byte after the header looks like an extension, this is the special case. Valid assertions
|
||||
// shouldn't have attestedCredentialData anyway, and if it did it should be a CBOR string
|
||||
&& (data[HEADER_LENGTH] & CBOR_MAJOR_TYPE_MASK) == CBOR_MAP_MAJOR_TYPE;
|
||||
}
|
||||
}
|
||||
+3
-2
@@ -138,7 +138,8 @@ public class AppleDeviceCheckManager {
|
||||
final DCAttestationData dcAttestationData;
|
||||
try {
|
||||
dcAttestationData = deviceCheckManager.validate(dcAttestationRequest,
|
||||
new DCAttestationParameters(new DCServerProperty(teamId, bundleId, new DefaultChallenge(challenge))));
|
||||
new DCAttestationParameters(new DCServerProperty(teamId, bundleId,
|
||||
new DefaultChallenge(challenge.getBytes(StandardCharsets.UTF_8)))));
|
||||
} catch (VerificationException e) {
|
||||
logger.info("Failed to verify attestation", e);
|
||||
throw new DeviceCheckVerificationFailedException(e);
|
||||
@@ -204,7 +205,7 @@ public class AppleDeviceCheckManager {
|
||||
new DCAssertionParameters(new DCServerProperty(teamId, bundleId, new DefaultChallenge(request)), appleDevice);
|
||||
|
||||
try {
|
||||
deviceCheckManager.validate(AppAttestAssertionConverter.parseAppleAssertion(dcAssertionRequest), dcAssertionParameters);
|
||||
deviceCheckManager.validate(dcAssertionRequest, dcAssertionParameters);
|
||||
} catch (MaliciousCounterValueException e) {
|
||||
// We will only accept assertions that have a sign count greater than the last assertion we saw. Step 5 here:
|
||||
// https://developer.apple.com/documentation/devicecheck/validating-apps-that-connect-to-your-server#Verify-the-assertion
|
||||
|
||||
+67
-13
@@ -1,6 +1,7 @@
|
||||
package org.whispersystems.textsecuregcm.storage.foundationdb;
|
||||
|
||||
import com.apple.foundationdb.KeySelector;
|
||||
import com.apple.foundationdb.MutationType;
|
||||
import com.apple.foundationdb.StreamingMode;
|
||||
import com.apple.foundationdb.Transaction;
|
||||
import com.apple.foundationdb.tuple.Versionstamp;
|
||||
@@ -8,6 +9,8 @@ import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.protobuf.InvalidProtocolBufferException;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
import java.time.Clock;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
@@ -42,6 +45,8 @@ class FoundationDbMessagePublisher {
|
||||
/// time the publisher was created. For an infinite publisher, this is the end of subspace range.
|
||||
private final KeySelector endKeyExclusive;
|
||||
|
||||
private final byte[] readsSinceLastAcknowledgedMessageKey;
|
||||
|
||||
/// The key that stores the server ID/timestamp indicating when/where the connected client was last known to be
|
||||
/// present. Active publishers refresh this key at regular intervals (see [#renewPresenceFuture]).
|
||||
@Nullable private final byte[] presenceKey;
|
||||
@@ -87,6 +92,12 @@ class FoundationDbMessagePublisher {
|
||||
|
||||
private static final int STREAM_ID_UNASSIGNED = -1;
|
||||
|
||||
// FoundationDB's `ADD` mutation operate on little-endian, 64-bit integers rather than on tuple-encoded integers
|
||||
private static final byte[] ONE_LITTLE_ENDIAN = ByteBuffer.allocate(Long.BYTES)
|
||||
.order(ByteOrder.LITTLE_ENDIAN)
|
||||
.putLong(1L)
|
||||
.array();
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(FoundationDbMessagePublisher.class);
|
||||
|
||||
private static final String WATCHES_COUNTER = MetricsUtil.name(FoundationDbMessagePublisher.class, "watches");
|
||||
@@ -131,6 +142,7 @@ class FoundationDbMessagePublisher {
|
||||
final KeySelector beginKeyInclusive,
|
||||
final KeySelector endKeyExclusive,
|
||||
final int streamId,
|
||||
final byte[] readsSinceLastAcknowledgedMessageKey,
|
||||
@Nullable final byte[] presenceKey,
|
||||
@Nullable final ScheduledExecutorService presenceRenewalExecutorService,
|
||||
@Nullable final byte[] messagesAvailableWatchKey,
|
||||
@@ -141,6 +153,7 @@ class FoundationDbMessagePublisher {
|
||||
this.beginKeyCursor = beginKeyInclusive;
|
||||
this.endKeyExclusive = endKeyExclusive;
|
||||
this.streamId = streamId;
|
||||
this.readsSinceLastAcknowledgedMessageKey = readsSinceLastAcknowledgedMessageKey;
|
||||
this.presenceKey = presenceKey;
|
||||
this.presenceRenewalExecutorService = presenceRenewalExecutorService;
|
||||
this.messagesAvailableWatchKey = messagesAvailableWatchKey;
|
||||
@@ -176,13 +189,15 @@ class FoundationDbMessagePublisher {
|
||||
final FaultTolerantDatabase database,
|
||||
final Clock clock,
|
||||
final KeySelector beginKeyInclusive,
|
||||
final KeySelector endKeyExclusive) {
|
||||
final KeySelector endKeyExclusive,
|
||||
final byte[] readsSinceHeadAcknowledgedKey) {
|
||||
|
||||
return new FoundationDbMessagePublisher(database,
|
||||
clock,
|
||||
beginKeyInclusive,
|
||||
endKeyExclusive,
|
||||
STREAM_ID_UNASSIGNED,
|
||||
readsSinceHeadAcknowledgedKey,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
@@ -198,6 +213,7 @@ class FoundationDbMessagePublisher {
|
||||
final KeySelector beginKeyInclusive,
|
||||
final KeySelector endKeyExclusive,
|
||||
final int streamId,
|
||||
final byte[] readsSinceHeadAcknowledgedKey,
|
||||
final byte[] presenceKey,
|
||||
final ScheduledExecutorService presenceRenewalExecutorService,
|
||||
final byte[] messagesAvailableWatchKey) {
|
||||
@@ -207,6 +223,7 @@ class FoundationDbMessagePublisher {
|
||||
beginKeyInclusive,
|
||||
endKeyExclusive,
|
||||
streamId,
|
||||
readsSinceHeadAcknowledgedKey,
|
||||
presenceKey,
|
||||
presenceRenewalExecutorService,
|
||||
messagesAvailableWatchKey,
|
||||
@@ -316,7 +333,22 @@ class FoundationDbMessagePublisher {
|
||||
// This is an unbounded publisher and we've established presence, so we should check for conflicts
|
||||
checkPresenceFuture = transaction.get(presenceKey)
|
||||
.thenAccept(presenceValue -> {
|
||||
if (presenceValue == null) {
|
||||
// We wrote a presence key earlier, but now it is gone. Two possibilities:
|
||||
// 1. The queue was cleared by an account/device delete. We should eventually get a disconnection
|
||||
// request so we should stay present until then.
|
||||
// 2. Someone else connected, wrote their own presence key, and then disconnected (nulling the key),
|
||||
// without us ever noticing an update to messagesAvailableWatchKey. Though we briefly did
|
||||
// conflict, we're not conflicting any more so we can continue.
|
||||
// In either case, we can try to re-establish our presence (unless we've already been disposed)
|
||||
if (!isTerminated()) {
|
||||
setPresence(transaction);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (isPresenceContested(presenceValue)) {
|
||||
// Someone else established presence over us
|
||||
throw new CompletionException(new ConflictingMessageConsumerException());
|
||||
}
|
||||
});
|
||||
@@ -330,7 +362,14 @@ class FoundationDbMessagePublisher {
|
||||
transaction.getRange(beginKeyCursor, endKeyExclusive, maxMessages, false, StreamingMode.EXACT).asList(),
|
||||
(_, keyValues) -> keyValues)
|
||||
.thenApply(keyValues -> {
|
||||
if (keyValues.size() < maxMessages && !terminateOnQueueEmpty) {
|
||||
final int keyValuesSize = keyValues.size();
|
||||
|
||||
if (keyValuesSize > 0 && !hasEmittedEntry()) {
|
||||
// We're about to emit our first message; increment the "sent head of queue since last ACK" counter
|
||||
incrementReadsSinceHeadAcknowledged(transaction);
|
||||
}
|
||||
|
||||
if (keyValuesSize < maxMessages && !terminateOnQueueEmpty) {
|
||||
setWatch(transaction);
|
||||
}
|
||||
|
||||
@@ -383,6 +422,10 @@ class FoundationDbMessagePublisher {
|
||||
return (int) Math.min(totalRequested - totalEmitted, Integer.MAX_VALUE);
|
||||
}
|
||||
|
||||
private synchronized boolean hasEmittedEntry() {
|
||||
return totalEmitted > 0;
|
||||
}
|
||||
|
||||
/// Fetch and publish messages. Messages are fetched in batches to avoid excessive memory consumption. After each
|
||||
/// fetch operation, [#beginKeyCursor] is updated to the next key we need to start reading from. If the fetch
|
||||
/// operation returns fewer items than the batch size, we infer that we have fetched all available messages and
|
||||
@@ -411,9 +454,13 @@ class FoundationDbMessagePublisher {
|
||||
return this.messagePublisher;
|
||||
}
|
||||
|
||||
private void incrementReadsSinceHeadAcknowledged(final Transaction transaction) {
|
||||
transaction.mutate(MutationType.ADD, readsSinceLastAcknowledgedMessageKey, ONE_LITTLE_ENDIAN);
|
||||
}
|
||||
|
||||
private synchronized void setWatch(final Transaction transaction) {
|
||||
assert messagesAvailableWatchKey != null;
|
||||
if (state == State.TERMINATED || state == State.ERROR) {
|
||||
if (isTerminated()) {
|
||||
// If we're already in a terminal state, we don't want to set a watch that would leak
|
||||
return;
|
||||
}
|
||||
@@ -490,16 +537,20 @@ class FoundationDbMessagePublisher {
|
||||
}
|
||||
|
||||
private synchronized CompletableFuture<Void> renewPresence() {
|
||||
if (state == State.TERMINATED || state == State.ERROR) {
|
||||
if (isTerminated()) {
|
||||
return CompletableFuture.failedFuture(new IllegalStateException("Publisher already terminated"));
|
||||
}
|
||||
|
||||
return database.runAsync(transaction -> {
|
||||
transaction.set(presenceKey, FoundationDbMessageStore.getPresenceValue(clock.instant(), streamId));
|
||||
setPresence(transaction);
|
||||
return CompletableFuture.completedFuture(null);
|
||||
}, FaultTolerantDatabase.Context.SET_PRESENCE);
|
||||
}
|
||||
|
||||
private void setPresence(final Transaction transaction) {
|
||||
transaction.set(presenceKey, FoundationDbMessageStore.getPresenceValue(clock.instant(), streamId));
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
synchronized void clearPresence() {
|
||||
if (renewPresenceFuture != null) {
|
||||
@@ -507,7 +558,10 @@ class FoundationDbMessagePublisher {
|
||||
|
||||
renewPresenceFuture.whenComplete((_, _) ->
|
||||
database.runAsync(transaction -> transaction.get(presenceKey).thenAccept(presenceValue -> {
|
||||
if (!isPresenceContested(presenceValue)) {
|
||||
if (presenceValue == null || !isPresenceContested(presenceValue)) {
|
||||
// Note: we still try to set the value to null even if it is already null. This way we would still
|
||||
// cause a FoundationDB transaction conflict with a concurrent presence renewal that was updating
|
||||
// from null to something else.
|
||||
transaction.clear(presenceKey);
|
||||
}
|
||||
}), FaultTolerantDatabase.Context.CLEAR_PRESENCE)
|
||||
@@ -519,19 +573,19 @@ class FoundationDbMessagePublisher {
|
||||
}
|
||||
}
|
||||
|
||||
/// @return true if a publisher other than us has claimed presence
|
||||
private boolean isPresenceContested(final byte[] presenceValue) {
|
||||
if (presenceValue == null) {
|
||||
// Some other process has cleared our presence key, so we must assume a conflict somewhere
|
||||
return true;
|
||||
}
|
||||
|
||||
return streamId != FoundationDbMessageStore.getPresenceStreamId(presenceValue) ||
|
||||
!Arrays.equals(FoundationDbMessageStore.getPresenceServerId(presenceValue), FoundationDbMessageStore.getServerId());
|
||||
}
|
||||
|
||||
private synchronized boolean isTerminated() {
|
||||
return state == State.TERMINATED || state == State.ERROR;
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
synchronized void terminateWithError(final Throwable throwable) {
|
||||
if (state != State.TERMINATED && state != State.ERROR && !emitter.isCancelled()) {
|
||||
if (!isTerminated() && !emitter.isCancelled()) {
|
||||
setState(State.ERROR, Event.INTERNAL_TRIGGER);
|
||||
emitter.error(throwable);
|
||||
}
|
||||
@@ -540,7 +594,7 @@ class FoundationDbMessagePublisher {
|
||||
private synchronized void onDispose() {
|
||||
// Unless the state machine is an already terminal state, directly set state to "terminated", since there's no point
|
||||
// in evaluating the state machine when there's no live subscription.
|
||||
if (state != State.TERMINATED && state != State.ERROR) {
|
||||
if (!isTerminated()) {
|
||||
setState(State.TERMINATED, Event.INTERNAL_TRIGGER);
|
||||
}
|
||||
cancelWatch();
|
||||
|
||||
+47
-55
@@ -21,6 +21,7 @@ import io.micrometer.core.instrument.Tags;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
@@ -31,7 +32,6 @@ import java.util.IdentityHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
@@ -80,7 +80,7 @@ public class FoundationDbMessageStore {
|
||||
private final ScheduledExecutorService presenceRenewalExecutorService;
|
||||
private final Clock clock;
|
||||
|
||||
// Per-attempt timeout and retry limit for batch priority transacitons, e.g. expired-message trim.
|
||||
// Per-attempt timeout and retry limit for batch priority transactions, e.g. expired-message trim.
|
||||
private final Duration batchPriorityTransactionTimeout;
|
||||
private final long batchPriorityTransactionRetryLimit;
|
||||
|
||||
@@ -398,6 +398,8 @@ public class FoundationDbMessageStore {
|
||||
|
||||
return databasesByEpoch[getConfigurationEpoch(versionstamp)][getShardId(versionstamp)].runAsync(transaction -> {
|
||||
transaction.clear(messageKey);
|
||||
transaction.clear(getReadsSinceLastAcknowledgedMessageKey(aci, deviceId));
|
||||
|
||||
return CompletableFuture.completedFuture(null);
|
||||
}, FaultTolerantDatabase.Context.DELETE_MESSAGE)
|
||||
.thenRun(() -> {
|
||||
@@ -406,35 +408,6 @@ public class FoundationDbMessageStore {
|
||||
});
|
||||
}
|
||||
|
||||
CompletableFuture<Optional<FoundationDbMessageStreamEntry.Message>> deleteAndGet(final AciServiceIdentifier aci, final byte deviceId, final UUID messageGuid) {
|
||||
return deleteAndGet(aci, deviceId, versionstampUUIDCipher.decryptVersionstamp(messageGuid, aci.uuid(), deviceId));
|
||||
}
|
||||
|
||||
CompletableFuture<Optional<FoundationDbMessageStreamEntry.Message>> deleteAndGet(final AciServiceIdentifier aci, final byte deviceId, final Versionstamp versionstamp) {
|
||||
final Timer.Sample sample = Timer.start();
|
||||
|
||||
final byte[] messageKey = getDeviceQueueSubspace(aci, deviceId).pack(Tuple.from(versionstamp));
|
||||
|
||||
return databasesByEpoch[getConfigurationEpoch(versionstamp)][getShardId(versionstamp)].runAsync(
|
||||
transaction -> transaction.get(messageKey)
|
||||
.thenApply(value -> {
|
||||
if (value == null) {
|
||||
return Optional.<byte[]>empty();
|
||||
}
|
||||
transaction.clear(messageKey);
|
||||
return Optional.of(value);
|
||||
}), FaultTolerantDatabase.Context.DELETE_MESSAGE)
|
||||
.whenComplete((_, _) -> sample.stop(DELETE_MESSAGE_TIMER))
|
||||
.thenApply(maybeValue -> maybeValue.map(value -> {
|
||||
DELETE_MESSAGE_COUNTER.increment();
|
||||
try {
|
||||
return new FoundationDbMessageStreamEntry.Message(versionstamp, MessageProtos.Envelope.parseFrom(value));
|
||||
} catch (final InvalidProtocolBufferException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
public void clearAll(final AciServiceIdentifier aci) {
|
||||
doForAllDatabasesWithMessages(aci, database -> database.run(transaction -> {
|
||||
transaction.clear(getAccountSubspace(aci).range());
|
||||
@@ -461,28 +434,15 @@ public class FoundationDbMessageStore {
|
||||
return getMessages(aci, deviceId, Util.NOOP);
|
||||
}
|
||||
|
||||
FaultTolerantDatabase[] getDatabasesByEpochForAci(final AciServiceIdentifier aci) {
|
||||
// For each configured database epoch, which database held (or holds) the messages for this ACI/device pair?
|
||||
final FaultTolerantDatabase[] databasesForQueueByEpoch = new FaultTolerantDatabase[databasesByEpoch.length];
|
||||
|
||||
for (final int epoch : liveEpochs) {
|
||||
databasesForQueueByEpoch[epoch] = getShardForAci(aci, epoch);
|
||||
}
|
||||
|
||||
return databasesForQueueByEpoch;
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
FoundationDbMessageStream getMessages(final AciServiceIdentifier aci,
|
||||
final byte deviceId,
|
||||
final Runnable doAfterCleanup) {
|
||||
|
||||
final FaultTolerantDatabase[] databasesForQueueByEpoch = getDatabasesByEpochForAci(aci);
|
||||
|
||||
return new FoundationDbMessageStream(this,
|
||||
aci,
|
||||
deviceId,
|
||||
databasesForQueueByEpoch,
|
||||
getDistinctDatabasesForAci(aci),
|
||||
new MessageGuidCodec(aci.uuid(), deviceId, versionstampUUIDCipher),
|
||||
doAfterCleanup,
|
||||
presenceRenewalExecutorService,
|
||||
@@ -496,7 +456,7 @@ public class FoundationDbMessageStore {
|
||||
///
|
||||
/// @return a future that yields `true` if the identified queue contains any messages or `false` if the queue is empty
|
||||
public CompletableFuture<Boolean> hasMessages(final AciServiceIdentifier aci, final byte deviceId) {
|
||||
return getDistinctDatabasesForAci(aci)
|
||||
return Flux.fromArray(getDistinctDatabasesForAci(aci))
|
||||
.flatMap(database -> Mono.fromFuture(() -> database.readAsync(transaction ->
|
||||
transaction.getRange(getDeviceQueueSubspace(aci, deviceId).range(), 1).asList(),
|
||||
FaultTolerantDatabase.Context.GET_HAS_MESSAGES)))
|
||||
@@ -514,7 +474,7 @@ public class FoundationDbMessageStore {
|
||||
/// @return a future that yields `true` if the identified queue contains an urgent message within a sample or `false`
|
||||
/// otherwise
|
||||
public CompletableFuture<Boolean> mayHaveUrgentMessages(final AciServiceIdentifier aci, final byte deviceId) {
|
||||
return getDistinctDatabasesForAci(aci)
|
||||
return Flux.fromArray(getDistinctDatabasesForAci(aci))
|
||||
.flatMap(database -> Mono.fromFuture(() -> database.readAsync(transaction ->
|
||||
transaction.getRange(getDeviceQueueSubspace(aci, deviceId).range(), MAY_HAVE_URGENT_MESSAGES_QUERY_LIMIT).asList(),
|
||||
FaultTolerantDatabase.Context.GET_HAS_URGENT_MESSAGES))
|
||||
@@ -540,7 +500,7 @@ public class FoundationDbMessageStore {
|
||||
public CompletableFuture<Optional<Instant>> getEarliestUndeliveredMessageTimestamp(final AciServiceIdentifier aci,
|
||||
final byte deviceId) {
|
||||
|
||||
return getDistinctDatabasesForAci(aci)
|
||||
return Flux.fromArray(getDistinctDatabasesForAci(aci))
|
||||
.flatMap(database -> Mono.fromFuture(() -> database.readAsync(transaction ->
|
||||
transaction.getRange(getDeviceQueueSubspace(aci, deviceId).range(), 1).asList(),
|
||||
FaultTolerantDatabase.Context.GET_EARLIEST_TIMESTAMP))
|
||||
@@ -684,8 +644,17 @@ public class FoundationDbMessageStore {
|
||||
@VisibleForTesting
|
||||
record QueueSizeAndRangeSplitPoints(long estimatedQueueSize, Map<FaultTolerantDatabase, List<byte[]>> splitPointsByDatabase) {}
|
||||
|
||||
private Flux<FaultTolerantDatabase> getDistinctDatabasesForAci(final AciServiceIdentifier aci) {
|
||||
return Flux.fromStream(Arrays.stream(getDatabasesByEpochForAci(aci)).filter(Objects::nonNull).distinct());
|
||||
private FaultTolerantDatabase[] getDistinctDatabasesForAci(final AciServiceIdentifier aci) {
|
||||
// Optimization: if we only have one live epoch (true most of the time!), we can skip the overhead of working with
|
||||
// a stream
|
||||
if (liveEpochs.length == 1) {
|
||||
return new FaultTolerantDatabase[] { getShardForAci(aci, liveEpochs[0]) };
|
||||
}
|
||||
|
||||
return Arrays.stream(liveEpochs)
|
||||
.mapToObj(epoch -> getShardForAci(aci, epoch))
|
||||
.distinct()
|
||||
.toArray(FaultTolerantDatabase[]::new);
|
||||
}
|
||||
|
||||
/// Estimates the size of the provided queue in bytes.
|
||||
@@ -696,7 +665,7 @@ public class FoundationDbMessageStore {
|
||||
Mono<Long> estimateQueueSize(final AciServiceIdentifier aci, final byte deviceId) {
|
||||
final Range deviceQueueRange = getDeviceQueueSubspace(aci, deviceId).range();
|
||||
|
||||
return getDistinctDatabasesForAci(aci)
|
||||
return Flux.fromArray(getDistinctDatabasesForAci(aci))
|
||||
.flatMap(database -> Mono.fromFuture(() -> database.runAsync(transaction -> transaction.getEstimatedRangeSizeBytes(deviceQueueRange), FaultTolerantDatabase.Context.ESTIMATE_QUEUE_SIZE)))
|
||||
.reduce(0L, Long::sum);
|
||||
}
|
||||
@@ -712,7 +681,8 @@ public class FoundationDbMessageStore {
|
||||
final AciServiceIdentifier aci,
|
||||
final byte deviceId,
|
||||
final long rangeSplitChunkSize) {
|
||||
return getDistinctDatabasesForAci(aci)
|
||||
|
||||
return Flux.fromArray(getDistinctDatabasesForAci(aci))
|
||||
.flatMap(database -> Mono.fromFuture(() -> estimateQueueSizeAndRangeSplitsForDatabase(database, aci, deviceId, rangeSplitChunkSize))
|
||||
.map(pair -> Tuples.of(pair.first(), database, pair.second().getKeys())))
|
||||
.collect(Collectors.teeing(
|
||||
@@ -740,7 +710,7 @@ public class FoundationDbMessageStore {
|
||||
final long maxQueueSizeBytes,
|
||||
final long targetQueueSizeBytes,
|
||||
final long rangeSplitChunkSizeBytes,
|
||||
final UnaryOperator<Mono<Boolean>> deleteModifier) {
|
||||
final Function<Mono<Boolean>, Mono<Boolean>> deleteModifier) {
|
||||
final Tag platformTag = Tag.of("platform", DevicePlatformUtil.getDevicePlatform(device)
|
||||
.map(platform -> platform.name().toLowerCase(Locale.ROOT))
|
||||
.orElse("unknown"));
|
||||
@@ -794,9 +764,9 @@ public class FoundationDbMessageStore {
|
||||
remainingBytesToDelete.addAndGet(-estimatedDeletedBytes);
|
||||
ESTIMATED_TRIMMED_BYTES_COUNTER.increment(estimatedDeletedBytes);
|
||||
})
|
||||
.flatMap(_ -> Mono.just(true));
|
||||
.then(Mono.just(true));
|
||||
|
||||
return deleteModifier.apply(deleteMono)
|
||||
return deleteMono.transform(deleteModifier)
|
||||
.onErrorResume(throwable -> {
|
||||
if (!ExceptionUtils.isBreakerOpen(throwable)) {
|
||||
LOGGER.warn("Failed to trim message queue for {}:{}", aci, device.getId(), throwable);
|
||||
@@ -828,6 +798,24 @@ public class FoundationDbMessageStore {
|
||||
}, FaultTolerantDatabase.Context.TRIM_QUEUE);
|
||||
}
|
||||
|
||||
/// Returns the number of times a subscriber has started reading a message queue since the last time any message in
|
||||
/// the queue was acknowledged. In cases where a caller's messages span multiple database shards (i.e. during a
|
||||
/// migration), this method returns the maximum count across all shards.
|
||||
///
|
||||
/// @param aci the account identifier for which to retrieve a read-without-acknowledging-head count
|
||||
/// @param deviceId the device ID for which to retrieve a read-without-acknowledging-head count
|
||||
///
|
||||
/// @return the number of times a subscriber has started reading messages from the identified message queue since the
|
||||
/// last time any message in the queue was acknowledged
|
||||
public CompletableFuture<Long> getReadsSinceLastAcknowledgedMessage(final AciServiceIdentifier aci, final byte deviceId) {
|
||||
return Flux.fromArray(getDistinctDatabasesForAci(aci))
|
||||
.flatMap(database -> Mono.fromFuture(() -> database.readAsync(transaction ->
|
||||
transaction.get(getReadsSinceLastAcknowledgedMessageKey(aci, deviceId)), FaultTolerantDatabase.Context.TEST)))
|
||||
.map(countBytes -> ByteBuffer.wrap(countBytes).order(ByteOrder.LITTLE_ENDIAN).getLong())
|
||||
.reduce(0L, Math::max)
|
||||
.toFuture();
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
public static Subspace getAccountSubspace(final AciServiceIdentifier aci) {
|
||||
return getAccountSubspace(MESSAGES_SUBSPACE, aci);
|
||||
@@ -842,6 +830,10 @@ public class FoundationDbMessageStore {
|
||||
return getAccountSubspace(aci).pack("l");
|
||||
}
|
||||
|
||||
static byte[] getReadsSinceLastAcknowledgedMessageKey(final AciServiceIdentifier aci, final byte deviceId) {
|
||||
return getDeviceSubspace(aci, deviceId).pack("r");
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static byte[] getServerId() {
|
||||
return SERVER_ID;
|
||||
|
||||
+7
-25
@@ -8,10 +8,7 @@ import com.apple.foundationdb.subspace.Subspace;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.time.Clock;
|
||||
import java.util.Arrays;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
@@ -42,7 +39,7 @@ public class FoundationDbMessageStream implements MessageStream {
|
||||
private final Subspace deviceQueueSubspace;
|
||||
private final byte[] presenceKey;
|
||||
private final byte[] messagesAvailableWatchKey;
|
||||
private final FaultTolerantDatabase[] databasesByEpoch;
|
||||
private final FaultTolerantDatabase[] databases;
|
||||
private final MessageGuidCodec messageGuidCodec;
|
||||
/// The maximum number of messages we will fetch per range query operation to avoid excessive memory consumption
|
||||
private final Flow.Publisher<MessageStreamEntry> messageStreamPublisher;
|
||||
@@ -71,7 +68,7 @@ public class FoundationDbMessageStream implements MessageStream {
|
||||
FoundationDbMessageStream(final FoundationDbMessageStore foundationDbMessageStore,
|
||||
final AciServiceIdentifier aciServiceIdentifier,
|
||||
final byte deviceId,
|
||||
final FaultTolerantDatabase[] databasesByEpoch,
|
||||
final FaultTolerantDatabase[] databases,
|
||||
final MessageGuidCodec messageGuidCodec,
|
||||
final Runnable doAfterCleanup,
|
||||
final ScheduledExecutorService presenceRenewalExecutorService,
|
||||
@@ -82,7 +79,7 @@ public class FoundationDbMessageStream implements MessageStream {
|
||||
this.deviceQueueSubspace = FoundationDbMessageStore.getDeviceQueueSubspace(aciServiceIdentifier, deviceId);
|
||||
this.presenceKey = FoundationDbMessageStore.getPresenceKey(aciServiceIdentifier, deviceId);
|
||||
this.messagesAvailableWatchKey = FoundationDbMessageStore.getMessagesAvailableWatchKey(aciServiceIdentifier);
|
||||
this.databasesByEpoch = databasesByEpoch;
|
||||
this.databases = databases;
|
||||
this.messageGuidCodec = messageGuidCodec;
|
||||
this.messageStreamPublisher = JdkFlowAdapter.publisherToFlowPublisher(createMessagePublisher());
|
||||
this.doAfterCleanup = doAfterCleanup;
|
||||
@@ -124,11 +121,7 @@ public class FoundationDbMessageStream implements MessageStream {
|
||||
/// on [#messagesAvailableWatchKey] which is updated when a new message is available.
|
||||
/// See [FoundationDbMessageStore] for more details on the message insert process.
|
||||
private Flux<FoundationDbMessageStreamEntry> createFoundationDbMessagePublisher() {
|
||||
// This may seem like an odd construction since it looks like we could also just do `Flux#fromArray`, but
|
||||
// `Flux#fromArray` cannot handle `null` elements
|
||||
final List<FaultTolerantDatabase> databases = Arrays.stream(databasesByEpoch).filter(Objects::nonNull).distinct().toList();
|
||||
|
||||
return Flux.fromIterable(databases)
|
||||
return Flux.fromArray(this.databases)
|
||||
.flatMap(database -> Mono.fromFuture(() -> getEndOfQueueKeyExclusive(database))
|
||||
.map(maybeEndOfQueueKeyExclusive -> Tuples.of(database, maybeEndOfQueueKeyExclusive)))
|
||||
.collectMap(Tuple2::getT1, Tuple2::getT2)
|
||||
@@ -144,7 +137,8 @@ public class FoundationDbMessageStream implements MessageStream {
|
||||
database,
|
||||
clock,
|
||||
KeySelector.firstGreaterOrEqual(deviceQueueSubspace.range().begin),
|
||||
endOfQueueKeyExclusive)
|
||||
endOfQueueKeyExclusive,
|
||||
FoundationDbMessageStore.getReadsSinceLastAcknowledgedMessageKey(aciServiceIdentifier, deviceId))
|
||||
.getMessages())
|
||||
.orElseGet(Flux::empty)
|
||||
.handle((fdbMessageStreamEntry, sink) -> {
|
||||
@@ -177,6 +171,7 @@ public class FoundationDbMessageStream implements MessageStream {
|
||||
infinitePublisherBeginKey,
|
||||
KeySelector.firstGreaterThan(deviceQueueSubspace.range().end),
|
||||
NEXT_STREAM_ID.getAndIncrement(),
|
||||
FoundationDbMessageStore.getReadsSinceLastAcknowledgedMessageKey(aciServiceIdentifier, deviceId),
|
||||
presenceKey,
|
||||
presenceRenewalExecutorService,
|
||||
messagesAvailableWatchKey).getMessages();
|
||||
@@ -229,17 +224,4 @@ public class FoundationDbMessageStream implements MessageStream {
|
||||
|
||||
return foundationDbMessageStore.delete(aciServiceIdentifier, deviceId, messageGuid);
|
||||
}
|
||||
|
||||
public CompletableFuture<Optional<MessageStreamEntry.Envelope>> acknowledgeAndGetMessage(final UUID messageGuid) {
|
||||
messageAcknowledgedCounter.increment();
|
||||
|
||||
return foundationDbMessageStore.deleteAndGet(aciServiceIdentifier, deviceId, messageGuid)
|
||||
.thenApply(foundationDbMessageStreamEntry -> foundationDbMessageStreamEntry.map(m -> {
|
||||
final MessageStreamEntry messageStreamEntry = m.toMessageStreamEntry(messageGuidCodec);
|
||||
if (!(messageStreamEntry instanceof MessageStreamEntry.Envelope)) {
|
||||
throw new AssertionError("Expected MessageStreamEntry.Envelope, got " + messageStreamEntry);
|
||||
}
|
||||
return (MessageStreamEntry.Envelope) messageStreamEntry;
|
||||
}));
|
||||
}
|
||||
}
|
||||
+1
@@ -23,6 +23,7 @@
|
||||
/// | | device was present
|
||||
/// | | + {device ID (byte)} (device subspace)
|
||||
/// | | | * "p" => presence: server-id || last-seen-time
|
||||
/// | | | * "r" => reads since last message acknowledgement: 64-bit integer (little-endian)
|
||||
/// | | | + "Q" (device message queue subspace)
|
||||
/// | | | | * versionstamp => serialized envelope
|
||||
/// ```
|
||||
|
||||
+4
-2
@@ -7,9 +7,11 @@ package org.whispersystems.textsecuregcm.util;
|
||||
|
||||
import org.signal.libsignal.usernames.BaseUsernameException;
|
||||
import org.signal.libsignal.usernames.Username;
|
||||
import org.signal.libsignal.usernames.UsernameHash;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
|
||||
public class UsernameHashZkProofVerifier {
|
||||
public void verifyProof(final byte[] proof, final byte[] hash) throws BaseUsernameException {
|
||||
Username.verifyProof(proof, hash);
|
||||
public void verifyProof(final byte[] proof, final byte[] hash) throws BaseUsernameException, InvalidInputException {
|
||||
Username.verifyProof(proof, new UsernameHash(hash));
|
||||
}
|
||||
}
|
||||
@@ -230,17 +230,6 @@ public class Util {
|
||||
return workingCopy == prefix;
|
||||
}
|
||||
|
||||
/**
|
||||
* Benin changed phone number formats from +229 XXXXXXXX to +229 01XXXXXXXX on November 30, 2024
|
||||
*
|
||||
* @param phoneNumber the phone number to check.
|
||||
* @return whether the provided phone number is an old-format Benin phone number
|
||||
*/
|
||||
public static boolean isOldFormatBeninPhoneNumber(final Phonenumber.PhoneNumber phoneNumber) {
|
||||
return "BJ".equals(PHONE_NUMBER_UTIL.getRegionCodeForNumber(phoneNumber)) &&
|
||||
PHONE_NUMBER_UTIL.getNationalSignificantNumber(phoneNumber).length() == 8;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return whether the E164-formatted {@code number} is in a range that registration-service treats as fictitious
|
||||
*/
|
||||
@@ -257,9 +246,6 @@ public class Util {
|
||||
*/
|
||||
public static Phonenumber.PhoneNumber canonicalizePhoneNumber(final Phonenumber.PhoneNumber phoneNumber)
|
||||
throws NumberParseException, ObsoletePhoneNumberFormatException {
|
||||
if (isOldFormatBeninPhoneNumber(phoneNumber)) {
|
||||
throw new ObsoletePhoneNumberFormatException("bj");
|
||||
}
|
||||
return phoneNumber;
|
||||
}
|
||||
|
||||
|
||||
+1
-4
@@ -9,14 +9,11 @@ import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import net.logstash.logback.marker.Markers;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.Marker;
|
||||
|
||||
/// Log errors that represent a programming logic error
|
||||
public final class ImpossibleEvents {
|
||||
|
||||
private static final Marker IMPOSSIBLE = Markers.append("impossible", true);
|
||||
private static final Counter COUNTER = Metrics.counter(name(ImpossibleEvents.class, "count"));
|
||||
|
||||
private ImpossibleEvents() {
|
||||
@@ -25,6 +22,6 @@ public final class ImpossibleEvents {
|
||||
/// Log that an event should never happen.
|
||||
public static void logImpossible(final Logger logger, final String message, final Object... args) {
|
||||
COUNTER.increment();
|
||||
logger.error(IMPOSSIBLE, message, args);
|
||||
logger.atError().addKeyValue("impossible", true).log(message, args);
|
||||
}
|
||||
}
|
||||
+4
-2
@@ -13,6 +13,7 @@ import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.asn.AsnInfoProvider;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestManager;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.metrics.MessageMetrics;
|
||||
@@ -24,6 +25,7 @@ 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.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesManager;
|
||||
import org.whispersystems.websocket.WebSocketClient;
|
||||
import org.whispersystems.websocket.session.WebSocketSessionContext;
|
||||
@@ -59,7 +61,7 @@ public class AuthenticatedConnectListener implements WebSocketConnectListener {
|
||||
final Scheduler messageDeliveryScheduler,
|
||||
final Supplier<AsnInfoProvider> asnInfoProviderSupplier,
|
||||
final ClientReleaseManager clientReleaseManager,
|
||||
final ExperimentEnrollmentManager experimentEnrollmentManager) {
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
|
||||
|
||||
this(accountsManager,
|
||||
disconnectionRequestManager,
|
||||
@@ -76,7 +78,7 @@ public class AuthenticatedConnectListener implements WebSocketConnectListener {
|
||||
client,
|
||||
messageDeliveryScheduler,
|
||||
clientReleaseManager,
|
||||
experimentEnrollmentManager)
|
||||
dynamicConfigurationManager)
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
+50
-15
@@ -8,7 +8,6 @@ package org.whispersystems.textsecuregcm.websocket;
|
||||
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.Metrics;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
@@ -20,19 +19,21 @@ import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.concurrent.atomic.LongAdder;
|
||||
import javax.annotation.Nullable;
|
||||
import org.eclipse.jetty.util.ConstantThrowable;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.metrics.MessageMetrics;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.push.NotPushRegisteredException;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationScheduler;
|
||||
import org.whispersystems.textsecuregcm.push.ReceiptSender;
|
||||
@@ -40,6 +41,7 @@ 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.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.storage.MessageStream;
|
||||
import org.whispersystems.textsecuregcm.storage.MessageStreamEntry;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesManager;
|
||||
@@ -54,12 +56,13 @@ import org.whispersystems.websocket.messages.WebSocketResponseMessage;
|
||||
import reactor.adapter.JdkFlowAdapter;
|
||||
import reactor.core.Disposable;
|
||||
import reactor.core.observability.micrometer.Micrometer;
|
||||
import reactor.core.publisher.Hooks;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
|
||||
public class WebSocketConnection {
|
||||
|
||||
private static final Counter sendFailuresCounter = Metrics.counter(name(WebSocketConnection.class, "sendFailures"));
|
||||
private static final String SEND_FAILURES_COUNTER_NAME = name(WebSocketConnection.class, "sendFailures");
|
||||
|
||||
private static final String NON_SUCCESS_RESPONSE_COUNTER_NAME = name(WebSocketConnection.class,
|
||||
"clientNonSuccessResponse");
|
||||
@@ -81,13 +84,14 @@ public class WebSocketConnection {
|
||||
private static final Duration CLOSE_WITH_PENDING_MESSAGES_NOTIFICATION_DELAY = Duration.ofMinutes(1);
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(WebSocketConnection.class);
|
||||
private static final Logger droppedErrorLogger = LoggerFactory.getLogger("droppedError");
|
||||
|
||||
private final ReceiptSender receiptSender;
|
||||
private final MessagesManager messagesManager;
|
||||
private final MessageMetrics messageMetrics;
|
||||
private final PushNotificationManager pushNotificationManager;
|
||||
private final PushNotificationScheduler pushNotificationScheduler;
|
||||
private final ExperimentEnrollmentManager experimentEnrollmentManager;
|
||||
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
|
||||
|
||||
private final Account authenticatedAccount;
|
||||
private final Device authenticatedDevice;
|
||||
@@ -113,7 +117,7 @@ public class WebSocketConnection {
|
||||
final WebSocketClient client,
|
||||
final Scheduler messageDeliveryScheduler,
|
||||
final ClientReleaseManager clientReleaseManager,
|
||||
final ExperimentEnrollmentManager experimentEnrollmentManager) {
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
|
||||
|
||||
this.receiptSender = receiptSender;
|
||||
this.messagesManager = messagesManager;
|
||||
@@ -125,7 +129,7 @@ public class WebSocketConnection {
|
||||
this.client = client;
|
||||
this.messageDeliveryScheduler = messageDeliveryScheduler;
|
||||
this.clientReleaseManager = clientReleaseManager;
|
||||
this.experimentEnrollmentManager = experimentEnrollmentManager;
|
||||
this.dynamicConfigurationManager = dynamicConfigurationManager;
|
||||
|
||||
this.messageStream =
|
||||
messagesManager.getMessages(authenticatedAccount.getAccountIdentifier(), authenticatedDevice);
|
||||
@@ -138,10 +142,21 @@ public class WebSocketConnection {
|
||||
|
||||
final Timer.Sample queueDrainStart = Timer.start();
|
||||
|
||||
messageSubscription.set(JdkFlowAdapter.flowPublisherToFlux(messageStream.getMessages())
|
||||
.name(SEND_MESSAGES_FLUX_NAME)
|
||||
.tap(Micrometer.metrics(Metrics.globalRegistry))
|
||||
.limitRate(MESSAGE_PUBLISHER_LIMIT_RATE)
|
||||
final AtomicInteger maxConcurrency = new AtomicInteger(MESSAGE_SENDER_MAX_CONCURRENCY);
|
||||
|
||||
messageSubscription.set(Mono.fromFuture(() -> messagesManager.hasSuspectedDeliveryLoop(authenticatedAccount.getAccountIdentifier(), authenticatedDevice.getId()))
|
||||
.flatMapMany(hasSuspectedDeliveryLoop -> {
|
||||
if (hasSuspectedDeliveryLoop) {
|
||||
maxConcurrency.set(1);
|
||||
MessageMetrics.recordSuspectedDeliveryLoop(MessageMetrics.WEBSOCKET_CHANNEL, userAgent, clientReleaseManager);
|
||||
}
|
||||
|
||||
return JdkFlowAdapter.flowPublisherToFlux(messageStream.getMessages())
|
||||
.name(SEND_MESSAGES_FLUX_NAME)
|
||||
.tag("hasSuspectedDeliveryLoop", String.valueOf(hasSuspectedDeliveryLoop))
|
||||
.tap(Micrometer.metrics(Metrics.globalRegistry))
|
||||
.limitRate(maxConcurrency.get());
|
||||
})
|
||||
// We want to handle conflicting connections as soon as possible, and so do this before we start processing
|
||||
// messages in the `flatMapSequential` stage below. If we didn't do this first, then we'd wait for clients to
|
||||
// process messages before sending the "connected elsewhere" signal, and while that's ultimately not harmful,
|
||||
@@ -153,7 +168,7 @@ public class WebSocketConnection {
|
||||
.flatMapSequential(entry -> switch (entry) {
|
||||
case MessageStreamEntry.Envelope envelope -> Mono.fromFuture(() -> sendMessage(envelope.message())).thenReturn(entry);
|
||||
case MessageStreamEntry.QueueEmpty _ -> Mono.just(entry);
|
||||
}, MESSAGE_SENDER_MAX_CONCURRENCY)
|
||||
}, maxConcurrency.get())
|
||||
.subscribeOn(messageDeliveryScheduler)
|
||||
.subscribe(
|
||||
entry -> {
|
||||
@@ -192,9 +207,18 @@ public class WebSocketConnection {
|
||||
messagesManager.mayHaveMessages(authenticatedAccount.getAccountIdentifier(), authenticatedDevice)
|
||||
.thenAccept(mayHaveMessages -> {
|
||||
if (mayHaveMessages) {
|
||||
pushNotificationScheduler.scheduleDelayedNotification(authenticatedAccount,
|
||||
authenticatedDevice,
|
||||
CLOSE_WITH_PENDING_MESSAGES_NOTIFICATION_DELAY);
|
||||
if (dynamicConfigurationManager.getConfiguration().getNotificationConfiguration().sendRemainingMessagesNotificationImmediately()) {
|
||||
try {
|
||||
pushNotificationManager.sendNewMessageNotification(authenticatedAccount,
|
||||
authenticatedDevice.getId(),
|
||||
true);
|
||||
} catch (NotPushRegisteredException _) {
|
||||
}
|
||||
} else {
|
||||
pushNotificationScheduler.scheduleDelayedNotification(authenticatedAccount,
|
||||
authenticatedDevice,
|
||||
CLOSE_WITH_PENDING_MESSAGES_NOTIFICATION_DELAY);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -233,7 +257,8 @@ public class WebSocketConnection {
|
||||
List.of(HeaderUtils.getTimestampHeader()), body)
|
||||
.whenComplete((ignored, throwable) -> {
|
||||
if (throwable != null) {
|
||||
sendFailuresCounter.increment();
|
||||
Metrics.counter(SEND_FAILURES_COUNTER_NAME, EXCEPTION_TYPE_TAG, throwable.getClass().getSimpleName())
|
||||
.increment();
|
||||
} else {
|
||||
messageMetrics.measureOutgoingMessageLatency(serverTimestamp,
|
||||
MessageMetrics.WEBSOCKET_CHANNEL,
|
||||
@@ -272,6 +297,16 @@ public class WebSocketConnection {
|
||||
.thenRun(() -> messageMetrics.measureSendMessageDuration(MessageMetrics.WEBSOCKET_CHANNEL, userAgent, sample));
|
||||
}
|
||||
|
||||
/// Registers a global hook that discards exceptions caused by closed connections and logs everything else.
|
||||
/// Hooks are additive and should therefore be called exactly once at startup.
|
||||
public static void registerDroppedErrorHook() {
|
||||
Hooks.onErrorDropped(throwable -> {
|
||||
if (!WebSocketConnection.isConnectionClosedException(ExceptionUtils.unwrap(throwable))) {
|
||||
droppedErrorLogger.error("Dropped error", throwable);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static byte[] serializeMessage(final Envelope message) {
|
||||
return message.toBuilder().clearEphemeral().build().toByteArray();
|
||||
|
||||
@@ -90,9 +90,12 @@ enum DeviceCapability {
|
||||
reserved 5;
|
||||
DEVICE_CAPABILITY_ATTACHMENT_BACKFILL = 6;
|
||||
DEVICE_CAPABILITY_SPARSE_POST_QUANTUM_RATCHET = 7;
|
||||
DEVICE_CAPABILITY_PROFILES_V2 = 8;
|
||||
reserved 8;
|
||||
DEVICE_CAPABILITY_USERNAME_CHANGE_SYNC_MESSAGE = 9;
|
||||
DEVICE_CAPABILITY_OPTIONAL_PHONE_NUMBER = 10;
|
||||
DEVICE_CAPABILITY_REPLY_PRIVATELY = 11;
|
||||
DEVICE_CAPABILITY_CONTACT_DELETE = 12;
|
||||
DEVICE_CAPABILITY_ADMIN_REMOVE_AND_DELETE = 13;
|
||||
}
|
||||
|
||||
message ZkCredential {
|
||||
|
||||
@@ -46,6 +46,9 @@ service Devices {
|
||||
|
||||
// Declares that the authenticated device supports certain features.
|
||||
rpc SetCapabilities(SetCapabilitiesRequest) returns (SetCapabilitiesResponse) {}
|
||||
|
||||
// Changes the password for the currently authenticated device.
|
||||
rpc ChangeDevicePassword(ChangeDevicePasswordRequest) returns (ChangeDevicePasswordResponse) {}
|
||||
}
|
||||
|
||||
message GetDevicesRequest {}
|
||||
@@ -136,3 +139,9 @@ message SetCapabilitiesRequest {
|
||||
}
|
||||
|
||||
message SetCapabilitiesResponse {}
|
||||
|
||||
message ChangeDevicePasswordRequest {
|
||||
string new_password = 1 [(require.size) = {min: 32; max: 255}];
|
||||
}
|
||||
|
||||
message ChangeDevicePasswordResponse {}
|
||||
@@ -137,7 +137,7 @@ message DevicePreKeyBundle {
|
||||
|
||||
// A one-time KEM pre-key (or a last-resort KEM pre-key) for the targeted
|
||||
// account/device/identity.
|
||||
common.KemSignedPreKey kem_one_time_pre_key = 3;
|
||||
common.KemSignedPreKey kem_pre_key = 3;
|
||||
|
||||
// The registration ID for the targeted account/device/identity.
|
||||
uint32 registration_id = 4;
|
||||
@@ -230,8 +230,16 @@ message CheckIdentityKeyRequest {
|
||||
}
|
||||
|
||||
message CheckIdentityKeyResponse {
|
||||
// The service identifier of the account for which there is a mismatch between the client and server identity key fingerprints.
|
||||
common.ServiceIdentifier target_identifier = 1;
|
||||
// The identity key that is stored by the server for the target account/identity type.
|
||||
bytes identity_key = 2;
|
||||
|
||||
oneof response {
|
||||
// The key for the target account/identity type matched.
|
||||
google.protobuf.Empty matched = 1;
|
||||
|
||||
// The identity key that is stored by the server for the target account/identity type.
|
||||
bytes identity_key = 2;
|
||||
|
||||
// Either the target account was not found, or it has no identity key for
|
||||
// the requested identity type.
|
||||
errors.NotFound target_not_found = 3 [(tag.reason) = "not_found"];
|
||||
}
|
||||
}
|
||||
@@ -95,6 +95,12 @@ message GetMessagesResponse {
|
||||
// to deliver newly arrived messages.
|
||||
google.protobuf.Empty queue_empty = 2;
|
||||
}
|
||||
|
||||
// The time, in milliseconds since the Unix epoch, at which this response
|
||||
// was sent, according to the server's clock. This can be helpful for detecting
|
||||
// clock drift between the client and server, which can be important for
|
||||
// time-sensitive messages.
|
||||
uint64 server_time_epoch_millis = 3;
|
||||
}
|
||||
|
||||
// Provides methods for sending "sealed sender" messages.
|
||||
|
||||
@@ -30,8 +30,8 @@ service OneTimeDonations {
|
||||
// and token.
|
||||
//
|
||||
// The PayPal approval page presented to the user may be localized. Callers
|
||||
// should set their language preferences via an "Accept-Language" header on
|
||||
// the request:
|
||||
// should set their language preferences via gRPC metadata on the request with
|
||||
// the key "Accept-Language" header:
|
||||
// https://datatracker.ietf.org/doc/html/rfc3282#section-3
|
||||
rpc CreatePayPalBoost(CreatePayPalBoostRequest) returns (CreatePayPalBoostResponse) {}
|
||||
|
||||
|
||||
@@ -289,8 +289,8 @@ message LegacyProfileResult {
|
||||
bytes about = 2;
|
||||
// The ciphertext of the emoji on the profile.
|
||||
bytes about_emoji = 3;
|
||||
// The cdn0 path of the avatar on the profile.
|
||||
string avatar = 4;
|
||||
// The URL of the avatar on the profile.
|
||||
string avatar_url = 4;
|
||||
// The ciphertext of the phone-number sharing setting on the profile.
|
||||
bytes phone_number_sharing = 5;
|
||||
// The ciphertext of the MobileCoin wallet ID on the profile.
|
||||
@@ -414,7 +414,7 @@ message ExtendAvatarTTLRequest {
|
||||
message ExtendAvatarTTLResponse {
|
||||
oneof response {
|
||||
// The avatar that was extended. May be used as a check against state de-synchronization.
|
||||
string path = 1;
|
||||
string url = 1;
|
||||
errors.FailedZkAuthentication invalid_credential_presentation = 2 [(tag.reason) = "invalid_credential_presentation"];
|
||||
// the identity does not have an active avatar
|
||||
errors.NotFound not_found = 3 [(tag.reason) = "no_active_avatar"];
|
||||
|
||||
@@ -25,8 +25,8 @@ service RemoteConfiguration {
|
||||
// Returns detailed information for all configured badges, keyed by badge ID.
|
||||
//
|
||||
// Badge descriptions may contain localized strings. Callers should set their
|
||||
// language preferences via an "Accept-Language" header on the request
|
||||
// https://datatracker.ietf.org/doc/html/rfc3282#section-3
|
||||
// language preferences via gRPC metadata on the request with the key
|
||||
// "Accept-Language": https://datatracker.ietf.org/doc/html/rfc3282#section-3
|
||||
//
|
||||
// Callers may cache a badges result for up to 1 day before checking (via
|
||||
// etag) if there are any new updates.
|
||||
|
||||
@@ -39,8 +39,8 @@ service Subscriptions {
|
||||
// Returns a PayPal billing agreement approval URL and token that can be used to set up PayPal as a payment method.
|
||||
//
|
||||
// The presented billing agreement may be localized. Callers should set their
|
||||
// language preferences via an "Accept-Language" header on the request:
|
||||
// https://datatracker.ietf.org/doc/html/rfc3282#section-3
|
||||
// language preferences via gRPC metadata on the request with the key
|
||||
// "Accept-Language": https://datatracker.ietf.org/doc/html/rfc3282#section-3
|
||||
rpc CreatePayPalPaymentMethod(CreatePayPalPaymentMethodRequest) returns (CreatePayPalPaymentMethodResponse) {}
|
||||
|
||||
// Sets the default payment method for a subscriber.
|
||||
|
||||
+6
-5
@@ -60,6 +60,7 @@ import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.signal.libsignal.usernames.BaseUsernameException;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
|
||||
import org.whispersystems.textsecuregcm.auth.StoredRegistrationLock;
|
||||
@@ -675,7 +676,7 @@ class AccountControllerTest {
|
||||
|
||||
@Test
|
||||
void testConfirmUsernameHash()
|
||||
throws BaseUsernameException, UsernameHashNotAvailableException, UsernameReservationNotFoundException {
|
||||
throws BaseUsernameException, UsernameHashNotAvailableException, UsernameReservationNotFoundException, InvalidInputException {
|
||||
Account account = mock(Account.class);
|
||||
final UUID uuid = UUID.randomUUID();
|
||||
when(account.getUsernameHash()).thenReturn(Optional.of(USERNAME_HASH_1));
|
||||
@@ -713,7 +714,7 @@ class AccountControllerTest {
|
||||
|
||||
@Test
|
||||
void testConfirmUsernameHashOld()
|
||||
throws BaseUsernameException, UsernameHashNotAvailableException, UsernameReservationNotFoundException {
|
||||
throws BaseUsernameException, UsernameHashNotAvailableException, UsernameReservationNotFoundException, InvalidInputException {
|
||||
Account account = mock(Account.class);
|
||||
when(account.getUsernameHash()).thenReturn(Optional.of(USERNAME_HASH_1));
|
||||
when(account.getUsernameLinkHandle()).thenReturn(null);
|
||||
@@ -737,7 +738,7 @@ class AccountControllerTest {
|
||||
|
||||
@Test
|
||||
void testConfirmUnreservedUsernameHash()
|
||||
throws BaseUsernameException, UsernameHashNotAvailableException, UsernameReservationNotFoundException {
|
||||
throws BaseUsernameException, UsernameHashNotAvailableException, UsernameReservationNotFoundException, InvalidInputException {
|
||||
when(accountsManager.confirmReservedUsernameHash(any(), eq(USERNAME_HASH_1), any()))
|
||||
.thenThrow(new UsernameReservationNotFoundException());
|
||||
|
||||
@@ -754,7 +755,7 @@ class AccountControllerTest {
|
||||
|
||||
@Test
|
||||
void testConfirmLapsedUsernameHash()
|
||||
throws BaseUsernameException, UsernameHashNotAvailableException, UsernameReservationNotFoundException {
|
||||
throws BaseUsernameException, UsernameHashNotAvailableException, UsernameReservationNotFoundException, InvalidInputException {
|
||||
when(accountsManager.confirmReservedUsernameHash(any(), eq(USERNAME_HASH_1), any()))
|
||||
.thenThrow(new UsernameHashNotAvailableException());
|
||||
|
||||
@@ -805,7 +806,7 @@ class AccountControllerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCommitUsernameHashWithInvalidProof() throws BaseUsernameException {
|
||||
void testCommitUsernameHashWithInvalidProof() throws BaseUsernameException, InvalidInputException {
|
||||
doThrow(new BaseUsernameException("invalid username")).when(usernameZkProofVerifier).verifyProof(eq(ZK_PROOF), eq(USERNAME_HASH_1));
|
||||
|
||||
try (final Response response = resources.getJerseyTest()
|
||||
|
||||
+12
-11
@@ -144,22 +144,12 @@ class AttachmentControllerV4Test {
|
||||
.isEqualTo(Response.Status.REQUEST_ENTITY_TOO_LARGE.getStatusCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingUploadLengthDoesNotRateLimit() throws RateLimitExceededException {
|
||||
doThrow(RateLimitExceededException.class).when(BYTE_RATE_LIMITER).validate(AuthHelper.VALID_UUID);
|
||||
|
||||
assertThatNoException().isThrownBy(() -> resources.getJerseyTest()
|
||||
.target("/v4/attachments/form/upload")
|
||||
.request()
|
||||
.header("Authorization", CDN3_ENABLED_CREDS)
|
||||
.get().getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void countRateLimitExceeded() throws RateLimitExceededException {
|
||||
doThrow(RateLimitExceededException.class).when(COUNT_RATE_LIMITER).validate(AuthHelper.VALID_UUID);
|
||||
assertThat(resources.getJerseyTest()
|
||||
.target("/v4/attachments/form/upload")
|
||||
.queryParam("uploadLength", MAX_UPLOAD_LENGTH)
|
||||
.request()
|
||||
.header("Authorization", CDN3_ENABLED_CREDS)
|
||||
.get().getStatus())
|
||||
@@ -202,6 +192,7 @@ class AttachmentControllerV4Test {
|
||||
void testV4GcsForm() throws MalformedURLException {
|
||||
AttachmentDescriptorV3 descriptor = resources.getJerseyTest()
|
||||
.target("/v4/attachments/form/upload")
|
||||
.queryParam("uploadLength", MAX_UPLOAD_LENGTH)
|
||||
.request()
|
||||
.header("Authorization", CDN3_DISABLED_CREDS)
|
||||
.get(AttachmentDescriptorV3.class);
|
||||
@@ -209,6 +200,16 @@ class AttachmentControllerV4Test {
|
||||
assertValidCdn2Response(descriptor);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testV4GcsFormNoUploadLength() throws MalformedURLException {
|
||||
assertThat(resources.getJerseyTest()
|
||||
.target("/v4/attachments/form/upload")
|
||||
.request()
|
||||
.header("Authorization", CDN3_DISABLED_CREDS)
|
||||
.get()
|
||||
.getStatus()).isEqualTo(400);
|
||||
}
|
||||
|
||||
private static void assertValidCdn2Response(final AttachmentDescriptorV3 descriptor) throws MalformedURLException {
|
||||
assertThat(descriptor.key()).isNotBlank();
|
||||
assertThat(descriptor.cdn()).isEqualTo(2);
|
||||
|
||||
-19
@@ -259,25 +259,6 @@ class VerificationControllerTest {
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void createBeninSessionFailure() throws RateLimitExceededException {
|
||||
// libphonenumber 8.13.50 and on generate new-format numbers for Benin
|
||||
final String newFormatBeninE164 = PhoneNumberUtil.getInstance()
|
||||
.format(PhoneNumberUtil.getInstance().getExampleNumber("BJ"), PhoneNumberUtil.PhoneNumberFormat.E164);
|
||||
final String oldFormatBeninE164 = newFormatBeninE164.replaceFirst("01", "");
|
||||
|
||||
when(registrationServiceClient.createRegistrationSession(any(), anyString(), anyBoolean(), any(), any(), any()))
|
||||
.thenReturn(new RegistrationServiceSession(SESSION_ID, NUMBER, false, null, null, null, SESSION_EXPIRATION_SECONDS));
|
||||
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
.target("/v1/verification/session")
|
||||
.request()
|
||||
.header(HttpHeaders.X_FORWARDED_FOR, "127.0.0.1");
|
||||
try (Response response = request.post(Entity.json(createSessionJson(oldFormatBeninE164, "token", "fcm")))) {
|
||||
assertEquals(499, response.getStatus());
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void createSessionSuccess(final String pushToken, final String pushTokenType,
|
||||
|
||||
+2
-1
@@ -112,6 +112,7 @@ import org.signal.chat.errors.FailedPrecondition;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.signal.libsignal.protocol.ecc.ECKeyPair;
|
||||
import org.signal.libsignal.usernames.BaseUsernameException;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.ZkCredentialKeyPair;
|
||||
import org.signal.libsignal.zkgroup.ZkCredentialPublicKey;
|
||||
import org.whispersystems.textsecuregcm.auth.InvalidRegistrationSessionException;
|
||||
@@ -520,7 +521,7 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
|
||||
}
|
||||
|
||||
@Test
|
||||
void confirmUsernameHashInvalidProof() throws BaseUsernameException {
|
||||
void confirmUsernameHashInvalidProof() throws BaseUsernameException, InvalidInputException {
|
||||
final byte[] usernameHash = TestRandomUtil.nextBytes(AccountController.USERNAME_HASH_LENGTH);
|
||||
|
||||
final byte[] usernameCiphertext = TestRandomUtil.nextBytes(32);
|
||||
|
||||
+24
@@ -170,6 +170,30 @@ class BackupsGrpcServiceTest extends SimpleBaseGrpcTest<BackupsGrpcService, Back
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void setBackupIdMissingAccount() {
|
||||
when(accountsManager.getByAccountIdentifier(any())).thenReturn(Optional.empty());
|
||||
|
||||
GrpcTestUtils.assertStatusException(
|
||||
Status.UNAUTHENTICATED, () -> authenticatedServiceStub().setBackupId(SetBackupIdRequest.newBuilder()
|
||||
.setMediaBackupAuthCredentialRequest(ByteString.copyFrom(mediaAuthCredRequest.serialize()))
|
||||
.setMessagesBackupAuthCredentialRequest(ByteString.copyFrom(messagesAuthCredRequest.serialize()))
|
||||
.build())
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void setBackupIdMissingDevice() {
|
||||
when(account.getDevice(AUTHENTICATED_DEVICE_ID)).thenReturn(Optional.empty());
|
||||
|
||||
GrpcTestUtils.assertStatusException(
|
||||
Status.UNAUTHENTICATED, () -> authenticatedServiceStub().setBackupId(SetBackupIdRequest.newBuilder()
|
||||
.setMediaBackupAuthCredentialRequest(ByteString.copyFrom(mediaAuthCredRequest.serialize()))
|
||||
.setMessagesBackupAuthCredentialRequest(ByteString.copyFrom(messagesAuthCredRequest.serialize()))
|
||||
.build())
|
||||
);
|
||||
}
|
||||
|
||||
public static Stream<Arguments> redeemReceipt() {
|
||||
return Stream.of(
|
||||
Arguments.of(null, RedeemReceiptResponse.ResponseCase.SUCCESS),
|
||||
|
||||
+85
-1
@@ -36,6 +36,7 @@ import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.junitpioneer.jupiter.cartesian.CartesianTest;
|
||||
import org.mockito.Mock;
|
||||
import org.signal.chat.device.ChangeDevicePasswordRequest;
|
||||
import org.signal.chat.device.ClearPushTokenRequest;
|
||||
import org.signal.chat.device.ClearPushTokenResponse;
|
||||
import org.signal.chat.device.DevicesGrpc;
|
||||
@@ -448,7 +449,10 @@ class DevicesGrpcServiceTest extends SimpleBaseGrpcTest<DevicesGrpcService, Devi
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean transfer,
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean attachmentBackfill,
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean spqr,
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean usernameChangeSyncMessage) {
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean usernameChangeSyncMessage,
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean replyPrivately,
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean contactDelete,
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean adminRemoveAndDelete) {
|
||||
|
||||
mockAuthenticationInterceptor().setAuthenticatedDevice(AUTHENTICATED_ACI, deviceId);
|
||||
|
||||
@@ -477,6 +481,18 @@ class DevicesGrpcServiceTest extends SimpleBaseGrpcTest<DevicesGrpcService, Devi
|
||||
requestBuilder.addCapabilities(org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_USERNAME_CHANGE_SYNC_MESSAGE);
|
||||
}
|
||||
|
||||
if (replyPrivately) {
|
||||
requestBuilder.addCapabilities(org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_REPLY_PRIVATELY);
|
||||
}
|
||||
|
||||
if (contactDelete) {
|
||||
requestBuilder.addCapabilities(org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_CONTACT_DELETE);
|
||||
}
|
||||
|
||||
if (adminRemoveAndDelete) {
|
||||
requestBuilder.addCapabilities(org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_ADMIN_REMOVE_AND_DELETE);
|
||||
}
|
||||
|
||||
final SetCapabilitiesResponse ignored = authenticatedServiceStub().setCapabilities(requestBuilder.build());
|
||||
|
||||
final Set<DeviceCapability> expectedCapabilities = new HashSet<>();
|
||||
@@ -502,6 +518,74 @@ class DevicesGrpcServiceTest extends SimpleBaseGrpcTest<DevicesGrpcService, Devi
|
||||
expectedCapabilities.add(DeviceCapability.USERNAME_CHANGE_SYNC_MESSAGE);
|
||||
}
|
||||
|
||||
if (replyPrivately) {
|
||||
expectedCapabilities.add(DeviceCapability.REPLY_PRIVATELY);
|
||||
}
|
||||
|
||||
if (contactDelete) {
|
||||
expectedCapabilities.add(DeviceCapability.CONTACT_DELETE);
|
||||
}
|
||||
|
||||
if (adminRemoveAndDelete) {
|
||||
expectedCapabilities.add(DeviceCapability.ADMIN_REMOVE_AND_DELETE);
|
||||
}
|
||||
|
||||
verify(device).setCapabilities(expectedCapabilities);
|
||||
}
|
||||
|
||||
@Test
|
||||
void changeDevicePassword() {
|
||||
final byte deviceId = 127;
|
||||
mockAuthenticationInterceptor().setAuthenticatedDevice(AUTHENTICATED_ACI, deviceId);
|
||||
|
||||
final String newPassword = RandomStringUtils.insecure().nextAlphanumeric(32);
|
||||
|
||||
when(accountsManager.updateDevicePassword(any(), anyByte(), any())).thenReturn(true);
|
||||
|
||||
authenticatedServiceStub().changeDevicePassword(ChangeDevicePasswordRequest.newBuilder()
|
||||
.setNewPassword(newPassword)
|
||||
.build());
|
||||
|
||||
verify(accountsManager).updateDevicePassword(AUTHENTICATED_ACI, deviceId, newPassword);
|
||||
}
|
||||
|
||||
@Test
|
||||
void changeDevicePasswordNotChanged() {
|
||||
when(accountsManager.updateDevicePassword(any(), anyByte(), any())).thenReturn(false);
|
||||
|
||||
assertStatusException(Status.UNAUTHENTICATED,
|
||||
() -> authenticatedServiceStub().changeDevicePassword(ChangeDevicePasswordRequest.newBuilder()
|
||||
.setNewPassword(RandomStringUtils.insecure().nextAlphanumeric(32))
|
||||
.build()));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void changeDevicePasswordIllegalArgument(final ChangeDevicePasswordRequest request) {
|
||||
assertStatusException(Status.INVALID_ARGUMENT, () -> authenticatedServiceStub().changeDevicePassword(request));
|
||||
verify(accountsManager, never()).updateDevicePassword(any(), anyByte(), any());
|
||||
}
|
||||
|
||||
private static Stream<Arguments> changeDevicePasswordIllegalArgument() {
|
||||
return Stream.of(
|
||||
Arguments.argumentSet("No new password",
|
||||
ChangeDevicePasswordRequest.newBuilder()
|
||||
.build()),
|
||||
|
||||
Arguments.argumentSet("New password too short",
|
||||
ChangeDevicePasswordRequest.newBuilder()
|
||||
.setNewPassword(RandomStringUtils.insecure().nextAlphanumeric(31))
|
||||
.build()),
|
||||
|
||||
Arguments.argumentSet("New password blank",
|
||||
ChangeDevicePasswordRequest.newBuilder()
|
||||
.setNewPassword(" ".repeat(64))
|
||||
.build()),
|
||||
|
||||
Arguments.argumentSet("New password too long",
|
||||
ChangeDevicePasswordRequest.newBuilder()
|
||||
.setNewPassword(RandomStringUtils.insecure().nextAlphanumeric(256))
|
||||
.build())
|
||||
);
|
||||
}
|
||||
}
|
||||
+173
@@ -0,0 +1,173 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import io.grpc.CallOptions;
|
||||
import io.grpc.Channel;
|
||||
import io.grpc.ClientCall;
|
||||
import io.grpc.ClientInterceptor;
|
||||
import io.grpc.Codec;
|
||||
import io.grpc.DecompressorRegistry;
|
||||
import io.grpc.ForwardingClientCall;
|
||||
import io.grpc.ForwardingClientCallListener;
|
||||
import io.grpc.ManagedChannel;
|
||||
import io.grpc.Metadata;
|
||||
import io.grpc.MethodDescriptor;
|
||||
import io.grpc.Server;
|
||||
import io.grpc.inprocess.InProcessChannelBuilder;
|
||||
import io.grpc.inprocess.InProcessServerBuilder;
|
||||
import java.io.IOException;
|
||||
import java.util.Collections;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import javax.annotation.Nullable;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.signal.chat.rpc.EchoRequest;
|
||||
import org.signal.chat.rpc.EchoResponse;
|
||||
import org.signal.chat.rpc.EchoServiceGrpc;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicGrpcCompressionConfiguration;
|
||||
import org.whispersystems.textsecuregcm.tests.util.FakeDynamicConfigurationManager;
|
||||
|
||||
class GrpcCompressionInterceptorTest {
|
||||
|
||||
private static final String SERVER_NAME = GrpcCompressionInterceptor.class.getSimpleName();
|
||||
|
||||
private static final Metadata.Key<String> GRPC_ENCODING_KEY =
|
||||
Metadata.Key.of("grpc-encoding", Metadata.ASCII_STRING_MARSHALLER);
|
||||
|
||||
private static final EchoRequest REQUEST = EchoRequest.newBuilder()
|
||||
.setPayload(ByteString.copyFromUtf8("compressible ".repeat(100)))
|
||||
.build();
|
||||
|
||||
private Server server;
|
||||
private ManagedChannel channel;
|
||||
private final ResponseHeaderCapturingInterceptor responseHeaderCapturingInterceptor =
|
||||
new ResponseHeaderCapturingInterceptor();
|
||||
|
||||
@AfterEach
|
||||
void tearDown() throws Exception {
|
||||
server.shutdownNow();
|
||||
channel.shutdownNow();
|
||||
server.awaitTermination(1, TimeUnit.SECONDS);
|
||||
channel.awaitTermination(1, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@Test
|
||||
void noCompressionByDefault() throws Exception {
|
||||
final EchoServiceGrpc.EchoServiceBlockingStub client =
|
||||
setup(Collections.emptySet(), Collections.emptySet(), DecompressorRegistry.getDefaultInstance());
|
||||
|
||||
assertThat(client.echo(REQUEST).getPayload()).isEqualTo(REQUEST.getPayload());
|
||||
assertThat(responseHeaderCapturingInterceptor.responseEncoding).isEqualTo("identity");
|
||||
}
|
||||
|
||||
@Test
|
||||
void compressByMethod() throws Exception {
|
||||
final EchoServiceGrpc.EchoServiceBlockingStub client =
|
||||
setup(Collections.emptySet(), Set.of("org.signal.chat.rpc.EchoService/echo"),
|
||||
DecompressorRegistry.getDefaultInstance());
|
||||
|
||||
final EchoResponse echo = client.echo(REQUEST);
|
||||
assertThat(echo.getPayload()).isEqualTo(REQUEST.getPayload());
|
||||
assertThat(responseHeaderCapturingInterceptor.responseEncoding).isEqualTo("gzip");
|
||||
|
||||
final EchoResponse echo2 = client.echo2(REQUEST);
|
||||
assertThat(echo2.getPayload()).isEqualTo(REQUEST.getPayload());
|
||||
assertThat(responseHeaderCapturingInterceptor.responseEncoding).isEqualTo("identity");
|
||||
}
|
||||
|
||||
@Test
|
||||
void compressByService() throws Exception {
|
||||
final EchoServiceGrpc.EchoServiceBlockingStub client =
|
||||
setup(Set.of("org.signal.chat.rpc.EchoService"), Collections.emptySet(),
|
||||
DecompressorRegistry.getDefaultInstance());
|
||||
|
||||
final EchoResponse echo = client.echo(REQUEST);
|
||||
assertThat(echo.getPayload()).isEqualTo(REQUEST.getPayload());
|
||||
assertThat(responseHeaderCapturingInterceptor.responseEncoding).isEqualTo("gzip");
|
||||
|
||||
final EchoResponse echo2 = client.echo2(REQUEST);
|
||||
assertThat(echo2.getPayload()).isEqualTo(REQUEST.getPayload());
|
||||
assertThat(responseHeaderCapturingInterceptor.responseEncoding).isEqualTo("gzip");
|
||||
}
|
||||
|
||||
@Test
|
||||
void compressByServiceWrongService() throws Exception {
|
||||
final EchoServiceGrpc.EchoServiceBlockingStub client =
|
||||
setup(Set.of("org.signal.chat.rpc.NotEchoService"), Collections.emptySet(),
|
||||
DecompressorRegistry.getDefaultInstance());
|
||||
|
||||
assertThat(client.echo(REQUEST).getPayload()).isEqualTo(REQUEST.getPayload());
|
||||
assertThat(responseHeaderCapturingInterceptor.responseEncoding).isEqualTo("identity");
|
||||
}
|
||||
|
||||
@Test
|
||||
void clientDoesNotAcceptGzip() throws Exception {
|
||||
final EchoServiceGrpc.EchoServiceBlockingStub client =
|
||||
setup(Set.of("org.signal.chat.rpc.EchoService"), Collections.emptySet(),
|
||||
DecompressorRegistry.emptyInstance().with(Codec.Identity.NONE, true));
|
||||
|
||||
assertThat(client.echo(REQUEST).getPayload()).isEqualTo(REQUEST.getPayload());
|
||||
assertThat(responseHeaderCapturingInterceptor.responseEncoding).isEqualTo("identity");
|
||||
}
|
||||
|
||||
private EchoServiceGrpc.EchoServiceBlockingStub setup(
|
||||
final Set<String> compressedServices,
|
||||
final Set<String> compressedMethods,
|
||||
final DecompressorRegistry clientDecompressorRegistry) throws IOException {
|
||||
|
||||
final DynamicConfiguration configuration = mock(DynamicConfiguration.class);
|
||||
when(configuration.getGrpcCompression())
|
||||
.thenReturn(new DynamicGrpcCompressionConfiguration(compressedServices, compressedMethods));
|
||||
|
||||
server = InProcessServerBuilder.forName(SERVER_NAME)
|
||||
.directExecutor()
|
||||
.addService(new EchoServiceImpl())
|
||||
.intercept(new GrpcCompressionInterceptor(new FakeDynamicConfigurationManager<>(configuration)))
|
||||
.build()
|
||||
.start();
|
||||
|
||||
channel = InProcessChannelBuilder.forName(SERVER_NAME)
|
||||
.directExecutor()
|
||||
.decompressorRegistry(clientDecompressorRegistry)
|
||||
.intercept(responseHeaderCapturingInterceptor)
|
||||
.build();
|
||||
|
||||
return EchoServiceGrpc.newBlockingStub(channel);
|
||||
}
|
||||
|
||||
private static class ResponseHeaderCapturingInterceptor implements ClientInterceptor {
|
||||
|
||||
@Nullable
|
||||
private volatile String responseEncoding;
|
||||
|
||||
@Override
|
||||
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(final MethodDescriptor<ReqT, RespT> method,
|
||||
final CallOptions callOptions, final Channel next) {
|
||||
|
||||
return new ForwardingClientCall.SimpleForwardingClientCall<>(next.newCall(method, callOptions)) {
|
||||
@Override
|
||||
public void start(final Listener<RespT> responseListener, final Metadata headers) {
|
||||
responseEncoding = null;
|
||||
|
||||
super.start(new ForwardingClientCallListener.SimpleForwardingClientCallListener<>(responseListener) {
|
||||
@Override
|
||||
public void onHeaders(final Metadata responseHeaders) {
|
||||
responseEncoding = responseHeaders.get(GRPC_ENCODING_KEY);
|
||||
super.onHeaders(responseHeaders);
|
||||
}
|
||||
}, headers);
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
+20
-18
@@ -26,13 +26,12 @@ import java.security.NoSuchAlgorithmException;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
@@ -45,6 +44,7 @@ import org.signal.chat.common.EcPreKey;
|
||||
import org.signal.chat.common.EcSignedPreKey;
|
||||
import org.signal.chat.common.KemSignedPreKey;
|
||||
import org.signal.chat.common.ServiceIdentifier;
|
||||
import org.signal.chat.errors.NotFound;
|
||||
import org.signal.chat.keys.AccountPreKeyBundles;
|
||||
import org.signal.chat.keys.CheckIdentityKeyRequest;
|
||||
import org.signal.chat.keys.CheckIdentityKeyResponse;
|
||||
@@ -54,7 +54,6 @@ import org.signal.chat.keys.GetPreKeysAnonymousResponse;
|
||||
import org.signal.chat.keys.GetPreKeysRequest;
|
||||
import org.signal.chat.keys.KeysAnonymousGrpc;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.signal.libsignal.protocol.InvalidKeyException;
|
||||
import org.signal.libsignal.protocol.ecc.ECKeyPair;
|
||||
import org.signal.libsignal.zkgroup.ServerSecretParams;
|
||||
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessChecksum;
|
||||
@@ -137,7 +136,7 @@ class KeysAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<KeysAnonymousGrpcS
|
||||
.putDevicePreKeys(Device.PRIMARY_ID, DevicePreKeyBundle.newBuilder()
|
||||
.setEcOneTimePreKey(toGrpcEcPreKey(ecPreKey))
|
||||
.setEcSignedPreKey(toGrpcEcSignedPreKey(ecSignedPreKey))
|
||||
.setKemOneTimePreKey(toGrpcKemSignedPreKey(kemSignedPreKey))
|
||||
.setKemPreKey(toGrpcKemSignedPreKey(kemSignedPreKey))
|
||||
.build()))
|
||||
.build();
|
||||
|
||||
@@ -197,7 +196,7 @@ class KeysAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<KeysAnonymousGrpcS
|
||||
.putDevicePreKeys(Device.PRIMARY_ID, DevicePreKeyBundle.newBuilder()
|
||||
.setEcOneTimePreKey(toGrpcEcPreKey(ecPreKey))
|
||||
.setEcSignedPreKey(toGrpcEcSignedPreKey(ecSignedPreKey))
|
||||
.setKemOneTimePreKey(toGrpcKemSignedPreKey(kemSignedPreKey))
|
||||
.setKemPreKey(toGrpcKemSignedPreKey(kemSignedPreKey))
|
||||
.setRegistrationId(identityType == IdentityType.ACI ? aciRegistrationId : pniRegistrationId)
|
||||
.build());
|
||||
|
||||
@@ -258,7 +257,7 @@ class KeysAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<KeysAnonymousGrpcS
|
||||
.putDevicePreKeys(Device.PRIMARY_ID, DevicePreKeyBundle.newBuilder()
|
||||
.setEcOneTimePreKey(toGrpcEcPreKey(ecPreKey))
|
||||
.setEcSignedPreKey(toGrpcEcSignedPreKey(ecSignedPreKey))
|
||||
.setKemOneTimePreKey(toGrpcKemSignedPreKey(kemSignedPreKey))
|
||||
.setKemPreKey(toGrpcKemSignedPreKey(kemSignedPreKey))
|
||||
.build()))
|
||||
.build();
|
||||
|
||||
@@ -463,7 +462,6 @@ class KeysAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<KeysAnonymousGrpcS
|
||||
final IdentityKey mismatchedPniFingerpringAccountIdentityKey = new IdentityKey(ECKeyPair.generate().getPublicKey());
|
||||
|
||||
// Complete futures asynchronously to catch potential async/context-propagation issues
|
||||
final Duration futureDelay = Duration.ofMillis(1);
|
||||
when(mismatchedAciFingerprintAccount.getAccountIdentityKey()).thenReturn(mismatchedAciFingerprintAccountIdentityKey);
|
||||
when(accountsManager.getByServiceIdentifierAsync(new AciServiceIdentifier(mismatchedAciFingerprintAccountIdentifier)))
|
||||
.thenReturn(delayedAccount(mismatchedAciFingerprintAccount));
|
||||
@@ -476,11 +474,21 @@ class KeysAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<KeysAnonymousGrpcS
|
||||
when(accountsManager.getByServiceIdentifierAsync(new PniServiceIdentifier(mismatchedPniFingerprintAccountIdentifier)))
|
||||
.thenReturn(delayedAccount(mismatchedPniFingerprintAccount));
|
||||
|
||||
final Map<UUID, IdentityKey> expectedResponses = Map.of(
|
||||
mismatchedAciFingerprintAccountIdentifier, mismatchedAciFingerprintAccountIdentityKey,
|
||||
mismatchedPniFingerprintAccountIdentifier, mismatchedPniFingerpringAccountIdentityKey);
|
||||
final List<CheckIdentityKeyResponse> expectedResponses = List.of(
|
||||
CheckIdentityKeyResponse.newBuilder()
|
||||
.setIdentityKey(ByteString.copyFrom(mismatchedAciFingerprintAccountIdentityKey.serialize()))
|
||||
.build(),
|
||||
CheckIdentityKeyResponse.newBuilder()
|
||||
.setMatched(Empty.getDefaultInstance())
|
||||
.build(),
|
||||
CheckIdentityKeyResponse.newBuilder()
|
||||
.setTargetNotFound(NotFound.getDefaultInstance())
|
||||
.build(),
|
||||
CheckIdentityKeyResponse.newBuilder()
|
||||
.setIdentityKey(ByteString.copyFrom(mismatchedPniFingerpringAccountIdentityKey.serialize()))
|
||||
.build());
|
||||
|
||||
final Map<UUID, IdentityKey> responses = new ConcurrentHashMap<>();
|
||||
final List<CheckIdentityKeyResponse> responses = Collections.synchronizedList(new ArrayList<>());
|
||||
final CountDownLatch completedLatch = new CountDownLatch(1);
|
||||
final AtomicReference<Throwable> error = new AtomicReference<>();
|
||||
|
||||
@@ -488,13 +496,7 @@ class KeysAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<KeysAnonymousGrpcS
|
||||
keysAnonymousStub.checkIdentityKeys(new StreamObserver<>() {
|
||||
@Override
|
||||
public void onNext(final CheckIdentityKeyResponse checkIdentityKeyResponse) {
|
||||
try {
|
||||
responses.put(
|
||||
GrpcServiceIdentifierUtil.fromGrpcServiceIdentifier(checkIdentityKeyResponse.getTargetIdentifier()).uuid(),
|
||||
new IdentityKey(checkIdentityKeyResponse.getIdentityKey().toByteArray()));
|
||||
} catch (final InvalidKeyException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
responses.add(checkIdentityKeyResponse);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
+1
-1
@@ -597,7 +597,7 @@ class KeysGrpcServiceTest extends SimpleBaseGrpcTest<KeysGrpcService, KeysGrpc.K
|
||||
.setPublicKey(ByteString.copyFrom(ecSignedPreKey.serializedPublicKey()))
|
||||
.setSignature(ByteString.copyFrom(ecSignedPreKey.signature()))
|
||||
.build())
|
||||
.setKemOneTimePreKey(KemSignedPreKey.newBuilder()
|
||||
.setKemPreKey(KemSignedPreKey.newBuilder()
|
||||
.setKeyId(KeyIdUtil.toUnsignedInt(kemSignedPreKey.keyId()))
|
||||
.setPublicKey(ByteString.copyFrom(kemSignedPreKey.serializedPublicKey()))
|
||||
.setSignature(ByteString.copyFrom(kemSignedPreKey.signature()))
|
||||
|
||||
+62
-6
@@ -12,6 +12,7 @@ import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import io.grpc.Status;
|
||||
import java.io.IOException;
|
||||
import java.security.SecureRandom;
|
||||
import java.time.Clock;
|
||||
@@ -25,14 +26,18 @@ import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import org.apache.commons.lang3.RandomStringUtils;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -42,6 +47,8 @@ import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.signal.chat.messages.GetMessagesResponse;
|
||||
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestManager;
|
||||
import org.whispersystems.textsecuregcm.configuration.BulkheadConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.CircuitBreakerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
@@ -49,6 +56,7 @@ import org.whispersystems.textsecuregcm.metrics.MessageMetrics;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationScheduler;
|
||||
import org.whispersystems.textsecuregcm.push.ReceiptSender;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisServerExtension;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
@@ -66,6 +74,7 @@ import reactor.core.publisher.Mono;
|
||||
import reactor.core.publisher.Sinks;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
import reactor.core.scheduler.Schedulers;
|
||||
import reactor.test.StepVerifier;
|
||||
import reactor.test.publisher.TestPublisher;
|
||||
|
||||
@Timeout(value = 30, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
|
||||
@@ -75,7 +84,17 @@ class MessageDispatcherIntegrationTest {
|
||||
static final DynamoDbExtension DYNAMO_DB_EXTENSION = new DynamoDbExtension(Tables.MESSAGES);
|
||||
|
||||
@RegisterExtension
|
||||
static FoundationDbClusterExtension FOUNDATION_DB_EXTENSION = new FoundationDbClusterExtension(1);
|
||||
static final FoundationDbClusterExtension FOUNDATION_DB_EXTENSION;
|
||||
|
||||
static {
|
||||
final BulkheadConfiguration bulkheadConfiguration = new BulkheadConfiguration();
|
||||
bulkheadConfiguration.setMaxConcurrentCalls(256);
|
||||
|
||||
FOUNDATION_DB_EXTENSION = new FoundationDbClusterExtension(1, new CircuitBreakerConfiguration(), bulkheadConfiguration);
|
||||
}
|
||||
|
||||
@RegisterExtension
|
||||
static final RedisServerExtension REDIS_EXTENSION = RedisServerExtension.builder().build();
|
||||
|
||||
private static ExecutorService sharedExecutorService;
|
||||
private static ScheduledExecutorService sharedScheduledExecutorService;
|
||||
@@ -86,6 +105,7 @@ class MessageDispatcherIntegrationTest {
|
||||
private Account account;
|
||||
private Device device;
|
||||
private MessageDispatcher messageDispatcher;
|
||||
private DisconnectionRequestManager disconnectionRequestManager;
|
||||
|
||||
private long serialTimestamp = System.currentTimeMillis();
|
||||
|
||||
@@ -128,6 +148,11 @@ class MessageDispatcherIntegrationTest {
|
||||
when(account.getAccountIdentifier()).thenReturn(UUID.randomUUID());
|
||||
when(device.getId()).thenReturn(Device.PRIMARY_ID);
|
||||
|
||||
disconnectionRequestManager = new DisconnectionRequestManager(REDIS_EXTENSION.getRedisClient(),
|
||||
Runnable::run,
|
||||
mock(ScheduledExecutorService.class));
|
||||
disconnectionRequestManager.start();
|
||||
|
||||
messageDispatcher = new MessageDispatcher(
|
||||
mock(ReceiptSender.class),
|
||||
new MessagesManager(messagesDynamoDb, foundationDbMessageStore,
|
||||
@@ -136,8 +161,14 @@ class MessageDispatcherIntegrationTest {
|
||||
new MessageMetrics(),
|
||||
mock(PushNotificationManager.class),
|
||||
mock(PushNotificationScheduler.class),
|
||||
mock(DisconnectionRequestManager.class),
|
||||
mock(ClientReleaseManager.class));
|
||||
disconnectionRequestManager,
|
||||
mock(ClientReleaseManager.class),
|
||||
Clock.systemUTC());
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
disconnectionRequestManager.stop();
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
@@ -178,13 +209,14 @@ class MessageDispatcherIntegrationTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testProcessStoredMessagesMultipleSegments() {
|
||||
void testProcessStoredMessagesMultipleSegments() throws ExecutionException, InterruptedException, TimeoutException {
|
||||
final int dynamoDbMessageCount = 77;
|
||||
|
||||
final List<Envelope> expectedMessages = fillRandomMessages(dynamoDbMessageCount, 0);
|
||||
final AtomicInteger remainingMessages = new AtomicInteger(dynamoDbMessageCount);
|
||||
final int additionalMessageCount = 67;
|
||||
|
||||
final AtomicReference<Future<List<Envelope>>> additionalMessagesFuture = new AtomicReference<>();
|
||||
final Sinks.Many<UUID> acks = Sinks.many().unicast().onBackpressureBuffer();
|
||||
final List<Envelope> receivedMessages = messageDispatcher
|
||||
.getMessages(true, null, account, device, acks.asFlux())
|
||||
@@ -193,13 +225,14 @@ class MessageDispatcherIntegrationTest {
|
||||
.doOnNext(envelope -> {
|
||||
acks.tryEmitNext(UUIDUtil.fromByteString(envelope.getServerGuid()));
|
||||
if (remainingMessages.addAndGet(-1) == 60) {
|
||||
sharedExecutorService
|
||||
.submit(() -> expectedMessages.addAll(fillRandomMessages( 0, additionalMessageCount)));
|
||||
additionalMessagesFuture.set(sharedExecutorService.submit(() ->
|
||||
fillRandomMessages(0, additionalMessageCount)));
|
||||
}
|
||||
})
|
||||
.take(dynamoDbMessageCount + additionalMessageCount)
|
||||
.collectList()
|
||||
.block(Duration.ofSeconds(15));
|
||||
expectedMessages.addAll(additionalMessagesFuture.get().get(15, TimeUnit.SECONDS));
|
||||
assertEquals(expectedMessages.size(), receivedMessages.size());
|
||||
assertEquals(expectedMessages, receivedMessages);
|
||||
}
|
||||
@@ -224,6 +257,29 @@ class MessageDispatcherIntegrationTest {
|
||||
assertTrue(expectedMessages.containsAll(receivedMessages));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testAccountDeletedWhileConnected() {
|
||||
final AciServiceIdentifier aci = new AciServiceIdentifier(account.getAccountIdentifier());
|
||||
final Envelope envelope = generateRandomMessage(UUID.randomUUID()).toBuilder().clearServerGuid().build();
|
||||
final Sinks.Many<UUID> acks = Sinks.many().unicast().onBackpressureBuffer();
|
||||
|
||||
StepVerifier.create(messageDispatcher.getMessages(true, null, account, device, acks.asFlux()))
|
||||
.expectNextMatches(GetMessagesResponse::hasQueueEmpty)
|
||||
// Clearing deletes the watch key, which wakes our stream only if the key exists. Make sure we have written a
|
||||
// watch key by sending a message while we're present to make the interaction with clear more interesting.
|
||||
.then(() -> foundationDbMessageStore.insert(aci, Map.of(device.getId(), envelope)).join())
|
||||
.expectNextMatches(GetMessagesResponse::hasEnvelope)
|
||||
// Emulate an account delete
|
||||
.then(() -> foundationDbMessageStore.clearAll(aci))
|
||||
// Increase the chance that the stream observes the effects of the clear before the disconnection
|
||||
.thenAwait(Duration.ofMillis(1))
|
||||
.then(() -> disconnectionRequestManager.requestDisconnection(aci.uuid(), List.of(device.getId()))
|
||||
.toCompletableFuture().join())
|
||||
.expectErrorSatisfies(throwable ->
|
||||
assertEquals(Status.Code.UNAUTHENTICATED, Status.fromThrowable(throwable).getCode()))
|
||||
.verify(Duration.ofSeconds(5));
|
||||
}
|
||||
|
||||
private List<Envelope> fillRandomMessages(final int dynamoDbMessageCount, final int foundationDbMessageCount) {
|
||||
|
||||
final List<Envelope> expectedMessages = new ArrayList<>(dynamoDbMessageCount + foundationDbMessageCount);
|
||||
|
||||
+29
-22
@@ -7,6 +7,7 @@ package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyByte;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
@@ -20,7 +21,9 @@ import com.google.protobuf.ByteString;
|
||||
import com.google.protobuf.Empty;
|
||||
import io.grpc.Status;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
@@ -38,7 +41,6 @@ import org.whispersystems.textsecuregcm.auth.DisconnectionRequestManager;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.metrics.MessageMetrics;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
|
||||
@@ -51,6 +53,7 @@ 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.TestClock;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import reactor.adapter.JdkFlowAdapter;
|
||||
import reactor.core.publisher.Flux;
|
||||
@@ -59,13 +62,13 @@ import reactor.test.publisher.TestPublisher;
|
||||
|
||||
class MessageDispatcherTest {
|
||||
|
||||
private static final GetMessagesResponse QUEUE_EMPTY =
|
||||
GetMessagesResponse.newBuilder().setQueueEmpty(Empty.getDefaultInstance()).build();
|
||||
|
||||
private static final UUID ACI = UUID.randomUUID();
|
||||
private static final byte DEVICE_ID = 2;
|
||||
private static final int SOURCE_DEVICE_ID = 1;
|
||||
private static final String TEST_UA = "test-user-agent";
|
||||
private static final Clock CLOCK = TestClock.pinned(Instant.now());
|
||||
private static final GetMessagesResponse QUEUE_EMPTY =
|
||||
GetMessagesResponse.newBuilder().setQueueEmpty(Empty.getDefaultInstance()).setServerTimeEpochMillis(CLOCK.millis()).build();
|
||||
|
||||
private Account account;
|
||||
private Device device;
|
||||
@@ -92,6 +95,9 @@ class MessageDispatcherTest {
|
||||
when(device.getId()).thenReturn(DEVICE_ID);
|
||||
when(device.isPrimary()).thenReturn(true);
|
||||
|
||||
when(messagesManager.hasSuspectedDeliveryLoop(any(), anyByte()))
|
||||
.thenReturn(CompletableFuture.completedFuture(false));
|
||||
|
||||
dispatcher = new MessageDispatcher(
|
||||
receiptSender,
|
||||
messagesManager,
|
||||
@@ -99,7 +105,8 @@ class MessageDispatcherTest {
|
||||
pushNotificationManager,
|
||||
pushNotificationScheduler,
|
||||
disconnectionRequestManager,
|
||||
mock(ClientReleaseManager.class));
|
||||
mock(ClientReleaseManager.class),
|
||||
CLOCK);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@@ -119,7 +126,7 @@ class MessageDispatcherTest {
|
||||
CompletableFuture.completedFuture(mayHaveMoreMessages));
|
||||
|
||||
StepVerifier.create(responses)
|
||||
.expectNext(GetMessagesResponse.newBuilder().setEnvelope(expectedEnvelope).build())
|
||||
.expectNext(GetMessagesResponse.newBuilder().setEnvelope(expectedEnvelope).setServerTimeEpochMillis(CLOCK.millis()).build())
|
||||
.then(() -> verify(disconnectionRequestManager).addListener(eq(ACI), eq(DEVICE_ID), any()))
|
||||
.thenCancel()
|
||||
.verify(Duration.ofSeconds(5));
|
||||
@@ -137,14 +144,14 @@ class MessageDispatcherTest {
|
||||
final AciServiceIdentifier sourceServiceId = new AciServiceIdentifier(UUID.randomUUID());
|
||||
|
||||
final List<Envelope> messages = IntStream
|
||||
.range(0, MessageDispatcher.MAX_UNACKED_MESSAGES + 2)
|
||||
.range(0, MessageDispatcher.DEFAULT_MAX_UNACKED_MESSAGES + 2)
|
||||
.mapToObj(i -> createMessage(sourceServiceId, ACI, i, "hello"))
|
||||
.toList();
|
||||
final List<UUID> guids = messages.stream().map(Envelope::getServerGuid).map(UUIDUtil::fromByteString).toList();
|
||||
final List<Long> timestamps = messages.stream().map(Envelope::getServerTimestamp).toList();
|
||||
final List<GetMessagesResponse> expectedMessages = messages.stream()
|
||||
.map(e -> e.toBuilder().clearEphemeral().build())
|
||||
.map(e -> GetMessagesResponse.newBuilder().setEnvelope(e).build())
|
||||
.map(e -> GetMessagesResponse.newBuilder().setEnvelope(e).setServerTimeEpochMillis(CLOCK.millis()).build())
|
||||
.toList();
|
||||
|
||||
final MessageStream messageStream = mockMessages(messages);
|
||||
@@ -155,18 +162,18 @@ class MessageDispatcherTest {
|
||||
dispatcher.getMessages(true, TEST_UA, account, device, acks.flux());
|
||||
|
||||
StepVerifier.create(responses)
|
||||
.expectNext(expectedMessages.subList(0, MessageDispatcher.MAX_UNACKED_MESSAGES).toArray(GetMessagesResponse[]::new))
|
||||
.expectNext(expectedMessages.subList(0, MessageDispatcher.DEFAULT_MAX_UNACKED_MESSAGES).toArray(GetMessagesResponse[]::new))
|
||||
.expectNoEvent(Duration.ofMillis(1))
|
||||
|
||||
// Sending an ack should allow another message to come back
|
||||
.then(() -> acks.next(guids.get(0)))
|
||||
.expectNext(expectedMessages.get(MessageDispatcher.MAX_UNACKED_MESSAGES))
|
||||
.expectNext(expectedMessages.get(MessageDispatcher.DEFAULT_MAX_UNACKED_MESSAGES))
|
||||
.then(() -> verify(messageStream, times(1)).acknowledgeMessage(guids.get(0), timestamps.get(0)))
|
||||
.expectNoEvent(Duration.ofMillis(1))
|
||||
|
||||
// Send another one
|
||||
.then(() -> acks.next(guids.get(1)))
|
||||
.expectNext(expectedMessages.get(MessageDispatcher.MAX_UNACKED_MESSAGES + 1))
|
||||
.expectNext(expectedMessages.get(MessageDispatcher.DEFAULT_MAX_UNACKED_MESSAGES + 1))
|
||||
.then(() -> verify(messageStream, times(1)).acknowledgeMessage(guids.get(1), timestamps.get(1)))
|
||||
.expectNoEvent(Duration.ofMillis(1))
|
||||
|
||||
@@ -184,7 +191,7 @@ class MessageDispatcherTest {
|
||||
void maxOutstandingAllowsGaps() {
|
||||
final AciServiceIdentifier sourceServiceId = new AciServiceIdentifier(UUID.randomUUID());
|
||||
|
||||
final int totalMessages = MessageDispatcher.MAX_UNACKED_MESSAGES * 2;
|
||||
final int totalMessages = MessageDispatcher.DEFAULT_MAX_UNACKED_MESSAGES * 2;
|
||||
|
||||
final List<Envelope> messages = IntStream
|
||||
.range(0, totalMessages)
|
||||
@@ -195,7 +202,7 @@ class MessageDispatcherTest {
|
||||
.toList();
|
||||
final List<GetMessagesResponse> expectedMessages = messages.stream()
|
||||
.map(e -> e.toBuilder().clearEphemeral().build())
|
||||
.map(e -> GetMessagesResponse.newBuilder().setEnvelope(e).build())
|
||||
.map(e -> GetMessagesResponse.newBuilder().setEnvelope(e).setServerTimeEpochMillis(CLOCK.millis()).build())
|
||||
.toList();
|
||||
|
||||
mockMessages(messages);
|
||||
@@ -205,22 +212,22 @@ class MessageDispatcherTest {
|
||||
dispatcher.getMessages(true, TEST_UA, account, device, acks.flux());
|
||||
|
||||
StepVerifier.create(responses)
|
||||
.expectNext(expectedMessages.subList(0, MessageDispatcher.MAX_UNACKED_MESSAGES).toArray(GetMessagesResponse[]::new))
|
||||
.expectNext(expectedMessages.subList(0, MessageDispatcher.DEFAULT_MAX_UNACKED_MESSAGES).toArray(GetMessagesResponse[]::new))
|
||||
.expectNoEvent(Duration.ofMillis(1))
|
||||
.then(() -> {
|
||||
for (int i = 0; i < MessageDispatcher.MAX_UNACKED_MESSAGES; i++) {
|
||||
for (int i = 0; i < MessageDispatcher.DEFAULT_MAX_UNACKED_MESSAGES; i++) {
|
||||
if (i != 2) {
|
||||
acks.next(ackRequests.get(i));
|
||||
}
|
||||
}
|
||||
})
|
||||
.expectNext(expectedMessages.subList(MessageDispatcher.MAX_UNACKED_MESSAGES, totalMessages - 1).toArray(GetMessagesResponse[]::new))
|
||||
.expectNext(expectedMessages.subList(MessageDispatcher.DEFAULT_MAX_UNACKED_MESSAGES, totalMessages - 1).toArray(GetMessagesResponse[]::new))
|
||||
.expectNoEvent(Duration.ofMillis(1))
|
||||
.then(() -> acks.next(ackRequests.get(2)))
|
||||
.expectNext(expectedMessages.get(totalMessages - 1))
|
||||
.expectNoEvent(Duration.ofMillis(1))
|
||||
.then(() -> {
|
||||
for (int i = MessageDispatcher.MAX_UNACKED_MESSAGES; i < totalMessages; i++) {
|
||||
for (int i = MessageDispatcher.DEFAULT_MAX_UNACKED_MESSAGES; i < totalMessages; i++) {
|
||||
acks.next(ackRequests.get(i));
|
||||
}
|
||||
})
|
||||
@@ -233,7 +240,7 @@ class MessageDispatcherTest {
|
||||
void duplicateAckIgnored() {
|
||||
final AciServiceIdentifier sourceServiceId = new AciServiceIdentifier(UUID.randomUUID());
|
||||
final List<Envelope> messages = IntStream
|
||||
.range(0, MessageDispatcher.MAX_UNACKED_MESSAGES + 2)
|
||||
.range(0, MessageDispatcher.DEFAULT_MAX_UNACKED_MESSAGES + 2)
|
||||
.mapToObj(i -> createMessage(sourceServiceId, ACI, i, "hello"))
|
||||
.toList();
|
||||
|
||||
@@ -246,7 +253,7 @@ class MessageDispatcherTest {
|
||||
|
||||
StepVerifier
|
||||
.create(dispatcher.getMessages(true, TEST_UA, account, device, acks.flux()))
|
||||
.expectNextCount(MessageDispatcher.MAX_UNACKED_MESSAGES)
|
||||
.expectNextCount(MessageDispatcher.DEFAULT_MAX_UNACKED_MESSAGES)
|
||||
.expectNoEvent(Duration.ofMillis(1))
|
||||
|
||||
// Ack a message, we should then get a new message
|
||||
@@ -277,7 +284,7 @@ class MessageDispatcherTest {
|
||||
dispatcher.getMessages(true, TEST_UA, account, device, Flux.never());
|
||||
ArgumentCaptor<DisconnectionRequestListener> listener = ArgumentCaptor.forClass(DisconnectionRequestListener.class);
|
||||
StepVerifier.create(responses)
|
||||
.expectNext(GetMessagesResponse.newBuilder().setEnvelope(expectedEnvelope).build())
|
||||
.expectNext(GetMessagesResponse.newBuilder().setEnvelope(expectedEnvelope).setServerTimeEpochMillis(CLOCK.millis()).build())
|
||||
.then(() -> {
|
||||
verify(disconnectionRequestManager).addListener(eq(ACI), eq(DEVICE_ID), listener.capture());
|
||||
listener.getValue().handleDisconnectionRequest();
|
||||
@@ -309,7 +316,7 @@ class MessageDispatcherTest {
|
||||
void conflictingConsumerWhileWaitingForAcks() {
|
||||
final AciServiceIdentifier sourceServiceId = new AciServiceIdentifier(UUID.randomUUID());
|
||||
final List<MessageStreamEntry.Envelope> messages = IntStream
|
||||
.range(0, MessageDispatcher.MAX_UNACKED_MESSAGES + 2)
|
||||
.range(0, MessageDispatcher.DEFAULT_MAX_UNACKED_MESSAGES + 2)
|
||||
.mapToObj(i -> createMessage(sourceServiceId, ACI, i, "hello"))
|
||||
.map(MessageStreamEntry.Envelope::new)
|
||||
.toList();
|
||||
@@ -320,7 +327,7 @@ class MessageDispatcherTest {
|
||||
StepVerifier
|
||||
.create(dispatcher.getMessages(true, TEST_UA, account, device, Flux.never()))
|
||||
.then(() -> messages.forEach(source::next))
|
||||
.expectNextCount(MessageDispatcher.MAX_UNACKED_MESSAGES)
|
||||
.expectNextCount(MessageDispatcher.DEFAULT_MAX_UNACKED_MESSAGES)
|
||||
.expectNoEvent(Duration.ofMillis(1))
|
||||
// The error should make it to us immediately even though there are max-unacked messages outstanding
|
||||
.then(() -> source.error(new ConflictingMessageConsumerException()))
|
||||
|
||||
+1
-7
@@ -103,7 +103,7 @@ public class MetricServerInterceptorTest {
|
||||
void unary() {
|
||||
final EchoServiceGrpc.EchoServiceBlockingStub client = EchoServiceGrpc.newBlockingStub(channel);
|
||||
final EchoRequest request = EchoRequest.newBuilder().setPayload(ByteString.copyFromUtf8("hello")).build();
|
||||
final EchoResponse response = client.echo(request);
|
||||
client.echo(request);
|
||||
|
||||
final Tags commonTags = Tags.of(
|
||||
"platform", "android",
|
||||
@@ -119,9 +119,6 @@ public class MetricServerInterceptorTest {
|
||||
final Counter responseCount = find(Counter.class, MetricServerInterceptor.RESPONSE_COUNTER_NAME);
|
||||
assertThat(responseCount.count()).isCloseTo(1.0, offset(0.01));
|
||||
|
||||
final Counter responseByteCount = find(Counter.class, MetricServerInterceptor.RESPONSE_BYTES_COUNTER_NAME);
|
||||
assertThat(responseByteCount.count()).isCloseTo(response.getSerializedSize(), offset(0.01));
|
||||
|
||||
final Counter rpcCount = find(Counter.class, MetricServerInterceptor.RPC_COUNTER_NAME);
|
||||
assertThat(rpcCount.count()).isCloseTo(1.0, offset(0.01));
|
||||
|
||||
@@ -170,9 +167,6 @@ public class MetricServerInterceptorTest {
|
||||
final Counter responseCount = find(Counter.class, MetricServerInterceptor.RESPONSE_COUNTER_NAME);
|
||||
assertThat(responseCount.count()).isCloseTo(responses.size(), offset(0.01));
|
||||
|
||||
final Counter responseByteCount = find(Counter.class, MetricServerInterceptor.RESPONSE_BYTES_COUNTER_NAME);
|
||||
assertThat(responseByteCount.count()).isCloseTo(responses.stream().mapToInt(EchoResponse::getSerializedSize).sum(), offset(0.01));
|
||||
|
||||
final Counter rpcCount = find(Counter.class, MetricServerInterceptor.RPC_COUNTER_NAME);
|
||||
assertThat(rpcCount.count()).isCloseTo(1.0, offset(0.01));
|
||||
|
||||
|
||||
+149
@@ -0,0 +1,149 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.offset;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.google.common.net.InetAddresses;
|
||||
import com.google.protobuf.ByteString;
|
||||
import io.grpc.ManagedChannel;
|
||||
import io.grpc.Server;
|
||||
import io.grpc.netty.NettyChannelBuilder;
|
||||
import io.grpc.netty.NettyServerBuilder;
|
||||
import io.grpc.stub.BlockingClientCall;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.IntStream;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.signal.chat.rpc.EchoRequest;
|
||||
import org.signal.chat.rpc.EchoResponse;
|
||||
import org.signal.chat.rpc.EchoServiceGrpc;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicGrpcCompressionConfiguration;
|
||||
import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
|
||||
import org.whispersystems.textsecuregcm.tests.util.FakeDynamicConfigurationManager;
|
||||
|
||||
class MetricServerStreamTracerTest {
|
||||
|
||||
private static final String USER_AGENT = "Signal-Android/12.53.7 (Android 14.1; libsignal)";
|
||||
|
||||
private static final EchoRequest REQUEST = EchoRequest.newBuilder()
|
||||
.setPayload(ByteString.copyFromUtf8("compressible ".repeat(100)))
|
||||
.build();
|
||||
|
||||
private Server server;
|
||||
private ManagedChannel channel;
|
||||
private SimpleMeterRegistry simpleMeterRegistry;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
simpleMeterRegistry = new SimpleMeterRegistry();
|
||||
|
||||
final MockRequestAttributesInterceptor mockRequestAttributesInterceptor = new MockRequestAttributesInterceptor();
|
||||
mockRequestAttributesInterceptor.setRequestAttributes(
|
||||
new RequestAttributes(InetAddresses.forString("127.0.0.1"), USER_AGENT, null));
|
||||
|
||||
// Only compress echo
|
||||
final DynamicConfiguration configuration = mock(DynamicConfiguration.class);
|
||||
when(configuration.getGrpcCompression())
|
||||
.thenReturn(new DynamicGrpcCompressionConfiguration(Set.of(), Set.of("org.signal.chat.rpc.EchoService/echo")));
|
||||
|
||||
// By default, the in-process transport doesn't report message sizes to stream tracers at all, and it never
|
||||
// compresses messages; use a real transport instead
|
||||
server = NettyServerBuilder.forPort(0)
|
||||
.directExecutor()
|
||||
.addService(new EchoServiceImpl())
|
||||
.addStreamTracerFactory(new MetricServerStreamTracer.Factory())
|
||||
.intercept(new GrpcCompressionInterceptor(new FakeDynamicConfigurationManager<>(configuration)))
|
||||
.intercept(new MetricServerInterceptor(simpleMeterRegistry, mock(ClientReleaseManager.class)))
|
||||
.intercept(mockRequestAttributesInterceptor)
|
||||
.build()
|
||||
.start();
|
||||
|
||||
channel = NettyChannelBuilder.forAddress("localhost", server.getPort())
|
||||
.directExecutor()
|
||||
.usePlaintext()
|
||||
.build();
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() throws Exception {
|
||||
server.shutdownNow();
|
||||
channel.shutdownNow();
|
||||
server.awaitTermination(1, TimeUnit.SECONDS);
|
||||
channel.awaitTermination(1, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@Test
|
||||
void uncompressed() {
|
||||
final EchoResponse response = EchoServiceGrpc.newBlockingStub(channel).echo2(REQUEST);
|
||||
|
||||
final Counter wireBytes = find(MetricServerInterceptor.RESPONSE_BYTES_COUNTER_NAME, "echo2");
|
||||
assertThat(wireBytes.count()).isCloseTo(response.getSerializedSize(), offset(0.01));
|
||||
}
|
||||
|
||||
@Test
|
||||
void streaming() throws Exception {
|
||||
final EchoServiceGrpc.EchoServiceBlockingV2Stub client = EchoServiceGrpc.newBlockingV2Stub(channel);
|
||||
final BlockingClientCall<EchoRequest, EchoResponse> echoStream = client.echoStream();
|
||||
|
||||
final List<EchoRequest> requests = IntStream.range(0, 2)
|
||||
.mapToObj(i -> EchoRequest.newBuilder().setPayload(ByteString.copyFromUtf8(String.valueOf(i))).build())
|
||||
.toList();
|
||||
|
||||
final List<EchoResponse> responses = new ArrayList<>(requests.size());
|
||||
|
||||
for (final EchoRequest request : requests) {
|
||||
echoStream.write(request);
|
||||
responses.add(echoStream.read());
|
||||
}
|
||||
|
||||
echoStream.halfClose();
|
||||
|
||||
// Wait for the close to finish; metrics are reported after close
|
||||
channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
|
||||
|
||||
final int expectedBytes = responses.stream().mapToInt(EchoResponse::getSerializedSize).sum();
|
||||
|
||||
assertThat(find(MetricServerInterceptor.RESPONSE_BYTES_COUNTER_NAME, "echoStream").count())
|
||||
.isCloseTo(expectedBytes, offset(0.01));
|
||||
}
|
||||
|
||||
@Test
|
||||
void compressed() {
|
||||
final EchoResponse response = EchoServiceGrpc.newBlockingStub(channel).echo(REQUEST);
|
||||
|
||||
final Counter wireBytes = find(MetricServerInterceptor.RESPONSE_BYTES_COUNTER_NAME, "echo");
|
||||
|
||||
assertThat(wireBytes.count()).isPositive().isLessThan(response.getSerializedSize());
|
||||
|
||||
// we expect >90% compression
|
||||
assertThat(wireBytes.count() / response.getSerializedSize()).isLessThan(0.1);
|
||||
|
||||
final Tags expectedTags = Tags.of(
|
||||
"platform", "android",
|
||||
"grpcService", "org.signal.chat.rpc.EchoService",
|
||||
"method", "echo");
|
||||
|
||||
for (final Tag tag : expectedTags) {
|
||||
assertThat(wireBytes.getId().getTag(tag.getKey())).isEqualTo(tag.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
private Counter find(final String name, final String method) {
|
||||
return simpleMeterRegistry.find(name).tag("method", method).counter();
|
||||
}
|
||||
}
|
||||
+6
-7
@@ -98,7 +98,6 @@ import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
|
||||
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
|
||||
import org.whispersystems.textsecuregcm.storage.VersionedProfile;
|
||||
import org.whispersystems.textsecuregcm.storage.VersionedProfileV1;
|
||||
@@ -111,6 +110,8 @@ import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
|
||||
public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileAnonymousGrpcService, ProfileAnonymousGrpc.ProfileAnonymousBlockingStub> {
|
||||
|
||||
private static final String CDN_BASE_URL = "https://cdn.example.com";
|
||||
|
||||
private static final ServerSecretParams SERVER_SECRET_PARAMS = ServerSecretParams.generate();
|
||||
|
||||
@Mock
|
||||
@@ -152,6 +153,7 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
|
||||
profilesManager,
|
||||
profileBadgeConverter,
|
||||
new PostPolicyGenerator("us-west-1", "profile-bucket", "accessKey", "accessSecret"),
|
||||
CDN_BASE_URL,
|
||||
genericServerSecretParams,
|
||||
rateLimiters,
|
||||
clock,
|
||||
@@ -211,7 +213,7 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
|
||||
.setName(ByteString.copyFrom(name))
|
||||
.setAbout(ByteString.copyFrom(about))
|
||||
.setAboutEmoji(ByteString.copyFrom(emoji))
|
||||
.setAvatar(avatar)
|
||||
.setAvatarUrl(CDN_BASE_URL + "/" + avatar)
|
||||
.setPhoneNumberSharing(ByteString.copyFrom(phoneNumberSharing))
|
||||
.setAccountInfo(AccountInfo.newBuilder()
|
||||
.addAllBadgeIds(badgeIds)
|
||||
@@ -261,7 +263,6 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
|
||||
when(account.getCurrentProfileVersion()).thenReturn(Optional.of(version));
|
||||
when(account.isUnrestrictedUnidentifiedAccess()).thenReturn(true);
|
||||
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
|
||||
when(account.hasCapability(DeviceCapability.PROFILES_V2)).thenReturn(true);
|
||||
when(account.getAccountIdentityKey()).thenReturn(identityKey);
|
||||
when(account.getBadges()).thenReturn(Collections.emptyList());
|
||||
|
||||
@@ -317,7 +318,6 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
|
||||
when(account.getCurrentProfileVersion()).thenReturn(Optional.of(version));
|
||||
when(account.isUnrestrictedUnidentifiedAccess()).thenReturn(true);
|
||||
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
|
||||
when(account.hasCapability(DeviceCapability.PROFILES_V2)).thenReturn(true);
|
||||
when(account.getAccountIdentityKey()).thenReturn(identityKey);
|
||||
when(account.getBadges()).thenReturn(Collections.emptyList());
|
||||
|
||||
@@ -515,7 +515,6 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
|
||||
final ProfileKeyCredentialRequestContext profileKeyCredentialRequestContext =
|
||||
clientZkProfile.createProfileKeyCredentialRequestContext(new ServiceId.Aci(targetUuid), profileKey);
|
||||
|
||||
when(account.hasCapability(DeviceCapability.PROFILES_V2)).thenReturn(hasV2Capability);
|
||||
if (hasV2Capability) {
|
||||
final VersionedProfile profile = mock(VersionedProfile.class);
|
||||
when(profile.commitment()).thenReturn(profileKeyCommitment.serialize());
|
||||
@@ -790,9 +789,9 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
|
||||
|
||||
final ExtendAvatarTTLResponse response = authenticatedServiceStub().extendAvatarTTL(request);
|
||||
|
||||
assertTrue(response.hasPath());
|
||||
assertTrue(response.hasUrl());
|
||||
|
||||
assertEquals(path, response.getPath());
|
||||
assertEquals(CDN_BASE_URL + "/" + path, response.getUrl());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+15
-2
@@ -15,9 +15,8 @@ import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.signal.chat.common.DeviceCapability;
|
||||
import org.signal.chat.profile.ProfileResult;
|
||||
import org.signal.chat.profile.AccountInfo;
|
||||
import org.signal.chat.profile.ProfileResult;
|
||||
|
||||
class ProfileGrpcHelperTest {
|
||||
|
||||
@@ -86,6 +85,20 @@ class ProfileGrpcHelperTest {
|
||||
assertArrayEquals(unset, explicitlyEmpty);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void cdnUrl(final String baseUrl, final String path) {
|
||||
assertEquals("https://cdn.example.com/profiles/abc", ProfileGrpcHelper.cdnUrl(baseUrl, path));
|
||||
}
|
||||
|
||||
private static Stream<Arguments> cdnUrl() {
|
||||
return Stream.of(
|
||||
Arguments.of("https://cdn.example.com", "profiles/abc"),
|
||||
Arguments.of("https://cdn.example.com/", "profiles/abc"),
|
||||
Arguments.of("https://cdn.example.com", "/profiles/abc"),
|
||||
Arguments.of("https://cdn.example.com/", "/profiles/abc"));
|
||||
}
|
||||
|
||||
private static ProfileResult.Builder profile() {
|
||||
return ProfileResult.newBuilder()
|
||||
.setData(ByteString.copyFromUtf8("profile-data"))
|
||||
|
||||
+4
-5
@@ -103,7 +103,6 @@ import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountBadge;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
|
||||
import org.whispersystems.textsecuregcm.storage.VersionedProfile;
|
||||
@@ -118,6 +117,8 @@ import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
|
||||
public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcService, ProfileGrpc.ProfileBlockingStub> {
|
||||
|
||||
private static final String CDN_BASE_URL = "https://cdn.example.com";
|
||||
|
||||
private static final byte[] VERSION = TestRandomUtil.nextBytes(32);
|
||||
|
||||
private static final byte[] VALID_DATA = new byte[128];
|
||||
@@ -192,7 +193,6 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
|
||||
when(account.getAccountIdentifier()).thenReturn(AUTHENTICATED_ACI);
|
||||
when(account.getNumber()).thenReturn(Optional.of(phoneNumber));
|
||||
when(account.getBadges()).thenReturn(Collections.emptyList());
|
||||
when(account.hasCapability(DeviceCapability.PROFILES_V2)).thenReturn(true);
|
||||
|
||||
when(profile.paymentAddress()).thenReturn(null);
|
||||
when(profile.avatar()).thenReturn("");
|
||||
@@ -215,6 +215,7 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
|
||||
dynamicConfigurationManager,
|
||||
badgesConfiguration,
|
||||
policyGenerator,
|
||||
CDN_BASE_URL,
|
||||
genericServerSecretParams,
|
||||
profileBadgeConverter,
|
||||
rateLimiters
|
||||
@@ -653,7 +654,7 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
|
||||
.setName(ByteString.copyFrom(name))
|
||||
.setAbout(ByteString.copyFrom(about))
|
||||
.setAboutEmoji(ByteString.copyFrom(emoji))
|
||||
.setAvatar(avatar)
|
||||
.setAvatarUrl(CDN_BASE_URL + "/" + avatar)
|
||||
.setPhoneNumberSharing(ByteString.copyFrom(phoneNumberSharing))
|
||||
.setAccountInfo(AccountInfo.newBuilder()
|
||||
.addAllBadgeIds(badgeIds)
|
||||
@@ -695,7 +696,6 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
|
||||
|
||||
when(account.getAccountIdentifier()).thenReturn(targetAci);
|
||||
when(account.getCurrentProfileVersion()).thenReturn(Optional.of(version));
|
||||
when(account.hasCapability(DeviceCapability.PROFILES_V2)).thenReturn(true);
|
||||
when(account.getAccountIdentityKey()).thenReturn(identityKey);
|
||||
when(account.isUnrestrictedUnidentifiedAccess()).thenReturn(true);
|
||||
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
|
||||
@@ -747,7 +747,6 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
|
||||
|
||||
final UUID targetAci = UUID.randomUUID();
|
||||
when(account.getAccountIdentifier()).thenReturn(targetAci);
|
||||
when(account.hasCapability(DeviceCapability.PROFILES_V2)).thenReturn(true);
|
||||
when(accountsManager.getByServiceIdentifier(new AciServiceIdentifier(targetAci))).thenReturn(Optional.of(account));
|
||||
|
||||
when(account.getAccountIdentityKey()).thenReturn(identityKey);
|
||||
|
||||
-29
@@ -1,29 +0,0 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.grpc.net;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.util.Optional;
|
||||
import javax.annotation.Nullable;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
|
||||
class BoringSslServerKeyManagerTest {
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource(nullValues = "null", value = {
|
||||
"Ed25519, EdDSA",
|
||||
"SHA256withECDSA, EC",
|
||||
"SHA512withECDSA, EC",
|
||||
"SHA256withRSA, RSA",
|
||||
"SHA512withRSA, RSA",
|
||||
"SHA256withRSA_PSS_PSS, null",
|
||||
"Ed448, null",
|
||||
})
|
||||
void getJdkKeyType(final String signatureAlgorithm, @Nullable final String expectedKeyType) {
|
||||
assertEquals(Optional.ofNullable(expectedKeyType), BoringSslServerKeyManager.getJdkKeyType(signatureAlgorithm));
|
||||
}
|
||||
}
|
||||
+321
-156
@@ -4,6 +4,7 @@ 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.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import io.dropwizard.util.DataSize;
|
||||
@@ -16,12 +17,13 @@ import io.netty.channel.ChannelFutureListener;
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.channel.ChannelInboundHandlerAdapter;
|
||||
import io.netty.channel.ChannelInitializer;
|
||||
import io.netty.channel.DefaultEventLoopGroup;
|
||||
import io.netty.channel.EventLoopGroup;
|
||||
import io.netty.channel.MultiThreadIoEventLoopGroup;
|
||||
import io.netty.channel.SimpleUserEventChannelHandler;
|
||||
import io.netty.channel.local.LocalAddress;
|
||||
import io.netty.channel.local.LocalIoHandler;
|
||||
import io.netty.channel.local.LocalServerChannel;
|
||||
import io.netty.channel.nio.NioEventLoopGroup;
|
||||
import io.netty.channel.nio.NioIoHandler;
|
||||
import io.netty.channel.socket.SocketChannel;
|
||||
import io.netty.channel.socket.nio.NioChannelOption;
|
||||
import io.netty.channel.socket.nio.NioServerSocketChannel;
|
||||
@@ -36,6 +38,8 @@ import io.netty.handler.codec.http2.DefaultHttp2GoAwayFrame;
|
||||
import io.netty.handler.codec.http2.DefaultHttp2Headers;
|
||||
import io.netty.handler.codec.http2.DefaultHttp2HeadersFrame;
|
||||
import io.netty.handler.codec.http2.DefaultHttp2ResetFrame;
|
||||
import io.netty.handler.codec.http2.DefaultHttp2WindowUpdateFrame;
|
||||
import io.netty.handler.codec.http2.Http2CodecUtil;
|
||||
import io.netty.handler.codec.http2.Http2DataFrame;
|
||||
import io.netty.handler.codec.http2.Http2Error;
|
||||
import io.netty.handler.codec.http2.Http2FrameCodecBuilder;
|
||||
@@ -66,7 +70,7 @@ import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
@@ -112,8 +116,10 @@ class OmnibusH2ServerTest {
|
||||
/// filled with the byte `b`
|
||||
private static final String FIXED_RESPONSE_PATH_PREFIX = "/fixed-response/";
|
||||
|
||||
private static NioEventLoopGroup nioEventLoopGroup;
|
||||
private static DefaultEventLoopGroup localEventLoopGroup;
|
||||
private static final String TEST_DOMAIN = "foo.example.com";
|
||||
|
||||
private static EventLoopGroup nioEventLoopGroup;
|
||||
private static EventLoopGroup localEventLoopGroup;
|
||||
|
||||
private static Mapping<String, SslContext> sniMapping;
|
||||
|
||||
@@ -127,7 +133,7 @@ class OmnibusH2ServerTest {
|
||||
final Instant now = Instant.now();
|
||||
|
||||
final char[] keyStorePassword = RandomStringUtils.insecure().nextAlphanumeric(16).toCharArray();
|
||||
final String domain = "foo.example.com";
|
||||
final String domain = TEST_DOMAIN;
|
||||
|
||||
final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
|
||||
|
||||
@@ -145,8 +151,8 @@ class OmnibusH2ServerTest {
|
||||
sniMapping = SniMapper.buildSniMapping(new ByteArrayInputStream(byteArrayOutputStream.toByteArray()),
|
||||
new String(keyStorePassword), SslProvider.OPENSSL);
|
||||
|
||||
nioEventLoopGroup = new NioEventLoopGroup();
|
||||
localEventLoopGroup = new DefaultEventLoopGroup();
|
||||
nioEventLoopGroup = new MultiThreadIoEventLoopGroup(NioIoHandler.newFactory());
|
||||
localEventLoopGroup = new MultiThreadIoEventLoopGroup(LocalIoHandler.newFactory());
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
@@ -168,14 +174,20 @@ class OmnibusH2ServerTest {
|
||||
static void tearDownAfterAll() throws InterruptedException {
|
||||
localEventLoopGroup.shutdownGracefully(1, 1000, TimeUnit.MILLISECONDS).sync();
|
||||
nioEventLoopGroup.shutdownGracefully(1, 1000, TimeUnit.MILLISECONDS).sync();
|
||||
|
||||
ReferenceCountUtil.release(sniMapping.map(TEST_DOMAIN));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void defaultBackend(final boolean localChannel) throws Exception {
|
||||
final OmnibusH2Server server = startOmnibusServer(
|
||||
Map.of(PATH, startBackendServer(localChannel, PATH_BACKEND_IDENTITY)),
|
||||
startBackendServer(localChannel, DEFAULT_BACKEND_IDENTITY));
|
||||
@CartesianTest
|
||||
void defaultBackend(
|
||||
@CartesianTest.Values(booleans = {false, true}) final boolean localChannel,
|
||||
@CartesianTest.Values(booleans = {false, true}) final boolean pooled)
|
||||
throws Exception {
|
||||
final OmnibusH2Server server = omnibusServer()
|
||||
.addRoute(PATH, backendServer().localChannel(localChannel).identity(PATH_BACKEND_IDENTITY))
|
||||
.pooled(pooled)
|
||||
.addDefault(backendServer().localChannel(localChannel))
|
||||
.start();
|
||||
final String response = sendRequestThroughOmnibus(connectToOmnibus(server), "/a/different/path");
|
||||
assertEquals(DEFAULT_BACKEND_IDENTITY, response);
|
||||
}
|
||||
@@ -187,7 +199,7 @@ class OmnibusH2ServerTest {
|
||||
final HAProxyMessage proxyMessage = usePpv2
|
||||
? new HAProxyMessage(HAProxyProtocolVersion.V2, HAProxyCommand.PROXY, HAProxyProxiedProtocol.TCP4, expectedSource, "127.0.0.2", 1234, 5678)
|
||||
: null;
|
||||
final OmnibusH2Server server = startOmnibusServer(startBackendServer(true, DEFAULT_BACKEND_IDENTITY));
|
||||
final OmnibusH2Server server = omnibusServer().start();
|
||||
final Channel h2Connection = connectToOmnibus(server, proxyMessage);
|
||||
final String xForwardedFor = sendRequestThroughOmnibus(h2Connection, "/forwarded-for");
|
||||
assertEquals(expectedSource, xForwardedFor);
|
||||
@@ -196,10 +208,12 @@ class OmnibusH2ServerTest {
|
||||
@CartesianTest
|
||||
void pathBackend(
|
||||
@CartesianTest.Values(booleans = {false, true}) final boolean localChannel,
|
||||
@CartesianTest.Values(booleans = {false, true}) final boolean pooled,
|
||||
@CartesianTest.Values(strings = {"/v1/path/", "/v1/path/?foo=bar", "/v1/path/?foo=bar&baz=quux"}) final String path) throws Exception {
|
||||
final OmnibusH2Server server = startOmnibusServer(
|
||||
Map.of(PATH, startBackendServer(localChannel, PATH_BACKEND_IDENTITY)),
|
||||
startBackendServer(true, DEFAULT_BACKEND_IDENTITY));
|
||||
final OmnibusH2Server server = omnibusServer()
|
||||
.addRoute(PATH, backendServer().localChannel(localChannel).identity(PATH_BACKEND_IDENTITY))
|
||||
.pooled(pooled)
|
||||
.start();
|
||||
final String response = sendRequestThroughOmnibus(connectToOmnibus(server), path);
|
||||
assertEquals(PATH_BACKEND_IDENTITY, response);
|
||||
}
|
||||
@@ -208,9 +222,10 @@ class OmnibusH2ServerTest {
|
||||
void multipleStreamsOnSameConnection(
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean defaultLocalChannel,
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean prefixLocalChannel) throws Exception {
|
||||
final OmnibusH2Server server = startOmnibusServer(
|
||||
Map.of(PATH, startBackendServer(prefixLocalChannel, PATH_BACKEND_IDENTITY)),
|
||||
startBackendServer(defaultLocalChannel, DEFAULT_BACKEND_IDENTITY));
|
||||
final OmnibusH2Server server = omnibusServer()
|
||||
.addRoute(PATH, backendServer().localChannel(prefixLocalChannel).identity(PATH_BACKEND_IDENTITY))
|
||||
.addDefault(backendServer().localChannel(defaultLocalChannel))
|
||||
.start();
|
||||
final Channel h2Connection = connectToOmnibus(server);
|
||||
final int numStreams = 10;
|
||||
|
||||
@@ -232,14 +247,15 @@ class OmnibusH2ServerTest {
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void backendDownStreamReset(final boolean localChannel) throws Exception {
|
||||
final Channel backend = startBackendServer(localChannel, DEFAULT_BACKEND_IDENTITY);
|
||||
final OmnibusH2Server server = startOmnibusServer(backend);
|
||||
@CartesianTest
|
||||
void backendDownStreamReset(
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean localChannel,
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean pooled) throws Exception {
|
||||
final BackendServerBuilder backend = backendServer().localChannel(localChannel);
|
||||
final OmnibusH2Server server = omnibusServer().addDefault(backend).pooled(pooled).start();
|
||||
|
||||
// Kill the default backend so connection attempts from the omnibus fail
|
||||
backend.close().syncUninterruptibly();
|
||||
backend.channel().close().syncUninterruptibly();
|
||||
|
||||
final Channel h2Connection = connectToOmnibus(server);
|
||||
final CompletableFuture<Http2HeadersFrame> headersFuture = new CompletableFuture<>();
|
||||
@@ -270,8 +286,12 @@ class OmnibusH2ServerTest {
|
||||
@CartesianTest
|
||||
void backendCloseClosesClientStream(
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean localChannel,
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean pooled,
|
||||
@CartesianTest.Values(strings = {"/goaway", "/reset"}) final String path) throws Exception {
|
||||
final OmnibusH2Server server = startOmnibusServer(startBackendServer(localChannel, DEFAULT_BACKEND_IDENTITY));
|
||||
final OmnibusH2Server server = omnibusServer()
|
||||
.addDefault(backendServer().localChannel(localChannel))
|
||||
.pooled(pooled)
|
||||
.start();
|
||||
final Channel h2Connection = connectToOmnibus(server);
|
||||
|
||||
final CompletableFuture<Http2ResetFrame> resetFuture = new CompletableFuture<>();
|
||||
@@ -294,10 +314,14 @@ class OmnibusH2ServerTest {
|
||||
assertTrue(h2Connection.isActive());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void queuedDataFrames(final boolean localChannel) throws Exception {
|
||||
final OmnibusH2Server server = startOmnibusServer(startBackendServer(localChannel, DEFAULT_BACKEND_IDENTITY));
|
||||
@CartesianTest
|
||||
void queuedDataFrames(
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean localChannel,
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean pooled) throws Exception {
|
||||
final OmnibusH2Server server = omnibusServer()
|
||||
.addDefault(backendServer().localChannel(localChannel))
|
||||
.pooled(pooled)
|
||||
.start();
|
||||
final Channel h2Connection = connectToOmnibus(server);
|
||||
final CompletableFuture<byte[]> responseFuture = new CompletableFuture<>();
|
||||
final Http2StreamChannel stream = new Http2StreamChannelBootstrap(h2Connection)
|
||||
@@ -333,12 +357,19 @@ class OmnibusH2ServerTest {
|
||||
h2Connection.close().syncUninterruptibly();
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void clientDisconnectClosesBackendConnections(final boolean localChannel) throws Exception {
|
||||
@CartesianTest
|
||||
void clientDisconnectClosesBackendStreams(
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean localChannel,
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean pooled) throws Exception {
|
||||
final CompletableFuture<Channel> backendH2Connection = new CompletableFuture<>();
|
||||
final Channel backendServerChannel = startBackendServer(localChannel, DEFAULT_BACKEND_IDENTITY, backendH2Connection::complete, _ -> {});
|
||||
final OmnibusH2Server server = startOmnibusServer(backendServerChannel);
|
||||
final CompletableFuture<Channel> backendH2Stream = new CompletableFuture<>();
|
||||
final OmnibusH2Server server = omnibusServer()
|
||||
.addDefault(backendServer()
|
||||
.localChannel(localChannel)
|
||||
.h2ChannelInit(backendH2Connection::complete)
|
||||
.h2StreamInit(backendH2Stream::complete))
|
||||
.pooled(pooled)
|
||||
.start();
|
||||
final Channel h2Connection = connectToOmnibus(server);
|
||||
|
||||
final Http2StreamChannelBootstrap streamBootstrap = new Http2StreamChannelBootstrap(h2Connection);
|
||||
@@ -356,25 +387,31 @@ class OmnibusH2ServerTest {
|
||||
.authority("localhost");
|
||||
stream.writeAndFlush(new DefaultHttp2HeadersFrame(headers, false)).syncUninterruptibly();
|
||||
|
||||
assertFalse(
|
||||
backendH2Connection.join().closeFuture().awaitUninterruptibly(10, TimeUnit.MILLISECONDS),
|
||||
"Channel should be open");
|
||||
final Channel backendStream = backendH2Stream.get(5, TimeUnit.SECONDS);
|
||||
assertFalse(backendStream.closeFuture().awaitUninterruptibly(10, TimeUnit.MILLISECONDS), "Stream should be open");
|
||||
|
||||
// All backend connections the omnibus opened on behalf of this client should close if we disconnect the client
|
||||
// All backend streams the omnibus opened on behalf of this client should close if we disconnect the client
|
||||
h2Connection.close().syncUninterruptibly();
|
||||
assertTrue(backendH2Connection.join().closeFuture().await(5, TimeUnit.SECONDS));
|
||||
assertTrue(backendStream.closeFuture().await(5, TimeUnit.SECONDS));
|
||||
|
||||
// Pooled connections are shared with other clients, so only unpooled connections should close
|
||||
assertEquals(!pooled, backendH2Connection.join().closeFuture().await(pooled ? 100 : 5000, TimeUnit.MILLISECONDS));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void requestBackpressure(final boolean localChannel) throws Exception {
|
||||
@CartesianTest
|
||||
void requestBackpressure(@CartesianTest.Values(booleans = {true, false}) final boolean localChannel,
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean pooled) throws Exception {
|
||||
final AtomicReference<Channel> backendStreamChannel = new AtomicReference<>();
|
||||
final Channel backendServer = startBackendServer(localChannel, "request-backpressure", _ -> {
|
||||
}, ch -> {
|
||||
ch.config().setAutoRead(false);
|
||||
backendStreamChannel.set(ch);
|
||||
});
|
||||
final OmnibusH2Server omnibusH2Server = startOmnibusServer(backendServer);
|
||||
final OmnibusH2Server omnibusH2Server = omnibusServer()
|
||||
.addDefault(backendServer()
|
||||
.localChannel(localChannel)
|
||||
.identity("request-backpressure")
|
||||
.h2StreamInit(ch -> {
|
||||
ch.config().setAutoRead(false);
|
||||
backendStreamChannel.set(ch);
|
||||
}))
|
||||
.pooled(pooled)
|
||||
.start();
|
||||
final Channel h2Connection = connectToOmnibus(omnibusH2Server, null);
|
||||
|
||||
// We'll take the client channel becoming unwritable as backpressure signal
|
||||
@@ -441,6 +478,7 @@ class OmnibusH2ServerTest {
|
||||
|
||||
@CartesianTest
|
||||
void responseBackpressure(@CartesianTest.Values(booleans = {true, false}) final boolean localChannel,
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean pooled,
|
||||
@CartesianTest.Values(ints = {193, 512, 2048}) final int responseSizeKib) throws Exception {
|
||||
|
||||
final int responseSize = Math.toIntExact(DataSize.kibibytes(responseSizeKib).toBytes());
|
||||
@@ -453,21 +491,26 @@ class OmnibusH2ServerTest {
|
||||
final CountDownLatch backendStreamUnwritable = new CountDownLatch(1);
|
||||
final AtomicLong pendingWhenUnwritable = new AtomicLong();
|
||||
|
||||
final OmnibusH2Server server = startOmnibusServer(startBackendServer(localChannel, "response-backpressure",
|
||||
_ -> {}, ch -> {
|
||||
ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
|
||||
@Override
|
||||
public void channelWritabilityChanged(final ChannelHandlerContext backendStreamCtx) {
|
||||
if (!backendStreamCtx.channel().isWritable() && backendStreamUnwritable.getCount() > 0) {
|
||||
// A change in writability on the backend stream means we introduced backpressure
|
||||
pendingWhenUnwritable.set(backendStreamCtx.channel().bytesBeforeWritable());
|
||||
backendStreamUnwritable.countDown();
|
||||
}
|
||||
backendStreamCtx.fireChannelWritabilityChanged();
|
||||
}
|
||||
});
|
||||
backendStreamInitialized.countDown();
|
||||
}));
|
||||
final OmnibusH2Server server = omnibusServer()
|
||||
.addDefault(backendServer()
|
||||
.localChannel(localChannel)
|
||||
.identity("response-backpressure")
|
||||
.h2StreamInit(ch -> {
|
||||
ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
|
||||
@Override
|
||||
public void channelWritabilityChanged(final ChannelHandlerContext backendStreamCtx) {
|
||||
if (!backendStreamCtx.channel().isWritable() && backendStreamUnwritable.getCount() > 0) {
|
||||
// A change in writability on the backend stream means we introduced backpressure
|
||||
pendingWhenUnwritable.set(backendStreamCtx.channel().bytesBeforeWritable());
|
||||
backendStreamUnwritable.countDown();
|
||||
}
|
||||
backendStreamCtx.fireChannelWritabilityChanged();
|
||||
}
|
||||
});
|
||||
backendStreamInitialized.countDown();
|
||||
}))
|
||||
.pooled(pooled)
|
||||
.start();
|
||||
final Channel h2Connection = connectToOmnibus(server);
|
||||
|
||||
final AtomicReference<Http2StreamChannel> clientStream = new AtomicReference<>();
|
||||
@@ -495,12 +538,57 @@ class OmnibusH2ServerTest {
|
||||
h2Connection.close().syncUninterruptibly();
|
||||
}
|
||||
|
||||
@Test
|
||||
void pausedStreamDoesNotStallPooledConnection() throws Exception {
|
||||
final CountDownLatch backendStreamUnwritable = new CountDownLatch(1);
|
||||
final OmnibusH2Server server = omnibusServer()
|
||||
.addDefault(backendServer()
|
||||
.h2StreamInit(ch -> ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
|
||||
@Override
|
||||
public void channelWritabilityChanged(final ChannelHandlerContext ctx) {
|
||||
if (!ctx.channel().isWritable()) {
|
||||
backendStreamUnwritable.countDown();
|
||||
}
|
||||
ctx.fireChannelWritabilityChanged();
|
||||
}
|
||||
})))
|
||||
.pooled(true)
|
||||
.start();
|
||||
final Channel h2Connection = connectToOmnibus(server);
|
||||
|
||||
// Open our own connection-level window, so the paused stream doesn't stall our connection to the omnibus
|
||||
h2Connection.writeAndFlush(
|
||||
new DefaultHttp2WindowUpdateFrame(Integer.MAX_VALUE - Http2CodecUtil.DEFAULT_WINDOW_SIZE)).syncUninterruptibly();
|
||||
|
||||
// Force one of the streams to go unwritable
|
||||
final AtomicReference<Channel> pausedStream = new AtomicReference<>();
|
||||
final int pausedResponseSize = Math.toIntExact(DataSize.mebibytes(1).toBytes());
|
||||
final CompletableFuture<byte[]> pausedResponse = request(h2Connection, pausedResponseSize, (byte) 1, ch -> {
|
||||
ch.config().setAutoRead(false);
|
||||
pausedStream.set(ch);
|
||||
});
|
||||
assertTrue(backendStreamUnwritable.await(5, TimeUnit.SECONDS), "failed to introduce backpressure");
|
||||
|
||||
// A different stream should not be affected
|
||||
final int responseSize = Math.toIntExact(DataSize.kibibytes(1).toBytes());
|
||||
assertArrayEquals(expectedBody(responseSize, (byte) 2),
|
||||
request(h2Connection, responseSize, (byte) 2, _ -> {}).get(5, TimeUnit.SECONDS));
|
||||
assertFalse(pausedResponse.isDone());
|
||||
|
||||
pausedStream.get().eventLoop().execute(() -> pausedStream.get().config().setAutoRead(true));
|
||||
assertArrayEquals(expectedBody(pausedResponseSize, (byte) 1), pausedResponse.get(5, TimeUnit.SECONDS));
|
||||
|
||||
h2Connection.close().syncUninterruptibly();
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void idleTest(final boolean localChannel) throws Exception {
|
||||
final Duration timeout = Duration.ofMillis(500);
|
||||
final OmnibusH2Server timeoutServer =
|
||||
startOmnibusServer(Collections.emptyMap(), startBackendServer(localChannel, DEFAULT_BACKEND_IDENTITY), timeout);
|
||||
final OmnibusH2Server timeoutServer = omnibusServer()
|
||||
.addDefault(backendServer().localChannel(localChannel))
|
||||
.idleTimeout(timeout)
|
||||
.start();
|
||||
final Channel channel = connectToOmnibus(timeoutServer, null);
|
||||
|
||||
// Send a request to make sure idleTimeouts work even after a stream / backend connection has been established
|
||||
@@ -515,9 +603,9 @@ class OmnibusH2ServerTest {
|
||||
@Test
|
||||
void loadShed() throws Exception {
|
||||
dynamicConfiguration.set(new DynamicOmnibusConfiguration(BigDecimal.ONE));
|
||||
final OmnibusH2Server server = startOmnibusServer(
|
||||
Map.of(PATH, startBackendServer(true, PATH_BACKEND_IDENTITY)),
|
||||
startBackendServer(true, DEFAULT_BACKEND_IDENTITY));
|
||||
final OmnibusH2Server server = omnibusServer()
|
||||
.addRoute(PATH, backendServer().identity(PATH_BACKEND_IDENTITY))
|
||||
.start();
|
||||
|
||||
final CompletableFuture<Http2GoAwayFrame> goAwayFuture = new CompletableFuture<>();
|
||||
final Bootstrap clientBootstrap = new Bootstrap()
|
||||
@@ -566,8 +654,8 @@ class OmnibusH2ServerTest {
|
||||
@CartesianTest.Values(ints = {10}) final int repetitions) throws Exception {
|
||||
|
||||
// Use two threads to make sure that our connections are working concurrently
|
||||
final NioEventLoopGroup nioEventLoopGroup = new NioEventLoopGroup(2);
|
||||
final DefaultEventLoopGroup localEventLoopGroup = new DefaultEventLoopGroup(2);
|
||||
final EventLoopGroup nioEventLoopGroup = new MultiThreadIoEventLoopGroup(2, NioIoHandler.newFactory());
|
||||
final EventLoopGroup localEventLoopGroup = new MultiThreadIoEventLoopGroup(2, LocalIoHandler.newFactory());
|
||||
|
||||
groupsToShutDown.add(nioEventLoopGroup);
|
||||
groupsToShutDown.add(localEventLoopGroup);
|
||||
@@ -577,11 +665,11 @@ class OmnibusH2ServerTest {
|
||||
try {
|
||||
final int responseSize = Math.toIntExact(DataSize.kibibytes(responseSizeKib).toBytes());
|
||||
|
||||
final OmnibusH2Server server = startOmnibusServer(nioEventLoopGroup, localEventLoopGroup,
|
||||
Collections.emptyMap(),
|
||||
startBackendServer(localChannel ? localEventLoopGroup : nioEventLoopGroup, localChannel,
|
||||
DEFAULT_BACKEND_IDENTITY, _ -> {}, _ -> {}),
|
||||
Duration.ofMinutes(1));
|
||||
final OmnibusH2Server server = omnibusServer()
|
||||
.eventLoopGroups(nioEventLoopGroup, localEventLoopGroup)
|
||||
.addDefault(backendServer().localChannel(localChannel))
|
||||
.pooled(false)
|
||||
.start();
|
||||
|
||||
for (int i = 0; i < connections; i++) {
|
||||
clientConnections.add(connectToOmnibus(server));
|
||||
@@ -646,90 +734,155 @@ class OmnibusH2ServerTest {
|
||||
return body;
|
||||
}
|
||||
|
||||
/// Start an OmnibusH2Server. The returned server and provided backends will be torn down in [#tearDown()]
|
||||
///
|
||||
/// @param routes A map of prefixes and the corresponding backend server channels the omnibus will target
|
||||
/// @param defaultBackend The target backend if no prefix routes match the request path
|
||||
/// @param timeout The omnibus idle timeout
|
||||
private OmnibusH2Server startOmnibusServer(final Map<String, Channel> routes, final Channel defaultBackend, final Duration timeout) throws Exception {
|
||||
return startOmnibusServer(nioEventLoopGroup, localEventLoopGroup, routes, defaultBackend, timeout);
|
||||
/// A builder for an OmnibusH2Server. The started server and its backends will be torn down in [#tearDown()]
|
||||
private OmnibusServerBuilder omnibusServer() {
|
||||
return new OmnibusServerBuilder();
|
||||
}
|
||||
|
||||
private OmnibusH2Server startOmnibusServer(
|
||||
final NioEventLoopGroup nioEventLoopGroup,
|
||||
final DefaultEventLoopGroup localEventLoopGroup,
|
||||
final Map<String, Channel> routes,
|
||||
final Channel defaultBackend,
|
||||
final Duration timeout) throws Exception {
|
||||
backendChannelsToShutDown.addAll(routes.values());
|
||||
backendChannelsToShutDown.add(defaultBackend);
|
||||
private class OmnibusServerBuilder {
|
||||
|
||||
final OmnibusH2Server server = new OmnibusH2Server(
|
||||
sniMapping,
|
||||
nioEventLoopGroup,
|
||||
localEventLoopGroup,
|
||||
new InetSocketAddress("127.0.0.1", 0),
|
||||
new OmnibusRouter(routes.entrySet().stream().collect(Collectors.toMap(
|
||||
Map.Entry::getKey,
|
||||
e -> e.getValue().localAddress())),
|
||||
defaultBackend.localAddress()),
|
||||
dynamicConfiguration::get,
|
||||
timeout);
|
||||
server.start();
|
||||
omnibusH2ServersToShutDown.add(server);
|
||||
return server;
|
||||
private final Map<String, BackendServerBuilder> routes = new HashMap<>();
|
||||
private BackendServerBuilder defaultBackend = backendServer();
|
||||
private Duration idleTimeout = Duration.ofMinutes(1);
|
||||
private boolean pooled = true;
|
||||
private EventLoopGroup nioEventLoopGroup = OmnibusH2ServerTest.nioEventLoopGroup;
|
||||
private EventLoopGroup localEventLoopGroup = OmnibusH2ServerTest.localEventLoopGroup;
|
||||
|
||||
/// Requests with paths starting with `prefix` will go to `backend`
|
||||
OmnibusServerBuilder addRoute(final String prefix, final BackendServerBuilder backend) {
|
||||
routes.put(prefix, backend);
|
||||
return this;
|
||||
}
|
||||
|
||||
/// Requests that don't match any route will go to `backend`. Defaults to [#backendServer()].
|
||||
OmnibusServerBuilder addDefault(final BackendServerBuilder backend) {
|
||||
this.defaultBackend = backend;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// Defaults to 1 minute
|
||||
OmnibusServerBuilder idleTimeout(final Duration idleTimeout) {
|
||||
this.idleTimeout = idleTimeout;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// Whether to connect to backends via pooled h2 connections. Defaults to true.
|
||||
OmnibusServerBuilder pooled(final boolean pooled) {
|
||||
this.pooled = pooled;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// The event loop groups used by the omnibus and its backends. Defaults to the shared event loop groups.
|
||||
OmnibusServerBuilder eventLoopGroups(final EventLoopGroup nioEventLoopGroup,
|
||||
final EventLoopGroup localEventLoopGroup) {
|
||||
this.nioEventLoopGroup = nioEventLoopGroup;
|
||||
this.localEventLoopGroup = localEventLoopGroup;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// Start the backends and then the omnibus
|
||||
OmnibusH2Server start() throws Exception {
|
||||
final OmnibusRouter router = new OmnibusRouter(routes.entrySet().stream().collect(Collectors.toMap(
|
||||
Map.Entry::getKey,
|
||||
e -> startBackend(e.getValue()))),
|
||||
startBackend(defaultBackend));
|
||||
|
||||
final OmnibusH2Server server = new OmnibusH2Server(
|
||||
sniMapping,
|
||||
nioEventLoopGroup,
|
||||
new InetSocketAddress("127.0.0.1", 0),
|
||||
router,
|
||||
dynamicConfiguration::get,
|
||||
idleTimeout);
|
||||
server.start();
|
||||
omnibusH2ServersToShutDown.add(server);
|
||||
return server;
|
||||
}
|
||||
|
||||
private H2ConnectionFactory startBackend(final BackendServerBuilder backend) {
|
||||
final EventLoopGroup eventLoopGroup = backend.localChannel ? localEventLoopGroup : nioEventLoopGroup;
|
||||
final Channel channel = backend.start(eventLoopGroup);
|
||||
backendChannelsToShutDown.add(channel);
|
||||
return pooled
|
||||
? new PooledH2ConnectionFactory(channel.localAddress(), eventLoopGroup, Duration.ofDays(1))
|
||||
: new UnpooledH2ConnectionFactory(channel.localAddress(), eventLoopGroup);
|
||||
}
|
||||
}
|
||||
|
||||
private OmnibusH2Server startOmnibusServer(final Channel defaultBackend) throws Exception {
|
||||
return startOmnibusServer(Collections.emptyMap(), defaultBackend, Duration.ofMinutes(1));
|
||||
/// A builder for a h2c server that can be used as a target of the omnibus. The server is started by
|
||||
/// [OmnibusServerBuilder#start()].
|
||||
private BackendServerBuilder backendServer() {
|
||||
return new BackendServerBuilder();
|
||||
}
|
||||
|
||||
private OmnibusH2Server startOmnibusServer(final Map<String, Channel> routes, final Channel defaultBackend) throws Exception {
|
||||
return startOmnibusServer(routes, defaultBackend, Duration.ofMinutes(1));
|
||||
}
|
||||
private class BackendServerBuilder {
|
||||
|
||||
/// Start a h2c server that can be used as a target of the omnibus
|
||||
///
|
||||
/// @param localChannel whether the omnibus should target this backend via a LocalChannel or an NioChannel
|
||||
/// @param identity how the backend should respond to identity requests
|
||||
/// @param h2ChannelInit a Consumer that will be called every time a new HTTP/2 connection is made to this server
|
||||
/// @param h2StreamInit a Consumer that will be called every time a new HTTP/2 stream is created on this server
|
||||
private Channel startBackendServer(final boolean localChannel, final String identity, Consumer<Channel> h2ChannelInit, Consumer<Channel> h2StreamInit) {
|
||||
return startBackendServer(localChannel ? localEventLoopGroup : nioEventLoopGroup,
|
||||
localChannel, identity, h2ChannelInit, h2StreamInit);
|
||||
}
|
||||
private boolean localChannel = true;
|
||||
private String identity = DEFAULT_BACKEND_IDENTITY;
|
||||
private Consumer<Channel> h2ChannelInit = _ -> {};
|
||||
private Consumer<Channel> h2StreamInit = _ -> {};
|
||||
@Nullable
|
||||
private Channel channel = null;
|
||||
|
||||
private Channel startBackendServer(final EventLoopGroup eventLoopGroup, final boolean localChannel,
|
||||
final String identity, Consumer<Channel> h2ChannelInit, Consumer<Channel> h2StreamInit) {
|
||||
return new ServerBootstrap()
|
||||
.group(eventLoopGroup, eventLoopGroup)
|
||||
.channel(localChannel ? LocalServerChannel.class : NioServerSocketChannel.class)
|
||||
.childHandler(new ChannelInitializer<>() {
|
||||
@Override
|
||||
protected void initChannel(final Channel ch) {
|
||||
h2ChannelInit.accept(ch);
|
||||
ch.pipeline().addLast(Http2FrameCodecBuilder.forServer().build());
|
||||
ch.pipeline().addLast(new Http2MultiplexHandler(new ChannelInitializer<Http2StreamChannel>() {
|
||||
@Override
|
||||
protected void initChannel(final Http2StreamChannel ch) {
|
||||
h2StreamInit.accept(ch);
|
||||
ch.pipeline().addLast(new TestHandler(identity));
|
||||
}
|
||||
}));
|
||||
}
|
||||
})
|
||||
.bind(localChannel ? new LocalAddress(identity) : new InetSocketAddress("127.0.0.1", 0))
|
||||
.syncUninterruptibly()
|
||||
.channel();
|
||||
}
|
||||
/// Whether the omnibus should target this backend via a LocalChannel or an NioChannel. Defaults to true.
|
||||
BackendServerBuilder localChannel(final boolean localChannel) {
|
||||
this.localChannel = localChannel;
|
||||
return this;
|
||||
}
|
||||
|
||||
private Channel startBackendServer(final boolean localChannel, final String identity) {
|
||||
return startBackendServer(localChannel, identity, _ -> {}, _ -> {});
|
||||
/// How the backend should respond to identity requests. Defaults to [#DEFAULT_BACKEND_IDENTITY].
|
||||
BackendServerBuilder identity(final String identity) {
|
||||
this.identity = identity;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// A Consumer that will be called every time a new HTTP/2 connection is made to this server
|
||||
BackendServerBuilder h2ChannelInit(final Consumer<Channel> h2ChannelInit) {
|
||||
this.h2ChannelInit = h2ChannelInit;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// A Consumer that will be called every time a new HTTP/2 stream is created on this server
|
||||
BackendServerBuilder h2StreamInit(final Consumer<Channel> h2StreamInit) {
|
||||
this.h2StreamInit = h2StreamInit;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// The backend's server channel, once it has started
|
||||
Channel channel() {
|
||||
assertNotNull(channel, "backend has not started");
|
||||
return channel;
|
||||
}
|
||||
|
||||
private Channel start(final EventLoopGroup eventLoopGroup) {
|
||||
channel = new ServerBootstrap()
|
||||
.group(eventLoopGroup, eventLoopGroup)
|
||||
.channel(localChannel ? LocalServerChannel.class : NioServerSocketChannel.class)
|
||||
.childHandler(new ChannelInitializer<>() {
|
||||
@Override
|
||||
protected void initChannel(final Channel ch) {
|
||||
h2ChannelInit.accept(ch);
|
||||
ch.pipeline().addLast(Http2FrameCodecBuilder.forServer().build());
|
||||
ch.pipeline().addLast(new Http2MultiplexHandler(new ChannelInitializer<Http2StreamChannel>() {
|
||||
@Override
|
||||
protected void initChannel(final Http2StreamChannel ch) {
|
||||
h2StreamInit.accept(ch);
|
||||
ch.pipeline().addLast(new TestHandler(identity));
|
||||
}
|
||||
}));
|
||||
}
|
||||
})
|
||||
.bind(localChannel ? new LocalAddress(identity) : new InetSocketAddress("127.0.0.1", 0))
|
||||
.syncUninterruptibly()
|
||||
.channel();
|
||||
return channel;
|
||||
}
|
||||
}
|
||||
|
||||
/// Makes an H2 connection to the omnibus at `server` on which new H2 streams can be opened
|
||||
private Channel connectToOmnibus(final OmnibusH2Server server, @Nullable final HAProxyMessage proxyHeader) {
|
||||
final SslContext clientSsl = sslContext();
|
||||
final CompletableFuture<Void> pipelineConfigured = new CompletableFuture<>();
|
||||
|
||||
final Bootstrap clientBootstrap = new Bootstrap()
|
||||
.group(nioEventLoopGroup)
|
||||
@@ -741,23 +894,34 @@ class OmnibusH2ServerTest {
|
||||
@Override
|
||||
protected void initChannel(final SocketChannel ch) {
|
||||
ch.pipeline().addLast(HAProxyMessageEncoder.INSTANCE);
|
||||
ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
|
||||
@Override
|
||||
public void channelActive(final ChannelHandlerContext ctx) {
|
||||
// The TLS and HTTP/2 handlers can't be added until after the proxy header is written
|
||||
if (proxyHeader != null) {
|
||||
ctx.writeAndFlush(proxyHeader);
|
||||
}
|
||||
ctx.pipeline().remove(HAProxyMessageEncoder.INSTANCE);
|
||||
ctx.pipeline().remove(this);
|
||||
ctx.pipeline().addLast(clientSsl.newHandler(ctx.alloc(), server.getLocalAddress().getHostName(), server.getLocalAddress().getPort()));
|
||||
ctx.pipeline().addLast(Http2FrameCodecBuilder.forClient()
|
||||
.initialSettings(Http2Settings.defaultSettings())
|
||||
.build());
|
||||
ctx.pipeline().addLast(new Http2MultiplexHandler(new ChannelInboundHandlerAdapter()));
|
||||
pipelineConfigured.complete(null);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
final Channel ch = clientBootstrap.connect(server.getLocalAddress())
|
||||
.syncUninterruptibly()
|
||||
.channel();
|
||||
if (proxyHeader != null) {
|
||||
ch.writeAndFlush(proxyHeader).syncUninterruptibly();
|
||||
}
|
||||
ch.pipeline().remove(HAProxyMessageEncoder.INSTANCE);
|
||||
ch.pipeline().addLast(clientSsl.newHandler(ch.alloc(), server.getLocalAddress().getHostName(), server.getLocalAddress().getPort()));
|
||||
ch.pipeline().addLast(Http2FrameCodecBuilder.forClient()
|
||||
.initialSettings(Http2Settings.defaultSettings())
|
||||
.build());
|
||||
ch.pipeline().addLast(new Http2MultiplexHandler(new ChannelInboundHandlerAdapter()));
|
||||
// The connect future completes before channelActive fires, so wait until streams can actually be opened
|
||||
pipelineConfigured.orTimeout(5, TimeUnit.SECONDS).join();
|
||||
return ch;
|
||||
}
|
||||
|
||||
|
||||
private Channel connectToOmnibus(final OmnibusH2Server server) {
|
||||
return connectToOmnibus(server, null);
|
||||
}
|
||||
@@ -765,6 +929,7 @@ class OmnibusH2ServerTest {
|
||||
private static SslContext sslContext() {
|
||||
try {
|
||||
return SslContextBuilder.forClient()
|
||||
.sslProvider(SslProvider.JDK)
|
||||
.trustManager(InsecureTrustManagerFactory.INSTANCE)
|
||||
.applicationProtocolConfig(new ApplicationProtocolConfig(
|
||||
ApplicationProtocolConfig.Protocol.ALPN,
|
||||
|
||||
+220
@@ -0,0 +1,220 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.grpc.net;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import io.netty.bootstrap.ServerBootstrap;
|
||||
import io.netty.channel.Channel;
|
||||
import io.netty.channel.ChannelFuture;
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.channel.ChannelInboundHandlerAdapter;
|
||||
import io.netty.channel.ChannelInitializer;
|
||||
import io.netty.channel.EventLoop;
|
||||
import io.netty.channel.EventLoopGroup;
|
||||
import io.netty.channel.MultiThreadIoEventLoopGroup;
|
||||
import io.netty.channel.group.ChannelGroup;
|
||||
import io.netty.channel.group.DefaultChannelGroup;
|
||||
import io.netty.channel.local.LocalAddress;
|
||||
import io.netty.channel.local.LocalIoHandler;
|
||||
import io.netty.channel.local.LocalServerChannel;
|
||||
import io.netty.handler.codec.http2.DefaultHttp2GoAwayFrame;
|
||||
import io.netty.handler.codec.http2.Http2Error;
|
||||
import io.netty.handler.codec.http2.Http2FrameCodecBuilder;
|
||||
import io.netty.handler.codec.http2.Http2GoAwayFrame;
|
||||
import io.netty.handler.codec.http2.Http2MultiplexHandler;
|
||||
import io.netty.util.concurrent.GlobalEventExecutor;
|
||||
import io.netty.util.test.LeakPresenceExtension;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.LinkedBlockingQueue;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
|
||||
@ExtendWith(LeakPresenceExtension.class)
|
||||
class PooledH2ConnectionFactoryTest {
|
||||
|
||||
private static EventLoopGroup backendEventLoopGroup;
|
||||
private static EventLoopGroup callerEventLoopGroup;
|
||||
|
||||
private LocalAddress backendAddress;
|
||||
private Channel backendServer;
|
||||
private BlockingQueue<Channel> newBackendConnections;
|
||||
private ChannelGroup allBackendConnections;
|
||||
private PooledH2ConnectionFactory factory;
|
||||
|
||||
@BeforeAll
|
||||
static void setUpBeforeAll() {
|
||||
backendEventLoopGroup = new MultiThreadIoEventLoopGroup(LocalIoHandler.newFactory());
|
||||
callerEventLoopGroup = new MultiThreadIoEventLoopGroup(2, LocalIoHandler.newFactory());
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
backendAddress = new LocalAddress(PooledH2ConnectionFactoryTest.class);
|
||||
newBackendConnections = new LinkedBlockingQueue<>();
|
||||
allBackendConnections = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
|
||||
startBackend();
|
||||
factory = new PooledH2ConnectionFactory(backendAddress, backendEventLoopGroup, Duration.ofDays(1));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
backendServer.close().syncUninterruptibly();
|
||||
allBackendConnections.close().syncUninterruptibly();
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void tearDownAfterAll() throws InterruptedException {
|
||||
backendEventLoopGroup.shutdownGracefully(0, 1, TimeUnit.SECONDS).sync();
|
||||
callerEventLoopGroup.shutdownGracefully(0, 1, TimeUnit.SECONDS).sync();
|
||||
}
|
||||
|
||||
@Test
|
||||
void reuseConnection() throws Exception {
|
||||
final EventLoop eventLoop1 = callerEventLoopGroup.next();
|
||||
final EventLoop eventLoop2 = callerEventLoopGroup.next();
|
||||
final Channel connection = getConnection(eventLoop1).channel();
|
||||
assertSame(connection, getConnection(eventLoop1).channel());
|
||||
assertNotSame(connection, getConnection(eventLoop2).channel());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shareConnectionWhileConnecting() throws Exception {
|
||||
final EventLoop callerEventLoop = callerEventLoopGroup.next();
|
||||
final List<ChannelFuture> connectFutures = callerEventLoop.submit(() -> List.of(
|
||||
factory.getConnectionChannelFuture(callerEventLoop),
|
||||
factory.getConnectionChannelFuture(callerEventLoop)))
|
||||
.get();
|
||||
|
||||
assertSame(connectFutures.get(0), connectFutures.get(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void replaceClosedConnection() throws Exception {
|
||||
final EventLoop callerEventLoop = callerEventLoopGroup.next();
|
||||
final Channel connection = getConnection(callerEventLoop).channel();
|
||||
|
||||
backendConnection().close().syncUninterruptibly();
|
||||
connection.closeFuture().syncUninterruptibly();
|
||||
|
||||
final Channel replacement = getConnection(callerEventLoop).channel();
|
||||
assertNotSame(connection, replacement);
|
||||
assertTrue(replacement.isActive());
|
||||
}
|
||||
|
||||
@Test
|
||||
void replaceFailedConnection() throws Exception {
|
||||
backendServer.close().syncUninterruptibly();
|
||||
|
||||
final EventLoop callerEventLoop = callerEventLoopGroup.next();
|
||||
assertFalse(getConnection(callerEventLoop).isSuccess());
|
||||
|
||||
startBackend();
|
||||
assertTrue(getConnection(callerEventLoop).isSuccess());
|
||||
}
|
||||
|
||||
@Test
|
||||
void replaceConnectionAfterGoAway() throws Exception {
|
||||
final EventLoop callerEventLoop = callerEventLoopGroup.next();
|
||||
final Channel connection = getConnection(callerEventLoop).channel();
|
||||
|
||||
final CompletableFuture<Void> goAwayRead = goAwayRead(connection);
|
||||
backendConnection().writeAndFlush(new DefaultHttp2GoAwayFrame(Http2Error.NO_ERROR)).syncUninterruptibly();
|
||||
goAwayRead.get(5, TimeUnit.SECONDS);
|
||||
|
||||
assertNotSame(connection, getConnection(callerEventLoop).channel());
|
||||
assertTrue(connection.isActive());
|
||||
|
||||
factory.release(connection);
|
||||
assertTrue(connection.closeFuture().await(5, TimeUnit.SECONDS));
|
||||
}
|
||||
|
||||
@Test
|
||||
void retireConnection() throws Exception {
|
||||
factory = new PooledH2ConnectionFactory(backendAddress, backendEventLoopGroup, Duration.ZERO);
|
||||
|
||||
final EventLoop callerEventLoop = callerEventLoopGroup.next();
|
||||
final Channel connection = getConnection(callerEventLoop).channel();
|
||||
|
||||
assertNotSame(connection, getConnection(callerEventLoop).channel());
|
||||
assertTrue(connection.isActive());
|
||||
|
||||
factory.release(connection);
|
||||
assertTrue(connection.closeFuture().await(5, TimeUnit.SECONDS));
|
||||
}
|
||||
|
||||
@Test
|
||||
void closeUnusedConnectionWhenReplaced() throws Exception {
|
||||
factory = new PooledH2ConnectionFactory(backendAddress, backendEventLoopGroup, Duration.ZERO);
|
||||
|
||||
final EventLoop callerEventLoop = callerEventLoopGroup.next();
|
||||
final Channel connection = getConnection(callerEventLoop).channel();
|
||||
factory.release(connection);
|
||||
assertTrue(connection.isActive());
|
||||
|
||||
getConnection(callerEventLoop);
|
||||
assertTrue(connection.closeFuture().await(5, TimeUnit.SECONDS));
|
||||
}
|
||||
|
||||
private void startBackend() {
|
||||
backendServer = new ServerBootstrap()
|
||||
.group(backendEventLoopGroup)
|
||||
.channel(LocalServerChannel.class)
|
||||
.childHandler(new ChannelInitializer<>() {
|
||||
@Override
|
||||
protected void initChannel(final Channel ch) {
|
||||
ch.pipeline().addLast(Http2FrameCodecBuilder.forServer().build());
|
||||
ch.pipeline().addLast(new Http2MultiplexHandler(new ChannelInboundHandlerAdapter()));
|
||||
newBackendConnections.add(ch);
|
||||
allBackendConnections.add(ch);
|
||||
}
|
||||
})
|
||||
.bind(backendAddress)
|
||||
.syncUninterruptibly()
|
||||
.channel();
|
||||
}
|
||||
|
||||
/// Get a connection from the factory on `callerEventLoop`, waiting for it to finish connecting
|
||||
private ChannelFuture getConnection(final EventLoop callerEventLoop) throws Exception {
|
||||
return callerEventLoop.submit(() -> factory.getConnectionChannelFuture(callerEventLoop)).get().await();
|
||||
}
|
||||
|
||||
/// The backend's side of the next connection the factory made
|
||||
private Channel backendConnection() throws InterruptedException {
|
||||
final Channel backendConnection = newBackendConnections.poll(5, TimeUnit.SECONDS);
|
||||
assertNotNull(backendConnection);
|
||||
return backendConnection;
|
||||
}
|
||||
|
||||
/// A future that completes once the factory has seen a GOAWAY on `connection`
|
||||
private static CompletableFuture<Void> goAwayRead(final Channel connection) {
|
||||
final CompletableFuture<Void> goAwayRead = new CompletableFuture<>();
|
||||
connection.eventLoop().submit(() -> connection.pipeline()
|
||||
.addAfter(connection.pipeline().context(Http2MultiplexHandler.class).name(), null,
|
||||
new ChannelInboundHandlerAdapter() {
|
||||
@Override
|
||||
public void channelRead(final ChannelHandlerContext ctx, final Object msg) {
|
||||
ctx.fireChannelRead(msg);
|
||||
if (msg instanceof Http2GoAwayFrame) {
|
||||
goAwayRead.complete(null);
|
||||
}
|
||||
}
|
||||
}))
|
||||
.syncUninterruptibly();
|
||||
return goAwayRead;
|
||||
}
|
||||
}
|
||||
@@ -15,10 +15,12 @@ import io.netty.bootstrap.ServerBootstrap;
|
||||
import io.netty.channel.Channel;
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.channel.ChannelInitializer;
|
||||
import io.netty.channel.DefaultEventLoopGroup;
|
||||
import io.netty.channel.EventLoopGroup;
|
||||
import io.netty.channel.MultiThreadIoEventLoopGroup;
|
||||
import io.netty.channel.SimpleUserEventChannelHandler;
|
||||
import io.netty.channel.local.LocalAddress;
|
||||
import io.netty.channel.local.LocalChannel;
|
||||
import io.netty.channel.local.LocalIoHandler;
|
||||
import io.netty.channel.local.LocalServerChannel;
|
||||
import io.netty.handler.ssl.SniHandler;
|
||||
import io.netty.handler.ssl.SslContext;
|
||||
@@ -30,6 +32,8 @@ import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
|
||||
import io.netty.pkitesting.CertificateBuilder;
|
||||
import io.netty.pkitesting.X509Bundle;
|
||||
import io.netty.util.Mapping;
|
||||
import io.netty.util.ReferenceCountUtil;
|
||||
import io.netty.util.test.LeakPresenceExtension;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.security.KeyStore;
|
||||
@@ -53,11 +57,13 @@ import org.apache.commons.lang3.RandomStringUtils;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.EnumSource;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
|
||||
@ExtendWith(LeakPresenceExtension.class)
|
||||
class SniMapperTest {
|
||||
|
||||
// Configuration for precomputed keystore blob defined in sni-mapper-test-keystore.p12
|
||||
@@ -69,7 +75,7 @@ class SniMapperTest {
|
||||
CertificateBuilder.Algorithm.rsa2048
|
||||
};
|
||||
|
||||
private static DefaultEventLoopGroup eventLoopGroup;
|
||||
private static EventLoopGroup eventLoopGroup;
|
||||
private static final Map<SslProvider, Mapping<String, SslContext>> sniMappingsByProvider =
|
||||
new EnumMap<>(SslProvider.class);
|
||||
|
||||
@@ -109,7 +115,7 @@ class SniMapperTest {
|
||||
new ByteArrayInputStream(byteArrayOutputStream.toByteArray()), new String(keyStorePassword), sslProvider));
|
||||
}
|
||||
|
||||
eventLoopGroup = new DefaultEventLoopGroup();
|
||||
eventLoopGroup = new MultiThreadIoEventLoopGroup(LocalIoHandler.newFactory());
|
||||
}
|
||||
|
||||
private void startServer(final SslProvider sslProvider) throws InterruptedException {
|
||||
@@ -139,6 +145,10 @@ class SniMapperTest {
|
||||
@AfterAll
|
||||
static void tearDownAfterAll() throws InterruptedException {
|
||||
eventLoopGroup.shutdownGracefully(1, 1000, TimeUnit.MILLISECONDS).sync();
|
||||
sniMappingsByProvider.values().forEach(sniMapping -> {
|
||||
ReferenceCountUtil.release(sniMapping.map(FOO_DOMAIN));
|
||||
ReferenceCountUtil.release(sniMapping.map(BAR_DOMAIN));
|
||||
});
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
|
||||
+17
-6
@@ -18,10 +18,11 @@ import io.netty.channel.Channel;
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.channel.ChannelInboundHandlerAdapter;
|
||||
import io.netty.channel.ChannelInitializer;
|
||||
import io.netty.channel.DefaultEventLoopGroup;
|
||||
import io.netty.channel.MultithreadEventLoopGroup;
|
||||
import io.netty.channel.EventLoopGroup;
|
||||
import io.netty.channel.MultiThreadIoEventLoopGroup;
|
||||
import io.netty.channel.local.LocalAddress;
|
||||
import io.netty.channel.local.LocalChannel;
|
||||
import io.netty.channel.local.LocalIoHandler;
|
||||
import io.netty.channel.local.LocalServerChannel;
|
||||
import io.netty.handler.ssl.SniHandler;
|
||||
import io.netty.handler.ssl.SslContext;
|
||||
@@ -33,6 +34,8 @@ import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
|
||||
import io.netty.pkitesting.CertificateBuilder;
|
||||
import io.netty.pkitesting.X509Bundle;
|
||||
import io.netty.util.Mapping;
|
||||
import io.netty.util.ReferenceCountUtil;
|
||||
import io.netty.util.test.LeakPresenceExtension;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.security.KeyStore;
|
||||
@@ -51,19 +54,22 @@ import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.EnumSource;
|
||||
|
||||
@ExtendWith(LeakPresenceExtension.class)
|
||||
class TlsHandshakeMetricsHandlerTest {
|
||||
|
||||
private static final String DOMAIN = "example.org";
|
||||
|
||||
private static MultithreadEventLoopGroup eventLoopGroup;
|
||||
private static EventLoopGroup eventLoopGroup;
|
||||
private static byte[] keyStoreBytes;
|
||||
private static String keyStorePassword;
|
||||
|
||||
private SimpleMeterRegistry meterRegistry;
|
||||
private SslContext clientSslContext;
|
||||
private Mapping<String, SslContext> sniMapping;
|
||||
private Channel serverChannel;
|
||||
|
||||
/// Completed by the server once the handshake event has passed the metrics handler
|
||||
@@ -89,7 +95,7 @@ class TlsHandshakeMetricsHandlerTest {
|
||||
keyStoreBytes = byteArrayOutputStream.toByteArray();
|
||||
keyStorePassword = new String(password);
|
||||
|
||||
eventLoopGroup = new DefaultEventLoopGroup();
|
||||
eventLoopGroup = new MultiThreadIoEventLoopGroup(LocalIoHandler.newFactory());
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
@@ -108,6 +114,9 @@ class TlsHandshakeMetricsHandlerTest {
|
||||
if (serverChannel != null) {
|
||||
serverChannel.close().sync();
|
||||
}
|
||||
if (sniMapping != null) {
|
||||
ReferenceCountUtil.release(sniMapping.map(DOMAIN));
|
||||
}
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
@@ -118,7 +127,8 @@ class TlsHandshakeMetricsHandlerTest {
|
||||
@ParameterizedTest
|
||||
@EnumSource(value = SslProvider.class, names = {"JDK", "OPENSSL"})
|
||||
void handshake(final SslProvider sslProvider) throws Exception {
|
||||
final AtomicReference<Channel> lastServerChildChannel = startServer(buildSniMapping(sslProvider));
|
||||
sniMapping = buildSniMapping(sslProvider);
|
||||
final AtomicReference<Channel> lastServerChildChannel = startServer(sniMapping);
|
||||
connect(null);
|
||||
|
||||
assertEquals(1, getCount(true));
|
||||
@@ -130,7 +140,8 @@ class TlsHandshakeMetricsHandlerTest {
|
||||
@ParameterizedTest
|
||||
@EnumSource(value = SslProvider.class, names = {"JDK", "OPENSSL"})
|
||||
void failedHandshake(final SslProvider sslProvider) throws Exception {
|
||||
startServer(buildSniMapping(sslProvider));
|
||||
sniMapping = buildSniMapping(sslProvider);
|
||||
startServer(sniMapping);
|
||||
|
||||
// The server only holds an Ed25519 key
|
||||
connect(new String[] { "rsa_pss_rsae_sha256" });
|
||||
|
||||
+48
@@ -1414,6 +1414,54 @@ class AccountsManagerTest {
|
||||
);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void testUpdateDevicePassword(final boolean credentialsLocked) {
|
||||
final Account account = AccountsHelper.generateTestAccount(null, UUID.randomUUID(), null, new ArrayList<>(), new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH]);
|
||||
addRetrievableAccount(account);
|
||||
|
||||
final String newPassword = RandomStringUtils.insecure().nextAlphanumeric(32);
|
||||
|
||||
final Device device = new Device();
|
||||
device.setId(Device.PRIMARY_ID);
|
||||
device.setAuthTokenHash(SaltedTokenHash.generateFor("old-password"));
|
||||
account.addDevice(device);
|
||||
|
||||
if (credentialsLocked) {
|
||||
device.lockAuthTokenHash();
|
||||
}
|
||||
final SaltedTokenHash lockedCredentials = device.getAuthTokenHash();
|
||||
|
||||
assertEquals(!credentialsLocked, accountsManager.updateDevicePassword(account.getAccountIdentifier(),
|
||||
Device.PRIMARY_ID, newPassword));
|
||||
|
||||
if (credentialsLocked) {
|
||||
assertEquals(lockedCredentials, device.getAuthTokenHash());
|
||||
assertTrue(device.hasLockedCredentials());
|
||||
|
||||
verify(accounts, never()).update(any());
|
||||
verifyNoInteractions(disconnectionRequestManager);
|
||||
} else {
|
||||
assertTrue(device.getAuthTokenHash().verify(newPassword));
|
||||
|
||||
verify(accounts).update(account);
|
||||
verify(disconnectionRequestManager)
|
||||
.requestDisconnection(account.getAccountIdentifier(), List.of(Device.PRIMARY_ID));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testUpdateDevicePasswordDeviceNotFound() {
|
||||
final Account account = AccountsHelper.generateTestAccount(null, UUID.randomUUID(), null, new ArrayList<>(), new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH]);
|
||||
addRetrievableAccount(account);
|
||||
final byte unknownDeviceId = 2;
|
||||
|
||||
assertFalse(accountsManager.updateDevicePassword(account.getAccountIdentifier(), unknownDeviceId, "new-password"));
|
||||
|
||||
verify(accounts, never()).update(any());
|
||||
verifyNoInteractions(disconnectionRequestManager);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({
|
||||
"+14152222222,+14153333333",
|
||||
|
||||
+53
-5
@@ -5,6 +5,7 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
@@ -19,6 +20,7 @@ import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStream;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import reactor.adapter.JdkFlowAdapter;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.test.StepVerifier;
|
||||
@@ -65,14 +67,60 @@ class ConcatenatingMessageStreamTest {
|
||||
final UUID v4Uuid = UUID.randomUUID();
|
||||
final long serverTimestamp = System.currentTimeMillis();
|
||||
|
||||
concatenatingMessageStream.acknowledgeMessage(v4Uuid, serverTimestamp).join();
|
||||
when(dynamoDbMessageStream.getMessages())
|
||||
.thenReturn(JdkFlowAdapter.publisherToFlowPublisher(Flux.just(new MessageStreamEntry.Envelope(MessageProtos.Envelope.newBuilder()
|
||||
.setServerGuid(UUIDUtil.toByteString(v4Uuid))
|
||||
.setServerTimestamp(serverTimestamp)
|
||||
.build()))));
|
||||
|
||||
final UUID v8UUID = MessageGuidUtil.generateRandomV8UUID();
|
||||
|
||||
when(foundationDbMessageStream.getMessages())
|
||||
.thenReturn(JdkFlowAdapter.publisherToFlowPublisher(Flux.just(new MessageStreamEntry.Envelope(MessageProtos.Envelope.newBuilder()
|
||||
.setServerGuid(UUIDUtil.toByteString(v8UUID))
|
||||
.setServerTimestamp(serverTimestamp)
|
||||
.build()))));
|
||||
|
||||
JdkFlowAdapter.flowPublisherToFlux(concatenatingMessageStream.getMessages())
|
||||
.filter(messageStreamEntry -> messageStreamEntry instanceof MessageStreamEntry.Envelope)
|
||||
.cast(MessageStreamEntry.Envelope.class)
|
||||
.doOnNext(envelopeEntry -> concatenatingMessageStream.acknowledgeMessage(
|
||||
UUIDUtil.fromByteString(envelopeEntry.message().getServerGuid()),
|
||||
envelopeEntry.message().getServerTimestamp()))
|
||||
.then()
|
||||
.block();
|
||||
|
||||
verify(dynamoDbMessageStream).acknowledgeMessage(v4Uuid, serverTimestamp);
|
||||
verify(foundationDbMessageStream, never()).acknowledgeMessage(eq(v4Uuid), anyLong());
|
||||
|
||||
final UUID v8Uuid = MessageGuidUtil.generateRandomV8UUID();
|
||||
verify(dynamoDbMessageStream).acknowledgeMessage(v8UUID, serverTimestamp);
|
||||
verify(foundationDbMessageStream).acknowledgeMessage(v8UUID, serverTimestamp);
|
||||
}
|
||||
|
||||
concatenatingMessageStream.acknowledgeMessage(v8Uuid, serverTimestamp).join();
|
||||
verify(dynamoDbMessageStream).acknowledgeMessage(v8Uuid, serverTimestamp);
|
||||
verify(foundationDbMessageStream).acknowledgeMessage(v8Uuid, serverTimestamp);
|
||||
@Test
|
||||
void acknowledgeMessageDynamoDbEmpty() {
|
||||
when(dynamoDbMessageStream.getMessages())
|
||||
.thenReturn(JdkFlowAdapter.publisherToFlowPublisher(Flux.empty()));
|
||||
|
||||
final UUID v8UUID = MessageGuidUtil.generateRandomV8UUID();
|
||||
final long serverTimestamp = System.currentTimeMillis();
|
||||
|
||||
when(foundationDbMessageStream.getMessages())
|
||||
.thenReturn(JdkFlowAdapter.publisherToFlowPublisher(Flux.just(new MessageStreamEntry.Envelope(MessageProtos.Envelope.newBuilder()
|
||||
.setServerGuid(UUIDUtil.toByteString(v8UUID))
|
||||
.setServerTimestamp(serverTimestamp)
|
||||
.build()))));
|
||||
|
||||
JdkFlowAdapter.flowPublisherToFlux(concatenatingMessageStream.getMessages())
|
||||
.filter(messageStreamEntry -> messageStreamEntry instanceof MessageStreamEntry.Envelope)
|
||||
.cast(MessageStreamEntry.Envelope.class)
|
||||
.doOnNext(envelopeEntry -> concatenatingMessageStream.acknowledgeMessage(
|
||||
UUIDUtil.fromByteString(envelopeEntry.message().getServerGuid()),
|
||||
envelopeEntry.message().getServerTimestamp()))
|
||||
.then()
|
||||
.block();
|
||||
|
||||
verify(dynamoDbMessageStream, never()).acknowledgeMessage(any(), anyLong());
|
||||
verify(foundationDbMessageStream).acknowledgeMessage(v8UUID, serverTimestamp);
|
||||
}
|
||||
}
|
||||
+9
-4
@@ -48,7 +48,8 @@ public class FoundationDbClusterExtension implements AutoCloseable, BeforeAllCal
|
||||
|
||||
@Override
|
||||
public void beforeAll(final ExtensionContext context) throws IOException {
|
||||
final String resilienceConfigurationName = "foundationdb-test-" + RandomStringUtils.insecure().nextAlphanumeric(6);
|
||||
final String resilienceSuffix = RandomStringUtils.insecure().nextAlphanumeric(6);
|
||||
final String resilienceConfigurationName = "foundationdb-test-" + resilienceSuffix;
|
||||
|
||||
ResilienceUtil.getCircuitBreakerRegistry().addConfiguration(resilienceConfigurationName,
|
||||
circuitBreakerConfiguration.toCircuitBreakerConfig());
|
||||
@@ -61,11 +62,15 @@ public class FoundationDbClusterExtension implements AutoCloseable, BeforeAllCal
|
||||
|
||||
for (int i = 0; i < databaseLifecycleManagers.length; i++) {
|
||||
final FoundationDbDatabaseLifecycleManager databaseLifecycleManager = serviceContainerNamePrefix != null
|
||||
? new ServiceContainerFoundationDbDatabaseLifecycleManager(serviceContainerNamePrefix + i)
|
||||
: new TestcontainersFoundationDbDatabaseLifecycleManager();
|
||||
? new ServiceContainerFoundationDbDatabaseLifecycleManager(serviceContainerNamePrefix + i)
|
||||
: new TestcontainersFoundationDbDatabaseLifecycleManager();
|
||||
databaseLifecycleManager.initializeDatabase(FDB.selectAPIVersion(FoundationDbVersion.getFoundationDbApiVersion()));
|
||||
databaseLifecycleManagers[i] = databaseLifecycleManager;
|
||||
databases[i] = new FaultTolerantDatabase(databaseLifecycleManager.getDatabase(), String.format("messages-%d", i), resilienceConfigurationName, resilienceConfigurationName);
|
||||
|
||||
// Circuit breakers and bulkheads are cached by name in static registries that outlive individual test
|
||||
// classes, so use a unique name to make sure this extension's configuration actually takes effect
|
||||
databases[i] = new FaultTolerantDatabase(databaseLifecycleManager.getDatabase(),
|
||||
String.format("messages-%d-%s", i, resilienceSuffix), resilienceConfigurationName, resilienceConfigurationName);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+23
@@ -34,8 +34,10 @@ import java.util.stream.Collectors;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.junit.jupiter.params.provider.EnumSource;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.junitpioneer.jupiter.cartesian.CartesianTest;
|
||||
import org.signal.libsignal.protocol.InvalidMessageException;
|
||||
import org.signal.libsignal.protocol.InvalidVersionException;
|
||||
@@ -297,4 +299,25 @@ class MessagesManagerTest {
|
||||
messagesManager.getEarliestUndeliveredTimestampForDevice(accountIdentifier, device).join();
|
||||
assertEquals(Optional.ofNullable(expected).map(Instant::ofEpochMilli), earliest);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void hasSuspectedDeliveryLoop(final long readsSinceLastAcknowledgedMessage, final boolean expectSuspectedLoop) {
|
||||
final AciServiceIdentifier aciServiceIdentifier = new AciServiceIdentifier(UUID.randomUUID());
|
||||
final byte deviceId = Device.PRIMARY_ID;
|
||||
|
||||
when(foundationDbMessageStore.getReadsSinceLastAcknowledgedMessage(aciServiceIdentifier, deviceId))
|
||||
.thenReturn(CompletableFuture.completedFuture(readsSinceLastAcknowledgedMessage));
|
||||
|
||||
assertEquals(expectSuspectedLoop,
|
||||
messagesManager.hasSuspectedDeliveryLoop(aciServiceIdentifier.uuid(), deviceId).join());
|
||||
}
|
||||
|
||||
private static List<Arguments> hasSuspectedDeliveryLoop() {
|
||||
return List.of(
|
||||
Arguments.of(MessagesManager.DELIVERY_LOOP_READ_THRESHOLD - 1, false),
|
||||
Arguments.of(MessagesManager.DELIVERY_LOOP_READ_THRESHOLD, true),
|
||||
Arguments.of(MessagesManager.DELIVERY_LOOP_READ_THRESHOLD + 1, true)
|
||||
);
|
||||
}
|
||||
}
|
||||
-69
@@ -1,69 +0,0 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.storage.devicecheck;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
|
||||
|
||||
import com.webauthn4j.appattest.DeviceCheckManager;
|
||||
import com.webauthn4j.appattest.data.DCAssertionData;
|
||||
import com.webauthn4j.appattest.data.DCAssertionRequest;
|
||||
import com.webauthn4j.converter.exception.DataConversionException;
|
||||
import com.webauthn4j.converter.util.ObjectConverter;
|
||||
import com.webauthn4j.data.attestation.authenticator.AuthenticatorData;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.Map;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
class AppAttestAssertionConverterTest {
|
||||
|
||||
private static final ObjectConverter OBJECT_CONVERTER = DeviceCheckManager.createObjectConverter();
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(bytes = {AuthenticatorData.BIT_AT, AuthenticatorData.BIT_ED, AuthenticatorData.BIT_AT | AuthenticatorData.BIT_ED})
|
||||
void parseBadAssertion(byte flags) {
|
||||
final DCAssertionData data = AppAttestAssertionConverter.parseAppleAssertion(
|
||||
new DCAssertionRequest(new byte[32], createAssertion(flags), new byte[32]));
|
||||
|
||||
assertThat(data.getAuthenticatorDataBytes()).isEqualTo(createAuthenticatorData(flags));
|
||||
assertThat(data.getAuthenticatorData().getFlags()).isEqualTo(flags);
|
||||
assertThat(data.getAuthenticatorData().getSignCount()).isEqualTo(32);
|
||||
assertThat(data.getAuthenticatorData().getAttestedCredentialData()).isNull();
|
||||
assertThat(data.getAuthenticatorData().getExtensions().getKeys())
|
||||
.containsExactlyInAnyOrder("apple_bundle_version_01", "apple_validation_category_01");
|
||||
}
|
||||
|
||||
// If this test fails, we have updated to a version of webauthn4j that handles misformatted attestations, and
|
||||
// the helper class can be removed.
|
||||
@Test
|
||||
void webauthn4jRejectsIOS27Assertion() {
|
||||
final DeviceCheckManager deviceCheckManager = new DeviceCheckManager(new AppleDeviceCheckTrustAnchor());
|
||||
final byte[] appAttestAssertion = createAssertion((byte) (AuthenticatorData.BIT_AT | AuthenticatorData.BIT_ED));
|
||||
assertThatExceptionOfType(DataConversionException.class).isThrownBy(() ->
|
||||
deviceCheckManager.parse(new DCAssertionRequest(new byte[32], appAttestAssertion, new byte[32])));
|
||||
}
|
||||
|
||||
/// An assertion that has extensions and no attestedCredentialData but potentially with mismatched flags
|
||||
private static byte[] createAssertion(final byte flags) {
|
||||
return OBJECT_CONVERTER.getCborMapper().writeValueAsBytes(Map.of(
|
||||
"signature", new byte[64],
|
||||
"authenticatorData", createAuthenticatorData(flags)));
|
||||
}
|
||||
|
||||
private static byte[] createAuthenticatorData(final byte flags) {
|
||||
final byte[] extensions = OBJECT_CONVERTER.getCborMapper().writeValueAsBytes(Map.of(
|
||||
"apple_bundle_version_01", "1",
|
||||
"apple_validation_category_01", new byte[]{2, 0, 0, 0}));
|
||||
|
||||
return ByteBuffer.allocate(37 + extensions.length)
|
||||
.put(new byte[32]) // rpIdHash
|
||||
.put((byte) flags) // flags
|
||||
.putInt(32) // signCount
|
||||
.put(extensions)
|
||||
.array();
|
||||
}
|
||||
}
|
||||
Loaded 100 of 109 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user