mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-11-30 11:06:47 +00:00
Compare commits
128
Commits
| 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 | ||
|
|
9c5170d47c | ||
|
|
4c940f2a39 | ||
|
|
3f79eb32c3 | ||
|
|
1c4933e23c | ||
|
|
6e79823f74 | ||
|
|
b6e4349caa | ||
|
|
9830e147ff | ||
|
|
954be67307 | ||
|
|
1ca19fb02c | ||
|
|
48a5fa529d | ||
|
|
f9b490c24f | ||
|
|
faff0e1751 | ||
|
|
78ec09cc25 | ||
|
|
5318ef4562 | ||
|
|
746304935d | ||
|
|
4dd84f4fc8 | ||
|
|
578f96f426 | ||
|
|
94e412031a | ||
|
|
5f24e3f771 | ||
|
|
ccc22f9ac4 | ||
|
|
58938b9775 | ||
|
|
e1534d3ef3 | ||
|
|
db6f370575 | ||
|
|
7238d00f4d | ||
|
|
773081ce36 | ||
|
|
4a25ca3937 | ||
|
|
8f78fdf58b | ||
|
|
bcf3658557 | ||
|
|
4090b1fb4a | ||
|
|
d1073e00bd | ||
|
|
9333174b58 | ||
|
|
0a04be011f | ||
|
|
a3d9f7591d | ||
|
|
458eadf0a0 | ||
|
|
edfefba78f | ||
|
|
8b92313a85 | ||
|
|
9e6b142189 | ||
|
|
ff642c1ae5 | ||
|
|
b6685b5140 | ||
|
|
e3b303e2c8 | ||
|
|
1f77698420 | ||
|
|
03b4f16ac3 | ||
|
|
01eb99d281 | ||
|
|
73d3c88ef4 | ||
|
|
5fde1d8f7b | ||
|
|
367854ea14 | ||
|
|
f46d6c566b | ||
|
|
9d4280938e | ||
|
|
b898880a0d | ||
|
|
7857f85710 | ||
|
|
635350d66a | ||
|
|
1f0bf83fef | ||
|
|
8f394663b0 | ||
|
|
55abc73cac | ||
|
|
031beed7e4 | ||
|
|
ef4c46941c | ||
|
|
ddb8c02e40 |
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.12"]
|
||||
- dependency-name: "org.eclipse.jetty.ee10:*"
|
||||
versions: ["<=12.1.12"]
|
||||
|
||||
# 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
|
||||
@@ -65,8 +65,8 @@ jobs:
|
||||
run: docker exec foundationdb1 /usr/bin/fdbcli --exec 'configure new single memory'
|
||||
- name: Download and install FoundationDB client
|
||||
run: |
|
||||
./mvnw -e -B -Pexclude-spam-filter clean prepare-package -DskipTests=true
|
||||
./mvnw -e -B -Pexclude-spam-filter -pl service download:wget@install-foundationdb-client-library
|
||||
cp service/target/jib-extra/usr/lib/libfdb_c.so /usr/lib/libfdb_c.x86_64.so
|
||||
ldconfig
|
||||
- name: Build with Maven
|
||||
run: ./mvnw -e -B clean verify -DfoundationDb.serviceContainerNamePrefix=foundationdb
|
||||
run: ./mvnw -e -B -Pprepull-testcontainers-images clean verify -DfoundationDb.serviceContainerNamePrefix=foundationdb
|
||||
+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,17 +53,23 @@ 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;
|
||||
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;
|
||||
@@ -82,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;
|
||||
@@ -95,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;
|
||||
@@ -113,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 {
|
||||
@@ -235,53 +260,67 @@ public final class Operations {
|
||||
Optional.empty(),
|
||||
Optional.empty()));
|
||||
|
||||
final Pair<Integer, MfaFailureExceptionMapper.MfaFailureResponse> initialResponse = apiPost("/v1/registration", initialRequest)
|
||||
// For a numberless account recovery, the username is the ACI
|
||||
.authorized(testUser.aciUuid().toString(), testUser.accountPassword())
|
||||
.execute(MfaFailureExceptionMapper.MfaFailureResponse.class);
|
||||
|
||||
// we expect (and need) failure with status 441, which will contain the WebAuthn challenge
|
||||
assert initialResponse.getLeft() == 441;
|
||||
|
||||
final MfaFailureExceptionMapper.MfaFailureResponse mfaFailureResponse = initialResponse.getRight();
|
||||
assert mfaFailureResponse.webAuthnParameters().allowedCredentialIds()
|
||||
.stream()
|
||||
.anyMatch(allowedId -> Arrays.equals(allowedId, 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 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)
|
||||
MfaFailureExceptionMapper.MfaFailureResponse mfaFailureResponse = apiPost("/v1/registration", initialRequest)
|
||||
// For a numberless account recovery, the username is the ACI
|
||||
.authorized(testUser.aciUuid().toString(), testUser.accountPassword())
|
||||
.executeExpectSuccess(AccountIdentityResponse.class);
|
||||
.executeExpectStatusCode(441, MfaFailureExceptionMapper.MfaFailureResponse.class);
|
||||
|
||||
recoveredUser.setAciUuid(registrationResponse.uuid());
|
||||
return recoveredUser;
|
||||
// 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 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 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);
|
||||
|
||||
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));
|
||||
@@ -328,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) {
|
||||
@@ -444,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);
|
||||
@@ -458,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;
|
||||
@@ -495,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);
|
||||
}
|
||||
@@ -525,6 +597,15 @@ public final class Operations {
|
||||
response.statusCode(), expectedStatusCode, response.body());
|
||||
}
|
||||
|
||||
public <T> T executeExpectStatusCode(final int expectedStatusCode, final Class<T> expectedType) {
|
||||
final RawResponse response = executeRaw();
|
||||
Validate.isTrue(
|
||||
response.statusCode() == expectedStatusCode,
|
||||
"Unexpected response code: %d (expected %d), body: %s",
|
||||
response.statusCode(), expectedStatusCode, response.body());
|
||||
return requireNonNull(parseBody(response.body(), expectedType));
|
||||
}
|
||||
|
||||
public <T> Pair<Integer, T> execute(final Class<T> expectedType) {
|
||||
final RawResponse response = executeRaw();
|
||||
return Pair.of(response.statusCode(), parseBody(response.body(), expectedType));
|
||||
@@ -535,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);
|
||||
@@ -564,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) {
|
||||
@@ -582,7 +680,17 @@ public final class Operations {
|
||||
connector.setSslContextFactory(sslContextFactory);
|
||||
|
||||
final HTTP2Client http2Client = new HTTP2Client(connector);
|
||||
final HttpClient httpClient = new HttpClient(new HttpClientTransportOverHTTP2(http2Client));
|
||||
final HttpClient httpClient = new HttpClient(new HttpClientTransportOverHTTP2(http2Client)) {
|
||||
// There is an upstream Jetty bug where an HTTP/2 reader can race against and beat a websocket connection in
|
||||
// reading the first websocket frame. See https://github.com/jetty/jetty.project/issues/15981 for more details.
|
||||
//
|
||||
// As a workaround, register a response content listener that never reads. This stops the HTTP client's default
|
||||
// response content consumer from reading websocket frames off the upgraded HTTP/2 stream.
|
||||
@Override
|
||||
public Request newRequest(final URI uri) {
|
||||
return super.newRequest(uri).onResponseContentSource((_, _) -> {});
|
||||
}
|
||||
};
|
||||
|
||||
final WebSocketClient wsClient = new WebSocketClient(httpClient);
|
||||
wsClient.start();
|
||||
@@ -607,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.54.7</aws.sdk2.version>
|
||||
<braintree.version>3.53.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,52 +59,51 @@
|
||||
<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.87.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 -->
|
||||
<gson.version>2.14.0</gson.version>
|
||||
<guava.version>33.7.1-jre</guava.version>
|
||||
<!-- several libraries (AWS, Google Cloud) use Apache http components transitively, and we need to align them -->
|
||||
<httpcore.version>4.4.16</httpcore.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.2</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>
|
||||
<jsr305.version>3.0.2</jsr305.version>
|
||||
<kotlin.version>2.4.10</kotlin.version>
|
||||
<kotlin.version>2.4.21</kotlin.version>
|
||||
<!-- 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.38</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.18.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.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.0</protobuf.version>
|
||||
<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>
|
||||
<slf4j.version>2.0.18</slf4j.version>
|
||||
<stripe.version>33.4.0</stripe.version>
|
||||
<swagger.version>2.2.54</swagger.version>
|
||||
<simple-grpc.version>0.3.0</simple-grpc.version>
|
||||
<slf4j.version>2.0.20</slf4j.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.9.RELEASE</webauthn4j.version>
|
||||
<webauthn4j.version>0.32.0.RELEASE</webauthn4j.version>
|
||||
|
||||
<!-- images to use in tests via testcontainers -->
|
||||
<!-- 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>
|
||||
<localstack.image>localstack/localstack:4.14@sha256:3ebc37595918b8accb852f8048fef2aff047d465167edd655528065b07bc364a</localstack.image>
|
||||
<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>
|
||||
@@ -197,17 +210,10 @@
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.opentelemetry</groupId>
|
||||
<artifactId>opentelemetry-bom</artifactId>
|
||||
<version>1.65.0</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.opentelemetry.instrumentation</groupId>
|
||||
<artifactId>opentelemetry-instrumentation-bom</artifactId>
|
||||
<version>2.31.1</version>
|
||||
<version>${opentelemetry-instrumentation.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
@@ -260,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>
|
||||
@@ -306,11 +307,6 @@
|
||||
<artifactId>jsr305</artifactId>
|
||||
<version>${jsr305.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.code.gson</groupId>
|
||||
<artifactId>gson</artifactId>
|
||||
<version>${gson.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
@@ -319,13 +315,13 @@
|
||||
<dependency>
|
||||
<groupId>com.redis</groupId>
|
||||
<artifactId>testcontainers-redis</artifactId>
|
||||
<version>2.2.4</version>
|
||||
<version>3.0.1</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.signal</groupId>
|
||||
<artifactId>libsignal-server</artifactId>
|
||||
<version>0.101.2</version>
|
||||
<version>0.108.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.signal</groupId>
|
||||
@@ -339,11 +335,6 @@
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.httpcomponents</groupId>
|
||||
<artifactId>httpcore</artifactId>
|
||||
<version>${httpcore.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.httpcomponents</groupId>
|
||||
<artifactId>httpclient</artifactId>
|
||||
@@ -447,6 +438,46 @@
|
||||
</file>
|
||||
</activation>
|
||||
</profile>
|
||||
|
||||
<profile>
|
||||
<!-- Starts pulling Testcontainers images in the background, reducing test blocks. This is primarily useful in CI,
|
||||
where images are less likely to be cached.-->
|
||||
<id>prepull-testcontainers-images</id>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
<!-- Run once for the whole reactor, rather than once per module -->
|
||||
<inherited>false</inherited>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>prepull-testcontainers-images</id>
|
||||
<phase>initialize</phase>
|
||||
<goals>
|
||||
<goal>exec</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<executable>sh</executable>
|
||||
<arguments>
|
||||
<argument>-c</argument>
|
||||
<!-- Images are pulled one at a time to limit contention with the build. If any fails, then exit status
|
||||
is non-zero, so failure is logged. -->
|
||||
<argument>status=0; for image in "$@"; do docker pull -q "$image" || status=1; done; exit $status</argument>
|
||||
<argument>sh</argument>
|
||||
<argument>${redis-cluster.image}</argument>
|
||||
<argument>${redis.image}</argument>
|
||||
<argument>${dynamodb.image}</argument>
|
||||
<argument>${localstack.image}</argument>
|
||||
</arguments>
|
||||
<async>true</async>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
</profiles>
|
||||
|
||||
<build>
|
||||
@@ -467,12 +498,12 @@
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>3.5.6</version>
|
||||
<version>3.6.1</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-failsafe-plugin</artifactId>
|
||||
<version>3.5.6</version>
|
||||
<version>3.6.1</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
@@ -492,12 +523,12 @@
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
<version>3.6.3</version>
|
||||
<version>3.7.0</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>properties-maven-plugin</artifactId>
|
||||
<version>1.3.0</version>
|
||||
<version>1.4.0</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</pluginManagement>
|
||||
@@ -538,9 +569,9 @@
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.15.0</version>
|
||||
<version>3.16.0</version>
|
||||
<configuration>
|
||||
<release>26</release>
|
||||
<release>27</release>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
@@ -580,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>
|
||||
@@ -601,7 +632,7 @@
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-install-plugin</artifactId>
|
||||
<version>3.1.4</version>
|
||||
<version>3.2.0</version>
|
||||
<configuration>
|
||||
<skip>true</skip>
|
||||
</configuration>
|
||||
@@ -610,7 +641,7 @@
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-deploy-plugin</artifactId>
|
||||
<version>3.1.4</version>
|
||||
<version>3.2.0</version>
|
||||
<configuration>
|
||||
<skip>true</skip>
|
||||
</configuration>
|
||||
|
||||
@@ -134,8 +134,6 @@ dynamoDbTables:
|
||||
tableName: Example_ProfilesV2
|
||||
pushChallenge:
|
||||
tableName: Example_PushChallenge
|
||||
pushNotificationExperimentSamples:
|
||||
tableName: Example_PushNotificationExperimentSamples
|
||||
redeemedReceipts:
|
||||
tableName: Example_RedeemedReceipts
|
||||
registrationRecovery:
|
||||
@@ -232,11 +230,6 @@ svrb:
|
||||
AAAAAAAAAAAAAAAAAAAA
|
||||
-----END CERTIFICATE-----
|
||||
|
||||
messageCache: # Redis server configuration for message store cache
|
||||
persistDelayMinutes: 1
|
||||
cluster:
|
||||
configurationUri: redis://redis.example.com:6379/
|
||||
|
||||
attachments:
|
||||
maxAttachmentUploadSizeInBytes: 1024
|
||||
maxMessageBackupUploadSizeInBytes: 1024
|
||||
@@ -262,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
|
||||
|
||||
+15
-36
@@ -14,13 +14,13 @@
|
||||
<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.10.0</firebase-admin.version>
|
||||
<libphonenumber-geocoder.version>3.38</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.0</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>2.31.1-alpha</opentelemetry-logback-appender-1.0.version>
|
||||
<opentelemetry-logback-appender-1.0.version>${opentelemetry-instrumentation.version}-alpha</opentelemetry-logback-appender-1.0.version>
|
||||
<storekit.version>5.2.0</storekit.version>
|
||||
</properties>
|
||||
|
||||
@@ -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.1</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>io.dropwizard.metrics</groupId>
|
||||
<artifactId>metrics-core</artifactId>
|
||||
@@ -240,7 +221,7 @@
|
||||
<artifactId>opentelemetry-logback-appender-1.0</artifactId>
|
||||
<version>${opentelemetry-logback-appender-1.0.version}</version>
|
||||
<exclusions>
|
||||
<!-- incubator packages aren't included in the opentelemetry BOM, and we don't use them -->
|
||||
<!-- conflicts with google-cloud-firestore; incubator packages aren't included in the opentelemetry BOM, and we don't use them -->
|
||||
<exclusion>
|
||||
<groupId>io.opentelemetry.instrumentation</groupId>
|
||||
<artifactId>opentelemetry-instrumentation-api-incubator</artifactId>
|
||||
@@ -307,7 +288,7 @@
|
||||
<version>${firebase-admin.version}</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<!-- conflicts with jackson-dataformat 2.22.1 -->
|
||||
<!-- google-cloud-storage pins 4.2.2, but jackson-dataformat-xml 2.22.x wants 4.3.0 -->
|
||||
<groupId>org.codehaus.woodstox</groupId>
|
||||
<artifactId>stax2-api</artifactId>
|
||||
</exclusion>
|
||||
@@ -315,15 +296,15 @@
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.google.code.findbugs</groupId>
|
||||
<artifactId>jsr305</artifactId>
|
||||
<!-- jackson-dataformat-xml (via firebase-admin), wants >= 4.3.0 -->
|
||||
<groupId>org.codehaus.woodstox</groupId>
|
||||
<artifactId>stax2-api</artifactId>
|
||||
<version>4.3.2</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<!-- manually resolve dependency conflict -->
|
||||
<groupId>org.codehaus.woodstox</groupId>
|
||||
<artifactId>stax2-api</artifactId>
|
||||
<version>4.3.0</version>
|
||||
<groupId>com.google.code.findbugs</groupId>
|
||||
<artifactId>jsr305</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
@@ -644,6 +625,7 @@
|
||||
<version>${apollo-api-jvm.version}</version>
|
||||
|
||||
<exclusions>
|
||||
<!-- conflicts with kotlin-stdlib -->
|
||||
<exclusion>
|
||||
<groupId>org.jetbrains</groupId>
|
||||
<artifactId>annotations</artifactId>
|
||||
@@ -661,7 +643,7 @@
|
||||
<groupId>com.squareup.okio</groupId>
|
||||
<artifactId>okio-jvm</artifactId>
|
||||
<!-- update dependabot.yml when this dependency is removed -->
|
||||
<version>3.17.0</version>
|
||||
<version>3.18.1</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
@@ -804,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>
|
||||
@@ -877,7 +856,7 @@
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>templating-maven-plugin</artifactId>
|
||||
<version>3.1.0</version>
|
||||
<version>3.2.0</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>filter-src</id>
|
||||
|
||||
-10
@@ -47,7 +47,6 @@ import org.whispersystems.textsecuregcm.configuration.KeyTransparencyServiceConf
|
||||
import org.whispersystems.textsecuregcm.configuration.LinkDeviceSecretConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.LoginPurchaseConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.MessageByteLimitCardinalityEstimatorConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.MessageCacheConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.OpenTelemetryConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.PagedSingleUseKEMPreKeyStoreConfiguration;
|
||||
@@ -190,11 +189,6 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
@JsonProperty
|
||||
private FaultTolerantRedisClusterFactory rateLimitersCluster;
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
@JsonProperty
|
||||
private MessageCacheConfiguration messageCache;
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
@@ -481,10 +475,6 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
return storageService;
|
||||
}
|
||||
|
||||
public MessageCacheConfiguration getMessageCacheConfiguration() {
|
||||
return messageCache;
|
||||
}
|
||||
|
||||
public FaultTolerantRedisClusterFactory getPushSchedulerCluster() {
|
||||
return pushSchedulerCluster;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
@@ -75,6 +76,7 @@ import org.eclipse.jetty.ee10.websocket.server.config.JettyWebSocketServletConta
|
||||
import org.eclipse.jetty.websocket.core.WebSocketExtensionRegistry;
|
||||
import org.eclipse.jetty.websocket.core.server.WebSocketServerComponents;
|
||||
import org.glassfish.jersey.server.ServerProperties;
|
||||
import org.signal.chat.require.Auth;
|
||||
import org.signal.i18n.HeaderControlledResourceBundleLookup;
|
||||
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
|
||||
import org.signal.libsignal.zkgroup.ServerSecretParams;
|
||||
@@ -175,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;
|
||||
@@ -183,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;
|
||||
@@ -192,11 +196,15 @@ 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;
|
||||
import org.whispersystems.textsecuregcm.limits.CardinalityEstimator;
|
||||
@@ -205,6 +213,7 @@ import org.whispersystems.textsecuregcm.limits.RateLimitByIpFilter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimitChallengeManager;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.mappers.BackupExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.CallNotPermittedExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.CompletionExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.DeviceLimitExceededExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.IOExceptionMapper;
|
||||
@@ -238,7 +247,6 @@ import org.whispersystems.textsecuregcm.push.ProvisioningManager;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationScheduler;
|
||||
import org.whispersystems.textsecuregcm.push.ReceiptSender;
|
||||
import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager;
|
||||
import org.whispersystems.textsecuregcm.redis.ConnectionEventLogger;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
@@ -266,7 +274,6 @@ import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.storage.FoundationDbVersion;
|
||||
import org.whispersystems.textsecuregcm.storage.IssuedReceiptsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.KeysManager;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesCache;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesDynamoDb;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesManager;
|
||||
import org.whispersystems.textsecuregcm.storage.OneTimeDonationsManager;
|
||||
@@ -326,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;
|
||||
@@ -336,7 +344,6 @@ import org.whispersystems.textsecuregcm.workers.ClearOrphanedFoundationDbQueuesC
|
||||
import org.whispersystems.textsecuregcm.workers.CopyToS3Command;
|
||||
import org.whispersystems.textsecuregcm.workers.DeleteUserCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.IdleDeviceNotificationSchedulerFactory;
|
||||
import org.whispersystems.textsecuregcm.workers.MessagePersisterServiceCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.NotifyIdleDevicesCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.ProcessScheduledJobsServiceCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.RegenerateSecondaryDynamoDbTableDataCommand;
|
||||
@@ -398,7 +405,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
bootstrap.addCommand(new SetUserDiscoverabilityCommand());
|
||||
bootstrap.addCommand(new UnlinkDeviceCommand());
|
||||
bootstrap.addCommand(new ScheduledApnPushNotificationSenderServiceCommand());
|
||||
bootstrap.addCommand(new MessagePersisterServiceCommand());
|
||||
bootstrap.addCommand(new RemoveExpiredAccountsCommand(Clock.systemUTC()));
|
||||
bootstrap.addCommand(new RemoveExpiredSandboxAccountsCommand(Clock.systemUTC()));
|
||||
bootstrap.addCommand(new SandboxAccountPoolCommand());
|
||||
@@ -562,7 +568,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
BlockingQueue<Runnable> messageDeletionQueue = new LinkedBlockingQueue<>();
|
||||
Metrics.gaugeCollectionSize(name(getClass(), "messageDeletionQueueSize"), Collections.emptyList(),
|
||||
messageDeletionQueue);
|
||||
ExecutorService messageDeletionAsyncExecutor = ExecutorServiceBuilder.of(environment, "messageDeletionAsyncExecutor")
|
||||
final ExecutorService messageDeletionAsyncExecutor = ExecutorServiceBuilder.of(environment, "messageDeletionAsyncExecutor")
|
||||
.minThreads(2)
|
||||
.maxThreads(2)
|
||||
.allowCoreThreadTimeOut(true)
|
||||
@@ -635,9 +641,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
|
||||
FaultTolerantRedisClusterClient cacheCluster = config.getCacheClusterConfiguration()
|
||||
.build("main_cache", sharedClientResources.mutate());
|
||||
FaultTolerantRedisClusterClient messagesCluster =
|
||||
config.getMessageCacheConfiguration().getRedisClusterConfiguration()
|
||||
.build("messages", sharedClientResources.mutate());
|
||||
FaultTolerantRedisClusterClient pushSchedulerCluster = config.getPushSchedulerCluster().build("push_scheduler",
|
||||
sharedClientResources.mutate());
|
||||
FaultTolerantRedisClusterClient rateLimitersCluster = config.getRateLimitersCluster().build("rate_limiters",
|
||||
@@ -729,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)
|
||||
@@ -794,8 +798,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
disconnectionRequestListenerExecutor, retryExecutor);
|
||||
ProfilesManager profilesManager = new ProfilesManager(profilesV1, profiles, profileAvatars, cacheCluster, retryExecutor, asyncCdnS3Client,
|
||||
config.getCdnConfiguration().bucket());
|
||||
MessagesCache messagesCache = new MessagesCache(messagesCluster, messageDeliveryScheduler,
|
||||
messageDeletionAsyncExecutor, retryExecutor, clock);
|
||||
final FoundationDbMessageStore foundationDbMessageStore = new FoundationDbMessageStore(messageDatabasesByEpoch,
|
||||
config.getFoundationDbMessagesConfiguration().activeEpoch(),
|
||||
new VersionstampUUIDCipher(config.getFoundationDbMessagesConfiguration().currentVersionstampCipherKey(),
|
||||
@@ -810,11 +812,9 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
Clock.systemUTC());
|
||||
ReportMessageManager reportMessageManager = new ReportMessageManager(reportMessageDynamoDb, rateLimitersCluster,
|
||||
config.getReportMessageConfiguration().getCounterTtl());
|
||||
RedisMessageAvailabilityManager redisMessageAvailabilityManager =
|
||||
new RedisMessageAvailabilityManager(messagesCluster, clientEventExecutor, asyncOperationQueueingExecutor);
|
||||
MessagesManager messagesManager =
|
||||
new MessagesManager(messagesDynamoDb, messagesCache, foundationDbMessageStore, redisMessageAvailabilityManager,
|
||||
reportMessageManager, messageDeletionAsyncExecutor, Clock.systemUTC(), experimentEnrollmentManager);
|
||||
final MessagesManager messagesManager =
|
||||
new MessagesManager(messagesDynamoDb, foundationDbMessageStore,
|
||||
reportMessageManager, messageDeletionAsyncExecutor, Clock.systemUTC());
|
||||
final ChangeNumberWaitingPeriods changeNumberWaitingPeriods = new ChangeNumberWaitingPeriods(
|
||||
config.getDynamoDbTables().getChangeNumberWaitingPeriods().getTableName(), dynamoDbClient);
|
||||
final ChangeNumberWaitingPeriodManager changeNumberWaitingPeriodManager = new ChangeNumberWaitingPeriodManager(
|
||||
@@ -942,7 +942,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
environment.lifecycle().manage(pushNotificationScheduler);
|
||||
environment.lifecycle().manage(provisioningManager);
|
||||
environment.lifecycle().manage(disconnectionRequestManager);
|
||||
environment.lifecycle().manage(redisMessageAvailabilityManager);
|
||||
environment.lifecycle().manage(currencyManager);
|
||||
environment.lifecycle().manage(registrationServiceClient);
|
||||
environment.lifecycle().manage(keyTransparencyServiceClient);
|
||||
@@ -1105,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();
|
||||
@@ -1120,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(),
|
||||
@@ -1141,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),
|
||||
@@ -1151,9 +1152,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
new PaymentsGrpcService(currencyManager),
|
||||
new ChallengeGrpcService(accountsManager, rateLimitChallengeManager, challengeConstraintChecker),
|
||||
new DonationsGrpcService(clock, zkReceiptOperations, redeemedReceiptsManager, accountsManager, config.getBadges(), ReceiptCredentialPresentation::new, donationPermitsManager, rateLimiters),
|
||||
new ProductConfigurationGrpcService(config.getSubscription(), config.getOneTimeDonations(),
|
||||
config.getLoginPurchase(), List.of(stripeManager, braintreeManager),
|
||||
config.getBackupConfiguration().maxTotalMediaSize()),
|
||||
new RemoteConfigurationGrpcService(remoteConfigsManager, profileBadgeConverter,
|
||||
config.getBadges().getBadges().stream()
|
||||
.map(BadgeConfiguration::getId)
|
||||
@@ -1164,6 +1162,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
validatingInterceptor,
|
||||
errorMappingInterceptor,
|
||||
errorConformanceInterceptor,
|
||||
grpcCompressionInterceptor,
|
||||
grpcAllowListInterceptor,
|
||||
remoteDeprecationFilter,
|
||||
metricServerInterceptor,
|
||||
@@ -1177,12 +1176,16 @@ 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())),
|
||||
new CredentialsAnonymousGrpcService(accountsManager, ExternalServiceDefinitions.SVR.generatorFactory().apply(config, Clock.systemUTC()), rateLimiters),
|
||||
new SubscriptionsGrpcService(clock, config.getSubscription(), subscriptionManager, donationPermitsManager,
|
||||
stripeManager, braintreeManager, googlePlayBillingManager, appleAppStoreManager, bankMandateTranslator),
|
||||
new ProductConfigurationGrpcService(config.getSubscription(), config.getOneTimeDonations(),
|
||||
config.getLoginPurchase(), List.of(stripeManager, braintreeManager),
|
||||
config.getBackupConfiguration().maxTotalMediaSize()),
|
||||
new OneTimeDonationsGrpcService(config.getOneTimeDonations(), stripeManager, braintreeManager,
|
||||
payPalDonationsTranslator, oneTimeDonationsManager, issuedReceiptsManager,
|
||||
zkReceiptOperations, clock, rateLimiters, donationPermitsManager))
|
||||
@@ -1193,6 +1196,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
validatingInterceptor,
|
||||
errorMappingInterceptor,
|
||||
errorConformanceInterceptor,
|
||||
grpcCompressionInterceptor,
|
||||
grpcAllowListInterceptor,
|
||||
remoteDeprecationFilter,
|
||||
metricServerInterceptor,
|
||||
@@ -1201,15 +1205,21 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
concurrentCallLimitingInterceptor))
|
||||
.toList();
|
||||
|
||||
final ManagedEventLoopGroup<DefaultEventLoopGroup> omnibusLocalEventLoopGroup = new ManagedEventLoopGroup<>(new DefaultEventLoopGroup());
|
||||
final ManagedEventLoopGroup<NioEventLoopGroup> omnibusNioEventLoopGroup = new ManagedEventLoopGroup<>(new NioEventLoopGroup());
|
||||
verifyServiceAuth(authenticatedServices, Auth.AUTH_ONLY_AUTHENTICATED);
|
||||
verifyServiceAuth(unauthenticatedServices, Auth.AUTH_ONLY_ANONYMOUS);
|
||||
|
||||
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());
|
||||
@@ -1219,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(),
|
||||
@@ -1231,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());
|
||||
@@ -1284,13 +1296,13 @@ 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));
|
||||
webSocketEnvironment.jersey().register(MultiRecipientMessageProvider.class);
|
||||
webSocketEnvironment.jersey().register(new MetricsApplicationEventListener(TrafficSource.WEBSOCKET, clientReleaseManager));
|
||||
webSocketEnvironment.jersey().register(new KeepAliveController(redisMessageAvailabilityManager));
|
||||
webSocketEnvironment.jersey().register(new KeepAliveController());
|
||||
webSocketEnvironment.jersey().register(new TimestampResponseFilter());
|
||||
|
||||
final PersistentTimer persistentTimer = new PersistentTimer(rateLimitersCluster, clock);
|
||||
@@ -1352,9 +1364,11 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
webSocketEnvironment.getRequestLog(), Duration.ofMillis(60000));
|
||||
provisioningEnvironment.setConnectListener(new ProvisioningConnectListener(provisioningManager, asnInfoProviderSupplier, clientReleaseManager, provisioningWebsocketTimeoutExecutor, Duration.ofSeconds(90)));
|
||||
provisioningEnvironment.jersey().register(new MetricsApplicationEventListener(TrafficSource.WEBSOCKET, clientReleaseManager));
|
||||
provisioningEnvironment.jersey().register(new KeepAliveController(redisMessageAvailabilityManager));
|
||||
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);
|
||||
@@ -1400,6 +1414,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
List.of(
|
||||
new LoggingUnhandledExceptionMapper(),
|
||||
new CompletionExceptionMapper(),
|
||||
new CallNotPermittedExceptionMapper(),
|
||||
new IOExceptionMapper(),
|
||||
new RateLimitExceededExceptionMapper(),
|
||||
new InvalidWebsocketAddressExceptionMapper(),
|
||||
@@ -1422,6 +1437,16 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
});
|
||||
}
|
||||
|
||||
private static void verifyServiceAuth(final List<ServerServiceDefinition> services, final Auth expectedAuthType) {
|
||||
for (final ServerServiceDefinition service : services) {
|
||||
final Auth authType = ValidatorUtils.serviceAuthExtensionValue(service).orElse(Auth.AUTH_UNSPECIFIED);
|
||||
if (!authType.equals(expectedAuthType)) {
|
||||
throw new IllegalStateException("gRPC service %s is annotated with %s but was registered as %s"
|
||||
.formatted(service.getServiceDescriptor().getName(), authType, expectedAuthType));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static class ExecutorServiceBuilder extends io.dropwizard.lifecycle.setup.ExecutorServiceBuilder {
|
||||
private final String baseName;
|
||||
|
||||
|
||||
@@ -24,6 +24,7 @@ import java.util.Optional;
|
||||
import java.util.TreeMap;
|
||||
import java.util.zip.GZIPInputStream;
|
||||
import javax.annotation.Nonnull;
|
||||
import com.google.common.net.InetAddresses;
|
||||
import org.apache.commons.csv.CSVFormat;
|
||||
import org.apache.commons.csv.CSVParser;
|
||||
import org.apache.commons.csv.CSVRecord;
|
||||
@@ -74,8 +75,8 @@ public class AsnInfoProviderImpl implements AsnInfoProvider {
|
||||
for (final CSVRecord record : csvParser) {
|
||||
// format:
|
||||
// range_start_ip_string range_end_ip_string AS_number country_code AS_description
|
||||
final InetAddress startIp = InetAddress.getByName(record.get(0));
|
||||
final InetAddress endIp = InetAddress.getByName(record.get(1));
|
||||
final InetAddress startIp = InetAddresses.forString(record.get(0));
|
||||
final InetAddress endIp = InetAddresses.forString(record.get(1));
|
||||
final long asn = Long.parseLong(record.get(2));
|
||||
final String regionCode = record.get(3);
|
||||
// country code should be the same for any ASN, so we're caching AsnInfo objects
|
||||
@@ -123,7 +124,7 @@ public class AsnInfoProviderImpl implements AsnInfoProvider {
|
||||
@Override
|
||||
public Optional<AsnInfo> lookup(@Nonnull final String ipString) {
|
||||
try {
|
||||
final InetAddress address = InetAddress.getByName(ipString);
|
||||
final InetAddress address = InetAddresses.forString(ipString);
|
||||
if (address instanceof Inet4Address ip4) {
|
||||
final Long key = ip4BytesToLong(ip4);
|
||||
return lookupInMap(asnBlocksByFirstIpv4, key);
|
||||
|
||||
+4
-1
@@ -10,6 +10,7 @@ import org.whispersystems.textsecuregcm.auth.JwtGenerator;
|
||||
import org.whispersystems.textsecuregcm.util.HeaderUtils;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.util.Base64;
|
||||
import java.util.Map;
|
||||
|
||||
@@ -19,15 +20,17 @@ public class TusAttachmentGenerator implements AttachmentGenerator {
|
||||
|
||||
private final JwtGenerator jwtGenerator;
|
||||
private final String tusUri;
|
||||
private final Duration tokenExpiration;
|
||||
|
||||
public TusAttachmentGenerator(final TusConfiguration cfg) {
|
||||
this.tusUri = cfg.uploadUri();
|
||||
this.tokenExpiration = cfg.tokenExpiration();
|
||||
this.jwtGenerator = new JwtGenerator(cfg.userAuthenticationTokenSharedSecret().value(), Clock.systemUTC());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Descriptor generateAttachment(final String key, final long uploadLength) {
|
||||
final String token = jwtGenerator.generateJwt(ATTACHMENTS, key,
|
||||
final String token = jwtGenerator.generateJwt(ATTACHMENTS, key, tokenExpiration,
|
||||
builder -> builder.withClaim(JwtGenerator.MAX_LENGTH_CLAIM_KEY, uploadLength));
|
||||
final String b64Key = Base64.getEncoder().encodeToString(key.getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
|
||||
+19
-3
@@ -5,11 +5,27 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.attachments;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import jakarta.validation.constraints.Positive;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import java.time.Duration;
|
||||
import org.hibernate.validator.constraints.time.DurationMin;
|
||||
import org.whispersystems.textsecuregcm.configuration.secrets.SecretBytes;
|
||||
import org.whispersystems.textsecuregcm.util.ExactlySize;
|
||||
|
||||
public record TusConfiguration(
|
||||
@ExactlySize(32) SecretBytes userAuthenticationTokenSharedSecret,
|
||||
@NotEmpty String uploadUri){}
|
||||
@ExactlySize(32) SecretBytes userAuthenticationTokenSharedSecret,
|
||||
@NotEmpty String uploadUri,
|
||||
// The TUS server enforces its own `MAX_TOKEN_AGE`, so this must be greater than or equal to it.
|
||||
// https://github.com/signalapp/tus-server/tree/main/src/index.ts
|
||||
@NotNull @DurationMin(days = 7) Duration tokenExpiration){
|
||||
|
||||
@VisibleForTesting
|
||||
public static final Duration DEFAULT_TOKEN_EXPIRATION = Duration.ofDays(7);
|
||||
|
||||
public TusConfiguration {
|
||||
if (tokenExpiration == null) {
|
||||
tokenExpiration = DEFAULT_TOKEN_EXPIRATION;
|
||||
}
|
||||
}
|
||||
}
|
||||
+10
-6
@@ -6,6 +6,7 @@
|
||||
package org.whispersystems.textsecuregcm.auth;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import io.github.resilience4j.circuitbreaker.CallNotPermittedException;
|
||||
import io.netty.resolver.dns.DnsNameResolver;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import java.io.IOException;
|
||||
@@ -14,10 +15,8 @@ import java.net.URI;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.time.Duration;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import javax.annotation.Nullable;
|
||||
@@ -27,7 +26,6 @@ import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfigurati
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.http.FaultTolerantHttpClient;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
|
||||
public class CloudflareTurnCredentialsManager {
|
||||
@@ -133,10 +131,16 @@ public class CloudflareTurnCredentialsManager {
|
||||
|
||||
final HttpResponse<String> response;
|
||||
try {
|
||||
response = cloudflareTurnClient.sendAsync(getCredentialsRequest, HttpResponse.BodyHandlers.ofString()).join();
|
||||
} catch (CompletionException e) {
|
||||
response = cloudflareTurnClient.send(getCredentialsRequest, HttpResponse.BodyHandlers.ofString());
|
||||
} catch (Exception e) {
|
||||
|
||||
if (e instanceof CallNotPermittedException cnpe) {
|
||||
// the circuit breaker is open, and this can escape up to the exception mapper
|
||||
throw cnpe;
|
||||
}
|
||||
|
||||
logger.warn("failed to make http request to Cloudflare Turn: {}", e.getMessage());
|
||||
throw new IOException(ExceptionUtils.unwrap(e));
|
||||
throw new IOException(e);
|
||||
}
|
||||
|
||||
if (response.statusCode() != Response.Status.CREATED.getStatusCode()) {
|
||||
|
||||
+16
-17
@@ -27,7 +27,6 @@ import java.util.concurrent.ScheduledExecutorService;
|
||||
import javax.annotation.Nullable;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantPubSubConnection;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient;
|
||||
@@ -120,10 +119,6 @@ public class DisconnectionRequestManager extends RedisPubSubAdapter<byte[], byte
|
||||
|
||||
/**
|
||||
* Adds a listener for disconnection requests for a specific authenticated device.
|
||||
*
|
||||
* @param accountIdentifier TODO
|
||||
* @param deviceId TODO
|
||||
* @param listener the listener to register
|
||||
*/
|
||||
public void addListener(final UUID accountIdentifier, final byte deviceId, final DisconnectionRequestListener listener) {
|
||||
listeners.compute(new AccountIdentifierAndDeviceId(accountIdentifier, deviceId), (_, existingListeners) -> {
|
||||
@@ -138,10 +133,6 @@ public class DisconnectionRequestManager extends RedisPubSubAdapter<byte[], byte
|
||||
|
||||
/**
|
||||
* Removes a listener for disconnection requests for a specific authenticated device.
|
||||
*
|
||||
* @param accountIdentifier TODO
|
||||
* @param deviceId TODO
|
||||
* @param listener the listener to remove
|
||||
*/
|
||||
public void removeListener(final UUID accountIdentifier, final byte deviceId, final DisconnectionRequestListener listener) {
|
||||
listeners.computeIfPresent(new AccountIdentifierAndDeviceId(accountIdentifier, deviceId), (_, existingListeners) -> {
|
||||
@@ -218,14 +209,22 @@ public class DisconnectionRequestManager extends RedisPubSubAdapter<byte[], byte
|
||||
}
|
||||
|
||||
deviceIds.forEach(deviceId -> {
|
||||
listeners.getOrDefault(new AccountIdentifierAndDeviceId(accountIdentifier, deviceId), Collections.emptyList())
|
||||
.forEach(listener -> listenerEventExecutor.execute(() -> {
|
||||
try {
|
||||
listener.handleDisconnectionRequest();
|
||||
} catch (final Exception e) {
|
||||
logger.warn("Listener failed to handle disconnection request", e);
|
||||
}
|
||||
}));
|
||||
final ArrayList<DisconnectionRequestListener> listenersForDevice = new ArrayList<>();
|
||||
|
||||
// This is a little weird, but it's a thread-safe way to get an immutable copy of the list of listeners for a
|
||||
// given device
|
||||
listeners.computeIfPresent(new AccountIdentifierAndDeviceId(accountIdentifier, deviceId), (_, existingListeners) -> {
|
||||
listenersForDevice.addAll(existingListeners);
|
||||
return existingListeners;
|
||||
});
|
||||
|
||||
listenersForDevice.forEach(listener -> listenerEventExecutor.execute(() -> {
|
||||
try {
|
||||
listener.handleDisconnectionRequest();
|
||||
} catch (final Exception e) {
|
||||
logger.warn("Listener failed to handle disconnection request", e);
|
||||
}
|
||||
}));
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import com.auth0.jwt.JWT;
|
||||
import com.auth0.jwt.JWTCreator;
|
||||
import com.auth0.jwt.algorithms.Algorithm;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
@@ -27,12 +28,13 @@ public class JwtGenerator {
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
public String generateJwt(final String audience, final String subject, Consumer<JWTCreator.Builder> claimCustomizer) {
|
||||
public String generateJwt(final String audience, final String subject, final Duration expiration, Consumer<JWTCreator.Builder> claimCustomizer) {
|
||||
final Instant now = clock.instant();
|
||||
JWTCreator.Builder builder = JWT.create()
|
||||
.withAudience(audience)
|
||||
.withSubject(subject)
|
||||
.withIssuedAt(now);
|
||||
.withIssuedAt(now)
|
||||
.withExpiresAt(now.plus(expiration));
|
||||
claimCustomizer.accept(builder);
|
||||
return builder.sign(algorithm);
|
||||
}
|
||||
|
||||
+9
-7
@@ -5,25 +5,27 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.backup;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.util.Base64;
|
||||
import java.util.Map;
|
||||
import org.apache.http.HttpHeaders;
|
||||
import org.whispersystems.textsecuregcm.attachments.TusConfiguration;
|
||||
import org.whispersystems.textsecuregcm.auth.JwtGenerator;
|
||||
import org.whispersystems.textsecuregcm.util.HeaderUtils;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Clock;
|
||||
import java.util.Base64;
|
||||
import java.util.Map;
|
||||
|
||||
public class Cdn3BackupCredentialGenerator {
|
||||
public static final String CDN_PATH = "backups";
|
||||
public static final int BACKUP_CDN = 3;
|
||||
|
||||
private final String tusUri;
|
||||
private final Duration tokenExpiration;
|
||||
private final JwtGenerator jwtGenerator;
|
||||
|
||||
public Cdn3BackupCredentialGenerator(final TusConfiguration cfg) {
|
||||
this.tusUri = cfg.uploadUri();
|
||||
this.tokenExpiration = cfg.tokenExpiration();
|
||||
this.jwtGenerator = new JwtGenerator(cfg.userAuthenticationTokenSharedSecret().value(), Clock.systemUTC());
|
||||
}
|
||||
|
||||
@@ -32,7 +34,7 @@ public class Cdn3BackupCredentialGenerator {
|
||||
throw new IllegalArgumentException("Upload descriptors must have non-empty keys");
|
||||
}
|
||||
|
||||
final String token = jwtGenerator.generateJwt(CDN_PATH, key, builder -> builder
|
||||
final String token = jwtGenerator.generateJwt(CDN_PATH, key, tokenExpiration, builder -> builder
|
||||
.withClaim(JwtGenerator.MAX_LENGTH_CLAIM_KEY, uploadSize)
|
||||
.withClaim(JwtGenerator.SCOPE_CLAIM_KEY, "write"));
|
||||
|
||||
@@ -53,7 +55,7 @@ public class Cdn3BackupCredentialGenerator {
|
||||
throw new IllegalArgumentException("Backup subdir name must be non-empty");
|
||||
}
|
||||
|
||||
final String token = jwtGenerator.generateJwt(CDN_PATH, hashedBackupId, builder -> builder
|
||||
final String token = jwtGenerator.generateJwt(CDN_PATH, hashedBackupId, tokenExpiration, builder -> builder
|
||||
.withClaim(JwtGenerator.SCOPE_CLAIM_KEY, "read"));
|
||||
return Map.of(HttpHeaders.AUTHORIZATION, HeaderUtils.bearerAuthHeader(token));
|
||||
}
|
||||
|
||||
+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) {
|
||||
|
||||
-9
@@ -68,7 +68,6 @@ public class DynamoDbTables {
|
||||
private final Table profiles;
|
||||
private final Table profilesV2;
|
||||
private final Table pushChallenge;
|
||||
private final Table pushNotificationExperimentSamples;
|
||||
private final Table redeemedReceipts;
|
||||
private final TableWithExpiration registrationRecovery;
|
||||
private final Table remoteConfig;
|
||||
@@ -100,7 +99,6 @@ public class DynamoDbTables {
|
||||
@JsonProperty("profiles") final Table profiles,
|
||||
@JsonProperty("profilesV2") final Table profilesV2,
|
||||
@JsonProperty("pushChallenge") final Table pushChallenge,
|
||||
@JsonProperty("pushNotificationExperimentSamples") final Table pushNotificationExperimentSamples,
|
||||
@JsonProperty("redeemedReceipts") final Table redeemedReceipts,
|
||||
@JsonProperty("registrationRecovery") final TableWithExpiration registrationRecovery,
|
||||
@JsonProperty("remoteConfig") final Table remoteConfig,
|
||||
@@ -131,7 +129,6 @@ public class DynamoDbTables {
|
||||
this.profiles = profiles;
|
||||
this.profilesV2 = profilesV2;
|
||||
this.pushChallenge = pushChallenge;
|
||||
this.pushNotificationExperimentSamples = pushNotificationExperimentSamples;
|
||||
this.redeemedReceipts = redeemedReceipts;
|
||||
this.registrationRecovery = registrationRecovery;
|
||||
this.remoteConfig = remoteConfig;
|
||||
@@ -268,12 +265,6 @@ public class DynamoDbTables {
|
||||
return pushChallenge;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
public Table getPushNotificationExperimentSamples() {
|
||||
return pushNotificationExperimentSamples;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
public Table getRedeemedReceipts() {
|
||||
|
||||
+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;
|
||||
|
||||
-29
@@ -1,29 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2020 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
|
||||
public class MessageCacheConfiguration {
|
||||
|
||||
@JsonProperty
|
||||
@NotNull
|
||||
@Valid
|
||||
private FaultTolerantRedisClusterFactory cluster;
|
||||
|
||||
@JsonProperty
|
||||
private int persistDelayMinutes = 10;
|
||||
|
||||
public FaultTolerantRedisClusterFactory getRedisClusterConfiguration() {
|
||||
return cluster;
|
||||
}
|
||||
|
||||
public int getPersistDelayMinutes() {
|
||||
return persistDelayMinutes;
|
||||
}
|
||||
}
|
||||
+14
-6
@@ -43,11 +43,11 @@ public class DynamicConfiguration {
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
DynamicMessagePersisterConfiguration messagePersister = new DynamicMessagePersisterConfiguration();
|
||||
DynamicMessageDeliveryConfiguration messageDelivery = new DynamicMessageDeliveryConfiguration();
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
DynamicMessageDeliveryConfiguration messageDelivery = new DynamicMessageDeliveryConfiguration();
|
||||
DynamicNotificationConfiguration notifications = DynamicNotificationConfiguration.DEFAULT;
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
@@ -77,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,14 +119,14 @@ public class DynamicConfiguration {
|
||||
return captcha;
|
||||
}
|
||||
|
||||
public DynamicMessagePersisterConfiguration getMessagePersisterConfiguration() {
|
||||
return messagePersister;
|
||||
}
|
||||
|
||||
public DynamicMessageDeliveryConfiguration getMessageDeliveryConfiguration() {
|
||||
return messageDelivery;
|
||||
}
|
||||
|
||||
public DynamicNotificationConfiguration getNotificationConfiguration() {
|
||||
return notifications;
|
||||
}
|
||||
|
||||
public DynamicRegistrationConfiguration getRegistrationConfiguration() {
|
||||
return registrationConfiguration;
|
||||
}
|
||||
@@ -151,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());
|
||||
}
|
||||
}
|
||||
+7
@@ -12,7 +12,14 @@ public class DynamicMessageDeliveryConfiguration {
|
||||
@JsonProperty
|
||||
private boolean readOnly = false;
|
||||
|
||||
@JsonProperty
|
||||
private boolean dropEphemeralMessages = false;
|
||||
|
||||
public boolean isReadOnly() {
|
||||
return readOnly;
|
||||
}
|
||||
|
||||
public boolean dropEphemeralMessages() {
|
||||
return dropEphemeralMessages;
|
||||
}
|
||||
}
|
||||
-58
@@ -1,58 +0,0 @@
|
||||
/*
|
||||
* Copyright 2022 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration.dynamic;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import java.time.Duration;
|
||||
|
||||
public class DynamicMessagePersisterConfiguration {
|
||||
|
||||
@JsonProperty
|
||||
private boolean persistenceEnabled = true;
|
||||
|
||||
/**
|
||||
* If we have to trim a client's persisted queue to make room to persist from Redis to DynamoDB, how much extra room should we make
|
||||
*/
|
||||
@JsonProperty
|
||||
private double trimOversizedQueueExtraRoomRatio = 1.5;
|
||||
|
||||
@JsonProperty
|
||||
private Duration nodeClaimTtl = Duration.ofMinutes(5);
|
||||
|
||||
@JsonProperty
|
||||
private Duration sleepBetweenNodes = Duration.ofSeconds(5);
|
||||
|
||||
public DynamicMessagePersisterConfiguration() {}
|
||||
|
||||
@VisibleForTesting
|
||||
public DynamicMessagePersisterConfiguration(final boolean persistenceEnabled,
|
||||
final double trimOversizedQueueExtraRoomRatio,
|
||||
final Duration nodeClaimTtl,
|
||||
final Duration sleepBetweenNodes) {
|
||||
|
||||
this.persistenceEnabled = persistenceEnabled;
|
||||
this.trimOversizedQueueExtraRoomRatio = trimOversizedQueueExtraRoomRatio;
|
||||
this.nodeClaimTtl = nodeClaimTtl;
|
||||
this.sleepBetweenNodes = sleepBetweenNodes;
|
||||
}
|
||||
|
||||
public boolean isPersistenceEnabled() {
|
||||
return persistenceEnabled;
|
||||
}
|
||||
|
||||
public double getTrimOversizedQueueExtraRoomRatio() {
|
||||
return trimOversizedQueueExtraRoomRatio;
|
||||
}
|
||||
|
||||
public Duration getNodeClaimTtl() {
|
||||
return nodeClaimTtl;
|
||||
}
|
||||
|
||||
public Duration getSleepBetweenNodes() {
|
||||
return sleepBetweenNodes;
|
||||
}
|
||||
}
|
||||
+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);
|
||||
}
|
||||
+19
-1
@@ -38,7 +38,9 @@ import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
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;
|
||||
@@ -97,6 +99,7 @@ public class AccountController {
|
||||
@Path("/gcm/")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@ManagedAsync
|
||||
public void setGcmRegistrationId(@Auth AuthenticatedDevice auth,
|
||||
@NotNull @Valid GcmRegistrationId registrationId) {
|
||||
|
||||
@@ -118,6 +121,7 @@ public class AccountController {
|
||||
|
||||
@DELETE
|
||||
@Path("/gcm/")
|
||||
@ManagedAsync
|
||||
public void deleteGcmRegistrationId(@Auth AuthenticatedDevice auth) {
|
||||
accounts.updateDevice(auth.accountIdentifier(), auth.deviceId(), d -> {
|
||||
d.setGcmId(null);
|
||||
@@ -130,6 +134,7 @@ public class AccountController {
|
||||
@Path("/apn/")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@ManagedAsync
|
||||
public void setApnRegistrationId(@Auth AuthenticatedDevice auth,
|
||||
@NotNull @Valid ApnRegistrationId registrationId) {
|
||||
|
||||
@@ -144,6 +149,7 @@ public class AccountController {
|
||||
|
||||
@DELETE
|
||||
@Path("/apn/")
|
||||
@ManagedAsync
|
||||
public void deleteApnRegistrationId(@Auth AuthenticatedDevice auth) {
|
||||
accounts.updateDevice(auth.accountIdentifier(), auth.deviceId(), d -> {
|
||||
d.setApnId(null);
|
||||
@@ -155,6 +161,7 @@ public class AccountController {
|
||||
@PUT
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/registration_lock")
|
||||
@ManagedAsync
|
||||
public void setRegistrationLock(@Auth AuthenticatedDevice auth, @NotNull @Valid RegistrationLock accountLock) {
|
||||
final SaltedTokenHash credentials = SaltedTokenHash.generateFor(accountLock.registrationLock());
|
||||
|
||||
@@ -168,6 +175,7 @@ public class AccountController {
|
||||
|
||||
@DELETE
|
||||
@Path("/registration_lock")
|
||||
@ManagedAsync
|
||||
public void removeRegistrationLock(@Auth AuthenticatedDevice auth) {
|
||||
accounts.update(auth.accountIdentifier(), a -> a.setRegistrationLock(null, null));
|
||||
}
|
||||
@@ -183,6 +191,7 @@ public class AccountController {
|
||||
@ApiResponse(responseCode = "204", description = "Device name changed successfully")
|
||||
@ApiResponse(responseCode = "404", description = "No device found with the given ID")
|
||||
@ApiResponse(responseCode = "403", description = "Not authorized to change the name of the device with the given ID")
|
||||
@ManagedAsync
|
||||
public void setName(@Auth final AuthenticatedDevice auth,
|
||||
@NotNull @Valid final DeviceName deviceName,
|
||||
|
||||
@@ -214,6 +223,7 @@ public class AccountController {
|
||||
@Path("/attributes/")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@ManagedAsync
|
||||
public void setAccountAttributes(
|
||||
@Auth AuthenticatedDevice auth,
|
||||
@HeaderParam(HeaderUtils.X_SIGNAL_AGENT) String signalAgent,
|
||||
@@ -260,6 +270,7 @@ public class AccountController {
|
||||
@GET
|
||||
@Path("/whoami")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@ManagedAsync
|
||||
public AccountIdentityResponse whoAmI(@Auth final AuthenticatedDevice auth) {
|
||||
final Account account = accounts.getByAccountIdentifier(auth.accountIdentifier())
|
||||
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
|
||||
@@ -278,6 +289,7 @@ public class AccountController {
|
||||
)
|
||||
@ApiResponse(responseCode = "204", description = "Username successfully deleted.", useReturnTypeSchema = true)
|
||||
@ApiResponse(responseCode = "401", description = "Account authentication check failed.")
|
||||
@ManagedAsync
|
||||
public void deleteUsernameHash(@Auth final AuthenticatedDevice auth) {
|
||||
accounts.clearUsernameHash(auth.accountIdentifier());
|
||||
}
|
||||
@@ -298,6 +310,7 @@ public class AccountController {
|
||||
@ApiResponse(responseCode = "409", description = "All username hashes from the list are taken.")
|
||||
@ApiResponse(responseCode = "422", description = "Invalid request format.")
|
||||
@ApiResponse(responseCode = "429", description = "Ratelimited.")
|
||||
@ManagedAsync
|
||||
public ReserveUsernameHashResponse reserveUsernameHash(
|
||||
@Auth final AuthenticatedDevice auth,
|
||||
@NotNull @Valid final ReserveUsernameHashRequest usernameRequest) throws RateLimitExceededException {
|
||||
@@ -337,13 +350,14 @@ public class AccountController {
|
||||
@ApiResponse(responseCode = "410", description = "Username hash not available (username can't be used).")
|
||||
@ApiResponse(responseCode = "422", description = "Invalid request format.")
|
||||
@ApiResponse(responseCode = "429", description = "Ratelimited.")
|
||||
@ManagedAsync
|
||||
public UsernameHashResponse confirmUsernameHash(
|
||||
@Auth final AuthenticatedDevice auth,
|
||||
@NotNull @Valid final ConfirmUsernameHashRequest confirmRequest) throws RateLimitExceededException {
|
||||
|
||||
try {
|
||||
usernameHashZkProofVerifier.verifyProof(confirmRequest.zkProof(), confirmRequest.usernameHash());
|
||||
} catch (final BaseUsernameException e) {
|
||||
} catch (final BaseUsernameException | InvalidInputException e) {
|
||||
throw new WebApplicationException(Response.status(422).build());
|
||||
}
|
||||
|
||||
@@ -417,6 +431,7 @@ public class AccountController {
|
||||
@ApiResponse(responseCode = "409", description = "Username is not set for the account.")
|
||||
@ApiResponse(responseCode = "422", description = "Invalid request format.")
|
||||
@ApiResponse(responseCode = "429", description = "Ratelimited.")
|
||||
@ManagedAsync
|
||||
public UsernameLinkHandle updateUsernameLink(
|
||||
@Auth final AuthenticatedDevice auth,
|
||||
@NotNull @Valid final EncryptedUsername encryptedUsername) throws RateLimitExceededException {
|
||||
@@ -454,6 +469,7 @@ public class AccountController {
|
||||
@ApiResponse(responseCode = "204", description = "Username Link successfully deleted.", useReturnTypeSchema = true)
|
||||
@ApiResponse(responseCode = "401", description = "Account authentication check failed.")
|
||||
@ApiResponse(responseCode = "429", description = "Ratelimited.")
|
||||
@ManagedAsync
|
||||
public void deleteUsernameLink(@Auth final AuthenticatedDevice auth) throws RateLimitExceededException {
|
||||
// check ratelimiter for username link operations
|
||||
rateLimiters.forDescriptor(RateLimiters.For.USERNAME_LINK_OPERATION).validate(auth.accountIdentifier());
|
||||
@@ -503,6 +519,7 @@ public class AccountController {
|
||||
@HEAD
|
||||
@Path("/account/{identifier}")
|
||||
@RateLimitedByIp(RateLimiters.For.CHECK_ACCOUNT_EXISTENCE)
|
||||
@ManagedAsync
|
||||
public Response accountExists(
|
||||
@Auth final Optional<AuthenticatedDevice> authenticatedAccount,
|
||||
|
||||
@@ -519,6 +536,7 @@ public class AccountController {
|
||||
|
||||
@DELETE
|
||||
@Path("/me")
|
||||
@ManagedAsync
|
||||
public void deleteAccount(@Auth AuthenticatedDevice auth) {
|
||||
accounts.delete(auth.accountIdentifier(), AccountsManager.DeletionReason.USER_REQUEST);
|
||||
}
|
||||
|
||||
+4
@@ -33,6 +33,7 @@ import java.io.IOException;
|
||||
import java.time.Instant;
|
||||
import java.util.UUID;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.glassfish.jersey.server.ManagedAsync;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.ChangesPhoneNumber;
|
||||
import org.whispersystems.textsecuregcm.auth.InvalidRegistrationSessionException;
|
||||
@@ -84,6 +85,7 @@ public class AccountControllerV2 {
|
||||
@ApiResponse(responseCode = "429", description = "Too many attempts", headers = @Header(
|
||||
name = "Retry-After",
|
||||
description = "If present, a positive integer indicating the number of seconds before a subsequent attempt could succeed"))
|
||||
@ManagedAsync
|
||||
public AccountIdentityResponse changeNumber(@Auth final AuthenticatedDevice authenticatedDevice,
|
||||
@NotNull @Valid final ChangeNumberRequest request,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgentString,
|
||||
@@ -151,6 +153,7 @@ public class AccountControllerV2 {
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Operation(summary = "Sets whether the account should be discoverable by phone number in the directory.")
|
||||
@ApiResponse(responseCode = "204", description = "The setting was successfully updated.")
|
||||
@ManagedAsync
|
||||
public void setPhoneNumberDiscoverability(
|
||||
@Auth AuthenticatedDevice auth,
|
||||
@NotNull @Valid PhoneNumberDiscoverabilityRequest phoneNumberDiscoverability) {
|
||||
@@ -171,6 +174,7 @@ public class AccountControllerV2 {
|
||||
@ApiResponse(responseCode = "200",
|
||||
description = "Response with data report. A plain text representation is a field in the response.",
|
||||
useReturnTypeSchema = true)
|
||||
@ManagedAsync
|
||||
public AccountDataReportResponse getAccountDataReport(@Auth final AuthenticatedDevice auth) {
|
||||
|
||||
final Account account = accountsManager.getByAccountIdentifier(auth.accountIdentifier())
|
||||
|
||||
+12
-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,9 +25,9 @@ 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;
|
||||
import org.whispersystems.textsecuregcm.attachments.AttachmentGenerator;
|
||||
import org.whispersystems.textsecuregcm.attachments.AttachmentUtil;
|
||||
import org.whispersystems.textsecuregcm.attachments.GcsAttachmentGenerator;
|
||||
@@ -99,33 +97,31 @@ public class AttachmentControllerV4 {
|
||||
@ApiResponse(responseCode = "429", description = "Too many attempts", headers = @Header(
|
||||
name = "Retry-After",
|
||||
description = "If present, an positive integer indicating the number of seconds before a subsequent attempt could succeed"))
|
||||
@ManagedAsync
|
||||
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);
|
||||
|
||||
|
||||
+2
@@ -14,6 +14,7 @@ import jakarta.ws.rs.QueryParam;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import org.glassfish.jersey.server.ManagedAsync;
|
||||
import org.signal.libsignal.protocol.ServiceId;
|
||||
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
@@ -55,6 +56,7 @@ public class CallLinkController {
|
||||
@ApiResponse(responseCode = "401", description = "Account authentication check failed.")
|
||||
@ApiResponse(responseCode = "422", description = "Invalid request format.")
|
||||
@ApiResponse(responseCode = "429", description = "Ratelimited.")
|
||||
@ManagedAsync
|
||||
public CreateCallLinkCredential getCreateAuth(
|
||||
final @Auth AuthenticatedDevice auth,
|
||||
final @NotNull @Valid GetCreateCallLinkCredentialsRequest request,
|
||||
|
||||
+2
@@ -18,6 +18,7 @@ import jakarta.ws.rs.Produces;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
import org.glassfish.jersey.server.ManagedAsync;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.CloudflareTurnCredentialsManager;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
@@ -54,6 +55,7 @@ public class CallRoutingControllerV2 {
|
||||
@ApiResponse(responseCode = "401", description = "Account authentication check failed.")
|
||||
@ApiResponse(responseCode = "422", description = "Invalid request format.")
|
||||
@ApiResponse(responseCode = "429", description = "Rate limited.")
|
||||
@ManagedAsync
|
||||
public GetCallingRelaysResponse getCallingRelays(final @Auth AuthenticatedDevice auth)
|
||||
throws RateLimitExceededException, IOException {
|
||||
|
||||
|
||||
+3
@@ -29,6 +29,7 @@ import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import javax.annotation.Nonnull;
|
||||
import org.glassfish.jersey.server.ManagedAsync;
|
||||
import org.signal.libsignal.protocol.ServiceId;
|
||||
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
|
||||
import org.signal.libsignal.zkgroup.auth.AuthCredentialWithPniResponse;
|
||||
@@ -77,6 +78,7 @@ public class CertificateController {
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/delivery")
|
||||
@ManagedAsync
|
||||
public DeliveryCertificate getDeliveryCertificate(@Auth AuthenticatedDevice auth,
|
||||
@QueryParam("includeE164") @DefaultValue("true") boolean includeE164) {
|
||||
|
||||
@@ -96,6 +98,7 @@ public class CertificateController {
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/auth/group")
|
||||
@ManagedAsync
|
||||
public GroupCredentials getGroupAuthenticationCredentials(
|
||||
@Auth AuthenticatedDevice auth,
|
||||
@QueryParam("redemptionStartSeconds") long startSeconds,
|
||||
|
||||
+3
@@ -31,6 +31,7 @@ import jakarta.ws.rs.core.Context;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import java.io.IOException;
|
||||
import org.glassfish.jersey.server.ManagedAsync;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
@@ -88,6 +89,7 @@ public class ChallengeController {
|
||||
@ApiResponse(responseCode = "429", description = "Too many attempts", headers = @Header(
|
||||
name = "Retry-After",
|
||||
description = "If present, an positive integer indicating the number of seconds before a subsequent attempt could succeed"))
|
||||
@ManagedAsync
|
||||
public Response handleChallengeResponse(@Auth final AuthenticatedDevice auth,
|
||||
@Valid final AnswerChallengeRequest answerRequest,
|
||||
@Context final ContainerRequestContext requestContext,
|
||||
@@ -182,6 +184,7 @@ public class ChallengeController {
|
||||
@ApiResponse(responseCode = "429", description = "Too many attempts", headers = @Header(
|
||||
name = "Retry-After",
|
||||
description = "If present, an positive integer indicating the number of seconds before a subsequent attempt could succeed"))
|
||||
@ManagedAsync
|
||||
public Response requestPushChallenge(@Auth final AuthenticatedDevice auth,
|
||||
@Context ContainerRequestContext requestContext) {
|
||||
|
||||
|
||||
+6
@@ -47,6 +47,7 @@ import java.util.concurrent.CompletionStage;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.stream.Collectors;
|
||||
import javax.annotation.Nullable;
|
||||
import org.glassfish.jersey.server.ManagedAsync;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.BasicAuthorizationHeader;
|
||||
import org.whispersystems.textsecuregcm.auth.ChangesLinkedDevices;
|
||||
@@ -135,6 +136,7 @@ public class DeviceController {
|
||||
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@ManagedAsync
|
||||
public DeviceInfoList getDevices(@Auth AuthenticatedDevice auth) {
|
||||
// Devices may change their own names (and primary devices may change the names of linked devices) and so the device
|
||||
// state associated with the authenticated account may be stale. Fetch a fresh copy to compensate.
|
||||
@@ -149,6 +151,7 @@ public class DeviceController {
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/{device_id}")
|
||||
@ChangesLinkedDevices
|
||||
@ManagedAsync
|
||||
public void removeDevice(@Auth AuthenticatedDevice auth, @PathParam("device_id") byte deviceId) {
|
||||
if (auth.deviceId() != Device.PRIMARY_ID && auth.deviceId() != deviceId) {
|
||||
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
|
||||
@@ -189,6 +192,7 @@ public class DeviceController {
|
||||
@ApiResponse(responseCode = "429", description = "Too many attempts", headers = @Header(
|
||||
name = "Retry-After",
|
||||
description = "If present, an positive integer indicating the number of seconds before a subsequent attempt could succeed"))
|
||||
@ManagedAsync
|
||||
public LinkDeviceToken createDeviceToken(@Auth AuthenticatedDevice auth)
|
||||
throws RateLimitExceededException, DeviceLimitExceededException {
|
||||
|
||||
@@ -223,6 +227,7 @@ public class DeviceController {
|
||||
@ApiResponse(responseCode = "429", description = "Too many attempts", headers = @Header(
|
||||
name = "Retry-After",
|
||||
description = "If present, an positive integer indicating the number of seconds before a subsequent attempt could succeed"))
|
||||
@ManagedAsync
|
||||
public LinkDeviceResponse linkDevice(@HeaderParam(HttpHeaders.AUTHORIZATION) @NotNull BasicAuthorizationHeader authorizationHeader,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) @Nullable String userAgent,
|
||||
@NotNull @Valid LinkDeviceRequest linkDeviceRequest)
|
||||
@@ -391,6 +396,7 @@ public class DeviceController {
|
||||
@PUT
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/capabilities")
|
||||
@ManagedAsync
|
||||
public void setCapabilities(@Auth final AuthenticatedDevice auth, @NotNull final Map<String, Boolean> capabilities) {
|
||||
accounts.updateDevice(auth.accountIdentifier(), auth.deviceId(),
|
||||
d -> d.setCapabilities(DeviceCapabilityAdapter.mapToSet(capabilities)));
|
||||
|
||||
+1
@@ -160,6 +160,7 @@ public class DonationController {
|
||||
@ApiResponse(responseCode = "401", description = "Account authentication check failed")
|
||||
@ApiResponse(responseCode = "422", description = "Invalid request format")
|
||||
@ApiResponse(responseCode = "429", description = "Rate-limited; reduce requested permit count and/or try again after the prescribed delay")
|
||||
@ManagedAsync
|
||||
public CreateDonationPermitResponse createPermits(@Auth final AuthenticatedDevice auth,
|
||||
@NotNull @Valid final CreateDonationPermitsRequest request) throws RateLimitExceededException {
|
||||
|
||||
|
||||
+1
-50
@@ -5,66 +5,18 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.ws.rs.GET;
|
||||
import jakarta.ws.rs.Path;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Optional;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager;
|
||||
import org.whispersystems.websocket.session.WebSocketSession;
|
||||
import org.whispersystems.websocket.session.WebSocketSessionContext;
|
||||
|
||||
|
||||
@Path("/v1/keepalive")
|
||||
@Tag(name = "Keep Alive")
|
||||
public class KeepAliveController {
|
||||
|
||||
private final Logger logger = LoggerFactory.getLogger(KeepAliveController.class);
|
||||
|
||||
private final RedisMessageAvailabilityManager redisMessageAvailabilityManager;
|
||||
|
||||
private static final String CLOSED_CONNECTION_AGE_DISTRIBUTION_NAME = name(KeepAliveController.class,
|
||||
"closedConnectionAge");
|
||||
|
||||
|
||||
public KeepAliveController(final RedisMessageAvailabilityManager redisMessageAvailabilityManager) {
|
||||
this.redisMessageAvailabilityManager = redisMessageAvailabilityManager;
|
||||
}
|
||||
|
||||
@GET
|
||||
public Response getKeepAlive(@Auth Optional<AuthenticatedDevice> maybeAuth,
|
||||
@WebSocketSession WebSocketSessionContext context) {
|
||||
|
||||
maybeAuth.ifPresent(auth -> {
|
||||
if (!redisMessageAvailabilityManager.isLocallyPresent(auth.accountIdentifier(), auth.deviceId())) {
|
||||
|
||||
final Duration age = Duration.between(context.getClient().getCreated(), Instant.now());
|
||||
|
||||
logger.debug("***** No local subscription found for {}::{}; age = {}ms, User-Agent = {}",
|
||||
auth.accountIdentifier(), auth.deviceId(), age.toMillis(),
|
||||
context.getClient().getUserAgent());
|
||||
|
||||
context.getClient().close(1000, "OK");
|
||||
|
||||
Timer.builder(CLOSED_CONNECTION_AGE_DISTRIBUTION_NAME)
|
||||
.tags(Tags.of(UserAgentTagUtil.getPlatformTag(context.getClient().getUserAgent())))
|
||||
.register(Metrics.globalRegistry)
|
||||
.record(age);
|
||||
}
|
||||
});
|
||||
|
||||
public Response getKeepAlive() {
|
||||
return Response.ok().build();
|
||||
}
|
||||
|
||||
@@ -73,5 +25,4 @@ public class KeepAliveController {
|
||||
public Response getProvisioningKeepAlive() {
|
||||
return Response.ok().build();
|
||||
}
|
||||
|
||||
}
|
||||
+2
@@ -463,6 +463,7 @@ public class MessageController {
|
||||
@ApiResponse(
|
||||
responseCode = "410", description = "Mismatched registration ids supplied for some recipient devices",
|
||||
content = @Content(schema = @Schema(implementation = AccountStaleDevices[].class)))
|
||||
@ManagedAsync
|
||||
public Response sendMultiRecipientMessage(
|
||||
@Deprecated
|
||||
@Parameter(description="The bitwise xor of the unidentified access keys for every recipient of the message. Will be replaced with group send endorsements")
|
||||
@@ -729,6 +730,7 @@ public class MessageController {
|
||||
@POST
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Path("/report/{source}/{messageGuid}")
|
||||
@ManagedAsync
|
||||
public Response reportSpamMessage(
|
||||
@Auth AuthenticatedDevice auth,
|
||||
@PathParam("source") UUID source,
|
||||
|
||||
+7
-21
@@ -36,14 +36,11 @@ import jakarta.ws.rs.core.Context;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import java.io.IOException;
|
||||
import java.math.BigDecimal;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import org.glassfish.jersey.server.ManagedAsync;
|
||||
@@ -69,7 +66,7 @@ import org.whispersystems.textsecuregcm.purchases.PayPalDonationsTranslator;
|
||||
import org.whispersystems.textsecuregcm.purchases.PaymentDetails;
|
||||
import org.whispersystems.textsecuregcm.purchases.PaymentMethod;
|
||||
import org.whispersystems.textsecuregcm.purchases.PaymentProvider;
|
||||
import org.whispersystems.textsecuregcm.purchases.PurchaseInvalidAmountException;
|
||||
import org.whispersystems.textsecuregcm.purchases.PurchaseAmountTooLargeException;
|
||||
import org.whispersystems.textsecuregcm.purchases.PurchaseNotFoundException;
|
||||
import org.whispersystems.textsecuregcm.purchases.PurchasePaymentRequiredException;
|
||||
import org.whispersystems.textsecuregcm.purchases.PurchaseProcessorException;
|
||||
@@ -181,7 +178,7 @@ public class OneTimeDonationController {
|
||||
@HeaderParam(HeaderUtils.DONATION_PERMIT) final Optional<DonationPermitHeader> donationPermitHeader,
|
||||
|
||||
@NotNull @Valid final CreateBoostRequest request,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent) throws PurchaseInvalidAmountException {
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent) throws PurchaseAmountTooLargeException {
|
||||
|
||||
if (authenticatedAccount.isPresent()) {
|
||||
throw new ForbiddenException("must not use authenticated connection for one-time donation operations");
|
||||
@@ -217,24 +214,13 @@ public class OneTimeDonationController {
|
||||
private void validateRequestCurrencyAmount(final CreateBoostRequest request, final long amount,
|
||||
final CustomerAwareSubscriptionPaymentProcessor manager) {
|
||||
|
||||
final Map<String, String> errorBody = switch (OneTimeDonationUtil.validateOneTimeDonationRequest(request.currency,
|
||||
amount, request.level, request.paymentMethod, oneTimeDonationConfiguration, manager)) {
|
||||
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.UnsupportedLevel _ ->
|
||||
Map.of("error", "invalid_level");
|
||||
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.UnsupportedCurrency _ ->
|
||||
Map.of("error", "unsupported_currency");
|
||||
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.AmountBelowMinimum(final BigDecimal min) ->
|
||||
Map.of("error", "amount_below_currency_minimum", "minimum", min.toString());
|
||||
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.AmountAboveSepaLimit(final BigDecimal max) ->
|
||||
Map.of("error", "amount_above_sepa_limit", "maximum", max.toString());
|
||||
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.Success _ -> Collections.emptyMap();
|
||||
};
|
||||
|
||||
if (!errorBody.isEmpty()) {
|
||||
try {
|
||||
OneTimeDonationUtil.validateOneTimeDonationRequest(request.currency, amount, request.level, request.paymentMethod,
|
||||
oneTimeDonationConfiguration, manager);
|
||||
} catch (OneTimeDonationUtil.ValidationException e) {
|
||||
throw new BadRequestException(
|
||||
Response.status(Response.Status.BAD_REQUEST).entity(errorBody).build());
|
||||
Response.status(Response.Status.BAD_REQUEST).entity(e.getErrorBody()).build());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static class CreatePayPalBoostRequest extends CreateBoostRequest {
|
||||
|
||||
+2
-5
@@ -168,8 +168,8 @@ 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,
|
||||
@NotNull @Valid CreateProfileRequest request,
|
||||
@Context final ContainerRequestContext requestContext) {
|
||||
@@ -177,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());
|
||||
|
||||
@@ -278,6 +274,7 @@ public class ProfileController {
|
||||
@ApiResponse(responseCode = "401", description = "Not authorized to access this profile.")
|
||||
@ApiResponse(responseCode = "404", description = "Profile or account not found.")
|
||||
@ApiResponse(responseCode = "429", description = "Rate limit exceeded.")
|
||||
@ManagedAsync
|
||||
public ExpiringProfileKeyCredentialProfileResponse getProfile(
|
||||
@Auth Optional<AuthenticatedDevice> maybeAuthenticatedDevice,
|
||||
@HeaderParam(HeaderUtils.UNIDENTIFIED_ACCESS_KEY) Optional<Anonymous> accessKey,
|
||||
|
||||
+2
@@ -29,6 +29,7 @@ import jakarta.ws.rs.WebApplicationException;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import java.util.Base64;
|
||||
import org.glassfish.jersey.server.ManagedAsync;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.entities.ProvisioningMessage;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
@@ -76,6 +77,7 @@ public class ProvisioningController {
|
||||
@ApiResponse(responseCode="204", description="The provisioning message was delivered to the given provisioning address")
|
||||
@ApiResponse(responseCode="400", description="The provisioning message was too large")
|
||||
@ApiResponse(responseCode="404", description="No device with the given provisioning address was connected at the time of the request")
|
||||
@ManagedAsync
|
||||
public void sendProvisioningMessage(@Auth final AuthenticatedDevice auth,
|
||||
|
||||
@Parameter(description = "The temporary provisioning address to which to send a provisioning message")
|
||||
|
||||
+5
-1
@@ -45,6 +45,7 @@ import java.util.UUID;
|
||||
import javax.annotation.Nullable;
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.glassfish.jersey.server.ManagedAsync;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.VerificationFailedException;
|
||||
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialPresentation;
|
||||
@@ -98,6 +99,7 @@ public class RegistrationController {
|
||||
private static final String COUNTRY_CODE_TAG_NAME = "countryCode";
|
||||
private static final String REGION_CODE_TAG_NAME = "regionCode";
|
||||
private static final String VERIFICATION_TYPE_TAG_NAME = "verification";
|
||||
private static final String FICTITIOUS_NUMBER_TAG_NAME = "fictitiousNumber";
|
||||
|
||||
private final AccountsManager accounts;
|
||||
private final PhoneVerificationTokenManager phoneVerificationTokenManager;
|
||||
@@ -160,6 +162,7 @@ public class RegistrationController {
|
||||
""",
|
||||
content = @Content(schema = @Schema(implementation = MfaFailureExceptionMapper.MfaFailureResponse.class)))
|
||||
@ApiResponse(responseCode = "499", description = "Client must support post-quantum ratchet")
|
||||
@ManagedAsync
|
||||
public AccountCreationResponse register(
|
||||
@Parameter(
|
||||
in = ParameterIn.HEADER,
|
||||
@@ -320,7 +323,8 @@ public class RegistrationController {
|
||||
Metrics.counter(ACCOUNT_CREATED_COUNTER_NAME, Tags.of(UserAgentTagUtil.getPlatformTag(userAgent),
|
||||
Tag.of(COUNTRY_CODE_TAG_NAME, Util.getCountryCode(number)),
|
||||
Tag.of(REGION_CODE_TAG_NAME, Util.getRegion(number)),
|
||||
Tag.of(VERIFICATION_TYPE_TAG_NAME, verificationType.name())))
|
||||
Tag.of(VERIFICATION_TYPE_TAG_NAME, verificationType.name()),
|
||||
Tag.of(FICTITIOUS_NUMBER_TAG_NAME, String.valueOf(Util.isFictitiousNumber(number)))))
|
||||
.increment();
|
||||
|
||||
final AccountIdentityResponse identityResponse = new AccountIdentityResponseBuilder(account)
|
||||
|
||||
+2
@@ -24,6 +24,7 @@ import jakarta.ws.rs.core.Response;
|
||||
import java.util.HexFormat;
|
||||
import java.util.Map;
|
||||
import javax.annotation.Nullable;
|
||||
import org.glassfish.jersey.server.ManagedAsync;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.entities.RemoteConfigurationResponse;
|
||||
import org.whispersystems.textsecuregcm.storage.RemoteConfigsManager;
|
||||
@@ -52,6 +53,7 @@ public class RemoteConfigController {
|
||||
@ApiResponse(responseCode = "304", description = "There is no change since the last fetch", content = {})
|
||||
@ApiResponse(responseCode = "401", description = "This request requires authentication", content = {})
|
||||
|
||||
@ManagedAsync
|
||||
public Response getAll(
|
||||
@Auth AuthenticatedDevice auth,
|
||||
|
||||
|
||||
+2
@@ -32,6 +32,7 @@ import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
import org.glassfish.jersey.server.ManagedAsync;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
|
||||
@@ -115,6 +116,7 @@ public class SecureValueRecovery2Controller {
|
||||
@ApiResponse(responseCode = "200", description = "`JSON` with the check results.", useReturnTypeSchema = true)
|
||||
@ApiResponse(responseCode = "422", description = "Provided list of SVR2 credentials could not be parsed")
|
||||
@ApiResponse(responseCode = "400", description = "`POST` request body is not a valid `JSON`")
|
||||
@ManagedAsync
|
||||
public AuthCheckResponseV2 authCheck(
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
|
||||
@NotNull @Valid final AuthCheckRequest request) {
|
||||
|
||||
+2
@@ -21,6 +21,7 @@ import java.time.Instant;
|
||||
import java.util.HexFormat;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import org.glassfish.jersey.server.ManagedAsync;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.entities.StickerPackFormUploadAttributes;
|
||||
import org.whispersystems.textsecuregcm.entities.StickerPackFormUploadAttributes.StickerPackFormUploadItem;
|
||||
@@ -49,6 +50,7 @@ public class StickerController {
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/pack/form/{count}")
|
||||
@ManagedAsync
|
||||
public StickerPackFormUploadAttributes getStickersForm(@Auth AuthenticatedDevice auth,
|
||||
@PathParam("count") @Min(1) @Max(201) int stickerCount)
|
||||
throws RateLimitExceededException {
|
||||
|
||||
+6
@@ -60,6 +60,7 @@ import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import org.apache.commons.lang3.Strings;
|
||||
import org.apache.http.HttpStatus;
|
||||
import org.glassfish.jersey.server.ManagedAsync;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.captcha.AssessmentResult;
|
||||
@@ -184,6 +185,7 @@ public class VerificationController {
|
||||
name = "Retry-After",
|
||||
description = "If present, an positive integer indicating the number of seconds before a subsequent attempt could succeed",
|
||||
schema = @Schema(implementation = Integer.class)))
|
||||
@ManagedAsync
|
||||
public VerificationSessionResponse createSession(@NotNull @Valid final CreateVerificationSessionRequest request,
|
||||
@Context final ContainerRequestContext requestContext)
|
||||
throws RateLimitExceededException, ObsoletePhoneNumberFormatException {
|
||||
@@ -263,6 +265,7 @@ public class VerificationController {
|
||||
name = "Retry-After",
|
||||
description = "If present, an positive integer indicating the number of seconds before a subsequent attempt could succeed",
|
||||
schema = @Schema(implementation = Integer.class)))
|
||||
@ManagedAsync
|
||||
public VerificationSessionResponse updateSession(
|
||||
@PathParam("sessionId") final String encodedSessionId,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
|
||||
@@ -518,6 +521,7 @@ public class VerificationController {
|
||||
@ApiResponse(responseCode = "400", description = "Invalid session ID")
|
||||
@ApiResponse(responseCode = "404", description = "Session with the specified ID could not be found")
|
||||
@ApiResponse(responseCode = "422", description = "Malformed session ID encoding")
|
||||
@ManagedAsync
|
||||
public VerificationSessionResponse getSession(@PathParam("sessionId") final String encodedSessionId) {
|
||||
|
||||
final RegistrationServiceSession registrationServiceSession = retrieveRegistrationServiceSession(encodedSessionId);
|
||||
@@ -564,6 +568,7 @@ public class VerificationController {
|
||||
future attempts to request or submit verification codes (since those attempts would be all but guaranteed to fail).
|
||||
""",
|
||||
content = @Content(schema = @Schema(implementation = RegistrationServiceSenderExceptionMapper.SendVerificationCodeFailureResponse.class)))
|
||||
@ManagedAsync
|
||||
public VerificationSessionResponse requestVerificationCode(@PathParam("sessionId") final String encodedSessionId,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
|
||||
@Parameter(in = ParameterIn.HEADER, description = "Ordered list of languages in which the client prefers to receive SMS or voice verification messages") @HeaderParam(HttpHeaders.ACCEPT_LANGUAGE)
|
||||
@@ -700,6 +705,7 @@ public class VerificationController {
|
||||
name = "Retry-After",
|
||||
description = "If present, an positive integer indicating the number of seconds before a subsequent attempt could succeed",
|
||||
schema = @Schema(implementation = Integer.class)))
|
||||
@ManagedAsync
|
||||
public VerificationSessionResponse verifyCode(@PathParam("sessionId") final String encodedSessionId,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
|
||||
@NotNull @Valid final SubmitVerificationCodeRequest submitVerificationCodeRequest) {
|
||||
|
||||
-132
@@ -1,132 +0,0 @@
|
||||
package org.whispersystems.textsecuregcm.experiment;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.workers.IdleWakeupEligibilityChecker;
|
||||
import reactor.core.publisher.Flux;
|
||||
import javax.annotation.Nullable;
|
||||
import java.util.Collections;
|
||||
import java.util.EnumMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
abstract class IdleDevicePushNotificationExperiment implements PushNotificationExperiment<DeviceLastSeenState> {
|
||||
|
||||
private final IdleWakeupEligibilityChecker idleWakeupEligibilityChecker;
|
||||
|
||||
private final Logger log = LoggerFactory.getLogger(getClass());
|
||||
|
||||
@VisibleForTesting
|
||||
enum Population {
|
||||
APNS_CONTROL,
|
||||
APNS_EXPERIMENT,
|
||||
FCM_CONTROL,
|
||||
FCM_EXPERIMENT
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
enum Outcome {
|
||||
DELETED,
|
||||
UNINSTALLED,
|
||||
REACTIVATED,
|
||||
UNCHANGED
|
||||
}
|
||||
|
||||
protected IdleDevicePushNotificationExperiment(final IdleWakeupEligibilityChecker idleWakeupEligibilityChecker) {
|
||||
this.idleWakeupEligibilityChecker = idleWakeupEligibilityChecker;
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
boolean hasPushToken(final Device device) {
|
||||
return !StringUtils.isAllBlank(device.getApnId(), device.getGcmId());
|
||||
}
|
||||
|
||||
abstract boolean isIdleDeviceEligible(final Account account, final Device idleDevice, final DeviceLastSeenState state);
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Boolean> isDeviceEligible(final Account account, final Device device) {
|
||||
return idleWakeupEligibilityChecker.isDeviceEligible(account, device).thenApply(idle ->
|
||||
idle && isIdleDeviceEligible(account, device, getState(account, device)));
|
||||
}
|
||||
|
||||
@Override
|
||||
public DeviceLastSeenState getState(@Nullable final Account account, @Nullable final Device device) {
|
||||
if (account != null && device != null) {
|
||||
final DeviceLastSeenState.PushTokenType pushTokenType;
|
||||
if (StringUtils.isNotBlank(device.getApnId())) {
|
||||
pushTokenType = DeviceLastSeenState.PushTokenType.APNS;
|
||||
} else if (StringUtils.isNotBlank(device.getGcmId())) {
|
||||
pushTokenType = DeviceLastSeenState.PushTokenType.FCM;
|
||||
} else {
|
||||
pushTokenType = null;
|
||||
}
|
||||
return new DeviceLastSeenState(true, device.getAccountRegistrationId(), hasPushToken(device), device.getLastSeen(), pushTokenType);
|
||||
} else {
|
||||
return DeviceLastSeenState.MISSING_DEVICE_STATE;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void analyzeResults(final Flux<PushNotificationExperimentSample<DeviceLastSeenState>> samples) {
|
||||
final Map<Population, Map<Outcome, Integer>> contingencyTable = new EnumMap<>(Population.class);
|
||||
|
||||
samples.doOnNext(sample ->
|
||||
contingencyTable.computeIfAbsent(getPopulation(sample), ignored -> new EnumMap<>(Outcome.class))
|
||||
.merge(getOutcome(sample), 1, Integer::sum))
|
||||
.then()
|
||||
.block();
|
||||
|
||||
final StringBuilder reportBuilder = new StringBuilder("population,deleted,uninstalled,reactivated,unchanged\n");
|
||||
|
||||
for (final Population population : Population.values()) {
|
||||
final Map<Outcome, Integer> countsByOutcome = contingencyTable.getOrDefault(population, Collections.emptyMap());
|
||||
|
||||
reportBuilder.append(population.name());
|
||||
reportBuilder.append(",");
|
||||
reportBuilder.append(countsByOutcome.getOrDefault(Outcome.DELETED, 0));
|
||||
reportBuilder.append(",");
|
||||
reportBuilder.append(countsByOutcome.getOrDefault(Outcome.UNINSTALLED, 0));
|
||||
reportBuilder.append(",");
|
||||
reportBuilder.append(countsByOutcome.getOrDefault(Outcome.REACTIVATED, 0));
|
||||
reportBuilder.append(",");
|
||||
reportBuilder.append(countsByOutcome.getOrDefault(Outcome.UNCHANGED, 0));
|
||||
reportBuilder.append("\n");
|
||||
}
|
||||
|
||||
log.info(reportBuilder.toString());
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static Population getPopulation(final PushNotificationExperimentSample<DeviceLastSeenState> sample) {
|
||||
assert sample.initialState() != null && sample.initialState().pushTokenType() != null;
|
||||
|
||||
return switch (sample.initialState().pushTokenType()) {
|
||||
case APNS -> sample.inExperimentGroup() ? Population.APNS_EXPERIMENT : Population.APNS_CONTROL;
|
||||
case FCM -> sample.inExperimentGroup() ? Population.FCM_EXPERIMENT : Population.FCM_CONTROL;
|
||||
};
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static Outcome getOutcome(final PushNotificationExperimentSample<DeviceLastSeenState> sample) {
|
||||
final Outcome outcome;
|
||||
|
||||
assert sample.finalState() != null;
|
||||
|
||||
if (!sample.finalState().deviceExists() || sample.initialState().registrationId() != sample.finalState().registrationId()) {
|
||||
outcome = Outcome.DELETED;
|
||||
} else if (!sample.finalState().hasPushToken()) {
|
||||
outcome = Outcome.UNINSTALLED;
|
||||
} else if (sample.initialState().lastSeenMillis() != sample.finalState().lastSeenMillis()) {
|
||||
outcome = Outcome.REACTIVATED;
|
||||
} else {
|
||||
outcome = Outcome.UNCHANGED;
|
||||
}
|
||||
|
||||
return outcome;
|
||||
}
|
||||
}
|
||||
-85
@@ -1,85 +0,0 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.experiment;
|
||||
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import reactor.core.publisher.Flux;
|
||||
import javax.annotation.Nullable;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
/**
|
||||
* A push notification selects for eligible devices, applies a control or experimental treatment, and provides a
|
||||
* mechanism for comparing device states before and after receiving the treatment.
|
||||
*
|
||||
* @param <T> the type of state object stored for this experiment
|
||||
*/
|
||||
public interface PushNotificationExperiment<T> {
|
||||
|
||||
/**
|
||||
* Returns the unique name of this experiment.
|
||||
*
|
||||
* @return the unique name of this experiment
|
||||
*/
|
||||
String getExperimentName();
|
||||
|
||||
/**
|
||||
* Tests whether a device is eligible for this experiment. An eligible device may be assigned to either the control
|
||||
* or experiment group within an experiment. Ineligible devices will not participate in the experiment in any way.
|
||||
*
|
||||
* @param account the account to which the device belongs
|
||||
* @param device the device to test for eligibility in this experiment
|
||||
*
|
||||
* @return a future that yields a boolean value indicating whether the target device is eligible for this experiment
|
||||
*/
|
||||
CompletableFuture<Boolean> isDeviceEligible(Account account, Device device);
|
||||
|
||||
/**
|
||||
* Returns the class of the state object stored for this experiment.
|
||||
*
|
||||
* @return the class of the state object stored for this experiment
|
||||
*/
|
||||
Class<T> getStateClass();
|
||||
|
||||
/**
|
||||
* Generates an experiment specific state "snapshot" of the given device. Experiment results are generally evaluated
|
||||
* by comparing a device's state before a treatment is applied and its state after the treatment is applied.
|
||||
*
|
||||
* @param account the account to which the device belongs
|
||||
* @param device the device for which to generate a state "snapshot"
|
||||
*
|
||||
* @return an experiment-specific state "snapshot" of the given device
|
||||
*/
|
||||
T getState(@Nullable Account account, @Nullable Device device);
|
||||
|
||||
/**
|
||||
* Applies a control treatment to the given device. In many cases (and by default) no action is taken for devices in
|
||||
* the control group.
|
||||
*
|
||||
* @param account the account to which the device belongs
|
||||
* @param device the device to which to apply the control treatment for this experiment
|
||||
*
|
||||
* @return a future that completes when the control treatment has been applied for the given device
|
||||
*/
|
||||
default CompletableFuture<Void> applyControlTreatment(Account account, Device device) {
|
||||
return CompletableFuture.completedFuture(null);
|
||||
};
|
||||
|
||||
/**
|
||||
* Applies an experimental treatment to the given device. This generally involves sending or scheduling a specific
|
||||
* type of push notification for the given device.
|
||||
*
|
||||
* @param account the account to which the device belongs
|
||||
* @param device the device to which to apply the experimental treatment for this experiment
|
||||
*
|
||||
* @return a future that completes when the experimental treatment has been applied for the given device
|
||||
*/
|
||||
CompletableFuture<Void> applyExperimentTreatment(Account account, Device device);
|
||||
|
||||
/**
|
||||
* Consumes a stream of finished samples and emits an analysis of the results via an implementation-specific channel
|
||||
* (e.g. a log message). Implementations must block until all samples have been consumed and analyzed.
|
||||
*
|
||||
* @param samples a stream of finished samples from this experiment
|
||||
*/
|
||||
void analyzeResults(Flux<PushNotificationExperimentSample<T>> samples);
|
||||
}
|
||||
-11
@@ -1,11 +0,0 @@
|
||||
package org.whispersystems.textsecuregcm.experiment;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
import java.util.UUID;
|
||||
|
||||
public record PushNotificationExperimentSample<T>(UUID accountIdentifier,
|
||||
byte deviceId,
|
||||
boolean inExperimentGroup,
|
||||
T initialState,
|
||||
@Nullable T finalState) {
|
||||
}
|
||||
-279
@@ -1,279 +0,0 @@
|
||||
package org.whispersystems.textsecuregcm.experiment;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.util.function.Tuple2;
|
||||
import reactor.util.function.Tuples;
|
||||
import reactor.util.retry.Retry;
|
||||
import software.amazon.awssdk.core.SdkBytes;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
|
||||
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ConditionalCheckFailedException;
|
||||
import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.PutItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ReturnValue;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ScanRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;
|
||||
|
||||
public class PushNotificationExperimentSamples {
|
||||
|
||||
private final DynamoDbAsyncClient dynamoDbAsyncClient;
|
||||
private final String tableName;
|
||||
private final Clock clock;
|
||||
|
||||
// Experiment name; DynamoDB string; partition key
|
||||
public static final String KEY_EXPERIMENT_NAME = "N";
|
||||
|
||||
// Combined ACI and device ID; DynamoDB byte array; sort key
|
||||
public static final String ATTR_ACI_AND_DEVICE_ID = "AD";
|
||||
|
||||
// Whether the device is enrolled in the experiment group (as opposed to control group); DynamoDB boolean
|
||||
static final String ATTR_IN_EXPERIMENT_GROUP = "X";
|
||||
|
||||
// The experiment-specific state of the device at the start of the experiment, represented as a JSON blob; DynamoDB
|
||||
// string
|
||||
static final String ATTR_INITIAL_STATE = "I";
|
||||
|
||||
// The experiment-specific state of the device at the end of the experiment, represented as a JSON blob; DynamoDB
|
||||
// string
|
||||
static final String ATTR_FINAL_STATE = "F";
|
||||
|
||||
// The time, in seconds since the epoch, at which this sample should be deleted automatically
|
||||
static final String ATTR_TTL = "E";
|
||||
|
||||
private static final Duration FINAL_SAMPLE_TTL = Duration.ofDays(7);
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(PushNotificationExperimentSamples.class);
|
||||
|
||||
public PushNotificationExperimentSamples(final DynamoDbAsyncClient dynamoDbAsyncClient,
|
||||
final String tableName,
|
||||
final Clock clock) {
|
||||
|
||||
this.dynamoDbAsyncClient = dynamoDbAsyncClient;
|
||||
this.tableName = tableName;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes the initial state of a device participating in a push notification experiment.
|
||||
*
|
||||
* @param accountIdentifier the account identifier for the account to which the target device is linked
|
||||
* @param deviceId the identifier for the device within the given account
|
||||
* @param experimentName the name of the experiment
|
||||
* @param inExperimentGroup whether the given device is in the experiment group (as opposed to control group)
|
||||
* @param initialState the initial state of the object; must be serializable as a JSON text
|
||||
*
|
||||
* @return a future that completes when the record has been stored; the future yields {@code true} if a new record
|
||||
* was stored or {@code false} if a conflicting record already exists
|
||||
*
|
||||
* @param <T> the type of state object for this sample
|
||||
*
|
||||
* @throws JsonProcessingException if the given {@code initialState} could not be serialized as a JSON text
|
||||
*/
|
||||
public <T> CompletableFuture<Boolean> recordInitialState(final UUID accountIdentifier,
|
||||
final byte deviceId,
|
||||
final String experimentName,
|
||||
final boolean inExperimentGroup,
|
||||
final T initialState) throws JsonProcessingException {
|
||||
|
||||
final AttributeValue initialStateAttributeValue =
|
||||
AttributeValue.fromS(SystemMapper.jsonMapper().writeValueAsString(initialState));
|
||||
|
||||
final AttributeValue inExperimentGroupAttributeValue = AttributeValue.fromBool(inExperimentGroup);
|
||||
|
||||
return dynamoDbAsyncClient.putItem(PutItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.item(Map.of(
|
||||
KEY_EXPERIMENT_NAME, AttributeValue.fromS(experimentName),
|
||||
ATTR_ACI_AND_DEVICE_ID, buildSortKey(accountIdentifier, deviceId),
|
||||
ATTR_IN_EXPERIMENT_GROUP, inExperimentGroupAttributeValue,
|
||||
ATTR_INITIAL_STATE, initialStateAttributeValue,
|
||||
ATTR_TTL, AttributeValue.fromN(String.valueOf(clock.instant().plus(FINAL_SAMPLE_TTL).getEpochSecond()))))
|
||||
.conditionExpression("(attribute_not_exists(#inExperimentGroup) OR #inExperimentGroup = :inExperimentGroup) AND (attribute_not_exists(#initialState) OR #initialState = :initialState) AND attribute_not_exists(#finalState)")
|
||||
.expressionAttributeNames(Map.of(
|
||||
"#inExperimentGroup", ATTR_IN_EXPERIMENT_GROUP,
|
||||
"#initialState", ATTR_INITIAL_STATE,
|
||||
"#finalState", ATTR_FINAL_STATE))
|
||||
.expressionAttributeValues(Map.of(
|
||||
":inExperimentGroup", inExperimentGroupAttributeValue,
|
||||
":initialState", initialStateAttributeValue))
|
||||
.build())
|
||||
.thenApply(ignored -> true)
|
||||
.exceptionally(throwable -> {
|
||||
if (ExceptionUtils.unwrap(throwable) instanceof ConditionalCheckFailedException) {
|
||||
return false;
|
||||
}
|
||||
|
||||
throw ExceptionUtils.wrap(throwable);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes the final state of a device participating in a push notification experiment.
|
||||
*
|
||||
* @param accountIdentifier the account identifier for the account to which the target device is linked
|
||||
* @param deviceId the identifier for the device within the given account
|
||||
* @param experimentName the name of the experiment
|
||||
* @param finalState the final state of the object; must be serializable as a JSON text and of the same type as the
|
||||
* previously-stored initial state
|
||||
|
||||
* @return A future that completes when the final state has been stored; yields a finished sample if an initial sample
|
||||
* was found or empty if no initial sample was found for the given account, device, and experiment. The future may
|
||||
* with a {@link JsonProcessingException} if the initial state could not be read or the final state could not be
|
||||
* written as a JSON text.
|
||||
*
|
||||
* @param <T> the type of state object for this sample
|
||||
*/
|
||||
public <T> CompletableFuture<PushNotificationExperimentSample<T>> recordFinalState(final UUID accountIdentifier,
|
||||
final byte deviceId,
|
||||
final String experimentName,
|
||||
final T finalState) {
|
||||
|
||||
CompletableFuture<String> finalStateJsonFuture;
|
||||
|
||||
// Process the final state JSON on the calling thread, but inside a CompletionStage so there's just one "channel"
|
||||
// for reporting JSON exceptions. The alternative is to `throw JsonProcessingException`, but then callers would have
|
||||
// to both catch the exception when calling this method and also watch the returned future for the same exception.
|
||||
try {
|
||||
finalStateJsonFuture =
|
||||
CompletableFuture.completedFuture(SystemMapper.jsonMapper().writeValueAsString(finalState));
|
||||
} catch (final JsonProcessingException e) {
|
||||
finalStateJsonFuture = CompletableFuture.failedFuture(e);
|
||||
}
|
||||
|
||||
final AttributeValue aciAndDeviceIdAttributeValue = buildSortKey(accountIdentifier, deviceId);
|
||||
|
||||
return finalStateJsonFuture.thenCompose(finalStateJson -> {
|
||||
return dynamoDbAsyncClient.updateItem(UpdateItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.key(Map.of(
|
||||
KEY_EXPERIMENT_NAME, AttributeValue.fromS(experimentName),
|
||||
ATTR_ACI_AND_DEVICE_ID, aciAndDeviceIdAttributeValue))
|
||||
// `UpdateItem` will, by default, create a new item if one does not already exist for the given primary key. We
|
||||
// want update-only-if-exists behavior, though, and so check that there's already an existing item for this ACI
|
||||
// and device ID.
|
||||
.conditionExpression("#aciAndDeviceId = :aciAndDeviceId")
|
||||
.updateExpression("SET #finalState = if_not_exists(#finalState, :finalState)")
|
||||
.expressionAttributeNames(Map.of(
|
||||
"#aciAndDeviceId", ATTR_ACI_AND_DEVICE_ID,
|
||||
"#finalState", ATTR_FINAL_STATE))
|
||||
.expressionAttributeValues(Map.of(
|
||||
":aciAndDeviceId", aciAndDeviceIdAttributeValue,
|
||||
":finalState", AttributeValue.fromS(finalStateJson)))
|
||||
.returnValues(ReturnValue.ALL_NEW)
|
||||
.build())
|
||||
.thenApply(updateItemResponse -> {
|
||||
try {
|
||||
final boolean inExperimentGroup = updateItemResponse.attributes().get(ATTR_IN_EXPERIMENT_GROUP).bool();
|
||||
|
||||
@SuppressWarnings("unchecked") final T parsedInitialState =
|
||||
(T) parseState(updateItemResponse.attributes().get(ATTR_INITIAL_STATE).s(), finalState.getClass());
|
||||
|
||||
@SuppressWarnings("unchecked") final T parsedFinalState =
|
||||
(T) parseState(updateItemResponse.attributes().get(ATTR_FINAL_STATE).s(), finalState.getClass());
|
||||
|
||||
return new PushNotificationExperimentSample<>(accountIdentifier, deviceId, inExperimentGroup, parsedInitialState, parsedFinalState);
|
||||
} catch (final JsonProcessingException e) {
|
||||
throw ExceptionUtils.wrap(e);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a publisher across all samples for a given experiment.
|
||||
*
|
||||
* @param experimentName the name of the experiment for which to fetch samples
|
||||
* @param stateClass the type of state object for sample in the given experiment
|
||||
*
|
||||
* @return a publisher of tuples of ACI, device ID, and sample for all samples associated with the given experiment
|
||||
*
|
||||
* @param <T> the type of the sample's state objects
|
||||
*
|
||||
* @see <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Scan.html#Scan.ParallelScan">Working with scans - Parallel scan</a>
|
||||
*/
|
||||
public <T> Flux<PushNotificationExperimentSample<T>> getSamples(final String experimentName, final Class<T> stateClass) {
|
||||
|
||||
return Flux.from(dynamoDbAsyncClient.queryPaginator(QueryRequest.builder()
|
||||
.tableName(tableName)
|
||||
.keyConditionExpression("#experiment = :experiment")
|
||||
.expressionAttributeNames(Map.of("#experiment", KEY_EXPERIMENT_NAME))
|
||||
.expressionAttributeValues(Map.of(":experiment", AttributeValue.fromS(experimentName)))
|
||||
.build())
|
||||
.items())
|
||||
.handle((item, sink) -> {
|
||||
try {
|
||||
final Tuple2<UUID, Byte> aciAndDeviceId = parseSortKey(item.get(ATTR_ACI_AND_DEVICE_ID));
|
||||
|
||||
final boolean inExperimentGroup = item.get(ATTR_IN_EXPERIMENT_GROUP).bool();
|
||||
final T initialState = parseState(item.get(ATTR_INITIAL_STATE).s(), stateClass);
|
||||
final T finalState = item.get(ATTR_FINAL_STATE) != null
|
||||
? parseState(item.get(ATTR_FINAL_STATE).s(), stateClass)
|
||||
: null;
|
||||
|
||||
sink.next(new PushNotificationExperimentSample<>(aciAndDeviceId.getT1(), aciAndDeviceId.getT2(), inExperimentGroup, initialState, finalState));
|
||||
} catch (final JsonProcessingException e) {
|
||||
sink.error(e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> discardSamples(final String experimentName, final int maxConcurrency) {
|
||||
final AttributeValue experimentNameAttributeValue = AttributeValue.fromS(experimentName);
|
||||
|
||||
return Flux.from(dynamoDbAsyncClient.scanPaginator(ScanRequest.builder()
|
||||
.tableName(tableName)
|
||||
.filterExpression("#experiment = :experiment")
|
||||
.expressionAttributeNames(Map.of("#experiment", KEY_EXPERIMENT_NAME))
|
||||
.expressionAttributeValues(Map.of(":experiment", experimentNameAttributeValue))
|
||||
.projectionExpression(ATTR_ACI_AND_DEVICE_ID)
|
||||
.build())
|
||||
.items())
|
||||
.map(item -> item.get(ATTR_ACI_AND_DEVICE_ID))
|
||||
.flatMap(aciAndDeviceId -> Mono.fromFuture(() -> dynamoDbAsyncClient.deleteItem(DeleteItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.key(Map.of(
|
||||
KEY_EXPERIMENT_NAME, experimentNameAttributeValue,
|
||||
ATTR_ACI_AND_DEVICE_ID, aciAndDeviceId))
|
||||
.build()))
|
||||
.retryWhen(Retry.backoff(5, Duration.ofSeconds(5)))
|
||||
.onErrorResume(throwable -> {
|
||||
log.warn("Failed to delete sample for experiment {}", experimentName, throwable);
|
||||
return Mono.empty();
|
||||
}), maxConcurrency)
|
||||
.then()
|
||||
.toFuture();
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static AttributeValue buildSortKey(final UUID accountIdentifier, final byte deviceId) {
|
||||
return AttributeValue.fromB(SdkBytes.fromByteBuffer(ByteBuffer.allocate(17)
|
||||
.putLong(accountIdentifier.getMostSignificantBits())
|
||||
.putLong(accountIdentifier.getLeastSignificantBits())
|
||||
.put(deviceId)
|
||||
.flip()));
|
||||
}
|
||||
|
||||
private static Tuple2<UUID, Byte> parseSortKey(final AttributeValue sortKey) {
|
||||
final ByteBuffer byteBuffer = sortKey.b().asByteBuffer();
|
||||
|
||||
return Tuples.of(new UUID(byteBuffer.getLong(), byteBuffer.getLong()), byteBuffer.get());
|
||||
}
|
||||
|
||||
private static <T> T parseState(final String state, final Class<T> clazz) throws JsonProcessingException {
|
||||
return SystemMapper.jsonMapper().readValue(state, clazz);
|
||||
}
|
||||
}
|
||||
+7
-2
@@ -7,6 +7,7 @@ package org.whispersystems.textsecuregcm.filters;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.google.common.net.InetAddresses;
|
||||
import io.grpc.Metadata;
|
||||
import io.grpc.MethodDescriptor;
|
||||
import io.grpc.ServerCall;
|
||||
@@ -73,8 +74,12 @@ public class ExternalRequestFilter implements Filter, ServerInterceptor {
|
||||
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
|
||||
throws IOException, ServletException {
|
||||
|
||||
final InetAddress remoteInetAddress = InetAddress.getByName(
|
||||
(String) request.getAttribute(RemoteAddressFilter.REMOTE_ADDRESS_ATTRIBUTE_NAME));
|
||||
final String remoteAddressString = (String) request.getAttribute(RemoteAddressFilter.REMOTE_ADDRESS_ATTRIBUTE_NAME);
|
||||
|
||||
final InetAddress remoteInetAddress = remoteAddressString != null
|
||||
? InetAddresses.forString(remoteAddressString)
|
||||
: InetAddress.getLoopbackAddress();
|
||||
|
||||
final boolean restricted = shouldBlock(remoteInetAddress);
|
||||
|
||||
Metrics.counter(REQUESTS_COUNTER_NAME,
|
||||
|
||||
+4
@@ -59,6 +59,10 @@ public class RequestStatisticsFilter implements ContainerRequestFilter {
|
||||
private static String resolveIpVersion(@Nonnull final ContainerRequestContext ctx) {
|
||||
final String ipString = (String) ctx.getProperty(RemoteAddressFilter.REMOTE_ADDRESS_ATTRIBUTE_NAME);
|
||||
|
||||
if (ipString == null) {
|
||||
return "unresolved";
|
||||
}
|
||||
|
||||
try {
|
||||
final InetAddress addr = InetAddresses.forString(ipString);
|
||||
if (addr instanceof Inet4Address) {
|
||||
|
||||
+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> {
|
||||
|
||||
+11
-2
@@ -12,6 +12,8 @@ import org.signal.chat.credentials.SimpleCredentialsAnonymousGrpc;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsSelector;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import java.util.HashSet;
|
||||
@@ -23,18 +25,25 @@ public class CredentialsAnonymousGrpcService extends SimpleCredentialsAnonymousG
|
||||
|
||||
private final AccountsManager accountsManager;
|
||||
private final ExternalServiceCredentialsGenerator svrCredentialsGenerator;
|
||||
private final RateLimiters rateLimiters;
|
||||
|
||||
private static final long MAX_SVR_PASSWORD_AGE_SECONDS = TimeUnit.DAYS.toSeconds(30);
|
||||
|
||||
public CredentialsAnonymousGrpcService(final AccountsManager accountsManager,
|
||||
final ExternalServiceCredentialsGenerator svrCredentialsGenerator) {
|
||||
final ExternalServiceCredentialsGenerator svrCredentialsGenerator,
|
||||
final RateLimiters rateLimiters) {
|
||||
|
||||
this.svrCredentialsGenerator = svrCredentialsGenerator;
|
||||
this.accountsManager = accountsManager;
|
||||
this.rateLimiters = rateLimiters;
|
||||
}
|
||||
|
||||
@Override
|
||||
public CheckSvrCredentialsResponse checkSvrCredentials(final CheckSvrCredentialsRequest request) {
|
||||
public CheckSvrCredentialsResponse checkSvrCredentials(final CheckSvrCredentialsRequest request)
|
||||
throws RateLimitExceededException {
|
||||
|
||||
RateLimitUtil.rateLimitByRemoteAddress(rateLimiters.getBackupAuthCheckLimiter());
|
||||
|
||||
final List<String> tokens = request.getPasswordsList().stream().distinct().toList();
|
||||
final List<ExternalServiceCredentialsSelector.CredentialInfo> credentials = ExternalServiceCredentialsSelector.check(
|
||||
new HashSet<>(tokens),
|
||||
|
||||
+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"));
|
||||
|
||||
+10
-1
@@ -5,6 +5,7 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import io.github.resilience4j.circuitbreaker.CallNotPermittedException;
|
||||
import io.grpc.ForwardingServerCall;
|
||||
import io.grpc.Metadata;
|
||||
import io.grpc.ServerCall;
|
||||
@@ -12,6 +13,7 @@ import io.grpc.ServerCallHandler;
|
||||
import io.grpc.ServerInterceptor;
|
||||
import io.grpc.Status;
|
||||
import io.grpc.StatusRuntimeException;
|
||||
import io.lettuce.core.RedisException;
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import org.slf4j.Logger;
|
||||
@@ -66,6 +68,13 @@ public class ErrorMappingInterceptor implements ServerInterceptor {
|
||||
ImpossibleEvents.logImpossible(log, e.getMessage(), e);
|
||||
yield GrpcExceptions.unavailable();
|
||||
}
|
||||
case CallNotPermittedException _ -> GrpcExceptions.unavailable();
|
||||
case RedisException e -> {
|
||||
if (!ExceptionUtils.isBreakerOpen(e)) {
|
||||
log.warn("RPC {} encountered RedisException", call.getMethodDescriptor().getFullMethodName(), e);
|
||||
}
|
||||
yield GrpcExceptions.unavailable();
|
||||
}
|
||||
case null -> {
|
||||
log.error("RPC {} finished with status UNKNOWN: {}",
|
||||
call.getMethodDescriptor().getFullMethodName(), status.getDescription());
|
||||
@@ -73,7 +82,7 @@ public class ErrorMappingInterceptor implements ServerInterceptor {
|
||||
}
|
||||
default -> {
|
||||
log.error("RPC {} finished with status UNKNOWN",
|
||||
call.getMethodDescriptor().getFullMethodName(), status.getCause());
|
||||
call.getMethodDescriptor().getFullMethodName(), cause);
|
||||
yield GrpcExceptions.unavailable();
|
||||
}
|
||||
};
|
||||
|
||||
+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
-15
@@ -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;
|
||||
@@ -18,7 +20,6 @@ import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestListener;
|
||||
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestManager;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.metrics.MessageMetrics;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
|
||||
@@ -38,7 +39,6 @@ import reactor.adapter.JdkFlowAdapter;
|
||||
import reactor.core.observability.micrometer.Micrometer;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.core.publisher.Signal;
|
||||
import reactor.core.publisher.Sinks;
|
||||
|
||||
/// A MessageDispatcher is used to stream messages to an authenticated device and coordinates message acknowledgement,
|
||||
@@ -48,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())
|
||||
@@ -69,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,
|
||||
@@ -76,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;
|
||||
@@ -84,6 +85,7 @@ public class MessageDispatcher {
|
||||
this.pushNotificationScheduler = pushNotificationScheduler;
|
||||
this.disconnectionRequestManager = disconnectionRequestManager;
|
||||
this.clientReleaseManager = clientReleaseManager;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
/// Retrieve messages for the device.
|
||||
@@ -132,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());
|
||||
@@ -149,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;
|
||||
@@ -164,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
|
||||
@@ -184,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);
|
||||
@@ -195,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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+37
-22
@@ -4,6 +4,8 @@ import java.math.BigDecimal;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration;
|
||||
@@ -31,59 +33,72 @@ public class OneTimeDonationUtil {
|
||||
public record LocalizedPayPalDonationLineItem(Locale locale, String itemName){}
|
||||
public record DonationLevelDetails(ReceiptLevel level, Duration levelExpiration){}
|
||||
|
||||
public sealed interface OneTimeDonationRequestValidationResult permits OneTimeDonationRequestValidationResult.Success,
|
||||
OneTimeDonationRequestValidationResult.UnsupportedCurrency,
|
||||
OneTimeDonationRequestValidationResult.UnsupportedLevel,
|
||||
OneTimeDonationRequestValidationResult.AmountBelowMinimum,
|
||||
OneTimeDonationRequestValidationResult.AmountAboveSepaLimit {
|
||||
/// Thrown when a one-time donation request that failed validation
|
||||
public static class ValidationException extends Exception {
|
||||
/// A human-readable description of the failure, suitable for logging
|
||||
private final String description;
|
||||
/// The fields of the REST error response body
|
||||
private final Map<String, String> errorBody;
|
||||
|
||||
record Success() implements OneTimeDonationRequestValidationResult {}
|
||||
public ValidationException(final String description, final Map<String, String> errorBody) {
|
||||
this.description = description;
|
||||
this.errorBody = errorBody;
|
||||
}
|
||||
|
||||
record UnsupportedCurrency() implements OneTimeDonationRequestValidationResult {}
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
record UnsupportedLevel() implements OneTimeDonationRequestValidationResult {}
|
||||
|
||||
record AmountBelowMinimum(BigDecimal minimum) implements OneTimeDonationRequestValidationResult {}
|
||||
|
||||
record AmountAboveSepaLimit(BigDecimal maximum) implements OneTimeDonationRequestValidationResult {}
|
||||
public Map<String, String> getErrorBody() {
|
||||
return errorBody;
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isOneTimeDonationLevel(final long level) {
|
||||
return ReceiptLevel.lookupLevel(level)
|
||||
.map(rl -> rl == ReceiptLevel.ONE_TIME_DONATION || rl == ReceiptLevel.ONE_TIME_GIFT_DONATION)
|
||||
.orElse(false);
|
||||
}
|
||||
|
||||
/// Validates a request is for a valid one-time donation level and is at least the configured minimum for the currency
|
||||
/// and payment method.
|
||||
public static OneTimeDonationRequestValidationResult validateOneTimeDonationRequest(
|
||||
///
|
||||
/// @return the validation error, or empty if the request is valid
|
||||
public static void validateOneTimeDonationRequest(
|
||||
final String currency,
|
||||
final long amount,
|
||||
final long level,
|
||||
final PaymentMethod paymentMethod,
|
||||
final OneTimeDonationConfiguration oneTimeDonationConfiguration,
|
||||
final CustomerAwareSubscriptionPaymentProcessor manager
|
||||
) {
|
||||
) throws ValidationException {
|
||||
|
||||
if (ReceiptLevel.lookupLevel(level)
|
||||
.map(rl -> rl != ReceiptLevel.ONE_TIME_DONATION && rl != ReceiptLevel.ONE_TIME_GIFT_DONATION)
|
||||
.orElse(true)) {
|
||||
return new OneTimeDonationRequestValidationResult.UnsupportedLevel();
|
||||
if (!isOneTimeDonationLevel(level)) {
|
||||
throw new ValidationException("Not a one-time donation level", Map.of("error", "invalid_level"));
|
||||
}
|
||||
|
||||
if (!manager.getSupportedCurrenciesForPaymentMethod(paymentMethod)
|
||||
.contains(currency.toLowerCase(Locale.ROOT))) {
|
||||
return new OneTimeDonationRequestValidationResult.UnsupportedCurrency();
|
||||
throw new ValidationException(
|
||||
"Currency '" + currency + "' is not supported for payment method " + paymentMethod,
|
||||
Map.of("error", "unsupported_currency"));
|
||||
}
|
||||
|
||||
final BigDecimal minCurrencyAmount =
|
||||
oneTimeDonationConfiguration.currencies().get(currency.toLowerCase(Locale.ROOT)).minimum();
|
||||
if (SubscriptionCurrencyUtil.convertPrimaryToMinorUnits(currency, minCurrencyAmount) > amount) {
|
||||
return new OneTimeDonationRequestValidationResult.AmountBelowMinimum(minCurrencyAmount);
|
||||
throw new ValidationException(
|
||||
"Amount is below the minimum for currency '" + currency + "'",
|
||||
Map.of("error", "amount_below_currency_minimum", "minimum", minCurrencyAmount.toString()));
|
||||
}
|
||||
|
||||
if (paymentMethod == PaymentMethod.SEPA_DEBIT) {
|
||||
final BigDecimal sepaMaximumEuros = oneTimeDonationConfiguration.sepaMaximumEuros();
|
||||
if (amount > SubscriptionCurrencyUtil.convertPrimaryToMinorUnits(EURO_CURRENCY_CODE, sepaMaximumEuros)) {
|
||||
return new OneTimeDonationRequestValidationResult.AmountAboveSepaLimit(sepaMaximumEuros);
|
||||
throw new ValidationException("Amount is above the SEPA Direct Debit maximum",
|
||||
Map.of("error", "amount_above_sepa_limit", "maximum", sepaMaximumEuros.toString()));
|
||||
}
|
||||
}
|
||||
return new OneTimeDonationRequestValidationResult.Success();
|
||||
}
|
||||
|
||||
public static LocalizedPayPalDonationLineItem localizePayPalDonationLineItem(
|
||||
|
||||
+82
-147
@@ -5,7 +5,6 @@
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil.getClientPlatform;
|
||||
import static org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil.toChargeFailure;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
@@ -17,19 +16,19 @@ import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Optional;
|
||||
import org.signal.chat.errors.FailedPrecondition;
|
||||
import org.signal.chat.errors.FailedZkAuthentication;
|
||||
import org.signal.chat.errors.NotFound;
|
||||
import org.signal.chat.purchase.AmountAboveSepaLimitError;
|
||||
import org.signal.chat.purchase.AmountBelowMinimumError;
|
||||
import org.signal.chat.purchase.ConfirmPayPalBoostRequest;
|
||||
import org.signal.chat.purchase.ConfirmPayPalBoostResponse;
|
||||
import org.signal.chat.purchase.CreateBoostReceiptCredentialRequest;
|
||||
import org.signal.chat.purchase.CreateBoostReceiptCredentialResponse;
|
||||
import org.signal.chat.purchase.CreateBoostRequest;
|
||||
import org.signal.chat.purchase.CreateBoostResponse;
|
||||
import org.signal.chat.purchase.CreateStripeBoostRequest;
|
||||
import org.signal.chat.purchase.CreateStripeBoostResponse;
|
||||
import org.signal.chat.purchase.CreatePayPalBoostRequest;
|
||||
import org.signal.chat.purchase.CreatePayPalBoostResponse;
|
||||
import org.signal.chat.purchase.PaymentRequired;
|
||||
import org.signal.chat.purchase.SimpleOneTimeDonationsGrpc;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.VerificationFailedException;
|
||||
@@ -42,16 +41,16 @@ import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.purchases.BraintreeManager;
|
||||
import org.whispersystems.textsecuregcm.purchases.CustomerAwareSubscriptionPaymentProcessor;
|
||||
import org.whispersystems.textsecuregcm.purchases.PayPalDonationsTranslator;
|
||||
import org.whispersystems.textsecuregcm.purchases.PaymentDetails;
|
||||
import org.whispersystems.textsecuregcm.purchases.PaymentProvider;
|
||||
import org.whispersystems.textsecuregcm.purchases.PurchaseInvalidAmountException;
|
||||
import org.whispersystems.textsecuregcm.purchases.PurchaseAmountTooLargeException;
|
||||
import org.whispersystems.textsecuregcm.purchases.PurchaseNotFoundException;
|
||||
import org.whispersystems.textsecuregcm.purchases.PurchasePaymentRequiredException;
|
||||
import org.whispersystems.textsecuregcm.purchases.PurchaseProcessorException;
|
||||
import org.whispersystems.textsecuregcm.purchases.PurchaseReceiptRequestedForOpenPaymentException;
|
||||
import org.whispersystems.textsecuregcm.purchases.StripeManager;
|
||||
import org.whispersystems.textsecuregcm.purchases.SubscriptionCurrencyUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.DonationPermitsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.IssuedReceiptsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.OneTimeDonationsManager;
|
||||
@@ -94,121 +93,77 @@ public class OneTimeDonationsGrpcService extends SimpleOneTimeDonationsGrpc.OneT
|
||||
}
|
||||
|
||||
@Override
|
||||
public CreateBoostResponse createBoost(final CreateBoostRequest request)
|
||||
public CreateStripeBoostResponse createStripeBoost(final CreateStripeBoostRequest request)
|
||||
throws RateLimitExceededException {
|
||||
RateLimitUtil.rateLimitByRemoteAddress(rateLimiters.forDescriptor(RateLimiters.For.ONE_TIME_DONATION));
|
||||
|
||||
try {
|
||||
final DonationPermit donationPermit = new DonationPermit(request.getDonationPermit().toByteArray());
|
||||
if (!donationPermitsManager.spend(donationPermit)) {
|
||||
return CreateBoostResponse.newBuilder()
|
||||
.setPermitRejected(FailedZkAuthentication.newBuilder()
|
||||
.setDescription("donation permit rejected")
|
||||
.build())
|
||||
.build();
|
||||
}
|
||||
} catch (InvalidInputException | VerificationFailedException _) {
|
||||
return CreateBoostResponse.newBuilder()
|
||||
.setPermitRejected(FailedZkAuthentication.newBuilder()
|
||||
.setDescription("donation permit rejected")
|
||||
.build())
|
||||
.build();
|
||||
}
|
||||
|
||||
final org.whispersystems.textsecuregcm.purchases.PaymentMethod paymentMethod =
|
||||
switch (request.getPaymentMethod()) {
|
||||
case PAYMENT_METHOD_CARD -> org.whispersystems.textsecuregcm.purchases.PaymentMethod.CARD;
|
||||
case PAYMENT_METHOD_SEPA_DEBIT -> org.whispersystems.textsecuregcm.purchases.PaymentMethod.SEPA_DEBIT;
|
||||
case PAYMENT_METHOD_IDEAL -> org.whispersystems.textsecuregcm.purchases.PaymentMethod.IDEAL;
|
||||
default -> throw GrpcExceptions.fieldViolation("payment_method", "Unsupported payment method");
|
||||
default -> throw new IllegalStateException("payment_method should already have been validated");
|
||||
};
|
||||
|
||||
final OneTimeDonationUtil.OneTimeDonationRequestValidationResult validationResult =
|
||||
OneTimeDonationUtil.validateOneTimeDonationRequest(
|
||||
request.getCurrency(),
|
||||
request.getAmount(),
|
||||
request.getLevel(),
|
||||
paymentMethod,
|
||||
oneTimeDonationConfiguration,
|
||||
stripeManager);
|
||||
|
||||
return switch (validationResult) {
|
||||
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.UnsupportedLevel _ ->
|
||||
CreateBoostResponse.newBuilder()
|
||||
.setUnsupportedLevel(FailedPrecondition.getDefaultInstance()).build();
|
||||
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.UnsupportedCurrency _ ->
|
||||
CreateBoostResponse.newBuilder()
|
||||
.setUnsupportedCurrency(FailedPrecondition.getDefaultInstance()).build();
|
||||
case final OneTimeDonationUtil.OneTimeDonationRequestValidationResult.AmountBelowMinimum r ->
|
||||
CreateBoostResponse.newBuilder()
|
||||
.setAmountBelowMinimum(AmountBelowMinimumError.newBuilder()
|
||||
.setMinimum(SubscriptionCurrencyUtil.convertPrimaryToMinorUnits(request.getCurrency(),
|
||||
r.minimum()))
|
||||
.build()).build();
|
||||
case final OneTimeDonationUtil.OneTimeDonationRequestValidationResult.AmountAboveSepaLimit r ->
|
||||
CreateBoostResponse.newBuilder()
|
||||
.setAmountAboveSepaLimit(AmountAboveSepaLimitError.newBuilder()
|
||||
.setMaximum(SubscriptionCurrencyUtil.convertPrimaryToMinorUnits(
|
||||
OneTimeDonationUtil.EURO_CURRENCY_CODE, r.maximum()))
|
||||
.build()).build();
|
||||
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.Success _ -> {
|
||||
try {
|
||||
final com.stripe.model.PaymentIntent paymentIntent = stripeManager.createPaymentIntent(
|
||||
request.getCurrency(), request.getAmount(), request.getLevel(),
|
||||
getClientPlatform(RequestAttributesUtil.getUserAgent().orElse(null)));
|
||||
yield CreateBoostResponse.newBuilder().setClientSecret(paymentIntent.getClientSecret()).build();
|
||||
} catch (final PurchaseInvalidAmountException e) {
|
||||
yield CreateBoostResponse.newBuilder()
|
||||
.setInvalidAmount(FailedPrecondition.newBuilder()
|
||||
.setDescription(e.getErrorCode()).build())
|
||||
.build();
|
||||
}
|
||||
try {
|
||||
OneTimeDonationUtil.validateOneTimeDonationRequest(
|
||||
request.getCurrency(), request.getAmount(), request.getLevel(), paymentMethod, oneTimeDonationConfiguration, stripeManager);
|
||||
final DonationPermit donationPermit = new DonationPermit(request.getDonationPermit().toByteArray());
|
||||
if (!donationPermitsManager.spend(donationPermit)) {
|
||||
return CreateStripeBoostResponse.newBuilder()
|
||||
.setPermitRejected(FailedZkAuthentication.newBuilder()
|
||||
.setDescription("donation permit rejected")
|
||||
.build())
|
||||
.build();
|
||||
}
|
||||
};
|
||||
} catch (InvalidInputException | VerificationFailedException _) {
|
||||
return CreateStripeBoostResponse.newBuilder()
|
||||
.setPermitRejected(FailedZkAuthentication.newBuilder()
|
||||
.setDescription("donation permit rejected")
|
||||
.build())
|
||||
.build();
|
||||
} catch (OneTimeDonationUtil.ValidationException e) {
|
||||
return CreateStripeBoostResponse.newBuilder()
|
||||
.setInvalidSelection(FailedPrecondition.newBuilder().setDescription(e.getDescription()).build())
|
||||
.build();
|
||||
}
|
||||
|
||||
try {
|
||||
final com.stripe.model.PaymentIntent paymentIntent = stripeManager.createPaymentIntent(
|
||||
request.getCurrency(), request.getAmount(), request.getLevel(),
|
||||
getClientPlatform(RequestAttributesUtil.getUserAgent().orElse(null)));
|
||||
return CreateStripeBoostResponse.newBuilder().setClientSecret(paymentIntent.getClientSecret()).build();
|
||||
} catch (final PurchaseAmountTooLargeException e) {
|
||||
return CreateStripeBoostResponse.newBuilder()
|
||||
.setInvalidSelection(FailedPrecondition.newBuilder()
|
||||
.setDescription("Amount exceeds the payment processor's maximum for currency " + request.getCurrency()))
|
||||
.build();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public CreatePayPalBoostResponse createPayPalBoost(final CreatePayPalBoostRequest request) throws IOException {
|
||||
|
||||
final OneTimeDonationUtil.OneTimeDonationRequestValidationResult validationResult =
|
||||
OneTimeDonationUtil.validateOneTimeDonationRequest(
|
||||
request.getCurrency(),
|
||||
request.getAmount(),
|
||||
request.getLevel(),
|
||||
org.whispersystems.textsecuregcm.purchases.PaymentMethod.PAYPAL,
|
||||
oneTimeDonationConfiguration,
|
||||
braintreeManager);
|
||||
try {
|
||||
OneTimeDonationUtil.validateOneTimeDonationRequest(request.getCurrency(), request.getAmount(), request.getLevel(), org.whispersystems.textsecuregcm.purchases.PaymentMethod.PAYPAL, oneTimeDonationConfiguration, braintreeManager);
|
||||
} catch (OneTimeDonationUtil.ValidationException e) {
|
||||
return CreatePayPalBoostResponse.newBuilder()
|
||||
.setInvalidSelection(FailedPrecondition.newBuilder().setDescription(e.getDescription()).build())
|
||||
.build();
|
||||
}
|
||||
|
||||
return switch (validationResult) {
|
||||
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.UnsupportedLevel _ ->
|
||||
CreatePayPalBoostResponse.newBuilder()
|
||||
.setUnsupportedLevel(FailedPrecondition.getDefaultInstance()).build();
|
||||
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.UnsupportedCurrency _ ->
|
||||
CreatePayPalBoostResponse.newBuilder()
|
||||
.setUnsupportedCurrency(FailedPrecondition.getDefaultInstance()).build();
|
||||
case final OneTimeDonationUtil.OneTimeDonationRequestValidationResult.AmountBelowMinimum r ->
|
||||
CreatePayPalBoostResponse.newBuilder()
|
||||
.setAmountBelowMinimum(AmountBelowMinimumError.newBuilder()
|
||||
.setMinimum(SubscriptionCurrencyUtil.convertPrimaryToMinorUnits(request.getCurrency(),
|
||||
r.minimum()))
|
||||
.build()).build();
|
||||
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.AmountAboveSepaLimit _ ->
|
||||
throw new IllegalStateException("SEPA limit should not trigger for PayPal");
|
||||
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.Success _ -> {
|
||||
final List<Locale> acceptableLocales = RequestAttributesUtil.getAvailableAcceptedLocales();
|
||||
final OneTimeDonationUtil.LocalizedPayPalDonationLineItem localizedLineItem = OneTimeDonationUtil.localizePayPalDonationLineItem(
|
||||
payPalDonationsTranslator, acceptableLocales);
|
||||
final BraintreeManager.PayPalOneTimePaymentApprovalDetails approvalDetails =
|
||||
braintreeManager.createOneTimePayment(
|
||||
request.getCurrency().toUpperCase(Locale.ROOT), request.getAmount(),
|
||||
localizedLineItem.locale().toLanguageTag(), request.getReturnUrl(), request.getCancelUrl(),
|
||||
localizedLineItem.itemName());
|
||||
yield CreatePayPalBoostResponse.newBuilder()
|
||||
.setResult(CreatePayPalBoostResponse.CreatePayPalBoostResult.newBuilder()
|
||||
.setApprovalUrl(approvalDetails.approvalUrl())
|
||||
.setPaymentId(approvalDetails.paymentId()).build()).build();
|
||||
}
|
||||
};
|
||||
final List<Locale> acceptableLocales = RequestAttributesUtil.getAvailableAcceptedLocales();
|
||||
final OneTimeDonationUtil.LocalizedPayPalDonationLineItem localizedLineItem = OneTimeDonationUtil.localizePayPalDonationLineItem(
|
||||
payPalDonationsTranslator, acceptableLocales);
|
||||
final BraintreeManager.PayPalOneTimePaymentApprovalDetails approvalDetails =
|
||||
braintreeManager.createOneTimePayment(
|
||||
request.getCurrency().toUpperCase(Locale.ROOT), request.getAmount(),
|
||||
localizedLineItem.locale().toLanguageTag(), request.getReturnUrl(), request.getCancelUrl(),
|
||||
localizedLineItem.itemName());
|
||||
return CreatePayPalBoostResponse.newBuilder()
|
||||
.setResult(CreatePayPalBoostResponse.CreatePayPalBoostResult.newBuilder()
|
||||
.setApprovalUrl(approvalDetails.approvalUrl())
|
||||
.setPaymentId(approvalDetails.paymentId()).build()).build();
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -216,48 +171,28 @@ public class OneTimeDonationsGrpcService extends SimpleOneTimeDonationsGrpc.OneT
|
||||
throws RateLimitExceededException, IOException {
|
||||
RateLimitUtil.rateLimitByRemoteAddress(rateLimiters.forDescriptor(RateLimiters.For.ONE_TIME_DONATION));
|
||||
|
||||
final OneTimeDonationUtil.OneTimeDonationRequestValidationResult validationResult =
|
||||
OneTimeDonationUtil.validateOneTimeDonationRequest(
|
||||
request.getCurrency(),
|
||||
request.getAmount(),
|
||||
request.getLevel(),
|
||||
org.whispersystems.textsecuregcm.purchases.PaymentMethod.PAYPAL,
|
||||
oneTimeDonationConfiguration,
|
||||
braintreeManager);
|
||||
|
||||
return switch (validationResult) {
|
||||
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.UnsupportedLevel _ ->
|
||||
ConfirmPayPalBoostResponse.newBuilder()
|
||||
.setUnsupportedLevel(FailedPrecondition.getDefaultInstance()).build();
|
||||
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.UnsupportedCurrency _ ->
|
||||
ConfirmPayPalBoostResponse.newBuilder()
|
||||
.setUnsupportedCurrency(FailedPrecondition.getDefaultInstance()).build();
|
||||
case final OneTimeDonationUtil.OneTimeDonationRequestValidationResult.AmountBelowMinimum r ->
|
||||
ConfirmPayPalBoostResponse.newBuilder()
|
||||
.setAmountBelowMinimum(AmountBelowMinimumError.newBuilder()
|
||||
.setMinimum(SubscriptionCurrencyUtil.convertPrimaryToMinorUnits(request.getCurrency(),
|
||||
r.minimum()))
|
||||
.build()).build();
|
||||
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.AmountAboveSepaLimit _ ->
|
||||
throw new IllegalStateException("SEPA limit should not trigger for PayPal");
|
||||
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.Success _ -> {
|
||||
final BraintreeManager.PayPalChargeSuccessDetails chargeSuccessDetails;
|
||||
try {
|
||||
chargeSuccessDetails = braintreeManager.captureOneTimePayment(
|
||||
request.getPayerId(), request.getPaymentId(), request.getPaymentToken(),
|
||||
request.getCurrency(), request.getAmount(), request.getLevel(),
|
||||
SubscriptionsUtil.getClientPlatform(RequestAttributesUtil.getUserAgent().orElse(null)));
|
||||
oneTimeDonationsManager.putPaidAt(chargeSuccessDetails.paymentId(), clock.instant());
|
||||
yield ConfirmPayPalBoostResponse.newBuilder()
|
||||
.setResult(ConfirmPayPalBoostResponse.ConfirmPayPalBoostResult.newBuilder()
|
||||
.setPaymentId(chargeSuccessDetails.paymentId()).build()).build();
|
||||
} catch (final PurchaseProcessorException e) {
|
||||
yield ConfirmPayPalBoostResponse.newBuilder()
|
||||
.setChargeFailure(SubscriptionsUtil.toChargeFailure(e.getProcessor(), e.getChargeFailure()))
|
||||
.build();
|
||||
}
|
||||
}
|
||||
};
|
||||
try {
|
||||
OneTimeDonationUtil.validateOneTimeDonationRequest(request.getCurrency(), request.getAmount(), request.getLevel(),
|
||||
org.whispersystems.textsecuregcm.purchases.PaymentMethod.PAYPAL, oneTimeDonationConfiguration,
|
||||
braintreeManager);
|
||||
final BraintreeManager.PayPalChargeSuccessDetails chargeSuccessDetails = braintreeManager.captureOneTimePayment(
|
||||
request.getPayerId(), request.getPaymentId(), request.getPaymentToken(),
|
||||
request.getCurrency(), request.getAmount(), request.getLevel(),
|
||||
SubscriptionsUtil.getClientPlatform(RequestAttributesUtil.getUserAgent().orElse(null)));
|
||||
oneTimeDonationsManager.putPaidAt(chargeSuccessDetails.paymentId(), clock.instant());
|
||||
return ConfirmPayPalBoostResponse.newBuilder()
|
||||
.setResult(ConfirmPayPalBoostResponse.ConfirmPayPalBoostResult.newBuilder()
|
||||
.setPaymentId(chargeSuccessDetails.paymentId()).build()).build();
|
||||
} catch (OneTimeDonationUtil.ValidationException e) {
|
||||
return ConfirmPayPalBoostResponse.newBuilder()
|
||||
.setInvalidSelection(FailedPrecondition.newBuilder().setDescription(e.getDescription()).build())
|
||||
.build();
|
||||
} catch (final PurchaseProcessorException e) {
|
||||
return ConfirmPayPalBoostResponse.newBuilder()
|
||||
.setPaymentRequired(PaymentRequired.newBuilder()
|
||||
.setChargeFailure(SubscriptionsUtil.toChargeFailure(e.getProcessor(), e.getChargeFailure())))
|
||||
.build();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
+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();
|
||||
}
|
||||
|
||||
|
||||
+6
-4
@@ -67,11 +67,13 @@ public class ProductConfigurationGrpcService extends SimpleProductConfigurationG
|
||||
donationLevels.put(ReceiptLevel.ONE_TIME_DONATION.getValue(),
|
||||
LevelConfiguration.newBuilder()
|
||||
.setBadgeId(oneTimeDonationConfiguration.boost().badge())
|
||||
.setBadgeDurationSeconds(oneTimeDonationConfiguration.boost().expiration().toSeconds()).build());
|
||||
.setBadgeDurationSeconds(Math.toIntExact(oneTimeDonationConfiguration.boost().expiration().toSeconds()))
|
||||
.build());
|
||||
donationLevels.put(ReceiptLevel.ONE_TIME_GIFT_DONATION.getValue(),
|
||||
LevelConfiguration.newBuilder()
|
||||
.setBadgeId(oneTimeDonationConfiguration.gift().badge())
|
||||
.setBadgeDurationSeconds(oneTimeDonationConfiguration.gift().expiration().toSeconds()).build());
|
||||
.setBadgeDurationSeconds(Math.toIntExact(oneTimeDonationConfiguration.gift().expiration().toSeconds()))
|
||||
.build());
|
||||
return donationLevels;
|
||||
}
|
||||
|
||||
@@ -83,11 +85,11 @@ public class ProductConfigurationGrpcService extends SimpleProductConfigurationG
|
||||
e -> BackupLevelConfiguration.newBuilder()
|
||||
.setStorageAllowanceBytes(backupMediaStorageAllowanceBytes)
|
||||
.setPlayProductId(e.getValue().playProductId())
|
||||
.setMediaTtlDays(e.getValue().mediaTtl().toDays())
|
||||
.setMediaTtlDays(Math.toIntExact(e.getValue().mediaTtl().toDays()))
|
||||
.build()));
|
||||
return BackupConfiguration.newBuilder()
|
||||
.putAllLevels(backupLevels)
|
||||
.setFreeTierMediaDays(subscriptionConfiguration.getbackupFreeTierMediaDuration().toDays())
|
||||
.setFreeTierMediaDays(Math.toIntExact(subscriptionConfiguration.getbackupFreeTierMediaDuration().toDays()))
|
||||
.build();
|
||||
}
|
||||
|
||||
|
||||
+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
-10
@@ -18,9 +18,11 @@ 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;
|
||||
import org.signal.chat.profile.ExpectedVersionConflict;
|
||||
import org.signal.chat.profile.GetAvatarCredentialRequest;
|
||||
import org.signal.chat.profile.GetAvatarCredentialResponse;
|
||||
import org.signal.chat.profile.GetProfileRequest;
|
||||
@@ -72,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,
|
||||
@@ -85,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) {
|
||||
@@ -96,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;
|
||||
@@ -115,9 +120,11 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
|
||||
final boolean currentVersionMatchesExpected = Arrays.equals(account.getCurrentProfileVersion().orElse(new byte[0]), expectedCurrentVersion);
|
||||
|
||||
if (!currentVersionMatchesExpected) {
|
||||
return SetProfileResponse.newBuilder().setExpectedVersionWriteConflict(FailedPrecondition.newBuilder()
|
||||
.setDescription("current and expected profile versions must match")
|
||||
.build()).build();
|
||||
final ExpectedVersionConflict conflict = account.getCurrentProfileVersion()
|
||||
.map(v -> ExpectedVersionConflict.newBuilder().setCurrentProfileVersion(ByteString.copyFrom(v)).build())
|
||||
.orElseGet(ExpectedVersionConflict::getDefaultInstance);
|
||||
return SetProfileResponse.newBuilder().setExpectedVersionWriteConflict(conflict)
|
||||
.build();
|
||||
}
|
||||
|
||||
final byte[] version = request.getVersion().toByteArray();
|
||||
@@ -190,12 +197,13 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
|
||||
a.setBadges(clock, updatedBadges);
|
||||
});
|
||||
|
||||
} catch (final WriteConflictException _) {
|
||||
return SetProfileResponse.newBuilder()
|
||||
.setExpectedVersionWriteConflict(FailedPrecondition.newBuilder()
|
||||
.setDescription("current and expected version mismatch")
|
||||
.build())
|
||||
.build();
|
||||
} catch (final WriteConflictException e) {
|
||||
|
||||
final ExpectedVersionConflict conflict = e.getConflictedValue()
|
||||
.map(v -> ExpectedVersionConflict.newBuilder().setCurrentProfileVersion(ByteString.copyFrom(v)).build())
|
||||
.orElseGet(ExpectedVersionConflict::getDefaultInstance);
|
||||
|
||||
return SetProfileResponse.newBuilder().setExpectedVersionWriteConflict(conflict).build();
|
||||
}
|
||||
|
||||
if (request.getV1Request().getAvatarChange() != AvatarChange.AVATAR_CHANGE_UNCHANGED && avatarData.currentAvatar().isPresent()) {
|
||||
@@ -264,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());
|
||||
}
|
||||
|
||||
+1
-3
@@ -98,9 +98,7 @@ public class RemoteConfigurationGrpcService extends SimpleRemoteConfigurationGrp
|
||||
.setEtag(etag(badges))
|
||||
.build();
|
||||
|
||||
// This could race and multiple threads could decide to build-and-cache. That's fine, they should all calculate
|
||||
// the same etag.
|
||||
localeToBadgesEtag.put(locale, taggedBadges.getEtag());
|
||||
localeToBadgesEtag.computeIfAbsent(locale, _ -> taggedBadges.getEtag());
|
||||
return GetBadgesResponse.newBuilder().setTaggedBadges(taggedBadges).build();
|
||||
}
|
||||
|
||||
|
||||
+53
-43
@@ -18,8 +18,8 @@ import org.signal.chat.errors.FailedZkAuthentication;
|
||||
import org.signal.chat.errors.NotFound;
|
||||
import org.signal.chat.purchase.CreatePayPalPaymentMethodRequest;
|
||||
import org.signal.chat.purchase.CreatePayPalPaymentMethodResponse;
|
||||
import org.signal.chat.purchase.CreatePaymentMethodRequest;
|
||||
import org.signal.chat.purchase.CreatePaymentMethodResponse;
|
||||
import org.signal.chat.purchase.CreateStripePaymentMethodRequest;
|
||||
import org.signal.chat.purchase.CreateStripePaymentMethodResponse;
|
||||
import org.signal.chat.purchase.DeleteSubscriberRequest;
|
||||
import org.signal.chat.purchase.DeleteSubscriberResponse;
|
||||
import org.signal.chat.purchase.GetBankMandateRequest;
|
||||
@@ -28,6 +28,7 @@ import org.signal.chat.purchase.GetReceiptCredentialRequest;
|
||||
import org.signal.chat.purchase.GetReceiptCredentialResponse;
|
||||
import org.signal.chat.purchase.GetSubscriptionInformationRequest;
|
||||
import org.signal.chat.purchase.GetSubscriptionInformationResponse;
|
||||
import org.signal.chat.purchase.PaymentRequired;
|
||||
import org.signal.chat.purchase.SetDefaultPaymentMethodRequest;
|
||||
import org.signal.chat.purchase.SetDefaultPaymentMethodResponse;
|
||||
import org.signal.chat.purchase.SetIapSubscriptionRequest;
|
||||
@@ -170,42 +171,38 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
|
||||
}
|
||||
|
||||
@Override
|
||||
public CreatePaymentMethodResponse createPaymentMethod(final CreatePaymentMethodRequest request) {
|
||||
public CreateStripePaymentMethodResponse createStripePaymentMethod(final CreateStripePaymentMethodRequest request) {
|
||||
final SubscriberCredentials subscriberCredentials = SubscriberCredentials.process(
|
||||
request.getSubscriberId().toByteArray(), clock);
|
||||
final CustomerAwareSubscriptionPaymentProcessor customerAwareSubscriptionPaymentProcessor = switch (request.getPaymentMethod()) {
|
||||
case PAYMENT_METHOD_CARD, PAYMENT_METHOD_SEPA_DEBIT, PAYMENT_METHOD_IDEAL -> stripeManager;
|
||||
default -> throw GrpcExceptions.fieldViolation("payment_method", "Unsupported payment method");
|
||||
};
|
||||
|
||||
try {
|
||||
final DonationPermit permit = new DonationPermit(request.getDonationPermit().toByteArray());
|
||||
|
||||
if (!SubscriptionsUtil.verifyAndSpendDonationPermit(permit, donationPermitsManager, clock)) {
|
||||
return CreatePaymentMethodResponse.newBuilder()
|
||||
return CreateStripePaymentMethodResponse.newBuilder()
|
||||
.setPermitRejected(FailedZkAuthentication.getDefaultInstance())
|
||||
.build();
|
||||
}
|
||||
} catch (final InvalidInputException _) {
|
||||
throw GrpcExceptions.invalidArguments("invalid donation permit");
|
||||
} catch (final VerificationFailedException _) {
|
||||
return CreatePaymentMethodResponse.newBuilder()
|
||||
return CreateStripePaymentMethodResponse.newBuilder()
|
||||
.setPermitRejected(FailedZkAuthentication.getDefaultInstance())
|
||||
.build();
|
||||
}
|
||||
|
||||
try {
|
||||
final String token = subscriptionManager.addPaymentMethodToCustomer(subscriberCredentials,
|
||||
customerAwareSubscriptionPaymentProcessor,
|
||||
stripeManager,
|
||||
getClientPlatform(RequestAttributesUtil.getUserAgent().orElse(null)),
|
||||
CustomerAwareSubscriptionPaymentProcessor::createPaymentMethodSetupToken);
|
||||
return CreatePaymentMethodResponse.newBuilder().setResult(
|
||||
CreatePaymentMethodResponse.CreatePaymentMethodResult.newBuilder().setClientSecret(token)
|
||||
.setPaymentProvider(customerAwareSubscriptionPaymentProcessor.getProvider().toProto()).build()).build();
|
||||
return CreateStripePaymentMethodResponse.newBuilder().setResult(
|
||||
CreateStripePaymentMethodResponse.CreateStripePaymentMethodResult.newBuilder().setClientSecret(token).build())
|
||||
.build();
|
||||
} catch (final PurchaseNotFoundException | PurchaseForbiddenException _) {
|
||||
return CreatePaymentMethodResponse.newBuilder().setSubscriberNotFound(NotFound.newBuilder()).build();
|
||||
return CreateStripePaymentMethodResponse.newBuilder().setSubscriberNotFound(NotFound.newBuilder()).build();
|
||||
} catch (final PurchaseProcessorConflictException e) {
|
||||
return CreatePaymentMethodResponse.newBuilder().setSubscriptionProcessorConflict(
|
||||
return CreateStripePaymentMethodResponse.newBuilder().setSubscriptionProcessorConflict(
|
||||
FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
|
||||
}
|
||||
}
|
||||
@@ -263,13 +260,13 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
|
||||
// a missing customer ID indicates the client made requests out of order,
|
||||
// and needs to call create_payment_method to create a customer for the given payment method
|
||||
.orElseGet(() -> SetDefaultPaymentMethodResponse.newBuilder()
|
||||
.setPaymentMethodNotSetUp(FailedPrecondition.newBuilder().build())
|
||||
.setFailedPrecondition(FailedPrecondition.newBuilder().build())
|
||||
.build());
|
||||
} catch (final PurchaseNotFoundException | PurchaseForbiddenException _) {
|
||||
return SetDefaultPaymentMethodResponse.newBuilder().setSubscriberNotFound(NotFound.newBuilder().build()).build();
|
||||
} catch (final PurchaseProcessorConflictException _) {
|
||||
return SetDefaultPaymentMethodResponse.newBuilder()
|
||||
.setPaymentMethodNotSetUp(FailedPrecondition.newBuilder().build())
|
||||
.setFailedPrecondition(FailedPrecondition.newBuilder().build())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
@@ -284,7 +281,7 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
|
||||
// Here, invalid arguments must mean that the client has made requests out of order, and needs to finish
|
||||
// setting up the paymentMethod first
|
||||
return SetDefaultPaymentMethodResponse.newBuilder()
|
||||
.setPaymentMethodNotSetUp(FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build())
|
||||
.setFailedPrecondition(FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build())
|
||||
.build();
|
||||
} catch (final IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
@@ -298,10 +295,11 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
|
||||
request.getSubscriberId().toByteArray(), clock);
|
||||
try {
|
||||
final Subscriptions.Record record = subscriptionManager.getSubscriber(subscriberCredentials);
|
||||
return record.getProcessorCustomer().map(processorCustomer ->
|
||||
setSubscriptionLevelForCustomer(processorCustomer, subscriberCredentials, record, request))
|
||||
return record.getProcessorCustomer()
|
||||
.map(processorCustomer -> setSubscriptionLevelForCustomer(processorCustomer, subscriberCredentials, record, request))
|
||||
.orElseGet(() -> SetSubscriptionLevelResponse.newBuilder()
|
||||
.setPaymentMethodNotSetUp(FailedPrecondition.newBuilder().build())
|
||||
.setFailedPrecondition(FailedPrecondition.newBuilder()
|
||||
.setDescription("No payment method has been created for the subscriber"))
|
||||
.build());
|
||||
|
||||
} catch (final PurchaseNotFoundException | PurchaseForbiddenException _) {
|
||||
@@ -312,31 +310,35 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
|
||||
private SetSubscriptionLevelResponse setSubscriptionLevelForCustomer(final ProcessorCustomer processorCustomer,
|
||||
final SubscriberCredentials subscriberCredentials, final Subscriptions.Record subscriptionRecord,
|
||||
final SetSubscriptionLevelRequest request) {
|
||||
final CustomerAwareSubscriptionPaymentProcessor manager;
|
||||
switch (processorCustomer.processor()) {
|
||||
case STRIPE -> manager = stripeManager;
|
||||
case BRAINTREE -> manager = braintreeManager;
|
||||
default -> {
|
||||
return SetSubscriptionLevelResponse.newBuilder()
|
||||
.setFailedPrecondition(FailedPrecondition.newBuilder()
|
||||
.setDescription(String.format("Subscription level %s invalid for %s", request.getLevel(), processorCustomer.processor())))
|
||||
.build();
|
||||
}
|
||||
}
|
||||
|
||||
final SubscriptionLevelConfiguration config = subscriptionConfiguration.getSubscriptionLevel(request.getLevel());
|
||||
if (config == null) {
|
||||
return SetSubscriptionLevelResponse.newBuilder().setUnsupportedLevel(FailedPrecondition.newBuilder().build())
|
||||
return SetSubscriptionLevelResponse.newBuilder()
|
||||
.setInvalidSelection(FailedPrecondition.newBuilder()
|
||||
.setDescription("Unsupported subscription level " + request.getLevel()))
|
||||
.build();
|
||||
}
|
||||
final Optional<String> templateId = Optional.ofNullable(
|
||||
config.prices().get(request.getCurrency().toLowerCase(Locale.ROOT)))
|
||||
.map(priceConfiguration -> priceConfiguration.processorIds().get(processorCustomer.processor()));
|
||||
if (templateId.isEmpty()) {
|
||||
return SetSubscriptionLevelResponse.newBuilder().setUnsupportedCurrency(FailedPrecondition.newBuilder().build())
|
||||
return SetSubscriptionLevelResponse.newBuilder()
|
||||
.setInvalidSelection(FailedPrecondition.newBuilder()
|
||||
.setDescription(String.format("Currency %s is not supported for %s", request.getCurrency(), processorCustomer.processor())))
|
||||
.build();
|
||||
}
|
||||
|
||||
final CustomerAwareSubscriptionPaymentProcessor manager;
|
||||
switch (processorCustomer.processor()) {
|
||||
case STRIPE -> manager = stripeManager;
|
||||
case BRAINTREE -> manager = braintreeManager;
|
||||
default -> {
|
||||
return SetSubscriptionLevelResponse.newBuilder().setUnsupportedOperation(FailedPrecondition.newBuilder()
|
||||
.setDescription(
|
||||
"Operation cannot be performed with the '" + processorCustomer.processor() + "' payment provider")
|
||||
.build()).build();
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
subscriptionManager.updateSubscriptionLevelForCustomer(subscriberCredentials, subscriptionRecord, manager,
|
||||
request.getLevel(), request.getCurrency(), request.getIdempotencyKey(), templateId.get(),
|
||||
@@ -345,22 +347,30 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
|
||||
.build();
|
||||
} catch (final PurchaseInvalidIdempotencyKeyException e) {
|
||||
return SetSubscriptionLevelResponse.newBuilder()
|
||||
.setInvalidIdempotencyKey(FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build())
|
||||
.setFailedPrecondition(FailedPrecondition.newBuilder()
|
||||
.setDescription("Idempotency key was reused with a modified request"))
|
||||
.build();
|
||||
} catch (final PurchaseProcessorException e) {
|
||||
return SetSubscriptionLevelResponse.newBuilder()
|
||||
.setChargeFailure(SubscriptionsUtil.toChargeFailure(e.getProcessor(), e.getChargeFailure())).build();
|
||||
.setPaymentRequired(PaymentRequired.newBuilder()
|
||||
.setChargeFailure(SubscriptionsUtil.toChargeFailure(e.getProcessor(), e.getChargeFailure())))
|
||||
.build();
|
||||
} catch (final PurchasePaymentRequiresActionException e) {
|
||||
return SetSubscriptionLevelResponse.newBuilder().setPaymentRequiresAction(FailedPrecondition.newBuilder().build())
|
||||
return SetSubscriptionLevelResponse.newBuilder()
|
||||
.setFailedPrecondition(FailedPrecondition.newBuilder()
|
||||
.setDescription("Payment processor requires additional customer action before the payment method can be charged"))
|
||||
.build();
|
||||
} catch (final PurchaseInvalidLevelException e) {
|
||||
return SetSubscriptionLevelResponse.newBuilder()
|
||||
.setInvalidLevelTransition(FailedPrecondition.newBuilder().build()).build();
|
||||
.setFailedPrecondition(FailedPrecondition.newBuilder()
|
||||
.setDescription("Cannot transition to level " + request.getLevel()))
|
||||
.build();
|
||||
} catch (final PurchaseProcessorConflictException e) {
|
||||
// We just looked up the subscription processor from the database, a conflict is not possible
|
||||
throw new IllegalStateException(e);
|
||||
return SetSubscriptionLevelResponse.newBuilder()
|
||||
.setFailedPrecondition(FailedPrecondition.newBuilder()
|
||||
.setDescription("No payment method set up"))
|
||||
.build();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -385,7 +395,7 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
|
||||
return SetIapSubscriptionResponse.newBuilder().setSubscriptionProcessorConflict(
|
||||
FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
|
||||
} catch (final PurchasePaymentRequiredException e) {
|
||||
return SetIapSubscriptionResponse.newBuilder().setPaymentRequired(FailedPrecondition.newBuilder().build())
|
||||
return SetIapSubscriptionResponse.newBuilder().setPaymentRequired(SubscriptionsUtil.toPaymentRequired(e))
|
||||
.build();
|
||||
} catch (final PurchaseInvalidArgumentsException e) {
|
||||
return SetIapSubscriptionResponse.newBuilder()
|
||||
|
||||
+3
-1
@@ -19,6 +19,7 @@ import java.util.Map;
|
||||
import org.signal.chat.require.ElementConstraint;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.grpc.validators.AllowedValuesFieldValidator;
|
||||
import org.whispersystems.textsecuregcm.grpc.validators.Base64UrlFieldValidator;
|
||||
import org.whispersystems.textsecuregcm.grpc.validators.FieldValidator;
|
||||
import org.whispersystems.textsecuregcm.grpc.validators.E164FieldValidator;
|
||||
@@ -49,7 +50,8 @@ public class ValidatingInterceptor implements ServerInterceptor {
|
||||
"size", new SizeFieldValidator(),
|
||||
"base64url", new Base64UrlFieldValidator(),
|
||||
"identityType", new ServiceIdentifierIdentityTypeValidator(),
|
||||
"present", new PresentFieldValidator());
|
||||
"present", new PresentFieldValidator(),
|
||||
"allowedValues", new AllowedValuesFieldValidator());
|
||||
|
||||
@Override
|
||||
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(
|
||||
|
||||
-123
@@ -1,123 +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 io.netty.handler.ssl.ReferenceCountedOpenSslEngine;
|
||||
import io.netty.internal.tcnative.SSL;
|
||||
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.annotation.Nullable;
|
||||
import javax.net.ssl.KeyManager;
|
||||
import javax.net.ssl.SSLEngine;
|
||||
import javax.net.ssl.X509ExtendedKeyManager;
|
||||
import javax.net.ssl.X509KeyManager;
|
||||
|
||||
/// 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#10916](https://github.com/netty/netty/issues/10916) by addressing two issues in key selection:
|
||||
///
|
||||
/// 1. Netty’s engine only declares support for RSA- and EC-family key types, and
|
||||
/// 2. the handshake session's peer signature algorithm converter (`io.netty.handler.ssl.SignatureAlgorithmConverter`)
|
||||
/// doesn't match BoringSSL's `ed25519`, so ed25519 gets dropped, even if one is presented as a candidate
|
||||
class BoringSslServerKeyManager extends X509ExtendedKeyManager {
|
||||
|
||||
private final X509KeyManager delegate;
|
||||
|
||||
@VisibleForTesting
|
||||
BoringSslServerKeyManager(final X509KeyManager delegate) {
|
||||
if (!"BoringSSL".equals(OpenSsl.versionString())) {
|
||||
throw new IllegalStateException("BoringSSL required, found " + OpenSsl.versionString());
|
||||
}
|
||||
this.delegate = delegate;
|
||||
}
|
||||
|
||||
/// @throws IllegalArgumentException if `keyManagers` contains no [X509KeyManager]
|
||||
static BoringSslServerKeyManager wrap(final KeyManager[] keyManagers) {
|
||||
return Arrays.stream(keyManagers)
|
||||
.filter(X509KeyManager.class::isInstance)
|
||||
.map(X509KeyManager.class::cast)
|
||||
.findFirst()
|
||||
.map(BoringSslServerKeyManager::new)
|
||||
.orElseThrow(() -> new IllegalArgumentException("No X509KeyManager found"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public String chooseEngineServerAlias(final String keyType, final Principal[] issuers, final SSLEngine engine) {
|
||||
if (!(engine instanceof ReferenceCountedOpenSslEngine openSslEngine)) {
|
||||
throw new IllegalArgumentException("BoringSslServerKeyManager requires netty's OpenSSL provider");
|
||||
}
|
||||
|
||||
@Nullable final String[] peerSignatureAlgorithms = SSL.getSigAlgs(openSslEngine.sslPointer());
|
||||
if (peerSignatureAlgorithms == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
for (final String signatureAlgorithm : peerSignatureAlgorithms) {
|
||||
final Optional<String> maybeAlias = getJdkKeyType(signatureAlgorithm)
|
||||
// The Netty OpenSSL engine doesn't advertise support for Ed25519, and so we can't include the engine in the
|
||||
// delegate's selection process. Instead, we loop through the peer signature algorithms and find a matching key.
|
||||
.map(jdkKeyType -> delegate.chooseServerAlias(jdkKeyType, issuers, null));
|
||||
|
||||
if (maybeAlias.isPresent()) {
|
||||
return maybeAlias.get();
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// Maps a [BoringSSL signature algorithm name](https://github.com/google/boringssl/blob/8525ff3/ssl/ssl_privkey.cc#L420-L433)
|
||||
/// 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.startsWith("ecdsa_")) {
|
||||
return Optional.of("EC");
|
||||
} else if (signatureAlgorithm.startsWith("rsa_pss_rsae_")) {
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -21,7 +21,7 @@ class ProxyMessageAttributeSetterHandler extends ChannelInboundHandlerAdapter {
|
||||
static final AttributeKey<InetAddress> PROXY_REMOTE_ADDRESS = AttributeKey.newInstance("proxyRemoteAddress");
|
||||
|
||||
@Override
|
||||
public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception {
|
||||
public void channelRead(final ChannelHandlerContext ctx, final Object msg) {
|
||||
if (!(msg instanceof HAProxyMessage proxyMessage)) {
|
||||
ctx.pipeline().remove(this);
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.grpc.validators;
|
||||
|
||||
import com.google.protobuf.Descriptors;
|
||||
import java.util.Set;
|
||||
import org.signal.chat.require.AllowedValuesConstraint;
|
||||
|
||||
public class AllowedValuesFieldValidator extends FieldValidator<AllowedValuesConstraint> {
|
||||
|
||||
public AllowedValuesFieldValidator() {
|
||||
super("allowedValues", Set.of(
|
||||
Descriptors.FieldDescriptor.Type.INT32,
|
||||
Descriptors.FieldDescriptor.Type.INT64,
|
||||
Descriptors.FieldDescriptor.Type.UINT32,
|
||||
Descriptors.FieldDescriptor.Type.UINT64,
|
||||
Descriptors.FieldDescriptor.Type.FIXED32,
|
||||
Descriptors.FieldDescriptor.Type.FIXED64,
|
||||
Descriptors.FieldDescriptor.Type.SFIXED32,
|
||||
Descriptors.FieldDescriptor.Type.SFIXED64,
|
||||
Descriptors.FieldDescriptor.Type.SINT32,
|
||||
Descriptors.FieldDescriptor.Type.SINT64,
|
||||
Descriptors.FieldDescriptor.Type.STRING,
|
||||
Descriptors.FieldDescriptor.Type.ENUM
|
||||
), MissingOptionalAction.SUCCEED, false);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected AllowedValuesConstraint resolveExtensionValue(final Object extensionValue) {
|
||||
return (AllowedValuesConstraint) extensionValue;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void validateIntegerNumber(
|
||||
final AllowedValuesConstraint constraint,
|
||||
final long fieldValue,
|
||||
final Descriptors.FieldDescriptor.Type type) throws FieldValidationException {
|
||||
if (constraint.getIntsCount() == 0) {
|
||||
throw new IllegalArgumentException("allowedValues on integer field must specify ints");
|
||||
}
|
||||
if (constraint.getIntsList().contains(fieldValue)) {
|
||||
return;
|
||||
}
|
||||
throw new FieldValidationException("field value is [%d] but expected to be one of %s"
|
||||
.formatted(fieldValue, constraint.getIntsList()));
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void validateStringValue(
|
||||
final AllowedValuesConstraint constraint,
|
||||
final String fieldValue) throws FieldValidationException {
|
||||
if (constraint.getStringsCount() == 0) {
|
||||
throw new IllegalArgumentException("allowedValues on string field must specify strings");
|
||||
}
|
||||
if (constraint.getStringsList().contains(fieldValue)) {
|
||||
return;
|
||||
}
|
||||
throw new FieldValidationException("field value is [%s] but expected to be one of %s"
|
||||
.formatted(fieldValue, constraint.getStringsList()));
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void validateEnumValue(
|
||||
final AllowedValuesConstraint constraint,
|
||||
final Descriptors.EnumValueDescriptor enumValueDescriptor) throws FieldValidationException {
|
||||
if (constraint.getEnumsCount() == 0) {
|
||||
throw new IllegalArgumentException("allowedValues on enum field must specify enums");
|
||||
}
|
||||
if (constraint.getEnumsList().contains(enumValueDescriptor.getName())) {
|
||||
return;
|
||||
}
|
||||
throw new FieldValidationException("field value is [%s] but expected to be one of %s"
|
||||
.formatted(enumValueDescriptor.getName(), constraint.getEnumsList()));
|
||||
}
|
||||
}
|
||||
+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
|
||||
|
||||
@@ -128,6 +128,10 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
|
||||
return forDescriptor(For.ATTACHMENT_BYTES);
|
||||
}
|
||||
|
||||
public RateLimiter getBackupAuthCheckLimiter() {
|
||||
return forDescriptor(For.BACKUP_AUTH_CHECK);
|
||||
}
|
||||
|
||||
public RateLimiter getPinLimiter() {
|
||||
return forDescriptor(For.PIN);
|
||||
}
|
||||
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.mappers;
|
||||
|
||||
import io.github.resilience4j.circuitbreaker.CallNotPermittedException;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import jakarta.ws.rs.ext.ExceptionMapper;
|
||||
|
||||
public class CallNotPermittedExceptionMapper implements ExceptionMapper<CallNotPermittedException> {
|
||||
|
||||
@Override
|
||||
public Response toResponse(final CallNotPermittedException exception) {
|
||||
return Response.status(Response.Status.SERVICE_UNAVAILABLE).build();
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -15,7 +15,7 @@ import java.util.Map;
|
||||
import org.whispersystems.textsecuregcm.purchases.ChargeFailure;
|
||||
import org.whispersystems.textsecuregcm.purchases.PurchaseException;
|
||||
import org.whispersystems.textsecuregcm.purchases.PurchaseForbiddenException;
|
||||
import org.whispersystems.textsecuregcm.purchases.PurchaseInvalidAmountException;
|
||||
import org.whispersystems.textsecuregcm.purchases.PurchaseAmountTooLargeException;
|
||||
import org.whispersystems.textsecuregcm.purchases.PurchaseInvalidArgumentsException;
|
||||
import org.whispersystems.textsecuregcm.purchases.PurchaseNotFoundException;
|
||||
import org.whispersystems.textsecuregcm.purchases.PurchasePaymentRequiredException;
|
||||
@@ -34,7 +34,7 @@ public class PurchaseExceptionMapper implements ExceptionMapper<PurchaseExceptio
|
||||
public Response toResponse(final PurchaseException exception) {
|
||||
|
||||
// Some exceptions have specific error body formats
|
||||
if (exception instanceof PurchaseInvalidAmountException e) {
|
||||
if (exception instanceof PurchaseAmountTooLargeException e) {
|
||||
return Response
|
||||
.status(Response.Status.BAD_REQUEST)
|
||||
.entity(Map.of("error", e.getErrorCode()))
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -122,7 +122,8 @@ public class MetricsHttpEventHandler extends EventsHandler {
|
||||
|
||||
private void onResponseFailure(Request request, int status, Throwable failure) {
|
||||
|
||||
if (failure instanceof org.eclipse.jetty.io.EofException) {
|
||||
if (failure instanceof org.eclipse.jetty.io.EofException
|
||||
|| (failure instanceof java.io.IOException && failure.getCause() instanceof org.eclipse.jetty.io.EofException)) {
|
||||
// the client disconnected early
|
||||
return;
|
||||
}
|
||||
|
||||
+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();
|
||||
});
|
||||
|
||||
+31
-14
@@ -15,6 +15,7 @@ import com.apple.itunes.storekit.model.StatusResponse;
|
||||
import com.apple.itunes.storekit.model.TransactionInfoResponse;
|
||||
import com.apple.itunes.storekit.verification.SignedDataVerifier;
|
||||
import com.apple.itunes.storekit.verification.VerificationException;
|
||||
import com.apple.itunes.storekit.verification.VerificationStatus;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.github.resilience4j.retry.Retry;
|
||||
import io.github.resilience4j.retry.RetryConfig;
|
||||
@@ -23,11 +24,11 @@ import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.stream.Collectors;
|
||||
import javax.annotation.Nullable;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
@@ -84,7 +85,10 @@ public class AppleAppStoreClient {
|
||||
new AppStoreServerAPIClient(encodedKey, keyId, issuerId, bundleId, Environment.PRODUCTION),
|
||||
new SignedDataVerifier(decodeRootCerts(base64AppleRootCerts), bundleId, appAppleId, Environment.SANDBOX, true),
|
||||
new AppStoreServerAPIClient(encodedKey, keyId, issuerId, bundleId, Environment.SANDBOX),
|
||||
retryConfigurationName);
|
||||
ResilienceUtil.getRetryRegistry().retry("appstore-retry", retryConfig(
|
||||
Optional.ofNullable(retryConfigurationName)
|
||||
.flatMap(name -> ResilienceUtil.getRetryRegistry().getConfiguration(name))
|
||||
.orElseGet(() -> ResilienceUtil.getRetryRegistry().getDefaultConfig()))));
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
@@ -94,20 +98,15 @@ public class AppleAppStoreClient {
|
||||
AppStoreServerAPIClient productionApiClient,
|
||||
SignedDataVerifier sandboxSignedDataVerifier,
|
||||
AppStoreServerAPIClient sandboxApiClient,
|
||||
@Nullable final String retryConfigurationName) {
|
||||
final Retry retry) {
|
||||
this.defaultEnvironment = defaultEnvironment;
|
||||
this.sandboxSignedDataVerifier = sandboxSignedDataVerifier;
|
||||
this.sandboxApiClient = sandboxApiClient;
|
||||
this.productionSignedDataVerifier = productionSignedDataVerifier;
|
||||
this.productionApiClient = productionApiClient;
|
||||
this.retry = ResilienceUtil.getRetryRegistry().retry("appstore-retry", RetryConfig
|
||||
.<HttpResponse<?>>from(Optional.ofNullable(retryConfigurationName)
|
||||
.flatMap(name -> ResilienceUtil.getRetryRegistry().getConfiguration(name))
|
||||
.orElseGet(() -> ResilienceUtil.getRetryRegistry().getDefaultConfig()))
|
||||
.retryOnException(AppleAppStoreClient::shouldRetry).build());
|
||||
this.retry = retry;
|
||||
}
|
||||
|
||||
|
||||
/// Verify signature and decode transaction payload for a recurring subscription
|
||||
AppleAppStoreDecodedTransaction verifySubscription(final Environment environment, final LastTransactionsItem tx) {
|
||||
final SignedDataVerifier signedDataVerifier = switch (environment) {
|
||||
@@ -116,10 +115,10 @@ public class AppleAppStoreClient {
|
||||
default -> throw new IllegalStateException("Unexpected environment: " + environment);
|
||||
};
|
||||
try {
|
||||
return new AppleAppStoreDecodedTransaction(
|
||||
return verifyWithRetry(() -> new AppleAppStoreDecodedTransaction(
|
||||
tx,
|
||||
signedDataVerifier.verifyAndDecodeTransaction(tx.getSignedTransactionInfo()),
|
||||
signedDataVerifier.verifyAndDecodeRenewalInfo(tx.getSignedRenewalInfo()));
|
||||
signedDataVerifier.verifyAndDecodeRenewalInfo(tx.getSignedRenewalInfo())));
|
||||
} catch (VerificationException e) {
|
||||
throw new UncheckedIOException(new IOException("Failed to verify payload from App Store Server", e));
|
||||
}
|
||||
@@ -149,7 +148,8 @@ public class AppleAppStoreClient {
|
||||
return Optional.of(lookupByTransactionId(transactionId, errorTags, (environment, txId) -> {
|
||||
try {
|
||||
final TransactionInfoResponse transactionInfo = client(environment).getTransactionInfo(txId);
|
||||
return verifier(environment).verifyAndDecodeTransaction(transactionInfo.getSignedTransactionInfo());
|
||||
return verifyWithRetry(() ->
|
||||
verifier(environment).verifyAndDecodeTransaction(transactionInfo.getSignedTransactionInfo()));
|
||||
} catch (VerificationException e) {
|
||||
throw new IOException("Failed to verify payload from App Store Server", e);
|
||||
}
|
||||
@@ -220,6 +220,16 @@ public class AppleAppStoreClient {
|
||||
}
|
||||
}
|
||||
|
||||
private <T> T verifyWithRetry(final Callable<T> verification) throws VerificationException {
|
||||
try {
|
||||
return retry.executeCallable(verification);
|
||||
} catch (VerificationException e) {
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private AppStoreServerAPIClient client(final Environment environment) {
|
||||
return switch (environment) {
|
||||
case SANDBOX -> sandboxApiClient;
|
||||
@@ -236,6 +246,12 @@ public class AppleAppStoreClient {
|
||||
};
|
||||
}
|
||||
|
||||
/// Adds App Store-specific retry predicate to the given base retry configuration
|
||||
@VisibleForTesting
|
||||
static RetryConfig retryConfig(final RetryConfig baseConfig) {
|
||||
return RetryConfig.from(baseConfig).retryOnException(AppleAppStoreClient::shouldRetry).build();
|
||||
}
|
||||
|
||||
private static Set<InputStream> decodeRootCerts(final List<String> rootCerts) {
|
||||
return rootCerts.stream()
|
||||
.map(Base64.getDecoder()::decode)
|
||||
@@ -244,11 +260,12 @@ public class AppleAppStoreClient {
|
||||
}
|
||||
|
||||
private static boolean shouldRetry(Throwable e) {
|
||||
if (e instanceof VerificationException verificationException) {
|
||||
return verificationException.getStatus() == VerificationStatus.RETRYABLE_VERIFICATION_FAILURE;
|
||||
}
|
||||
return e instanceof APIException apiException && switch (apiException.getApiError()) {
|
||||
case ORIGINAL_TRANSACTION_ID_NOT_FOUND_RETRYABLE, GENERAL_INTERNAL_RETRYABLE, APP_NOT_FOUND_RETRYABLE, ACCOUNT_NOT_FOUND_RETRYABLE -> true;
|
||||
case null, default -> false;
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+4
-5
@@ -4,12 +4,11 @@
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.purchases;
|
||||
|
||||
public class PurchaseInvalidAmountException extends PurchaseInvalidArgumentsException {
|
||||
public class PurchaseAmountTooLargeException extends PurchaseInvalidArgumentsException {
|
||||
private final String errorCode;
|
||||
|
||||
private String errorCode;
|
||||
|
||||
public PurchaseInvalidAmountException(String errorCode) {
|
||||
super(null, null);
|
||||
public PurchaseAmountTooLargeException(final String errorCode) {
|
||||
super("Purchase amount too large");
|
||||
this.errorCode = errorCode;
|
||||
}
|
||||
|
||||
+12
-5
@@ -44,6 +44,7 @@ import com.stripe.param.SubscriptionRetrieveParams;
|
||||
import com.stripe.param.SubscriptionUpdateParams;
|
||||
import com.stripe.param.SubscriptionUpdateParams.BillingCycleAnchor;
|
||||
import com.stripe.param.SubscriptionUpdateParams.ProrationBehavior;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
@@ -71,6 +72,7 @@ import org.apache.commons.lang3.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerVersion;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.PaymentTime;
|
||||
import org.whispersystems.textsecuregcm.util.Conversions;
|
||||
import org.whispersystems.textsecuregcm.util.ExecutorUtil;
|
||||
@@ -79,6 +81,8 @@ import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
|
||||
public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor, OneTimePaymentProcessor {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(StripeManager.class);
|
||||
private static final String PAYMENT_REQUIRES_ACTION_COUNTER_NAME =
|
||||
MetricsUtil.name(StripeManager.class, "subscriptionPaymentRequiresAction");
|
||||
private static final String METADATA_KEY_LEVEL = "level";
|
||||
private static final String METADATA_KEY_CLIENT_PLATFORM = "clientPlatform";
|
||||
|
||||
@@ -208,13 +212,13 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor,
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a payment intent. May throw a {@link PurchaseInvalidAmountException} if stripe rejects the attempt if
|
||||
* the amount is too large or too small
|
||||
* Creates a payment intent. May throw a {@link PurchaseAmountTooLargeException} if stripe rejects the attempt because
|
||||
* the amount is too large
|
||||
*/
|
||||
public PaymentIntent createPaymentIntent(final String currency,
|
||||
final long amount,
|
||||
final long level,
|
||||
@Nullable final ClientPlatform clientPlatform) throws PurchaseInvalidAmountException {
|
||||
@Nullable final ClientPlatform clientPlatform) throws PurchaseAmountTooLargeException {
|
||||
|
||||
final PaymentIntentCreateParams.Builder builder = PaymentIntentCreateParams.builder()
|
||||
.setAmount(amount)
|
||||
@@ -234,7 +238,9 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor,
|
||||
? "unknown"
|
||||
: e.getCode().toLowerCase(Locale.ROOT);
|
||||
switch (errorCode) {
|
||||
case "amount_too_small", "amount_too_large" -> throw new PurchaseInvalidAmountException(errorCode);
|
||||
case "amount_too_large" -> throw new PurchaseAmountTooLargeException(errorCode);
|
||||
// Callers should validate against configured minimums first
|
||||
case "amount_too_small" -> throw new IllegalStateException(String.format("Stripe rejected %d %s, the configured minimum is too low", amount, currency), e);
|
||||
default -> throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
@@ -319,6 +325,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor,
|
||||
throw new PurchaseProcessorException(getProvider(), createChargeFailureFromCardException(e));
|
||||
} catch (final StripeException e) {
|
||||
if ("subscription_payment_intent_requires_action".equals(e.getCode())) {
|
||||
Metrics.counter(PAYMENT_REQUIRES_ACTION_COUNTER_NAME).increment();
|
||||
throw new PurchasePaymentRequiresActionException();
|
||||
}
|
||||
throw new UncheckedIOException(new IOException(e));
|
||||
@@ -358,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)
|
||||
|
||||
-33
@@ -1,33 +0,0 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.push;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* A message availability listener handles message availability and presence events related to a client's open message
|
||||
* stream. Handler methods are run on dedicated threads and may safely perform blocking operations.
|
||||
*
|
||||
* @see RedisMessageAvailabilityManager#handleClientConnected(UUID, byte, MessageAvailabilityListener)
|
||||
*/
|
||||
public interface MessageAvailabilityListener {
|
||||
|
||||
/**
|
||||
* Indicates that a new message is available in the connected client's message queue.
|
||||
*/
|
||||
void handleNewMessageAvailable();
|
||||
|
||||
/**
|
||||
* Indicates that messages for the client have been persisted from short-term storage to long-term storage.
|
||||
*/
|
||||
void handleMessagesPersisted();
|
||||
|
||||
/**
|
||||
* Indicates a newer instance of this client has started reading messages and the listener should close this client's
|
||||
* underlying network connection.
|
||||
*/
|
||||
void handleConflictingMessageConsumer();
|
||||
}
|
||||
Loaded 100 of 254 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user