mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-12-01 04:46:47 +00:00
Compare commits
41
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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,7 +65,7 @@ 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
|
||||
|
||||
@@ -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,44 +55,44 @@
|
||||
<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 -->
|
||||
<dynamodb.image>amazon/dynamodb-local:3.3.1@sha256:ff89bd48ff32cd8d9be5fee8873b65b8854dc408f1afe881be6eb00247bc0dab</dynamodb.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>
|
||||
@@ -325,7 +313,7 @@
|
||||
<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>
|
||||
@@ -467,12 +450,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 +475,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 +521,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 +584,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 +593,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>
|
||||
|
||||
@@ -145,6 +145,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>
|
||||
|
||||
@@ -287,6 +287,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 +343,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 +400,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 +828,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());
|
||||
@@ -1173,7 +1180,7 @@ 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 OneTimeDonationsGrpcService(config.getOneTimeDonations(), stripeManager, braintreeManager,
|
||||
|
||||
+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
@@ -73,6 +73,7 @@ public class DynamoDbTables {
|
||||
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;
|
||||
@@ -104,6 +105,7 @@ public class DynamoDbTables {
|
||||
@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) {
|
||||
@@ -134,6 +136,7 @@ public class DynamoDbTables {
|
||||
this.registrationRecovery = registrationRecovery;
|
||||
this.remoteConfig = remoteConfig;
|
||||
this.reportMessage = reportMessage;
|
||||
this.sandboxAccounts = sandboxAccounts;
|
||||
this.scheduledJobs = scheduledJobs;
|
||||
this.subscriptions = subscriptions;
|
||||
this.verificationSessions = verificationSessions;
|
||||
@@ -295,6 +298,12 @@ public class DynamoDbTables {
|
||||
return reportMessage;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
public Table getSandboxAccounts() {
|
||||
return sandboxAccounts;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
public TableWithExpiration getScheduledJobs() {
|
||||
|
||||
+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) {
|
||||
|
||||
+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) {
|
||||
|
||||
+1
-1
@@ -366,7 +366,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);
|
||||
|
||||
+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,
|
||||
|
||||
@@ -49,6 +49,8 @@ public class OneTimeDonationUtil {
|
||||
|
||||
}
|
||||
|
||||
/// Validates a request is for a valid one-time donation level and is at least the configured minimum for the currency
|
||||
/// and payment method.
|
||||
public static OneTimeDonationRequestValidationResult validateOneTimeDonationRequest(
|
||||
final String currency,
|
||||
final long amount,
|
||||
|
||||
+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();
|
||||
}
|
||||
|
||||
|
||||
+3
-4
@@ -341,8 +341,7 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
|
||||
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()
|
||||
@@ -358,8 +357,8 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
|
||||
return SetSubscriptionLevelResponse.newBuilder()
|
||||
.setInvalidLevelTransition(FailedPrecondition.newBuilder().build()).build();
|
||||
} catch (final PurchaseProcessorConflictException e) {
|
||||
return SetSubscriptionLevelResponse.newBuilder().setSubscriptionProcessorConflict(
|
||||
FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
|
||||
// We just looked up the subscription processor from the database, a conflict is not possible
|
||||
throw new IllegalStateException(e);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+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");
|
||||
}
|
||||
|
||||
|
||||
@@ -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> {
|
||||
|
||||
+4
@@ -195,6 +195,10 @@ public class AppleAppStoreClient {
|
||||
}
|
||||
}
|
||||
|
||||
Environment getDefaultEnvironment() {
|
||||
return defaultEnvironment;
|
||||
}
|
||||
|
||||
private <T> T lookupByTransactionIdInEnvironment(final Environment env, final String transactionId, final Tags errorTags, final TransactionFinder<T> lookupFunction) throws APIException, IOException {
|
||||
try {
|
||||
return retry.executeCallable(() -> {
|
||||
|
||||
+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());
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
+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()
|
||||
|
||||
+179
-79
@@ -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);
|
||||
@@ -683,20 +750,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 +867,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 +909,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 +958,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.
|
||||
@@ -2275,4 +2368,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() {
|
||||
@@ -181,7 +181,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);
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
-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
-3
@@ -82,6 +82,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;
|
||||
@@ -132,7 +133,8 @@ public record CommandDependencies(
|
||||
PhoneNumberIdentifiers phoneNumberIdentifiers,
|
||||
DynamoDbRecoveryManager dynamoDbRecoveryManager,
|
||||
FDB fdb,
|
||||
AccountLockManager accountLockManager) {
|
||||
AccountLockManager accountLockManager,
|
||||
SandboxAccounts sandboxAccounts) {
|
||||
|
||||
static CommandDependencies build(
|
||||
final String name,
|
||||
@@ -389,10 +391,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);
|
||||
@@ -496,7 +500,8 @@ public record CommandDependencies(
|
||||
phoneNumberIdentifiers,
|
||||
dynamoDbRecoveryManager,
|
||||
fdb,
|
||||
accountLockManager);
|
||||
accountLockManager,
|
||||
sandboxAccounts);
|
||||
}
|
||||
|
||||
}
|
||||
+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"));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -185,7 +185,7 @@ message CreatePaymentMethodRequest {
|
||||
// other values will result in an INVALID_ARGUMENT error.
|
||||
bytes subscriber_id = 1 [(require.exactlySize) = 32];
|
||||
PaymentMethod payment_method = 2 [(require.specified) = true];
|
||||
// a libsignal DonationPermit from rpc Donations.CreateDonationPermit
|
||||
// a libsignal DonationPermit from rpc Donations.CreateDonationPermits
|
||||
bytes donation_permit = 3 [(require.nonEmpty) = true];
|
||||
}
|
||||
|
||||
@@ -308,33 +308,26 @@ 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"];
|
||||
errors.FailedPrecondition payment_method_not_set_up = 3 [(tag.reason) = "payment_method_not_set_up"];
|
||||
// The payment processor does not support this operation
|
||||
errors.FailedPrecondition unsupported_operation = 5 [(tag.reason) = "unsupported_operation"];
|
||||
errors.FailedPrecondition unsupported_operation = 4 [(tag.reason) = "unsupported_operation"];
|
||||
// The requested level was invalid
|
||||
errors.FailedPrecondition unsupported_level = 6 [(tag.reason) = "unsupported_level"];
|
||||
errors.FailedPrecondition unsupported_level = 5 [(tag.reason) = "unsupported_level"];
|
||||
// The requested currency was invalid
|
||||
errors.FailedPrecondition unsupported_currency = 7 [(tag.reason) = "unsupported_currency"];
|
||||
errors.FailedPrecondition unsupported_currency = 6 [(tag.reason) = "unsupported_currency"];
|
||||
// The card could not be charged
|
||||
errors.FailedPrecondition payment_requires_action = 8 [(tag.reason) = "payment_requires_action"];
|
||||
errors.FailedPrecondition payment_requires_action = 7 [(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"];
|
||||
errors.FailedPrecondition invalid_level_transition = 8 [(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"];
|
||||
errors.FailedPrecondition invalid_idempotency_key = 9 [(tag.reason) = "invalid_idempotency_key"];
|
||||
// The payment failed; see charge failure details
|
||||
ChargeFailure charge_failure = 11 [(tag.reason) = "charge_failure"];
|
||||
ChargeFailure charge_failure = 10 [(tag.reason) = "charge_failure"];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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")
|
||||
|
||||
+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()));
|
||||
|
||||
}
|
||||
|
||||
+63
-23
@@ -37,6 +37,8 @@ import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.EnumSource;
|
||||
import org.junitpioneer.jupiter.cartesian.CartesianTest;
|
||||
import org.mockito.Mock;
|
||||
import org.signal.chat.common.EcPreKey;
|
||||
@@ -61,6 +63,7 @@ import org.whispersystems.textsecuregcm.entities.ECPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
@@ -141,25 +144,33 @@ class KeysAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<KeysAnonymousGrpcS
|
||||
assertEquals(expectedResponse, response);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getPreKeysGroupSendEndorsement() throws Exception {
|
||||
@ParameterizedTest
|
||||
@EnumSource(IdentityType.class)
|
||||
void getPreKeysGroupSendEndorsement(final IdentityType identityType) throws Exception {
|
||||
final Account targetAccount = mock(Account.class);
|
||||
|
||||
final Device targetDevice = DevicesHelper.createDevice(Device.PRIMARY_ID);
|
||||
final int aciRegistrationId = 7;
|
||||
final int pniRegistrationId = 17;
|
||||
final Device targetDevice = DevicesHelper.createDevice(Device.PRIMARY_ID, 0, aciRegistrationId);
|
||||
targetDevice.setPhoneNumberIdentityRegistrationId(pniRegistrationId);
|
||||
when(targetAccount.getDevice(Device.PRIMARY_ID)).thenReturn(Optional.of(targetDevice));
|
||||
|
||||
final ECKeyPair identityKeyPair = ECKeyPair.generate();
|
||||
final IdentityKey identityKey = new IdentityKey(identityKeyPair.getPublicKey());
|
||||
final UUID uuid = UUID.randomUUID();
|
||||
final AciServiceIdentifier identifier = new AciServiceIdentifier(uuid);
|
||||
final ECKeyPair aciIdentityKeyPair = ECKeyPair.generate();
|
||||
final ECKeyPair pniIdentityKeyPair = ECKeyPair.generate();
|
||||
final UUID aci = UUID.randomUUID();
|
||||
final org.whispersystems.textsecuregcm.identity.ServiceIdentifier identifier = switch (identityType) {
|
||||
case ACI -> new AciServiceIdentifier(aci);
|
||||
case PNI -> new PniServiceIdentifier(UUID.randomUUID());
|
||||
};
|
||||
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
|
||||
|
||||
when(targetAccount.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
|
||||
when(targetAccount.getAccountIdentifier()).thenReturn(uuid);
|
||||
when(targetAccount.getAccountIdentityKey()).thenReturn(identityKey);
|
||||
when(accountsManager.getByServiceIdentifier(identifier))
|
||||
.thenReturn(Optional.of(targetAccount));
|
||||
when(targetAccount.getAccountIdentifier()).thenReturn(aci);
|
||||
when(targetAccount.getAccountIdentityKey()).thenReturn(new IdentityKey(aciIdentityKeyPair.getPublicKey()));
|
||||
when(targetAccount.getPhoneNumberIdentityKey()).thenReturn(Optional.of(new IdentityKey(pniIdentityKeyPair.getPublicKey())));
|
||||
when(accountsManager.getByServiceIdentifier(identifier)).thenReturn(Optional.of(targetAccount));
|
||||
|
||||
final ECKeyPair identityKeyPair = identityType == IdentityType.ACI ? aciIdentityKeyPair : pniIdentityKeyPair;
|
||||
final ECPreKey ecPreKey = new ECPreKey(1, ECKeyPair.generate().getPublicKey());
|
||||
final ECSignedPreKey ecSignedPreKey = KeysHelper.signedECPreKey(2, identityKeyPair);
|
||||
final KEMSignedPreKey kemSignedPreKey = KeysHelper.signedKEMPreKey(3, identityKeyPair);
|
||||
@@ -181,18 +192,22 @@ class KeysAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<KeysAnonymousGrpcS
|
||||
.setDeviceId(Device.PRIMARY_ID))
|
||||
.build());
|
||||
|
||||
final GetPreKeysAnonymousResponse expectedResponse = GetPreKeysAnonymousResponse.newBuilder()
|
||||
.setPreKeys(AccountPreKeyBundles.newBuilder()
|
||||
.setIdentityKey(ByteString.copyFrom(identityKey.serialize()))
|
||||
.setUnidentifiedAccessKeyFingerprint(ByteString.copyFrom(UnidentifiedAccessChecksum.generateFor(unidentifiedAccessKey)))
|
||||
.putDevicePreKeys(Device.PRIMARY_ID, DevicePreKeyBundle.newBuilder()
|
||||
.setEcOneTimePreKey(toGrpcEcPreKey(ecPreKey))
|
||||
.setEcSignedPreKey(toGrpcEcSignedPreKey(ecSignedPreKey))
|
||||
.setKemOneTimePreKey(toGrpcKemSignedPreKey(kemSignedPreKey))
|
||||
.build()))
|
||||
.build();
|
||||
final AccountPreKeyBundles.Builder expectedPreKeys = AccountPreKeyBundles.newBuilder()
|
||||
.setIdentityKey(ByteString.copyFrom(identityKeyPair.getPublicKey().serialize()))
|
||||
.putDevicePreKeys(Device.PRIMARY_ID, DevicePreKeyBundle.newBuilder()
|
||||
.setEcOneTimePreKey(toGrpcEcPreKey(ecPreKey))
|
||||
.setEcSignedPreKey(toGrpcEcSignedPreKey(ecSignedPreKey))
|
||||
.setKemOneTimePreKey(toGrpcKemSignedPreKey(kemSignedPreKey))
|
||||
.setRegistrationId(identityType == IdentityType.ACI ? aciRegistrationId : pniRegistrationId)
|
||||
.build());
|
||||
|
||||
assertEquals(expectedResponse, response);
|
||||
// PNIs don't allow unidentified access, so their bundles never carry a UAK fingerprint
|
||||
if (identityType == IdentityType.ACI) {
|
||||
expectedPreKeys.setUnidentifiedAccessKeyFingerprint(
|
||||
ByteString.copyFrom(UnidentifiedAccessChecksum.generateFor(unidentifiedAccessKey)));
|
||||
}
|
||||
|
||||
assertEquals(GetPreKeysAnonymousResponse.newBuilder().setPreKeys(expectedPreKeys).build(), response);
|
||||
}
|
||||
|
||||
@CartesianTest
|
||||
@@ -368,7 +383,7 @@ class KeysAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<KeysAnonymousGrpcS
|
||||
.setGroupSendToken(ByteString.copyFrom(token))
|
||||
.setRequest(GetPreKeysRequest.newBuilder()
|
||||
.setTargetIdentifier(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(nonexistentAci)))
|
||||
.build());
|
||||
.build());
|
||||
assertTrue(preKeysResponse.hasTargetNotFound());
|
||||
verifyNoInteractions(keysManager);
|
||||
}
|
||||
@@ -402,6 +417,31 @@ class KeysAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<KeysAnonymousGrpcS
|
||||
assertTrue(response.hasFailedUnidentifiedAuthorization());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@EnumSource(value = GetPreKeysAnonymousRequest.AuthorizationCase.class, names = {"UNIDENTIFIED_ACCESS_KEY", "UNRESTRICTED_ACCESS"})
|
||||
void getPreKeysPniInvalidArgument(final GetPreKeysAnonymousRequest.AuthorizationCase authorizationCase) {
|
||||
final PniServiceIdentifier identifier = new PniServiceIdentifier(UUID.randomUUID());
|
||||
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
|
||||
|
||||
final Account targetAccount = mock(Account.class);
|
||||
when(targetAccount.isUnrestrictedUnidentifiedAccess()).thenReturn(true);
|
||||
when(targetAccount.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
|
||||
when(accountsManager.getByServiceIdentifier(identifier)).thenReturn(Optional.of(targetAccount));
|
||||
|
||||
final GetPreKeysAnonymousRequest.Builder requestBuilder = GetPreKeysAnonymousRequest.newBuilder()
|
||||
.setRequest(GetPreKeysRequest.newBuilder()
|
||||
.setTargetIdentifier(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(identifier)));
|
||||
|
||||
switch (authorizationCase) {
|
||||
case UNIDENTIFIED_ACCESS_KEY -> requestBuilder.setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey));
|
||||
case UNRESTRICTED_ACCESS -> requestBuilder.setUnrestrictedAccess(Empty.getDefaultInstance());
|
||||
default -> throw new AssertionError("unexpected authorization case: " + authorizationCase);
|
||||
}
|
||||
|
||||
GrpcTestUtils.assertStatusInvalidArgument(() -> unauthenticatedServiceStub().getPreKeys(requestBuilder.build()));
|
||||
verifyNoInteractions(keysManager);
|
||||
}
|
||||
|
||||
@Test
|
||||
void checkIdentityKeys() throws InterruptedException {
|
||||
final KeysAnonymousGrpc.KeysAnonymousStub keysAnonymousStub =
|
||||
|
||||
+85
-6
@@ -41,13 +41,13 @@ import org.mockito.Mock;
|
||||
import org.signal.chat.errors.FailedUnidentifiedAuthorization;
|
||||
import org.signal.chat.messages.ChallengeRequired;
|
||||
import org.signal.chat.messages.IndividualRecipientMessageBundle;
|
||||
import org.signal.chat.messages.SendMessageType;
|
||||
import org.signal.chat.messages.MessagesAnonymousGrpc;
|
||||
import org.signal.chat.messages.MismatchedDevices;
|
||||
import org.signal.chat.messages.MultiRecipientMessage;
|
||||
import org.signal.chat.messages.MultiRecipientMismatchedDevices;
|
||||
import org.signal.chat.messages.MultiRecipientSuccess;
|
||||
import org.signal.chat.messages.SendMessageResponse;
|
||||
import org.signal.chat.messages.SendMessageType;
|
||||
import org.signal.chat.messages.SendMultiRecipientMessageRequest;
|
||||
import org.signal.chat.messages.SendMultiRecipientMessageResponse;
|
||||
import org.signal.chat.messages.SendMultiRecipientStoryRequest;
|
||||
@@ -60,7 +60,6 @@ import org.whispersystems.textsecuregcm.controllers.MultiRecipientMismatchedDevi
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.limits.CardinalityEstimator;
|
||||
@@ -251,7 +250,7 @@ class MessagesAnonymousGrpcServiceTest extends
|
||||
generateRequest(serviceIdentifier, false, true, messages, UNIDENTIFIED_ACCESS_KEY, null)));
|
||||
verifyNoInteractions(messageSender);
|
||||
}
|
||||
|
||||
|
||||
@CartesianTest
|
||||
void sendUnrestrictedAccessMessage(
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean useUak,
|
||||
@@ -390,8 +389,9 @@ class MessagesAnonymousGrpcServiceTest extends
|
||||
verify(messageSender, never()).sendMessages(any(), any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void pniIdentifierWithUak() {
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void pniIdentifierWithoutGroupSendToken(final boolean useUak) {
|
||||
final byte deviceId = Device.PRIMARY_ID;
|
||||
final int registrationId = 7;
|
||||
final Device destinationDevice = DevicesHelper.createDevice(deviceId, CLOCK.millis(), registrationId);
|
||||
@@ -399,6 +399,7 @@ class MessagesAnonymousGrpcServiceTest extends
|
||||
final Account destinationAccount = mock(Account.class);
|
||||
when(destinationAccount.getDevices()).thenReturn(List.of(destinationDevice));
|
||||
when(destinationAccount.getDevice(deviceId)).thenReturn(Optional.of(destinationDevice));
|
||||
when(destinationAccount.isUnrestrictedUnidentifiedAccess()).thenReturn(true);
|
||||
when(destinationAccount.getUnidentifiedAccessKey()).thenReturn(Optional.of(UNIDENTIFIED_ACCESS_KEY));
|
||||
|
||||
final PniServiceIdentifier pniIdentifier = new PniServiceIdentifier(UUID.randomUUID());
|
||||
@@ -411,11 +412,57 @@ class MessagesAnonymousGrpcServiceTest extends
|
||||
.build());
|
||||
|
||||
final SendSealedSenderMessageRequest request =
|
||||
generateRequest(pniIdentifier, false, true, messages, UNIDENTIFIED_ACCESS_KEY, null);
|
||||
generateRequest(pniIdentifier, false, true, messages, useUak ? UNIDENTIFIED_ACCESS_KEY : null, null);
|
||||
|
||||
GrpcTestUtils.assertStatusException(
|
||||
Status.INVALID_ARGUMENT,
|
||||
() -> unauthenticatedServiceStub().sendSingleRecipientMessage(request));
|
||||
verifyNoInteractions(messageSender);
|
||||
}
|
||||
|
||||
@Test
|
||||
void pniIdentifierWithGroupSendToken()
|
||||
throws MessageTooLargeException, MismatchedDevicesException, MessageDeliveryNotAllowedException {
|
||||
final byte deviceId = Device.PRIMARY_ID;
|
||||
final int registrationId = 7;
|
||||
final Device destinationDevice = DevicesHelper.createDevice(deviceId, CLOCK.millis(), registrationId);
|
||||
|
||||
final Account destinationAccount = mock(Account.class);
|
||||
when(destinationAccount.getDevices()).thenReturn(List.of(destinationDevice));
|
||||
when(destinationAccount.getDevice(deviceId)).thenReturn(Optional.of(destinationDevice));
|
||||
|
||||
final PniServiceIdentifier pniIdentifier = new PniServiceIdentifier(UUID.randomUUID());
|
||||
when(accountsManager.getByServiceIdentifier(pniIdentifier)).thenReturn(Optional.of(destinationAccount));
|
||||
|
||||
final byte[] payload = TestRandomUtil.nextBytes(128);
|
||||
final Map<Byte, IndividualRecipientMessageBundle.Message> messages =
|
||||
Map.of(deviceId, IndividualRecipientMessageBundle.Message.newBuilder()
|
||||
.setRegistrationId(registrationId)
|
||||
.setPayload(ByteString.copyFrom(payload))
|
||||
.setType(SendMessageType.UNIDENTIFIED_SENDER)
|
||||
.build());
|
||||
|
||||
final SendMessageResponse response = unauthenticatedServiceStub().sendSingleRecipientMessage(
|
||||
generateRequest(pniIdentifier, false, true, messages, null, GROUP_SEND_TOKEN));
|
||||
|
||||
assertEquals(SendMessageResponse.newBuilder().setSuccess(Empty.getDefaultInstance()).build(), response);
|
||||
|
||||
final MessageProtos.Envelope expectedEnvelope = MessageProtos.Envelope.newBuilder()
|
||||
.setType(MessageProtos.Envelope.Type.UNIDENTIFIED_SENDER)
|
||||
.setDestinationServiceId(pniIdentifier.toCompactByteString())
|
||||
.setClientTimestamp(CLOCK.millis())
|
||||
.setServerTimestamp(CLOCK.millis())
|
||||
.setEphemeral(false)
|
||||
.setUrgent(true)
|
||||
.setContent(ByteString.copyFrom(payload))
|
||||
.build();
|
||||
|
||||
verify(messageSender).sendMessages(destinationAccount,
|
||||
pniIdentifier,
|
||||
Map.of(deviceId, expectedEnvelope),
|
||||
Map.of(deviceId, registrationId),
|
||||
Optional.empty(),
|
||||
null);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -1467,6 +1514,38 @@ class MessagesAnonymousGrpcServiceTest extends
|
||||
.sendMultiRecipientMessage(any(), any(), anyLong(), anyBoolean(), anyBoolean(), anyBoolean(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rateLimited()
|
||||
throws MessageTooLargeException, MessageDeliveryNotAllowedException, MultiRecipientMismatchedDevicesException {
|
||||
|
||||
final AciServiceIdentifier serviceIdentifier = new AciServiceIdentifier(UUID.randomUUID());
|
||||
final Account destinationAccount = mock(Account.class);
|
||||
when(destinationAccount.getAccountIdentifier()).thenReturn(serviceIdentifier.uuid());
|
||||
|
||||
when(accountsManager.getByServiceIdentifierAsync(serviceIdentifier))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(destinationAccount)));
|
||||
|
||||
final byte[] payload = MultiRecipientMessageHelper.generateMultiRecipientMessage(List.of(
|
||||
new TestRecipient(serviceIdentifier, Device.PRIMARY_ID, 17, new byte[48])));
|
||||
|
||||
final SendMultiRecipientStoryRequest request = SendMultiRecipientStoryRequest.newBuilder()
|
||||
.setMessage(MultiRecipientMessage.newBuilder()
|
||||
.setTimestamp(CLOCK.millis())
|
||||
.setPayload(ByteString.copyFrom(payload))
|
||||
.build())
|
||||
.setUrgent(true)
|
||||
.build();
|
||||
|
||||
final Duration retryDuration = Duration.ofHours(7);
|
||||
when(rateLimiter.validateAsync(any(UUID.class)))
|
||||
.thenReturn(CompletableFuture.failedFuture(new RateLimitExceededException(retryDuration)));
|
||||
|
||||
GrpcTestUtils.assertRateLimitExceeded(retryDuration, () -> unauthenticatedServiceStub().sendMultiRecipientStory(request));
|
||||
|
||||
verify(messageSender, never())
|
||||
.sendMultiRecipientMessage(any(), any(), anyLong(), anyBoolean(), anyBoolean(), anyBoolean(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void oversizedMessage()
|
||||
throws MessageTooLargeException, MultiRecipientMismatchedDevicesException, MessageDeliveryNotAllowedException {
|
||||
|
||||
+1
-4
@@ -419,7 +419,6 @@ public class SubscriptionsGrpcServiceTest extends
|
||||
.setIdempotencyKey("test-idempotency-key")
|
||||
.build());
|
||||
assertEquals(SetSubscriptionLevelResponse.ResponseCase.SUCCESS, response.getResponseCase());
|
||||
assertEquals(LEVEL, response.getSuccess().getLevel());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -498,9 +497,7 @@ public class SubscriptionsGrpcServiceTest extends
|
||||
Arguments.of(new PurchasePaymentRequiresActionException(),
|
||||
SetSubscriptionLevelResponse.ResponseCase.PAYMENT_REQUIRES_ACTION),
|
||||
Arguments.of(new PurchaseInvalidLevelException(),
|
||||
SetSubscriptionLevelResponse.ResponseCase.INVALID_LEVEL_TRANSITION),
|
||||
Arguments.of(new PurchaseProcessorConflictException(),
|
||||
SetSubscriptionLevelResponse.ResponseCase.SUBSCRIPTION_PROCESSOR_CONFLICT)
|
||||
SetSubscriptionLevelResponse.ResponseCase.INVALID_LEVEL_TRANSITION)
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
+9
-10
@@ -15,16 +15,15 @@ class BoringSslServerKeyManagerTest {
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource(nullValues = "null", value = {
|
||||
"ed25519, EdDSA",
|
||||
"ecdsa_sha256, EC",
|
||||
"ecdsa_secp256r1_sha256, EC",
|
||||
"rsa_pss_rsae_sha256, RSA",
|
||||
"rsa_pss_rsae_sha512, RSA",
|
||||
"rsa_pkcs1_sha256, null",
|
||||
"rsa_pss_pss_sha256, null",
|
||||
"ed448, null",
|
||||
"Ed25519, EdDSA",
|
||||
"SHA256withECDSA, EC",
|
||||
"SHA512withECDSA, EC",
|
||||
"SHA256withRSA, RSA",
|
||||
"SHA512withRSA, RSA",
|
||||
"SHA256withRSA_PSS_PSS, null",
|
||||
"Ed448, null",
|
||||
})
|
||||
void getJdkKeyType(final String boringSslSignatureAlgorithm, @Nullable final String expectedKeyType) {
|
||||
assertEquals(Optional.ofNullable(expectedKeyType), BoringSslServerKeyManager.getJdkKeyType(boringSslSignatureAlgorithm));
|
||||
void getJdkKeyType(final String signatureAlgorithm, @Nullable final String expectedKeyType) {
|
||||
assertEquals(Optional.ofNullable(expectedKeyType), BoringSslServerKeyManager.getJdkKeyType(signatureAlgorithm));
|
||||
}
|
||||
}
|
||||
+10
-4
@@ -35,6 +35,7 @@ import java.util.Map;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.junit.jupiter.params.provider.EnumSource;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
|
||||
@@ -196,8 +197,12 @@ class AppleAppStoreManagerTest {
|
||||
assertDoesNotThrow(() -> appleAppStoreManager.cancelAllActiveSubscriptions(ORIGINAL_TX_ID));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getPaymentDetails()
|
||||
@ParameterizedTest
|
||||
@CsvSource({
|
||||
"PRODUCTION, LOGIN",
|
||||
"SANDBOX, LOGIN_SANDBOX",
|
||||
})
|
||||
public void getPaymentDetails(final Environment environment, final ReceiptLevel receiptLevel)
|
||||
throws APIException, IOException, VerificationException, PurchaseException, RateLimitExceededException {
|
||||
when(apiClient.getTransactionInfo(TRANSACTION_ID))
|
||||
.thenReturn(new TransactionInfoResponse().signedTransactionInfo(SIGNED_TX_INFO));
|
||||
@@ -206,14 +211,15 @@ class AppleAppStoreManagerTest {
|
||||
.productId(ONE_TIME_PRODUCT_ID)
|
||||
.type(Type.CONSUMABLE)
|
||||
.inAppOwnershipType(InAppOwnershipType.PURCHASED)
|
||||
.purchaseDate(Instant.EPOCH.plus(Duration.ofDays(1)).toEpochMilli());
|
||||
.purchaseDate(Instant.EPOCH.plus(Duration.ofDays(1)).toEpochMilli())
|
||||
.environment(environment);
|
||||
when(signedDataVerifier.verifyAndDecodeTransaction(SIGNED_TX_INFO)).thenReturn(payload);
|
||||
|
||||
{
|
||||
// PURCHASED payment
|
||||
final PaymentDetails paymentDetails = appleAppStoreManager.claimOneTimePurchase(TRANSACTION_ID);
|
||||
assertThat(paymentDetails.id()).isEqualTo(TRANSACTION_ID);
|
||||
assertThat(paymentDetails.level()).isEqualTo(ReceiptLevel.LOGIN);
|
||||
assertThat(paymentDetails.level()).isEqualTo(receiptLevel);
|
||||
assertThat(paymentDetails.created()).isEqualTo(Instant.EPOCH.plus(Duration.ofDays(1)));
|
||||
}
|
||||
|
||||
|
||||
+12
-14
@@ -19,6 +19,8 @@ import java.util.Map;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.EnumSource;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.signal.libsignal.zkgroup.ServerSecretParams;
|
||||
@@ -63,10 +65,11 @@ class LoginPurchaseManagerTest {
|
||||
new ServerZkReceiptOperations(SERVER_SECRET_PARAMS));
|
||||
}
|
||||
|
||||
@Test
|
||||
void generateReceiptSuccess() throws Exception {
|
||||
@ParameterizedTest
|
||||
@EnumSource(mode = EnumSource.Mode.INCLUDE, names = {"LOGIN_SANDBOX", "LOGIN"})
|
||||
void generateReceiptSuccess(ReceiptLevel receiptLevel) throws Exception {
|
||||
when(paymentProcessor.claimOneTimePurchase(PURCHASE_ID))
|
||||
.thenReturn(new PaymentDetails(PURCHASE_ID, ReceiptLevel.LOGIN, PURCHASED_AT));
|
||||
.thenReturn(new PaymentDetails(PURCHASE_ID, receiptLevel, PURCHASED_AT));
|
||||
|
||||
final ReceiptCredentialResponse receipt =
|
||||
loginPurchaseManager.generateReceipt(PROVIDER, PURCHASE_ID, receiptCredentialRequestContext.getRequest());
|
||||
@@ -74,25 +77,20 @@ class LoginPurchaseManagerTest {
|
||||
clientZkReceiptOperations.receiveReceiptCredential(receiptCredentialRequestContext, receipt);
|
||||
|
||||
final Instant expectedExpiration = PURCHASED_AT
|
||||
.plus(LoginPurchaseManager.LOGIN_EXPIRATION)
|
||||
.plus(switch (receiptLevel) {
|
||||
case LOGIN -> LoginPurchaseManager.LOGIN_EXPIRATION;
|
||||
case LOGIN_SANDBOX -> LoginPurchaseManager.SANDBOX_LOGIN_EXPIRATION;
|
||||
default -> throw new IllegalStateException();
|
||||
})
|
||||
.truncatedTo(ChronoUnit.DAYS);
|
||||
|
||||
assertThat(receiptCredential.getReceiptLevel()).isEqualTo(ReceiptLevel.LOGIN.getValue());
|
||||
assertThat(receiptCredential.getReceiptLevel()).isEqualTo(receiptLevel.getValue());
|
||||
assertThat(receiptCredential.getReceiptExpirationTime()).isEqualTo(expectedExpiration.getEpochSecond());
|
||||
|
||||
verify(issuedReceiptsManager).recordOneTimeIssuance(
|
||||
PURCHASE_ID, PROVIDER, receiptCredentialRequestContext.getRequest(), expectedExpiration);
|
||||
}
|
||||
|
||||
@Test
|
||||
void generateReceiptUnknownLevel() throws Exception {
|
||||
when(paymentProcessor.claimOneTimePurchase(PURCHASE_ID))
|
||||
.thenReturn(new PaymentDetails(PURCHASE_ID, null, PURCHASED_AT));
|
||||
assertThatExceptionOfType(PurchaseInvalidArgumentsException.class).isThrownBy(() ->
|
||||
loginPurchaseManager.generateReceipt(PROVIDER, PURCHASE_ID, receiptCredentialRequestContext.getRequest()));
|
||||
verifyNoInteractions(issuedReceiptsManager);
|
||||
}
|
||||
|
||||
@Test
|
||||
void generateReceiptNonLoginLevel() throws Exception {
|
||||
when(paymentProcessor.claimOneTimePurchase(PURCHASE_ID))
|
||||
|
||||
+9
-7
@@ -55,6 +55,7 @@ import org.whispersystems.textsecuregcm.entities.ApnRegistrationId;
|
||||
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.GcmRegistrationId;
|
||||
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.purchases.ReceiptLevel;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
|
||||
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
|
||||
@@ -171,6 +172,7 @@ public class AccountCreationDeletionIntegrationTest {
|
||||
svr2Client,
|
||||
disconnectionRequestManager,
|
||||
phoneNumberRecoveryPasswordsManager,
|
||||
mock(SandboxAccounts.class),
|
||||
executor,
|
||||
executor,
|
||||
CLOCK,
|
||||
@@ -310,7 +312,7 @@ public class AccountCreationDeletionIntegrationTest {
|
||||
|
||||
final Account account = accountsManager.create(accountAttributes,
|
||||
new IdentityKey(aciKeyPair.getPublicKey()),
|
||||
receiptPresentation(CLOCK.instant().plus(Duration.ofDays(30)), 1),
|
||||
receiptPresentation(CLOCK.instant().plus(Duration.ofDays(30)), ReceiptLevel.LOGIN.getValue()),
|
||||
new DeviceSpec(
|
||||
deviceName,
|
||||
password,
|
||||
@@ -538,7 +540,7 @@ public class AccountCreationDeletionIntegrationTest {
|
||||
: accountsManager.create(new AccountAttributes(true, 1, null, "name".getBytes(StandardCharsets.UTF_8), null, false, Set.of(),
|
||||
originalRecoveryPassword),
|
||||
new IdentityKey(aciKeyPair.getPublicKey()),
|
||||
receiptPresentation(receiptSerial, CLOCK.instant().plus(Duration.ofDays(30)), 1),
|
||||
receiptPresentation(receiptSerial, CLOCK.instant().plus(Duration.ofDays(30)), ReceiptLevel.LOGIN.getValue()),
|
||||
new DeviceSpec(null,
|
||||
"password?",
|
||||
"OWI",
|
||||
@@ -684,7 +686,7 @@ public class AccountCreationDeletionIntegrationTest {
|
||||
} else {
|
||||
account = accountsManager.create(accountAttributes,
|
||||
new IdentityKey(aciKeyPair.getPublicKey()),
|
||||
receiptPresentation(CLOCK.instant().plus(Duration.ofDays(30)), 1),
|
||||
receiptPresentation(CLOCK.instant().plus(Duration.ofDays(30)), ReceiptLevel.LOGIN.getValue()),
|
||||
new DeviceSpec(
|
||||
deviceName,
|
||||
password,
|
||||
@@ -734,7 +736,7 @@ public class AccountCreationDeletionIntegrationTest {
|
||||
new AccountAttributes(true, 1, null, "name".getBytes(StandardCharsets.UTF_8), null, false, Set.of(), null)
|
||||
.setRecoveryPassword(recoveryPassword),
|
||||
aciIdentityKey,
|
||||
receiptPresentation(receiptSerial, CLOCK.instant().plus(Duration.ofDays(30)), 1),
|
||||
receiptPresentation(receiptSerial, CLOCK.instant().plus(Duration.ofDays(30)), ReceiptLevel.LOGIN.getValue()),
|
||||
new DeviceSpec(null,
|
||||
password,
|
||||
"OWI",
|
||||
@@ -777,7 +779,7 @@ public class AccountCreationDeletionIntegrationTest {
|
||||
|
||||
final Account retriedAccount = accountsManager.create(accountAttributes,
|
||||
aciIdentityKey,
|
||||
receiptPresentation(receiptSerial, CLOCK.instant().plus(Duration.ofDays(30)), 1),
|
||||
receiptPresentation(receiptSerial, CLOCK.instant().plus(Duration.ofDays(30)), ReceiptLevel.LOGIN.getValue()),
|
||||
new DeviceSpec(deviceName,
|
||||
password,
|
||||
signalAgent,
|
||||
@@ -831,7 +833,7 @@ public class AccountCreationDeletionIntegrationTest {
|
||||
final Account existingAccount = accountsManager.create(
|
||||
new AccountAttributes(true, 1, null, "name".getBytes(StandardCharsets.UTF_8), null, false, Set.of(), recoveryPassword),
|
||||
aciIdentityKey,
|
||||
receiptPresentation(receiptSerial, CLOCK.instant().plus(Duration.ofDays(30)), 1),
|
||||
receiptPresentation(receiptSerial, CLOCK.instant().plus(Duration.ofDays(30)), ReceiptLevel.LOGIN.getValue()),
|
||||
new DeviceSpec(null,
|
||||
password,
|
||||
"OWI",
|
||||
@@ -849,7 +851,7 @@ public class AccountCreationDeletionIntegrationTest {
|
||||
// Using a different account recovery password should throw an exception
|
||||
new AccountAttributes(true, 1, null, "name".getBytes(StandardCharsets.UTF_8), null, false, Set.of(), TestRandomUtil.nextBytes(16)),
|
||||
aciIdentityKey,
|
||||
receiptPresentation(receiptSerial, CLOCK.instant().plus(Duration.ofDays(30)), 1),
|
||||
receiptPresentation(receiptSerial, CLOCK.instant().plus(Duration.ofDays(30)), ReceiptLevel.LOGIN.getValue()),
|
||||
new DeviceSpec(null,
|
||||
password,
|
||||
"OWI",
|
||||
|
||||
+1
@@ -151,6 +151,7 @@ class AccountsManagerChangeNumberIntegrationTest {
|
||||
svr2Client,
|
||||
disconnectionRequestManager,
|
||||
phoneNumberRecoveryPasswordsManager,
|
||||
mock(SandboxAccounts.class),
|
||||
executor,
|
||||
executor,
|
||||
mock(Clock.class),
|
||||
|
||||
+1
@@ -132,6 +132,7 @@ class AccountsManagerConcurrentModificationIntegrationTest {
|
||||
mock(SecureValueRecoveryClient.class),
|
||||
mock(DisconnectionRequestManager.class),
|
||||
phoneNumberRecoveryPasswordsManager,
|
||||
mock(SandboxAccounts.class),
|
||||
mock(ScheduledExecutorService.class),
|
||||
mock(ScheduledExecutorService.class),
|
||||
mock(Clock.class),
|
||||
|
||||
+1
@@ -67,6 +67,7 @@ public class AccountsManagerDeviceTransferIntegrationTest {
|
||||
mock(SecureValueRecoveryClient.class),
|
||||
mock(DisconnectionRequestManager.class),
|
||||
mock(PhoneNumberRecoveryPasswordsManager.class),
|
||||
mock(SandboxAccounts.class),
|
||||
mock(ScheduledExecutorService.class),
|
||||
mock(ScheduledExecutorService.class),
|
||||
Clock.systemUTC(),
|
||||
|
||||
+1
@@ -137,6 +137,7 @@ public class AccountsManagerMigrateRecoveryPasswordIntegrationTest {
|
||||
svr2Client,
|
||||
disconnectionRequestManager,
|
||||
phoneNumberRecoveryPasswordsManager,
|
||||
mock(SandboxAccounts.class),
|
||||
executor,
|
||||
executor,
|
||||
mock(Clock.class),
|
||||
|
||||
+151
-9
@@ -89,6 +89,7 @@ import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.junitpioneer.jupiter.cartesian.CartesianTest;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.stubbing.Answer;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.signal.libsignal.protocol.ecc.ECKeyPair;
|
||||
@@ -107,6 +108,7 @@ import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.purchases.ReceiptLevel;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
|
||||
@@ -122,6 +124,7 @@ import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import org.whispersystems.textsecuregcm.util.TestClock;
|
||||
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
|
||||
import org.whispersystems.textsecuregcm.util.ThrowingSupplier;
|
||||
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem;
|
||||
|
||||
@Timeout(value = 10, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
|
||||
class AccountsManagerTest {
|
||||
@@ -146,6 +149,7 @@ class AccountsManagerTest {
|
||||
private static TestClock CLOCK;
|
||||
|
||||
private Accounts accounts;
|
||||
private SandboxAccounts sandboxAccounts;
|
||||
private PhoneNumberIdentifiers phoneNumberIdentifiers;
|
||||
private KeysManager keysManager;
|
||||
private MessagesManager messagesManager;
|
||||
@@ -173,6 +177,7 @@ class AccountsManagerTest {
|
||||
@BeforeEach
|
||||
void setup() throws Exception {
|
||||
accounts = mock(Accounts.class);
|
||||
sandboxAccounts = mock(SandboxAccounts.class);
|
||||
keysManager = mock(KeysManager.class);
|
||||
messagesManager = mock(MessagesManager.class);
|
||||
profilesManager = mock(ProfilesManager.class);
|
||||
@@ -265,6 +270,7 @@ class AccountsManagerTest {
|
||||
svr2Client,
|
||||
disconnectionRequestManager,
|
||||
phoneNumberRecoveryPasswordsManager,
|
||||
sandboxAccounts,
|
||||
mock(ScheduledExecutorService.class),
|
||||
mock(ScheduledExecutorService.class),
|
||||
CLOCK,
|
||||
@@ -836,7 +842,7 @@ class AccountsManagerTest {
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void testCreateFreshAccount(final boolean hasE164)
|
||||
throws AccountAlreadyExistsException, ReceiptAlreadyRedeemedException {
|
||||
throws AccountAlreadyExistsException, ReceiptAlreadyRedeemedException, AccountCreationConditionException {
|
||||
when(accounts.create(any(), any())).thenReturn(true);
|
||||
|
||||
final Optional<String> maybeE164 = hasE164 ? Optional.of("+18005550123") : Optional.empty();
|
||||
@@ -886,12 +892,50 @@ class AccountsManagerTest {
|
||||
verifyNoInteractions(profilesManager);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCreateSandboxAccount() throws Exception {
|
||||
CLOCK.pin(Instant.now());
|
||||
final UUID sandboxAci = UUID.randomUUID();
|
||||
final TransactWriteItem claim = TransactWriteItem.builder().build();
|
||||
when(sandboxAccounts.getAvailable()).thenReturn(List.of(sandboxAci));
|
||||
when(sandboxAccounts.buildClaimWriteItem(sandboxAci, CLOCK.instant())).thenReturn(claim);
|
||||
|
||||
final Account createdAccount = createSandboxAccount(sandboxAccountAttributes());
|
||||
|
||||
assertEquals(sandboxAci, createdAccount.getAccountIdentifier());
|
||||
assertTrue(createdAccount.getNumber().isEmpty());
|
||||
assertTrue(createdAccount.getAuthCredentialSalt().isPresent());
|
||||
verify(accounts).create(argThat(account -> sandboxAci.equals(account.getAccountIdentifier())), any(), any(), argThat(list -> list.contains(claim)));
|
||||
verify(keysManager).buildWriteItemsForNewDevice(eq(sandboxAci), eq(Optional.empty()), eq(Device.PRIMARY_ID),
|
||||
notNull(), eq(Optional.empty()), notNull(), eq(Optional.empty()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCreateSandboxAccountIdentifierUnavailable() throws Exception {
|
||||
final UUID firstAci = UUID.randomUUID();
|
||||
final UUID secondAci = UUID.randomUUID();
|
||||
when(sandboxAccounts.getAvailable()).thenReturn(List.of(firstAci, secondAci));
|
||||
when(accounts.create(any(), any(), any(), any()))
|
||||
.thenThrow(new AccountCreationConditionException(0))
|
||||
.thenReturn(true);
|
||||
|
||||
final Account createdAccount = createSandboxAccount(sandboxAccountAttributes());
|
||||
|
||||
final ArgumentCaptor<Account> accountCaptor = ArgumentCaptor.forClass(Account.class);
|
||||
verify(accounts, times(2)).create(accountCaptor.capture(), any(), any(), any());
|
||||
final List<UUID> attemptedAcis =
|
||||
accountCaptor.getAllValues().stream().map(Account::getAccountIdentifier).toList();
|
||||
|
||||
assertEquals(Set.of(firstAci, secondAci), Set.copyOf(attemptedAcis));
|
||||
assertEquals(attemptedAcis.getLast(), createdAccount.getAccountIdentifier());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void testReregisterAccount(
|
||||
final Optional<String> maybeE164,
|
||||
final Optional<String> maybeExistingAccountE164)
|
||||
throws AccountAlreadyExistsException, ReceiptAlreadyRedeemedException {
|
||||
throws AccountAlreadyExistsException, ReceiptAlreadyRedeemedException, AccountCreationConditionException {
|
||||
final UUID existingUuid = UUID.randomUUID();
|
||||
final Integer pniRegistrationId = maybeE164.isPresent() ? 2 : null;
|
||||
final AccountAttributes attributes = new AccountAttributes(false, 1, pniRegistrationId, null, null, maybeE164.isPresent(), null,
|
||||
@@ -1223,7 +1267,7 @@ class AccountsManagerTest {
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void testAddDevice(boolean accountHasPhoneNumber) throws LinkDeviceTokenAlreadyUsedException {
|
||||
void testAddDevice(boolean accountHasPhoneNumber) throws LinkDeviceTokenAlreadyUsedException, DeviceLimitExceededException {
|
||||
final String phoneNumber =
|
||||
PhoneNumberUtil.getInstance().format(PhoneNumberUtil.getInstance().getExampleNumber("US"),
|
||||
PhoneNumberUtil.PhoneNumberFormat.E164);
|
||||
@@ -1269,7 +1313,7 @@ class AccountsManagerTest {
|
||||
true,
|
||||
Optional.empty(),
|
||||
Optional.empty()),
|
||||
accountsManager.generateLinkDeviceToken(aci));
|
||||
accountsManager.generateLinkDeviceToken(account));
|
||||
|
||||
verify(keysManager).deleteSingleUsePreKeys(aci, nextDeviceId);
|
||||
maybePni.ifPresent(pni -> verify(keysManager).deleteSingleUsePreKeys(pni, nextDeviceId));
|
||||
@@ -1298,6 +1342,55 @@ class AccountsManagerTest {
|
||||
assertNull(device.getGcmId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testAddDeviceExceedsMaxDevices() {
|
||||
final List<Device> devices = IntStream.range(0, AccountsManager.MAX_DEVICES - 1)
|
||||
.mapToObj(i -> {
|
||||
final Device device = generateTestDevice(CLOCK.millis());
|
||||
device.setId((byte) (Device.PRIMARY_ID + i));
|
||||
return device;
|
||||
})
|
||||
.toList();
|
||||
|
||||
final Account account = AccountsHelper.generateTestAccount("+14152222222", devices);
|
||||
final UUID aci = account.getAccountIdentifier();
|
||||
account.setIdentityKey(new IdentityKey(ECKeyPair.generate().getPublicKey()));
|
||||
|
||||
final String linkDeviceToken = assertDoesNotThrow(() -> accountsManager.generateLinkDeviceToken(account),
|
||||
"the account should still have a free device slot");
|
||||
|
||||
// Simulate a concurrent link request
|
||||
final Device concurrentlyLinkedDevice = generateTestDevice(CLOCK.millis());
|
||||
concurrentlyLinkedDevice.setId(account.getNextDeviceId());
|
||||
account.addDevice(concurrentlyLinkedDevice);
|
||||
|
||||
when(accounts.getByAccountIdentifier(aci)).thenReturn(Optional.of(account));
|
||||
|
||||
final ECKeyPair aciKeyPair = ECKeyPair.generate();
|
||||
final ECKeyPair pniKeyPair = ECKeyPair.generate();
|
||||
|
||||
final DeviceLimitExceededException exception = assertThrows(DeviceLimitExceededException.class,
|
||||
() -> accountsManager.addDevice(aci,
|
||||
new DeviceSpec(
|
||||
"device-name".getBytes(StandardCharsets.UTF_8),
|
||||
"password",
|
||||
"OWT",
|
||||
Set.of(),
|
||||
new DeviceIdentityInfo(17, KeysHelper.signedECPreKey(1, aciKeyPair), KeysHelper.signedKEMPreKey(3, aciKeyPair)),
|
||||
Optional.of(new DeviceIdentityInfo(19, KeysHelper.signedECPreKey(2, pniKeyPair), KeysHelper.signedKEMPreKey(4, pniKeyPair))),
|
||||
true,
|
||||
Optional.empty(),
|
||||
Optional.empty()),
|
||||
linkDeviceToken));
|
||||
|
||||
assertEquals(AccountsManager.MAX_DEVICES, exception.getCurrentDevices());
|
||||
assertEquals(AccountsManager.MAX_DEVICES, exception.getMaxDevices());
|
||||
|
||||
verify(accounts, never()).updateTransactionally(any(), any());
|
||||
verifyNoInteractions(keysManager);
|
||||
verifyNoInteractions(messagesManager);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void testUpdateDeviceLastSeen(final boolean expectUpdate, final long initialLastSeen, final long updatedLastSeen) {
|
||||
@@ -1725,9 +1818,38 @@ class AccountsManagerTest {
|
||||
private Account createAccount(final AccountAttributes accountAttributes) throws ReceiptAlreadyRedeemedException {
|
||||
final ECKeyPair aciKeyPair = ECKeyPair.generate();
|
||||
|
||||
final ReceiptCredentialPresentation receiptCredentialPresentation = mock(ReceiptCredentialPresentation.class);
|
||||
when(receiptCredentialPresentation.getReceiptLevel()).thenReturn(ReceiptLevel.LOGIN.getValue());
|
||||
return accountsManager.create(accountAttributes,
|
||||
new IdentityKey(aciKeyPair.getPublicKey()),
|
||||
mock(ReceiptCredentialPresentation.class),
|
||||
receiptCredentialPresentation,
|
||||
new DeviceSpec(
|
||||
accountAttributes.getName(),
|
||||
"password",
|
||||
null,
|
||||
accountAttributes.getCapabilities(),
|
||||
new DeviceIdentityInfo(accountAttributes.getRegistrationId(), KeysHelper.signedECPreKey(1, aciKeyPair), KeysHelper.signedKEMPreKey(3, aciKeyPair)),
|
||||
Optional.empty(),
|
||||
accountAttributes.getFetchesMessages(),
|
||||
Optional.empty(),
|
||||
Optional.empty()),
|
||||
null);
|
||||
}
|
||||
|
||||
private static AccountAttributes sandboxAccountAttributes() {
|
||||
return new AccountAttributes(false, 1, null, null, null, false, null, TestRandomUtil.nextBytes(16));
|
||||
}
|
||||
|
||||
private Account createSandboxAccount(final AccountAttributes accountAttributes)
|
||||
throws ReceiptAlreadyRedeemedException {
|
||||
final ECKeyPair aciKeyPair = ECKeyPair.generate();
|
||||
|
||||
final ReceiptCredentialPresentation receiptCredentialPresentation = mock(ReceiptCredentialPresentation.class);
|
||||
when(receiptCredentialPresentation.getReceiptLevel()).thenReturn(ReceiptLevel.LOGIN_SANDBOX.getValue());
|
||||
|
||||
return accountsManager.create(accountAttributes,
|
||||
new IdentityKey(aciKeyPair.getPublicKey()),
|
||||
receiptCredentialPresentation,
|
||||
new DeviceSpec(
|
||||
accountAttributes.getName(),
|
||||
"password",
|
||||
@@ -1765,11 +1887,31 @@ class AccountsManagerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void checkDeviceLinkingToken() {
|
||||
final UUID aci = UUID.randomUUID();
|
||||
void checkDeviceLinkingToken() throws Exception {
|
||||
final Account account = createAccount(new AccountAttributes(false, 1, 2, null, null, false, null,
|
||||
TestRandomUtil.nextBytes(16)));
|
||||
|
||||
assertEquals(Optional.of(aci),
|
||||
accountsManager.checkDeviceLinkingToken(accountsManager.generateLinkDeviceToken(aci)));
|
||||
assertEquals(Optional.of(account.getAccountIdentifier()),
|
||||
accountsManager.checkDeviceLinkingToken(accountsManager.generateLinkDeviceToken(account)));
|
||||
}
|
||||
|
||||
static List<Arguments> isCanonicallyBase64UrlEncoded() {
|
||||
final byte[] bytes = new byte[32];
|
||||
final String canonical = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
|
||||
|
||||
return List.of(
|
||||
Arguments.argumentSet("Canonical", canonical, bytes, true),
|
||||
Arguments.argumentSet("Missing padding", "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", bytes, false),
|
||||
Arguments.argumentSet("Extra bits", "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB=", bytes, false),
|
||||
Arguments.argumentSet("Extra bits, missing padding", "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD", bytes, false)
|
||||
);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void isCanonicallyBase64UrlEncoded(final String encoded, final byte[] bytes, final boolean expectCanonical) {
|
||||
assertArrayEquals(bytes, Base64.getUrlDecoder().decode(encoded));
|
||||
assertEquals(expectCanonical, AccountsManager.isCanonicallyBase64UrlEncoded(encoded, bytes));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
|
||||
+1
@@ -153,6 +153,7 @@ class AccountsManagerUsernameIntegrationTest {
|
||||
mock(SecureValueRecoveryClient.class),
|
||||
disconnectionRequestManager,
|
||||
phoneNumberRecoveryPasswordsManager,
|
||||
mock(SandboxAccounts.class),
|
||||
Executors.newSingleThreadScheduledExecutor(),
|
||||
Executors.newSingleThreadScheduledExecutor(),
|
||||
Clock.systemUTC(),
|
||||
|
||||
@@ -126,12 +126,14 @@ class AccountsTest {
|
||||
Tables.DELETED_ACCOUNTS,
|
||||
Tables.USED_LINK_DEVICE_TOKENS,
|
||||
Tables.REDEEMED_RECEIPTS,
|
||||
Tables.SANDBOX_ACCOUNTS,
|
||||
|
||||
// This is an unrelated table used to test "tag-along" transactional updates
|
||||
Tables.CLIENT_RELEASES);
|
||||
|
||||
private final TestClock clock = TestClock.pinned(Instant.EPOCH);
|
||||
private Accounts accounts;
|
||||
private SandboxAccounts sandboxAccounts;
|
||||
|
||||
private record UsernameConstraint(UUID accountIdentifier, boolean confirmed, Optional<Instant> expiration) {
|
||||
}
|
||||
@@ -157,6 +159,8 @@ class AccountsTest {
|
||||
Tables.USERNAMES.tableName(),
|
||||
Tables.DELETED_ACCOUNTS.tableName(),
|
||||
Tables.USED_LINK_DEVICE_TOKENS.tableName());
|
||||
|
||||
sandboxAccounts = new SandboxAccounts(Tables.SANDBOX_ACCOUNTS.tableName(), DYNAMO_DB_EXTENSION.getDynamoDbClient());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@@ -224,17 +228,16 @@ class AccountsTest {
|
||||
assertRedeemedReceiptConstraintExists(receiptCredentialPresentation, account.getAccountIdentifier());
|
||||
}
|
||||
|
||||
freshUser = number != null ? createAccount(account) : createNumberlessAccount(account, receiptCredentialPresentation, TestRandomUtil.nextBytes(16));
|
||||
|
||||
assertThat(freshUser).isTrue();
|
||||
verifyStoredState(Optional.ofNullable(number), account.getAccountIdentifier(), account.getPhoneNumberIdentifier(), null, account, number != null);
|
||||
|
||||
if (number != null) {
|
||||
// For an account with a number only, try creating it again. Numberless accounts cannot be created with an old ACI
|
||||
freshUser = createAccount(account);
|
||||
|
||||
assertThat(freshUser).isTrue();
|
||||
verifyStoredState(Optional.ofNullable(number), account.getAccountIdentifier(), account.getPhoneNumberIdentifier(), null, account, number != null);
|
||||
|
||||
assertThat(account.getPhoneNumberIdentifier()).isPresent();
|
||||
assertPhoneNumberConstraintExists(number, account.getAccountIdentifier());
|
||||
assertPhoneNumberIdentifierConstraintExists(account.getPhoneNumberIdentifier().get(), account.getAccountIdentifier());
|
||||
} else {
|
||||
assertRedeemedReceiptConstraintExists(receiptCredentialPresentation, account.getAccountIdentifier());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -580,8 +583,43 @@ class AccountsTest {
|
||||
final Account secondAccount =
|
||||
generateAccount(null, UUID.randomUUID(), null, List.of(generateDevice(DEVICE_ID_1)), accountRecoveryPassword);
|
||||
assertThrows(ReceiptAlreadyRedeemedException.class,
|
||||
() -> accounts.create(secondAccount, receiptCredentialPresentation, accountRecoveryPassword,
|
||||
Collections.emptyList()));
|
||||
() -> accounts.create(secondAccount, receiptCredentialPresentation, accountRecoveryPassword, Collections.emptyList()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCreateSandboxAccount() throws Exception {
|
||||
final UUID uuid = UUID.randomUUID();
|
||||
sandboxAccounts.add(uuid);
|
||||
|
||||
final byte[] accountRecoveryPassword = TestRandomUtil.nextBytes(16);
|
||||
final Account account =
|
||||
generateAccount(null, uuid, null, List.of(generateDevice(DEVICE_ID_1)), accountRecoveryPassword);
|
||||
accounts.create(account, receiptPresentation(), accountRecoveryPassword,
|
||||
List.of(sandboxAccounts.buildClaimWriteItem(uuid, clock.instant())));
|
||||
|
||||
assertTrue(accounts.getByAccountIdentifier(uuid).isPresent());
|
||||
assertEquals(List.of(new SandboxAccounts.SandboxAccountReservation(uuid, Optional.of(clock.instant()))),
|
||||
sandboxAccounts.getAll());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCreateSandboxAccountAlreadyClaimed() throws Exception {
|
||||
final UUID uuid = UUID.randomUUID();
|
||||
sandboxAccounts.add(uuid);
|
||||
|
||||
// Mark the sandbox ACI as already used
|
||||
DYNAMO_DB_EXTENSION.getDynamoDbClient().transactWriteItems(TransactWriteItemsRequest.builder()
|
||||
.transactItems(sandboxAccounts.buildClaimWriteItem(uuid, clock.instant()))
|
||||
.build());
|
||||
|
||||
final byte[] accountRecoveryPassword = TestRandomUtil.nextBytes(16);
|
||||
final Account account =
|
||||
generateAccount(null, uuid, null, List.of(generateDevice(DEVICE_ID_1)), accountRecoveryPassword);
|
||||
assertThrows(AccountCreationConditionException.class,
|
||||
() -> accounts.create(account, receiptPresentation(), accountRecoveryPassword,
|
||||
List.of(sandboxAccounts.buildClaimWriteItem(uuid, clock.instant().plusSeconds(1)))));
|
||||
|
||||
assertTrue(accounts.getByAccountIdentifier(uuid).isEmpty());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@@ -2430,7 +2468,7 @@ class AccountsTest {
|
||||
private boolean createNumberlessAccount(final Account account, final ReceiptCredentialPresentation receiptCredentialPresentation, final byte[] accountRecoveryPassword) {
|
||||
try {
|
||||
return accounts.create(account, receiptCredentialPresentation, accountRecoveryPassword, Collections.emptyList());
|
||||
} catch (final AccountAlreadyExistsException | ReceiptAlreadyRedeemedException e) {
|
||||
} catch (final AccountAlreadyExistsException | ReceiptAlreadyRedeemedException | AccountCreationConditionException e) {
|
||||
throw new IllegalStateException(e);
|
||||
}
|
||||
}
|
||||
|
||||
+20
-19
@@ -152,6 +152,7 @@ public class AddRemoveDeviceIntegrationTest {
|
||||
svr2Client,
|
||||
mock(DisconnectionRequestManager.class),
|
||||
phoneNumberRecoveryPasswordsManager,
|
||||
mock(SandboxAccounts.class),
|
||||
scheduledExecutorService,
|
||||
scheduledExecutorService,
|
||||
clock,
|
||||
@@ -163,12 +164,12 @@ public class AddRemoveDeviceIntegrationTest {
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() throws InterruptedException {
|
||||
void tearDown() {
|
||||
accountsManager.stop();
|
||||
}
|
||||
|
||||
@Test
|
||||
void addDevice() throws LinkDeviceTokenAlreadyUsedException {
|
||||
void addDevice() throws LinkDeviceTokenAlreadyUsedException, DeviceLimitExceededException {
|
||||
final String number = PhoneNumberUtil.getInstance().format(
|
||||
PhoneNumberUtil.getInstance().getExampleNumber("US"),
|
||||
PhoneNumberUtil.PhoneNumberFormat.E164);
|
||||
@@ -190,7 +191,7 @@ public class AddRemoveDeviceIntegrationTest {
|
||||
true,
|
||||
Optional.empty(),
|
||||
Optional.empty()),
|
||||
accountsManager.generateLinkDeviceToken(account.getAccountIdentifier()));
|
||||
accountsManager.generateLinkDeviceToken(account));
|
||||
|
||||
assertEquals(2, updatedAccountAndDevice.first().getDevices().size());
|
||||
|
||||
@@ -212,7 +213,7 @@ public class AddRemoveDeviceIntegrationTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void addDeviceReusedToken() throws LinkDeviceTokenAlreadyUsedException {
|
||||
void addDeviceReusedToken() throws LinkDeviceTokenAlreadyUsedException, DeviceLimitExceededException {
|
||||
final String number = PhoneNumberUtil.getInstance().format(
|
||||
PhoneNumberUtil.getInstance().getExampleNumber("US"),
|
||||
PhoneNumberUtil.PhoneNumberFormat.E164);
|
||||
@@ -223,7 +224,7 @@ public class AddRemoveDeviceIntegrationTest {
|
||||
final Account account = AccountsHelper.createAccount(accountsManager, number);
|
||||
assertEquals(1, accountsManager.getByAccountIdentifier(account.getAccountIdentifier()).orElseThrow().getDevices().size());
|
||||
|
||||
final String linkDeviceToken = accountsManager.generateLinkDeviceToken(account.getAccountIdentifier());
|
||||
final String linkDeviceToken = accountsManager.generateLinkDeviceToken(account);
|
||||
|
||||
final Pair<Account, Device> updatedAccountAndDevice =
|
||||
accountsManager.addDevice(account.getAccountIdentifier(), new DeviceSpec(
|
||||
@@ -261,7 +262,7 @@ public class AddRemoveDeviceIntegrationTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void removeDevice() throws LinkDeviceTokenAlreadyUsedException {
|
||||
void removeDevice()throws LinkDeviceTokenAlreadyUsedException, DeviceLimitExceededException {
|
||||
final String number = PhoneNumberUtil.getInstance().format(
|
||||
PhoneNumberUtil.getInstance().getExampleNumber("US"),
|
||||
PhoneNumberUtil.PhoneNumberFormat.E164);
|
||||
@@ -283,7 +284,7 @@ public class AddRemoveDeviceIntegrationTest {
|
||||
true,
|
||||
Optional.empty(),
|
||||
Optional.empty()),
|
||||
accountsManager.generateLinkDeviceToken(account.getAccountIdentifier()));
|
||||
accountsManager.generateLinkDeviceToken(account));
|
||||
|
||||
final byte addedDeviceId = updatedAccountAndDevice.second().getId();
|
||||
|
||||
@@ -306,7 +307,7 @@ public class AddRemoveDeviceIntegrationTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void removeDevicePartialFailure() throws LinkDeviceTokenAlreadyUsedException {
|
||||
void removeDevicePartialFailure() throws LinkDeviceTokenAlreadyUsedException, DeviceLimitExceededException {
|
||||
final String number = PhoneNumberUtil.getInstance().format(
|
||||
PhoneNumberUtil.getInstance().getExampleNumber("US"),
|
||||
PhoneNumberUtil.PhoneNumberFormat.E164);
|
||||
@@ -330,7 +331,7 @@ public class AddRemoveDeviceIntegrationTest {
|
||||
true,
|
||||
Optional.empty(),
|
||||
Optional.empty()),
|
||||
accountsManager.generateLinkDeviceToken(account.getAccountIdentifier()));
|
||||
accountsManager.generateLinkDeviceToken(account));
|
||||
|
||||
final byte addedDeviceId = updatedAccountAndDevice.second().getId();
|
||||
|
||||
@@ -360,7 +361,7 @@ public class AddRemoveDeviceIntegrationTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void waitForNewLinkedDevice() throws LinkDeviceTokenAlreadyUsedException {
|
||||
void waitForNewLinkedDevice() throws LinkDeviceTokenAlreadyUsedException, DeviceLimitExceededException {
|
||||
final String number = PhoneNumberUtil.getInstance().format(
|
||||
PhoneNumberUtil.getInstance().getExampleNumber("US"),
|
||||
PhoneNumberUtil.PhoneNumberFormat.E164);
|
||||
@@ -370,7 +371,7 @@ public class AddRemoveDeviceIntegrationTest {
|
||||
|
||||
final Account account = AccountsHelper.createAccount(accountsManager, number);
|
||||
|
||||
final String linkDeviceToken = accountsManager.generateLinkDeviceToken(account.getAccountIdentifier());
|
||||
final String linkDeviceToken = accountsManager.generateLinkDeviceToken(account);
|
||||
final String linkDeviceTokenIdentifier = AccountsManager.getLinkDeviceTokenIdentifier(linkDeviceToken);
|
||||
|
||||
final CompletableFuture<Optional<DeviceInfo>> displacedFuture = accountsManager.waitForNewLinkedDevice(
|
||||
@@ -409,7 +410,7 @@ public class AddRemoveDeviceIntegrationTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void waitForNewLinkedDeviceAlreadyAdded() throws LinkDeviceTokenAlreadyUsedException {
|
||||
void waitForNewLinkedDeviceAlreadyAdded() throws LinkDeviceTokenAlreadyUsedException, DeviceLimitExceededException {
|
||||
final String number = PhoneNumberUtil.getInstance().format(
|
||||
PhoneNumberUtil.getInstance().getExampleNumber("US"),
|
||||
PhoneNumberUtil.PhoneNumberFormat.E164);
|
||||
@@ -419,7 +420,7 @@ public class AddRemoveDeviceIntegrationTest {
|
||||
|
||||
final Account account = AccountsHelper.createAccount(accountsManager, number);
|
||||
|
||||
final String linkDeviceToken = accountsManager.generateLinkDeviceToken(account.getAccountIdentifier());
|
||||
final String linkDeviceToken = accountsManager.generateLinkDeviceToken(account);
|
||||
final String linkDeviceTokenIdentifier = AccountsManager.getLinkDeviceTokenIdentifier(linkDeviceToken);
|
||||
|
||||
final Pair<Account, Device> updatedAccountAndDevice =
|
||||
@@ -452,13 +453,13 @@ public class AddRemoveDeviceIntegrationTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void waitForNewLinkedDeviceTimeout() {
|
||||
void waitForNewLinkedDeviceTimeout() throws Exception {
|
||||
final String number = PhoneNumberUtil.getInstance().format(
|
||||
PhoneNumberUtil.getInstance().getExampleNumber("US"),
|
||||
PhoneNumberUtil.PhoneNumberFormat.E164);
|
||||
final Account account = AccountsHelper.createAccount(accountsManager, number);
|
||||
|
||||
final String linkDeviceToken = accountsManager.generateLinkDeviceToken(UUID.randomUUID());
|
||||
final String linkDeviceToken = accountsManager.generateLinkDeviceToken(account);
|
||||
final String linkDeviceTokenIdentifier = AccountsManager.getLinkDeviceTokenIdentifier(linkDeviceToken);
|
||||
|
||||
final CompletableFuture<Optional<DeviceInfo>> linkedDeviceFuture = accountsManager.waitForNewLinkedDevice(
|
||||
@@ -477,7 +478,7 @@ public class AddRemoveDeviceIntegrationTest {
|
||||
"10_000,10_001,false", // pending message after now
|
||||
})
|
||||
void waitForMessageFetch(long currentTime, Long oldestMessage, boolean shouldWait)
|
||||
throws LinkDeviceTokenAlreadyUsedException {
|
||||
throws LinkDeviceTokenAlreadyUsedException, DeviceLimitExceededException {
|
||||
final String number = PhoneNumberUtil.getInstance().format(
|
||||
PhoneNumberUtil.getInstance().getExampleNumber("US"),
|
||||
PhoneNumberUtil.PhoneNumberFormat.E164);
|
||||
@@ -485,7 +486,7 @@ public class AddRemoveDeviceIntegrationTest {
|
||||
final ECKeyPair pniKeyPair = ECKeyPair.generate();
|
||||
final Account account = AccountsHelper.createAccount(accountsManager, number);
|
||||
|
||||
final String linkDeviceToken = accountsManager.generateLinkDeviceToken(UUID.randomUUID());
|
||||
final String linkDeviceToken = accountsManager.generateLinkDeviceToken(account);
|
||||
final String linkDeviceTokenIdentifier = AccountsManager.getLinkDeviceTokenIdentifier(linkDeviceToken);
|
||||
|
||||
accountsManager.addDevice(account.getAccountIdentifier(), new DeviceSpec(
|
||||
@@ -514,7 +515,7 @@ public class AddRemoveDeviceIntegrationTest {
|
||||
// preempted by the timeout check
|
||||
@Timeout(value = 10, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
|
||||
@Test
|
||||
void waitForMessageFetchRetries() throws LinkDeviceTokenAlreadyUsedException {
|
||||
void waitForMessageFetchRetries() throws LinkDeviceTokenAlreadyUsedException, DeviceLimitExceededException {
|
||||
final String number = PhoneNumberUtil.getInstance().format(
|
||||
PhoneNumberUtil.getInstance().getExampleNumber("US"),
|
||||
PhoneNumberUtil.PhoneNumberFormat.E164);
|
||||
@@ -522,7 +523,7 @@ public class AddRemoveDeviceIntegrationTest {
|
||||
final ECKeyPair pniKeyPair = ECKeyPair.generate();
|
||||
final Account account = AccountsHelper.createAccount(accountsManager, number);
|
||||
|
||||
final String linkDeviceToken = accountsManager.generateLinkDeviceToken(UUID.randomUUID());
|
||||
final String linkDeviceToken = accountsManager.generateLinkDeviceToken(account);
|
||||
final String linkDeviceTokenIdentifier = AccountsManager.getLinkDeviceTokenIdentifier(linkDeviceToken);
|
||||
|
||||
clock.pin(Instant.ofEpochMilli(0));
|
||||
|
||||
+9
@@ -343,6 +343,15 @@ public final class DynamoDbExtensionSchema {
|
||||
.build()),
|
||||
List.of(), List.of()),
|
||||
|
||||
SANDBOX_ACCOUNTS("sandbox_accounts_test",
|
||||
SandboxAccounts.KEY_ACCOUNT_UUID,
|
||||
null,
|
||||
List.of(AttributeDefinition.builder()
|
||||
.attributeName(SandboxAccounts.KEY_ACCOUNT_UUID)
|
||||
.attributeType(ScalarAttributeType.B)
|
||||
.build()),
|
||||
List.of(), List.of()),
|
||||
|
||||
SCHEDULED_JOBS("scheduled_jobs_test",
|
||||
JobScheduler.KEY_SCHEDULER_NAME,
|
||||
JobScheduler.ATTR_RUN_AT,
|
||||
|
||||
+5
-4
@@ -40,6 +40,7 @@ import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.junitpioneer.jupiter.cartesian.CartesianTest;
|
||||
import org.signal.libsignal.protocol.InvalidMessageException;
|
||||
import org.signal.libsignal.protocol.InvalidVersionException;
|
||||
import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage;
|
||||
@@ -82,12 +83,12 @@ class MessagesManagerTest {
|
||||
experimentEnrollmentManager);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void insert(final boolean mirrorInsert) {
|
||||
@CartesianTest
|
||||
void insert(@CartesianTest.Enum Envelope.Type envelopeType, @CartesianTest.Values(booleans = {true, false}) final boolean mirrorInsert) {
|
||||
final UUID sourceAci = UUID.randomUUID();
|
||||
final Envelope message = Envelope.newBuilder()
|
||||
.setSourceServiceId(new AciServiceIdentifier(sourceAci).toCompactByteString())
|
||||
.setType(envelopeType)
|
||||
.build();
|
||||
|
||||
if (mirrorInsert) {
|
||||
@@ -110,7 +111,7 @@ class MessagesManagerTest {
|
||||
|
||||
messagesManager.insert(destinationUuid, Map.of(Device.PRIMARY_ID, message));
|
||||
|
||||
verify(reportMessageManager).store(eq(sourceAci.toString()), any(UUID.class));
|
||||
verify(reportMessageManager, times(envelopeType.equals(Envelope.Type.SERVER_DELIVERY_RECEIPT) ? 0 : 1)).store(eq(sourceAci.toString()), any(UUID.class));
|
||||
|
||||
final Envelope syncMessage = Envelope.newBuilder(message)
|
||||
.setSourceServiceId(new AciServiceIdentifier(destinationUuid).toCompactByteString())
|
||||
|
||||
+7
-1
@@ -20,8 +20,14 @@ public class ReceiptCredentialTestUtil {
|
||||
public static ReceiptCredentialPresentation receiptPresentation()
|
||||
throws InvalidInputException, VerificationFailedException {
|
||||
|
||||
return receiptPresentation(1);
|
||||
}
|
||||
|
||||
public static ReceiptCredentialPresentation receiptPresentation(final long receiptLevel)
|
||||
throws InvalidInputException, VerificationFailedException {
|
||||
|
||||
return receiptPresentation(new ReceiptSerial(TestRandomUtil.nextBytes(ReceiptSerial.SIZE)), Instant.now().plus(
|
||||
Duration.ofDays(30)), 1);
|
||||
Duration.ofDays(30)), receiptLevel);
|
||||
}
|
||||
|
||||
public static ReceiptCredentialPresentation receiptPresentation(final Instant expiresAt, final long receiptLevel)
|
||||
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamoDbExtensionSchema.Tables;
|
||||
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItemsRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.TransactionCanceledException;
|
||||
|
||||
class SandboxAccountsTest {
|
||||
|
||||
@RegisterExtension
|
||||
static final DynamoDbExtension DYNAMO_DB_EXTENSION = new DynamoDbExtension(Tables.SANDBOX_ACCOUNTS);
|
||||
|
||||
private SandboxAccounts sandboxAccounts;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
sandboxAccounts = new SandboxAccounts(Tables.SANDBOX_ACCOUNTS.tableName(), DYNAMO_DB_EXTENSION.getDynamoDbClient());
|
||||
}
|
||||
|
||||
@Test
|
||||
void addClaimRelease() {
|
||||
final Instant now = Instant.now();
|
||||
|
||||
final UUID first = UUID.randomUUID();
|
||||
final UUID second = UUID.randomUUID();
|
||||
sandboxAccounts.add(first);
|
||||
sandboxAccounts.add(second);
|
||||
|
||||
assertThat(sandboxAccounts.getAvailable()).containsExactlyInAnyOrder(first, second);
|
||||
assertThat(sandboxAccounts.getAll()).containsExactlyInAnyOrder(
|
||||
new SandboxAccounts.SandboxAccountReservation(first, Optional.empty()),
|
||||
new SandboxAccounts.SandboxAccountReservation(second, Optional.empty()));
|
||||
|
||||
claim(first, now);
|
||||
assertThat(sandboxAccounts.getAvailable()).containsExactly(second);
|
||||
assertThat(sandboxAccounts.getAll()).containsExactlyInAnyOrder(
|
||||
new SandboxAccounts.SandboxAccountReservation(first, Optional.of(now.truncatedTo(ChronoUnit.SECONDS))),
|
||||
new SandboxAccounts.SandboxAccountReservation(second, Optional.empty()));
|
||||
|
||||
assertThat(sandboxAccounts.releaseAci(first, now.truncatedTo(ChronoUnit.SECONDS))).isTrue();
|
||||
assertThat(sandboxAccounts.releaseAci(first, now.truncatedTo(ChronoUnit.SECONDS))).isFalse();
|
||||
assertThat(sandboxAccounts.getAvailable()).containsExactlyInAnyOrder(first, second);
|
||||
}
|
||||
|
||||
@Test
|
||||
void claimFailure() {
|
||||
final Instant now = Instant.now();
|
||||
final UUID notInPool = UUID.randomUUID();
|
||||
final UUID alreadyClaimed = UUID.randomUUID();
|
||||
|
||||
sandboxAccounts.add(alreadyClaimed);
|
||||
claim(alreadyClaimed, now);
|
||||
|
||||
assertThrows(TransactionCanceledException.class, () -> claim(alreadyClaimed, now));
|
||||
assertThrows(TransactionCanceledException.class, () -> claim(notInPool, now));
|
||||
}
|
||||
|
||||
@Test
|
||||
void removeIfAvailable() {
|
||||
final UUID available = UUID.randomUUID();
|
||||
final UUID claimed = UUID.randomUUID();
|
||||
sandboxAccounts.add(available);
|
||||
sandboxAccounts.add(claimed);
|
||||
claim(claimed, Instant.now());
|
||||
|
||||
assertThat(sandboxAccounts.removeIfAvailable(available)).isTrue();
|
||||
assertThat(sandboxAccounts.removeIfAvailable(available)).isFalse();
|
||||
assertThat(sandboxAccounts.removeIfAvailable(claimed)).isFalse();
|
||||
assertThat(sandboxAccounts.getAll()).extracting(SandboxAccounts.SandboxAccountReservation::uuid).containsExactly(claimed);
|
||||
}
|
||||
|
||||
private void claim(final UUID aci, final Instant registeredAt) {
|
||||
DYNAMO_DB_EXTENSION.getDynamoDbClient().transactWriteItems(TransactWriteItemsRequest.builder()
|
||||
.transactItems(sandboxAccounts.buildClaimWriteItem(aci, registeredAt))
|
||||
.build());
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -33,6 +33,7 @@ import org.whispersystems.textsecuregcm.entities.AccountAttributes;
|
||||
import org.whispersystems.textsecuregcm.entities.DeviceAttributes;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.purchases.ReceiptLevel;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
@@ -356,7 +357,7 @@ public class AccountsHelper {
|
||||
|
||||
private static ReceiptCredentialPresentation generateReceiptCredentialPresentation() {
|
||||
try {
|
||||
return ReceiptCredentialTestUtil.receiptPresentation();
|
||||
return ReceiptCredentialTestUtil.receiptPresentation(ReceiptLevel.LOGIN.getValue());
|
||||
} catch (final InvalidInputException | VerificationFailedException e) {
|
||||
throw new AssertionError("Failed to generate receipt credential presentation", e);
|
||||
}
|
||||
|
||||
+1
-1
@@ -45,7 +45,7 @@ class ClearExpiredFoundationDbMessagesCommandTest {
|
||||
super(clock);
|
||||
|
||||
this.commandDependencies = new CommandDependencies(null, null, null, null, messagesManager, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null,
|
||||
null);
|
||||
null, null);
|
||||
this.dryRun = dryRun;
|
||||
}
|
||||
|
||||
|
||||
+1
@@ -89,6 +89,7 @@ class FinishPushNotificationExperimentCommandTest {
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null);
|
||||
|
||||
//noinspection unchecked
|
||||
|
||||
+1
@@ -69,6 +69,7 @@ class NotifyIdleDevicesCommandTest {
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null);
|
||||
|
||||
this.idleDeviceNotificationScheduler = idleDeviceNotificationScheduler;
|
||||
|
||||
+1
@@ -56,6 +56,7 @@ class RegenerateSecondaryDynamoDbTableDataCommandTest {
|
||||
null,
|
||||
dynamoDbRecoveryManager,
|
||||
null,
|
||||
null,
|
||||
null);
|
||||
|
||||
namespace = new Namespace(Map.of(
|
||||
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.workers;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import io.dropwizard.core.setup.Environment;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Stream;
|
||||
import javax.annotation.Nullable;
|
||||
import net.sourceforge.argparse4j.inf.Namespace;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.SandboxAccounts;
|
||||
import org.whispersystems.textsecuregcm.util.TestClock;
|
||||
import org.whispersystems.textsecuregcm.storage.SandboxAccounts.SandboxAccountReservation;
|
||||
|
||||
class RemoveExpiredSandboxAccountsCommandTest {
|
||||
|
||||
private static final Instant NOW = Instant.now();
|
||||
private static final Instant EXPIRED_REGISTRATION = NOW
|
||||
.minus(RemoveExpiredSandboxAccountsCommand.MAX_SANDBOX_ACCOUNT_AGE)
|
||||
.minusSeconds(1);
|
||||
private static final Instant FRESH_REGISTRATION = NOW.minus(Duration.ofHours(1));
|
||||
|
||||
private AccountsManager accountsManager;
|
||||
private SandboxAccounts sandboxAccounts;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
accountsManager = mock(AccountsManager.class);
|
||||
sandboxAccounts = mock(SandboxAccounts.class);
|
||||
when(sandboxAccounts.releaseAci(any(), any())).thenReturn(true);
|
||||
}
|
||||
|
||||
|
||||
static Stream<Arguments> processSandboxAccounts() {
|
||||
final Account account = mock(Account.class);
|
||||
return Stream.of(
|
||||
Arguments.argumentSet("stale-account", account, EXPIRED_REGISTRATION, true, true),
|
||||
Arguments.argumentSet("stale-deleted-account", null, EXPIRED_REGISTRATION, true, false),
|
||||
Arguments.argumentSet("fresh-account", account, FRESH_REGISTRATION, false, false),
|
||||
Arguments.argumentSet("fresh-deleted-account", null, FRESH_REGISTRATION, false, false),
|
||||
Arguments.argumentSet("untracked-account", account, null, false, false)
|
||||
);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void processSandboxAccounts(final @Nullable Account account, @Nullable final Instant registrationTime, final boolean expectRelease, final boolean expectDelete) throws Exception {
|
||||
final UUID aci = UUID.randomUUID();
|
||||
when(sandboxAccounts.getAll())
|
||||
.thenReturn(List.of(new SandboxAccountReservation(aci, Optional.ofNullable(registrationTime))));
|
||||
when(accountsManager.getByAccountIdentifier(aci))
|
||||
.thenReturn(Optional.ofNullable(account));
|
||||
|
||||
runCommand(false);
|
||||
|
||||
verify(sandboxAccounts, times(expectRelease ? 1 : 0)).releaseAci(aci, registrationTime);
|
||||
verify(accountsManager, times(expectDelete ? 1 : 0)).delete(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void dryRun() throws Exception {
|
||||
final UUID aci = UUID.randomUUID();
|
||||
when(sandboxAccounts.getAll())
|
||||
.thenReturn(List.of(new SandboxAccountReservation(aci, Optional.of(EXPIRED_REGISTRATION))));
|
||||
when(accountsManager.getByAccountIdentifier(aci))
|
||||
.thenReturn(Optional.of(mock(Account.class)));
|
||||
|
||||
runCommand(true);
|
||||
|
||||
verify(accountsManager, never()).delete(any(), any());
|
||||
verify(sandboxAccounts, never()).releaseAci(any(), any());
|
||||
}
|
||||
|
||||
private void runCommand(final boolean isDryRun) throws Exception {
|
||||
final CommandDependencies commandDependencies = mock(CommandDependencies.class);
|
||||
when(commandDependencies.accountsManager()).thenReturn(accountsManager);
|
||||
when(commandDependencies.sandboxAccounts()).thenReturn(sandboxAccounts);
|
||||
|
||||
final Namespace namespace = mock(Namespace.class);
|
||||
when(namespace.getBoolean(RemoveExpiredSandboxAccountsCommand.DRY_RUN_ARGUMENT)).thenReturn(isDryRun);
|
||||
|
||||
new RemoveExpiredSandboxAccountsCommand(TestClock.pinned(NOW))
|
||||
.run(mock(Environment.class), namespace, mock(WhisperServerConfiguration.class), commandDependencies);
|
||||
}
|
||||
}
|
||||
+1
@@ -77,6 +77,7 @@ class StartPushNotificationExperimentCommandTest {
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null);
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -39,7 +39,7 @@ public class TrimOversizedFoundationDbMessageQueuesCommandTest {
|
||||
final boolean dryRun) {
|
||||
|
||||
super();
|
||||
this.commandDependencies = new CommandDependencies(null, null, null, null, messagesManager, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null);
|
||||
this.commandDependencies = new CommandDependencies(null, null, null, null, messagesManager, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null);
|
||||
this.dryRun = dryRun;
|
||||
}
|
||||
|
||||
|
||||
@@ -151,6 +151,8 @@ dynamoDbTables:
|
||||
tableName: remote_config_test
|
||||
reportMessage:
|
||||
tableName: report_messages_test
|
||||
sandboxAccounts:
|
||||
tableName: sandbox_accounts_test
|
||||
scheduledJobs:
|
||||
tableName: scheduled_jobs_test
|
||||
expiration: P7D
|
||||
|
||||
+1
-1
Submodule spam-filter updated: 7b3100c6b0...643b5bd45e.
Reference in new issue
Block a user