mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-12-01 05:06:47 +00:00
Compare commits
69
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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 | ||
|
|
a15d5cdbb9 | ||
|
|
a0c321557f | ||
|
|
4765492415 | ||
|
|
e6aef34398 | ||
|
|
e7916302ba | ||
|
|
db00752f3d | ||
|
|
92b903c639 | ||
|
|
92fdac8d76 | ||
|
|
3bac6e5fd3 | ||
|
|
ef9df20be4 | ||
|
|
11741a5048 | ||
|
|
b2c638a635 | ||
|
|
12d7157a4e | ||
|
|
5026242122 | ||
|
|
fe39fcdb12 | ||
|
|
51af17e3b8 | ||
|
|
1389de1e0c | ||
|
|
669e955cd2 | ||
|
|
dec95043fa | ||
|
|
4be8e0bfc8 | ||
|
|
99d492c61c |
No files matched your search
@@ -28,9 +28,9 @@ updates:
|
||||
versions: [">=1.6.0"]
|
||||
# https://github.com/jetty/jetty.project/issues/15657
|
||||
- dependency-name: "org.eclipse.jetty:*"
|
||||
versions: ["<=12.1.12"]
|
||||
versions: ["<=12.1.14"]
|
||||
- dependency-name: "org.eclipse.jetty.ee10:*"
|
||||
versions: ["<=12.1.12"]
|
||||
versions: ["<=12.1.14"]
|
||||
|
||||
# Dependency convergence sentinels, pinned to specific versions
|
||||
- dependency-name: "tools.jackson.core:jackson-databind"
|
||||
|
||||
@@ -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
|
||||
@@ -58,6 +58,7 @@ import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.commons.lang3.Validate;
|
||||
import org.apache.commons.lang3.tuple.Pair;
|
||||
import org.eclipse.jetty.client.HttpClient;
|
||||
import org.eclipse.jetty.client.Request;
|
||||
import org.eclipse.jetty.http2.client.HTTP2Client;
|
||||
import org.eclipse.jetty.http2.client.transport.HttpClientTransportOverHTTP2;
|
||||
import org.eclipse.jetty.io.ClientConnector;
|
||||
@@ -235,18 +236,16 @@ public final class Operations {
|
||||
Optional.empty(),
|
||||
Optional.empty()));
|
||||
|
||||
final Pair<Integer, MfaFailureExceptionMapper.MfaFailureResponse> initialResponse = apiPost("/v1/registration", initialRequest)
|
||||
// we expect (and need) failure with status 441, which will contain the WebAuthn challenge
|
||||
final MfaFailureExceptionMapper.MfaFailureResponse mfaFailureResponse = apiPost("/v1/registration", initialRequest)
|
||||
// For a numberless account recovery, the username is the ACI
|
||||
.authorized(testUser.aciUuid().toString(), testUser.accountPassword())
|
||||
.execute(MfaFailureExceptionMapper.MfaFailureResponse.class);
|
||||
.executeExpectStatusCode(441, 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()
|
||||
Validate.isTrue(mfaFailureResponse.webAuthnParameters().allowedCredentialIds()
|
||||
.stream()
|
||||
.anyMatch(allowedId -> Arrays.equals(allowedId, credentialId));
|
||||
.anyMatch(allowedId -> Arrays.equals(allowedId, credentialId)),
|
||||
"Expected MFA failure to contain credentialId");
|
||||
|
||||
final PublicKeyCredential<AuthenticatorAssertionResponse, ?> credential =
|
||||
clientPlatform.get(new PublicKeyCredentialRequestOptions(
|
||||
@@ -438,9 +437,10 @@ public final class Operations {
|
||||
|
||||
private static ManagedChannel buildGrpcChannel() {
|
||||
try {
|
||||
final ByteArrayInputStream rootCert =
|
||||
new ByteArrayInputStream(CONFIG.rootCert().getBytes(StandardCharsets.UTF_8));
|
||||
final ChannelCredentials credentials = TlsChannelCredentials.newBuilder().trustManager(rootCert).build();
|
||||
final String rootCerts = String.join("\n", CONFIG.rootCerts());
|
||||
final ByteArrayInputStream rootCertInputStream =
|
||||
new ByteArrayInputStream(rootCerts.getBytes(StandardCharsets.UTF_8));
|
||||
final ChannelCredentials credentials = TlsChannelCredentials.newBuilder().trustManager(rootCertInputStream).build();
|
||||
return Grpc.newChannelBuilderForAddress(GRPC_DOMAIN, 443, credentials)
|
||||
.userAgent(USER_AGENT)
|
||||
.build();
|
||||
@@ -524,6 +524,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));
|
||||
@@ -564,7 +573,7 @@ public final class Operations {
|
||||
private static FaultTolerantHttpClient buildClient() {
|
||||
try {
|
||||
return FaultTolerantHttpClient.newBuilder("integration-test", Executors.newFixedThreadPool(16))
|
||||
.withTrustedServerCertificates(CONFIG.rootCert())
|
||||
.withTrustedServerCertificates(CONFIG.rootCerts().toArray(String[]::new))
|
||||
.build();
|
||||
} catch (final CertificateException e) {
|
||||
throw new RuntimeException(e);
|
||||
@@ -573,7 +582,7 @@ public final class Operations {
|
||||
|
||||
private static WebSocketClient buildWebSocketClient() {
|
||||
try {
|
||||
final KeyStore trustStore = CertificateUtil.buildKeyStoreForPem(CONFIG.rootCert());
|
||||
final KeyStore trustStore = CertificateUtil.buildKeyStoreForPem(CONFIG.rootCerts().toArray(String[]::new));
|
||||
final SslContextFactory.Client sslContextFactory = new SslContextFactory.Client();
|
||||
sslContextFactory.setTrustStore(trustStore);
|
||||
|
||||
@@ -581,7 +590,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();
|
||||
|
||||
@@ -7,11 +7,13 @@ package org.signal.integration.config;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import org.whispersystems.textsecuregcm.configuration.DynamoDbClientFactory;
|
||||
import java.util.List;
|
||||
|
||||
public record Config(@NotBlank String domain,
|
||||
@NotBlank String rootCert,
|
||||
@NotEmpty List<@NotBlank String> rootCerts,
|
||||
@NotNull @Valid DynamoDbClientFactory dynamoDbClient,
|
||||
@NotNull @Valid DynamoDbTables dynamoDbTables,
|
||||
@NotBlank String prescribedRegistrationNumber,
|
||||
|
||||
@@ -45,8 +45,8 @@
|
||||
</modules>
|
||||
|
||||
<properties>
|
||||
<aws.sdk2.version>2.54.7</aws.sdk2.version>
|
||||
<braintree.version>3.53.0</braintree.version>
|
||||
<aws.sdk2.version>2.55.14</aws.sdk2.version>
|
||||
<braintree.version>3.54.0</braintree.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,46 +55,46 @@
|
||||
<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.90.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.7.2-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.22.3</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>
|
||||
<libphonenumber.version>9.0.41</libphonenumber.version>
|
||||
<logstash.logback.version>9.0</logstash.logback.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>
|
||||
<netty.version>4.2.19.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>
|
||||
<!-- Instrumentation releases target upstream opentelemetry versions and include that BOM by reference -->
|
||||
<opentelemetry-instrumentation.version>2.32.0</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 -->
|
||||
<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>
|
||||
<slf4j.version>2.0.20</slf4j.version>
|
||||
<stripe.version>33.4.2</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.31.11.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>
|
||||
@@ -197,17 +197,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>
|
||||
@@ -306,11 +299,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 +307,13 @@
|
||||
<dependency>
|
||||
<groupId>com.redis</groupId>
|
||||
<artifactId>testcontainers-redis</artifactId>
|
||||
<version>2.2.4</version>
|
||||
<version>3.0.0</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.signal</groupId>
|
||||
<artifactId>libsignal-server</artifactId>
|
||||
<version>0.101.2</version>
|
||||
<version>0.105.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.signal</groupId>
|
||||
@@ -339,11 +327,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 +430,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 +490,12 @@
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>3.5.6</version>
|
||||
<version>3.6.0</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-failsafe-plugin</artifactId>
|
||||
<version>3.5.6</version>
|
||||
<version>3.6.0</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
@@ -492,12 +515,12 @@
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
<version>3.6.3</version>
|
||||
<version>3.6.4</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>properties-maven-plugin</artifactId>
|
||||
<version>1.3.0</version>
|
||||
<version>1.3.1</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</pluginManagement>
|
||||
@@ -538,7 +561,7 @@
|
||||
<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>
|
||||
</configuration>
|
||||
@@ -601,7 +624,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 +633,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:
|
||||
@@ -145,6 +143,8 @@ dynamoDbTables:
|
||||
tableName: Example_RemoteConfig
|
||||
reportMessage:
|
||||
tableName: Example_ReportMessage
|
||||
sandboxAccounts:
|
||||
tableName: Example_SandboxAccounts
|
||||
scheduledJobs:
|
||||
tableName: Example_ScheduledJobs
|
||||
expiration: P7D
|
||||
|
||||
+16
-15
@@ -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.11.0</firebase-admin.version>
|
||||
<libphonenumber-geocoder.version>3.41</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.1</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>
|
||||
|
||||
@@ -193,7 +193,7 @@
|
||||
<groupId>tools.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
<!-- update dependabot.yml when this dependency is removed -->
|
||||
<version>3.2.1</version>
|
||||
<version>3.2.3</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
@@ -240,7 +240,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 +307,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 +315,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 +644,7 @@
|
||||
<version>${apollo-api-jvm.version}</version>
|
||||
|
||||
<exclusions>
|
||||
<!-- conflicts with kotlin-stdlib -->
|
||||
<exclusion>
|
||||
<groupId>org.jetbrains</groupId>
|
||||
<artifactId>annotations</artifactId>
|
||||
@@ -661,7 +662,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>
|
||||
@@ -877,7 +878,7 @@
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>templating-maven-plugin</artifactId>
|
||||
<version>3.1.0</version>
|
||||
<version>3.1.1</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>filter-src</id>
|
||||
|
||||
@@ -75,6 +75,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;
|
||||
@@ -197,6 +198,7 @@ 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.SniMapper;
|
||||
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 +207,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;
|
||||
@@ -287,6 +290,7 @@ import org.whispersystems.textsecuregcm.storage.RepeatedUseECSignedPreKeyStore;
|
||||
import org.whispersystems.textsecuregcm.storage.RepeatedUseKEMSignedPreKeyStore;
|
||||
import org.whispersystems.textsecuregcm.storage.ReportMessageDynamoDb;
|
||||
import org.whispersystems.textsecuregcm.storage.ReportMessageManager;
|
||||
import org.whispersystems.textsecuregcm.storage.SandboxAccounts;
|
||||
import org.whispersystems.textsecuregcm.storage.SingleUseECPreKeyStore;
|
||||
import org.whispersystems.textsecuregcm.storage.SubscriptionManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Subscriptions;
|
||||
@@ -342,8 +346,10 @@ import org.whispersystems.textsecuregcm.workers.RegenerateSecondaryDynamoDbTable
|
||||
import org.whispersystems.textsecuregcm.workers.RemoveExpiredAccountsCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.RemoveExpiredBackupsCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.RemoveExpiredLinkedDevicesCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.RemoveExpiredSandboxAccountsCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.RemoveExpiredUsernameHoldsCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.RemoveOrphanedPreKeyPagesCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.SandboxAccountPoolCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.ScheduledApnPushNotificationSenderServiceCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.ServerVersionCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.SetRequestLoggingEnabledTask;
|
||||
@@ -397,6 +403,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
bootstrap.addCommand(new ScheduledApnPushNotificationSenderServiceCommand());
|
||||
bootstrap.addCommand(new MessagePersisterServiceCommand());
|
||||
bootstrap.addCommand(new RemoveExpiredAccountsCommand(Clock.systemUTC()));
|
||||
bootstrap.addCommand(new RemoveExpiredSandboxAccountsCommand(Clock.systemUTC()));
|
||||
bootstrap.addCommand(new SandboxAccountPoolCommand());
|
||||
bootstrap.addCommand(new RemoveExpiredUsernameHoldsCommand(Clock.systemUTC()));
|
||||
bootstrap.addCommand(new RemoveExpiredBackupsCommand(Clock.systemUTC()));
|
||||
bootstrap.addCommand(new RemoveOrphanedPreKeyPagesCommand(Clock.systemUTC()));
|
||||
@@ -823,10 +831,12 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
config.getRegistrationWebAuthnConfiguration().challengeTtl(),
|
||||
config.getRegistrationWebAuthnConfiguration().userHandleBlindingSecret().value(),
|
||||
rateLimitersCluster);
|
||||
final SandboxAccounts sandboxAccounts = new SandboxAccounts(
|
||||
config.getDynamoDbTables().getSandboxAccounts().getTableName(), dynamoDbClient);
|
||||
final AccountsManager accountsManager = new AccountsManager(accounts, phoneNumberIdentifiers, cacheCluster,
|
||||
pubsubClient, accountLockManager, keysManager, messagesManager, profilesManager,
|
||||
changeNumberWaitingPeriodManager, secureStorageClient, secureValueRecovery2Client, disconnectionRequestManager,
|
||||
phoneNumberRecoveryPasswordsManager, messagePollExecutor,
|
||||
phoneNumberRecoveryPasswordsManager, sandboxAccounts, messagePollExecutor,
|
||||
retryExecutor, clock, config.getLinkDeviceSecretConfiguration().secret().value(),
|
||||
webAuthnCeremonyManager, totpManager);
|
||||
RemoteConfigsManager remoteConfigsManager = new RemoteConfigsManager(remoteConfigs, config.getRemoteConfigConfiguration().globalConfig());
|
||||
@@ -1144,9 +1154,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)
|
||||
@@ -1173,9 +1180,12 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
new ProfileAnonymousGrpcService(accountsManager, profilesManager, profileBadgeConverter, profileCdnPolicyGenerator, 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))
|
||||
@@ -1194,6 +1204,9 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
concurrentCallLimitingInterceptor))
|
||||
.toList();
|
||||
|
||||
verifyServiceAuth(authenticatedServices, Auth.AUTH_ONLY_AUTHENTICATED);
|
||||
verifyServiceAuth(unauthenticatedServices, Auth.AUTH_ONLY_ANONYMOUS);
|
||||
|
||||
final ManagedEventLoopGroup<DefaultEventLoopGroup> omnibusLocalEventLoopGroup = new ManagedEventLoopGroup<>(new DefaultEventLoopGroup());
|
||||
final ManagedEventLoopGroup<NioEventLoopGroup> omnibusNioEventLoopGroup = new ManagedEventLoopGroup<>(new NioEventLoopGroup());
|
||||
final LocalAddress grpcLocalAddress = new LocalAddress("grpc");
|
||||
@@ -1283,7 +1296,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
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);
|
||||
@@ -1345,7 +1358,7 @@ 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());
|
||||
|
||||
registerExceptionMappers(environment, webSocketEnvironment, provisioningEnvironment);
|
||||
@@ -1393,6 +1406,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
List.of(
|
||||
new LoggingUnhandledExceptionMapper(),
|
||||
new CompletionExceptionMapper(),
|
||||
new CallNotPermittedExceptionMapper(),
|
||||
new IOExceptionMapper(),
|
||||
new RateLimitExceededExceptionMapper(),
|
||||
new InvalidWebsocketAddressExceptionMapper(),
|
||||
@@ -1415,6 +1429,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()) {
|
||||
|
||||
-9
@@ -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) -> {
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
|
||||
@@ -98,21 +98,21 @@ public class CaptchaChecker {
|
||||
});
|
||||
|
||||
if (!parsedAction.equals(expectedAction)) {
|
||||
Metrics.counter(INVALID_ACTION_COUNTER_NAME, "action", action).increment();
|
||||
Metrics.counter(INVALID_ACTION_COUNTER_NAME, "action", parsedAction.getActionName()).increment();
|
||||
throw new InvalidCaptchaArgumentException("invalid captcha action");
|
||||
}
|
||||
|
||||
final Set<String> allowedSiteKeys = client.validSiteKeys(parsedAction);
|
||||
if (!allowedSiteKeys.contains(siteKey)) {
|
||||
logger.debug("invalid site-key {}, action={}", siteKey, action);
|
||||
Metrics.counter(INVALID_SITEKEY_COUNTER_NAME, "action", action).increment();
|
||||
logger.debug("invalid site-key {}, action={}", siteKey, parsedAction.getActionName());
|
||||
Metrics.counter(INVALID_SITEKEY_COUNTER_NAME, "action", parsedAction.getActionName()).increment();
|
||||
throw new InvalidCaptchaArgumentException("invalid captcha site-key");
|
||||
}
|
||||
|
||||
try {
|
||||
final AssessmentResult result = client.verify(maybeAci, siteKey, parsedAction, token, ip, userAgent);
|
||||
Metrics.counter(ASSESSMENTS_COUNTER_NAME,
|
||||
"action", action,
|
||||
"action", parsedAction.getActionName(),
|
||||
"score", result.getScoreString(),
|
||||
"provider", provider)
|
||||
.increment();
|
||||
|
||||
+9
-9
@@ -68,11 +68,11 @@ 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;
|
||||
private final Table reportMessage;
|
||||
private final Table sandboxAccounts;
|
||||
private final TableWithExpiration scheduledJobs;
|
||||
private final Table subscriptions;
|
||||
private final Table verificationSessions;
|
||||
@@ -99,11 +99,11 @@ 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,
|
||||
@JsonProperty("reportMessage") final Table reportMessage,
|
||||
@JsonProperty("sandboxAccounts") final Table sandboxAccounts,
|
||||
@JsonProperty("scheduledJobs") final TableWithExpiration scheduledJobs,
|
||||
@JsonProperty("subscriptions") final Table subscriptions,
|
||||
@JsonProperty("verificationSessions") final Table verificationSessions) {
|
||||
@@ -129,11 +129,11 @@ public class DynamoDbTables {
|
||||
this.profiles = profiles;
|
||||
this.profilesV2 = profilesV2;
|
||||
this.pushChallenge = pushChallenge;
|
||||
this.pushNotificationExperimentSamples = pushNotificationExperimentSamples;
|
||||
this.redeemedReceipts = redeemedReceipts;
|
||||
this.registrationRecovery = registrationRecovery;
|
||||
this.remoteConfig = remoteConfig;
|
||||
this.reportMessage = reportMessage;
|
||||
this.sandboxAccounts = sandboxAccounts;
|
||||
this.scheduledJobs = scheduledJobs;
|
||||
this.subscriptions = subscriptions;
|
||||
this.verificationSessions = verificationSessions;
|
||||
@@ -265,12 +265,6 @@ public class DynamoDbTables {
|
||||
return pushChallenge;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
public Table getPushNotificationExperimentSamples() {
|
||||
return pushNotificationExperimentSamples;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
public Table getRedeemedReceipts() {
|
||||
@@ -295,6 +289,12 @@ public class DynamoDbTables {
|
||||
return reportMessage;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
public Table getSandboxAccounts() {
|
||||
return sandboxAccounts;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
public TableWithExpiration getScheduledJobs() {
|
||||
|
||||
+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;
|
||||
}
|
||||
}
|
||||
+17
@@ -38,6 +38,7 @@ 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.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
|
||||
@@ -97,6 +98,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 +120,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 +133,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 +148,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 +160,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 +174,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 +190,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 +222,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 +269,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 +288,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 +309,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,6 +349,7 @@ 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 {
|
||||
@@ -417,6 +430,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 +468,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 +518,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 +535,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())
|
||||
|
||||
+3
-2
@@ -25,6 +25,7 @@ import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.Max;
|
||||
import jakarta.validation.constraints.Min;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Positive;
|
||||
import jakarta.validation.constraints.PositiveOrZero;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import jakarta.ws.rs.BadRequestException;
|
||||
@@ -595,7 +596,7 @@ public class ArchiveController {
|
||||
@HeaderParam(X_SIGNAL_ZK_AUTH_SIGNATURE) final BackupAuthCredentialPresentationSignature signature,
|
||||
|
||||
@Parameter(description = "The size of the message backup to upload in bytes")
|
||||
@QueryParam("uploadLength") final Optional<Long> uploadLength)
|
||||
@QueryParam("uploadLength") final Optional<@Positive Long> uploadLength)
|
||||
throws BackupFailedZkAuthenticationException, BackupWrongCredentialTypeException, BackupPermissionException {
|
||||
if (account.isPresent()) {
|
||||
throw new BadRequestException("must not use authenticated connection for anonymous operations");
|
||||
@@ -651,7 +652,7 @@ public class ArchiveController {
|
||||
@HeaderParam(X_SIGNAL_ZK_AUTH_SIGNATURE) final BackupAuthCredentialPresentationSignature signature,
|
||||
|
||||
@Parameter(description = "The size of the temporary attachment to upload in bytes")
|
||||
@QueryParam("uploadLength") final Optional<Long> uploadLength)
|
||||
@QueryParam("uploadLength") final Optional<@Positive Long> uploadLength)
|
||||
throws RateLimitExceededException, BackupFailedZkAuthenticationException, BackupWrongCredentialTypeException, BackupPermissionException {
|
||||
if (account.isPresent()) {
|
||||
throw new BadRequestException("must not use authenticated connection for anonymous operations");
|
||||
|
||||
+2
@@ -30,6 +30,7 @@ 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,6 +100,7 @@ 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")
|
||||
|
||||
+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) {
|
||||
|
||||
|
||||
+8
-11
@@ -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;
|
||||
@@ -72,6 +73,7 @@ import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceIdentityInfo;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceSpec;
|
||||
import org.whispersystems.textsecuregcm.storage.LinkDeviceTokenAlreadyUsedException;
|
||||
import org.whispersystems.textsecuregcm.storage.PersistentTimer;
|
||||
@@ -88,8 +90,6 @@ import org.whispersystems.textsecuregcm.util.ua.UserAgentUtil;
|
||||
@Tag(name = "Devices")
|
||||
public class DeviceController {
|
||||
|
||||
static final int MAX_DEVICES = 6;
|
||||
|
||||
private final AccountsManager accounts;
|
||||
private final RateLimiters rateLimiters;
|
||||
private final PersistentTimer persistentTimer;
|
||||
@@ -136,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.
|
||||
@@ -150,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);
|
||||
@@ -190,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 {
|
||||
|
||||
@@ -198,15 +201,11 @@ public class DeviceController {
|
||||
|
||||
rateLimiters.getAllocateDeviceLimiter().validate(account.getAccountIdentifier());
|
||||
|
||||
if (account.getDevices().size() >= MAX_DEVICES) {
|
||||
throw new DeviceLimitExceededException(account.getDevices().size(), MAX_DEVICES);
|
||||
}
|
||||
|
||||
if (auth.deviceId() != Device.PRIMARY_ID) {
|
||||
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
|
||||
}
|
||||
|
||||
final String token = accounts.generateLinkDeviceToken(account.getAccountIdentifier());
|
||||
final String token = accounts.generateLinkDeviceToken(account);
|
||||
|
||||
return new LinkDeviceToken(token, AccountsManager.getLinkDeviceTokenIdentifier(token));
|
||||
}
|
||||
@@ -228,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)
|
||||
@@ -271,10 +271,6 @@ public class DeviceController {
|
||||
throw new WebApplicationException(Response.status(422).build());
|
||||
}
|
||||
|
||||
if (account.getDevices().size() >= MAX_DEVICES) {
|
||||
throw new DeviceLimitExceededException(account.getDevices().size(), MAX_DEVICES);
|
||||
}
|
||||
|
||||
final Set<DeviceCapability> capabilities = deviceAttributes.capabilities();
|
||||
|
||||
if (capabilities == null) {
|
||||
@@ -400,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
-49
@@ -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();
|
||||
}
|
||||
|
||||
|
||||
+4
-2
@@ -368,8 +368,8 @@ public class MessageController {
|
||||
final String userAgent = context.getHeaderString(HttpHeaders.USER_AGENT);
|
||||
|
||||
try {
|
||||
final int totalContentLength =
|
||||
messages.messages().stream().mapToInt(message -> message.content().length).sum();
|
||||
final long totalContentLength =
|
||||
messages.messages().stream().mapToLong(message -> message.content().length).sum();
|
||||
|
||||
rateLimiters.getInboundMessageBytes().validate(destinationIdentifier.uuid(), totalContentLength);
|
||||
} catch (final RateLimitExceededException e) {
|
||||
@@ -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
@@ -170,6 +170,7 @@ public class ProfileController {
|
||||
@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) {
|
||||
@@ -278,6 +279,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")
|
||||
|
||||
+6
-2
@@ -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)
|
||||
@@ -366,7 +370,7 @@ public class RegistrationController {
|
||||
}
|
||||
|
||||
final long receiptLevel = receiptCredentialPresentation.getReceiptLevel();
|
||||
if (receiptLevel != ReceiptLevel.LOGIN.getValue()) {
|
||||
if (receiptLevel != ReceiptLevel.LOGIN.getValue() && receiptLevel != ReceiptLevel.LOGIN_SANDBOX.getValue()) {
|
||||
throw new BadRequestException("Invalid receipt level");
|
||||
}
|
||||
|
||||
|
||||
+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) {
|
||||
|
||||
@@ -38,7 +38,7 @@ public class FixerClient {
|
||||
HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
if (response.statusCode() < 200 || response.statusCode() >= 300) {
|
||||
throw new FixerException("Bad response: " + response.statusCode() + " " + response.toString());
|
||||
throw new FixerException("Bad response: " + response.statusCode() + " " + response.toString().replaceAll(apiKey, "***"));
|
||||
}
|
||||
|
||||
final FixerResponse parsedResponse = SystemMapper.jsonMapper().readValue(response.body(), FixerResponse.class);
|
||||
|
||||
-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
-8
@@ -8,8 +8,6 @@ package org.whispersystems.textsecuregcm.filters;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.common.net.HttpHeaders;
|
||||
import com.vdurmont.semver4j.Semver;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import jakarta.ws.rs.WebApplicationException;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.ws.rs.container.ContainerRequestFilter;
|
||||
@@ -24,7 +22,6 @@ import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicRestDeprecationConfiguration.PlatformConfiguration;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
|
||||
import org.whispersystems.textsecuregcm.util.ua.UnrecognizedUserAgentException;
|
||||
@@ -34,7 +31,6 @@ import org.whispersystems.textsecuregcm.util.ua.UserAgentUtil;
|
||||
public class RestDeprecationFilter implements ContainerRequestFilter {
|
||||
|
||||
private static final String AUTHENTICATED_EXPERIMENT_NAME = "restDeprecation";
|
||||
private static final String DEPRECATED_REST_COUNTER_NAME = MetricsUtil.name(RestDeprecationFilter.class, "blockedRestRequest");
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(RestDeprecationFilter.class);
|
||||
|
||||
@@ -75,13 +71,10 @@ public class RestDeprecationFilter implements ContainerRequestFilter {
|
||||
return;
|
||||
}
|
||||
if (version.isGreaterThanOrEqualTo(config.minimumRestFreeVersion())) {
|
||||
Metrics.counter(
|
||||
DEPRECATED_REST_COUNTER_NAME, Tags.of("platform", platform.name().toLowerCase(), "version", version.toString()))
|
||||
.increment();
|
||||
throw new WebApplicationException("use websockets", 498);
|
||||
}
|
||||
} catch (final UnrecognizedUserAgentException e) {
|
||||
return; // at present we're only interested in experimenting on known clients
|
||||
// at present, we're only requiring this for known clients
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+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
-6
@@ -4,8 +4,8 @@ import com.google.protobuf.ByteString;
|
||||
import com.google.protobuf.Empty;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import org.signal.chat.donations.CreateDonationPermitRequest;
|
||||
import org.signal.chat.donations.CreateDonationPermitResponse;
|
||||
import org.signal.chat.donations.CreateDonationPermitsRequest;
|
||||
import org.signal.chat.donations.CreateDonationPermitsResponse;
|
||||
import org.signal.chat.donations.RedeemReceiptRequest;
|
||||
import org.signal.chat.donations.RedeemReceiptResponse;
|
||||
import org.signal.chat.donations.SimpleDonationsGrpc;
|
||||
@@ -120,10 +120,10 @@ public class DonationsGrpcService extends SimpleDonationsGrpc.DonationsImplBase
|
||||
}
|
||||
|
||||
@Override
|
||||
public CreateDonationPermitResponse createDonationPermit(final CreateDonationPermitRequest request) throws Exception {
|
||||
public CreateDonationPermitsResponse createDonationPermits(final CreateDonationPermitsRequest request) throws Exception {
|
||||
final DonationPermitRequest permitRequest;
|
||||
try {
|
||||
permitRequest = new DonationPermitRequest(request.getDonationPermitRequest().toByteArray());
|
||||
permitRequest = new DonationPermitRequest(request.getDonationPermitsRequest().toByteArray());
|
||||
} catch (InvalidInputException e) {
|
||||
throw GrpcExceptions.invalidArguments("invalid permit request");
|
||||
}
|
||||
@@ -133,8 +133,8 @@ public class DonationsGrpcService extends SimpleDonationsGrpc.DonationsImplBase
|
||||
|
||||
final DonationPermitResponse permitResponse = donationPermitsManager.issue(permitRequest);
|
||||
|
||||
return CreateDonationPermitResponse.newBuilder()
|
||||
.setDonationPermitResponse(ByteString.copyFrom(permitResponse.serialize()))
|
||||
return CreateDonationPermitsResponse.newBuilder()
|
||||
.setDonationPermitsResponse(ByteString.copyFrom(permitResponse.serialize()))
|
||||
.build();
|
||||
}
|
||||
}
|
||||
+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();
|
||||
}
|
||||
};
|
||||
|
||||
+6
@@ -22,6 +22,7 @@ import org.signal.chat.keys.SimpleKeysAnonymousGrpc;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.signal.libsignal.zkgroup.ServerSecretParams;
|
||||
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
@@ -48,6 +49,11 @@ public class KeysAnonymousGrpcService extends SimpleKeysAnonymousGrpc.KeysAnonym
|
||||
final ServiceIdentifier serviceIdentifier =
|
||||
GrpcServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getRequest().getTargetIdentifier());
|
||||
|
||||
if (serviceIdentifier.identityType() == IdentityType.PNI
|
||||
&& request.getAuthorizationCase() != GetPreKeysAnonymousRequest.AuthorizationCase.GROUP_SEND_TOKEN) {
|
||||
throw GrpcExceptions.fieldViolation("authorization", "group send token is required for PNI targets");
|
||||
}
|
||||
|
||||
final byte deviceId = request.getRequest().hasDeviceId()
|
||||
? DeviceIdUtil.validate(request.getRequest().getDeviceId())
|
||||
: KeysGrpcHelper.ALL_DEVICES;
|
||||
|
||||
@@ -18,7 +18,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 +37,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,
|
||||
|
||||
+19
-7
@@ -10,6 +10,7 @@ import com.google.protobuf.Empty;
|
||||
import java.time.Clock;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.stream.Collectors;
|
||||
import org.signal.chat.errors.FailedUnidentifiedAuthorization;
|
||||
import org.signal.chat.errors.NotFound;
|
||||
@@ -86,14 +87,15 @@ public class MessagesAnonymousGrpcService extends SimpleMessagesAnonymousGrpc.Me
|
||||
final ServiceIdentifier destinationServiceIdentifier =
|
||||
GrpcServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getDestination());
|
||||
|
||||
if (destinationServiceIdentifier.identityType() == IdentityType.PNI
|
||||
&& request.getAuthorizationCase() != SendSealedSenderMessageRequest.AuthorizationCase.GROUP_SEND_TOKEN) {
|
||||
throw GrpcExceptions.fieldViolation("authorization", "group send token is required for PNI destinations");
|
||||
}
|
||||
|
||||
final Optional<Account> maybeDestination = accountsManager.getByServiceIdentifier(destinationServiceIdentifier);
|
||||
|
||||
final boolean authorized = switch (request.getAuthorizationCase()) {
|
||||
case UNIDENTIFIED_ACCESS_KEY -> {
|
||||
if (destinationServiceIdentifier.identityType() == IdentityType.PNI) {
|
||||
throw GrpcExceptions.fieldViolation("authorization",
|
||||
"message for PNI cannot be authenticated with an unidentified access token");
|
||||
}
|
||||
final byte[] uak = request.getUnidentifiedAccessKey().toByteArray();
|
||||
yield maybeDestination
|
||||
.map(account -> UnidentifiedAccessUtil.checkUnidentifiedAccess(account, uak))
|
||||
@@ -104,7 +106,7 @@ public class MessagesAnonymousGrpcService extends SimpleMessagesAnonymousGrpc.Me
|
||||
case GROUP_SEND_TOKEN ->
|
||||
groupSendTokenUtil.checkGroupSendToken(request.getGroupSendToken(), destinationServiceIdentifier);
|
||||
case UNRESTRICTED_ACCESS ->
|
||||
maybeDestination.map(account -> account.isUnrestrictedUnidentifiedAccess()).orElse(false);
|
||||
maybeDestination.map(Account::isUnrestrictedUnidentifiedAccess).orElse(false);
|
||||
case AUTHORIZATION_NOT_SET ->
|
||||
throw GrpcExceptions.fieldViolation("authorization", "expected authorization token not provided");
|
||||
};
|
||||
@@ -118,7 +120,7 @@ public class MessagesAnonymousGrpcService extends SimpleMessagesAnonymousGrpc.Me
|
||||
if (maybeDestination.isEmpty()) {
|
||||
return SendMessageResponse.newBuilder().setDestinationNotFound(NotFound.getDefaultInstance()).build();
|
||||
}
|
||||
|
||||
|
||||
return sendIndividualMessage(maybeDestination.get(),
|
||||
destinationServiceIdentifier,
|
||||
request.getMessages(),
|
||||
@@ -168,7 +170,7 @@ public class MessagesAnonymousGrpcService extends SimpleMessagesAnonymousGrpc.Me
|
||||
destinationServiceIdentifier);
|
||||
|
||||
spamCheckResult.response().ifPresent(grpcResponse ->
|
||||
grpcResponse.throwStatusOr(_ -> GrpcExceptions.rateLimitExceeded(null)));
|
||||
grpcResponse.throwStatusOr(_ -> GrpcExceptions.rateLimitExceeded(null)));
|
||||
|
||||
try {
|
||||
final int totalPayloadLength = messages.getMessagesMap().values().stream()
|
||||
@@ -297,6 +299,16 @@ public class MessagesAnonymousGrpcService extends SimpleMessagesAnonymousGrpc.Me
|
||||
final Map<SealedSenderMultiRecipientMessage.Recipient, Account> resolvedRecipients =
|
||||
MessageUtil.resolveRecipients(accountsManager, multiRecipientMessage);
|
||||
|
||||
if (story) {
|
||||
CompletableFuture.allOf(resolvedRecipients.values()
|
||||
.stream()
|
||||
.map(Account::getAccountIdentifier)
|
||||
.map(accountIdentifier ->
|
||||
rateLimiters.getStoriesLimiter().validateAsync(accountIdentifier).toCompletableFuture())
|
||||
.toArray(CompletableFuture[]::new))
|
||||
.join();
|
||||
}
|
||||
|
||||
try {
|
||||
if (!resolvedRecipients.isEmpty()) {
|
||||
messageSender.sendMultiRecipientMessage(multiRecipientMessage,
|
||||
|
||||
+40
-23
@@ -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,57 +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 {}
|
||||
|
||||
record UnsupportedLevel() implements OneTimeDonationRequestValidationResult {}
|
||||
|
||||
record AmountBelowMinimum(BigDecimal minimum) implements OneTimeDonationRequestValidationResult {}
|
||||
|
||||
record AmountAboveSepaLimit(BigDecimal maximum) implements OneTimeDonationRequestValidationResult {}
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public Map<String, String> getErrorBody() {
|
||||
return errorBody;
|
||||
}
|
||||
}
|
||||
|
||||
public static OneTimeDonationRequestValidationResult validateOneTimeDonationRequest(
|
||||
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.
|
||||
///
|
||||
/// @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
|
||||
|
||||
+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();
|
||||
}
|
||||
|
||||
|
||||
+13
-9
@@ -21,6 +21,7 @@ import java.util.stream.Collectors;
|
||||
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;
|
||||
@@ -115,9 +116,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 +193,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()) {
|
||||
|
||||
+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();
|
||||
}
|
||||
|
||||
|
||||
+54
-45
@@ -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,56 +310,67 @@ 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(),
|
||||
(l1, l2) -> SubscriptionsUtil.subscriptionsAreSameType(subscriptionConfiguration, l1, l2));
|
||||
return SetSubscriptionLevelResponse.newBuilder().setSuccess(
|
||||
SetSubscriptionLevelResponse.SetSubscriptionLevelResult.newBuilder().setLevel(request.getLevel()).build())
|
||||
return SetSubscriptionLevelResponse.newBuilder().setSuccess(Empty.getDefaultInstance())
|
||||
.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) {
|
||||
return SetSubscriptionLevelResponse.newBuilder().setSubscriptionProcessorConflict(
|
||||
FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
|
||||
return SetSubscriptionLevelResponse.newBuilder()
|
||||
.setFailedPrecondition(FailedPrecondition.newBuilder()
|
||||
.setDescription("No payment method set up"))
|
||||
.build();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -386,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(
|
||||
|
||||
+18
-30
@@ -6,66 +6,55 @@ 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.ExtendedSSLSession;
|
||||
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
|
||||
/// This works around [netty#17690](https://github.com/netty/netty/issues/17690):
|
||||
/// netty’s engine only asks the key manager for RSA- and EC-family key types, so it never selects an Ed25519 key.
|
||||
class BoringSslServerKeyManager extends X509ExtendedKeyManager {
|
||||
|
||||
private final X509KeyManager delegate;
|
||||
private final X509ExtendedKeyManager delegate;
|
||||
|
||||
@VisibleForTesting
|
||||
BoringSslServerKeyManager(final X509KeyManager delegate) {
|
||||
BoringSslServerKeyManager(final X509ExtendedKeyManager delegate) {
|
||||
if (!"BoringSSL".equals(OpenSsl.versionString())) {
|
||||
throw new IllegalStateException("BoringSSL required, found " + OpenSsl.versionString());
|
||||
}
|
||||
this.delegate = delegate;
|
||||
}
|
||||
|
||||
/// @throws IllegalArgumentException if `keyManagers` contains no [X509KeyManager]
|
||||
/// @throws IllegalArgumentException if `keyManagers` contains no [X509ExtendedKeyManager]
|
||||
static BoringSslServerKeyManager wrap(final KeyManager[] keyManagers) {
|
||||
return Arrays.stream(keyManagers)
|
||||
.filter(X509KeyManager.class::isInstance)
|
||||
.map(X509KeyManager.class::cast)
|
||||
.filter(X509ExtendedKeyManager.class::isInstance)
|
||||
.map(X509ExtendedKeyManager.class::cast)
|
||||
.findFirst()
|
||||
.map(BoringSslServerKeyManager::new)
|
||||
.orElseThrow(() -> new IllegalArgumentException("No X509KeyManager found"));
|
||||
.orElseThrow(() -> new IllegalArgumentException("No X509ExtendedKeyManager 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) {
|
||||
if (!(engine.getHandshakeSession() instanceof ExtendedSSLSession session)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
for (final String signatureAlgorithm : peerSignatureAlgorithms) {
|
||||
// Netty will only call this with EC/RSA key types (https://github.com/netty/netty/issues/17690).
|
||||
// We can safely ignore `keyType` and loop through the peer's signature algorithms to find the best matching key.
|
||||
for (final String signatureAlgorithm : session.getPeerSupportedSignatureAlgorithms()) {
|
||||
final Optional<String> maybeAlias = getJdkKeyType(signatureAlgorithm)
|
||||
// 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));
|
||||
.map(jdkKeyType -> delegate.chooseEngineServerAlias(jdkKeyType, issuers, engine));
|
||||
|
||||
if (maybeAlias.isPresent()) {
|
||||
return maybeAlias.get();
|
||||
@@ -75,15 +64,14 @@ class BoringSslServerKeyManager extends X509ExtendedKeyManager {
|
||||
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
|
||||
/// Maps a JDK signature algorithm name to the JDK key type that can produce it
|
||||
@VisibleForTesting
|
||||
static Optional<String> getJdkKeyType(final String signatureAlgorithm) {
|
||||
if (signatureAlgorithm.equals("ed25519")) {
|
||||
if (signatureAlgorithm.equals("Ed25519")) {
|
||||
return Optional.of("EdDSA");
|
||||
} else if (signatureAlgorithm.startsWith("ecdsa_")) {
|
||||
} else if (signatureAlgorithm.endsWith("withECDSA")) {
|
||||
return Optional.of("EC");
|
||||
} else if (signatureAlgorithm.startsWith("rsa_pss_rsae_")) {
|
||||
} else if (signatureAlgorithm.endsWith("withRSA")) {
|
||||
return Optional.of("RSA");
|
||||
}
|
||||
|
||||
|
||||
+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);
|
||||
|
||||
+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()));
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -10,7 +10,7 @@ import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import jakarta.ws.rs.ext.ExceptionMapper;
|
||||
import jakarta.ws.rs.ext.Provider;
|
||||
import org.whispersystems.textsecuregcm.controllers.DeviceLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceLimitExceededException;
|
||||
|
||||
@Provider
|
||||
public class DeviceLimitExceededExceptionMapper implements ExceptionMapper<DeviceLimitExceededException> {
|
||||
|
||||
+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()))
|
||||
|
||||
+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;
|
||||
}
|
||||
|
||||
+35
-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);
|
||||
}
|
||||
@@ -195,6 +195,10 @@ public class AppleAppStoreClient {
|
||||
}
|
||||
}
|
||||
|
||||
Environment getDefaultEnvironment() {
|
||||
return defaultEnvironment;
|
||||
}
|
||||
|
||||
private <T> T lookupByTransactionIdInEnvironment(final Environment env, final String transactionId, final Tags errorTags, final TransactionFinder<T> lookupFunction) throws APIException, IOException {
|
||||
try {
|
||||
return retry.executeCallable(() -> {
|
||||
@@ -216,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;
|
||||
@@ -232,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)
|
||||
@@ -240,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;
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+8
-1
@@ -171,9 +171,16 @@ public class AppleAppStoreManager implements SubscriptionPaymentProcessor, OneTi
|
||||
if (transaction.getRevocationDate() != null) {
|
||||
throw new PurchasePaymentRequiredException(getProvider());
|
||||
}
|
||||
|
||||
ReceiptLevel receiptLevel = getLevel(transaction);
|
||||
if (receiptLevel == ReceiptLevel.LOGIN && transaction.getEnvironment() != appleAppStoreClient.getDefaultEnvironment()) {
|
||||
// This is a special case: if we had to resort to the fallback environment to resolve this transaction, we should
|
||||
// mark the purchase to indicate it only gets a restricted entitlement.
|
||||
receiptLevel = ReceiptLevel.LOGIN_SANDBOX;
|
||||
}
|
||||
return new PaymentDetails(
|
||||
Objects.requireNonNull(transaction.getTransactionId()),
|
||||
getLevel(transaction),
|
||||
receiptLevel,
|
||||
Instant.ofEpochMilli(transaction.getPurchaseDate()));
|
||||
|
||||
}
|
||||
|
||||
+13
-7
@@ -28,6 +28,9 @@ public class LoginPurchaseManager {
|
||||
@VisibleForTesting
|
||||
final static Duration LOGIN_EXPIRATION = Duration.ofDays(366 * 5);
|
||||
|
||||
@VisibleForTesting
|
||||
final static Duration SANDBOX_LOGIN_EXPIRATION = Duration.ofDays(2);
|
||||
|
||||
/// Construct a LoginPurchaseManager
|
||||
///
|
||||
/// @param oneTimePaymentProcessors The processor to use for each supported [PaymentProvider]
|
||||
@@ -65,23 +68,26 @@ public class LoginPurchaseManager {
|
||||
}
|
||||
|
||||
final PaymentDetails paymentDetails = oneTimePaymentProcessor.claimOneTimePurchase(purchaseId);
|
||||
if (paymentDetails.level() != ReceiptLevel.LOGIN) {
|
||||
throw new PurchaseInvalidArgumentsException("purchase was for an unexpected product");
|
||||
}
|
||||
final Duration expirationDuration = switch (paymentDetails.level()) {
|
||||
case LOGIN -> LOGIN_EXPIRATION;
|
||||
case LOGIN_SANDBOX -> SANDBOX_LOGIN_EXPIRATION;
|
||||
case ONE_TIME_DONATION, ONE_TIME_GIFT_DONATION, BACKUP_FREE, BACKUP_PAID, SUBSCRIPTION_LOW, SUBSCRIPTION_MEDIUM, SUBSCRIPTION_HIGH ->
|
||||
throw new PurchaseInvalidArgumentsException("purchase was for an unexpected product");
|
||||
};
|
||||
|
||||
// Calculating the expiration from the creation date works for IAP purchases. However, for other processors, the
|
||||
// creation date of the payment intent might be days before the payment actually completed. If we support non-IAP
|
||||
// processors we should attempt to get the latest date. see OneTimeDonationController/OneTimeDonationsManager
|
||||
final Instant expiration = paymentDetails.created().plus(LOGIN_EXPIRATION).truncatedTo(ChronoUnit.DAYS);
|
||||
final Instant expireAt = paymentDetails.created().plus(expirationDuration).truncatedTo(ChronoUnit.DAYS);
|
||||
|
||||
try {
|
||||
issuedReceiptsManager.recordOneTimeIssuance(paymentDetails.id(), paymentProvider, receiptCredentialRequest,
|
||||
expiration);
|
||||
expireAt);
|
||||
} catch (WriteConflictException _) {
|
||||
throw new PurchaseReceiptAlreadyRedeemedException();
|
||||
}
|
||||
|
||||
return zkReceiptOperations.issueReceiptCredential(receiptCredentialRequest, expiration.getEpochSecond(),
|
||||
ReceiptLevel.LOGIN.getValue());
|
||||
return zkReceiptOperations.issueReceiptCredential(receiptCredentialRequest, expireAt.getEpochSecond(),
|
||||
paymentDetails.level().getValue());
|
||||
}
|
||||
}
|
||||
+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;
|
||||
}
|
||||
|
||||
@@ -19,6 +19,7 @@ public enum ReceiptLevel {
|
||||
BACKUP_FREE(200L),
|
||||
BACKUP_PAID(201L),
|
||||
LOGIN(300L),
|
||||
LOGIN_SANDBOX(301L),
|
||||
SUBSCRIPTION_LOW(500),
|
||||
SUBSCRIPTION_MEDIUM(1000),
|
||||
SUBSCRIPTION_HIGH(2000);
|
||||
|
||||
+11
-4
@@ -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));
|
||||
|
||||
@@ -117,6 +117,12 @@ public class MessageSender {
|
||||
@Nullable final String userAgent)
|
||||
throws MismatchedDevicesException, MessageTooLargeException, MessageDeliveryNotAllowedException {
|
||||
|
||||
// Every message in the map is expected to have the same ephemerality.
|
||||
if (dynamicConfigurationManager.getConfiguration().getMessageDeliveryConfiguration().dropEphemeralMessages()
|
||||
&& messagesByDeviceId.values().stream().anyMatch(Envelope::getEphemeral)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (dynamicConfigurationManager.getConfiguration().getMessageDeliveryConfiguration().isReadOnly()) {
|
||||
throw new MessageDeliveryNotAllowedException();
|
||||
}
|
||||
@@ -199,6 +205,11 @@ public class MessageSender {
|
||||
@Nullable final String userAgent)
|
||||
throws MultiRecipientMismatchedDevicesException, MessageTooLargeException, MessageDeliveryNotAllowedException {
|
||||
|
||||
if (dynamicConfigurationManager.getConfiguration().getMessageDeliveryConfiguration().dropEphemeralMessages()
|
||||
&& isEphemeral) {
|
||||
return CompletableFuture.completedFuture(null);
|
||||
}
|
||||
|
||||
if (dynamicConfigurationManager.getConfiguration().getMessageDeliveryConfiguration().isReadOnly()) {
|
||||
throw new MessageDeliveryNotAllowedException();
|
||||
}
|
||||
|
||||
+15
-5
@@ -41,6 +41,8 @@ public class ProvisioningManager extends RedisPubSubAdapter<byte[], byte[]> impl
|
||||
private static final String RECEIVE_PROVISIONING_MESSAGE_COUNTER_NAME =
|
||||
name(ProvisioningManager.class, "receiveProvisioningMessage");
|
||||
|
||||
private static final String CHANNEL_PREFIX = "provisioning::";
|
||||
|
||||
private static final String RETRY_NAME = ResilienceUtil.name(ProvisioningManager.class);
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(ProvisioningManager.class);
|
||||
@@ -64,12 +66,12 @@ public class ProvisioningManager extends RedisPubSubAdapter<byte[], byte[]> impl
|
||||
|
||||
public void addListener(final String address, final Consumer<PubSubProtos.PubSubMessage> listener) {
|
||||
listenersByProvisioningAddress.put(address, listener);
|
||||
pubSubConnection.usePubSubConnection(connection -> connection.sync().subscribe(address.getBytes(StandardCharsets.UTF_8)));
|
||||
pubSubConnection.usePubSubConnection(connection -> connection.sync().subscribe(getChannel(address)));
|
||||
}
|
||||
|
||||
public void removeListener(final String address) {
|
||||
RedisOperation.unchecked(() ->
|
||||
pubSubConnection.usePubSubConnection(connection -> connection.sync().unsubscribe(address.getBytes(StandardCharsets.UTF_8))));
|
||||
pubSubConnection.usePubSubConnection(connection -> connection.sync().unsubscribe(getChannel(address))));
|
||||
|
||||
listenersByProvisioningAddress.remove(address);
|
||||
}
|
||||
@@ -82,7 +84,7 @@ public class ProvisioningManager extends RedisPubSubAdapter<byte[], byte[]> impl
|
||||
|
||||
final boolean receiverPresent = ResilienceUtil.getGeneralRedisRetry(RETRY_NAME)
|
||||
.executeSupplier(() -> pubSubClient.withBinaryConnection(connection ->
|
||||
connection.sync().publish(address.getBytes(StandardCharsets.UTF_8), pubSubMessage.toByteArray()) > 0));
|
||||
connection.sync().publish(getChannel(address), pubSubMessage.toByteArray()) > 0));
|
||||
|
||||
Metrics.counter(SEND_PROVISIONING_MESSAGE_COUNTER_NAME, "online", String.valueOf(receiverPresent)).increment();
|
||||
|
||||
@@ -92,7 +94,7 @@ public class ProvisioningManager extends RedisPubSubAdapter<byte[], byte[]> impl
|
||||
@Override
|
||||
public void message(final byte[] channel, final byte[] message) {
|
||||
try {
|
||||
final String address = new String(channel, StandardCharsets.UTF_8);
|
||||
final String address = getAddress(channel);
|
||||
final PubSubProtos.PubSubMessage pubSubMessage = PubSubProtos.PubSubMessage.parseFrom(message);
|
||||
|
||||
if (pubSubMessage.getType() == PubSubProtos.PubSubMessage.Type.DELIVER) {
|
||||
@@ -114,6 +116,14 @@ public class ProvisioningManager extends RedisPubSubAdapter<byte[], byte[]> impl
|
||||
|
||||
@Override
|
||||
public void unsubscribed(final byte[] channel, final long count) {
|
||||
listenersByProvisioningAddress.remove(new String(channel, StandardCharsets.UTF_8));
|
||||
listenersByProvisioningAddress.remove(getAddress(channel));
|
||||
}
|
||||
|
||||
private static byte[] getChannel(final String address) {
|
||||
return (CHANNEL_PREFIX + address).getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
private static String getAddress(final byte[] channel) {
|
||||
return new String(channel, StandardCharsets.UTF_8).substring(CHANNEL_PREFIX.length());
|
||||
}
|
||||
}
|
||||
+6
-2
@@ -35,9 +35,10 @@ import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.util.ResilienceUtil;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import org.whispersystems.textsecuregcm.util.RedisClusterUtil;
|
||||
import org.whispersystems.textsecuregcm.util.ResilienceUtil;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
@@ -99,7 +100,10 @@ public class PushNotificationScheduler implements Managed {
|
||||
Util.sleep(1000);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.warn("Exception while processing scheduled notifications", e);
|
||||
|
||||
if (!ExceptionUtils.isBreakerOpen(e)) {
|
||||
logger.warn("Exception while processing scheduled notifications", e);
|
||||
}
|
||||
|
||||
try {
|
||||
Thread.sleep(EXCEPTION_PAUSE);
|
||||
|
||||
@@ -20,6 +20,7 @@ import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import reactor.core.publisher.Flux;
|
||||
|
||||
public class ClusterLuaScript {
|
||||
@@ -109,7 +110,9 @@ public class ClusterLuaScript {
|
||||
return connection.sync().eval(script, scriptOutputType, keys, args);
|
||||
}
|
||||
} catch (final Exception e) {
|
||||
log.warn("Failed to execute script", e);
|
||||
if (!ExceptionUtils.isBreakerOpen(e)) {
|
||||
log.warn("Failed to execute script", e);
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
@@ -123,7 +126,9 @@ public class ClusterLuaScript {
|
||||
return connection.async().eval(script, scriptOutputType, keys, args);
|
||||
}
|
||||
|
||||
log.warn("Failed to execute script", throwable);
|
||||
if (!ExceptionUtils.isBreakerOpen(throwable)) {
|
||||
log.warn("Failed to execute script", throwable);
|
||||
}
|
||||
throw new RedisException(throwable);
|
||||
}).toCompletableFuture();
|
||||
}
|
||||
@@ -133,6 +138,10 @@ public class ClusterLuaScript {
|
||||
|
||||
return connection.reactive().evalsha(sha, scriptOutputType, keys, args)
|
||||
.onErrorResume(RedisNoScriptException.class, _ -> connection.reactive().eval(script, scriptOutputType, keys, args))
|
||||
.doOnError(throwable -> log.warn("Failed to execute script", throwable));
|
||||
.doOnError(throwable -> {
|
||||
if (!ExceptionUtils.isBreakerOpen(throwable)) {
|
||||
log.warn("Failed to execute script", throwable);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
/// One of the provided transaction write items to an account creation operation failed
|
||||
class AccountCreationConditionException extends Exception {
|
||||
|
||||
private final int index;
|
||||
|
||||
AccountCreationConditionException(final int index) {
|
||||
this.index = index;
|
||||
}
|
||||
|
||||
/// @return The index of the item that caused a conditional check failure
|
||||
public int getIndex() {
|
||||
return index;
|
||||
}
|
||||
}
|
||||
@@ -298,11 +298,25 @@ public class Accounts {
|
||||
return true;
|
||||
}
|
||||
|
||||
/// Create an account record via a receipt presentation
|
||||
///
|
||||
/// @param account The account to create
|
||||
/// @param receiptCredentialPresentation A presentation of a receipt credential that grants the ability to create
|
||||
/// one account
|
||||
/// @param accountRecoveryPasswordInRequest The account-recovery-password supplied in the request
|
||||
/// @param additionalWriteItems Additional items to include in the transaction
|
||||
///
|
||||
/// @return true
|
||||
/// @throws AccountAlreadyExistsException An account was already created using this receipt
|
||||
/// @throws ReceiptAlreadyRedeemedException The receipt was already used to create an account and this creation
|
||||
/// request would require a new account
|
||||
/// @throws AccountCreationConditionException One of the conditions in `additionalWriteItems` failed. The exception
|
||||
/// contains the index of the [TransactWriteItem] that failed
|
||||
boolean create(final Account account,
|
||||
final ReceiptCredentialPresentation receiptCredentialPresentation,
|
||||
final byte[] accountRecoveryPasswordInRequest,
|
||||
final List<TransactWriteItem> additionalWriteItems)
|
||||
throws AccountAlreadyExistsException, ReceiptAlreadyRedeemedException {
|
||||
throws AccountAlreadyExistsException, ReceiptAlreadyRedeemedException, AccountCreationConditionException {
|
||||
|
||||
final Timer.Sample sample = Timer.start();
|
||||
|
||||
@@ -320,6 +334,7 @@ public class Accounts {
|
||||
final Collection<TransactWriteItem> writeItems = new ArrayList<>(
|
||||
List.of(signalLoginReceiptConstraintPut, accountPut));
|
||||
|
||||
final int additionalWriteItemsStart = writeItems.size();
|
||||
writeItems.addAll(additionalWriteItems);
|
||||
|
||||
final TransactWriteItemsRequest request = TransactWriteItemsRequest.builder()
|
||||
@@ -358,7 +373,18 @@ public class Accounts {
|
||||
throw new AccountAlreadyExistsException(existingAccount);
|
||||
}
|
||||
|
||||
for (int i = additionalWriteItemsStart; i < e.cancellationReasons().size(); i++) {
|
||||
if (conditionalCheckFailed(e.cancellationReasons().get(i))) {
|
||||
// Indicate the first caller-supplied TransactWriteItem that failed
|
||||
throw new AccountCreationConditionException(i - additionalWriteItemsStart);
|
||||
}
|
||||
}
|
||||
|
||||
final CancellationReason accountCancellationReason = e.cancellationReasons().get(1);
|
||||
if (conditionalCheckFailed(accountCancellationReason)) {
|
||||
throw new IllegalStateException("Tried to create an account with an ACI that already exists " + account.getAccountIdentifier());
|
||||
}
|
||||
|
||||
if (TRANSACTION_CONFLICT.equals(accountCancellationReason.code())) {
|
||||
// this should only happen if two clients manage to make concurrent create() calls
|
||||
throw new ContestedOptimisticLockException();
|
||||
@@ -1632,6 +1658,8 @@ public class Accounts {
|
||||
.orElseGet(() -> Put.builder()
|
||||
.tableName(accountsTableName)
|
||||
.item(item)
|
||||
.conditionExpression("attribute_not_exists(#uuid)")
|
||||
.expressionAttributeNames(Map.of("#uuid", KEY_ACCOUNT_UUID))
|
||||
.build());
|
||||
|
||||
return TransactWriteItem.builder()
|
||||
|
||||
+206
-89
@@ -86,6 +86,7 @@ import org.whispersystems.textsecuregcm.entities.TransferArchiveResult;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.purchases.ReceiptLevel;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantPubSubConnection;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
@@ -127,6 +128,8 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
name(AccountsManager.class, "registrationIdRedisKeyCounter");
|
||||
private static final String CREATE_TIMER_NAME = name(AccountsManager.class, "create");
|
||||
private static final String HAS_NUMBER_TAG_NAME = "hasNumber";
|
||||
private static final String SANDBOX_POOL_EXHAUSTED_COUNTER_NAME =
|
||||
name(AccountsManager.class, "sandboxAccountPoolExhausted");
|
||||
|
||||
private static final String RETRY_NAME = ResilienceUtil.name(AccountsManager.class);
|
||||
|
||||
@@ -147,6 +150,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
private final SecureValueRecoveryClient secureValueRecovery2Client;
|
||||
private final DisconnectionRequestManager disconnectionRequestManager;
|
||||
private final PhoneNumberRecoveryPasswordsManager phoneNumberRecoveryPasswordsManager;
|
||||
private final SandboxAccounts sandboxAccounts;
|
||||
private final ScheduledExecutorService messagesPollExecutor;
|
||||
private final ScheduledExecutorService retryExecutor;
|
||||
private final Clock clock;
|
||||
@@ -197,6 +201,8 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
|
||||
private static final int MAX_UPDATE_ATTEMPTS = 10;
|
||||
|
||||
public static final int MAX_DEVICES = 6;
|
||||
|
||||
private static final SecureRandom SECURE_RANDOM = new SecureRandom();
|
||||
|
||||
private static final int AUTH_CREDENTIAL_SALT_SIZE = 16;
|
||||
@@ -287,6 +293,10 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
private static class UncheckedWebAuthnMismatchException extends NoStackTraceRuntimeException {
|
||||
}
|
||||
|
||||
private sealed interface CreationDetails permits NumberDetails, NumberlessDetails {}
|
||||
private record NumberDetails(boolean recentlyDeleted, String e164, UUID pni, IdentityKey pniIdentityKey) implements CreationDetails {}
|
||||
private record NumberlessDetails(ReceiptCredentialPresentation receiptCredentialPresentation, byte[] authCredentialSalt) implements CreationDetails {}
|
||||
|
||||
public AccountsManager(final Accounts accounts,
|
||||
final PhoneNumberIdentifiers phoneNumberIdentifiers,
|
||||
final FaultTolerantRedisClusterClient cacheCluster,
|
||||
@@ -300,6 +310,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
final SecureValueRecoveryClient secureValueRecovery2Client,
|
||||
final DisconnectionRequestManager disconnectionRequestManager,
|
||||
final PhoneNumberRecoveryPasswordsManager phoneNumberRecoveryPasswordsManager,
|
||||
final SandboxAccounts sandboxAccounts,
|
||||
final ScheduledExecutorService messagesPollExecutor,
|
||||
final ScheduledExecutorService retryExecutor,
|
||||
final Clock clock,
|
||||
@@ -319,6 +330,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
this.secureValueRecovery2Client = secureValueRecovery2Client;
|
||||
this.disconnectionRequestManager = disconnectionRequestManager;
|
||||
this.phoneNumberRecoveryPasswordsManager = requireNonNull(phoneNumberRecoveryPasswordsManager);
|
||||
this.sandboxAccounts = requireNonNull(sandboxAccounts);
|
||||
this.messagesPollExecutor = messagesPollExecutor;
|
||||
this.retryExecutor = retryExecutor;
|
||||
this.clock = requireNonNull(clock);
|
||||
@@ -392,16 +404,32 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
() -> new IllegalArgumentException("recovery password is required for accounts without phone numbers"));
|
||||
|
||||
// This salt is required for generating PNI-based auth credentials (e.g. group credentials) for accounts without a number
|
||||
final byte[] authCredentialSalt = new byte[AUTH_CREDENTIAL_SALT_SIZE];
|
||||
SECURE_RANDOM.nextBytes(authCredentialSalt);
|
||||
final byte[] authCredentialSalt = generateAuthCredentialSalt();
|
||||
|
||||
// We ignore this property on accounts without a number anyway, but ensure that it is false for consistency
|
||||
accountAttributes.setDiscoverableByPhoneNumber(false);
|
||||
|
||||
final Timer.Sample sample = Timer.start();
|
||||
final ReceiptLevel receiptLevel = ReceiptLevel.lookupLevel(receiptCredentialPresentation.getReceiptLevel())
|
||||
.orElseThrow(() -> new IllegalStateException("Invalid receipt level"));
|
||||
|
||||
final NumberlessDetails numberlessDetails = new NumberlessDetails(receiptCredentialPresentation, authCredentialSalt);
|
||||
|
||||
final Timer.Sample sample = Timer.start();
|
||||
try {
|
||||
return create(Optional.empty(), Optional.empty(), Optional.of(receiptCredentialPresentation), Optional.of(authCredentialSalt), accountAttributes, aciIdentityKey, Optional.empty(), primaryDeviceSpec, userAgent);
|
||||
return switch (receiptLevel) {
|
||||
case LOGIN -> {
|
||||
final UUID aci = UUID.randomUUID();
|
||||
final List<TransactWriteItem> additionalWriteItems = keysWriteItems(aci, Optional.empty(), primaryDeviceSpec);
|
||||
yield create(aci, numberlessDetails, accountAttributes, aciIdentityKey, primaryDeviceSpec, additionalWriteItems, userAgent);
|
||||
}
|
||||
case LOGIN_SANDBOX ->
|
||||
createSandboxAccount(accountAttributes, aciIdentityKey, primaryDeviceSpec, numberlessDetails, userAgent);
|
||||
default -> throw new IllegalStateException(
|
||||
"Invalid receipt level: " + receiptCredentialPresentation.getReceiptLevel());
|
||||
};
|
||||
} catch (final AccountCreationConditionException e) {
|
||||
logger.error("Unexpected condition exception while creating account", e);
|
||||
throw new IllegalStateException(e);
|
||||
} catch (final RuntimeException e) {
|
||||
logger.error("Unexpected exception while creating account", e);
|
||||
throw e;
|
||||
@@ -427,49 +455,87 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
final DeviceSpec primaryDeviceSpec,
|
||||
@Nullable final String userAgent) {
|
||||
|
||||
final UUID pni = phoneNumberIdentifiers.getPhoneNumberIdentifier(number).join();
|
||||
final Timer.Sample sample = Timer.start();
|
||||
try {
|
||||
final UUID pni = phoneNumberIdentifiers.getPhoneNumberIdentifier(number).join();
|
||||
return accountLockManager.withLock(Set.of(pni), () -> {
|
||||
try {
|
||||
// Reuse the ACI from any recently-deleted account with this number to cover cases where somebody is re-registering
|
||||
final Optional<UUID> recentlyDeletedAci = findRecentlyDeletedAccountIdentifier(pni);
|
||||
final UUID aci = recentlyDeletedAci.orElseGet(UUID::randomUUID);
|
||||
|
||||
return Metrics.timer(CREATE_TIMER_NAME, HAS_NUMBER_TAG_NAME, "true").record(() -> {
|
||||
try {
|
||||
return accountLockManager.withLock(Set.of(pni),
|
||||
() -> create(Optional.of(number), Optional.of(pni), Optional.empty(), Optional.empty(), accountAttributes, aciIdentityKey, Optional.of(pniIdentityKey), primaryDeviceSpec, userAgent));
|
||||
} catch (final ReceiptAlreadyRedeemedException e) {
|
||||
throw new AssertionError("ReceiptAlreadyRedeemedException must never be thrown for accounts with numbers");
|
||||
} catch (final RuntimeException e) {
|
||||
logger.error("Unexpected exception while creating account", e);
|
||||
throw e;
|
||||
}
|
||||
});
|
||||
final NumberDetails numberDetails =
|
||||
new NumberDetails(recentlyDeletedAci.isPresent(), number, pni, pniIdentityKey);
|
||||
final List<TransactWriteItem> additionalWriteItems = new ArrayList<>(keysWriteItems(aci, Optional.of(pni), primaryDeviceSpec));
|
||||
accountAttributes.recoveryPassword()
|
||||
.map(phoneNumberRecoveryPassword ->
|
||||
phoneNumberRecoveryPasswordsManager.buildTransactWriteItemForStorePassword(pni, phoneNumberRecoveryPassword))
|
||||
.ifPresent(additionalWriteItems::add);
|
||||
|
||||
return create(aci, numberDetails, accountAttributes, aciIdentityKey, primaryDeviceSpec, additionalWriteItems, userAgent);
|
||||
} catch (final ReceiptAlreadyRedeemedException | AccountCreationConditionException e) {
|
||||
throw new IllegalStateException("unexpected exception for account with a number", e);
|
||||
}
|
||||
});
|
||||
} catch (final RuntimeException e) {
|
||||
logger.error("Unexpected exception while creating account", e);
|
||||
throw e;
|
||||
} finally {
|
||||
sample.stop(Metrics.timer(CREATE_TIMER_NAME, HAS_NUMBER_TAG_NAME, "true"));
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
|
||||
private Account create(final Optional<String> maybeNumber,
|
||||
final Optional<UUID> maybePni,
|
||||
final Optional<ReceiptCredentialPresentation> maybeReceiptCredentialPresentation,
|
||||
final Optional<byte[]> maybeAuthCredentialSalt,
|
||||
/// Create a sandbox account without a phone number. Sandbox accounts use an account identifier claimed from the
|
||||
/// [SandboxAccounts] pool.
|
||||
///
|
||||
/// @param accountAttributes the account-level attributes to set on the account
|
||||
/// @param aciIdentityKey the ACI identity key to associate with the account
|
||||
/// @param primaryDeviceSpec the attributes to set on the account's primary device
|
||||
/// @param numberlessDetails details specific to account-creation without a number
|
||||
/// @param userAgent the user agent of the client requesting to create an account
|
||||
/// @return the created account
|
||||
private Account createSandboxAccount(
|
||||
final AccountAttributes accountAttributes,
|
||||
final IdentityKey aciIdentityKey,
|
||||
final Optional<IdentityKey> maybePniIdentityKey,
|
||||
final DeviceSpec primaryDeviceSpec,
|
||||
final NumberlessDetails numberlessDetails,
|
||||
@Nullable final String userAgent) throws ReceiptAlreadyRedeemedException {
|
||||
final List<UUID> candidates = new ArrayList<>(sandboxAccounts.getAvailable());
|
||||
Collections.shuffle(candidates);
|
||||
|
||||
assert maybeNumber.isPresent() ^ maybeReceiptCredentialPresentation.isPresent();
|
||||
for (final UUID candidate : candidates) {
|
||||
final List<TransactWriteItem> additionalWriteItems = new ArrayList<>();
|
||||
final int sandboxClaimIndex = additionalWriteItems.size();
|
||||
additionalWriteItems.add(sandboxAccounts.buildClaimWriteItem(candidate, clock.instant()));
|
||||
additionalWriteItems.addAll(keysWriteItems(candidate, Optional.empty(), primaryDeviceSpec));
|
||||
try {
|
||||
return create(candidate, numberlessDetails, accountAttributes, aciIdentityKey, primaryDeviceSpec,
|
||||
additionalWriteItems, userAgent);
|
||||
} catch (final AccountCreationConditionException e) {
|
||||
// If our sandbox claim failed, another registration claimed this identifier after we listed the available
|
||||
// identifiers so we can just try the next one. Otherwise, this is an unexpected condition failure.
|
||||
if (e.getIndex() != sandboxClaimIndex) {
|
||||
throw new IllegalStateException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Metrics.counter(SANDBOX_POOL_EXHAUSTED_COUNTER_NAME).increment();
|
||||
throw new ReceiptAlreadyRedeemedException();
|
||||
}
|
||||
|
||||
private Account create(
|
||||
final UUID aci,
|
||||
final CreationDetails creationDetails,
|
||||
final AccountAttributes accountAttributes,
|
||||
final IdentityKey aciIdentityKey,
|
||||
final DeviceSpec primaryDeviceSpec,
|
||||
final List<TransactWriteItem> additionalWriteItems,
|
||||
@Nullable final String userAgent) throws ReceiptAlreadyRedeemedException, AccountCreationConditionException {
|
||||
|
||||
final Account account = new Account();
|
||||
final Optional<UUID> maybeRecentlyDeletedAccountIdentifier =
|
||||
maybePni.flatMap(accounts::findRecentlyDeletedAccountIdentifier);
|
||||
|
||||
maybeNumber.ifPresent(number -> {
|
||||
account.setNumber(number, maybePni.orElseThrow(() -> new IllegalArgumentException("PNI must be provided if the account has a number")));
|
||||
account.setPhoneNumberIdentityKey(maybePniIdentityKey.orElseThrow(() -> new IllegalArgumentException("PNI identity key must be provided if the account has a number")));
|
||||
account.setRegistrationLockFromAttributes(accountAttributes);
|
||||
});
|
||||
|
||||
maybeAuthCredentialSalt.ifPresent(account::setAuthCredentialSalt);
|
||||
|
||||
// Reuse the ACI from any recently-deleted account with this number to cover cases where somebody is
|
||||
// re-registering.
|
||||
account.setAccountIdentifier(maybeRecentlyDeletedAccountIdentifier.orElseGet(UUID::randomUUID));
|
||||
account.setAccountIdentifier(aci);
|
||||
account.setIdentityKey(aciIdentityKey);
|
||||
account.addDevice(primaryDeviceSpec.toDevice(Device.PRIMARY_ID, clock, aciIdentityKey));
|
||||
account.setUnidentifiedAccessKey(accountAttributes.getUnidentifiedAccessKey());
|
||||
@@ -478,48 +544,43 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
|
||||
accountAttributes.recoveryPassword().ifPresent(account::setAccountRecoveryPassword);
|
||||
|
||||
AccountCreationType accountCreationType = maybeRecentlyDeletedAccountIdentifier.isPresent()
|
||||
? AccountCreationType.RECENTLY_DELETED
|
||||
: AccountCreationType.NEW;
|
||||
|
||||
final PushTokenType pushTokenType = PushTokenType.fromDeviceSpec(primaryDeviceSpec);
|
||||
|
||||
@Nullable PushTokenType previousPushTokenType = null;
|
||||
|
||||
AccountCreationType accountCreationType;
|
||||
|
||||
try {
|
||||
final List<TransactWriteItem> additionalWriteItems = new ArrayList<>(keysManager.buildWriteItemsForNewDevice(account.getAccountIdentifier(),
|
||||
account.getPhoneNumberIdentifier(),
|
||||
Device.PRIMARY_ID,
|
||||
primaryDeviceSpec.aciInfo().signedPreKey(),
|
||||
primaryDeviceSpec.pniInfo().map(DeviceIdentityInfo::signedPreKey),
|
||||
primaryDeviceSpec.aciInfo().pqLastResortPreKey(),
|
||||
primaryDeviceSpec.pniInfo().map(DeviceIdentityInfo::pqLastResortPreKey)));
|
||||
|
||||
maybePni.ifPresent(phoneNumberIdentifier ->
|
||||
accountAttributes.recoveryPassword().ifPresent(phoneNumberRecoveryPassword ->
|
||||
additionalWriteItems.add(phoneNumberRecoveryPasswordsManager.buildTransactWriteItemForStorePassword(phoneNumberIdentifier, phoneNumberRecoveryPassword))));
|
||||
|
||||
if (maybeNumber.isPresent()) {
|
||||
if (maybeRecentlyDeletedAccountIdentifier.isPresent()) {
|
||||
// If we are re-using a recently deleted ACI, also obtain a lock for it so that clearing queues for the ACI synchronize against it
|
||||
accountLockManager.withLock(Set.of(maybeRecentlyDeletedAccountIdentifier.get()), () -> {
|
||||
switch (creationDetails) {
|
||||
case NumberDetails numbered -> {
|
||||
account.setNumber(numbered.e164(), numbered.pni());
|
||||
account.setPhoneNumberIdentityKey(numbered.pniIdentityKey());
|
||||
account.setRegistrationLockFromAttributes(accountAttributes);
|
||||
if (numbered.recentlyDeleted()) {
|
||||
accountCreationType = AccountCreationType.RECENTLY_DELETED;
|
||||
// If we are re-using a recently deleted ACI, also obtain a lock for it so that clearing queues for the ACI synchronize against it
|
||||
accountLockManager.withLock(Set.of(aci), () -> {
|
||||
accounts.create(account, additionalWriteItems);
|
||||
return null;
|
||||
});
|
||||
} else {
|
||||
accountCreationType = AccountCreationType.NEW;
|
||||
accounts.create(account, additionalWriteItems);
|
||||
return null;
|
||||
});
|
||||
} else {
|
||||
accounts.create(account, additionalWriteItems);
|
||||
}
|
||||
}
|
||||
case NumberlessDetails numberless -> {
|
||||
accountCreationType = AccountCreationType.NEW;
|
||||
account.setAuthCredentialSalt(numberless.authCredentialSalt());
|
||||
assert accountAttributes.recoveryPassword().isPresent();
|
||||
accounts.create(account,
|
||||
numberless.receiptCredentialPresentation(),
|
||||
accountAttributes.recoveryPassword().get(),
|
||||
additionalWriteItems);
|
||||
}
|
||||
} else {
|
||||
assert accountAttributes.recoveryPassword().isPresent();
|
||||
accounts.create(account,
|
||||
maybeReceiptCredentialPresentation.get(),
|
||||
accountAttributes.recoveryPassword().get(),
|
||||
additionalWriteItems);
|
||||
}
|
||||
} catch (final AccountAlreadyExistsException e) {
|
||||
accountCreationType = AccountCreationType.RE_REGISTRATION;
|
||||
previousPushTokenType = PushTokenType.fromDevice(e.getExistingAccount().getPrimaryDevice());
|
||||
|
||||
reclaimAccount(account, e.getExistingAccount(), primaryDeviceSpec, accountAttributes);
|
||||
}
|
||||
|
||||
@@ -533,6 +594,16 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
return account;
|
||||
}
|
||||
|
||||
private List<TransactWriteItem> keysWriteItems(final UUID aci, final Optional<UUID> pni, final DeviceSpec primaryDeviceSpec) {
|
||||
return keysManager.buildWriteItemsForNewDevice(aci,
|
||||
pni,
|
||||
Device.PRIMARY_ID,
|
||||
primaryDeviceSpec.aciInfo().signedPreKey(),
|
||||
primaryDeviceSpec.pniInfo().map(DeviceIdentityInfo::signedPreKey),
|
||||
primaryDeviceSpec.aciInfo().pqLastResortPreKey(),
|
||||
primaryDeviceSpec.pniInfo().map(DeviceIdentityInfo::pqLastResortPreKey));
|
||||
}
|
||||
|
||||
/// Recovers (re-registers) an account with a specific identifier. Callers are responsible for checking that the end
|
||||
/// user has permission to recover the account (i.e. via an account recovery password).
|
||||
///
|
||||
@@ -574,11 +645,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
if (maybePniIdentityKey.isPresent()) {
|
||||
throw new IllegalArgumentException("PNI identity key must not be provided if existing account does not have a phone number");
|
||||
}
|
||||
|
||||
final byte[] authCredentialSalt = new byte[AUTH_CREDENTIAL_SALT_SIZE];
|
||||
SECURE_RANDOM.nextBytes(authCredentialSalt);
|
||||
|
||||
account.setAuthCredentialSalt(authCredentialSalt);
|
||||
account.setAuthCredentialSalt(generateAuthCredentialSalt());
|
||||
}
|
||||
|
||||
account.setIdentityKey(aciIdentityKey);
|
||||
@@ -673,7 +740,8 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
Tags tags = Tags.of(UserAgentTagUtil.getPlatformTag(userAgent),
|
||||
Tag.of("type", accountCreationType.getTagValue()),
|
||||
Tag.of("pushTokenType", pushTokenType.getTagValue()),
|
||||
Tag.of("hasRecoveryPassword", String.valueOf(hasRecoveryPassword)));
|
||||
Tag.of("hasRecoveryPassword", String.valueOf(hasRecoveryPassword)),
|
||||
Tag.of("fictitiousNumber", String.valueOf(account.getNumber().map(Util::isFictitiousNumber).orElse(false))));
|
||||
|
||||
if (previousPushTokenType != null) {
|
||||
tags = tags.and(Tag.of("previousPushTokenType", previousPushTokenType.getTagValue()));
|
||||
@@ -683,20 +751,31 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
}
|
||||
|
||||
public Pair<Account, Device> addDevice(final UUID accountIdentifier, final DeviceSpec deviceSpec, final String linkDeviceToken)
|
||||
throws LinkDeviceTokenAlreadyUsedException {
|
||||
throws LinkDeviceTokenAlreadyUsedException, DeviceLimitExceededException {
|
||||
|
||||
final Account account = accounts.getByAccountIdentifier(accountIdentifier)
|
||||
.orElseThrow(() -> new IllegalArgumentException("Account not found: " + accountIdentifier));
|
||||
|
||||
return accountLockManager.withSingleAccountLock(account,
|
||||
() -> addDevice(accountIdentifier, deviceSpec, linkDeviceToken, MAX_UPDATE_ATTEMPTS));
|
||||
try {
|
||||
return accountLockManager.withSingleAccountLock(account,
|
||||
() -> addDevice(accountIdentifier, deviceSpec, linkDeviceToken, MAX_UPDATE_ATTEMPTS));
|
||||
} catch (final LinkDeviceTokenAlreadyUsedException | DeviceLimitExceededException | RuntimeException e) {
|
||||
throw e;
|
||||
} catch (final Exception e) {
|
||||
throw new AssertionError("Unexpected exception adding device", e);
|
||||
}
|
||||
}
|
||||
|
||||
private Pair<Account, Device> addDevice(final UUID accountIdentifier, final DeviceSpec deviceSpec, final String linkDeviceToken, final int retries)
|
||||
throws LinkDeviceTokenAlreadyUsedException {
|
||||
throws LinkDeviceTokenAlreadyUsedException, DeviceLimitExceededException {
|
||||
|
||||
final Account account = accounts.getByAccountIdentifier(accountIdentifier)
|
||||
.orElseThrow(ContestedOptimisticLockException::new);
|
||||
|
||||
if (account.getDevices().size() >= MAX_DEVICES) {
|
||||
throw new DeviceLimitExceededException(account.getDevices().size(), MAX_DEVICES);
|
||||
}
|
||||
|
||||
final byte nextDeviceId = account.getNextDeviceId();
|
||||
|
||||
CompletableFuture
|
||||
@@ -739,7 +818,9 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
connection.async().set(key, deviceInfoJson, SetArgs.Builder.ex(RECENTLY_ADDED_DEVICE_TTL))))
|
||||
.whenComplete((_, pubSubThrowable) -> {
|
||||
if (pubSubThrowable != null) {
|
||||
logger.warn("Failed to record recently-created device", pubSubThrowable);
|
||||
if (!ExceptionUtils.isBreakerOpen(pubSubThrowable)) {
|
||||
logger.warn("Failed to record recently-created device", pubSubThrowable);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -789,8 +870,13 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
}
|
||||
}
|
||||
|
||||
public String generateLinkDeviceToken(final UUID aci) {
|
||||
final String claims = aci + "." + clock.instant().toEpochMilli();
|
||||
public String generateLinkDeviceToken(final Account account) throws DeviceLimitExceededException {
|
||||
|
||||
if (account.getDevices().size() >= MAX_DEVICES) {
|
||||
throw new DeviceLimitExceededException(account.getDevices().size(), MAX_DEVICES);
|
||||
}
|
||||
|
||||
final String claims = account.getAccountIdentifier() + "." + clock.instant().toEpochMilli();
|
||||
final byte[] signature = getInitializedMac().doFinal(claims.getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
return claims + ":" + Base64.getUrlEncoder().encodeToString(signature);
|
||||
@@ -826,15 +912,20 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
final byte[] expectedSignature = getInitializedMac().doFinal(claimsAndSignature[0].getBytes(StandardCharsets.UTF_8));
|
||||
final byte[] providedSignature;
|
||||
|
||||
try {
|
||||
providedSignature = Base64.getUrlDecoder().decode(claimsAndSignature[1]);
|
||||
|
||||
if (!isCanonicallyBase64UrlEncoded(claimsAndSignature[1], providedSignature)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
} catch (final IllegalArgumentException e) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
final byte[] expectedSignature = getInitializedMac().doFinal(claimsAndSignature[0].getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
if (!MessageDigest.isEqual(expectedSignature, providedSignature)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
@@ -870,6 +961,11 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
return Optional.of(aci);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static boolean isCanonicallyBase64UrlEncoded(final String encoded, final byte[] bytes) {
|
||||
return Base64.getUrlEncoder().encodeToString(bytes).equals(encoded);
|
||||
}
|
||||
|
||||
/**
|
||||
* Unlink a device from the given account. The device will be immediately disconnected if it is connected to any chat
|
||||
* frontend.
|
||||
@@ -1252,7 +1348,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
});
|
||||
|
||||
if (!maybeUpdatedAccount.getCurrentProfileVersion().map(v -> Arrays.equals(v, newVersion)).orElse(false)) {
|
||||
throw new WriteConflictException();
|
||||
throw new WriteConflictException(maybeUpdatedAccount.getCurrentProfileVersion().orElse(null));
|
||||
}
|
||||
|
||||
return maybeUpdatedAccount;
|
||||
@@ -1471,7 +1567,9 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
DELETION_REASON_TAG_NAME, deletionReason.tagValue)
|
||||
.increment();
|
||||
} catch (final RuntimeException e) {
|
||||
logger.warn("Failed to delete account", e);
|
||||
if (!ExceptionUtils.isBreakerOpen(e)) {
|
||||
logger.warn("Failed to delete account", e);
|
||||
}
|
||||
throw e;
|
||||
} finally {
|
||||
sample.stop(deleteTimer);
|
||||
@@ -1564,7 +1662,9 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
try {
|
||||
account.ifPresent(this::redisSet);
|
||||
} catch (RedisException e) {
|
||||
logger.warn("Failed to cache retrieved account", e);
|
||||
if (!ExceptionUtils.isBreakerOpen(e)) {
|
||||
logger.warn("Failed to cache retrieved account", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
return account;
|
||||
@@ -1585,7 +1685,9 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
.thenCompose(maybeAccountFromAccounts -> maybeAccountFromAccounts
|
||||
.map(account -> redisSetAsync(account)
|
||||
.exceptionally(ExceptionUtils.exceptionallyHandler(RedisException.class, e -> {
|
||||
logger.warn("Failed to cache retrieved account", e);
|
||||
if (!ExceptionUtils.isBreakerOpen(e)) {
|
||||
logger.warn("Failed to cache retrieved account", e);
|
||||
}
|
||||
return null;
|
||||
}))
|
||||
.thenApply(ignored -> maybeAccountFromAccounts))
|
||||
@@ -1603,7 +1705,9 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
logger.warn("Deserialization error", e);
|
||||
return Optional.empty();
|
||||
} catch (RedisException e) {
|
||||
logger.warn("Failed fetching account from cache by secondary key", e);
|
||||
if (!ExceptionUtils.isBreakerOpen(e)) {
|
||||
logger.warn("Failed fetching account from cache by secondary key", e);
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
});
|
||||
@@ -1621,7 +1725,9 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
}
|
||||
})
|
||||
.exceptionally(throwable -> {
|
||||
logger.warn("Failed to retrieve account from Redis", throwable);
|
||||
if (!ExceptionUtils.isBreakerOpen(throwable)) {
|
||||
logger.warn("Failed to retrieve account from Redis", throwable);
|
||||
}
|
||||
return Optional.empty();
|
||||
})
|
||||
.whenComplete((_, _) -> sample.stop(timer))
|
||||
@@ -1635,7 +1741,9 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
|
||||
return parseAccountJson(json, uuid);
|
||||
} catch (final RedisException e) {
|
||||
logger.warn("Failed to retrieve account from cache", e);
|
||||
if (!ExceptionUtils.isBreakerOpen(e)) {
|
||||
logger.warn("Failed to retrieve account from cache", e);
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
});
|
||||
@@ -1645,7 +1753,9 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
return cacheCluster.withCluster(connection -> connection.async().get(getAccountEntityKey(uuid)))
|
||||
.thenApply(accountJson -> parseAccountJson(accountJson, uuid))
|
||||
.exceptionally(throwable -> {
|
||||
logger.warn("Failed to retrieve account from Redis", throwable);
|
||||
if (!ExceptionUtils.isBreakerOpen(throwable)) {
|
||||
logger.warn("Failed to retrieve account from Redis", throwable);
|
||||
}
|
||||
return Optional.empty();
|
||||
})
|
||||
.toCompletableFuture();
|
||||
@@ -2275,4 +2385,11 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
.map(AnnotatedWebAuthnCredential.class::cast)
|
||||
.toList();
|
||||
}
|
||||
|
||||
private static byte[] generateAuthCredentialSalt() {
|
||||
final byte[] authCredentialSalt = new byte[AUTH_CREDENTIAL_SALT_SIZE];
|
||||
SECURE_RANDOM.nextBytes(authCredentialSalt);
|
||||
return authCredentialSalt;
|
||||
}
|
||||
|
||||
}
|
||||
+3
-3
@@ -1,9 +1,9 @@
|
||||
/*
|
||||
* Copyright 2013-2020 Signal Messenger, LLC
|
||||
* Copyright 2013 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
|
||||
public class DeviceLimitExceededException extends Exception {
|
||||
@@ -13,7 +13,7 @@ public class DeviceLimitExceededException extends Exception {
|
||||
|
||||
public DeviceLimitExceededException(int currentDevices, int maxDevices) {
|
||||
this.currentDevices = currentDevices;
|
||||
this.maxDevices = maxDevices;
|
||||
this.maxDevices = maxDevices;
|
||||
}
|
||||
|
||||
public int getCurrentDevices() {
|
||||
+1
-1
@@ -128,7 +128,7 @@ public class IssuedReceiptsManager {
|
||||
try {
|
||||
dynamoDbClient.updateItem(updateItemRequest);
|
||||
} catch (final ConditionalCheckFailedException _) {
|
||||
throw new WriteConflictException();
|
||||
throw new WriteConflictException(null);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -52,6 +52,7 @@ import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import org.whispersystems.textsecuregcm.util.ResilienceUtil;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
@@ -400,7 +401,11 @@ public class MessagesCache {
|
||||
.subscribe(messageGuids ->
|
||||
remove(destinationUuid, destinationDevice, messageGuids)
|
||||
.thenAccept(removedMessages -> counter.increment(removedMessages.size())),
|
||||
e -> logger.warn("Could not remove stale {} messages from cache", context, e));
|
||||
e -> {
|
||||
if (!ExceptionUtils.isBreakerOpen(e)) {
|
||||
logger.warn("Could not remove stale {} messages from cache", context, e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
@@ -524,7 +529,9 @@ public class MessagesCache {
|
||||
// MRM data) fails after it has been delivered. We return it so that it may be discarded from the queue.
|
||||
result = Mono.just(mrmMessage.toBuilder().setSharedMrmKey(STALE_MRM_KEY).build());
|
||||
} else {
|
||||
logger.warn("Failed to retrieve shared mrm data", throwable);
|
||||
if (!ExceptionUtils.isBreakerOpen(throwable)) {
|
||||
logger.warn("Failed to retrieve shared mrm data", throwable);
|
||||
}
|
||||
// For unexpected errors, return empty. The message will remain in the queue and be retried in the future.
|
||||
result = Mono.empty();
|
||||
}
|
||||
@@ -555,7 +562,9 @@ public class MessagesCache {
|
||||
REMOVE_MRM_RECIPIENT_VIEW_CONCURRENCY)
|
||||
.doOnNext(sharedMrmDataKeyRemovedCounter::increment)
|
||||
.onErrorResume(e -> {
|
||||
logger.warn("Error removing recipient view", e);
|
||||
if (!ExceptionUtils.isBreakerOpen(e)) {
|
||||
logger.warn("Error removing recipient view", e);
|
||||
}
|
||||
return Mono.just(0L);
|
||||
})
|
||||
.then()
|
||||
|
||||
+77
-107
@@ -13,7 +13,7 @@ import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.util.Collections;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
@@ -57,25 +57,13 @@ public class MessagesManager {
|
||||
private static final Counter PERSIST_MESSAGE_BYTES_COUNTER = Metrics.counter(
|
||||
name(MessagesManager.class, "persistMessageBytes"));
|
||||
|
||||
private static final String MAY_HAVE_MESSAGES_COUNTER_NAME =
|
||||
MetricsUtil.name(MessagesManager.class, "mayHaveMessages");
|
||||
|
||||
private static final String PRESENCE_MATCH_COUNTER_NAME =
|
||||
MetricsUtil.name(MessagesManager.class, "presenceMatch");
|
||||
|
||||
private static final String INSERT_FDB_EXCEPTIONS_COUNTER_NAME = name(MessagesManager.class, "insertExceptions");
|
||||
|
||||
@VisibleForTesting
|
||||
static final String MIRROR_INSERTS_EXPERIMENT_NAME = "foundationDbMirrorInserts";
|
||||
|
||||
@VisibleForTesting
|
||||
static final String MIRROR_DELETIONS_EXPERIMENT_NAME = "foundationDbMirrorDeletions";
|
||||
|
||||
@VisibleForTesting
|
||||
static final String MIRROR_READS_EXPERIMENT_NAME = "foundationDbMirrorReads";
|
||||
|
||||
@VisibleForTesting
|
||||
static final String READ_LIVE_MESSAGES_FROM_FOUNDATIONDB_EXPERIMENT_NAME = "foundationDbReadLiveMessages";
|
||||
static final String EXCLUSIVE_FOUNDATIONDB_INSERT_EXPERIMENT_NAME = "foundationDbExclusiveInsert";
|
||||
|
||||
private final MessagesDynamoDb messagesDynamoDb;
|
||||
private final MessagesCache messagesCache;
|
||||
@@ -123,42 +111,51 @@ public class MessagesManager {
|
||||
private CompletableFuture<Map<Byte, Boolean>> insertAsync(final UUID accountIdentifier, final Map<Byte, Envelope> messagesByDeviceId) {
|
||||
final Map<Byte, Boolean> devicePresenceById = new ConcurrentHashMap<>();
|
||||
|
||||
final CompletableFuture<Map<Byte, FoundationDbMessageStore.InsertResult>> foundationDbInsertFuture;
|
||||
// Multi-recipient messages will have both a "shared MRM key" and actual message content; we only need/want the
|
||||
// latter for FoundationDB
|
||||
final Map<Byte, Envelope> minimizedMessagesByDeviceId = messagesByDeviceId.entrySet().stream()
|
||||
.collect(Collectors.toUnmodifiableMap(
|
||||
Map.Entry::getKey,
|
||||
entry -> entry.getValue().toBuilder().clearSharedMrmKey().build()));
|
||||
|
||||
if (experimentEnrollmentManager.isEnrolled(accountIdentifier, MIRROR_INSERTS_EXPERIMENT_NAME)) {
|
||||
// Multi-recipient messages will have both a "shared MRM key" and actual message content; we only need/want the
|
||||
// latter for FoundationDB
|
||||
final Map<Byte, Envelope> minimizedMessagesByDeviceId = messagesByDeviceId.entrySet().stream()
|
||||
.collect(Collectors.toUnmodifiableMap(
|
||||
Map.Entry::getKey,
|
||||
entry -> entry.getValue().toBuilder().clearSharedMrmKey().build()));
|
||||
|
||||
foundationDbInsertFuture =
|
||||
foundationDbMessageStore.insert(new AciServiceIdentifier(accountIdentifier), minimizedMessagesByDeviceId)
|
||||
.exceptionally(e -> {
|
||||
if (ExceptionUtils.unwrap(e) instanceof final FDBException fdbException) {
|
||||
Metrics.counter(INSERT_FDB_EXCEPTIONS_COUNTER_NAME, "code", String.valueOf(fdbException.getCode()))
|
||||
.increment();
|
||||
} else {
|
||||
final CompletableFuture<Map<Byte, FoundationDbMessageStore.InsertResult>> foundationDbInsertFuture =
|
||||
foundationDbMessageStore.insert(new AciServiceIdentifier(accountIdentifier), minimizedMessagesByDeviceId)
|
||||
.exceptionally(e -> {
|
||||
if (ExceptionUtils.unwrap(e) instanceof final FDBException fdbException) {
|
||||
Metrics.counter(INSERT_FDB_EXCEPTIONS_COUNTER_NAME, "code", String.valueOf(fdbException.getCode()))
|
||||
.increment();
|
||||
} else {
|
||||
if (!ExceptionUtils.isBreakerOpen(e)) {
|
||||
logger.warn("Failed to insert {} message(s) for {} into FoundationDB",
|
||||
minimizedMessagesByDeviceId.size(),
|
||||
accountIdentifier,
|
||||
e);
|
||||
}
|
||||
}
|
||||
|
||||
throw ExceptionUtils.wrap(e);
|
||||
});
|
||||
} else {
|
||||
foundationDbInsertFuture = CompletableFuture.completedFuture(Collections.emptyMap());
|
||||
}
|
||||
throw ExceptionUtils.wrap(e);
|
||||
});
|
||||
|
||||
return foundationDbInsertFuture.thenCompose(foundationDbInsertResults -> {
|
||||
final boolean useFoundationDbPresence =
|
||||
experimentEnrollmentManager.isEnrolled(accountIdentifier, READ_LIVE_MESSAGES_FROM_FOUNDATIONDB_EXPERIMENT_NAME);
|
||||
foundationDbInsertResults.forEach((deviceId, insertResult) ->
|
||||
devicePresenceById.put(deviceId, insertResult.present()));
|
||||
|
||||
if (useFoundationDbPresence) {
|
||||
foundationDbInsertResults.forEach((deviceId, insertResult) ->
|
||||
devicePresenceById.put(deviceId, insertResult.present()));
|
||||
messagesByDeviceId.forEach((deviceId, message) -> {
|
||||
if (message.hasSourceServiceId()) {
|
||||
final ServiceIdentifier sourceServiceIdentifier =
|
||||
ServiceIdentifier.fromByteString(message.getSourceServiceId());
|
||||
|
||||
if (!accountIdentifier.equals(sourceServiceIdentifier.uuid()) && message.getType() != Envelope.Type.SERVER_DELIVERY_RECEIPT) {
|
||||
foundationDbInsertResults.get(deviceId).messageGuid().ifPresent(messageGuid -> {
|
||||
// Note that this is an asynchronous, best-effort, fire-and-forget operation
|
||||
reportMessageManager.store(sourceServiceIdentifier.toServiceIdentifierString(), messageGuid);
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (experimentEnrollmentManager.isEnrolled(accountIdentifier, EXCLUSIVE_FOUNDATIONDB_INSERT_EXPERIMENT_NAME)) {
|
||||
return CompletableFuture.completedFuture(null);
|
||||
}
|
||||
|
||||
return CompletableFuture.allOf(messagesByDeviceId.entrySet().stream()
|
||||
@@ -177,20 +174,6 @@ public class MessagesManager {
|
||||
|
||||
return messagesCache.insert(messageGuid, accountIdentifier, deviceId, message)
|
||||
.thenAccept(present -> {
|
||||
if (message.hasSourceServiceId()) {
|
||||
final ServiceIdentifier sourceServiceIdentifier =
|
||||
ServiceIdentifier.fromByteString(message.getSourceServiceId());
|
||||
|
||||
if (!accountIdentifier.equals(sourceServiceIdentifier.uuid())) {
|
||||
// Note that this is an asynchronous, best-effort, fire-and-forget operation
|
||||
reportMessageManager.store(sourceServiceIdentifier.toServiceIdentifierString(), messageGuid);
|
||||
}
|
||||
}
|
||||
|
||||
if (!useFoundationDbPresence) {
|
||||
devicePresenceById.put(deviceId, present);
|
||||
}
|
||||
|
||||
if (foundationDbInsertResults.containsKey(deviceId)) {
|
||||
Metrics.counter(PRESENCE_MATCH_COUNTER_NAME,
|
||||
"match", String.valueOf(present == foundationDbInsertResults.get(deviceId).present()))
|
||||
@@ -230,7 +213,13 @@ public class MessagesManager {
|
||||
|
||||
final long serverTimestamp = clock.millis();
|
||||
|
||||
return insertSharedMultiRecipientMessagePayload(multiRecipientMessage, resolvedRecipients.keySet())
|
||||
// Don't insert shared payloads for recipients enrolled in the "only insert into FoundationDB" experiment
|
||||
final Set<SealedSenderMultiRecipientMessage.Recipient> unenrolledResolvedRecipients = resolvedRecipients.entrySet().stream()
|
||||
.filter(entry -> !experimentEnrollmentManager.isEnrolled(entry.getValue().getAccountIdentifier(), EXCLUSIVE_FOUNDATIONDB_INSERT_EXPERIMENT_NAME))
|
||||
.map(Map.Entry::getKey)
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
return insertSharedMultiRecipientMessagePayload(multiRecipientMessage, unenrolledResolvedRecipients)
|
||||
.thenCompose(maybeSharedMrmKey -> {
|
||||
final Envelope.Builder envelopeBuilder = Envelope.newBuilder()
|
||||
.setType(Envelope.Type.UNIDENTIFIED_SENDER)
|
||||
@@ -274,54 +263,32 @@ public class MessagesManager {
|
||||
}
|
||||
|
||||
public CompletableFuture<Boolean> mayHavePersistedMessages(final UUID destinationUuid, final Device destinationDevice) {
|
||||
return messagesDynamoDb.mayHaveMessages(destinationUuid, destinationDevice);
|
||||
return foundationDbMessageStore.hasMessages(new AciServiceIdentifier(destinationUuid), destinationDevice.getId())
|
||||
.thenCombine(messagesDynamoDb.mayHaveMessages(destinationUuid, destinationDevice), (a, b) -> a || b);
|
||||
}
|
||||
|
||||
public CompletableFuture<Boolean> mayHaveMessages(final UUID destinationUuid, final Device destinationDevice) {
|
||||
return messagesCache.hasMessagesAsync(destinationUuid, destinationDevice.getId())
|
||||
.thenCombine(messagesDynamoDb.mayHaveMessages(destinationUuid, destinationDevice),
|
||||
(mayHaveCachedMessages, mayHavePersistedMessages) -> {
|
||||
final String outcome;
|
||||
@SuppressWarnings("unchecked") final CompletableFuture<Boolean>[] mayHaveMessagesFutures = new CompletableFuture[] {
|
||||
foundationDbMessageStore.hasMessages(new AciServiceIdentifier(destinationUuid), destinationDevice.getId()),
|
||||
messagesCache.hasMessagesAsync(destinationUuid, destinationDevice.getId()),
|
||||
messagesDynamoDb.mayHaveMessages(destinationUuid, destinationDevice)
|
||||
};
|
||||
|
||||
if (mayHaveCachedMessages && mayHavePersistedMessages) {
|
||||
outcome = "both";
|
||||
} else if (mayHaveCachedMessages) {
|
||||
outcome = "cached";
|
||||
} else if (mayHavePersistedMessages) {
|
||||
outcome = "persisted";
|
||||
} else {
|
||||
outcome = "none";
|
||||
}
|
||||
|
||||
Metrics.counter(MAY_HAVE_MESSAGES_COUNTER_NAME, "outcome", outcome).increment();
|
||||
|
||||
return mayHaveCachedMessages || mayHavePersistedMessages;
|
||||
});
|
||||
return CompletableFuture.allOf(mayHaveMessagesFutures)
|
||||
.thenApply(_ -> Arrays.stream(mayHaveMessagesFutures).anyMatch(CompletableFuture::resultNow));
|
||||
}
|
||||
|
||||
public CompletableFuture<Boolean> mayHaveUrgentPersistedMessages(final UUID destinationUuid, final Device destinationDevice) {
|
||||
return messagesDynamoDb.mayHaveUrgentMessages(destinationUuid, destinationDevice);
|
||||
return foundationDbMessageStore.mayHaveUrgentMessages(new AciServiceIdentifier(destinationUuid), destinationDevice.getId())
|
||||
.thenCombine(messagesDynamoDb.mayHaveUrgentMessages(destinationUuid, destinationDevice), (a, b) -> a || b);
|
||||
}
|
||||
|
||||
public MessageStream getMessages(final UUID destinationUuid, final Device destinationDevice) {
|
||||
if (experimentEnrollmentManager.isEnrolled(destinationUuid, READ_LIVE_MESSAGES_FROM_FOUNDATIONDB_EXPERIMENT_NAME)) {
|
||||
return new ConcatenatingMessageStream(
|
||||
new RedisDynamoDbMessageStream(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager,
|
||||
destinationUuid, destinationDevice, true),
|
||||
foundationDbMessageStore.getMessages(new AciServiceIdentifier(destinationUuid), destinationDevice.getId())
|
||||
);
|
||||
}
|
||||
|
||||
final RedisDynamoDbMessageStream redisDynamoDbMessageStream =
|
||||
return new ConcatenatingMessageStream(
|
||||
new RedisDynamoDbMessageStream(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager,
|
||||
destinationUuid, destinationDevice, false);
|
||||
|
||||
return new MirroringMessageStream(
|
||||
redisDynamoDbMessageStream,
|
||||
foundationDbMessageStore.getMessages(new AciServiceIdentifier(destinationUuid), destinationDevice.getId()),
|
||||
experimentEnrollmentManager,
|
||||
destinationUuid,
|
||||
destinationDevice.getId());
|
||||
destinationUuid, destinationDevice, true),
|
||||
foundationDbMessageStore.getMessages(new AciServiceIdentifier(destinationUuid), destinationDevice.getId())
|
||||
);
|
||||
}
|
||||
|
||||
Publisher<Envelope> getMessagesForDevice(final UUID destinationUuid, final Device destinationDevice) {
|
||||
@@ -333,29 +300,29 @@ public class MessagesManager {
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> clear(final UUID destinationUuid) {
|
||||
if (experimentEnrollmentManager.isEnrolled(destinationUuid, MessagesManager.MIRROR_DELETIONS_EXPERIMENT_NAME)) {
|
||||
messageDeletionExecutor.execute(() -> {
|
||||
try {
|
||||
foundationDbMessageStore.clearAll(new AciServiceIdentifier(destinationUuid));
|
||||
} catch (final Exception e) {
|
||||
messageDeletionExecutor.execute(() -> {
|
||||
try {
|
||||
foundationDbMessageStore.clearAll(new AciServiceIdentifier(destinationUuid));
|
||||
} catch (final Exception e) {
|
||||
if (!ExceptionUtils.isBreakerOpen(e)) {
|
||||
logger.warn("Failed to clear messages for {}", destinationUuid, e);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return messagesCache.clear(destinationUuid);
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> clear(final UUID destinationUuid, final byte deviceId) {
|
||||
if (experimentEnrollmentManager.isEnrolled(destinationUuid, MessagesManager.MIRROR_DELETIONS_EXPERIMENT_NAME)) {
|
||||
messageDeletionExecutor.execute(() -> {
|
||||
try {
|
||||
foundationDbMessageStore.clearAll(new AciServiceIdentifier(destinationUuid), deviceId);
|
||||
} catch (final Exception e) {
|
||||
messageDeletionExecutor.execute(() -> {
|
||||
try {
|
||||
foundationDbMessageStore.clearAll(new AciServiceIdentifier(destinationUuid), deviceId);
|
||||
} catch (final Exception e) {
|
||||
if (!ExceptionUtils.isBreakerOpen(e)) {
|
||||
logger.warn("Failed to clear messages for {}:{}", destinationUuid, deviceId, e);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return messagesCache.clear(destinationUuid, deviceId);
|
||||
}
|
||||
@@ -404,7 +371,10 @@ public class MessagesManager {
|
||||
// If there's any message in the persisted layer, return the oldest
|
||||
return Mono.from(messagesDynamoDb.load(destinationUuid, destinationDevice, 1)).map(Envelope::getServerTimestamp)
|
||||
// If not, return the oldest message in the cache
|
||||
.switchIfEmpty(messagesCache.getEarliestUndeliveredTimestamp(destinationUuid, destinationDevice.getId()))
|
||||
.switchIfEmpty(Mono.defer(() -> messagesCache.getEarliestUndeliveredTimestamp(destinationUuid, destinationDevice.getId())))
|
||||
// And if there are none there, then check FoundationDB
|
||||
.switchIfEmpty(Mono.fromFuture(() -> foundationDbMessageStore.getEarliestUndeliveredMessageTimestamp(new AciServiceIdentifier(destinationUuid), destinationDevice.getId()))
|
||||
.mapNotNull(maybeTimestamp -> maybeTimestamp.map(Instant::toEpochMilli).orElse(null)))
|
||||
.map(epochMilli -> Optional.of(Instant.ofEpochMilli(epochMilli)))
|
||||
.switchIfEmpty(Mono.just(Optional.empty()))
|
||||
.toFuture();
|
||||
|
||||
-335
@@ -1,335 +0,0 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import com.apple.foundationdb.FDBException;
|
||||
import com.google.common.hash.HashCode;
|
||||
import com.google.common.hash.Hashing;
|
||||
import com.google.protobuf.CodedOutputStream;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.DistributionSummary;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Flow;
|
||||
import jakarta.annotation.Nullable;
|
||||
import org.reactivestreams.Subscription;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStream;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import reactor.adapter.JdkFlowAdapter;
|
||||
import reactor.core.publisher.BaseSubscriber;
|
||||
import reactor.core.publisher.SignalType;
|
||||
|
||||
/// A temporary message stream that can mirror message acknowledgements (deletion requests) to FoundationDB
|
||||
public class MirroringMessageStream implements MessageStream {
|
||||
|
||||
private final RedisDynamoDbMessageStream redisDynamoDbMessageStream;
|
||||
private final FoundationDbMessageStream foundationDbMessageStream;
|
||||
private final ExperimentEnrollmentManager experimentEnrollmentManager;
|
||||
|
||||
private final AciServiceIdentifier accountIdentifier;
|
||||
private final byte deviceId;
|
||||
|
||||
private static final Counter CONFLICTING_CONSUMER_COUNTER =
|
||||
Metrics.counter(MetricsUtil.name(MirroringMessageStream.class, "conflictingConsumer"));
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(MirroringMessageStream.class);
|
||||
|
||||
private static final Counter MESSAGE_MISMATCHES_COUNTER =
|
||||
Metrics.counter(MetricsUtil.name(MirroringMessageStream.class, "messageMismatches"));
|
||||
|
||||
private static final String STREAM_AGREEMENTS = MetricsUtil.name(MirroringMessageStream.class, "streamAgreements");
|
||||
|
||||
private static final String MISSING_MESSAGES_COUNTER =
|
||||
MetricsUtil.name(MirroringMessageStream.class, "missingMessages");
|
||||
|
||||
private static final DistributionSummary MISSING_MESSAGE_AGE_DISTRIBUTION =
|
||||
DistributionSummary.builder(MetricsUtil.name(MirroringMessageStream.class, "missingMessageAge"))
|
||||
.register(Metrics.globalRegistry);
|
||||
|
||||
private static final int MAX_WINDOW_SIZE = 1024;
|
||||
|
||||
private final Map<UUID, HashCode> redisDynamoMessageWindow = new HashMap<>();
|
||||
private final Map<UUID, HashCode> foundationDbMessageWindow = new HashMap<>();
|
||||
|
||||
private boolean stopAgreementVerification = false;
|
||||
|
||||
@Nullable
|
||||
private Tags agreementFailureTags;
|
||||
|
||||
private final Set<UUID> recentFoundationDbUuids = Collections.newSetFromMap(new LinkedHashMap<>() {
|
||||
@Override
|
||||
protected boolean removeEldestEntry(final Map.Entry<UUID, Boolean> eldest) {
|
||||
return size() > MAX_WINDOW_SIZE;
|
||||
}
|
||||
});
|
||||
|
||||
private final Set<UUID> recentRedisDynamoEphemeralUuids = Collections.newSetFromMap(new LinkedHashMap<>() {
|
||||
@Override
|
||||
protected boolean removeEldestEntry(final Map.Entry<UUID, Boolean> eldest) {
|
||||
return size() > MAX_WINDOW_SIZE;
|
||||
}
|
||||
});
|
||||
|
||||
private enum Stream {
|
||||
REDIS_DYNAMO("redisDynamo"),
|
||||
FOUNDATION_DB("foundationDb");
|
||||
|
||||
private final String name;
|
||||
|
||||
Stream(final String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
||||
|
||||
private final FoundationDbSubscriber subscriber = new FoundationDbSubscriber();
|
||||
|
||||
private class FoundationDbSubscriber extends BaseSubscriber<MessageStreamEntry> {
|
||||
|
||||
public void handleRedisDynamoDbMessageStreamEntry(final MessageStreamEntry messageStreamEntry) {
|
||||
final boolean isMirroredMessage = switch (messageStreamEntry) {
|
||||
case final MessageStreamEntry.Envelope envelopeEntry -> {
|
||||
final boolean isUUIDv8 = UUIDUtil.fromByteString(envelopeEntry.message().getServerGuid()).version() == 8;
|
||||
if (isUUIDv8) {
|
||||
verifyMessageAgreement(envelopeEntry, Stream.REDIS_DYNAMO);
|
||||
}
|
||||
yield isUUIDv8;
|
||||
}
|
||||
|
||||
case MessageStreamEntry.QueueEmpty _ -> true;
|
||||
};
|
||||
|
||||
if (isMirroredMessage) {
|
||||
request(1);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void hookOnSubscribe(final Subscription subscription) {
|
||||
// The base `hookOnSubscribe` requests `Long.MAX_VALUE` elements, and that is something we're explicitly trying
|
||||
// to avoid with this subscriber
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void hookOnError(final Throwable throwable) {
|
||||
switch (ExceptionUtils.unwrap(throwable)) {
|
||||
case ConflictingMessageConsumerException _ -> CONFLICTING_CONSUMER_COUNTER.increment();
|
||||
case FDBException _ -> {
|
||||
// FDBExceptions are already instrumented by metrics, so do nothing
|
||||
}
|
||||
default -> super.hookOnError(throwable);
|
||||
}
|
||||
}
|
||||
|
||||
protected void hookOnNext(final MessageStreamEntry messageStreamEntry) {
|
||||
if (messageStreamEntry instanceof final MessageStreamEntry.Envelope envelope) {
|
||||
verifyMessageAgreement(envelope, Stream.FOUNDATION_DB);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void hookFinally(final SignalType type) {
|
||||
super.hookFinally(type);
|
||||
publishStreamAgreementMetrics();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public MirroringMessageStream(final RedisDynamoDbMessageStream redisDynamoDbMessageStream,
|
||||
final FoundationDbMessageStream foundationDbMessageStream,
|
||||
final ExperimentEnrollmentManager experimentEnrollmentManager,
|
||||
final UUID accountIdentifier,
|
||||
final byte deviceId) {
|
||||
|
||||
this.redisDynamoDbMessageStream = redisDynamoDbMessageStream;
|
||||
this.foundationDbMessageStream = foundationDbMessageStream;
|
||||
this.experimentEnrollmentManager = experimentEnrollmentManager;
|
||||
|
||||
this.accountIdentifier = new AciServiceIdentifier(accountIdentifier);
|
||||
this.deviceId = deviceId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Flow.Publisher<MessageStreamEntry> getMessages() {
|
||||
|
||||
if (experimentEnrollmentManager.isEnrolled(accountIdentifier.uuid(),
|
||||
MessagesManager.MIRROR_READS_EXPERIMENT_NAME)) {
|
||||
JdkFlowAdapter.flowPublisherToFlux(foundationDbMessageStream.getMessages())
|
||||
.subscribe(subscriber);
|
||||
|
||||
return JdkFlowAdapter.publisherToFlowPublisher(
|
||||
JdkFlowAdapter.flowPublisherToFlux(redisDynamoDbMessageStream.getMessages())
|
||||
.doOnNext(subscriber::handleRedisDynamoDbMessageStreamEntry)
|
||||
.doFinally(_ -> {
|
||||
try {
|
||||
subscriber.dispose();
|
||||
} catch (final Exception _) {
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
return redisDynamoDbMessageStream.getMessages();
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Void> acknowledgeMessage(final UUID messageGuid, final long serverTimestamp) {
|
||||
// All messages stored in FoundationDB use version 8 UUIDs; if a message has a version 4 UUID, then it only exists
|
||||
// in Redis/DynamoDB
|
||||
if (messageGuid.version() == 8 &&
|
||||
experimentEnrollmentManager.isEnrolled(accountIdentifier.uuid(),
|
||||
MessagesManager.MIRROR_DELETIONS_EXPERIMENT_NAME)) {
|
||||
|
||||
if (experimentEnrollmentManager.isEnrolled(accountIdentifier.uuid(), MessagesManager.MIRROR_READS_EXPERIMENT_NAME)
|
||||
&&
|
||||
messageNotDeliveredOnFoundationDbStream(messageGuid)) {
|
||||
foundationDbMessageStream.acknowledgeAndGetMessage(messageGuid)
|
||||
.thenAccept(deleteMessage -> {
|
||||
if (deleteMessage.isEmpty()) {
|
||||
handleMissingFoundationDbMessage(messageGuid, serverTimestamp);
|
||||
return;
|
||||
}
|
||||
verifyMessageAgreement(deleteMessage.get(), Stream.FOUNDATION_DB);
|
||||
})
|
||||
.whenComplete((_, throwable) -> {
|
||||
if (throwable != null) {
|
||||
logger.warn("Failed to delete message {}/{}/{} from FoundationDb", accountIdentifier.uuid(), deviceId,
|
||||
messageGuid, throwable);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
foundationDbMessageStream.acknowledgeMessage(messageGuid, serverTimestamp)
|
||||
.whenComplete((_, throwable) -> {
|
||||
if (throwable != null) {
|
||||
logger.warn("Failed to delete message {}/{}/{} from FoundationDb", accountIdentifier.uuid(), deviceId,
|
||||
messageGuid, throwable);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return redisDynamoDbMessageStream.acknowledgeMessage(messageGuid, serverTimestamp);
|
||||
}
|
||||
|
||||
private synchronized void verifyMessageAgreement(final MessageStreamEntry.Envelope envelope,
|
||||
final Stream stream) {
|
||||
|
||||
if (stopAgreementVerification) {
|
||||
return;
|
||||
}
|
||||
|
||||
final UUID messageUUID = UUIDUtil.fromByteString(envelope.message().getServerGuid());
|
||||
|
||||
if (envelope.message().getEphemeral()) {
|
||||
// We don't compare ephemeral messages across streams because the two systems have different ways of handling and
|
||||
// delivering ephemeral messages. However, we track recently seen ephemeral UUIDs on the Redis/Dynamo stream
|
||||
// to answer whether a message missing from FoundationDB was ephemeral or not.
|
||||
if (stream == Stream.REDIS_DYNAMO) {
|
||||
recentRedisDynamoEphemeralUuids.add(messageUUID);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// There could be a race where a FoundationDB message is delivered on the stream right after it was acknowledged,
|
||||
// so we don't want to add it to the window again; check it against a set of recently seen UUIDs before adding.
|
||||
if (Stream.FOUNDATION_DB == stream && !recentFoundationDbUuids.add(messageUUID)) {
|
||||
return;
|
||||
}
|
||||
|
||||
final Map<UUID, HashCode> thisStreamWindow;
|
||||
final Map<UUID, HashCode> otherStreamWindow;
|
||||
if (Stream.REDIS_DYNAMO == stream) {
|
||||
thisStreamWindow = redisDynamoMessageWindow;
|
||||
otherStreamWindow = foundationDbMessageWindow;
|
||||
} else {
|
||||
thisStreamWindow = foundationDbMessageWindow;
|
||||
otherStreamWindow = redisDynamoMessageWindow;
|
||||
}
|
||||
|
||||
final HashCode thisStreamMessageHashCode = hashCode(envelope.message());
|
||||
|
||||
final HashCode otherStreamMessageHashCode = otherStreamWindow.remove(messageUUID);
|
||||
if (otherStreamMessageHashCode != null) {
|
||||
if (!otherStreamMessageHashCode.equals(thisStreamMessageHashCode)) {
|
||||
MESSAGE_MISMATCHES_COUNTER.increment();
|
||||
}
|
||||
} else {
|
||||
thisStreamWindow.put(messageUUID, thisStreamMessageHashCode);
|
||||
if (thisStreamWindow.size() >= MAX_WINDOW_SIZE) {
|
||||
// Stream is way ahead of the other, stop comparing further
|
||||
stopAgreementVerification = true;
|
||||
thisStreamWindow.clear();
|
||||
otherStreamWindow.clear();
|
||||
recentFoundationDbUuids.clear();
|
||||
setAgreementFailure(Tags.of("reason", "overflow", "stream", stream.name));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized boolean messageNotDeliveredOnFoundationDbStream(final UUID messageGuid) {
|
||||
return redisDynamoMessageWindow.containsKey(messageGuid);
|
||||
}
|
||||
|
||||
private synchronized void setAgreementFailure(final Tags tags) {
|
||||
if (agreementFailureTags == null) {
|
||||
agreementFailureTags = tags;
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void publishStreamAgreementMetrics() {
|
||||
|
||||
Tags tags = Tags.of("success", String.valueOf(agreementFailureTags == null));
|
||||
if (agreementFailureTags != null) {
|
||||
tags = tags.and(agreementFailureTags);
|
||||
}
|
||||
|
||||
Metrics.counter(STREAM_AGREEMENTS, tags).increment();
|
||||
}
|
||||
|
||||
private synchronized void handleMissingFoundationDbMessage(final UUID messageGuid, final long serverTimestamp) {
|
||||
final Boolean ephemeral;
|
||||
if (redisDynamoMessageWindow.containsKey(messageGuid)) {
|
||||
// The comparison window always contains non-ephemeral messages since we ignore ephemeral messages for comparison
|
||||
ephemeral = false;
|
||||
} else if (recentRedisDynamoEphemeralUuids.contains(messageGuid)) {
|
||||
ephemeral = true;
|
||||
} else {
|
||||
ephemeral = null;
|
||||
}
|
||||
setAgreementFailure(Tags.of("reason", "missingMessages"));
|
||||
Metrics.counter(MISSING_MESSAGES_COUNTER, "ephemeral", ephemeral == null ? "unknown" : ephemeral.toString())
|
||||
.increment();
|
||||
MISSING_MESSAGE_AGE_DISTRIBUTION.record(System.currentTimeMillis() - serverTimestamp);
|
||||
}
|
||||
|
||||
private static HashCode hashCode(final MessageProtos.Envelope envelope) {
|
||||
final byte[] serialized = new byte[envelope.getSerializedSize()];
|
||||
final CodedOutputStream codedOutputStream = CodedOutputStream.newInstance(serialized);
|
||||
codedOutputStream.useDeterministicSerialization();
|
||||
try {
|
||||
envelope.writeTo(codedOutputStream);
|
||||
codedOutputStream.flush();
|
||||
} catch (final IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
return Hashing.murmur3_128().hashBytes(serialized);
|
||||
}
|
||||
|
||||
}
|
||||
+13
-4
@@ -27,6 +27,7 @@ import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.ResilienceUtil;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
@@ -177,7 +178,9 @@ public class ProfilesManager {
|
||||
try {
|
||||
profile.ifPresent(versionedProfile -> redisSet(uuid, null, versionedProfile));
|
||||
} catch (RedisException e) {
|
||||
logger.warn("Failed to cache retrieved profile", e);
|
||||
if (!ExceptionUtils.isBreakerOpen(e)) {
|
||||
logger.warn("Failed to cache retrieved profile", e);
|
||||
}
|
||||
}
|
||||
|
||||
return profile;
|
||||
@@ -190,7 +193,9 @@ public class ProfilesManager {
|
||||
try {
|
||||
profile.ifPresent(versionedProfile -> redisSet(uuid, versionedProfile, null));
|
||||
} catch (RedisException e) {
|
||||
logger.warn("Failed to cache retrieved profile", e);
|
||||
if (!ExceptionUtils.isBreakerOpen(e)) {
|
||||
logger.warn("Failed to cache retrieved profile", e);
|
||||
}
|
||||
}
|
||||
|
||||
return profile;
|
||||
@@ -239,7 +244,9 @@ public class ProfilesManager {
|
||||
|
||||
return parseProfileJson(json, VersionedProfile.class);
|
||||
} catch (RedisException e) {
|
||||
logger.warn("Redis exception", e);
|
||||
if (!ExceptionUtils.isBreakerOpen(e)) {
|
||||
logger.warn("Redis exception", e);
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
@@ -255,7 +262,9 @@ public class ProfilesManager {
|
||||
|
||||
return parseProfileJson(json, VersionedProfileV1.class);
|
||||
} catch (RedisException e) {
|
||||
logger.warn("Failed to retrieve profile from cache", e);
|
||||
if (!ExceptionUtils.isBreakerOpen(e)) {
|
||||
logger.warn("Failed to retrieve profile from cache", e);
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -162,7 +162,7 @@ public class ProfilesV2 {
|
||||
if (cancellationCode.isPresent()) {
|
||||
// any other conditional check failure is an expected data hash mismatch, which is a write conflict
|
||||
Metrics.counter(WRITE_CONFLICTS_COUNTER_NAME, "code", cancellationCode.get()).increment();
|
||||
throw new WriteConflictException();
|
||||
throw new WriteConflictException(null);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+7
-2
@@ -227,9 +227,14 @@ class RedisDynamoDbMessagePublisher implements MessageAvailabilityListener, Flow
|
||||
|
||||
synchronized void handleMessageAcknowledged() {
|
||||
acknowledgedEntries += 1;
|
||||
assert acknowledgedEntries <= publishedEntries;
|
||||
|
||||
maybeGenerateMessageSource();
|
||||
if (!terminated) {
|
||||
// As a temporary migration measure, we may receive additional acknowledgements after the stream has terminated
|
||||
// (i.e. we're mirroring deletions from FoundationDB)
|
||||
assert acknowledgedEntries <= publishedEntries;
|
||||
|
||||
maybeGenerateMessageSource();
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized boolean maybeSendQueueEmptySignal() {
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import org.whispersystems.textsecuregcm.util.AttributeValues;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
|
||||
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ConditionalCheckFailedException;
|
||||
import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.DeleteItemResponse;
|
||||
import software.amazon.awssdk.services.dynamodb.model.PutItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ReturnValue;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ScanRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem;
|
||||
import software.amazon.awssdk.services.dynamodb.model.Update;
|
||||
import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;
|
||||
|
||||
/// The pool of account identifiers available for short-lived sandbox accounts and whether they are currently in use.
|
||||
public class SandboxAccounts {
|
||||
|
||||
// B: uuid; primary key
|
||||
static final String KEY_ACCOUNT_UUID = "U";
|
||||
// N: registration timestamp in epoch seconds. Only present if there is an active account with this ACI
|
||||
static final String ATTR_REGISTERED_AT = "R";
|
||||
|
||||
private final String tableName;
|
||||
private final DynamoDbClient dynamoDbClient;
|
||||
|
||||
/// @param uuid the sandbox ACI
|
||||
/// @param registeredAt when an account registered with this ACI, or empty if the ACI is available
|
||||
public record SandboxAccountReservation(UUID uuid, Optional<Instant> registeredAt) {}
|
||||
|
||||
public SandboxAccounts(final String tableName, final DynamoDbClient dynamoDbClient) {
|
||||
this.tableName = tableName;
|
||||
this.dynamoDbClient = dynamoDbClient;
|
||||
}
|
||||
|
||||
/// Get sandbox ACIs that no account currently holds
|
||||
public List<UUID> getAvailable() {
|
||||
return dynamoDbClient.scanPaginator(ScanRequest.builder()
|
||||
.tableName(tableName)
|
||||
.filterExpression("attribute_not_exists(#registeredAt)")
|
||||
.expressionAttributeNames(Map.of("#registeredAt", ATTR_REGISTERED_AT))
|
||||
.build())
|
||||
.items()
|
||||
.stream()
|
||||
.map(item -> AttributeValues.getUUID(item, KEY_ACCOUNT_UUID, null))
|
||||
.toList();
|
||||
}
|
||||
|
||||
/// Get every ACI in the pool along with its registration timestamp, if any.
|
||||
public List<SandboxAccountReservation> getAll() {
|
||||
return dynamoDbClient.scanPaginator(ScanRequest.builder().tableName(tableName).build())
|
||||
.items()
|
||||
.stream()
|
||||
.map(item -> new SandboxAccountReservation(
|
||||
AttributeValues.getUUID(item, KEY_ACCOUNT_UUID, null),
|
||||
AttributeValues.get(item, ATTR_REGISTERED_AT)
|
||||
.map(AttributeValue::n)
|
||||
.map(Long::parseLong)
|
||||
.map(Instant::ofEpochSecond)))
|
||||
.toList();
|
||||
}
|
||||
|
||||
/// Build a [TransactWriteItem] that claims a pool ACI for a new account. The transaction fails if the ACI is not in
|
||||
/// the pool or is already claimed.
|
||||
///
|
||||
/// @param uuid the pool ACI to claim
|
||||
/// @param registeredAt the registration time of the new account
|
||||
public TransactWriteItem buildClaimWriteItem(final UUID uuid, final Instant registeredAt) {
|
||||
return TransactWriteItem.builder()
|
||||
.update(Update.builder()
|
||||
.tableName(tableName)
|
||||
.key(Map.of(KEY_ACCOUNT_UUID, AttributeValues.fromUUID(uuid)))
|
||||
.updateExpression("SET #registeredAt = :registeredAt")
|
||||
.conditionExpression("attribute_exists(#uuid) AND attribute_not_exists(#registeredAt)")
|
||||
.expressionAttributeNames(Map.of(
|
||||
"#uuid", KEY_ACCOUNT_UUID,
|
||||
"#registeredAt", ATTR_REGISTERED_AT))
|
||||
.expressionAttributeValues(Map.of(
|
||||
":registeredAt", AttributeValues.fromLong(registeredAt.getEpochSecond())))
|
||||
.build())
|
||||
.build();
|
||||
}
|
||||
|
||||
/// Mark a previously used ACI as available. The corresponding account must be deleted first.
|
||||
///
|
||||
/// @param uuid the ACI to release
|
||||
/// @param expectedRegisteredAt the registration timestamp the caller observed
|
||||
/// @return true if the registration was cleared, or false if the ACI's registration timestamp no longer matches
|
||||
/// `expectedRegisteredAt`
|
||||
public boolean releaseAci(final UUID uuid, final Instant expectedRegisteredAt) {
|
||||
try {
|
||||
dynamoDbClient.updateItem(UpdateItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.key(Map.of(KEY_ACCOUNT_UUID, AttributeValues.fromUUID(uuid)))
|
||||
.updateExpression("REMOVE #registeredAt")
|
||||
.conditionExpression("#registeredAt = :expectedRegisteredAt")
|
||||
.expressionAttributeNames(Map.of("#registeredAt", ATTR_REGISTERED_AT))
|
||||
.expressionAttributeValues(Map.of(
|
||||
":expectedRegisteredAt", AttributeValues.fromLong(expectedRegisteredAt.getEpochSecond())))
|
||||
.build());
|
||||
return true;
|
||||
} catch (final ConditionalCheckFailedException _) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Add an ACI to the pool. Adding an ACI that is already in the pool has no effect.
|
||||
public void add(final UUID uuid) {
|
||||
try {
|
||||
dynamoDbClient.putItem(PutItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.item(Map.of(KEY_ACCOUNT_UUID, AttributeValues.fromUUID(uuid)))
|
||||
.conditionExpression("attribute_not_exists(#uuid)")
|
||||
.expressionAttributeNames(Map.of("#uuid", KEY_ACCOUNT_UUID))
|
||||
.build());
|
||||
} catch (final ConditionalCheckFailedException _) {
|
||||
// Already in the pool
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove an ACI from the pool if no account currently holds it
|
||||
///
|
||||
/// @return true if the ACI was removed, or false if it is currently claimed or did not exist
|
||||
public boolean removeIfAvailable(final UUID uuid) {
|
||||
try {
|
||||
final DeleteItemResponse resp = dynamoDbClient.deleteItem(DeleteItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.key(Map.of(KEY_ACCOUNT_UUID, AttributeValues.fromUUID(uuid)))
|
||||
.conditionExpression("attribute_not_exists(#registeredAt)")
|
||||
.expressionAttributeNames(Map.of("#registeredAt", ATTR_REGISTERED_AT))
|
||||
.returnValues(ReturnValue.ALL_OLD)
|
||||
.build());
|
||||
return resp.hasAttributes();
|
||||
} catch (final ConditionalCheckFailedException _) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
+14
@@ -5,7 +5,21 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
import org.whispersystems.textsecuregcm.util.NoStackTraceException;
|
||||
import java.util.Optional;
|
||||
|
||||
public class WriteConflictException extends NoStackTraceException {
|
||||
|
||||
@Nullable
|
||||
private final byte[] conflictedValue;
|
||||
|
||||
public WriteConflictException(@Nullable final byte[] conflictedValue) {
|
||||
this.conflictedValue = conflictedValue;
|
||||
}
|
||||
|
||||
/// The conflicted key, if available and relevant
|
||||
public Optional<byte[]> getConflictedValue() {
|
||||
return Optional.ofNullable(conflictedValue);
|
||||
}
|
||||
}
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.storage.devicecheck;
|
||||
|
||||
import com.webauthn4j.appattest.DeviceCheckManager;
|
||||
import com.webauthn4j.appattest.data.DCAssertion;
|
||||
import com.webauthn4j.appattest.data.DCAssertionData;
|
||||
import com.webauthn4j.appattest.data.DCAssertionRequest;
|
||||
import com.webauthn4j.converter.AuthenticatorDataConverter;
|
||||
import com.webauthn4j.converter.exception.DataConversionException;
|
||||
import com.webauthn4j.converter.util.ObjectConverter;
|
||||
import com.webauthn4j.data.attestation.authenticator.AuthenticatorData;
|
||||
import com.webauthn4j.data.extension.authenticator.AuthenticationExtensionAuthenticatorOutput;
|
||||
import tools.jackson.core.JacksonException;
|
||||
import java.util.Arrays;
|
||||
|
||||
/// Parses Apple App Attest assertions
|
||||
///
|
||||
/// App Attest assertions since iOS 27 include an extensions map and don't include attested credential data. They
|
||||
/// set the AT flag which indicates data, so a standards-compliant parser barfs because there's an extensions map where
|
||||
/// the AT data should/ be.
|
||||
///
|
||||
/// If Apple fixes their headers or webauthn4j adopts some workaround, this class should be removed
|
||||
///
|
||||
/// [webauthn4j #1497](https://github.com/webauthn4j/webauthn4j/issues/1497)
|
||||
/// [webauthn4j #1518](https://github.com/webauthn4j/webauthn4j/pull/1518)
|
||||
class AppAttestAssertionConverter {
|
||||
|
||||
// https://www.w3.org/TR/webauthn/#sctn-authenticator-data
|
||||
// rpIdHash(32) || flags(1) || signCount(4) || attestedCredentialData(variable) || extensions(variable)
|
||||
private static final int FLAGS_OFFSET = 32;
|
||||
private static final int HEADER_LENGTH = 37;
|
||||
|
||||
// https://www.rfc-editor.org/info/rfc8949/#section-3.1:~:text=the%20CBOR%20Encoding-,3.1%20Major%20Types,-3.2%20Indefinite%20Lengths
|
||||
// CBOR major type 5 (map), covering both definite and indefinite length maps
|
||||
private static final int CBOR_MAJOR_TYPE_MASK = 0xe0;
|
||||
private static final int CBOR_MAP_MAJOR_TYPE = 0xa0;
|
||||
|
||||
private static final ObjectConverter OBJECT_CONVERTER = DeviceCheckManager.createObjectConverter();
|
||||
private static final AuthenticatorDataConverter AUTHENTICATOR_DATA_CONVERTER = new AuthenticatorDataConverter(OBJECT_CONVERTER);
|
||||
|
||||
/// Parse an assertion request that potentially has misconfigured FLAGS. The returned data must still be verified.
|
||||
static DCAssertionData parseAppleAssertion(final DCAssertionRequest request) throws DataConversionException {
|
||||
final DCAssertion assertion = OBJECT_CONVERTER.getCborMapper().readValue(request.getAssertion(), DCAssertion.class);
|
||||
final byte[] authenticatorDataBytes = assertion == null ? null : assertion.getAuthenticatorData();
|
||||
final AuthenticatorData<AuthenticationExtensionAuthenticatorOutput> authenticatorData =
|
||||
authenticatorDataBytes == null ? null : convertAuthenticatorData(authenticatorDataBytes);
|
||||
return new DCAssertionData(request.getKeyId(), authenticatorData, authenticatorDataBytes,
|
||||
request.getClientDataHash(), assertion == null ? null : assertion.getSignature());
|
||||
}
|
||||
|
||||
private static AuthenticatorData<AuthenticationExtensionAuthenticatorOutput> convertAuthenticatorData(final byte[] original) {
|
||||
if (!hasAppleAssertionExtensions(original)) {
|
||||
return AUTHENTICATOR_DATA_CONVERTER.convert(original);
|
||||
}
|
||||
|
||||
final AuthenticatorData<AuthenticationExtensionAuthenticatorOutput> parsed;
|
||||
try {
|
||||
// Create a copy just for parsing and set the flags as Apple should have set them
|
||||
final byte[] modified = Arrays.copyOf(original, original.length);
|
||||
modified[FLAGS_OFFSET] = (byte) ((original[FLAGS_OFFSET] & ~AuthenticatorData.BIT_AT) | AuthenticatorData.BIT_ED);
|
||||
parsed = AUTHENTICATOR_DATA_CONVERTER.convert(modified);
|
||||
} catch (final JacksonException _) {
|
||||
// Jackson error messages can include the (untrusted) extension contents
|
||||
throw new DataConversionException("Invalid App Attest assertion extension data");
|
||||
}
|
||||
|
||||
// Return the parsed structures but keep the original (incorrect) flags, so signature validation works
|
||||
return new AuthenticatorData<>(parsed.getRpIdHash(), original[FLAGS_OFFSET], parsed.getSignCount(),
|
||||
parsed.getExtensions());
|
||||
}
|
||||
|
||||
private static boolean hasAppleAssertionExtensions(final byte[] data) {
|
||||
// If we don't have AT or Extensions at all, webauthn can handle them being incorrectly set without any conversion
|
||||
return data.length > HEADER_LENGTH
|
||||
// If the data correctly sets the AT flag, webauthn can also handle it
|
||||
&& AuthenticatorData.checkFlagAT(data[FLAGS_OFFSET])
|
||||
// If the first byte after the header looks like an extension, this is the special case. Valid assertions
|
||||
// shouldn't have attestedCredentialData anyway, and if it did it should be a CBOR string
|
||||
&& (data[HEADER_LENGTH] & CBOR_MAJOR_TYPE_MASK) == CBOR_MAP_MAJOR_TYPE;
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -204,7 +204,7 @@ public class AppleDeviceCheckManager {
|
||||
new DCAssertionParameters(new DCServerProperty(teamId, bundleId, new DefaultChallenge(request)), appleDevice);
|
||||
|
||||
try {
|
||||
deviceCheckManager.validate(dcAssertionRequest, dcAssertionParameters);
|
||||
deviceCheckManager.validate(AppAttestAssertionConverter.parseAppleAssertion(dcAssertionRequest), dcAssertionParameters);
|
||||
} catch (MaliciousCounterValueException e) {
|
||||
// We will only accept assertions that have a sign count greater than the last assertion we saw. Step 5 here:
|
||||
// https://developer.apple.com/documentation/devicecheck/validating-apps-that-connect-to-your-server#Verify-the-assertion
|
||||
|
||||
+3
@@ -171,6 +171,9 @@ public class FaultTolerantDatabase {
|
||||
READ_STATUS("readStatus"),
|
||||
READ_VERSIONSTAMP("readVersionstamp"),
|
||||
RECORD_VERSIONSTAMP_AND_TIME("recordVersionstampAndTime"),
|
||||
GET_HAS_MESSAGES("hasMessages"),
|
||||
GET_HAS_URGENT_MESSAGES("hasUrgentMessages"),
|
||||
GET_EARLIEST_TIMESTAMP("getEarliestTimestamp"),
|
||||
TEST("test");
|
||||
|
||||
private final String name;
|
||||
|
||||
+11
-2
@@ -417,6 +417,13 @@ class FoundationDbMessagePublisher {
|
||||
// If we're already in a terminal state, we don't want to set a watch that would leak
|
||||
return;
|
||||
}
|
||||
|
||||
if (watchFuture != null && !watchFuture.isDone()) {
|
||||
LOGGER.warn("Setting a watch before previous watch future is done");
|
||||
}
|
||||
|
||||
cancelWatch();
|
||||
|
||||
// Set a watch that will be triggered when new messages arrive. When it is triggered, we attempt to fetch messages
|
||||
// again (if there is demand). When we run out of messages, this method will be called again, setting another watch,
|
||||
// and so on, thus achieving a "watch for new messages -> read -> publish" loop.
|
||||
@@ -451,7 +458,9 @@ class FoundationDbMessagePublisher {
|
||||
final ScheduledFuture<?> scheduledFuture = presenceRenewalExecutorService.schedule(() -> {
|
||||
renewPresence().whenComplete((_, throwable) -> {
|
||||
if (throwable != null) {
|
||||
LOGGER.warn("Failed to renew presence", throwable);
|
||||
if (!ExceptionUtils.isBreakerOpen(throwable)) {
|
||||
LOGGER.warn("Failed to renew presence", throwable);
|
||||
}
|
||||
renewPresenceFuture.completeExceptionally(throwable);
|
||||
} else {
|
||||
renewPresenceFuture.complete(null);
|
||||
@@ -503,7 +512,7 @@ class FoundationDbMessagePublisher {
|
||||
}
|
||||
}), FaultTolerantDatabase.Context.CLEAR_PRESENCE)
|
||||
.whenComplete((_, throwable) -> {
|
||||
if (throwable != null) {
|
||||
if (throwable != null && !ExceptionUtils.isBreakerOpen(throwable)) {
|
||||
LOGGER.warn("Failed to clear presence on disposal", throwable);
|
||||
}
|
||||
}));
|
||||
|
||||
+84
-2
@@ -50,6 +50,7 @@ import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.metrics.DevicePlatformUtil;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
@@ -91,6 +92,9 @@ public class FoundationDbMessageStore {
|
||||
@VisibleForTesting
|
||||
static final Duration PRESENCE_STALE_THRESHOLD = Duration.ofMinutes(5);
|
||||
|
||||
@VisibleForTesting
|
||||
static final int MAY_HAVE_URGENT_MESSAGES_QUERY_LIMIT = 20;
|
||||
|
||||
/// The (approximate) transaction size beyond which we do not add more messages in a transaction. The estimated size
|
||||
/// includes only message payloads (and not key reads/writes) which we assume will dominate the total
|
||||
/// transaction size. Note that the FDB [docs](https://apple.github.io/foundationdb/known-limitations.html) currently
|
||||
@@ -485,6 +489,80 @@ public class FoundationDbMessageStore {
|
||||
clock);
|
||||
}
|
||||
|
||||
/// Checks whether the message queue belonging to a specific device contains any messages.
|
||||
///
|
||||
/// @param aci the account identifier for the queue to check
|
||||
/// @param deviceId the account-specific device identifier for the queue to check
|
||||
///
|
||||
/// @return a future that yields `true` if the identified queue contains any messages or `false` if the queue is empty
|
||||
public CompletableFuture<Boolean> hasMessages(final AciServiceIdentifier aci, final byte deviceId) {
|
||||
return getDistinctDatabasesForAci(aci)
|
||||
.flatMap(database -> Mono.fromFuture(() -> database.readAsync(transaction ->
|
||||
transaction.getRange(getDeviceQueueSubspace(aci, deviceId).range(), 1).asList(),
|
||||
FaultTolerantDatabase.Context.GET_HAS_MESSAGES)))
|
||||
.map(keyValues -> !keyValues.isEmpty())
|
||||
.any(hasMessages -> hasMessages)
|
||||
.toFuture();
|
||||
}
|
||||
|
||||
/// Checks whether the message queue belonging to a specific device contains an urgent message within the first
|
||||
/// {@value MAY_HAVE_URGENT_MESSAGES_QUERY_LIMIT} messages.
|
||||
///
|
||||
/// @param aci the account identifier for the queue to check
|
||||
/// @param deviceId the account-specific device identifier for the queue to check
|
||||
///
|
||||
/// @return a future that yields `true` if the identified queue contains an urgent message within a sample or `false`
|
||||
/// otherwise
|
||||
public CompletableFuture<Boolean> mayHaveUrgentMessages(final AciServiceIdentifier aci, final byte deviceId) {
|
||||
return getDistinctDatabasesForAci(aci)
|
||||
.flatMap(database -> Mono.fromFuture(() -> database.readAsync(transaction ->
|
||||
transaction.getRange(getDeviceQueueSubspace(aci, deviceId).range(), MAY_HAVE_URGENT_MESSAGES_QUERY_LIMIT).asList(),
|
||||
FaultTolerantDatabase.Context.GET_HAS_URGENT_MESSAGES))
|
||||
.flatMapMany(keyValues -> Flux.fromIterable(keyValues)
|
||||
.<MessageProtos.Envelope>handle((keyValue, sink) -> {
|
||||
try {
|
||||
sink.next(MessageProtos.Envelope.parseFrom(keyValue.getValue()));
|
||||
} catch (final InvalidProtocolBufferException e) {
|
||||
sink.error(e);
|
||||
}
|
||||
})))
|
||||
.any(MessageProtos.Envelope::getUrgent)
|
||||
.toFuture();
|
||||
}
|
||||
|
||||
/// Gets the server timestamp of the earliest message in the queue for a specific device
|
||||
///
|
||||
/// @param aci the account identifier for the queue to check
|
||||
/// @param deviceId the account-specific device identifier for the queue to check
|
||||
///
|
||||
/// @return a future that yields the server timestamp of the earliest message in the queue, or empty if the queue
|
||||
/// contains no messages
|
||||
public CompletableFuture<Optional<Instant>> getEarliestUndeliveredMessageTimestamp(final AciServiceIdentifier aci,
|
||||
final byte deviceId) {
|
||||
|
||||
return getDistinctDatabasesForAci(aci)
|
||||
.flatMap(database -> Mono.fromFuture(() -> database.readAsync(transaction ->
|
||||
transaction.getRange(getDeviceQueueSubspace(aci, deviceId).range(), 1).asList(),
|
||||
FaultTolerantDatabase.Context.GET_EARLIEST_TIMESTAMP))
|
||||
.mapNotNull(keyValues -> {
|
||||
if (keyValues.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
return Instant.ofEpochMilli(MessageProtos.Envelope.parseFrom(keyValues.getFirst().getValue())
|
||||
.getServerTimestamp());
|
||||
} catch (final InvalidProtocolBufferException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
}))
|
||||
.sort()
|
||||
.next()
|
||||
.map(Optional::of)
|
||||
.switchIfEmpty(Mono.just(Optional.empty()))
|
||||
.toFuture();
|
||||
}
|
||||
|
||||
/// Record the versionstamp for the current time in each database's versionstamp clock.
|
||||
public void recordVersionstamps() {
|
||||
for (VersionstampClock versionstampClock : versionstampClocks.values()) {
|
||||
@@ -720,7 +798,9 @@ public class FoundationDbMessageStore {
|
||||
|
||||
return deleteModifier.apply(deleteMono)
|
||||
.onErrorResume(throwable -> {
|
||||
LOGGER.warn("Failed to trim message queue for {}:{}", aci, device.getId(), throwable);
|
||||
if (!ExceptionUtils.isBreakerOpen(throwable)) {
|
||||
LOGGER.warn("Failed to trim message queue for {}:{}", aci, device.getId(), throwable);
|
||||
}
|
||||
return Mono.just(false);
|
||||
});
|
||||
})
|
||||
@@ -731,7 +811,9 @@ public class FoundationDbMessageStore {
|
||||
.onErrorResume(throwable -> {
|
||||
// If we error out on estimating queue size, we don't know if this queue needed trimming
|
||||
Metrics.counter(TRIM_QUEUE_COUNTER_NAME, "success", "false").increment();
|
||||
LOGGER.warn("Failed to estimate queue size for {}:{}", aci, device.getId(), throwable);
|
||||
if (!ExceptionUtils.isBreakerOpen(throwable)) {
|
||||
LOGGER.warn("Failed to estimate queue size for {}:{}", aci, device.getId(), throwable);
|
||||
}
|
||||
return Mono.empty();
|
||||
});
|
||||
}
|
||||
|
||||
+4
-1
@@ -24,6 +24,7 @@ import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.storage.MessageStream;
|
||||
import org.whispersystems.textsecuregcm.storage.MessageStreamEntry;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import reactor.adapter.JdkFlowAdapter;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
@@ -215,7 +216,9 @@ public class FoundationDbMessageStream implements MessageStream {
|
||||
})
|
||||
.whenComplete((_, throwable) -> {
|
||||
if (throwable != null) {
|
||||
logger.warn("Failed to fetch end-of-queue key", throwable);
|
||||
if (!ExceptionUtils.isBreakerOpen(throwable)) {
|
||||
logger.warn("Failed to fetch end-of-queue key", throwable);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
+9
-4
@@ -9,6 +9,9 @@ import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.i18n.phonenumbers.Phonenumber;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpRequest;
|
||||
@@ -19,15 +22,13 @@ import java.util.Optional;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import javax.annotation.Nullable;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.whispersystems.textsecuregcm.http.FaultTolerantHttpClient;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.telephony.CarrierData;
|
||||
import org.whispersystems.textsecuregcm.telephony.CarrierDataException;
|
||||
import org.whispersystems.textsecuregcm.telephony.CarrierDataProvider;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
|
||||
/// A carrier data provider that uses [HLR Lookup](https://www.hlrlookup.com/) as its data source.
|
||||
@@ -117,10 +118,14 @@ public class HlrLookupCarrierDataProvider implements CarrierDataProvider {
|
||||
|
||||
Metrics.counter(REQUEST_COUNTER_NAME, "status", String.valueOf(httpResponse.statusCode()))
|
||||
.increment();
|
||||
} catch (final IOException | CarrierDataException e) {
|
||||
} catch (final IOException | CarrierDataException | RuntimeException e) {
|
||||
Metrics.counter(REQUEST_COUNTER_NAME, "exception", e.getClass().getSimpleName())
|
||||
.increment();
|
||||
|
||||
if (ExceptionUtils.isBreakerOpen(e)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
throw e;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
package org.whispersystems.textsecuregcm.util;
|
||||
|
||||
import io.github.resilience4j.circuitbreaker.CallNotPermittedException;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
public final class ExceptionUtils {
|
||||
|
||||
@@ -127,4 +129,19 @@ public final class ExceptionUtils {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks whether an exception in the chain is a [CallNotPermittedException].
|
||||
///
|
||||
/// This is useful to check when logging, to avoid repetitive output.
|
||||
public static boolean isBreakerOpen(@Nullable Throwable t) {
|
||||
if (t == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
while (!(t instanceof CallNotPermittedException) && t.getCause() != null) {
|
||||
t = t.getCause();
|
||||
}
|
||||
|
||||
return t instanceof CallNotPermittedException;
|
||||
}
|
||||
}
|
||||
@@ -57,6 +57,10 @@ public class InetAddressRange {
|
||||
}
|
||||
|
||||
public boolean contains(final String name) {
|
||||
if (name == null) {
|
||||
throw new IllegalArgumentException(new NullPointerException("Name must not be null"));
|
||||
}
|
||||
|
||||
// InetAddresses.forString() throws "IllegalArgumentException" for anything that is not an IP address
|
||||
return contains(InetAddresses.forString(name));
|
||||
}
|
||||
|
||||
@@ -24,6 +24,7 @@ import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.Function;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
@@ -37,6 +38,20 @@ public class Util {
|
||||
public static final String COUNTRY_CODE_NOT_APPLICABLE = "n/a";
|
||||
public static final String REGION_NOT_APPLICABLE = "n/a";
|
||||
|
||||
// Keep in sync with registration-service's FictitiousNumberVerificationCodeSender, which sends verification codes
|
||||
// for these numbers to a datastore instead of an SMS/voice provider; see
|
||||
// https://github.com/signalapp/registration-service/blob/cbace936454c1f5e62590d75eaa42ecd2b54f6ee/src/main/java/org/signal/registration/sender/fictitious/FictitiousNumberVerificationCodeSender.java#L43-L52
|
||||
private static final List<Pattern> FICTITIOUS_NUMBER_PATTERNS = List.of(
|
||||
// NANPA fictitious numbers
|
||||
Pattern.compile("\\+1[0-9]{3}55501[0-9]{2}"),
|
||||
|
||||
// UK "numbers for drama"
|
||||
Pattern.compile("\\+447700900[0-9]{3}"),
|
||||
|
||||
// French numbers "for use in audiovisual productions"
|
||||
Pattern.compile("\\+3363998[0-9]{4}")
|
||||
);
|
||||
|
||||
// We use a `HashMap` because `HashMap` allows for null keys at query time, and `PhoneNumberUtil` may return a null
|
||||
// region code for some phone numbers
|
||||
private static final Map<String, AlternatePhoneNumberFormGenerator> ALTERNATE_FORM_GENERATORS_BY_REGION =
|
||||
@@ -226,6 +241,13 @@ public class Util {
|
||||
PHONE_NUMBER_UTIL.getNationalSignificantNumber(phoneNumber).length() == 8;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return whether the E164-formatted {@code number} is in a range that registration-service treats as fictitious
|
||||
*/
|
||||
public static boolean isFictitiousNumber(final String number) {
|
||||
return FICTITIOUS_NUMBER_PATTERNS.stream().anyMatch(pattern -> pattern.matcher(number).matches());
|
||||
}
|
||||
|
||||
/**
|
||||
* If applicable, return the canonical form of the provided phone number.
|
||||
* This is relevant in cases where a numbering authority has changed the numbering format for a region.
|
||||
|
||||
Loaded 100 of 183 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user