mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-12-01 06:16:47 +00:00
Compare commits
59
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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
|
||||
@@ -235,18 +235,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 +436,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 +523,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 +572,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 +581,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);
|
||||
|
||||
|
||||
@@ -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;
|
||||
@@ -287,6 +289,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 +345,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 +402,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 +830,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 +1153,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 +1179,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 +1203,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 +1295,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(redisMessageAvailabilityManager, experimentEnrollmentManager));
|
||||
webSocketEnvironment.jersey().register(new TimestampResponseFilter());
|
||||
|
||||
final PersistentTimer persistentTimer = new PersistentTimer(rateLimitersCluster, clock);
|
||||
@@ -1345,7 +1357,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(redisMessageAvailabilityManager, experimentEnrollmentManager));
|
||||
provisioningEnvironment.jersey().register(new TimestampResponseFilter());
|
||||
|
||||
registerExceptionMappers(environment, webSocketEnvironment, provisioningEnvironment);
|
||||
@@ -1415,6 +1427,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 +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;
|
||||
}
|
||||
}
|
||||
+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
-11
@@ -72,6 +72,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 +89,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;
|
||||
@@ -198,15 +197,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));
|
||||
}
|
||||
@@ -271,10 +266,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) {
|
||||
|
||||
+8
-2
@@ -21,8 +21,10 @@ import java.util.Optional;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesManager;
|
||||
import org.whispersystems.websocket.session.WebSocketSession;
|
||||
import org.whispersystems.websocket.session.WebSocketSessionContext;
|
||||
|
||||
@@ -34,13 +36,16 @@ public class KeepAliveController {
|
||||
private final Logger logger = LoggerFactory.getLogger(KeepAliveController.class);
|
||||
|
||||
private final RedisMessageAvailabilityManager redisMessageAvailabilityManager;
|
||||
private final ExperimentEnrollmentManager experimentEnrollmentManager;
|
||||
|
||||
private static final String CLOSED_CONNECTION_AGE_DISTRIBUTION_NAME = name(KeepAliveController.class,
|
||||
"closedConnectionAge");
|
||||
|
||||
|
||||
public KeepAliveController(final RedisMessageAvailabilityManager redisMessageAvailabilityManager) {
|
||||
public KeepAliveController(final RedisMessageAvailabilityManager redisMessageAvailabilityManager,
|
||||
final ExperimentEnrollmentManager experimentEnrollmentManager) {
|
||||
this.redisMessageAvailabilityManager = redisMessageAvailabilityManager;
|
||||
this.experimentEnrollmentManager = experimentEnrollmentManager;
|
||||
}
|
||||
|
||||
@GET
|
||||
@@ -48,7 +53,8 @@ public class KeepAliveController {
|
||||
@WebSocketSession WebSocketSessionContext context) {
|
||||
|
||||
maybeAuth.ifPresent(auth -> {
|
||||
if (!redisMessageAvailabilityManager.isLocallyPresent(auth.accountIdentifier(), auth.deviceId())) {
|
||||
if (!(experimentEnrollmentManager.isEnrolled(auth.accountIdentifier(), MessagesManager.READ_LIVE_MESSAGES_FROM_FOUNDATIONDB_EXPERIMENT_NAME) ||
|
||||
redisMessageAvailabilityManager.isLocallyPresent(auth.accountIdentifier(), auth.deviceId()))) {
|
||||
|
||||
final Duration age = Duration.between(context.getClient().getCreated(), Instant.now());
|
||||
|
||||
|
||||
+2
-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) {
|
||||
|
||||
+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 {
|
||||
|
||||
+4
-2
@@ -98,6 +98,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;
|
||||
@@ -320,7 +321,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 +368,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");
|
||||
}
|
||||
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
+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;
|
||||
|
||||
+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);
|
||||
}
|
||||
|
||||
+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;
|
||||
}
|
||||
|
||||
+16
-11
@@ -23,7 +23,6 @@ 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;
|
||||
@@ -84,7 +83,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 +96,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) {
|
||||
@@ -195,6 +192,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(() -> {
|
||||
@@ -232,6 +233,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)
|
||||
@@ -245,6 +252,4 @@ public class AppleAppStoreClient {
|
||||
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());
|
||||
}
|
||||
}
|
||||
+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()
|
||||
|
||||
+182
-81
@@ -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
|
||||
@@ -789,8 +868,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 +910,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 +959,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 +1346,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;
|
||||
@@ -2275,4 +2369,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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -74,8 +74,7 @@ public class MessagesManager {
|
||||
@VisibleForTesting
|
||||
static final String MIRROR_READS_EXPERIMENT_NAME = "foundationDbMirrorReads";
|
||||
|
||||
@VisibleForTesting
|
||||
static final String READ_LIVE_MESSAGES_FROM_FOUNDATIONDB_EXPERIMENT_NAME = "foundationDbReadLiveMessages";
|
||||
public static final String READ_LIVE_MESSAGES_FROM_FOUNDATIONDB_EXPERIMENT_NAME = "foundationDbReadLiveMessages";
|
||||
|
||||
private final MessagesDynamoDb messagesDynamoDb;
|
||||
private final MessagesCache messagesCache;
|
||||
@@ -181,7 +180,7 @@ public class MessagesManager {
|
||||
final ServiceIdentifier sourceServiceIdentifier =
|
||||
ServiceIdentifier.fromByteString(message.getSourceServiceId());
|
||||
|
||||
if (!accountIdentifier.equals(sourceServiceIdentifier.uuid())) {
|
||||
if (!accountIdentifier.equals(sourceServiceIdentifier.uuid()) && message.getType() != Envelope.Type.SERVER_DELIVERY_RECEIPT) {
|
||||
// Note that this is an asynchronous, best-effort, fire-and-forget operation
|
||||
reportMessageManager.store(sourceServiceIdentifier.toServiceIdentifierString(), messageGuid);
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
|
||||
-6
@@ -70,7 +70,6 @@ public class WebSocketConnection {
|
||||
"sendMessageError");
|
||||
|
||||
private static final String STATUS_CODE_TAG = "status";
|
||||
private static final String STATUS_MESSAGE_TAG = "message";
|
||||
private static final String ERROR_TYPE_TAG = "errorType";
|
||||
private static final String EXCEPTION_TYPE_TAG = "exceptionType";
|
||||
|
||||
@@ -264,11 +263,6 @@ public class WebSocketConnection {
|
||||
} else {
|
||||
Tags tags = Tags.of(UserAgentTagUtil.getPlatformTag(userAgent), Tag.of(STATUS_CODE_TAG, String.valueOf(response.getStatus())));
|
||||
|
||||
// TODO Remove this once we've identified the cause of message rejections from desktop clients
|
||||
if (StringUtils.isNotBlank(response.getMessage())) {
|
||||
tags = tags.and(Tag.of(STATUS_MESSAGE_TAG, response.getMessage()));
|
||||
}
|
||||
|
||||
Metrics.counter(NON_SUCCESS_RESPONSE_COUNTER_NAME, tags).increment();
|
||||
|
||||
result = CompletableFuture.completedFuture(null);
|
||||
|
||||
-8
@@ -11,10 +11,7 @@ import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.stream.Collectors;
|
||||
import net.sourceforge.argparse4j.inf.Subparser;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesManager;
|
||||
@@ -36,11 +33,6 @@ public class ClearExpiredFoundationDbMessagesCommand extends AbstractSinglePassC
|
||||
@VisibleForTesting
|
||||
static final String VERSIONSTAMP_TTL_DAYS_ARGUMENT = "versionstamp-ttl-days";
|
||||
|
||||
@VisibleForTesting
|
||||
static final Duration TIMESTAMP_RETENTION_PERIOD = Duration.ofDays(60);
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(ClearExpiredFoundationDbMessagesCommand.class);
|
||||
|
||||
public ClearExpiredFoundationDbMessagesCommand(final Clock clock) {
|
||||
super("clear-expired-foundationdb-messages", "Removes expired messages from FoundationDB");
|
||||
|
||||
|
||||
+11
-13
@@ -43,10 +43,12 @@ import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfigurati
|
||||
import org.whispersystems.textsecuregcm.controllers.SecureStorageController;
|
||||
import org.whispersystems.textsecuregcm.controllers.SecureValueRecovery2Controller;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.experiment.PushNotificationExperimentSamples;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.metrics.MicrometerAwsSdkMetricPublisher;
|
||||
import org.whispersystems.textsecuregcm.purchases.AppleAppStoreClient;
|
||||
import org.whispersystems.textsecuregcm.purchases.AppleAppStoreManager;
|
||||
import org.whispersystems.textsecuregcm.purchases.GooglePlayBillingManager;
|
||||
import org.whispersystems.textsecuregcm.push.APNSender;
|
||||
import org.whispersystems.textsecuregcm.push.FcmSender;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
|
||||
@@ -82,6 +84,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;
|
||||
@@ -89,9 +92,6 @@ import org.whispersystems.textsecuregcm.storage.TotpManager;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.FaultTolerantDatabase;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStore;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.VersionstampUUIDCipher;
|
||||
import org.whispersystems.textsecuregcm.purchases.AppleAppStoreClient;
|
||||
import org.whispersystems.textsecuregcm.purchases.AppleAppStoreManager;
|
||||
import org.whispersystems.textsecuregcm.purchases.GooglePlayBillingManager;
|
||||
import org.whispersystems.textsecuregcm.util.ManagedAwsCrt;
|
||||
import org.whispersystems.textsecuregcm.util.ManagedExecutors;
|
||||
import org.whispersystems.textsecuregcm.util.ResilienceUtil;
|
||||
@@ -117,7 +117,6 @@ public record CommandDependencies(
|
||||
APNSender apnSender,
|
||||
FcmSender fcmSender,
|
||||
PushNotificationManager pushNotificationManager,
|
||||
PushNotificationExperimentSamples pushNotificationExperimentSamples,
|
||||
FaultTolerantRedisClusterClient cacheCluster,
|
||||
FaultTolerantRedisClusterClient pushSchedulerCluster,
|
||||
ClientResources.Builder redisClusterClientResourcesBuilder,
|
||||
@@ -132,7 +131,8 @@ public record CommandDependencies(
|
||||
PhoneNumberIdentifiers phoneNumberIdentifiers,
|
||||
DynamoDbRecoveryManager dynamoDbRecoveryManager,
|
||||
FDB fdb,
|
||||
AccountLockManager accountLockManager) {
|
||||
AccountLockManager accountLockManager,
|
||||
SandboxAccounts sandboxAccounts) {
|
||||
|
||||
static CommandDependencies build(
|
||||
final String name,
|
||||
@@ -389,10 +389,12 @@ public record CommandDependencies(
|
||||
configuration.getRegistrationWebAuthnConfiguration().challengeTtl(),
|
||||
configuration.getRegistrationWebAuthnConfiguration().userHandleBlindingSecret().value(),
|
||||
rateLimitersCluster);
|
||||
final SandboxAccounts sandboxAccounts = new SandboxAccounts(
|
||||
configuration.getDynamoDbTables().getSandboxAccounts().getTableName(), dynamoDbClient);
|
||||
AccountsManager accountsManager = new AccountsManager(accounts, phoneNumberIdentifiers, cacheCluster,
|
||||
pubsubClient, accountLockManager, keys, messagesManager, profilesManager,
|
||||
changeNumberWaitingPeriodManager, secureStorageClient, secureValueRecovery2Client, disconnectionRequestManager,
|
||||
phoneNumberRecoveryPasswordsManager, messagePollExecutor,
|
||||
phoneNumberRecoveryPasswordsManager, sandboxAccounts, messagePollExecutor,
|
||||
retryExecutor, clock, configuration.getLinkDeviceSecretConfiguration().secret().value(),
|
||||
webAuthnCeremonyManager, totpManager);
|
||||
RateLimiters rateLimiters = RateLimiters.create(dynamicConfigurationManager, rateLimitersCluster, retryExecutor);
|
||||
@@ -457,10 +459,6 @@ public record CommandDependencies(
|
||||
apnSender, fcmSender, accountsManager, 0, 0, retryExecutor);
|
||||
PushNotificationManager pushNotificationManager = new PushNotificationManager(accountsManager,
|
||||
apnSender, fcmSender, pushNotificationScheduler);
|
||||
PushNotificationExperimentSamples pushNotificationExperimentSamples =
|
||||
new PushNotificationExperimentSamples(dynamoDbAsyncClient,
|
||||
configuration.getDynamoDbTables().getPushNotificationExperimentSamples().getTableName(),
|
||||
Clock.systemUTC());
|
||||
|
||||
final DynamoDbRecoveryManager dynamoDbRecoveryManager =
|
||||
new DynamoDbRecoveryManager(accounts, phoneNumberIdentifiers);
|
||||
@@ -481,7 +479,6 @@ public record CommandDependencies(
|
||||
apnSender,
|
||||
fcmSender,
|
||||
pushNotificationManager,
|
||||
pushNotificationExperimentSamples,
|
||||
cacheCluster,
|
||||
pushSchedulerCluster,
|
||||
redisClientResourcesBuilder,
|
||||
@@ -496,7 +493,8 @@ public record CommandDependencies(
|
||||
phoneNumberIdentifiers,
|
||||
dynamoDbRecoveryManager,
|
||||
fdb,
|
||||
accountLockManager);
|
||||
accountLockManager,
|
||||
sandboxAccounts);
|
||||
}
|
||||
|
||||
}
|
||||
-62
@@ -1,62 +0,0 @@
|
||||
package org.whispersystems.textsecuregcm.workers;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.dropwizard.core.Application;
|
||||
import io.dropwizard.core.setup.Environment;
|
||||
import net.sourceforge.argparse4j.inf.Namespace;
|
||||
import net.sourceforge.argparse4j.inf.Subparser;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.experiment.PushNotificationExperiment;
|
||||
|
||||
public class DiscardPushNotificationExperimentSamplesCommand extends AbstractCommandWithDependencies {
|
||||
|
||||
private final PushNotificationExperimentFactory<?> experimentFactory;
|
||||
|
||||
private static final int DEFAULT_MAX_CONCURRENCY = 16;
|
||||
|
||||
@VisibleForTesting
|
||||
static final String MAX_CONCURRENCY_ARGUMENT = "max-concurrency";
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(DiscardPushNotificationExperimentSamplesCommand.class);
|
||||
|
||||
public DiscardPushNotificationExperimentSamplesCommand(final String name,
|
||||
final String description,
|
||||
final PushNotificationExperimentFactory<?> experimentFactory) {
|
||||
|
||||
super(new Application<>() {
|
||||
@Override
|
||||
public void run(final WhisperServerConfiguration configuration, final Environment environment) {
|
||||
}
|
||||
}, name, description);
|
||||
|
||||
this.experimentFactory = experimentFactory;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configure(final Subparser subparser) {
|
||||
super.configure(subparser);
|
||||
|
||||
subparser.addArgument("--max-concurrency")
|
||||
.type(Integer.class)
|
||||
.dest(MAX_CONCURRENCY_ARGUMENT)
|
||||
.setDefault(DEFAULT_MAX_CONCURRENCY)
|
||||
.help("Max concurrency for DynamoDB operations");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void run(final Environment environment,
|
||||
final Namespace namespace,
|
||||
final WhisperServerConfiguration configuration,
|
||||
final CommandDependencies commandDependencies) throws Exception {
|
||||
|
||||
final PushNotificationExperiment<?> experiment =
|
||||
experimentFactory.buildExperiment(commandDependencies, configuration);
|
||||
|
||||
final int maxConcurrency = namespace.getInt(MAX_CONCURRENCY_ARGUMENT);
|
||||
|
||||
commandDependencies.pushNotificationExperimentSamples()
|
||||
.discardSamples(experiment.getExperimentName(), maxConcurrency).join();
|
||||
}
|
||||
}
|
||||
-124
@@ -1,124 +0,0 @@
|
||||
package org.whispersystems.textsecuregcm.workers;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.dropwizard.core.Application;
|
||||
import io.dropwizard.core.setup.Environment;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import net.sourceforge.argparse4j.inf.Namespace;
|
||||
import net.sourceforge.argparse4j.inf.Subparser;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.experiment.PushNotificationExperiment;
|
||||
import org.whispersystems.textsecuregcm.experiment.PushNotificationExperimentSample;
|
||||
import org.whispersystems.textsecuregcm.experiment.PushNotificationExperimentSamples;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.util.retry.Retry;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ConditionalCheckFailedException;
|
||||
import java.time.Duration;
|
||||
|
||||
public class FinishPushNotificationExperimentCommand<T> extends AbstractCommandWithDependencies {
|
||||
|
||||
private final PushNotificationExperimentFactory<T> experimentFactory;
|
||||
|
||||
private static final int DEFAULT_MAX_CONCURRENCY = 16;
|
||||
|
||||
@VisibleForTesting
|
||||
static final String MAX_CONCURRENCY_ARGUMENT = "max-concurrency";
|
||||
|
||||
private static final String SAMPLES_READ_COUNTER_NAME =
|
||||
MetricsUtil.name(FinishPushNotificationExperimentCommand.class, "samplesRead");
|
||||
|
||||
private static final Counter ACCOUNT_READ_COUNTER =
|
||||
Metrics.counter(MetricsUtil.name(FinishPushNotificationExperimentCommand.class, "accountRead"));
|
||||
|
||||
private static final Counter FINAL_SAMPLE_STORED_COUNTER =
|
||||
Metrics.counter(MetricsUtil.name(FinishPushNotificationExperimentCommand.class, "finalSampleStored"));
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(FinishPushNotificationExperimentCommand.class);
|
||||
|
||||
public FinishPushNotificationExperimentCommand(final String name,
|
||||
final String description,
|
||||
final PushNotificationExperimentFactory<T> experimentFactory) {
|
||||
|
||||
super(new Application<>() {
|
||||
@Override
|
||||
public void run(final WhisperServerConfiguration configuration, final Environment environment) {
|
||||
}
|
||||
}, name, description);
|
||||
|
||||
this.experimentFactory = experimentFactory;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configure(final Subparser subparser) {
|
||||
super.configure(subparser);
|
||||
|
||||
subparser.addArgument("--max-concurrency")
|
||||
.type(Integer.class)
|
||||
.dest(MAX_CONCURRENCY_ARGUMENT)
|
||||
.setDefault(DEFAULT_MAX_CONCURRENCY)
|
||||
.help("Max concurrency for DynamoDB operations");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void run(final Environment environment,
|
||||
final Namespace namespace,
|
||||
final WhisperServerConfiguration configuration,
|
||||
final CommandDependencies commandDependencies) throws Exception {
|
||||
|
||||
final PushNotificationExperiment<T> experiment =
|
||||
experimentFactory.buildExperiment(commandDependencies, configuration);
|
||||
|
||||
final int maxConcurrency = namespace.getInt(MAX_CONCURRENCY_ARGUMENT);
|
||||
|
||||
log.info("Finishing \"{}\" with max concurrency: {}", experiment.getExperimentName(), maxConcurrency);
|
||||
|
||||
final AccountsManager accountsManager = commandDependencies.accountsManager();
|
||||
final PushNotificationExperimentSamples pushNotificationExperimentSamples = commandDependencies.pushNotificationExperimentSamples();
|
||||
|
||||
final Flux<PushNotificationExperimentSample<T>> finishedSamples =
|
||||
pushNotificationExperimentSamples.getSamples(experiment.getExperimentName(), experiment.getStateClass())
|
||||
.doOnNext(sample -> Metrics.counter(SAMPLES_READ_COUNTER_NAME, "final", String.valueOf(sample.finalState() != null)).increment())
|
||||
.flatMap(sample -> {
|
||||
if (sample.finalState() == null) {
|
||||
// We still need to record a final state for this sample
|
||||
return Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(sample.accountIdentifier()))
|
||||
.retryWhen(Retry.backoff(3, Duration.ofSeconds(1)))
|
||||
.doOnNext(ignored -> ACCOUNT_READ_COUNTER.increment())
|
||||
.flatMap(maybeAccount -> {
|
||||
final T finalState = experiment.getState(maybeAccount.orElse(null),
|
||||
maybeAccount.flatMap(account -> account.getDevice(sample.deviceId())).orElse(null));
|
||||
|
||||
return Mono.fromFuture(
|
||||
() -> pushNotificationExperimentSamples.recordFinalState(sample.accountIdentifier(),
|
||||
sample.deviceId(),
|
||||
experiment.getExperimentName(),
|
||||
finalState))
|
||||
.onErrorResume(ConditionalCheckFailedException.class, throwable -> Mono.empty())
|
||||
.onErrorResume(JsonProcessingException.class, throwable -> {
|
||||
log.error("Failed to parse sample state JSON", throwable);
|
||||
return Mono.empty();
|
||||
})
|
||||
.retryWhen(Retry.backoff(3, Duration.ofSeconds(1)))
|
||||
.onErrorResume(throwable -> {
|
||||
log.warn("Failed to record final state for {}:{} in experiment {}",
|
||||
sample.accountIdentifier(), sample.deviceId(), experiment.getExperimentName(), throwable);
|
||||
|
||||
return Mono.empty();
|
||||
})
|
||||
.doOnSuccess(ignored -> FINAL_SAMPLE_STORED_COUNTER.increment());
|
||||
});
|
||||
} else {
|
||||
return Mono.just(sample);
|
||||
}
|
||||
}, maxConcurrency);
|
||||
|
||||
experiment.analyzeResults(finishedSamples);
|
||||
}
|
||||
}
|
||||
-10
@@ -1,10 +0,0 @@
|
||||
package org.whispersystems.textsecuregcm.workers;
|
||||
|
||||
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.experiment.PushNotificationExperiment;
|
||||
|
||||
public interface PushNotificationExperimentFactory<T> {
|
||||
|
||||
PushNotificationExperiment<T> buildExperiment(CommandDependencies commandDependencies,
|
||||
WhisperServerConfiguration configuration);
|
||||
}
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.workers;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.dropwizard.core.Application;
|
||||
import io.dropwizard.core.setup.Environment;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Optional;
|
||||
import net.sourceforge.argparse4j.inf.Namespace;
|
||||
import net.sourceforge.argparse4j.inf.Subparser;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.SandboxAccounts;
|
||||
|
||||
/// Deletes sandbox accounts that are past [#MAX_SANDBOX_ACCOUNT_AGE]
|
||||
public class RemoveExpiredSandboxAccountsCommand extends AbstractCommandWithDependencies {
|
||||
private static final Logger log = LoggerFactory.getLogger(RemoveExpiredSandboxAccountsCommand.class);
|
||||
public static final Duration MAX_SANDBOX_ACCOUNT_AGE = Duration.ofDays(1);
|
||||
|
||||
private static final String RELEASED_ACI_COUNTER_NAME =
|
||||
name(RemoveExpiredSandboxAccountsCommand.class, "releasedAci");
|
||||
|
||||
@VisibleForTesting
|
||||
static final String DRY_RUN_ARGUMENT = "dry-run";
|
||||
|
||||
private final Clock clock;
|
||||
|
||||
public RemoveExpiredSandboxAccountsCommand(final Clock clock) {
|
||||
super(new Application<>() {
|
||||
@Override
|
||||
public void run(final WhisperServerConfiguration configuration, final Environment environment) {
|
||||
}
|
||||
}, "remove-expired-sandbox-accounts", "Removes expired sandbox accounts and returns their ACIs to the pool");
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configure(final Subparser subparser) {
|
||||
super.configure(subparser);
|
||||
|
||||
subparser.addArgument("--dry-run")
|
||||
.type(Boolean.class)
|
||||
.dest(DRY_RUN_ARGUMENT)
|
||||
.required(false)
|
||||
.setDefault(true)
|
||||
.help("If true, don't actually delete accounts or release ACIs");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void run(final Environment environment, final Namespace namespace,
|
||||
final WhisperServerConfiguration configuration, final CommandDependencies commandDependencies) throws Exception {
|
||||
final boolean isDryRun = namespace.getBoolean(DRY_RUN_ARGUMENT);
|
||||
final AccountsManager accountsManager = commandDependencies.accountsManager();
|
||||
final SandboxAccounts sandboxAccounts = commandDependencies.sandboxAccounts();
|
||||
final Instant expirationThreshold = clock.instant().minus(MAX_SANDBOX_ACCOUNT_AGE);
|
||||
|
||||
for (final SandboxAccounts.SandboxAccountReservation sandboxAccount : sandboxAccounts.getAll()) {
|
||||
if (sandboxAccount.registeredAt().isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
final Instant registeredAt = sandboxAccount.registeredAt().get();
|
||||
final boolean expired = registeredAt.isBefore(expirationThreshold);
|
||||
if (!expired) {
|
||||
log.info("Skipping unexpired sandbox account {}", sandboxAccount);
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
final Optional<Account> account = accountsManager.getByAccountIdentifier(sandboxAccount.uuid());
|
||||
if (!isDryRun) {
|
||||
account.ifPresent(_ -> accountsManager.delete(sandboxAccount.uuid(), AccountsManager.DeletionReason.EXPIRED));
|
||||
if (!sandboxAccounts.releaseAci(sandboxAccount.uuid(), registeredAt)) {
|
||||
log.warn("Registration for sandbox ACI {} changed before it could be released", sandboxAccount.uuid());
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
log.info("Released sandbox ACI {} registered at {} (exists: {}, dry run: {})",
|
||||
sandboxAccount.uuid(), registeredAt, account.isPresent(), isDryRun);
|
||||
Metrics.counter(RELEASED_ACI_COUNTER_NAME,
|
||||
"exists", String.valueOf(account.isPresent()),
|
||||
"dryRun", String.valueOf(isDryRun))
|
||||
.increment();
|
||||
} catch (final Exception e) {
|
||||
log.warn("Failed to remove sandbox account {}", sandboxAccount.uuid(), e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.workers;
|
||||
|
||||
import io.dropwizard.core.Application;
|
||||
import io.dropwizard.core.setup.Environment;
|
||||
import java.util.UUID;
|
||||
import net.sourceforge.argparse4j.impl.Arguments;
|
||||
import net.sourceforge.argparse4j.inf.Namespace;
|
||||
import net.sourceforge.argparse4j.inf.Subparser;
|
||||
import net.sourceforge.argparse4j.inf.Subparsers;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.storage.SandboxAccounts;
|
||||
|
||||
/// Manages the pool of ACIs available for sandbox accounts
|
||||
public class SandboxAccountPoolCommand extends AbstractCommandWithDependencies {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(SandboxAccountPoolCommand.class);
|
||||
|
||||
private static final String SUBCOMMAND_ARGUMENT = "subcommand";
|
||||
private static final String COUNT_ARGUMENT = "count";
|
||||
|
||||
@FunctionalInterface
|
||||
private interface Subcommand {
|
||||
void run(SandboxAccounts sandboxAccounts, Namespace namespace);
|
||||
}
|
||||
|
||||
public SandboxAccountPoolCommand() {
|
||||
super(new Application<>() {
|
||||
@Override
|
||||
public void run(final WhisperServerConfiguration configuration, final Environment environment) {
|
||||
}
|
||||
}, "sandbox-account-pool", "Adds, removes, or lists the ACIs available for sandbox accounts");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configure(final Subparser subparser) {
|
||||
super.configure(subparser);
|
||||
|
||||
final Subparsers subparsers = subparser.addSubparsers();
|
||||
|
||||
final Subparser addParser = subparsers.addParser("add")
|
||||
.help("Add random ACIs to the pool")
|
||||
.setDefault(SUBCOMMAND_ARGUMENT, (Subcommand) SandboxAccountPoolCommand::add);
|
||||
addCountArgument(addParser, "The number of ACIs to add");
|
||||
|
||||
final Subparser removeParser = subparsers.addParser("remove")
|
||||
.help("Remove unclaimed ACIs from the pool")
|
||||
.setDefault(SUBCOMMAND_ARGUMENT, (Subcommand) SandboxAccountPoolCommand::remove);
|
||||
addCountArgument(removeParser, "The number of ACIs to remove");
|
||||
|
||||
subparsers.addParser("list")
|
||||
.help("List all ACIs in the pool")
|
||||
.setDefault(SUBCOMMAND_ARGUMENT, (Subcommand) SandboxAccountPoolCommand::list);
|
||||
}
|
||||
|
||||
private static void addCountArgument(final Subparser subparser, final String help) {
|
||||
subparser.addArgument("count")
|
||||
.type(Integer.class)
|
||||
.dest(COUNT_ARGUMENT)
|
||||
.choices(Arguments.range(1, Integer.MAX_VALUE))
|
||||
.help(help);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void run(final Environment environment, final Namespace namespace,
|
||||
final WhisperServerConfiguration configuration, final CommandDependencies commandDependencies) throws Exception {
|
||||
final Subcommand subcommand = namespace.get(SUBCOMMAND_ARGUMENT);
|
||||
subcommand.run(commandDependencies.sandboxAccounts(), namespace);
|
||||
}
|
||||
|
||||
private static void add(final SandboxAccounts sandboxAccounts, final Namespace namespace) {
|
||||
final int count = namespace.getInt(COUNT_ARGUMENT);
|
||||
for (int i = 0; i < count; i++) {
|
||||
final UUID aci = UUID.randomUUID();
|
||||
sandboxAccounts.add(aci);
|
||||
log.info("Added sandbox ACI {}", aci);
|
||||
}
|
||||
}
|
||||
|
||||
private static void remove(final SandboxAccounts sandboxAccounts, final Namespace namespace) {
|
||||
final int count = namespace.getInt(COUNT_ARGUMENT);
|
||||
int removed = 0;
|
||||
for (final UUID aci : sandboxAccounts.getAvailable()) {
|
||||
if (removed == count) {
|
||||
break;
|
||||
}
|
||||
if (sandboxAccounts.removeIfAvailable(aci)) {
|
||||
log.info("Removed sandbox ACI {}", aci);
|
||||
removed++;
|
||||
} else {
|
||||
log.info("Not removing sandbox ACI {} because it is currently claimed", aci);
|
||||
}
|
||||
}
|
||||
|
||||
if (removed < count) {
|
||||
throw new RuntimeException(
|
||||
"Requested removal of %d sandbox ACIs, but only %d were unclaimed".formatted(count, removed));
|
||||
}
|
||||
}
|
||||
|
||||
private static void list(final SandboxAccounts sandboxAccounts, final Namespace namespace) {
|
||||
for (final SandboxAccounts.SandboxAccountReservation sandboxAccount : sandboxAccounts.getAll()) {
|
||||
log.info("{} {}", sandboxAccount.uuid(), sandboxAccount.registeredAt()
|
||||
.map(registeredAt -> "expires " + registeredAt.plus(RemoveExpiredSandboxAccountsCommand.MAX_SANDBOX_ACCOUNT_AGE))
|
||||
.orElse("available"));
|
||||
}
|
||||
}
|
||||
}
|
||||
-164
@@ -1,164 +0,0 @@
|
||||
package org.whispersystems.textsecuregcm.workers;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import net.sourceforge.argparse4j.inf.Subparser;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.experiment.PushNotificationExperiment;
|
||||
import org.whispersystems.textsecuregcm.experiment.PushNotificationExperimentSamples;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.util.function.Tuples;
|
||||
import reactor.util.retry.Retry;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.time.Duration;
|
||||
import java.util.UUID;
|
||||
|
||||
public class StartPushNotificationExperimentCommand<T> extends AbstractSinglePassCrawlAccountsCommand {
|
||||
|
||||
private final PushNotificationExperimentFactory<T> experimentFactory;
|
||||
|
||||
private static final int DEFAULT_MAX_CONCURRENCY = 16;
|
||||
|
||||
@VisibleForTesting
|
||||
static final String MAX_CONCURRENCY_ARGUMENT = "max-concurrency";
|
||||
|
||||
@VisibleForTesting
|
||||
static final String DRY_RUN_ARGUMENT = "dry-run";
|
||||
|
||||
private static final Counter DEVICE_INSPECTED_COUNTER =
|
||||
Metrics.counter(MetricsUtil.name(StartPushNotificationExperimentCommand.class, "deviceInspected"));
|
||||
|
||||
private static final String RECORD_INITIAL_SAMPLE_COUNTER_NAME =
|
||||
MetricsUtil.name(StartPushNotificationExperimentCommand.class, "recordInitialSample");
|
||||
|
||||
private static final String APPLY_TREATMENT_COUNTER_NAME =
|
||||
MetricsUtil.name(StartPushNotificationExperimentCommand.class, "applyTreatment");
|
||||
|
||||
private static final String DRY_RUN_TAG_NAME = "dryRun";
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(StartPushNotificationExperimentCommand.class);
|
||||
|
||||
public StartPushNotificationExperimentCommand(final String name,
|
||||
final String description,
|
||||
final PushNotificationExperimentFactory<T> experimentFactory) {
|
||||
|
||||
super(name, description);
|
||||
this.experimentFactory = experimentFactory;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configure(final Subparser subparser) {
|
||||
super.configure(subparser);
|
||||
|
||||
subparser.addArgument("--max-concurrency")
|
||||
.type(Integer.class)
|
||||
.dest(MAX_CONCURRENCY_ARGUMENT)
|
||||
.setDefault(DEFAULT_MAX_CONCURRENCY)
|
||||
.help("Max concurrency for DynamoDB operations");
|
||||
|
||||
subparser.addArgument("--dry-run")
|
||||
.type(Boolean.class)
|
||||
.dest(DRY_RUN_ARGUMENT)
|
||||
.required(false)
|
||||
.setDefault(true)
|
||||
.help("If true, don't actually record samples or apply treatments");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void crawlAccounts(final Flux<Account> accounts) {
|
||||
final int maxConcurrency = getNamespace().getInt(MAX_CONCURRENCY_ARGUMENT);
|
||||
final boolean dryRun = getNamespace().getBoolean(DRY_RUN_ARGUMENT);
|
||||
|
||||
final PushNotificationExperiment<T> experiment =
|
||||
experimentFactory.buildExperiment(getCommandDependencies(), getConfiguration());
|
||||
|
||||
final PushNotificationExperimentSamples pushNotificationExperimentSamples =
|
||||
getCommandDependencies().pushNotificationExperimentSamples();
|
||||
|
||||
log.info("Starting \"{}\" with max concurrency: {}", experiment.getExperimentName(), maxConcurrency);
|
||||
|
||||
accounts
|
||||
.flatMap(account -> Flux.fromIterable(account.getDevices()).map(device -> Tuples.of(account, device)))
|
||||
.doOnNext(ignored -> DEVICE_INSPECTED_COUNTER.increment())
|
||||
.flatMap(accountAndDevice -> Mono.fromFuture(() ->
|
||||
experiment.isDeviceEligible(accountAndDevice.getT1(), accountAndDevice.getT2()))
|
||||
.mapNotNull(eligible -> eligible ? accountAndDevice : null), maxConcurrency)
|
||||
.flatMap(accountAndDevice -> {
|
||||
final UUID accountIdentifier = accountAndDevice.getT1().getAccountIdentifier();
|
||||
final byte deviceId = accountAndDevice.getT2().getId();
|
||||
|
||||
final Mono<Boolean> recordInitialSampleMono = dryRun
|
||||
? Mono.just(true)
|
||||
: Mono.fromFuture(() -> {
|
||||
try {
|
||||
return pushNotificationExperimentSamples.recordInitialState(
|
||||
accountIdentifier,
|
||||
deviceId,
|
||||
experiment.getExperimentName(),
|
||||
isInExperimentGroup(accountIdentifier, deviceId, experiment.getExperimentName()),
|
||||
experiment.getState(accountAndDevice.getT1(), accountAndDevice.getT2()));
|
||||
} catch (final JsonProcessingException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
})
|
||||
.retryWhen(Retry.backoff(3, Duration.ofSeconds(1))
|
||||
.onRetryExhaustedThrow(((backoffSpec, retrySignal) -> retrySignal.failure())));
|
||||
|
||||
return recordInitialSampleMono.mapNotNull(stateStored -> {
|
||||
Metrics.counter(RECORD_INITIAL_SAMPLE_COUNTER_NAME,
|
||||
DRY_RUN_TAG_NAME, String.valueOf(dryRun),
|
||||
"initialSampleAlreadyExists", String.valueOf(!stateStored))
|
||||
.increment();
|
||||
|
||||
return stateStored ? accountAndDevice : null;
|
||||
})
|
||||
.onErrorResume(throwable -> {
|
||||
log.warn("Failed to record initial sample for {}:{} in experiment {}",
|
||||
accountIdentifier, deviceId, experiment.getExperimentName(), throwable);
|
||||
|
||||
return Mono.empty();
|
||||
});
|
||||
}, maxConcurrency)
|
||||
.flatMap(accountAndDevice -> {
|
||||
final Account account = accountAndDevice.getT1();
|
||||
final Device device = accountAndDevice.getT2();
|
||||
final boolean inExperimentGroup =
|
||||
isInExperimentGroup(account.getAccountIdentifier(), device.getId(), experiment.getExperimentName());
|
||||
|
||||
final Mono<Void> applyTreatmentMono = dryRun
|
||||
? Mono.empty()
|
||||
: Mono.fromFuture(() -> inExperimentGroup
|
||||
? experiment.applyExperimentTreatment(account, device)
|
||||
: experiment.applyControlTreatment(account, device))
|
||||
.onErrorResume(throwable -> {
|
||||
log.warn("Failed to apply {} treatment for {}:{} in experiment {}",
|
||||
inExperimentGroup ? "experimental" : " control",
|
||||
account.getAccountIdentifier(),
|
||||
device.getId(),
|
||||
experiment.getExperimentName(),
|
||||
throwable);
|
||||
|
||||
return Mono.empty();
|
||||
});
|
||||
|
||||
return applyTreatmentMono
|
||||
.doOnSuccess(ignored -> Metrics.counter(APPLY_TREATMENT_COUNTER_NAME,
|
||||
DRY_RUN_TAG_NAME, String.valueOf(dryRun),
|
||||
"treatment", inExperimentGroup ? "experiment" : "control").increment());
|
||||
}, maxConcurrency)
|
||||
.then()
|
||||
.block();
|
||||
}
|
||||
|
||||
private boolean isInExperimentGroup(final UUID accountIdentifier, final byte deviceId, final String experimentName) {
|
||||
return ((accountIdentifier.hashCode() ^ Byte.hashCode(deviceId) ^ experimentName.hashCode()) & 0x01) != 0;
|
||||
}
|
||||
}
|
||||
@@ -151,9 +151,8 @@ message GetEntitlementsRequest {
|
||||
|
||||
message GetEntitlementsResponse {
|
||||
message BadgeEntitlement {
|
||||
// The id of the badge the account is entitled. Metadata to display for
|
||||
// badges may be obtained by cross-referencing badge ids with
|
||||
// RemoteConfiguration.GetBadges.
|
||||
// The id of the badge. Metadata to display for badges may be obtained by
|
||||
// cross-referencing badge ids with RemoteConfiguration.GetBadges.
|
||||
string badge_id = 1;
|
||||
// When the badge expires, in number of seconds since epoch
|
||||
uint64 expiration_epoch_seconds = 2;
|
||||
|
||||
@@ -25,7 +25,7 @@ service Donations {
|
||||
// Generate a set of anonymous, single-use, permits for use with /v1/subscription endpoints.
|
||||
//
|
||||
// If rate limited, reduce requested permit count and/or try again after the prescribed delay.
|
||||
rpc CreateDonationPermit(CreateDonationPermitRequest) returns (CreateDonationPermitResponse) {}
|
||||
rpc CreateDonationPermits(CreateDonationPermitsRequest) returns (CreateDonationPermitsResponse) {}
|
||||
}
|
||||
|
||||
message RedeemReceiptRequest {
|
||||
@@ -48,12 +48,12 @@ message RedeemReceiptResponse {
|
||||
}
|
||||
}
|
||||
|
||||
message CreateDonationPermitRequest {
|
||||
// a serialized libsignal DonationPermitRequest
|
||||
bytes donation_permit_request = 1 [(require.nonEmpty) = true];
|
||||
message CreateDonationPermitsRequest {
|
||||
// a serialized libsignal DonationPermitsRequest
|
||||
bytes donation_permits_request = 1 [(require.nonEmpty) = true];
|
||||
}
|
||||
|
||||
message CreateDonationPermitResponse {
|
||||
// a serialized libsignal DonationPermitResponse
|
||||
bytes donation_permit_response = 1;
|
||||
message CreateDonationPermitsResponse {
|
||||
// a serialized libsignal DonationPermitsResponse
|
||||
bytes donation_permits_response = 1;
|
||||
}
|
||||
@@ -110,6 +110,7 @@ message GetPreKeysRequest {
|
||||
|
||||
message GetPreKeysAnonymousRequest {
|
||||
// The request to retrieve pre-keys for a specific account/device(s).
|
||||
// If `request.target_identifier` is a PNI, `authorization` must be a group send token.
|
||||
GetPreKeysRequest request = 1;
|
||||
|
||||
// A means to authorize the request.
|
||||
|
||||
@@ -25,9 +25,10 @@ service LoginPurchase {
|
||||
}
|
||||
|
||||
message CreateLoginReceiptCredentialRequest {
|
||||
// The payment processor. Currently, only GOOGLE_PLAY_BILLING and
|
||||
// APPLE_APP_STORE are supported.
|
||||
PaymentProvider processor = 1 [(require.specified) = true];
|
||||
// The payment processor
|
||||
PaymentProvider processor = 1 [(require.allowedValues) = {
|
||||
enums: ["PAYMENT_PROVIDER_GOOGLE_PLAY_BILLING", "PAYMENT_PROVIDER_APPLE_APP_STORE"]
|
||||
}];
|
||||
|
||||
// The identifier of a completed purchase for a signal login within the
|
||||
// payment provider
|
||||
|
||||
@@ -245,6 +245,7 @@ message SendSyncMessageRequest {
|
||||
message SendSealedSenderMessageRequest {
|
||||
|
||||
// The service identifier of the account to which to deliver the message.
|
||||
// If `destination` is a PNI, `authorization` must be a group send token.
|
||||
common.ServiceIdentifier destination = 1;
|
||||
|
||||
// If true, this message will only be delivered to destination devices that
|
||||
|
||||
@@ -22,7 +22,7 @@ service OneTimeDonations {
|
||||
|
||||
// Create a Stripe payment intent and return a client secret that can be used to complete the payment.
|
||||
// Once the payment is complete, the paymentIntentId can be used with CreateBoostReceiptCredential
|
||||
rpc CreateBoost(CreateBoostRequest) returns (CreateBoostResponse) {}
|
||||
rpc CreateStripeBoost(CreateStripeBoostRequest) returns (CreateStripeBoostResponse) {}
|
||||
|
||||
// Create a PayPal one-time payment.
|
||||
//
|
||||
@@ -44,47 +44,34 @@ service OneTimeDonations {
|
||||
rpc CreateBoostReceiptCredential(CreateBoostReceiptCredentialRequest) returns (CreateBoostReceiptCredentialResponse) {}
|
||||
}
|
||||
|
||||
// The amount is below the minimum for the currency.
|
||||
message AmountBelowMinimumError {
|
||||
// The minimum amount for the currency in the [currency's minor unit](https://docs.stripe.com/currencies#minor-units)
|
||||
uint64 minimum = 1;
|
||||
}
|
||||
|
||||
// The SEPA Direct Debit amount exceeds the allowed maximum.
|
||||
message AmountAboveSepaLimitError {
|
||||
// The maximum amount for a SEPA transaction in the [currency's minor unit](https://docs.stripe.com/currencies#minor-units)
|
||||
uint64 maximum = 1;
|
||||
}
|
||||
|
||||
message CreateBoostRequest {
|
||||
message CreateStripeBoostRequest {
|
||||
// ISO 4217 currency code, case-insensitive (e.g. "usd", "EUR")
|
||||
string currency = 1 [(require.exactlySize) = 3];
|
||||
// The amount to pay in the [currency's minor unit](https://docs.stripe.com/currencies#minor-units)
|
||||
uint64 amount = 2 [(require.range).min = 1];
|
||||
// The level for the boost payment
|
||||
uint64 level = 3 [(require.range).min = 1];
|
||||
// The payment method
|
||||
PaymentMethod payment_method = 4 [(require.specified) = true];
|
||||
// The level for the boost payment: 1 for a one-time donation, 100 for a gift donation
|
||||
uint64 level = 3 [(require.allowedValues) = { ints: [1, 100] }];
|
||||
// The payment method. Only card, SEPA Direct Debit, and iDEAL are supported.
|
||||
PaymentMethod payment_method = 4 [(require.allowedValues) = {
|
||||
enums: ["PAYMENT_METHOD_CARD", "PAYMENT_METHOD_SEPA_DEBIT", "PAYMENT_METHOD_IDEAL"]
|
||||
}];
|
||||
// A donation permit retrieved from Donations.createDonationPermit
|
||||
bytes donation_permit = 5 [(require.nonEmpty) = true];
|
||||
}
|
||||
|
||||
message CreateBoostResponse {
|
||||
message CreateStripeBoostResponse {
|
||||
oneof response {
|
||||
// A client secret that can be used to complete a stripe PaymentIntent
|
||||
string client_secret = 1;
|
||||
// The amount is below the minimum for the currency
|
||||
AmountBelowMinimumError amount_below_minimum = 2 [(tag.reason) = "amount_below_minimum"];
|
||||
// The amount exceeds the maximum for SEPA Direct Debit
|
||||
AmountAboveSepaLimitError amount_above_sepa_limit = 3 [(tag.reason) = "amount_above_sepa_limit"];
|
||||
// The requested currency is not supported for the given payment method
|
||||
errors.FailedPrecondition unsupported_currency = 4 [(tag.reason) = "unsupported_currency"];
|
||||
// The requested level is not a valid one-time donation level
|
||||
errors.FailedPrecondition unsupported_level = 5 [(tag.reason) = "unsupported_level"];
|
||||
// The currency is not supported for the payment method, or the amount is
|
||||
// outside the configured limits (e.g. below the currency's minimum, above
|
||||
// the SEPA Direct Debit maximum, above the processor's currency maximum).
|
||||
// The violated constraint may be present in the product configuration,
|
||||
// clients can attempt a refresh of ProductConfiguration/GetConfiguration
|
||||
// before giving up.
|
||||
errors.FailedPrecondition invalid_selection = 2 [(tag.reason) = "invalid_selection"];
|
||||
// Donation permit was invalid or already spent
|
||||
errors.FailedZkAuthentication permit_rejected = 6 [(tag.reason) = "permit_rejected"];
|
||||
// The amount in the specified currency is not supported by the payment provider
|
||||
errors.FailedPrecondition invalid_amount = 7 [(tag.reason) = "invalid_amount"];
|
||||
errors.FailedZkAuthentication permit_rejected = 3 [(tag.reason) = "permit_rejected"];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -93,8 +80,8 @@ message CreatePayPalBoostRequest {
|
||||
string currency = 1 [(require.exactlySize) = 3];
|
||||
// Amount in the currency's minor unit (e.g. cents for USD), must be >= 1
|
||||
uint64 amount = 2 [(require.range).min = 1];
|
||||
// Donation level.
|
||||
uint64 level = 3 [(require.range).min = 1];
|
||||
// Donation level: 1 for a one-time donation, 100 for a gift donation
|
||||
uint64 level = 3 [(require.allowedValues) = { ints: [1, 100] }];
|
||||
// URL to redirect the user to after PayPal approval
|
||||
string return_url = 4 [(require.nonEmpty) = true];
|
||||
// URL to redirect the user to if they cancel
|
||||
@@ -108,12 +95,11 @@ message CreatePayPalBoostResponse {
|
||||
}
|
||||
oneof response {
|
||||
CreatePayPalBoostResult result = 1;
|
||||
// The amount is below the minimum for the currency
|
||||
AmountBelowMinimumError amount_below_minimum = 2 [(tag.reason) = "amount_below_minimum"];
|
||||
// The requested currency is not supported for PayPal
|
||||
errors.FailedPrecondition unsupported_currency = 3 [(tag.reason) = "unsupported_currency"];
|
||||
// The requested level is not a valid one-time donation level
|
||||
errors.FailedPrecondition unsupported_level = 4 [(tag.reason) = "unsupported_level"];
|
||||
// The currency is not supported for PayPal, or the amount is below the
|
||||
// currency's minimum. The violated constraint may be present in the product
|
||||
// configuration, clients can attempt a refresh of
|
||||
// ProductConfiguration/GetConfiguration before giving up.
|
||||
errors.FailedPrecondition invalid_selection = 2 [(tag.reason) = "invalid_selection"];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -122,8 +108,8 @@ message ConfirmPayPalBoostRequest {
|
||||
string currency = 1 [(require.exactlySize) = 3];
|
||||
// Amount in the currency's minor unit, must be >= 1
|
||||
uint64 amount = 2 [(require.range).min = 1];
|
||||
// Donation level.
|
||||
uint64 level = 3 [(require.range).min = 1];
|
||||
// Donation level: 1 for a one-time donation, 100 for a gift donation
|
||||
uint64 level = 3 [(require.allowedValues) = { ints: [1, 100] }];
|
||||
// PayPal payer ID from the approval redirect
|
||||
string payer_id = 4 [(require.nonEmpty) = true];
|
||||
// PayPal payment ID (PAYID-…) from CreatePayPalBoost
|
||||
@@ -138,14 +124,13 @@ message ConfirmPayPalBoostResponse {
|
||||
}
|
||||
oneof response {
|
||||
ConfirmPayPalBoostResult result = 1;
|
||||
// The amount is below the minimum for the currency
|
||||
AmountBelowMinimumError amount_below_minimum = 2 [(tag.reason) = "amount_below_minimum"];
|
||||
// The requested currency is not supported for PayPal
|
||||
errors.FailedPrecondition unsupported_currency = 3 [(tag.reason) = "unsupported_currency"];
|
||||
// The requested level is not a valid one-time donation level
|
||||
errors.FailedPrecondition unsupported_level = 4 [(tag.reason) = "unsupported_level"];
|
||||
// The currency is not supported for PayPal, or the amount is below the
|
||||
// currency's minimum. The violated constraint may be present in the product
|
||||
// configuration, clients can attempt a refresh of
|
||||
// ProductConfiguration/GetConfiguration before giving up.
|
||||
errors.FailedPrecondition invalid_selection = 2 [(tag.reason) = "invalid_selection"];
|
||||
// The payment failed; see charge failure details
|
||||
ChargeFailure charge_failure = 5 [(tag.reason) = "charge_failure"];
|
||||
PaymentRequired payment_required = 3 [(tag.reason) = "payment_required"];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -155,7 +140,9 @@ message CreateBoostReceiptCredentialRequest {
|
||||
// ZK blind-signature receipt credential request bytes
|
||||
bytes receipt_credential_request = 2 [(require.nonEmpty) = true];
|
||||
// The processor that handled the payment
|
||||
PaymentProvider processor = 3 [(require.specified) = true];
|
||||
PaymentProvider processor = 3 [(require.allowedValues) = {
|
||||
enums: ["PAYMENT_PROVIDER_STRIPE", "PAYMENT_PROVIDER_BRAINTREE"]
|
||||
}];
|
||||
}
|
||||
|
||||
message CreateBoostReceiptCredentialResponse {
|
||||
|
||||
@@ -66,7 +66,7 @@ message LevelConfiguration {
|
||||
|
||||
// The duration for which a badge is valid. Present only for
|
||||
// one-time (boost, gift) badges
|
||||
optional uint64 badge_duration_seconds = 2;
|
||||
optional uint32 badge_duration_seconds = 2;
|
||||
}
|
||||
|
||||
// Configuration for a backup level - use to present appropriate client interfaces
|
||||
@@ -76,14 +76,14 @@ message BackupLevelConfiguration {
|
||||
// The play billing productID associated with this backup level
|
||||
string play_product_id = 2;
|
||||
// The duration, in days, for which your backed up media is retained on the server after you stop refreshing with a paid credential
|
||||
uint64 media_ttl_days = 3;
|
||||
uint32 media_ttl_days = 3;
|
||||
}
|
||||
|
||||
message BackupConfiguration {
|
||||
// A map of numeric backup level IDs to level-specific backup configuration
|
||||
map<uint64, BackupLevelConfiguration> levels = 1;
|
||||
// The number of days of media a free tier backup user gets
|
||||
uint64 free_tier_media_days = 2;
|
||||
uint32 free_tier_media_days = 2;
|
||||
}
|
||||
|
||||
// Configuration for one-time Signal Login purchases
|
||||
|
||||
@@ -175,6 +175,13 @@ message SetProfileResult {
|
||||
// next: 1
|
||||
}
|
||||
|
||||
message ExpectedVersionConflict {
|
||||
// In certain, highly unlikely, cases, a new profile version might not be
|
||||
// distributed among all devices. These devices wouldn't be able to decrypt the
|
||||
// profile, but the value can be used to set a new version.
|
||||
bytes current_profile_version = 2;
|
||||
}
|
||||
|
||||
message SetProfileResponse {
|
||||
oneof response {
|
||||
SetProfileResult result = 1;
|
||||
@@ -187,7 +194,7 @@ message SetProfileResponse {
|
||||
PaymentsForbiddenInRegion payments_forbidden_in_region = 3 [(tag.reason) = "payments_forbidden_in_region"];
|
||||
// The current version did not match the request's expectation, indicating
|
||||
// another device on the account may have created a new version the caller does not know about.
|
||||
errors.FailedPrecondition expected_version_write_conflict = 4 [(tag.reason) = "expected_version_write_conflict"];
|
||||
ExpectedVersionConflict expected_version_write_conflict = 4 [(tag.reason) = "expected_version_write_conflict"];
|
||||
|
||||
// next: 5
|
||||
}
|
||||
|
||||
@@ -200,7 +200,28 @@ extend google.protobuf.FieldOptions {
|
||||
*/
|
||||
optional ElementConstraint each = 70010;
|
||||
|
||||
// next 70011
|
||||
/*
|
||||
* Requires a value to be one of a fixed set of values. Use `ints` for integer
|
||||
* fields, `strings` for string fields, and `enums` (enum value names) for enum
|
||||
* fields.
|
||||
*
|
||||
* If the field is `optional`, this check allows a value to be not set.
|
||||
*
|
||||
* ```
|
||||
* import "org/signal/chat/require.proto";
|
||||
*
|
||||
* message Data {
|
||||
* uint64 level = 1 [(require.allowedValues) = { ints: [1, 100] }];
|
||||
* string kind = 2 [(require.allowedValues) = { strings: ["boost", "gift"] }];
|
||||
* Color color = 3 [(require.allowedValues) = { enums: ["COLOR_RED", "COLOR_BLUE"] }];
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* Applicable to integer, string, and enum fields.
|
||||
*/
|
||||
optional AllowedValuesConstraint allowedValues = 70011;
|
||||
|
||||
// next 70012
|
||||
}
|
||||
|
||||
message ElementConstraint {
|
||||
@@ -219,6 +240,15 @@ message SizeConstraint {
|
||||
optional uint32 max = 2;
|
||||
}
|
||||
|
||||
message AllowedValuesConstraint {
|
||||
// Permitted values for integer fields
|
||||
repeated int64 ints = 1;
|
||||
// Permitted values for string fields
|
||||
repeated string strings = 2;
|
||||
// Permitted value names for enum fields
|
||||
repeated string enums = 3;
|
||||
}
|
||||
|
||||
message ValueRangeConstraint {
|
||||
optional int64 min = 1;
|
||||
optional int64 max = 2;
|
||||
|
||||
@@ -33,8 +33,8 @@ service Subscriptions {
|
||||
// cancelling a subscription from storekit to keep server data up to date.
|
||||
rpc DeleteSubscriber(DeleteSubscriberRequest) returns (DeleteSubscriberResponse) {}
|
||||
|
||||
// Returns a client secret that can be used to set up a new payment method with the payment processor.
|
||||
rpc CreatePaymentMethod(CreatePaymentMethodRequest) returns (CreatePaymentMethodResponse) {}
|
||||
// Returns a Stripe client secret that can be used to set up a new payment method with Stripe.
|
||||
rpc CreateStripePaymentMethod(CreateStripePaymentMethodRequest) returns (CreateStripePaymentMethodResponse) {}
|
||||
|
||||
// Returns a PayPal billing agreement approval URL and token that can be used to set up PayPal as a payment method.
|
||||
//
|
||||
@@ -49,7 +49,7 @@ service Subscriptions {
|
||||
// Sets the subscription level and currency for a subscriber.
|
||||
rpc SetSubscriptionLevel(SetSubscriptionLevelRequest) returns (SetSubscriptionLevelResponse) {}
|
||||
|
||||
// Returns information about the current subscription associated with the provided subscriberId if one exists.
|
||||
// Returns information about the current subscription associated with the provided subscriber_id if one exists.
|
||||
//
|
||||
// Although it uses [Stripe's values](https://stripe.com/docs/billing/subscriptions/overview#subscription-statuses),
|
||||
// the status field in the response is generic, with [Braintree-specific values](https://developer.paypal.com/braintree/docs/guides/recurring-billing/overview#subscription-statuses) mapped
|
||||
@@ -98,11 +98,11 @@ service Subscriptions {
|
||||
// 4. Obtain a receipt via GetReceiptCredential which can then be used to obtain the
|
||||
// entitlement
|
||||
//
|
||||
// After calling this method, the payment is confirmed. Callers must durably store their subscriberId before calling
|
||||
// After calling this method, the payment is confirmed. Callers must durably store their subscriber_id before calling
|
||||
// this method to ensure their payment is tracked.
|
||||
//
|
||||
// Once a purchaseToken to is posted to a subscriberId, the same subscriberId must not be used with another payment
|
||||
// method. A different playbilling purchaseToken can be posted to the same subscriberId, in this case the subscription
|
||||
// Once a purchaseToken to is posted to a subscriber_id, the same subscriber_id must not be used with another payment
|
||||
// method. A different playbilling purchaseToken can be posted to the same subscriber_id, in this case the subscription
|
||||
// associated with the old purchaseToken will be cancelled.
|
||||
rpc SetIapSubscription(SetIapSubscriptionRequest) returns (SetIapSubscriptionResponse) {}
|
||||
|
||||
@@ -117,7 +117,7 @@ service Subscriptions {
|
||||
message UpdateSubscriberRequest {
|
||||
// New subscriber-ids must be a randomly-generated 32 byte byte-string.
|
||||
bytes subscriber_id = 1 [(require.exactlySize) = 32];
|
||||
// A libsignal DonationPermit from rpc Donations.CreateDonationPermit.
|
||||
// A libsignal DonationPermit from rpc Donations.CreateDonationPermits.
|
||||
// Not required if the subscriber already exists.
|
||||
bytes donation_permit = 2;
|
||||
}
|
||||
@@ -131,7 +131,7 @@ message UpdateSubscriberResponse {
|
||||
}
|
||||
|
||||
message DeleteSubscriberRequest {
|
||||
bytes subscriberId = 1 [(require.exactlySize) = 32];
|
||||
bytes subscriber_id = 1 [(require.exactlySize) = 32];
|
||||
}
|
||||
|
||||
message DeleteSubscriberResponse {
|
||||
@@ -180,23 +180,23 @@ enum SubscriptionStatus {
|
||||
SUBSCRIPTION_STATUS_UNPAID = 5;
|
||||
}
|
||||
|
||||
message CreatePaymentMethodRequest {
|
||||
// Only PAYMENT_METHOD_CARD, PAYMENT_METHOD_SEPA_DEBIT, and PAYMENT_METHOD_IDEAL are supported;
|
||||
// other values will result in an INVALID_ARGUMENT error.
|
||||
message CreateStripePaymentMethodRequest {
|
||||
bytes subscriber_id = 1 [(require.exactlySize) = 32];
|
||||
PaymentMethod payment_method = 2 [(require.specified) = true];
|
||||
// a libsignal DonationPermit from rpc Donations.CreateDonationPermit
|
||||
// The payment method. Only card, SEPA Direct Debit, and iDEAL are supported.
|
||||
PaymentMethod payment_method = 2 [(require.allowedValues) = {
|
||||
enums: ["PAYMENT_METHOD_CARD", "PAYMENT_METHOD_SEPA_DEBIT", "PAYMENT_METHOD_IDEAL"]
|
||||
}];
|
||||
// a libsignal DonationPermit from rpc Donations.CreateDonationPermits
|
||||
bytes donation_permit = 3 [(require.nonEmpty) = true];
|
||||
}
|
||||
|
||||
message CreatePaymentMethodResponse {
|
||||
message CreatePaymentMethodResult {
|
||||
string clientSecret = 1;
|
||||
PaymentProvider paymentProvider = 2;
|
||||
message CreateStripePaymentMethodResponse {
|
||||
message CreateStripePaymentMethodResult {
|
||||
string client_secret = 1;
|
||||
}
|
||||
|
||||
oneof response {
|
||||
CreatePaymentMethodResult result = 1;
|
||||
CreateStripePaymentMethodResult result = 1;
|
||||
// The subscriber did not exist
|
||||
errors.NotFound subscriber_not_found = 2 [(tag.reason) = "subscriber_not_found"];
|
||||
// New payment processor does not match existing processor associated with
|
||||
@@ -208,17 +208,17 @@ message CreatePaymentMethodResponse {
|
||||
}
|
||||
|
||||
message CreatePayPalPaymentMethodRequest {
|
||||
bytes subscriberId = 1 [(require.exactlySize) = 32];
|
||||
bytes subscriber_id = 1 [(require.exactlySize) = 32];
|
||||
// a callback URL (e.g. an in-client URL handler) for when the user approved the payment
|
||||
string returnUrl = 2;
|
||||
string return_url = 2;
|
||||
// a callback URL (e.g. an in-client URL handler) for when the user did not approve the payment
|
||||
string cancelUrl = 3;
|
||||
string cancel_url = 3;
|
||||
}
|
||||
|
||||
message CreatePayPalPaymentMethodResponse {
|
||||
message CreatePayPalPaymentMethodResult {
|
||||
// a URL to open where the user may approve the payment
|
||||
string approvalUrl = 1;
|
||||
string approval_url = 1;
|
||||
// an opaque PayPal payment identifier to use with SetDefaultPaymentMethodRequest
|
||||
string token = 2;
|
||||
}
|
||||
@@ -235,16 +235,16 @@ message CreatePayPalPaymentMethodResponse {
|
||||
|
||||
message SetDefaultPaymentMethodRequest {
|
||||
message StripePaymentMethod {
|
||||
string paymentMethodToken = 1 [(require.nonEmpty) = true];
|
||||
string payment_method_token = 1 [(require.nonEmpty) = true];
|
||||
}
|
||||
message BraintreePaymentMethod {
|
||||
string paymentMethodToken = 1 [(require.nonEmpty) = true];
|
||||
string payment_method_token = 1 [(require.nonEmpty) = true];
|
||||
}
|
||||
message SepaPaymentMethod {
|
||||
string setupIntentId = 1 [(require.nonEmpty) = true];
|
||||
string setup_intent_id = 1 [(require.nonEmpty) = true];
|
||||
}
|
||||
|
||||
bytes subscriberId = 1 [(require.exactlySize) = 32];
|
||||
bytes subscriber_id = 1 [(require.exactlySize) = 32];
|
||||
oneof request {
|
||||
StripePaymentMethod stripe = 2;
|
||||
BraintreePaymentMethod braintree = 3;
|
||||
@@ -257,17 +257,20 @@ message SetDefaultPaymentMethodResponse {
|
||||
google.protobuf.Empty success = 1;
|
||||
// The subscriber did not exist, or the referenced setup intent was not found
|
||||
errors.NotFound subscriber_not_found = 2 [(tag.reason) = "subscriber_not_found"];
|
||||
// No payment method has been created for the subscriber, or the provided
|
||||
// payment method has not finished being set up with the processor
|
||||
errors.FailedPrecondition payment_method_not_set_up = 3 [(tag.reason) = "payment_method_not_set_up"];
|
||||
// The request could not be applied in the subscriber's current state. This
|
||||
// typically indicates a client bug or an out-of-date client. Either
|
||||
// - No payment method has been created for the subscriber
|
||||
// - The provided payment method has not finished being set up with the
|
||||
// processor
|
||||
errors.FailedPrecondition failed_precondition = 3 [(tag.reason) = "failed_precondition"];
|
||||
}
|
||||
}
|
||||
|
||||
message SetSubscriptionLevelRequest {
|
||||
bytes subscriberId = 1 [(require.exactlySize) = 32];
|
||||
bytes subscriber_id = 1 [(require.exactlySize) = 32];
|
||||
uint64 level = 2;
|
||||
string currency = 3;
|
||||
string idempotencyKey = 4;
|
||||
string idempotency_key = 4;
|
||||
}
|
||||
|
||||
// Information about a charge failure.
|
||||
@@ -308,33 +311,25 @@ message PaymentRequired {
|
||||
}
|
||||
|
||||
message SetSubscriptionLevelResponse {
|
||||
message SetSubscriptionLevelResult {
|
||||
uint64 level = 1;
|
||||
}
|
||||
|
||||
oneof response {
|
||||
SetSubscriptionLevelResult success = 1;
|
||||
google.protobuf.Empty success = 1;
|
||||
// The subscriber did not exist
|
||||
errors.NotFound subscriber_not_found = 2 [(tag.reason) = "subscriber_not_found"];
|
||||
// New payment processor does not match existing processor associated with
|
||||
// the subscription
|
||||
errors.FailedPrecondition subscription_processor_conflict = 3 [(tag.reason) = "subscription_processor_conflict"];
|
||||
// No payment method has been created for the subscriber
|
||||
errors.FailedPrecondition payment_method_not_set_up = 4 [(tag.reason) = "payment_method_not_set_up"];
|
||||
// The payment processor does not support this operation
|
||||
errors.FailedPrecondition unsupported_operation = 5 [(tag.reason) = "unsupported_operation"];
|
||||
// The requested level was invalid
|
||||
errors.FailedPrecondition unsupported_level = 6 [(tag.reason) = "unsupported_level"];
|
||||
// The requested currency was invalid
|
||||
errors.FailedPrecondition unsupported_currency = 7 [(tag.reason) = "unsupported_currency"];
|
||||
// The card could not be charged
|
||||
errors.FailedPrecondition payment_requires_action = 8 [(tag.reason) = "payment_requires_action"];
|
||||
// Cannot transition from existing level to the requested level
|
||||
errors.FailedPrecondition invalid_level_transition = 9 [(tag.reason) = "invalid_level_transition"];
|
||||
// The idempotency key was invalid or re-used with a modified request
|
||||
errors.FailedPrecondition invalid_idempotency_key = 10 [(tag.reason) = "invalid_idempotency_key"];
|
||||
// The payment failed; see charge failure details
|
||||
ChargeFailure charge_failure = 11 [(tag.reason) = "charge_failure"];
|
||||
// The request could not be applied in the subscriber's current state. This
|
||||
// typically indicates a client bug or an out-of-date client. Some examples:
|
||||
// - the client failed to first set up a payment method
|
||||
// - the requested level cannot be transitioned to from the existing level
|
||||
// - the payment needs additional authorization before processing
|
||||
// The FailedPrecondition will contain the specific reason for the failure.
|
||||
errors.FailedPrecondition failed_precondition = 3 [(tag.reason) = "failed_precondition"];
|
||||
// The request contained a currency or level that is not supported. The
|
||||
// violated constraint may be present in the product configuration, clients
|
||||
// can attempt a refresh of ProductConfiguration/GetConfiguration before
|
||||
// giving up.
|
||||
errors.FailedPrecondition invalid_selection = 4 [(tag.reason) = "invalid_selection"];
|
||||
// The payment method could not be charged. If the processor declined the
|
||||
// charge, charge_failure will be present.
|
||||
PaymentRequired payment_required = 5 [(tag.reason) = "payment_required"];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -346,7 +341,7 @@ message SetIapSubscriptionRequest {
|
||||
string purchase_token = 1 [(require.nonEmpty) = true];
|
||||
}
|
||||
|
||||
bytes subscriberId = 1 [(require.exactlySize) = 32];
|
||||
bytes subscriber_id = 1 [(require.exactlySize) = 32];
|
||||
oneof request {
|
||||
AppStorePurchase app_store = 2;
|
||||
PlayBillingPurchase play_billing = 3;
|
||||
@@ -367,7 +362,7 @@ message SetIapSubscriptionResponse {
|
||||
errors.FailedPrecondition subscription_processor_conflict = 3 [(tag.reason) = "subscription_processor_conflict"];
|
||||
// The subscription is not in a purchase state that grants the user an
|
||||
// entitlement
|
||||
errors.FailedPrecondition payment_required = 4 [(tag.reason) = "payment_required"];
|
||||
PaymentRequired payment_required = 4 [(tag.reason) = "payment_required"];
|
||||
// The provided purchase identifier is malformed or the identified
|
||||
// transaction is not supported for use at this endpoint
|
||||
errors.FailedPrecondition invalid_transaction = 5 [(tag.reason) = "invalid_transaction"];
|
||||
@@ -375,13 +370,13 @@ message SetIapSubscriptionResponse {
|
||||
}
|
||||
|
||||
message GetReceiptCredentialRequest {
|
||||
bytes subscriberId = 1 [(require.exactlySize) = 32];
|
||||
bytes receiptCredentialRequest = 2 [(require.exactlySize) = 97];
|
||||
bytes subscriber_id = 1 [(require.exactlySize) = 32];
|
||||
bytes receipt_credential_request = 2 [(require.exactlySize) = 97];
|
||||
}
|
||||
|
||||
message GetReceiptCredentialResponse {
|
||||
message GetReceiptCredentialResult {
|
||||
bytes receiptCredentialResponse = 1;
|
||||
bytes receipt_credential_response = 1;
|
||||
}
|
||||
|
||||
oneof response {
|
||||
@@ -398,7 +393,7 @@ message GetReceiptCredentialResponse {
|
||||
}
|
||||
|
||||
message GetSubscriptionInformationRequest {
|
||||
bytes subscriberId = 1 [(require.exactlySize) = 32];
|
||||
bytes subscriber_id = 1 [(require.exactlySize) = 32];
|
||||
}
|
||||
|
||||
message GetSubscriptionInformationResponse {
|
||||
|
||||
+6
-6
@@ -11,12 +11,12 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.whispersystems.textsecuregcm.asn.AsnInfoProviderImpl.ip4BytesToLong;
|
||||
import static org.whispersystems.textsecuregcm.asn.AsnInfoProviderImpl.ip6BytesToBigInteger;
|
||||
|
||||
import com.google.common.net.InetAddresses;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.math.BigInteger;
|
||||
import java.net.Inet4Address;
|
||||
import java.net.Inet6Address;
|
||||
import java.net.InetAddress;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class AsnInfoProviderImplTest {
|
||||
@@ -54,12 +54,12 @@ public class AsnInfoProviderImplTest {
|
||||
|
||||
@Test
|
||||
public void testBytesToLong() throws Exception {
|
||||
assertEquals(0x00000000ffffffffL, ip4BytesToLong((Inet4Address) InetAddress.getByName("255.255.255.255")));
|
||||
assertEquals(0x0000000000000001L, ip4BytesToLong((Inet4Address) InetAddress.getByName("0.0.0.1")));
|
||||
assertEquals(0x00000000ff00ff01L, ip4BytesToLong((Inet4Address) InetAddress.getByName("255.0.255.1")));
|
||||
assertEquals(0x00000000ffffffffL, ip4BytesToLong((Inet4Address) InetAddresses.forString("255.255.255.255")));
|
||||
assertEquals(0x0000000000000001L, ip4BytesToLong((Inet4Address) InetAddresses.forString("0.0.0.1")));
|
||||
assertEquals(0x00000000ff00ff01L, ip4BytesToLong((Inet4Address) InetAddresses.forString("255.0.255.1")));
|
||||
|
||||
final BigInteger start = ip6BytesToBigInteger((Inet6Address) InetAddress.getByName("2c0f:fff1:0:0:0:0:0:0"));
|
||||
final BigInteger end = ip6BytesToBigInteger((Inet6Address) InetAddress.getByName("fdff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"));
|
||||
final BigInteger start = ip6BytesToBigInteger((Inet6Address) InetAddresses.forString("2c0f:fff1:0:0:0:0:0:0"));
|
||||
final BigInteger end = ip6BytesToBigInteger((Inet6Address) InetAddresses.forString("fdff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"));
|
||||
assertTrue(start.compareTo(BigInteger.ZERO) >= 0);
|
||||
assertTrue(end.compareTo(BigInteger.ZERO) >= 0);
|
||||
assertTrue(start.compareTo(end) <= 0);
|
||||
|
||||
+2
-2
@@ -16,11 +16,11 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.github.tomakehurst.wiremock.junit5.WireMockExtension;
|
||||
import com.google.common.net.InetAddresses;
|
||||
import io.netty.resolver.dns.DnsNameResolver;
|
||||
import io.netty.util.concurrent.GlobalEventExecutor;
|
||||
import io.netty.util.concurrent.SucceededFuture;
|
||||
import java.io.IOException;
|
||||
import java.net.InetAddress;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
@@ -126,7 +126,7 @@ public class CloudflareTurnCredentialsManagerTest {
|
||||
|
||||
when(dnsResolver.resolveAll(TURN_HOSTNAME))
|
||||
.thenReturn(new SucceededFuture<>(GlobalEventExecutor.INSTANCE,
|
||||
List.of(InetAddress.getByName("127.0.0.1"), InetAddress.getByName("::1"))));
|
||||
List.of(InetAddresses.forString("127.0.0.1"), InetAddresses.forString("::1"))));
|
||||
|
||||
final TurnToken token = cloudflareTurnCredentialsManager.retrieveFromCloudflare(UUID.randomUUID());
|
||||
|
||||
|
||||
@@ -8,9 +8,13 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
|
||||
|
||||
import com.auth0.jwt.JWT;
|
||||
import com.auth0.jwt.JWTVerifier;
|
||||
import com.auth0.jwt.algorithms.Algorithm;
|
||||
import com.auth0.jwt.exceptions.IncorrectClaimException;
|
||||
import com.auth0.jwt.exceptions.TokenExpiredException;
|
||||
import com.auth0.jwt.interfaces.DecodedJWT;
|
||||
import com.auth0.jwt.interfaces.Verification;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.whispersystems.textsecuregcm.util.TestClock;
|
||||
@@ -20,63 +24,76 @@ class JwtGeneratorTest {
|
||||
private static final byte[] SECRET = TestRandomUtil.nextBytes(32);
|
||||
private static final String AUD = "test-audience";
|
||||
private static final String SUB = "test-key";
|
||||
private static final Duration EXPIRATION = Duration.ofHours(1);
|
||||
|
||||
private static Verification verifier() {
|
||||
return JWT.require(Algorithm.HMAC256(SECRET))
|
||||
.withAudience(AUD)
|
||||
.withSubject(SUB);
|
||||
}
|
||||
|
||||
private static DecodedJWT verify(final Verification verification, final TestClock clock, final String token) {
|
||||
return ((JWTVerifier.BaseVerification) verification).build(clock).verify(token);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void validToken() {
|
||||
final TestClock clock = TestClock.pinned(Instant.EPOCH);
|
||||
final JwtGenerator jwtGenerator = new JwtGenerator(SECRET, clock);
|
||||
final String token = jwtGenerator.generateJwt(AUD, SUB, _ -> {});
|
||||
final String token = jwtGenerator.generateJwt(AUD, SUB, EXPIRATION, _ -> {});
|
||||
|
||||
final DecodedJWT decoded = JWT.require(Algorithm.HMAC256(SECRET))
|
||||
.withAudience(AUD)
|
||||
.withSubject(SUB)
|
||||
.build().verify(token);
|
||||
assertThat(decoded.getIssuedAt()).isEqualTo(Instant.EPOCH);
|
||||
assertThat(decoded.getClaims()).containsOnlyKeys("aud", "sub", "iat");
|
||||
final DecodedJWT decoded = verify(verifier(), clock, token);
|
||||
assertThat(decoded.getIssuedAtAsInstant()).isEqualTo(Instant.EPOCH);
|
||||
assertThat(decoded.getExpiresAtAsInstant()).isEqualTo(Instant.EPOCH.plus(EXPIRATION));
|
||||
assertThat(decoded.getClaims()).containsOnlyKeys("aud", "sub", "iat", "exp");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void validClaims() {
|
||||
final TestClock clock = TestClock.pinned(Instant.EPOCH);
|
||||
final JwtGenerator jwtGenerator = new JwtGenerator(SECRET, clock);
|
||||
final String token = jwtGenerator.generateJwt(AUD, SUB, builder -> builder
|
||||
final String token = jwtGenerator.generateJwt(AUD, SUB, EXPIRATION, builder -> builder
|
||||
.withClaim("number", 17)
|
||||
.withClaim("string", "abc"));
|
||||
|
||||
final DecodedJWT decoded = JWT.require(Algorithm.HMAC256(SECRET))
|
||||
.withAudience(AUD)
|
||||
.withSubject(SUB)
|
||||
final DecodedJWT decoded = verify(verifier()
|
||||
.withClaim("number", 17)
|
||||
.withClaim("string", "abc")
|
||||
.build().verify(token);
|
||||
assertThat(decoded.getIssuedAt()).isEqualTo(Instant.EPOCH);
|
||||
assertThat(decoded.getClaims()).containsOnlyKeys("aud", "sub", "iat", "number", "string");
|
||||
.withClaim("string", "abc"), clock, token);
|
||||
assertThat(decoded.getIssuedAtAsInstant()).isEqualTo(Instant.EPOCH);
|
||||
assertThat(decoded.getClaims()).containsOnlyKeys("aud", "sub", "iat", "exp", "number", "string");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void badAudience() {
|
||||
final TestClock clock = TestClock.pinned(Instant.EPOCH);
|
||||
final JwtGenerator jwtGenerator = new JwtGenerator(SECRET, clock);
|
||||
final String token = jwtGenerator.generateJwt("bad-audience", SUB, _ -> {});
|
||||
final String token = jwtGenerator.generateJwt("bad-audience", SUB, EXPIRATION, _ -> {});
|
||||
|
||||
assertThatExceptionOfType(IncorrectClaimException.class).isThrownBy(() -> JWT.require(Algorithm.HMAC256(SECRET))
|
||||
.withAudience(AUD)
|
||||
.withSubject(SUB)
|
||||
.build().verify(token));
|
||||
assertThatExceptionOfType(IncorrectClaimException.class).isThrownBy(() -> verify(verifier(), clock, token));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void badCustomClaim() {
|
||||
final TestClock clock = TestClock.pinned(Instant.EPOCH);
|
||||
final JwtGenerator jwtGenerator = new JwtGenerator(SECRET, clock);
|
||||
final String token = jwtGenerator.generateJwt(AUD, SUB, builder -> builder
|
||||
final String token = jwtGenerator.generateJwt(AUD, SUB, EXPIRATION, builder -> builder
|
||||
.withClaim("number", 18));
|
||||
|
||||
assertThatExceptionOfType(IncorrectClaimException.class).isThrownBy(() -> JWT.require(Algorithm.HMAC256(SECRET))
|
||||
.withAudience(AUD)
|
||||
.withSubject(SUB)
|
||||
.withClaim("number", 17)
|
||||
.build().verify(token));
|
||||
assertThatExceptionOfType(IncorrectClaimException.class).isThrownBy(() -> verify(verifier()
|
||||
.withClaim("number", 17), clock, token));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void expiredToken() {
|
||||
final TestClock clock = TestClock.pinned(Instant.EPOCH);
|
||||
final JwtGenerator jwtGenerator = new JwtGenerator(SECRET, clock);
|
||||
final String token = jwtGenerator.generateJwt(AUD, SUB, EXPIRATION, _ -> {});
|
||||
|
||||
clock.pin(Instant.EPOCH.plus(EXPIRATION).minusSeconds(1));
|
||||
assertThat(verify(verifier(), clock, token).getSubject()).isEqualTo(SUB);
|
||||
|
||||
clock.pin(Instant.EPOCH.plus(EXPIRATION).plus(Duration.ofSeconds(1)));
|
||||
assertThatExceptionOfType(TokenExpiredException.class).isThrownBy(() -> verify(verifier(), clock, token));
|
||||
}
|
||||
|
||||
}
|
||||
+7
-9
@@ -6,15 +6,11 @@
|
||||
package org.whispersystems.textsecuregcm.backup;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatNoException;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Base64;
|
||||
import java.util.Map;
|
||||
import com.auth0.jwt.JWT;
|
||||
import com.auth0.jwt.JWTVerifier;
|
||||
import com.auth0.jwt.algorithms.Algorithm;
|
||||
import com.auth0.jwt.interfaces.DecodedJWT;
|
||||
import java.util.Map;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.whispersystems.textsecuregcm.attachments.TusConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.secrets.SecretBytes;
|
||||
@@ -28,7 +24,8 @@ public class Cdn3BackupCredentialGeneratorTest {
|
||||
public void uploadGenerator() {
|
||||
final Cdn3BackupCredentialGenerator generator = new Cdn3BackupCredentialGenerator(new TusConfiguration(
|
||||
new SecretBytes(SECRET),
|
||||
"https://example.org/upload"));
|
||||
"https://example.org/upload",
|
||||
TusConfiguration.DEFAULT_TOKEN_EXPIRATION));
|
||||
|
||||
final BackupUploadDescriptor messageBackupUploadDescriptor = generator.generateUpload("subdir/key", MAX_UPLOAD_LENGTH);
|
||||
assertThat(messageBackupUploadDescriptor.signedUploadLocation()).isEqualTo("https://example.org/upload/backups");
|
||||
@@ -42,14 +39,15 @@ public class Cdn3BackupCredentialGeneratorTest {
|
||||
.withClaim("scope", "write")
|
||||
.withClaim("maxLen", MAX_UPLOAD_LENGTH)
|
||||
.build().verify(token);
|
||||
assertThat(decoded.getClaims()).containsOnlyKeys("aud", "sub", "scope", "iat", "maxLen");
|
||||
assertThat(decoded.getClaims()).containsOnlyKeys("aud", "sub", "scope", "iat", "exp", "maxLen");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void readCredential() {
|
||||
final Cdn3BackupCredentialGenerator generator = new Cdn3BackupCredentialGenerator(new TusConfiguration(
|
||||
new SecretBytes(SECRET),
|
||||
"https://example.org/upload"));
|
||||
"https://example.org/upload",
|
||||
TusConfiguration.DEFAULT_TOKEN_EXPIRATION));
|
||||
|
||||
final Map<String, String> headers = generator.readHeaders("subdir");
|
||||
assertThat(headers).containsKey("Authorization");
|
||||
@@ -58,7 +56,7 @@ public class Cdn3BackupCredentialGeneratorTest {
|
||||
.withSubject("subdir")
|
||||
.withClaim("scope", "read")
|
||||
.build().verify(parseBearerToken(headers.get("Authorization")));
|
||||
assertThat(decoded.getClaims()).containsOnlyKeys("aud", "sub", "scope", "iat");
|
||||
assertThat(decoded.getClaims()).containsOnlyKeys("aud", "sub", "scope", "iat", "exp");
|
||||
}
|
||||
|
||||
private static String parseBearerToken(final String authHeader) {
|
||||
|
||||
+14
-16
@@ -613,15 +613,16 @@ public class ArchiveControllerTest {
|
||||
|
||||
static Stream<Arguments> messagesUploadForm() {
|
||||
return Stream.of(
|
||||
Arguments.of(Optional.empty(), true),
|
||||
Arguments.of(Optional.of(MAX_MESSAGE_BACKUP_SIZE), true),
|
||||
Arguments.of(Optional.of(MAX_MESSAGE_BACKUP_SIZE + 1), false)
|
||||
Arguments.of(Optional.empty(), 200),
|
||||
Arguments.of(Optional.of(-1L), 400),
|
||||
Arguments.of(Optional.of(MAX_MESSAGE_BACKUP_SIZE), 200),
|
||||
Arguments.of(Optional.of(MAX_MESSAGE_BACKUP_SIZE + 1), 413)
|
||||
);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
public void messagesUploadForm(Optional<Long> uploadLength, boolean expectSuccess) throws VerificationFailedException, BackupException {
|
||||
public void messagesUploadForm(Optional<Long> uploadLength, int expectedStatus) throws VerificationFailedException, BackupException {
|
||||
final BackupAuthCredentialPresentation presentation =
|
||||
backupAuthTestUtil.getPresentation(BackupLevel.PAID, messagesBackupKey, aci);
|
||||
when(backupManager.authenticateBackupUser(any(), any(), any()))
|
||||
@@ -637,28 +638,27 @@ public class ArchiveControllerTest {
|
||||
.header("X-Signal-ZK-Auth", Base64.getEncoder().encodeToString(presentation.serialize()))
|
||||
.header("X-Signal-ZK-Auth-Signature", "aaa")
|
||||
.get();
|
||||
if (expectSuccess) {
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
assertThat(response.getStatus()).isEqualTo(expectedStatus);
|
||||
if (200 == expectedStatus) {
|
||||
ArchiveController.UploadDescriptorResponse desc = response.readEntity(ArchiveController.UploadDescriptorResponse.class);
|
||||
assertThat(desc)
|
||||
.isEqualTo(new ArchiveController.UploadDescriptorResponse(3, "abc", Map.of("k", "v"), "example.org"));
|
||||
verify(backupManager).createMessageBackupUploadDescriptor(any(), eq(uploadLength.orElse(MAX_MESSAGE_BACKUP_SIZE)));
|
||||
} else {
|
||||
assertThat(response.getStatus()).isEqualTo(413);
|
||||
}
|
||||
}
|
||||
|
||||
static Stream<Arguments> mediaUploadForm() {
|
||||
return Stream.of(
|
||||
Arguments.of(Optional.empty(), true),
|
||||
Arguments.of(Optional.of(MAX_ATTACHMENT_SIZE), true),
|
||||
Arguments.of(Optional.of(MAX_ATTACHMENT_SIZE + 1), false)
|
||||
Arguments.of(Optional.empty(), 200),
|
||||
Arguments.of(Optional.of(-1L), 400),
|
||||
Arguments.of(Optional.of(MAX_ATTACHMENT_SIZE), 200),
|
||||
Arguments.of(Optional.of(MAX_ATTACHMENT_SIZE + 1), 413)
|
||||
);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
public void mediaUploadForm(Optional<Long> uploadLength, boolean expectSuccess) throws VerificationFailedException, BackupException, RateLimitExceededException {
|
||||
public void mediaUploadForm(Optional<Long> uploadLength, int expectedSuccess) throws VerificationFailedException, BackupException, RateLimitExceededException {
|
||||
final BackupAuthCredentialPresentation presentation =
|
||||
backupAuthTestUtil.getPresentation(BackupLevel.PAID, messagesBackupKey, aci);
|
||||
when(backupManager.authenticateBackupUser(any(), any(), any()))
|
||||
@@ -673,15 +673,13 @@ public class ArchiveControllerTest {
|
||||
.header("X-Signal-ZK-Auth", Base64.getEncoder().encodeToString(presentation.serialize()))
|
||||
.header("X-Signal-ZK-Auth-Signature", "aaa")
|
||||
.get();
|
||||
if (expectSuccess) {
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
assertThat(response.getStatus()).isEqualTo(expectedSuccess);
|
||||
if (200 == expectedSuccess) {
|
||||
final ArchiveController.UploadDescriptorResponse desc =
|
||||
response.readEntity(ArchiveController.UploadDescriptorResponse.class);
|
||||
assertThat(desc)
|
||||
.isEqualTo(new ArchiveController.UploadDescriptorResponse(3, "abc", Map.of("k", "v"), "example.org"));
|
||||
verify(backupManager).createTemporaryAttachmentUploadDescriptor(any(), eq(uploadLength.orElse(MAX_ATTACHMENT_SIZE)));
|
||||
} else {
|
||||
assertThat(response.getStatus()).isEqualTo(413);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -108,7 +108,7 @@ class AttachmentControllerV4Test {
|
||||
.addProvider(new RateLimitExceededExceptionMapper())
|
||||
.addProvider(new AttachmentControllerV4(RATE_LIMITERS,
|
||||
gcsAttachmentGenerator,
|
||||
new TusAttachmentGenerator(new TusConfiguration(new SecretBytes(TUS_SECRET), TUS_URL)),
|
||||
new TusAttachmentGenerator(new TusConfiguration(new SecretBytes(TUS_SECRET), TUS_URL, TusConfiguration.DEFAULT_TOKEN_EXPIRATION)),
|
||||
EXPERIMENT_MANAGER, MAX_UPLOAD_LENGTH))
|
||||
.build();
|
||||
} catch (IOException | InvalidKeyException | InvalidKeySpecException e) {
|
||||
|
||||
+51
-12
@@ -34,11 +34,11 @@ import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
import java.util.EnumSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.stream.Stream;
|
||||
import org.apache.commons.lang3.RandomStringUtils;
|
||||
import org.glassfish.jersey.server.ServerProperties;
|
||||
@@ -80,6 +80,7 @@ import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceSpec;
|
||||
import org.whispersystems.textsecuregcm.storage.LinkDeviceTokenAlreadyUsedException;
|
||||
import org.whispersystems.textsecuregcm.storage.PersistentTimer;
|
||||
@@ -216,7 +217,7 @@ class DeviceControllerTest {
|
||||
final Optional<ApnRegistrationId> apnRegistrationId,
|
||||
final Optional<GcmRegistrationId> gcmRegistrationId,
|
||||
final Optional<String> expectedApnsToken,
|
||||
final Optional<String> expectedGcmToken) throws LinkDeviceTokenAlreadyUsedException {
|
||||
final Optional<String> expectedGcmToken) throws LinkDeviceTokenAlreadyUsedException, DeviceLimitExceededException {
|
||||
|
||||
final Device existingDevice = mock(Device.class);
|
||||
when(existingDevice.getId()).thenReturn(Device.PRIMARY_ID);
|
||||
@@ -304,7 +305,7 @@ class DeviceControllerTest {
|
||||
void deviceDowngrade(@CartesianTest.Enum(mode = CartesianTest.Enum.Mode.EXCLUDE, names = "SPARSE_POST_QUANTUM_RATCHET") final DeviceCapability capability,
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean accountHasCapability,
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean requestHasCapability)
|
||||
throws LinkDeviceTokenAlreadyUsedException {
|
||||
throws LinkDeviceTokenAlreadyUsedException, DeviceLimitExceededException {
|
||||
|
||||
when(accountsManager.getByAccountIdentifier(AuthHelper.VALID_UUID)).thenReturn(Optional.of(account));
|
||||
when(accountsManager.addDevice(any(), any(), any()))
|
||||
@@ -360,7 +361,7 @@ class DeviceControllerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingRequiredCapability() throws LinkDeviceTokenAlreadyUsedException {
|
||||
void missingRequiredCapability() throws LinkDeviceTokenAlreadyUsedException, DeviceLimitExceededException {
|
||||
|
||||
when(accountsManager.getByAccountIdentifier(AuthHelper.VALID_UUID)).thenReturn(Optional.of(account));
|
||||
when(accountsManager.addDevice(any(), any(), any()))
|
||||
@@ -447,7 +448,7 @@ class DeviceControllerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void linkDeviceAtomicReusedToken() throws LinkDeviceTokenAlreadyUsedException {
|
||||
void linkDeviceAtomicReusedToken() throws LinkDeviceTokenAlreadyUsedException, DeviceLimitExceededException {
|
||||
final Device existingDevice = mock(Device.class);
|
||||
when(existingDevice.getId()).thenReturn(Device.PRIMARY_ID);
|
||||
when(account.getDevices()).thenReturn(List.of(existingDevice));
|
||||
@@ -492,6 +493,47 @@ class DeviceControllerTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void linkDeviceMaxDevices() throws LinkDeviceTokenAlreadyUsedException, DeviceLimitExceededException {
|
||||
final Device existingDevice = mock(Device.class);
|
||||
when(existingDevice.getId()).thenReturn(Device.PRIMARY_ID);
|
||||
when(account.getDevices()).thenReturn(List.of(existingDevice));
|
||||
|
||||
final ECKeyPair aciIdentityKeyPair = ECKeyPair.generate();
|
||||
|
||||
final ECSignedPreKey aciSignedPreKey = KeysHelper.signedECPreKey(1, aciIdentityKeyPair);
|
||||
final KEMSignedPreKey aciPqLastResortPreKey = KeysHelper.signedKEMPreKey(3, aciIdentityKeyPair);
|
||||
|
||||
when(account.getAccountIdentityKey()).thenReturn(new IdentityKey(aciIdentityKeyPair.getPublicKey()));
|
||||
when(account.getPhoneNumberIdentityKey()).thenReturn(Optional.empty());
|
||||
|
||||
when(accountsManager.checkDeviceLinkingToken(anyString())).thenReturn(Optional.of(AuthHelper.VALID_UUID));
|
||||
|
||||
when(accountsManager.addDevice(any(), any(), any()))
|
||||
.thenThrow(new DeviceLimitExceededException(AccountsManager.MAX_DEVICES, AccountsManager.MAX_DEVICES));
|
||||
|
||||
final DeviceAttributes deviceAttributes = new DeviceAttributes(true, 1234, null, null,
|
||||
DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES);
|
||||
|
||||
final LinkDeviceRequest request = new LinkDeviceRequest("link-device-token",
|
||||
deviceAttributes,
|
||||
new DeviceActivationRequest(aciSignedPreKey, Optional.empty(), aciPqLastResortPreKey, Optional.empty(), Optional.empty(), Optional.empty()));
|
||||
|
||||
try (final Response response = resources.getJerseyTest()
|
||||
.target("/v1/devices/link")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getProvisioningAuthHeader(AuthHelper.VALID_NUMBER, "password1"))
|
||||
.put(Entity.entity(request, MediaType.APPLICATION_JSON_TYPE))) {
|
||||
|
||||
assertEquals(411, response.getStatus());
|
||||
|
||||
final Map<?, ?> details = response.readEntity(Map.class);
|
||||
assertEquals(Map.of("current", AccountsManager.MAX_DEVICES, "max", AccountsManager.MAX_DEVICES), details);
|
||||
}
|
||||
|
||||
verify(accountsManager).addDevice(eq(AuthHelper.VALID_UUID), any(), eq("link-device-token"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void linkDeviceAtomicWithVerificationTokenUsed() {
|
||||
|
||||
@@ -538,7 +580,7 @@ class DeviceControllerTest {
|
||||
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
|
||||
void linkDeviceAtomicConflictingChannel(final boolean fetchesMessages,
|
||||
final Optional<ApnRegistrationId> apnRegistrationId,
|
||||
final Optional<GcmRegistrationId> gcmRegistrationId) {
|
||||
final Optional<GcmRegistrationId> gcmRegistrationId) throws Exception {
|
||||
when(accountsManager.getByAccountIdentifier(AuthHelper.VALID_UUID)).thenReturn(Optional.of(account));
|
||||
when(accountsManager.generateLinkDeviceToken(any())).thenReturn("test");
|
||||
|
||||
@@ -849,7 +891,7 @@ class DeviceControllerTest {
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void linkDeviceRegistrationId(final int registrationId, final int pniRegistrationId, final int expectedStatusCode)
|
||||
throws LinkDeviceTokenAlreadyUsedException {
|
||||
throws LinkDeviceTokenAlreadyUsedException, DeviceLimitExceededException {
|
||||
final Device existingDevice = mock(Device.class);
|
||||
when(existingDevice.getId()).thenReturn(Device.PRIMARY_ID);
|
||||
when(account.getDevices()).thenReturn(List.of(existingDevice));
|
||||
@@ -955,12 +997,9 @@ class DeviceControllerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void maxDevicesTest() throws LinkDeviceTokenAlreadyUsedException {
|
||||
final List<Device> devices = IntStream.range(0, DeviceController.MAX_DEVICES + 1)
|
||||
.mapToObj(_ -> mock(Device.class))
|
||||
.toList();
|
||||
void generateTokenMaxDevicesTest() throws LinkDeviceTokenAlreadyUsedException, DeviceLimitExceededException {
|
||||
|
||||
when(account.getDevices()).thenReturn(devices);
|
||||
when(accountsManager.generateLinkDeviceToken(any())).thenThrow(new DeviceLimitExceededException(5, 5));
|
||||
|
||||
Response response = resources.getJerseyTest()
|
||||
.target("/v1/devices/provisioning/code")
|
||||
|
||||
+2
-2
@@ -51,7 +51,7 @@ import org.whispersystems.textsecuregcm.purchases.PaymentDetails;
|
||||
import org.whispersystems.textsecuregcm.purchases.PaymentMethod;
|
||||
import org.whispersystems.textsecuregcm.purchases.PaymentProvider;
|
||||
import org.whispersystems.textsecuregcm.purchases.PurchaseException;
|
||||
import org.whispersystems.textsecuregcm.purchases.PurchaseInvalidAmountException;
|
||||
import org.whispersystems.textsecuregcm.purchases.PurchaseAmountTooLargeException;
|
||||
import org.whispersystems.textsecuregcm.purchases.PurchasePaymentRequiredException;
|
||||
import org.whispersystems.textsecuregcm.purchases.PurchaseProcessorException;
|
||||
import org.whispersystems.textsecuregcm.purchases.ReceiptLevel;
|
||||
@@ -180,7 +180,7 @@ class OneTimeDonationControllerTest extends AbstractV1SubscriptionControllerTest
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void testCreateBoostPaymentIntent(final boolean donationPermitSpendOk) throws PurchaseInvalidAmountException {
|
||||
void testCreateBoostPaymentIntent(final boolean donationPermitSpendOk) throws PurchaseAmountTooLargeException {
|
||||
when(DONATION_PERMITS.spend(any(byte[].class), any(Instant.class))).thenReturn(donationPermitSpendOk);
|
||||
|
||||
when(STRIPE_MANAGER.getSupportedCurrenciesForPaymentMethod(PaymentMethod.CARD))
|
||||
|
||||
-191
@@ -1,191 +0,0 @@
|
||||
package org.whispersystems.textsecuregcm.experiment;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import reactor.core.publisher.Flux;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
abstract class IdleDevicePushNotificationExperimentTest {
|
||||
|
||||
protected static final Instant CURRENT_TIME = Instant.now();
|
||||
|
||||
protected abstract IdleDevicePushNotificationExperiment getExperiment();
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void hasPushToken(final Device device, final boolean expectHasPushToken) {
|
||||
assertEquals(expectHasPushToken, getExperiment().hasPushToken(device));
|
||||
}
|
||||
|
||||
private static List<Arguments> hasPushToken() {
|
||||
final List<Arguments> arguments = new ArrayList<>();
|
||||
|
||||
{
|
||||
// No token at all
|
||||
final Device device = mock(Device.class);
|
||||
|
||||
arguments.add(Arguments.of(device, false));
|
||||
}
|
||||
|
||||
{
|
||||
// FCM token
|
||||
final Device device = mock(Device.class);
|
||||
when(device.getGcmId()).thenReturn("fcm-token");
|
||||
|
||||
arguments.add(Arguments.of(device, true));
|
||||
}
|
||||
|
||||
{
|
||||
// APNs token
|
||||
final Device device = mock(Device.class);
|
||||
when(device.getApnId()).thenReturn("apns-token");
|
||||
|
||||
arguments.add(Arguments.of(device, true));
|
||||
}
|
||||
|
||||
return arguments;
|
||||
}
|
||||
|
||||
@Test
|
||||
void getState() {
|
||||
final IdleDevicePushNotificationExperiment experiment = getExperiment();
|
||||
|
||||
assertEquals(DeviceLastSeenState.MISSING_DEVICE_STATE, experiment.getState(null, null));
|
||||
assertEquals(DeviceLastSeenState.MISSING_DEVICE_STATE, experiment.getState(mock(Account.class), null));
|
||||
|
||||
final int registrationId = 123;
|
||||
|
||||
{
|
||||
final Device apnsDevice = mock(Device.class);
|
||||
when(apnsDevice.getApnId()).thenReturn("apns-token");
|
||||
when(apnsDevice.getAccountRegistrationId()).thenReturn(registrationId);
|
||||
when(apnsDevice.getLastSeen()).thenReturn(CURRENT_TIME.toEpochMilli());
|
||||
|
||||
assertEquals(
|
||||
new DeviceLastSeenState(true, registrationId, true, CURRENT_TIME.toEpochMilli(), DeviceLastSeenState.PushTokenType.APNS),
|
||||
experiment.getState(mock(Account.class), apnsDevice));
|
||||
}
|
||||
|
||||
{
|
||||
final Device fcmDevice = mock(Device.class);
|
||||
when(fcmDevice.getGcmId()).thenReturn("fcm-token");
|
||||
when(fcmDevice.getAccountRegistrationId()).thenReturn(registrationId);
|
||||
when(fcmDevice.getLastSeen()).thenReturn(CURRENT_TIME.toEpochMilli());
|
||||
|
||||
assertEquals(
|
||||
new DeviceLastSeenState(true, registrationId, true, CURRENT_TIME.toEpochMilli(), DeviceLastSeenState.PushTokenType.FCM),
|
||||
experiment.getState(mock(Account.class), fcmDevice));
|
||||
}
|
||||
|
||||
{
|
||||
final Device noTokenDevice = mock(Device.class);
|
||||
when(noTokenDevice.getAccountRegistrationId()).thenReturn(registrationId);
|
||||
when(noTokenDevice.getLastSeen()).thenReturn(CURRENT_TIME.toEpochMilli());
|
||||
|
||||
assertEquals(
|
||||
new DeviceLastSeenState(true, registrationId, false, CURRENT_TIME.toEpochMilli(), null),
|
||||
experiment.getState(mock(Account.class), noTokenDevice));
|
||||
}
|
||||
}
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void getPopulation(final boolean inExperimentGroup,
|
||||
final DeviceLastSeenState.PushTokenType tokenType,
|
||||
final IdleDevicePushNotificationExperiment.Population expectedPopulation) {
|
||||
|
||||
final DeviceLastSeenState state = new DeviceLastSeenState(true, 0, true, 0, tokenType);
|
||||
final PushNotificationExperimentSample<DeviceLastSeenState> sample =
|
||||
new PushNotificationExperimentSample<>(UUID.randomUUID(), Device.PRIMARY_ID, inExperimentGroup, state, state);
|
||||
|
||||
assertEquals(expectedPopulation, IdleDevicePushNotificationExperiment.getPopulation(sample));
|
||||
}
|
||||
|
||||
private static List<Arguments> getPopulation() {
|
||||
return List.of(
|
||||
Arguments.of(true, DeviceLastSeenState.PushTokenType.APNS,
|
||||
IdleDevicePushNotificationExperiment.Population.APNS_EXPERIMENT),
|
||||
|
||||
Arguments.of(false, DeviceLastSeenState.PushTokenType.APNS,
|
||||
IdleDevicePushNotificationExperiment.Population.APNS_CONTROL),
|
||||
|
||||
Arguments.of(true, DeviceLastSeenState.PushTokenType.FCM,
|
||||
IdleDevicePushNotificationExperiment.Population.FCM_EXPERIMENT),
|
||||
|
||||
Arguments.of(false, DeviceLastSeenState.PushTokenType.FCM,
|
||||
IdleDevicePushNotificationExperiment.Population.FCM_CONTROL)
|
||||
);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void getOutcome(final DeviceLastSeenState initialState,
|
||||
final DeviceLastSeenState finalState,
|
||||
final IdleDevicePushNotificationExperiment.Outcome expectedOutcome) {
|
||||
|
||||
final PushNotificationExperimentSample<DeviceLastSeenState> sample =
|
||||
new PushNotificationExperimentSample<>(UUID.randomUUID(), Device.PRIMARY_ID, true, initialState, finalState);
|
||||
|
||||
assertEquals(expectedOutcome, IdleDevicePushNotificationExperiment.getOutcome(sample));
|
||||
}
|
||||
|
||||
private static List<Arguments> getOutcome() {
|
||||
return List.of(
|
||||
// Device no longer exists
|
||||
Arguments.of(
|
||||
new DeviceLastSeenState(true, 0, true, 0, DeviceLastSeenState.PushTokenType.APNS),
|
||||
DeviceLastSeenState.MISSING_DEVICE_STATE,
|
||||
IdleDevicePushNotificationExperiment.Outcome.DELETED
|
||||
),
|
||||
|
||||
// Device re-registered (i.e. registration ID changed)
|
||||
Arguments.of(
|
||||
new DeviceLastSeenState(true, 123, true, 0, DeviceLastSeenState.PushTokenType.APNS),
|
||||
new DeviceLastSeenState(true, 1234, true, 1, DeviceLastSeenState.PushTokenType.APNS),
|
||||
IdleDevicePushNotificationExperiment.Outcome.DELETED
|
||||
),
|
||||
|
||||
// Device has lost push tokens
|
||||
Arguments.of(
|
||||
new DeviceLastSeenState(true, 0, true, 0, DeviceLastSeenState.PushTokenType.APNS),
|
||||
new DeviceLastSeenState(true, 0, false, 0, DeviceLastSeenState.PushTokenType.APNS),
|
||||
IdleDevicePushNotificationExperiment.Outcome.UNINSTALLED
|
||||
),
|
||||
|
||||
// Device reactivated
|
||||
Arguments.of(
|
||||
new DeviceLastSeenState(true, 0, true, 0, DeviceLastSeenState.PushTokenType.APNS),
|
||||
new DeviceLastSeenState(true, 0, true, 1, DeviceLastSeenState.PushTokenType.APNS),
|
||||
IdleDevicePushNotificationExperiment.Outcome.REACTIVATED
|
||||
),
|
||||
|
||||
// No change
|
||||
Arguments.of(
|
||||
new DeviceLastSeenState(true, 0, true, 0, DeviceLastSeenState.PushTokenType.APNS),
|
||||
new DeviceLastSeenState(true, 0, true, 0, DeviceLastSeenState.PushTokenType.APNS),
|
||||
IdleDevicePushNotificationExperiment.Outcome.UNCHANGED
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void analyzeResults() {
|
||||
assertDoesNotThrow(() -> getExperiment().analyzeResults(
|
||||
Flux.just(new PushNotificationExperimentSample<>(UUID.randomUUID(), Device.PRIMARY_ID, true,
|
||||
new DeviceLastSeenState(true, 0, true, 0, DeviceLastSeenState.PushTokenType.APNS),
|
||||
new DeviceLastSeenState(true, 0, true, 0, DeviceLastSeenState.PushTokenType.APNS)))));
|
||||
}
|
||||
}
|
||||
-304
@@ -1,304 +0,0 @@
|
||||
package org.whispersystems.textsecuregcm.experiment;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import java.time.Clock;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import java.util.stream.Collectors;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamoDbExtension;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamoDbExtensionSchema;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
|
||||
import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.GetItemResponse;
|
||||
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.QueryResponse;
|
||||
import software.amazon.awssdk.services.dynamodb.model.Select;
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
class PushNotificationExperimentSamplesTest {
|
||||
|
||||
private PushNotificationExperimentSamples pushNotificationExperimentSamples;
|
||||
|
||||
@RegisterExtension
|
||||
public static final DynamoDbExtension DYNAMO_DB_EXTENSION =
|
||||
new DynamoDbExtension(DynamoDbExtensionSchema.Tables.PUSH_NOTIFICATION_EXPERIMENT_SAMPLES);
|
||||
|
||||
private record TestDeviceState(int bounciness) {
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
pushNotificationExperimentSamples =
|
||||
new PushNotificationExperimentSamples(DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(),
|
||||
DynamoDbExtensionSchema.Tables.PUSH_NOTIFICATION_EXPERIMENT_SAMPLES.tableName(),
|
||||
Clock.systemUTC());
|
||||
}
|
||||
|
||||
@Test
|
||||
void recordInitialState() throws JsonProcessingException {
|
||||
final String experimentName = "test-experiment";
|
||||
final UUID accountIdentifier = UUID.randomUUID();
|
||||
final byte deviceId = (byte) ThreadLocalRandom.current().nextInt(Device.MAXIMUM_DEVICE_ID);
|
||||
final boolean inExperimentGroup = ThreadLocalRandom.current().nextBoolean();
|
||||
final int bounciness = ThreadLocalRandom.current().nextInt();
|
||||
|
||||
assertTrue(pushNotificationExperimentSamples.recordInitialState(accountIdentifier,
|
||||
deviceId,
|
||||
experimentName,
|
||||
inExperimentGroup,
|
||||
new TestDeviceState(bounciness))
|
||||
.join(),
|
||||
"Attempt to record an initial state should succeed for entirely new records");
|
||||
|
||||
assertEquals(new PushNotificationExperimentSample<>(accountIdentifier, deviceId, inExperimentGroup, new TestDeviceState(bounciness), null),
|
||||
getSample(accountIdentifier, deviceId, experimentName, TestDeviceState.class));
|
||||
|
||||
assertTrue(pushNotificationExperimentSamples.recordInitialState(accountIdentifier,
|
||||
deviceId,
|
||||
experimentName,
|
||||
inExperimentGroup,
|
||||
new TestDeviceState(bounciness))
|
||||
.join(),
|
||||
"Attempt to re-record an initial state should succeed for existing-but-unchanged records");
|
||||
|
||||
assertEquals(new PushNotificationExperimentSample<>(accountIdentifier, deviceId, inExperimentGroup, new TestDeviceState(bounciness), null),
|
||||
getSample(accountIdentifier, deviceId, experimentName, TestDeviceState.class),
|
||||
"Recorded initial state should be unchanged after repeated write");
|
||||
|
||||
assertFalse(pushNotificationExperimentSamples.recordInitialState(accountIdentifier,
|
||||
deviceId,
|
||||
experimentName,
|
||||
inExperimentGroup,
|
||||
new TestDeviceState(bounciness + 1))
|
||||
.join(),
|
||||
"Attempt to record a conflicting initial state should fail");
|
||||
|
||||
assertEquals(new PushNotificationExperimentSample<>(accountIdentifier, deviceId, inExperimentGroup, new TestDeviceState(bounciness), null),
|
||||
getSample(accountIdentifier, deviceId, experimentName, TestDeviceState.class),
|
||||
"Recorded initial state should be unchanged after unsuccessful write");
|
||||
|
||||
assertFalse(pushNotificationExperimentSamples.recordInitialState(accountIdentifier,
|
||||
deviceId,
|
||||
experimentName,
|
||||
!inExperimentGroup,
|
||||
new TestDeviceState(bounciness))
|
||||
.join(),
|
||||
"Attempt to record a new group assignment should fail");
|
||||
|
||||
assertEquals(new PushNotificationExperimentSample<>(accountIdentifier, deviceId, inExperimentGroup, new TestDeviceState(bounciness), null),
|
||||
getSample(accountIdentifier, deviceId, experimentName, TestDeviceState.class),
|
||||
"Recorded initial state should be unchanged after unsuccessful write");
|
||||
|
||||
final int finalBounciness = bounciness + 17;
|
||||
|
||||
pushNotificationExperimentSamples.recordFinalState(accountIdentifier,
|
||||
deviceId,
|
||||
experimentName,
|
||||
new TestDeviceState(finalBounciness))
|
||||
.join();
|
||||
|
||||
assertFalse(pushNotificationExperimentSamples.recordInitialState(accountIdentifier,
|
||||
deviceId,
|
||||
experimentName,
|
||||
inExperimentGroup,
|
||||
new TestDeviceState(bounciness))
|
||||
.join(),
|
||||
"Attempt to record an initial state should fail for samples with final states");
|
||||
|
||||
assertEquals(new PushNotificationExperimentSample<>(accountIdentifier, deviceId, inExperimentGroup, new TestDeviceState(bounciness), new TestDeviceState(finalBounciness)),
|
||||
getSample(accountIdentifier, deviceId, experimentName, TestDeviceState.class),
|
||||
"Recorded initial state should be unchanged after unsuccessful write");
|
||||
}
|
||||
|
||||
@Test
|
||||
void recordFinalState() throws JsonProcessingException {
|
||||
final String experimentName = "test-experiment";
|
||||
final UUID accountIdentifier = UUID.randomUUID();
|
||||
final byte deviceId = (byte) ThreadLocalRandom.current().nextInt(Device.MAXIMUM_DEVICE_ID);
|
||||
final boolean inExperimentGroup = ThreadLocalRandom.current().nextBoolean();
|
||||
final int initialBounciness = ThreadLocalRandom.current().nextInt();
|
||||
final int finalBounciness = initialBounciness + 17;
|
||||
|
||||
{
|
||||
pushNotificationExperimentSamples.recordInitialState(accountIdentifier,
|
||||
deviceId,
|
||||
experimentName,
|
||||
inExperimentGroup,
|
||||
new TestDeviceState(initialBounciness))
|
||||
.join();
|
||||
|
||||
final PushNotificationExperimentSample<TestDeviceState> returnedSample =
|
||||
pushNotificationExperimentSamples.recordFinalState(accountIdentifier,
|
||||
deviceId,
|
||||
experimentName,
|
||||
new TestDeviceState(finalBounciness))
|
||||
.join();
|
||||
|
||||
final PushNotificationExperimentSample<TestDeviceState> expectedSample =
|
||||
new PushNotificationExperimentSample<>(accountIdentifier, deviceId, inExperimentGroup,
|
||||
new TestDeviceState(initialBounciness),
|
||||
new TestDeviceState(finalBounciness));
|
||||
|
||||
assertEquals(expectedSample, returnedSample,
|
||||
"Attempt to update existing sample without final state should succeed");
|
||||
|
||||
assertEquals(expectedSample, getSample(accountIdentifier, deviceId, experimentName, TestDeviceState.class),
|
||||
"Attempt to update existing sample without final state should be persisted");
|
||||
}
|
||||
|
||||
assertThrows(CompletionException.class, () -> pushNotificationExperimentSamples.recordFinalState(accountIdentifier,
|
||||
(byte) (deviceId + 1),
|
||||
experimentName,
|
||||
new TestDeviceState(finalBounciness))
|
||||
.join(),
|
||||
"Attempts to record a final state without an initial state should fail");
|
||||
}
|
||||
|
||||
@SuppressWarnings("SameParameterValue")
|
||||
private <T> PushNotificationExperimentSample<T> getSample(final UUID accountIdentifier,
|
||||
final byte deviceId,
|
||||
final String experimentName,
|
||||
final Class<T> stateClass) throws JsonProcessingException {
|
||||
|
||||
final GetItemResponse response = DYNAMO_DB_EXTENSION.getDynamoDbClient().getItem(GetItemRequest.builder()
|
||||
.tableName(DynamoDbExtensionSchema.Tables.PUSH_NOTIFICATION_EXPERIMENT_SAMPLES.tableName())
|
||||
.key(Map.of(
|
||||
PushNotificationExperimentSamples.KEY_EXPERIMENT_NAME, AttributeValue.fromS(experimentName),
|
||||
PushNotificationExperimentSamples.ATTR_ACI_AND_DEVICE_ID, PushNotificationExperimentSamples.buildSortKey(accountIdentifier, deviceId)))
|
||||
.build());
|
||||
|
||||
final boolean inExperimentGroup =
|
||||
response.item().get(PushNotificationExperimentSamples.ATTR_IN_EXPERIMENT_GROUP).bool();
|
||||
|
||||
final T initialState =
|
||||
SystemMapper.jsonMapper().readValue(response.item().get(PushNotificationExperimentSamples.ATTR_INITIAL_STATE).s(), stateClass);
|
||||
|
||||
@Nullable final T finalState = response.item().containsKey(PushNotificationExperimentSamples.ATTR_FINAL_STATE)
|
||||
? SystemMapper.jsonMapper().readValue(response.item().get(PushNotificationExperimentSamples.ATTR_FINAL_STATE).s(), stateClass)
|
||||
: null;
|
||||
|
||||
return new PushNotificationExperimentSample<>(accountIdentifier, deviceId, inExperimentGroup, initialState, finalState);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getSamples() throws JsonProcessingException {
|
||||
final String experimentName = "test-experiment";
|
||||
final UUID initialSampleAccountIdentifier = UUID.randomUUID();
|
||||
final byte initialSampleDeviceId = (byte) ThreadLocalRandom.current().nextInt(Device.MAXIMUM_DEVICE_ID);
|
||||
final boolean initialSampleInExperimentGroup = ThreadLocalRandom.current().nextBoolean();
|
||||
|
||||
final UUID finalSampleAccountIdentifier = UUID.randomUUID();
|
||||
final byte finalSampleDeviceId = (byte) ThreadLocalRandom.current().nextInt(Device.MAXIMUM_DEVICE_ID);
|
||||
final boolean finalSampleInExperimentGroup = ThreadLocalRandom.current().nextBoolean();
|
||||
|
||||
final int initialBounciness = ThreadLocalRandom.current().nextInt();
|
||||
final int finalBounciness = initialBounciness + 17;
|
||||
|
||||
pushNotificationExperimentSamples.recordInitialState(initialSampleAccountIdentifier,
|
||||
initialSampleDeviceId,
|
||||
experimentName,
|
||||
initialSampleInExperimentGroup,
|
||||
new TestDeviceState(initialBounciness))
|
||||
.join();
|
||||
|
||||
pushNotificationExperimentSamples.recordInitialState(finalSampleAccountIdentifier,
|
||||
finalSampleDeviceId,
|
||||
experimentName,
|
||||
finalSampleInExperimentGroup,
|
||||
new TestDeviceState(initialBounciness))
|
||||
.join();
|
||||
|
||||
pushNotificationExperimentSamples.recordFinalState(finalSampleAccountIdentifier,
|
||||
finalSampleDeviceId,
|
||||
experimentName,
|
||||
new TestDeviceState(finalBounciness))
|
||||
.join();
|
||||
|
||||
pushNotificationExperimentSamples.recordInitialState(UUID.randomUUID(),
|
||||
(byte) ThreadLocalRandom.current().nextInt(Device.MAXIMUM_DEVICE_ID),
|
||||
experimentName + "-different",
|
||||
ThreadLocalRandom.current().nextBoolean(),
|
||||
new TestDeviceState(ThreadLocalRandom.current().nextInt()))
|
||||
.join();
|
||||
|
||||
final Set<PushNotificationExperimentSample<TestDeviceState>> expectedSamples = Set.of(
|
||||
new PushNotificationExperimentSample<>(initialSampleAccountIdentifier,
|
||||
initialSampleDeviceId,
|
||||
initialSampleInExperimentGroup,
|
||||
new TestDeviceState(initialBounciness),
|
||||
null),
|
||||
|
||||
new PushNotificationExperimentSample<>(finalSampleAccountIdentifier,
|
||||
finalSampleDeviceId,
|
||||
finalSampleInExperimentGroup,
|
||||
new TestDeviceState(initialBounciness),
|
||||
new TestDeviceState(finalBounciness)));
|
||||
|
||||
assertEquals(expectedSamples,
|
||||
pushNotificationExperimentSamples.getSamples(experimentName, TestDeviceState.class).collect(Collectors.toSet()).block());
|
||||
}
|
||||
|
||||
@Test
|
||||
void discardSamples() throws JsonProcessingException {
|
||||
final String discardSamplesExperimentName = "discard-experiment";
|
||||
final String retainSamplesExperimentName = "retain-experiment";
|
||||
final int sampleCount = 16;
|
||||
|
||||
for (int i = 0; i < sampleCount; i++) {
|
||||
pushNotificationExperimentSamples.recordInitialState(UUID.randomUUID(),
|
||||
Device.PRIMARY_ID,
|
||||
discardSamplesExperimentName,
|
||||
ThreadLocalRandom.current().nextBoolean(),
|
||||
new TestDeviceState(ThreadLocalRandom.current().nextInt()))
|
||||
.join();
|
||||
|
||||
pushNotificationExperimentSamples.recordInitialState(UUID.randomUUID(),
|
||||
Device.PRIMARY_ID,
|
||||
retainSamplesExperimentName,
|
||||
ThreadLocalRandom.current().nextBoolean(),
|
||||
new TestDeviceState(ThreadLocalRandom.current().nextInt()))
|
||||
.join();
|
||||
}
|
||||
|
||||
pushNotificationExperimentSamples.discardSamples(discardSamplesExperimentName, 1).join();
|
||||
|
||||
{
|
||||
final QueryResponse queryResponse = DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient().query(QueryRequest.builder()
|
||||
.tableName(DynamoDbExtensionSchema.Tables.PUSH_NOTIFICATION_EXPERIMENT_SAMPLES.tableName())
|
||||
.keyConditionExpression("#experiment = :experiment")
|
||||
.expressionAttributeNames(Map.of("#experiment", PushNotificationExperimentSamples.KEY_EXPERIMENT_NAME))
|
||||
.expressionAttributeValues(Map.of(":experiment", AttributeValue.fromS(discardSamplesExperimentName)))
|
||||
.select(Select.COUNT)
|
||||
.build())
|
||||
.join();
|
||||
|
||||
assertEquals(0, queryResponse.count());
|
||||
}
|
||||
|
||||
{
|
||||
final QueryResponse queryResponse = DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient().query(QueryRequest.builder()
|
||||
.tableName(DynamoDbExtensionSchema.Tables.PUSH_NOTIFICATION_EXPERIMENT_SAMPLES.tableName())
|
||||
.keyConditionExpression("#experiment = :experiment")
|
||||
.expressionAttributeNames(Map.of("#experiment", PushNotificationExperimentSamples.KEY_EXPERIMENT_NAME))
|
||||
.expressionAttributeValues(Map.of(":experiment", AttributeValue.fromS(retainSamplesExperimentName)))
|
||||
.select(Select.COUNT)
|
||||
.build())
|
||||
.join();
|
||||
|
||||
assertEquals(sampleCount, queryResponse.count());
|
||||
}
|
||||
}
|
||||
}
|
||||
+16
-3
@@ -14,7 +14,6 @@ import io.dropwizard.core.Configuration;
|
||||
import io.dropwizard.core.setup.Environment;
|
||||
import io.dropwizard.testing.DropwizardTestSupport;
|
||||
import io.dropwizard.testing.junit5.DropwizardAppExtension;
|
||||
import io.dropwizard.testing.junit5.DropwizardExtensionsSupport;
|
||||
import io.grpc.ManagedChannel;
|
||||
import io.grpc.Server;
|
||||
import io.grpc.Status;
|
||||
@@ -29,11 +28,13 @@ import java.util.Collections;
|
||||
import java.util.EnumSet;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.junit.jupiter.api.TestInstance;
|
||||
import org.signal.chat.rpc.EchoRequest;
|
||||
import org.signal.chat.rpc.EchoServiceGrpc;
|
||||
import org.whispersystems.textsecuregcm.grpc.EchoServiceImpl;
|
||||
@@ -42,7 +43,6 @@ import org.whispersystems.textsecuregcm.grpc.MockRequestAttributesInterceptor;
|
||||
import org.whispersystems.textsecuregcm.grpc.RequestAttributes;
|
||||
import org.whispersystems.textsecuregcm.util.InetAddressRange;
|
||||
|
||||
@ExtendWith(DropwizardExtensionsSupport.class)
|
||||
class ExternalRequestFilterTest {
|
||||
|
||||
@Nested
|
||||
@@ -118,11 +118,24 @@ class ExternalRequestFilterTest {
|
||||
private ManagedChannel channel;
|
||||
|
||||
@Nested
|
||||
// The DropwizardAppExtension is heavy, but the field can't be static because it uses `abstract` methods. Instead,
|
||||
// use PER_CLASS and manage its lifecycle manually, rather than with `DropwizardExtensionSupport`.
|
||||
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
|
||||
class Http {
|
||||
|
||||
private final DropwizardAppExtension<TestConfiguration> DROPWIZARD_APP_EXTENSION =
|
||||
new DropwizardAppExtension<>(getTestSupport());
|
||||
|
||||
@BeforeAll
|
||||
void setUp() throws Exception {
|
||||
DROPWIZARD_APP_EXTENSION.before();
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
void tearDown() {
|
||||
DROPWIZARD_APP_EXTENSION.after();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRestricted() {
|
||||
Client client = DROPWIZARD_APP_EXTENSION.client();
|
||||
|
||||
+1
-1
@@ -86,7 +86,7 @@ class AttachmentsGrpcServiceTest extends
|
||||
final GcsAttachmentGenerator gcsAttachmentGenerator = new GcsAttachmentGenerator(
|
||||
"some-cdn.signal.org", "signal@example.com", "/attach-here", gcsPrivateKeyPem);
|
||||
final TusAttachmentGenerator tusAttachmentGenerator =
|
||||
new TusAttachmentGenerator(new TusConfiguration(new SecretBytes(TUS_SECRET), TUS_URL));
|
||||
new TusAttachmentGenerator(new TusConfiguration(new SecretBytes(TUS_SECRET), TUS_URL, TusConfiguration.DEFAULT_TOKEN_EXPIRATION));
|
||||
|
||||
return new AttachmentsGrpcService(
|
||||
experimentEnrollmentManager,
|
||||
|
||||
+29
-1
@@ -7,6 +7,8 @@ package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@@ -30,6 +32,9 @@ import org.signal.chat.credentials.CheckSvrCredentialsResponse;
|
||||
import org.signal.chat.credentials.CredentialsAnonymousGrpc;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.util.MockUtils;
|
||||
@@ -60,9 +65,15 @@ class CredentialsAnonymousGrpcServiceTest extends
|
||||
@Mock
|
||||
private AccountsManager accountsManager;
|
||||
|
||||
@Mock
|
||||
private RateLimiters rateLimiters;
|
||||
|
||||
@Mock
|
||||
private RateLimiter rateLimiter;
|
||||
|
||||
@Override
|
||||
protected CredentialsAnonymousGrpcService createServiceBeforeEachTest() {
|
||||
return new CredentialsAnonymousGrpcService(accountsManager, SVR_CREDENTIALS_GENERATOR);
|
||||
return new CredentialsAnonymousGrpcService(accountsManager, SVR_CREDENTIALS_GENERATOR, rateLimiters);
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
@@ -71,6 +82,7 @@ class CredentialsAnonymousGrpcServiceTest extends
|
||||
when(account.getAccountIdentifier()).thenReturn(USER_UUID);
|
||||
|
||||
when(accountsManager.getByE164(USER_E164)).thenReturn(Optional.of(account));
|
||||
when(rateLimiters.getBackupAuthCheckLimiter()).thenReturn(rateLimiter);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -147,6 +159,22 @@ class CredentialsAnonymousGrpcServiceTest extends
|
||||
assertEquals(Status.INVALID_ARGUMENT.getCode(), status.getStatus().getCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void checkSvrCredentialsRateLimited() throws RateLimitExceededException {
|
||||
final Duration retryAfter = Duration.ofSeconds(11);
|
||||
|
||||
doThrow(new RateLimitExceededException(retryAfter))
|
||||
.when(rateLimiter).validate(anyString());
|
||||
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
GrpcTestUtils.assertRateLimitExceeded(retryAfter,
|
||||
() -> unauthenticatedServiceStub().checkSvrCredentials(CheckSvrCredentialsRequest.newBuilder()
|
||||
.setNumber(USER_E164)
|
||||
.addPasswords(token(USER_UUID, day(1)))
|
||||
.build()),
|
||||
accountsManager);
|
||||
}
|
||||
|
||||
private void assertExpectedCredentialCheckResponse(
|
||||
final Map<String, AuthCheckResult> expected,
|
||||
final long nowMillis) {
|
||||
|
||||
+10
-10
@@ -23,8 +23,8 @@ import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.junitpioneer.jupiter.cartesian.CartesianTest;
|
||||
import org.mockito.Mock;
|
||||
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.DonationsGrpc;
|
||||
import org.signal.chat.donations.RedeemReceiptRequest;
|
||||
import org.signal.chat.donations.RedeemReceiptResponse;
|
||||
@@ -182,12 +182,12 @@ class DonationsGrpcServiceTest extends SimpleBaseGrpcTest<DonationsGrpcService,
|
||||
final int permitCount = 10;
|
||||
final DonationPermitRequestContext context = DonationPermitRequestContext.forCount(permitCount);
|
||||
|
||||
final CreateDonationPermitResponse response = authenticatedServiceStub().createDonationPermit(
|
||||
CreateDonationPermitRequest.newBuilder()
|
||||
.setDonationPermitRequest(ByteString.copyFrom(context.request().serialize()))
|
||||
final CreateDonationPermitsResponse response = authenticatedServiceStub().createDonationPermits(
|
||||
CreateDonationPermitsRequest.newBuilder()
|
||||
.setDonationPermitsRequest(ByteString.copyFrom(context.request().serialize()))
|
||||
.build());
|
||||
|
||||
final DonationPermitResponse donationPermitResponse = new DonationPermitResponse(response.getDonationPermitResponse().toByteArray());
|
||||
final DonationPermitResponse donationPermitResponse = new DonationPermitResponse(response.getDonationPermitsResponse().toByteArray());
|
||||
final List<DonationPermit> donationPermits = context.receive(donationPermitResponse,
|
||||
donationsPermitSecretParams.getPublicParams(),
|
||||
clock.instant());
|
||||
@@ -201,8 +201,8 @@ class DonationsGrpcServiceTest extends SimpleBaseGrpcTest<DonationsGrpcService,
|
||||
final DonationPermitRequestContext context = DonationPermitRequestContext.forCount(permitCount);
|
||||
|
||||
GrpcTestUtils.assertStatusInvalidArgument(() ->
|
||||
authenticatedServiceStub().createDonationPermit(CreateDonationPermitRequest.newBuilder()
|
||||
.setDonationPermitRequest(ByteString.copyFrom(new byte[]{1, 2, 3}))
|
||||
authenticatedServiceStub().createDonationPermits(CreateDonationPermitsRequest.newBuilder()
|
||||
.setDonationPermitsRequest(ByteString.copyFrom(new byte[]{1, 2, 3}))
|
||||
.build()));
|
||||
}
|
||||
|
||||
@@ -216,8 +216,8 @@ class DonationsGrpcServiceTest extends SimpleBaseGrpcTest<DonationsGrpcService,
|
||||
final DonationPermitRequestContext context = DonationPermitRequestContext.forCount(permitCount);
|
||||
|
||||
GrpcTestUtils.assertRateLimitExceeded(retryDuration, () ->
|
||||
authenticatedServiceStub().createDonationPermit(CreateDonationPermitRequest.newBuilder()
|
||||
.setDonationPermitRequest(ByteString.copyFrom(context.request().serialize()))
|
||||
authenticatedServiceStub().createDonationPermits(CreateDonationPermitsRequest.newBuilder()
|
||||
.setDonationPermitsRequest(ByteString.copyFrom(context.request().serialize()))
|
||||
.build()));
|
||||
|
||||
}
|
||||
|
||||
Loaded 100 of 140 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user