mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-12-01 03:36:47 +00:00
Compare commits
209
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
58ad647d29 | ||
|
|
099073356c | ||
|
|
37038c4a63 | ||
|
|
ffa98e5b34 | ||
|
|
6013d00654 | ||
|
|
c03d63acb8 | ||
|
|
c6689ca07a | ||
|
|
1d0e2d29a7 | ||
|
|
d83d826236 | ||
|
|
2efe687b4b | ||
|
|
7cabc8f328 | ||
|
|
b57bdcaaea | ||
|
|
041643783d | ||
|
|
ed75ef917a | ||
|
|
7ea0885474 | ||
|
|
488e7c4913 | ||
|
|
6af4d41322 | ||
|
|
2b07a21477 | ||
|
|
4a42ff562d | ||
|
|
d4031893cc | ||
|
|
c2e3ab832c | ||
|
|
8c2f3c839f | ||
|
|
df188e6f15 | ||
|
|
12576daf1f | ||
|
|
46aefc0cbe | ||
|
|
9d4f9b4c12 | ||
|
|
3591e6bebd | ||
|
|
e12ba6b15b | ||
|
|
744b05244d | ||
|
|
c22b8fafa6 | ||
|
|
2194cf46e1 | ||
|
|
1a46ac122a | ||
|
|
55f85a81c6 | ||
|
|
5a8cb8a312 | ||
|
|
d641d1fc39 | ||
|
|
df56c65b54 | ||
|
|
1346fcb59e | ||
|
|
50f681ffe8 | ||
|
|
faef614d80 | ||
|
|
db2cd20dcb | ||
|
|
9ef6024291 | ||
|
|
a643a6c0f0 | ||
|
|
82e21b0c21 | ||
|
|
50e298a4f4 | ||
|
|
a0b9c40f6c | ||
|
|
359cf02161 | ||
|
|
6a1f01f876 | ||
|
|
0595acc48f | ||
|
|
46ff8d51dc | ||
|
|
dcd80e11f4 | ||
|
|
e1b1c7db8d | ||
|
|
99041bc593 | ||
|
|
dbd14481ed | ||
|
|
e3160bc717 | ||
|
|
6798958650 | ||
|
|
3a90c572b4 | ||
|
|
eab3c36d83 | ||
|
|
b7fee7b426 | ||
|
|
469955aec9 | ||
|
|
d1c9dff2c5 | ||
|
|
9491ebbe90 | ||
|
|
09b50383d7 | ||
|
|
8517eef3fe | ||
|
|
8955e31a1e | ||
|
|
f7a3971c64 | ||
|
|
552079d3c2 | ||
|
|
59d984e25d | ||
|
|
d17b9322b7 | ||
|
|
12bc175776 | ||
|
|
376458efa8 | ||
|
|
886984861f | ||
|
|
b248b6bc12 | ||
|
|
8d0d0d61f1 | ||
|
|
26c348520f | ||
|
|
ec79386306 | ||
|
|
093ac6fb16 | ||
|
|
68e2c511b7 | ||
|
|
47c82b42d9 | ||
|
|
e1a3b48c6e | ||
|
|
b8b17ae473 | ||
|
|
b203344ed4 | ||
|
|
6d30a45017 | ||
|
|
3f9863c441 | ||
|
|
47294ef6b8 | ||
|
|
2356d7c629 | ||
|
|
4908a0aa9e | ||
|
|
6032764052 | ||
|
|
908a41814b | ||
|
|
3ae145bd60 | ||
|
|
b086a73353 | ||
|
|
794e254d90 | ||
|
|
760c5737f9 | ||
|
|
ea17eee320 | ||
|
|
09ce79bd43 | ||
|
|
2dfd17af4a | ||
|
|
a9975e524b | ||
|
|
5d062285c2 | ||
|
|
e4b0f3ced5 | ||
|
|
6545bb9edb | ||
|
|
70ce6eff9e | ||
|
|
c84d96abee | ||
|
|
09eb42e5c6 | ||
|
|
06388b514c | ||
|
|
7c17a4067c | ||
|
|
48ada8e8ca | ||
|
|
282bcf6f34 | ||
|
|
1446d1acf8 | ||
|
|
aae94ffae3 | ||
|
|
ebd906a45d | ||
|
|
e30beb9c9f | ||
|
|
5a2e297991 | ||
|
|
ae1e7fbaa0 | ||
|
|
7e616a4056 | ||
|
|
c9e192564c | ||
|
|
47550d48e7 | ||
|
|
5cc76f48aa | ||
|
|
3ceaa8bd20 | ||
|
|
790b9bbf01 | ||
|
|
ee1016523f | ||
|
|
2f51778421 | ||
|
|
d3d68c2a60 | ||
|
|
0628b3e41c | ||
|
|
eac183495a | ||
|
|
0ae02da9be | ||
|
|
90fe634ddd | ||
|
|
1cae841ed6 | ||
|
|
a88560e557 | ||
|
|
3ca9a66323 | ||
|
|
3a4a55c245 | ||
|
|
f4a243861c | ||
|
|
68209f270e | ||
|
|
8af939d320 | ||
|
|
16a50935ea | ||
|
|
24ea10c451 | ||
|
|
95abda4870 | ||
|
|
c8993c4da8 | ||
|
|
d096798340 | ||
|
|
f2f5e0e26f | ||
|
|
9121032114 | ||
|
|
541bf968e5 | ||
|
|
8c3ebdcbab | ||
|
|
0593e9e89f | ||
|
|
0d412c88fd | ||
|
|
8280106493 | ||
|
|
a3e106fe04 | ||
|
|
981a04f33b | ||
|
|
26025e5abd | ||
|
|
4839a5ba70 | ||
|
|
85a1550485 | ||
|
|
77658415b2 | ||
|
|
68f27be7cd | ||
|
|
6460327372 | ||
|
|
a96c0ec7a3 | ||
|
|
33c0a27b85 | ||
|
|
d5b39cd496 | ||
|
|
5a35d69ed0 | ||
|
|
e1e94a33e2 | ||
|
|
18c9b177f3 | ||
|
|
1970741049 | ||
|
|
f16428ce2a | ||
|
|
14427523ae | ||
|
|
236b0496d3 | ||
|
|
f68ddf66e9 | ||
|
|
20685b6d69 | ||
|
|
4988b4e0f5 | ||
|
|
651e444875 | ||
|
|
2093fed554 | ||
|
|
cc7bb8b549 | ||
|
|
a99ac14c6a | ||
|
|
2c163352c3 | ||
|
|
fb6c4eca34 | ||
|
|
142e2cbe9d | ||
|
|
c70dd119d3 | ||
|
|
9e312cbdfa | ||
|
|
4d87b741cd | ||
|
|
d08bc4c413 | ||
|
|
f5d3d1e65d | ||
|
|
916314233f | ||
|
|
c7e6ee7297 | ||
|
|
557a6ecd4f | ||
|
|
0e04cac800 | ||
|
|
1db9258d39 | ||
|
|
2803c2acdb | ||
|
|
8be43566a4 | ||
|
|
d865cec2a4 | ||
|
|
6f0370a073 | ||
|
|
5b9f8177f2 | ||
|
|
6967e4e54b | ||
|
|
96fb0ac3ae | ||
|
|
7201938793 | ||
|
|
cdd6f78c73 | ||
|
|
ab94d3045d | ||
|
|
ff4e2bdfb7 | ||
|
|
ffed19d198 | ||
|
|
49d6a5e32d | ||
|
|
3ba7ba4f92 | ||
|
|
43ffc996db | ||
|
|
27f5f94c60 | ||
|
|
1d9734c824 | ||
|
|
717fb57a14 | ||
|
|
af1d21c225 | ||
|
|
3c8b2a82a3 | ||
|
|
0cb6f662c6 | ||
|
|
739ed56b4c | ||
|
|
9a19ef82fd | ||
|
|
5627ed141b | ||
|
|
e4a2af67b1 | ||
|
|
cba56f3263 | ||
|
|
1c3cf39b8a |
No files matched your search
@@ -11,8 +11,8 @@ jobs:
|
||||
contents: write
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7
|
||||
- uses: actions/setup-java@99b8673ff64fbf99d8d325f52d9a5bdedb8483e9 # v4.2.1
|
||||
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||
- uses: actions/setup-java@3a4f6e1af504cf6a31855fa899c6aa5355ba6c12 # v4.7.0
|
||||
with:
|
||||
distribution: 'temurin'
|
||||
java-version: '21'
|
||||
|
||||
@@ -13,13 +13,13 @@ jobs:
|
||||
id-token: write
|
||||
contents: read
|
||||
steps:
|
||||
- uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7
|
||||
- uses: actions/setup-java@99b8673ff64fbf99d8d325f52d9a5bdedb8483e9 # v4.2.1
|
||||
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||
- uses: actions/setup-java@3a4f6e1af504cf6a31855fa899c6aa5355ba6c12 # v4.7.0
|
||||
with:
|
||||
distribution: 'temurin'
|
||||
java-version: '21'
|
||||
cache: 'maven'
|
||||
- uses: aws-actions/configure-aws-credentials@5579c002bb4778aa43395ef1df492868a9a1c83f # v4.0.2
|
||||
- uses: aws-actions/configure-aws-credentials@ececac1a45f3b08a01d2dd070d28d111c5fe6722 # v4.1.0
|
||||
name: Configure AWS credentials from Test account
|
||||
with:
|
||||
role-to-assume: ${{ vars.AWS_ROLE }}
|
||||
|
||||
@@ -9,11 +9,12 @@ jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
container: ubuntu:22.04
|
||||
timeout-minutes: 20
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7
|
||||
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||
- name: Set up JDK 21
|
||||
uses: actions/setup-java@99b8673ff64fbf99d8d325f52d9a5bdedb8483e9 # v4.2.1
|
||||
uses: actions/setup-java@3a4f6e1af504cf6a31855fa899c6aa5355ba6c12 # v4.7.0
|
||||
with:
|
||||
distribution: 'temurin'
|
||||
java-version: 21
|
||||
|
||||
+2
-2
@@ -14,7 +14,7 @@
|
||||
# KIND, either express or implied. See the License for the
|
||||
# specific language governing permissions and limitations
|
||||
# under the License.
|
||||
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.8/apache-maven-3.9.8-bin.zip
|
||||
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip
|
||||
wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.3.2/maven-wrapper-3.3.2.jar
|
||||
distributionSha256Sum=8351955a9acf2f83c136c4eee0f6db894ab6265fdbe0a94b32a380307dbaa3e1
|
||||
distributionSha256Sum=4ec3f26fb1a692473aea0235c300bd20f0f9fe741947c82c1234cefd76ac3a3c
|
||||
wrapperSha256Sum=3d8f20ce6103913be8b52aef6d994e0c54705fb527324ceb9b835b338739c7a8
|
||||
@@ -8,9 +8,26 @@ Looking for protocol documentation? Check out the website!
|
||||
|
||||
https://signal.org/docs/
|
||||
|
||||
Cryptography Notice
|
||||
How to Build
|
||||
------------
|
||||
|
||||
```shell script
|
||||
$ ./mvnw clean test
|
||||
```
|
||||
|
||||
Security
|
||||
--------
|
||||
|
||||
Security issues should be sent to <a href=mailto:security@signal.org>security@signal.org</a>.
|
||||
|
||||
Help
|
||||
----
|
||||
|
||||
We cannot provide direct technical support. Get help running this software in your own environment in our [unofficial community forum][community forum].
|
||||
|
||||
Cryptography Notice
|
||||
-------------------
|
||||
|
||||
This distribution includes cryptographic software. The country in which you currently reside may have restrictions on the import, possession, use, and/or re-export to another country, of encryption software.
|
||||
BEFORE using any encryption software, please check your country's laws, regulations and policies concerning the import, possession, or use, and re-export of encryption software, to see if this is permitted.
|
||||
See <https://www.wassenaar.org/> for more information.
|
||||
@@ -19,8 +36,10 @@ The U.S. Government Department of Commerce, Bureau of Industry and Security (BIS
|
||||
The form and manner of this distribution makes it eligible for export under the License Exception ENC Technology Software Unrestricted (TSU) exception (see the BIS Export Administration Regulations, Section 740.13) for both object code and source code.
|
||||
|
||||
License
|
||||
---------------------
|
||||
-------
|
||||
|
||||
Copyright 2013-2024 Signal Messenger, LLC
|
||||
Copyright 2013 Signal Messenger, LLC
|
||||
|
||||
Licensed under the GNU AGPLv3: https://www.gnu.org/licenses/agpl-3.0.html
|
||||
|
||||
[community forum]: https://community.signalusers.org
|
||||
@@ -8,6 +8,7 @@ package org.signal.integration;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import org.signal.integration.config.Config;
|
||||
import org.whispersystems.textsecuregcm.metrics.NoopAwsSdkMetricPublisher;
|
||||
@@ -20,7 +21,6 @@ import org.whispersystems.textsecuregcm.storage.VerificationSessions;
|
||||
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
|
||||
import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
|
||||
|
||||
public class IntegrationTools {
|
||||
|
||||
@@ -28,6 +28,8 @@ public class IntegrationTools {
|
||||
|
||||
private final VerificationSessionManager verificationSessionManager;
|
||||
|
||||
private final PhoneNumberIdentifiers phoneNumberIdentifiers;
|
||||
|
||||
|
||||
public static IntegrationTools create(final Config config) {
|
||||
final AwsCredentialsProvider credentialsProvider = DefaultCredentialsProvider.builder().build();
|
||||
@@ -35,33 +37,32 @@ public class IntegrationTools {
|
||||
final DynamoDbAsyncClient dynamoDbAsyncClient =
|
||||
config.dynamoDbClient().buildAsyncClient(credentialsProvider, new NoopAwsSdkMetricPublisher());
|
||||
|
||||
final DynamoDbClient dynamoDbClient =
|
||||
config.dynamoDbClient().buildSyncClient(credentialsProvider, new NoopAwsSdkMetricPublisher());
|
||||
|
||||
final PhoneNumberIdentifiers phoneNumberIdentifiers =
|
||||
new PhoneNumberIdentifiers(dynamoDbAsyncClient, config.dynamoDbTables().phoneNumberIdentifiers());
|
||||
|
||||
final RegistrationRecoveryPasswords registrationRecoveryPasswords = new RegistrationRecoveryPasswords(
|
||||
config.dynamoDbTables().registrationRecovery(), Duration.ofDays(1), dynamoDbClient, dynamoDbAsyncClient);
|
||||
config.dynamoDbTables().registrationRecovery(), Duration.ofDays(1), dynamoDbAsyncClient, Clock.systemUTC());
|
||||
|
||||
final VerificationSessions verificationSessions = new VerificationSessions(
|
||||
dynamoDbAsyncClient, config.dynamoDbTables().verificationSessions(), Clock.systemUTC());
|
||||
|
||||
return new IntegrationTools(
|
||||
new RegistrationRecoveryPasswordsManager(registrationRecoveryPasswords, phoneNumberIdentifiers),
|
||||
new VerificationSessionManager(verificationSessions)
|
||||
new RegistrationRecoveryPasswordsManager(registrationRecoveryPasswords),
|
||||
new VerificationSessionManager(verificationSessions),
|
||||
new PhoneNumberIdentifiers(dynamoDbAsyncClient, config.dynamoDbTables().phoneNumberIdentifiers())
|
||||
);
|
||||
}
|
||||
|
||||
private IntegrationTools(
|
||||
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager,
|
||||
final VerificationSessionManager verificationSessionManager) {
|
||||
final VerificationSessionManager verificationSessionManager,
|
||||
final PhoneNumberIdentifiers phoneNumberIdentifiers) {
|
||||
this.registrationRecoveryPasswordsManager = registrationRecoveryPasswordsManager;
|
||||
this.verificationSessionManager = verificationSessionManager;
|
||||
this.phoneNumberIdentifiers = phoneNumberIdentifiers;
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> populateRecoveryPassword(final String e164, final byte[] password) {
|
||||
return registrationRecoveryPasswordsManager.storeForCurrentNumber(e164, password);
|
||||
public CompletableFuture<Void> populateRecoveryPassword(final String phoneNumber, final byte[] password) {
|
||||
return phoneNumberIdentifiers
|
||||
.getPhoneNumberIdentifier(phoneNumber)
|
||||
.thenCompose(pni -> registrationRecoveryPasswordsManager.store(pni, password));
|
||||
}
|
||||
|
||||
public CompletableFuture<Optional<String>> peekVerificationSessionPushChallenge(final String sessionId) {
|
||||
|
||||
@@ -8,7 +8,6 @@ package org.signal.integration;
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import org.apache.commons.lang3.tuple.Pair;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -27,11 +26,10 @@ public class MessagingTest {
|
||||
|
||||
try {
|
||||
final byte[] expectedContent = "Hello, World!".getBytes(StandardCharsets.UTF_8);
|
||||
final String contentBase64 = Base64.getEncoder().encodeToString(expectedContent);
|
||||
final IncomingMessage message = new IncomingMessage(1, Device.PRIMARY_ID, userB.registrationId(), contentBase64);
|
||||
final IncomingMessage message = new IncomingMessage(1, Device.PRIMARY_ID, userB.registrationId(), expectedContent);
|
||||
final IncomingMessageList messages = new IncomingMessageList(List.of(message), false, true, System.currentTimeMillis());
|
||||
|
||||
final Pair<Integer, SendMessageResponse> sendMessage = Operations
|
||||
Operations
|
||||
.apiPut("/v1/messages/%s".formatted(userB.aciUuid().toString()), messages)
|
||||
.authorized(userA)
|
||||
.execute(SendMessageResponse.class);
|
||||
@@ -40,7 +38,7 @@ public class MessagingTest {
|
||||
.authorized(userB)
|
||||
.execute(OutgoingMessageEntityList.class);
|
||||
|
||||
final byte[] actualContent = receiveMessages.getRight().messages().get(0).content();
|
||||
final byte[] actualContent = receiveMessages.getRight().messages().getFirst().content();
|
||||
assertArrayEquals(expectedContent, actualContent);
|
||||
} finally {
|
||||
Operations.deleteUser(userA);
|
||||
|
||||
@@ -37,45 +37,48 @@
|
||||
</modules>
|
||||
|
||||
<properties>
|
||||
<aws.sdk2.version>2.29.7</aws.sdk2.version>
|
||||
<braintree.version>3.37.0</braintree.version>
|
||||
<commons-csv.version>1.12.0</commons-csv.version>
|
||||
<commons-io.version>2.17.0</commons-io.version>
|
||||
<dropwizard.version>4.0.10</dropwizard.version>
|
||||
<dropwizard-metrics-datadog.version>1.1.13</dropwizard-metrics-datadog.version>
|
||||
<aws.sdk2.version>2.31.9</aws.sdk2.version>
|
||||
<braintree.version>3.40.0</braintree.version>
|
||||
<commons-csv.version>1.14.0</commons-csv.version>
|
||||
<commons-io.version>2.18.0</commons-io.version>
|
||||
<dropwizard.version>4.0.12</dropwizard.version>
|
||||
<dropwizard-metrics-datadog.version>1.1.14</dropwizard-metrics-datadog.version>
|
||||
<!-- can be updated to latest version with Dropwizard 5 (Jetty 12); will then need to disable telemetry -->
|
||||
<dynamodblocal.version>2.2.1</dynamodblocal.version>
|
||||
<google-cloud-libraries.version>26.50.0</google-cloud-libraries.version>
|
||||
<grpc.version>1.61.1</grpc.version> <!-- should be kept in sync with the value from Google libraries-bom -->
|
||||
<gson.version>2.11.0</gson.version>
|
||||
<google-cloud-libraries.version>26.57.0</google-cloud-libraries.version>
|
||||
<grpc.version>1.69.0</grpc.version> <!-- should be kept in sync with the value from Google libraries-bom -->
|
||||
<gson.version>2.12.1</gson.version>
|
||||
<!-- several libraries (AWS, Google Cloud) use Apache http components transitively, and we need to align them -->
|
||||
<httpcore.version>4.4.16</httpcore.version>
|
||||
<httpclient.version>4.5.14</httpclient.version>
|
||||
<jackson.version>2.18.1</jackson.version>
|
||||
<jaxb.version>2.3.1</jaxb.version>
|
||||
<jackson.version>2.18.3</jackson.version>
|
||||
<junit-pioneer.version>2.3.0</junit-pioneer.version>
|
||||
<jsr305.version>3.0.2</jsr305.version>
|
||||
<kotlin.version>1.9.24</kotlin.version>
|
||||
<kotlinx-serialization.version>1.5.1</kotlinx-serialization.version>
|
||||
<lettuce.version>6.4.1.RELEASE</lettuce.version>
|
||||
<libphonenumber.version>8.13.50</libphonenumber.version>
|
||||
<kotlin.version>2.1.20</kotlin.version>
|
||||
<!-- Logback 1.5.14+ has a null pointer bug: https://github.com/qos-ch/logback/issues/929. -->
|
||||
<logback.version>1.5.13</logback.version>
|
||||
<logback-access.version>2.0.5</logback-access.version>
|
||||
<lettuce.version>6.5.5.RELEASE</lettuce.version>
|
||||
<libphonenumber.version>9.0.2</libphonenumber.version>
|
||||
<logstash.logback.version>7.3</logstash.logback.version>
|
||||
<log4j-bom.version>2.23.1</log4j-bom.version>
|
||||
<luajava.version>3.4.0</luajava.version>
|
||||
<micrometer.version>1.13.6</micrometer.version>
|
||||
<netty.version>4.1.111.Final</netty.version>
|
||||
<protobuf.version>3.25.5</protobuf.version> <!-- must be greater than or equal to the value from Google libraries-bom, see https://protobuf.dev/support/cross-version-runtime-guarantee/ -->
|
||||
<log4j-bom.version>2.24.3</log4j-bom.version>
|
||||
<luajava.version>3.5.0</luajava.version>
|
||||
<micrometer.version>1.14.5</micrometer.version>
|
||||
<netty.version>4.1.119.Final</netty.version>
|
||||
<!-- Must be greater than or equal to the value from Google libraries-bom
|
||||
since some of its libraries generate code. See https://protobuf.dev/support/cross-version-runtime-guarantee/. -->
|
||||
<protobuf.version>3.25.5</protobuf.version>
|
||||
<pushy.version>0.15.4</pushy.version>
|
||||
<reactive.grpc.version>1.2.4</reactive.grpc.version>
|
||||
<reactor-bom.version>2023.0.11</reactor-bom.version> <!-- 3.6.x, see https://github.com/reactor/reactor#bom-versioning-scheme -->
|
||||
<resilience4j.version>2.2.0</resilience4j.version>
|
||||
<reactor-bom.version>2024.0.4</reactor-bom.version> <!-- 3.7.4, see https://github.com/reactor/reactor#bom-versioning-scheme -->
|
||||
<resilience4j.version>2.3.0</resilience4j.version>
|
||||
<semver4j.version>3.1.0</semver4j.version>
|
||||
<slf4j.version>2.0.13</slf4j.version>
|
||||
<slf4j.version>2.0.17</slf4j.version>
|
||||
<stripe.version>23.10.0</stripe.version>
|
||||
<swagger.version>2.2.25</swagger.version>
|
||||
<swagger.version>2.2.27</swagger.version>
|
||||
|
||||
<!-- 21.0.4_7-jre-jammy (note: always use the multi-arch manifest *LIST* here) -->
|
||||
<docker.image.sha256>870aae69d4521fdaf26e952f8026f75b37cb721e6302d4d4d7100f6b09823057</docker.image.sha256>
|
||||
<!-- eclipse-temurin:21.0.6_7-jre-jammy (note: always use the multi-arch manifest *LIST* here) -->
|
||||
<docker.image.sha256>02fc89fa8766a9ba221e69225f8d1c10bb91885ddbd3c112448e23488ba40ab6</docker.image.sha256>
|
||||
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
</properties>
|
||||
@@ -123,7 +126,7 @@
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.cloud</groupId>
|
||||
<artifactId>libraries-bom</artifactId>
|
||||
<artifactId>libraries-bom-protobuf3</artifactId>
|
||||
<version>${google-cloud-libraries.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
@@ -196,11 +199,6 @@
|
||||
<artifactId>lettuce-core</artifactId>
|
||||
<version>${lettuce.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.xml.bind</groupId>
|
||||
<artifactId>jaxb-api</artifactId>
|
||||
<version>${jaxb.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>net.logstash.logback</groupId>
|
||||
<artifactId>logstash-logback-encoder</artifactId>
|
||||
@@ -216,12 +214,6 @@
|
||||
<artifactId>dropwizard-metrics-datadog</artifactId>
|
||||
<version>${dropwizard-metrics-datadog.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.glassfish.jaxb</groupId>
|
||||
<artifactId>jaxb-runtime</artifactId>
|
||||
<version>${jaxb.version}</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-api</artifactId>
|
||||
@@ -236,12 +228,12 @@
|
||||
<dependency>
|
||||
<groupId>commons-logging</groupId>
|
||||
<artifactId>commons-logging</artifactId>
|
||||
<version>1.2</version>
|
||||
<version>1.3.5</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.ow2.asm</groupId>
|
||||
<artifactId>asm</artifactId>
|
||||
<version>9.5</version>
|
||||
<version>9.7.1 </version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
@@ -273,7 +265,7 @@
|
||||
<dependency>
|
||||
<groupId>org.signal</groupId>
|
||||
<artifactId>libsignal-server</artifactId>
|
||||
<version>0.60.0</version>
|
||||
<version>0.67.6</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.signal.forks</groupId>
|
||||
@@ -303,6 +295,21 @@
|
||||
<version>${dynamodblocal.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>ch.qos.logback</groupId>
|
||||
<artifactId>logback-core</artifactId>
|
||||
<version>${logback.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>ch.qos.logback</groupId>
|
||||
<artifactId>logback-classic</artifactId>
|
||||
<version>${logback.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>ch.qos.logback.access</groupId>
|
||||
<artifactId>logback-access-common</artifactId>
|
||||
<version>${logback-access.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
@@ -320,7 +327,7 @@
|
||||
<dependency>
|
||||
<groupId>org.wiremock</groupId>
|
||||
<artifactId>wiremock</artifactId>
|
||||
<version>3.9.1</version>
|
||||
<version>3.12.1</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
@@ -511,7 +518,7 @@
|
||||
<rules>
|
||||
<dependencyConvergence/>
|
||||
<requireMavenVersion>
|
||||
<version>3.8.6</version>
|
||||
<version>3.9.9</version>
|
||||
</requireMavenVersion>
|
||||
</rules>
|
||||
</configuration>
|
||||
|
||||
@@ -16,9 +16,6 @@ directoryV2.client.userIdTokenSharedSecret: bbcdefghijklmnopqrstuvwxyz0123456789
|
||||
svr2.userAuthenticationTokenSharedSecret: abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG= # base64-encoded secret shared with SVR2 to generate auth tokens for Signal users
|
||||
svr2.userIdTokenSharedSecret: bbcdefghijklmnopqrstuvwxyz0123456789ABCDEFG= # base64-encoded secret shared with SVR2 to generate auth identity tokens for Signal users
|
||||
|
||||
svr3.userAuthenticationTokenSharedSecret: cbcdefghijklmnopqrstuvwxyz0123456789ABCDEFG= # base64-encoded secret shared with SVR3 to generate auth tokens for Signal users
|
||||
svr3.userIdTokenSharedSecret: dbcdefghijklmnopqrstuvwxyz0123456789ABCDEFG= # base64-encoded secret shared with SVR3 to generate auth identity tokens for Signal users
|
||||
|
||||
tus.userAuthenticationTokenSharedSecret: abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG=
|
||||
|
||||
gcpAttachments.rsaSigningKey: |
|
||||
@@ -90,15 +87,13 @@ backupsZkConfig.serverSecret: ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijkl
|
||||
|
||||
paymentsService.userAuthenticationTokenSharedSecret: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= # base64-encoded 32-byte secret shared with MobileCoin services used to generate auth tokens for Signal users
|
||||
paymentsService.fixerApiKey: unset
|
||||
paymentsService.coinMarketCapApiKey: unset
|
||||
|
||||
artService.userAuthenticationTokenSharedSecret: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= # base64-encoded 32-byte secret not shared with any external service, but used in ArtController
|
||||
artService.userAuthenticationTokenUserIdSecret: AAAAAAAAAAA= # base64-encoded secret to obscure user phone numbers from Sticker Creator
|
||||
paymentsService.coinGeckoApiKey: unset
|
||||
|
||||
currentReportingKey.secret: AAAAAAAAAAA=
|
||||
currentReportingKey.salt: AAAAAAAAAAA=
|
||||
|
||||
turn.secret: AAAAAAAAAAA=
|
||||
registrationService.collationKeySalt: AAAAAAAAAAA=
|
||||
|
||||
turn.cloudflare.apiToken: ABCDEFGHIJKLM
|
||||
|
||||
linkDevice.secret: AAAAAAAAAAA=
|
||||
|
||||
+25
-61
@@ -92,6 +92,14 @@ appleAppStore:
|
||||
productIdToLevel: {}
|
||||
appleRootCerts: []
|
||||
|
||||
appleDeviceCheck:
|
||||
production: false
|
||||
teamId: 0123456789
|
||||
bundleId: bundle.name
|
||||
|
||||
deviceCheck:
|
||||
backupRedemptionDuration: P30D
|
||||
backupRedemptionLevel: 201
|
||||
|
||||
dynamoDbClient:
|
||||
region: us-west-2 # AWS Region
|
||||
@@ -103,6 +111,10 @@ dynamoDbTables:
|
||||
phoneNumberIdentifierTableName: Example_Accounts_PhoneNumberIdentifiers
|
||||
usernamesTableName: Example_Accounts_Usernames
|
||||
usedLinkDeviceTokensTableName: Example_Accounts_UsedLinkDeviceTokens
|
||||
appleDeviceChecks:
|
||||
tableName: Example_AppleDeviceChecks
|
||||
appleDeviceCheckPublicKeys:
|
||||
tableName: Example_AppleDeviceCheckPublicKeys
|
||||
backups:
|
||||
tableName: Example_Backups
|
||||
clientReleases:
|
||||
@@ -115,6 +127,11 @@ dynamoDbTables:
|
||||
tableName: Example_IssuedReceipts
|
||||
expiration: P30D # Duration of time until rows expire
|
||||
generator: abcdefg12345678= # random base64-encoded binary sequence
|
||||
maxIssuedReceiptsPerPaymentId:
|
||||
STRIPE: 1
|
||||
BRAINTREE: 1
|
||||
GOOGLE_PLAY_BILLING: 1
|
||||
APPLE_APP_STORE: 1
|
||||
ecKeys:
|
||||
tableName: Example_Keys
|
||||
ecSignedPreKeys:
|
||||
@@ -202,35 +219,6 @@ svr2:
|
||||
AAAAAAAAAAAAAAAAAAAA
|
||||
-----END CERTIFICATE-----
|
||||
|
||||
svr3:
|
||||
uri: svr3.example.com
|
||||
userAuthenticationTokenSharedSecret: secret://svr3.userAuthenticationTokenSharedSecret
|
||||
userIdTokenSharedSecret: secret://svr3.userIdTokenSharedSecret
|
||||
svrCaCertificates:
|
||||
- |
|
||||
-----BEGIN CERTIFICATE-----
|
||||
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
|
||||
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
|
||||
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
|
||||
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
|
||||
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
|
||||
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
|
||||
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
|
||||
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
|
||||
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
|
||||
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
|
||||
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
|
||||
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
|
||||
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
|
||||
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
|
||||
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
|
||||
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
|
||||
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
|
||||
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
|
||||
AAAAAAAAAAAAAAAAAAAA
|
||||
-----END CERTIFICATE-----
|
||||
|
||||
|
||||
messageCache: # Redis server configuration for message store cache
|
||||
persistDelayMinutes: 1
|
||||
cluster:
|
||||
@@ -339,13 +327,9 @@ paymentsService:
|
||||
- MOB
|
||||
externalClients:
|
||||
fixerApiKey: secret://paymentsService.fixerApiKey
|
||||
coinMarketCapApiKey: secret://paymentsService.coinMarketCapApiKey
|
||||
coinMarketCapCurrencyIds:
|
||||
MOB: 7878
|
||||
|
||||
artService:
|
||||
userAuthenticationTokenSharedSecret: secret://artService.userAuthenticationTokenSharedSecret
|
||||
userAuthenticationTokenUserIdSecret: secret://artService.userAuthenticationTokenUserIdSecret
|
||||
coinGeckoApiKey: secret://paymentsService.coinGeckoApiKey
|
||||
coinGeckoCurrencyIds:
|
||||
MOB: mobilecoin
|
||||
|
||||
badges:
|
||||
badges:
|
||||
@@ -415,6 +399,7 @@ registrationService:
|
||||
"example": "example"
|
||||
}
|
||||
identityTokenAudience: https://registration.example.com
|
||||
collationKeySalt: secret://registrationService.collationKeySalt
|
||||
registrationCaCertificate: | # Registration service TLS certificate trust root
|
||||
-----BEGIN CERTIFICATE-----
|
||||
ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyz
|
||||
@@ -488,7 +473,6 @@ keyTransparencyService:
|
||||
clientPrivateKey: secret://keyTransparencyService.clientPrivateKey
|
||||
|
||||
turn:
|
||||
secret: secret://turn.secret
|
||||
cloudflare:
|
||||
apiToken: secret://turn.cloudflare.apiToken
|
||||
endpoint: https://rtc.live.cloudflare.com/v1/turn/keys/LMNOP/credentials/generate
|
||||
@@ -500,34 +484,11 @@ turn:
|
||||
- turns:%s:443?transport=tcp
|
||||
ttl: 86400
|
||||
hostname: turn.cloudflare.example.com
|
||||
numHttpClients: 1
|
||||
|
||||
linkDevice:
|
||||
secret: secret://linkDevice.secret
|
||||
|
||||
maxmindCityDatabase:
|
||||
s3Region: a-region
|
||||
s3Bucket: a-bucket
|
||||
objectKey: an-object.tar.gz
|
||||
maxSize: 32777216
|
||||
|
||||
callingTurnDnsRecords:
|
||||
s3Region: a-region
|
||||
s3Bucket: a-bucket
|
||||
objectKey: an-object.tar.gz
|
||||
maxSize: 32777216
|
||||
|
||||
callingTurnPerformanceTable:
|
||||
s3Region: a-region
|
||||
s3Bucket: a-bucket
|
||||
objectKey: an-object.tar.gz
|
||||
maxSize: 32777216
|
||||
|
||||
callingTurnManualTable:
|
||||
s3Region: a-region
|
||||
s3Bucket: a-bucket
|
||||
objectKey: an-object.tar.gz
|
||||
maxSize: 32777216
|
||||
|
||||
noiseTunnel:
|
||||
port: 8443
|
||||
tlsKeyStoreFile: /path/to/file.p12
|
||||
@@ -543,3 +504,6 @@ externalRequestFilter:
|
||||
- /example
|
||||
permittedInternalRanges:
|
||||
- 127.0.0.0/8
|
||||
|
||||
idlePrimaryDeviceReminder:
|
||||
minIdleDuration: P30D
|
||||
+28
-21
@@ -11,13 +11,20 @@
|
||||
<artifactId>service</artifactId>
|
||||
|
||||
<properties>
|
||||
<firebase-admin.version>9.4.1</firebase-admin.version>
|
||||
<firebase-admin.version>9.4.3</firebase-admin.version>
|
||||
<java-uuid-generator.version>5.1.0</java-uuid-generator.version>
|
||||
<google-androidpublisher.version>v3-rev20241016-2.0.0</google-androidpublisher.version>
|
||||
<storekit.version>3.2.0</storekit.version>
|
||||
<google-androidpublisher.version>v3-rev20250318-2.0.0</google-androidpublisher.version>
|
||||
<storekit.version>3.4.0</storekit.version>
|
||||
<webauthn4j.version>0.28.6.RELEASE</webauthn4j.version>
|
||||
<java-jwt.version>4.5.0</java-jwt.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.auth0</groupId>
|
||||
<artifactId>java-jwt</artifactId>
|
||||
<version>${java-jwt.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.apis</groupId>
|
||||
<artifactId>google-api-services-androidpublisher</artifactId>
|
||||
@@ -35,6 +42,11 @@
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.webauthn4j</groupId>
|
||||
<artifactId>webauthn4j-appattest</artifactId>
|
||||
<version>${webauthn4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.swagger.core.v3</groupId>
|
||||
<artifactId>swagger-jaxrs2-jakarta</artifactId>
|
||||
@@ -131,8 +143,8 @@
|
||||
<artifactId>logback-core</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>ch.qos.logback</groupId>
|
||||
<artifactId>logback-access</artifactId>
|
||||
<groupId>ch.qos.logback.access</groupId>
|
||||
<artifactId>logback-access-common</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>ch.qos.logback</groupId>
|
||||
@@ -167,10 +179,6 @@
|
||||
<groupId>org.glassfish.jersey.core</groupId>
|
||||
<artifactId>jersey-client</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.glassfish.jaxb</groupId>
|
||||
<artifactId>jaxb-runtime</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>io.dropwizard</groupId>
|
||||
@@ -223,13 +231,7 @@
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-compress</artifactId>
|
||||
<version>1.26.0</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.maxmind.geoip2</groupId>
|
||||
<artifactId>geoip2</artifactId>
|
||||
<version>4.2.0</version>
|
||||
<version>1.27.1</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
@@ -237,21 +239,26 @@
|
||||
<artifactId>google-cloud-pubsub</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- resolve opentelemetry-semconv conflicts from lower in firebase-admin and firestore dependency trees -->
|
||||
<dependency>
|
||||
<groupId>com.google.firebase</groupId>
|
||||
<artifactId>firebase-admin</artifactId>
|
||||
<version>${firebase-admin.version}</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>io.opentelemetry.semconv</groupId>
|
||||
<artifactId>opentelemetry-semconv</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.opentelemetry.semconv</groupId>
|
||||
<artifactId>opentelemetry-semconv</artifactId>
|
||||
<version>1.25.0-alpha</version>
|
||||
<version>1.30.0</version>
|
||||
</dependency>
|
||||
<!-- resolve opentelemetry-semconv conflict from lower in firebase-admin dependency tree -->
|
||||
<dependency>
|
||||
<groupId>com.google.cloud</groupId>
|
||||
<artifactId>google-cloud-firestore</artifactId>
|
||||
<version>3.28.0</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>io.opentelemetry.semconv</groupId>
|
||||
@@ -362,7 +369,7 @@
|
||||
<dependency>
|
||||
<groupId>com.amazonaws</groupId>
|
||||
<artifactId>dynamodb-lock-client</artifactId>
|
||||
<version>1.2.0</version>
|
||||
<version>1.3.0</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
@@ -404,7 +411,7 @@
|
||||
<dependency>
|
||||
<groupId>com.googlecode.libphonenumber</groupId>
|
||||
<artifactId>geocoder</artifactId>
|
||||
<version>2.234</version>
|
||||
<version>3.2</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
|
||||
+36
-55
@@ -16,7 +16,7 @@ import java.util.Map;
|
||||
import org.whispersystems.textsecuregcm.attachments.TusConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.ApnConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.AppleAppStoreConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.ArtServiceConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.AppleDeviceCheckConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.AwsCredentialsProviderFactory;
|
||||
import org.whispersystems.textsecuregcm.configuration.BadgesConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.BraintreeConfiguration;
|
||||
@@ -25,6 +25,7 @@ import org.whispersystems.textsecuregcm.configuration.CdnConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.ClientReleaseConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.DatadogConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.DefaultAwsCredentialsFactory;
|
||||
import org.whispersystems.textsecuregcm.configuration.DeviceCheckConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.DirectoryV2Configuration;
|
||||
import org.whispersystems.textsecuregcm.configuration.DogstatsdConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.DynamoDbClientFactory;
|
||||
@@ -36,6 +37,7 @@ import org.whispersystems.textsecuregcm.configuration.FcmConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.GcpAttachmentsConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.GenericZkConfig;
|
||||
import org.whispersystems.textsecuregcm.configuration.GooglePlayBillingConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.IdlePrimaryDeviceReminderConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.KeyTransparencyServiceConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.LinkDeviceSecretConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.MaxDeviceConfiguration;
|
||||
@@ -50,7 +52,6 @@ import org.whispersystems.textsecuregcm.configuration.ReportMessageConfiguration
|
||||
import org.whispersystems.textsecuregcm.configuration.S3ObjectMonitorFactory;
|
||||
import org.whispersystems.textsecuregcm.configuration.SecureStorageServiceConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.SecureValueRecovery2Configuration;
|
||||
import org.whispersystems.textsecuregcm.configuration.SecureValueRecovery3Configuration;
|
||||
import org.whispersystems.textsecuregcm.configuration.ShortCodeExpanderConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.SpamFilterConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.StripeConfiguration;
|
||||
@@ -96,6 +97,16 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
@JsonProperty
|
||||
private AppleAppStoreConfiguration appleAppStore;
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
@JsonProperty
|
||||
private AppleDeviceCheckConfiguration appleDeviceCheck;
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
@JsonProperty
|
||||
private DeviceCheckConfiguration deviceCheck;
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
@JsonProperty
|
||||
@@ -145,10 +156,6 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
@Valid
|
||||
@JsonProperty
|
||||
private SecureValueRecovery2Configuration svr2;
|
||||
@NotNull
|
||||
@Valid
|
||||
@JsonProperty
|
||||
private SecureValueRecovery3Configuration svr3;
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
@@ -210,11 +217,6 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
@JsonProperty
|
||||
private PaymentsServiceConfiguration paymentsService;
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
private ArtServiceConfiguration artService;
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
@@ -299,27 +301,6 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
@JsonProperty
|
||||
private VirtualThreadConfiguration virtualThread = new VirtualThreadConfiguration(Duration.ofMillis(1));
|
||||
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
private S3ObjectMonitorFactory maxmindCityDatabase;
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
private S3ObjectMonitorFactory callingTurnDnsRecords;
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
private S3ObjectMonitorFactory callingTurnPerformanceTable;
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
private S3ObjectMonitorFactory callingTurnManualTable;
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
@@ -335,6 +316,13 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
@JsonProperty
|
||||
private KeyTransparencyServiceConfiguration keyTransparencyService;
|
||||
|
||||
@JsonProperty
|
||||
private boolean logMessageDeliveryLoops;
|
||||
|
||||
@JsonProperty
|
||||
private IdlePrimaryDeviceReminderConfiguration idlePrimaryDeviceReminder =
|
||||
new IdlePrimaryDeviceReminderConfiguration(Duration.ofDays(30));
|
||||
|
||||
public TlsKeyStoreConfiguration getTlsKeyStoreConfiguration() {
|
||||
return tlsKeyStore;
|
||||
}
|
||||
@@ -359,6 +347,14 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
return appleAppStore;
|
||||
}
|
||||
|
||||
public AppleDeviceCheckConfiguration getAppleDeviceCheck() {
|
||||
return appleDeviceCheck;
|
||||
}
|
||||
|
||||
public DeviceCheckConfiguration getDeviceCheck() {
|
||||
return deviceCheck;
|
||||
}
|
||||
|
||||
public DynamoDbClientFactory getDynamoDbClientConfiguration() {
|
||||
return dynamoDbClient;
|
||||
}
|
||||
@@ -390,9 +386,6 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
public SecureValueRecovery2Configuration getSvr2Configuration() {
|
||||
return svr2;
|
||||
}
|
||||
public SecureValueRecovery3Configuration getSvr3Configuration() {
|
||||
return svr3;
|
||||
}
|
||||
|
||||
public DirectoryV2Configuration getDirectoryV2Configuration() {
|
||||
return directoryV2;
|
||||
@@ -457,10 +450,6 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
return paymentsService;
|
||||
}
|
||||
|
||||
public ArtServiceConfiguration getArtServiceConfiguration() {
|
||||
return artService;
|
||||
}
|
||||
|
||||
public ZkConfig getZkConfig() {
|
||||
return zkConfig;
|
||||
}
|
||||
@@ -529,22 +518,6 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
return virtualThread;
|
||||
}
|
||||
|
||||
public S3ObjectMonitorFactory getMaxmindCityDatabase() {
|
||||
return maxmindCityDatabase;
|
||||
}
|
||||
|
||||
public S3ObjectMonitorFactory getCallingTurnDnsRecords() {
|
||||
return callingTurnDnsRecords;
|
||||
}
|
||||
|
||||
public S3ObjectMonitorFactory getCallingTurnPerformanceTable() {
|
||||
return callingTurnPerformanceTable;
|
||||
}
|
||||
|
||||
public S3ObjectMonitorFactory getCallingTurnManualTable() {
|
||||
return callingTurnManualTable;
|
||||
}
|
||||
|
||||
public NoiseWebSocketTunnelConfiguration getNoiseWebSocketTunnelConfiguration() {
|
||||
return noiseTunnel;
|
||||
}
|
||||
@@ -556,4 +529,12 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
public KeyTransparencyServiceConfiguration getKeyTransparencyServiceConfiguration() {
|
||||
return keyTransparencyService;
|
||||
}
|
||||
|
||||
public boolean logMessageDeliveryLoops() {
|
||||
return logMessageDeliveryLoops;
|
||||
}
|
||||
|
||||
public IdlePrimaryDeviceReminderConfiguration idlePrimaryDeviceReminderConfiguration() {
|
||||
return idlePrimaryDeviceReminder;
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import static com.codahale.metrics.MetricRegistry.name;
|
||||
import static java.util.Objects.requireNonNull;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
import com.webauthn4j.appattest.DeviceCheckManager;
|
||||
import io.dropwizard.auth.AuthDynamicFeature;
|
||||
import io.dropwizard.auth.AuthFilter;
|
||||
import io.dropwizard.auth.AuthValueFactoryProvider;
|
||||
@@ -81,9 +82,9 @@ import org.whispersystems.textsecuregcm.auth.CertificateGenerator;
|
||||
import org.whispersystems.textsecuregcm.auth.CloudflareTurnCredentialsManager;
|
||||
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestManager;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
|
||||
import org.whispersystems.textsecuregcm.auth.IdlePrimaryDeviceAuthenticatedWebSocketUpgradeFilter;
|
||||
import org.whispersystems.textsecuregcm.auth.PhoneVerificationTokenManager;
|
||||
import org.whispersystems.textsecuregcm.auth.RegistrationLockVerificationManager;
|
||||
import org.whispersystems.textsecuregcm.auth.TurnTokenGenerator;
|
||||
import org.whispersystems.textsecuregcm.auth.WebsocketRefreshApplicationEventListener;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.ProhibitAuthenticationInterceptor;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.RequireAuthenticationInterceptor;
|
||||
@@ -93,10 +94,6 @@ import org.whispersystems.textsecuregcm.backup.BackupsDb;
|
||||
import org.whispersystems.textsecuregcm.backup.Cdn3BackupCredentialGenerator;
|
||||
import org.whispersystems.textsecuregcm.backup.Cdn3RemoteStorageManager;
|
||||
import org.whispersystems.textsecuregcm.badges.ConfiguredProfileBadgeConverter;
|
||||
import org.whispersystems.textsecuregcm.calls.routing.CallDnsRecordsManager;
|
||||
import org.whispersystems.textsecuregcm.calls.routing.CallRoutingTableManager;
|
||||
import org.whispersystems.textsecuregcm.calls.routing.DynamicConfigTurnRouter;
|
||||
import org.whispersystems.textsecuregcm.calls.routing.TurnCallRouter;
|
||||
import org.whispersystems.textsecuregcm.captcha.CaptchaChecker;
|
||||
import org.whispersystems.textsecuregcm.captcha.CaptchaClient;
|
||||
import org.whispersystems.textsecuregcm.captcha.RegistrationCaptchaManager;
|
||||
@@ -107,13 +104,12 @@ import org.whispersystems.textsecuregcm.configuration.secrets.SecretsModule;
|
||||
import org.whispersystems.textsecuregcm.controllers.AccountController;
|
||||
import org.whispersystems.textsecuregcm.controllers.AccountControllerV2;
|
||||
import org.whispersystems.textsecuregcm.controllers.ArchiveController;
|
||||
import org.whispersystems.textsecuregcm.controllers.ArtController;
|
||||
import org.whispersystems.textsecuregcm.controllers.AttachmentControllerV4;
|
||||
import org.whispersystems.textsecuregcm.controllers.CallLinkController;
|
||||
import org.whispersystems.textsecuregcm.controllers.CallRoutingController;
|
||||
import org.whispersystems.textsecuregcm.controllers.CallRoutingControllerV2;
|
||||
import org.whispersystems.textsecuregcm.controllers.CertificateController;
|
||||
import org.whispersystems.textsecuregcm.controllers.ChallengeController;
|
||||
import org.whispersystems.textsecuregcm.controllers.DeviceCheckController;
|
||||
import org.whispersystems.textsecuregcm.controllers.DeviceController;
|
||||
import org.whispersystems.textsecuregcm.controllers.DirectoryV2Controller;
|
||||
import org.whispersystems.textsecuregcm.controllers.DonationController;
|
||||
@@ -129,11 +125,10 @@ import org.whispersystems.textsecuregcm.controllers.RegistrationController;
|
||||
import org.whispersystems.textsecuregcm.controllers.RemoteConfigController;
|
||||
import org.whispersystems.textsecuregcm.controllers.SecureStorageController;
|
||||
import org.whispersystems.textsecuregcm.controllers.SecureValueRecovery2Controller;
|
||||
import org.whispersystems.textsecuregcm.controllers.SecureValueRecovery3Controller;
|
||||
import org.whispersystems.textsecuregcm.controllers.StickerController;
|
||||
import org.whispersystems.textsecuregcm.controllers.SubscriptionController;
|
||||
import org.whispersystems.textsecuregcm.controllers.VerificationController;
|
||||
import org.whispersystems.textsecuregcm.currency.CoinMarketCapClient;
|
||||
import org.whispersystems.textsecuregcm.currency.CoinGeckoClient;
|
||||
import org.whispersystems.textsecuregcm.currency.CurrencyConversionManager;
|
||||
import org.whispersystems.textsecuregcm.currency.FixerClient;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
@@ -141,8 +136,8 @@ import org.whispersystems.textsecuregcm.filters.ExternalRequestFilter;
|
||||
import org.whispersystems.textsecuregcm.filters.RemoteAddressFilter;
|
||||
import org.whispersystems.textsecuregcm.filters.RemoteDeprecationFilter;
|
||||
import org.whispersystems.textsecuregcm.filters.RequestStatisticsFilter;
|
||||
import org.whispersystems.textsecuregcm.filters.RestDeprecationFilter;
|
||||
import org.whispersystems.textsecuregcm.filters.TimestampResponseFilter;
|
||||
import org.whispersystems.textsecuregcm.geo.MaxMindDatabaseManager;
|
||||
import org.whispersystems.textsecuregcm.grpc.AccountsAnonymousGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.AccountsGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.ErrorMappingInterceptor;
|
||||
@@ -154,6 +149,7 @@ import org.whispersystems.textsecuregcm.grpc.PaymentsGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.ProfileAnonymousGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.ProfileGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.RequestAttributesInterceptor;
|
||||
import org.whispersystems.textsecuregcm.grpc.ValidatingInterceptor;
|
||||
import org.whispersystems.textsecuregcm.grpc.net.GrpcClientConnectionManager;
|
||||
import org.whispersystems.textsecuregcm.grpc.net.ManagedDefaultEventLoopGroup;
|
||||
import org.whispersystems.textsecuregcm.grpc.net.ManagedLocalGrpcServer;
|
||||
@@ -163,10 +159,12 @@ import org.whispersystems.textsecuregcm.jetty.JettyHttpConfigurationCustomizer;
|
||||
import org.whispersystems.textsecuregcm.keytransparency.KeyTransparencyServiceClient;
|
||||
import org.whispersystems.textsecuregcm.limits.CardinalityEstimator;
|
||||
import org.whispersystems.textsecuregcm.limits.MessageDeliveryLoopMonitor;
|
||||
import org.whispersystems.textsecuregcm.limits.NoopMessageDeliveryLoopMonitor;
|
||||
import org.whispersystems.textsecuregcm.limits.PushChallengeManager;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimitByIpFilter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimitChallengeManager;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.limits.RedisMessageDeliveryLoopMonitor;
|
||||
import org.whispersystems.textsecuregcm.mappers.CompletionExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.DeviceLimitExceededExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.GrpcStatusRuntimeExceptionMapper;
|
||||
@@ -175,16 +173,19 @@ import org.whispersystems.textsecuregcm.mappers.ImpossiblePhoneNumberExceptionMa
|
||||
import org.whispersystems.textsecuregcm.mappers.InvalidWebsocketAddressExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.JsonMappingExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.NonNormalizedPhoneNumberExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.ObsoletePhoneNumberFormatExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.RegistrationServiceSenderExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.ServerRejectedExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.SubscriptionExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.metrics.BackupMetrics;
|
||||
import org.whispersystems.textsecuregcm.metrics.MessageMetrics;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsApplicationEventListener;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsHttpChannelListener;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.metrics.MicrometerAwsSdkMetricPublisher;
|
||||
import org.whispersystems.textsecuregcm.metrics.ReportedMessageMetricsListener;
|
||||
import org.whispersystems.textsecuregcm.metrics.TlsCertificateExpirationUtil;
|
||||
import org.whispersystems.textsecuregcm.metrics.TrafficSource;
|
||||
import org.whispersystems.textsecuregcm.providers.MultiRecipientMessageProvider;
|
||||
import org.whispersystems.textsecuregcm.providers.RedisClusterHealthCheck;
|
||||
@@ -225,6 +226,7 @@ import org.whispersystems.textsecuregcm.storage.MessagesCache;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesDynamoDb;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesManager;
|
||||
import org.whispersystems.textsecuregcm.storage.OneTimeDonationsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.PersistentTimer;
|
||||
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
|
||||
import org.whispersystems.textsecuregcm.storage.Profiles;
|
||||
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
|
||||
@@ -240,6 +242,9 @@ import org.whispersystems.textsecuregcm.storage.SubscriptionManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Subscriptions;
|
||||
import org.whispersystems.textsecuregcm.storage.VerificationSessionManager;
|
||||
import org.whispersystems.textsecuregcm.storage.VerificationSessions;
|
||||
import org.whispersystems.textsecuregcm.storage.devicecheck.AppleDeviceCheckManager;
|
||||
import org.whispersystems.textsecuregcm.storage.devicecheck.AppleDeviceCheckTrustAnchor;
|
||||
import org.whispersystems.textsecuregcm.storage.devicecheck.AppleDeviceChecks;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.AppleAppStoreManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.BankMandateTranslator;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.BraintreeManager;
|
||||
@@ -326,6 +331,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
bootstrap.addCommand(new BackupMetricsCommand(Clock.systemUTC()));
|
||||
bootstrap.addCommand(new RemoveExpiredLinkedDevicesCommand());
|
||||
bootstrap.addCommand(new NotifyIdleDevicesCommand());
|
||||
|
||||
bootstrap.addCommand(new ProcessScheduledJobsServiceCommand("process-idle-device-notification-jobs",
|
||||
"Processes scheduled jobs to send notifications to idle devices",
|
||||
new IdleDeviceNotificationSchedulerFactory()));
|
||||
@@ -360,6 +366,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
.forEach(connectorFactory -> {
|
||||
if (connectorFactory instanceof HttpsConnectorFactory h) {
|
||||
h.setKeyStorePassword(config.getTlsKeyStoreConfiguration().password().value());
|
||||
|
||||
TlsCertificateExpirationUtil.configureMetrics(h.getKeyStorePath(), h.getKeyStorePassword(), h.getKeyStoreType(), h.getKeyStoreProvider());
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -394,6 +402,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
.workQueue(messageDeletionQueue).build();
|
||||
|
||||
Accounts accounts = new Accounts(
|
||||
clock,
|
||||
dynamoDbClient,
|
||||
dynamoDbAsyncClient,
|
||||
config.getDynamoDbTables().getAccounts().getTableName(),
|
||||
@@ -423,15 +432,14 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
config.getDynamoDbTables().getRemoteConfig().getTableName());
|
||||
PushChallengeDynamoDb pushChallengeDynamoDb = new PushChallengeDynamoDb(dynamoDbClient,
|
||||
config.getDynamoDbTables().getPushChallenge().getTableName());
|
||||
ReportMessageDynamoDb reportMessageDynamoDb = new ReportMessageDynamoDb(dynamoDbClient,
|
||||
ReportMessageDynamoDb reportMessageDynamoDb = new ReportMessageDynamoDb(dynamoDbClient, dynamoDbAsyncClient,
|
||||
config.getDynamoDbTables().getReportMessage().getTableName(),
|
||||
config.getReportMessageConfiguration().getReportTtl());
|
||||
RegistrationRecoveryPasswords registrationRecoveryPasswords = new RegistrationRecoveryPasswords(
|
||||
config.getDynamoDbTables().getRegistrationRecovery().getTableName(),
|
||||
config.getDynamoDbTables().getRegistrationRecovery().getExpiration(),
|
||||
dynamoDbClient,
|
||||
dynamoDbAsyncClient
|
||||
);
|
||||
dynamoDbAsyncClient,
|
||||
clock);
|
||||
ClientPublicKeys clientPublicKeys =
|
||||
new ClientPublicKeys(dynamoDbAsyncClient, config.getDynamoDbTables().getClientPublicKeys().getTableName());
|
||||
|
||||
@@ -473,12 +481,14 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
.maxThreads(1).minThreads(1).build();
|
||||
ExecutorService fcmSenderExecutor = environment.lifecycle().executorService(name(getClass(), "fcmSender-%d"))
|
||||
.maxThreads(32).minThreads(32).workQueue(fcmSenderQueue).build();
|
||||
ExecutorService secureValueRecoveryServiceExecutor = environment.lifecycle()
|
||||
.executorService(name(getClass(), "secureValueRecoveryService-%d")).maxThreads(1).minThreads(1).build();
|
||||
ExecutorService secureValueRecovery2ServiceExecutor = environment.lifecycle()
|
||||
.executorService(name(getClass(), "secureValueRecoveryService2-%d")).maxThreads(1).minThreads(1).build();
|
||||
ExecutorService storageServiceExecutor = environment.lifecycle()
|
||||
.executorService(name(getClass(), "storageService-%d")).maxThreads(1).minThreads(1).build();
|
||||
ExecutorService virtualThreadEventLoggerExecutor = environment.lifecycle()
|
||||
.executorService(name(getClass(), "virtualThreadEventLogger-%d")).minThreads(1).maxThreads(1).build();
|
||||
ExecutorService asyncOperationQueueingExecutor = environment.lifecycle()
|
||||
.executorService(name(getClass(), "asyncOperationQueueing-%d")).minThreads(1).maxThreads(1).build();
|
||||
ScheduledExecutorService secureValueRecoveryServiceRetryExecutor = environment.lifecycle()
|
||||
.scheduledExecutorService(name(getClass(), "secureValueRecoveryServiceRetry-%d")).threads(1).build();
|
||||
ScheduledExecutorService storageServiceRetryExecutor = environment.lifecycle()
|
||||
@@ -502,8 +512,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
|
||||
// TODO: generally speaking this is a DynamoDB I/O executor for the accounts table; we should eventually have a general executor for speaking to the accounts table, but most of the server is still synchronous so this isn't widely useful yet
|
||||
ExecutorService batchIdentityCheckExecutor = environment.lifecycle().executorService(name(getClass(), "batchIdentityCheck-%d")).minThreads(32).maxThreads(32).build();
|
||||
ExecutorService multiRecipientMessageExecutor = environment.lifecycle()
|
||||
.executorService(name(getClass(), "multiRecipientMessage-%d")).minThreads(64).maxThreads(64).build();
|
||||
ExecutorService subscriptionProcessorExecutor = environment.lifecycle()
|
||||
.executorService(name(getClass(), "subscriptionProcessor-%d"))
|
||||
.maxThreads(availableProcessors) // mostly this is IO bound so tying to number of processors is tenuous at best
|
||||
@@ -559,6 +567,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
.scheduledExecutorService(name(getClass(), "cloudflareTurnRetry-%d")).threads(1).build();
|
||||
ScheduledExecutorService messagePollExecutor = environment.lifecycle()
|
||||
.scheduledExecutorService(name(getClass(), "messagePollExecutor-%d")).threads(1).build();
|
||||
ScheduledExecutorService provisioningWebsocketTimeoutExecutor = environment.lifecycle()
|
||||
.scheduledExecutorService(name(getClass(), "provisioningWebsocketTimeout-%d")).threads(1).build();
|
||||
|
||||
final ManagedNioEventLoopGroup dnsResolutionEventLoopGroup = new ManagedNioEventLoopGroup();
|
||||
final DnsNameResolver cloudflareDnsResolver = new DnsNameResolverBuilder(dnsResolutionEventLoopGroup.next())
|
||||
@@ -574,17 +584,13 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
config.getSecureStorageServiceConfiguration());
|
||||
ExternalServiceCredentialsGenerator paymentsCredentialsGenerator = PaymentsController.credentialsGenerator(
|
||||
config.getPaymentsServiceConfiguration());
|
||||
ExternalServiceCredentialsGenerator artCredentialsGenerator = ArtController.credentialsGenerator(
|
||||
config.getArtServiceConfiguration());
|
||||
ExternalServiceCredentialsGenerator svr2CredentialsGenerator = SecureValueRecovery2Controller.credentialsGenerator(
|
||||
config.getSvr2Configuration());
|
||||
ExternalServiceCredentialsGenerator svr3CredentialsGenerator = SecureValueRecovery3Controller.credentialsGenerator(
|
||||
config.getSvr3Configuration());
|
||||
|
||||
ExperimentEnrollmentManager experimentEnrollmentManager = new ExperimentEnrollmentManager(
|
||||
dynamicConfigurationManager);
|
||||
RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager =
|
||||
new RegistrationRecoveryPasswordsManager(registrationRecoveryPasswords, phoneNumberIdentifiers);
|
||||
new RegistrationRecoveryPasswordsManager(registrationRecoveryPasswords);
|
||||
UsernameHashZkProofVerifier usernameHashZkProofVerifier = new UsernameHashZkProofVerifier();
|
||||
|
||||
RegistrationServiceClient registrationServiceClient = config.getRegistrationServiceConfiguration()
|
||||
@@ -597,7 +603,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
config.getKeyTransparencyServiceConfiguration().clientPrivateKey().value(),
|
||||
keyTransparencyCallbackExecutor);
|
||||
SecureValueRecovery2Client secureValueRecovery2Client = new SecureValueRecovery2Client(svr2CredentialsGenerator,
|
||||
secureValueRecoveryServiceExecutor, secureValueRecoveryServiceRetryExecutor, config.getSvr2Configuration());
|
||||
secureValueRecovery2ServiceExecutor, secureValueRecoveryServiceRetryExecutor, config.getSvr2Configuration());
|
||||
SecureStorageClient secureStorageClient = new SecureStorageClient(storageCredentialsGenerator,
|
||||
storageServiceExecutor, storageServiceRetryExecutor, config.getSecureStorageServiceConfiguration());
|
||||
DisconnectionRequestManager disconnectionRequestManager = new DisconnectionRequestManager(pubsubClient, disconnectionRequestListenerExecutor);
|
||||
@@ -611,7 +617,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
ReportMessageManager reportMessageManager = new ReportMessageManager(reportMessageDynamoDb, rateLimitersCluster,
|
||||
config.getReportMessageConfiguration().getCounterTtl());
|
||||
MessagesManager messagesManager = new MessagesManager(messagesDynamoDb, messagesCache, reportMessageManager,
|
||||
messageDeletionAsyncExecutor);
|
||||
messageDeletionAsyncExecutor, Clock.systemUTC());
|
||||
AccountLockManager accountLockManager = new AccountLockManager(dynamoDbClient,
|
||||
config.getDynamoDbTables().getDeletedAccountsLock().getTableName());
|
||||
ClientPublicKeysManager clientPublicKeysManager =
|
||||
@@ -629,7 +635,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
PushNotificationManager pushNotificationManager =
|
||||
new PushNotificationManager(accountsManager, apnSender, fcmSender, pushNotificationScheduler);
|
||||
WebSocketConnectionEventManager webSocketConnectionEventManager =
|
||||
new WebSocketConnectionEventManager(accountsManager, pushNotificationManager, messagesCluster, clientEventExecutor);
|
||||
new WebSocketConnectionEventManager(accountsManager, pushNotificationManager, messagesCluster, clientEventExecutor, asyncOperationQueueingExecutor);
|
||||
RateLimiters rateLimiters = RateLimiters.createAndValidate(config.getLimitsConfiguration(),
|
||||
dynamicConfigurationManager, rateLimitersCluster);
|
||||
ProvisioningManager provisioningManager = new ProvisioningManager(pubsubClient);
|
||||
@@ -637,7 +643,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
config.getDynamoDbTables().getIssuedReceipts().getTableName(),
|
||||
config.getDynamoDbTables().getIssuedReceipts().getExpiration(),
|
||||
dynamoDbAsyncClient,
|
||||
config.getDynamoDbTables().getIssuedReceipts().getGenerator());
|
||||
config.getDynamoDbTables().getIssuedReceipts().getGenerator(),
|
||||
config.getDynamoDbTables().getIssuedReceipts().getmaxIssuedReceiptsPerPaymentId());
|
||||
OneTimeDonationsManager oneTimeDonationsManager = new OneTimeDonationsManager(
|
||||
config.getDynamoDbTables().getOnetimeDonations().getTableName(), config.getDynamoDbTables().getOnetimeDonations().getExpiration(), dynamoDbAsyncClient);
|
||||
RedeemedReceiptsManager redeemedReceiptsManager = new RedeemedReceiptsManager(clock,
|
||||
@@ -647,13 +654,13 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
Subscriptions subscriptions = new Subscriptions(
|
||||
config.getDynamoDbTables().getSubscriptions().getTableName(), dynamoDbAsyncClient);
|
||||
MessageDeliveryLoopMonitor messageDeliveryLoopMonitor =
|
||||
new MessageDeliveryLoopMonitor(rateLimitersCluster);
|
||||
config.logMessageDeliveryLoops() ? new RedisMessageDeliveryLoopMonitor(rateLimitersCluster) : new NoopMessageDeliveryLoopMonitor();
|
||||
|
||||
disconnectionRequestManager.addListener(webSocketConnectionEventManager);
|
||||
|
||||
final RegistrationLockVerificationManager registrationLockVerificationManager = new RegistrationLockVerificationManager(
|
||||
accountsManager, disconnectionRequestManager, svr2CredentialsGenerator, svr3CredentialsGenerator,
|
||||
registrationRecoveryPasswordsManager, pushNotificationManager, rateLimiters);
|
||||
accountsManager, disconnectionRequestManager, svr2CredentialsGenerator, registrationRecoveryPasswordsManager,
|
||||
pushNotificationManager, rateLimiters);
|
||||
|
||||
final ReportedMessageMetricsListener reportedMessageMetricsListener = new ReportedMessageMetricsListener(
|
||||
accountsManager);
|
||||
@@ -663,8 +670,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
|
||||
final MessageSender messageSender = new MessageSender(messagesManager, pushNotificationManager);
|
||||
final ReceiptSender receiptSender = new ReceiptSender(accountsManager, messageSender, receiptSenderExecutor);
|
||||
final TurnTokenGenerator turnTokenGenerator = new TurnTokenGenerator(dynamicConfigurationManager,
|
||||
config.getTurnConfiguration().secret().value());
|
||||
final CloudflareTurnCredentialsManager cloudflareTurnCredentialsManager = new CloudflareTurnCredentialsManager(
|
||||
config.getTurnConfiguration().cloudflare().apiToken().value(),
|
||||
config.getTurnConfiguration().cloudflare().endpoint(),
|
||||
@@ -672,6 +677,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
config.getTurnConfiguration().cloudflare().urls(),
|
||||
config.getTurnConfiguration().cloudflare().urlsWithIps(),
|
||||
config.getTurnConfiguration().cloudflare().hostname(),
|
||||
config.getTurnConfiguration().cloudflare().numHttpClients(),
|
||||
config.getTurnConfiguration().cloudflare().circuitBreaker(),
|
||||
cloudflareTurnHttpExecutor,
|
||||
config.getTurnConfiguration().cloudflare().retry(),
|
||||
@@ -692,9 +698,9 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
HttpClient currencyClient = HttpClient.newBuilder().version(HttpClient.Version.HTTP_2).connectTimeout(Duration.ofSeconds(10)).build();
|
||||
FixerClient fixerClient = config.getPaymentsServiceConfiguration().externalClients()
|
||||
.buildFixerClient(currencyClient);
|
||||
CoinMarketCapClient coinMarketCapClient = config.getPaymentsServiceConfiguration().externalClients()
|
||||
.buildCoinMarketCapClient(currencyClient);
|
||||
CurrencyConversionManager currencyManager = new CurrencyConversionManager(fixerClient, coinMarketCapClient,
|
||||
CoinGeckoClient coinGeckoClient = config.getPaymentsServiceConfiguration().externalClients()
|
||||
.buildCoinGeckoClient(currencyClient);
|
||||
CurrencyConversionManager currencyManager = new CurrencyConversionManager(fixerClient, coinGeckoClient,
|
||||
cacheCluster, config.getPaymentsServiceConfiguration().paymentCurrencies(), recurringJobExecutor, Clock.systemUTC());
|
||||
VirtualThreadPinEventMonitor virtualThreadPinEventMonitor = new VirtualThreadPinEventMonitor(
|
||||
virtualThreadEventLoggerExecutor,
|
||||
@@ -789,44 +795,19 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
cdn3RemoteStorageManager,
|
||||
clock);
|
||||
|
||||
final DynamicConfigTurnRouter configTurnRouter = new DynamicConfigTurnRouter(dynamicConfigurationManager);
|
||||
|
||||
MaxMindDatabaseManager geoIpCityDatabaseManager = new MaxMindDatabaseManager(
|
||||
recurringConfigSyncExecutor,
|
||||
awsCredentialsProvider,
|
||||
config.getMaxmindCityDatabase(),
|
||||
"city"
|
||||
);
|
||||
environment.lifecycle().manage(geoIpCityDatabaseManager);
|
||||
CallDnsRecordsManager callDnsRecordsManager = new CallDnsRecordsManager(
|
||||
recurringConfigSyncExecutor,
|
||||
awsCredentialsProvider,
|
||||
config.getCallingTurnDnsRecords()
|
||||
);
|
||||
environment.lifecycle().manage(callDnsRecordsManager);
|
||||
CallRoutingTableManager callRoutingTableManager = new CallRoutingTableManager(
|
||||
recurringConfigSyncExecutor,
|
||||
awsCredentialsProvider,
|
||||
config.getCallingTurnPerformanceTable(),
|
||||
"Performance"
|
||||
);
|
||||
environment.lifecycle().manage(callRoutingTableManager);
|
||||
CallRoutingTableManager manualCallRoutingTableManager = new CallRoutingTableManager(
|
||||
recurringConfigSyncExecutor,
|
||||
awsCredentialsProvider,
|
||||
config.getCallingTurnManualTable(),
|
||||
"Manual"
|
||||
);
|
||||
environment.lifecycle().manage(manualCallRoutingTableManager);
|
||||
|
||||
TurnCallRouter callRouter = new TurnCallRouter(
|
||||
callDnsRecordsManager,
|
||||
callRoutingTableManager,
|
||||
manualCallRoutingTableManager,
|
||||
configTurnRouter,
|
||||
geoIpCityDatabaseManager,
|
||||
false
|
||||
);
|
||||
final AppleDeviceChecks appleDeviceChecks = new AppleDeviceChecks(
|
||||
dynamoDbClient,
|
||||
DeviceCheckManager.createObjectConverter(),
|
||||
config.getDynamoDbTables().getAppleDeviceChecks().getTableName(),
|
||||
config.getDynamoDbTables().getAppleDeviceCheckPublicKeys().getTableName());
|
||||
final DeviceCheckManager deviceCheckManager = new DeviceCheckManager(new AppleDeviceCheckTrustAnchor());
|
||||
deviceCheckManager.getAttestationDataValidator().setProduction(config.getAppleDeviceCheck().production());
|
||||
final AppleDeviceCheckManager appleDeviceCheckManager = new AppleDeviceCheckManager(
|
||||
appleDeviceChecks,
|
||||
cacheCluster,
|
||||
deviceCheckManager,
|
||||
config.getAppleDeviceCheck().teamId(),
|
||||
config.getAppleDeviceCheck().bundleId());
|
||||
|
||||
final GrpcClientConnectionManager grpcClientConnectionManager = new GrpcClientConnectionManager();
|
||||
|
||||
@@ -842,6 +823,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
final RequestAttributesInterceptor requestAttributesInterceptor =
|
||||
new RequestAttributesInterceptor(grpcClientConnectionManager);
|
||||
|
||||
final ValidatingInterceptor validatingInterceptor = new ValidatingInterceptor();
|
||||
|
||||
final LocalAddress anonymousGrpcServerAddress = new LocalAddress("grpc-anonymous");
|
||||
final LocalAddress authenticatedGrpcServerAddress = new LocalAddress("grpc-authenticated");
|
||||
|
||||
@@ -855,6 +838,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
.intercept(
|
||||
new ExternalRequestFilter(config.getExternalRequestFilterConfiguration().permittedInternalRanges(),
|
||||
config.getExternalRequestFilterConfiguration().grpcMethods()))
|
||||
.intercept(validatingInterceptor)
|
||||
// TODO: specialize metrics with user-agent platform
|
||||
.intercept(metricCollectingServerInterceptor)
|
||||
.intercept(errorMappingInterceptor)
|
||||
@@ -877,6 +861,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
// http://grpc.github.io/grpc-java/javadoc/io/grpc/ServerBuilder.html#intercept-io.grpc.ServerInterceptor-
|
||||
serverBuilder
|
||||
// TODO: specialize metrics with user-agent platform
|
||||
.intercept(validatingInterceptor)
|
||||
.intercept(metricCollectingServerInterceptor)
|
||||
.intercept(errorMappingInterceptor)
|
||||
.intercept(remoteDeprecationFilter)
|
||||
@@ -974,8 +959,14 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
Set.of(websocketServletPath, provisioningWebsocketServletPath, "/health-check"));
|
||||
metricsHttpChannelListener.configure(environment);
|
||||
final MessageMetrics messageMetrics = new MessageMetrics();
|
||||
final BackupMetrics backupMetrics = new BackupMetrics();
|
||||
|
||||
// BufferingInterceptor is needed on the base environment but not the WebSocketEnvironment,
|
||||
// because we handle serialization of http responses on the websocket on our own and can
|
||||
// compute content lengths without it
|
||||
environment.jersey().register(new BufferingInterceptor());
|
||||
environment.jersey().register(new RestDeprecationFilter(dynamicConfigurationManager, experimentEnrollmentManager));
|
||||
|
||||
environment.jersey().register(new VirtualExecutorServiceProvider("managed-async-virtual-thread-"));
|
||||
environment.jersey().register(new RateLimitByIpFilter(rateLimiters));
|
||||
environment.jersey().register(new RequestStatisticsFilter(TrafficSource.HTTP));
|
||||
@@ -991,6 +982,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
config.getWebSocketConfiguration(), Duration.ofMillis(90000));
|
||||
webSocketEnvironment.jersey().register(new VirtualExecutorServiceProvider("managed-async-websocket-virtual-thread-"));
|
||||
webSocketEnvironment.setAuthenticator(new WebSocketAccountAuthenticator(accountAuthenticator, new AccountPrincipalSupplier(accountsManager)));
|
||||
webSocketEnvironment.setAuthenticatedWebSocketUpgradeFilter(new IdlePrimaryDeviceAuthenticatedWebSocketUpgradeFilter(
|
||||
keysManager, config.idlePrimaryDeviceReminderConfiguration().minIdleDuration(), Clock.systemUTC()));
|
||||
webSocketEnvironment.setConnectListener(
|
||||
new AuthenticatedConnectListener(receiptSender, messagesManager, messageMetrics, pushNotificationManager,
|
||||
pushNotificationScheduler, webSocketConnectionEventManager, websocketScheduledExecutor,
|
||||
@@ -1072,35 +1065,37 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
log.info("Registered spam filter: {}", filter.getClass().getName());
|
||||
});
|
||||
|
||||
final PersistentTimer persistentTimer = new PersistentTimer(rateLimitersCluster, clock);
|
||||
|
||||
final PhoneVerificationTokenManager phoneVerificationTokenManager = new PhoneVerificationTokenManager(
|
||||
registrationServiceClient, registrationRecoveryPasswordsManager, registrationRecoveryChecker);
|
||||
phoneNumberIdentifiers, registrationServiceClient, registrationRecoveryPasswordsManager, registrationRecoveryChecker);
|
||||
final List<Object> commonControllers = Lists.newArrayList(
|
||||
new AccountController(accountsManager, rateLimiters, turnTokenGenerator, registrationRecoveryPasswordsManager,
|
||||
new AccountController(accountsManager, rateLimiters, registrationRecoveryPasswordsManager,
|
||||
usernameHashZkProofVerifier),
|
||||
new AccountControllerV2(accountsManager, changeNumberManager, phoneVerificationTokenManager,
|
||||
registrationLockVerificationManager, rateLimiters),
|
||||
new ArtController(rateLimiters, artCredentialsGenerator),
|
||||
new AttachmentControllerV4(rateLimiters, gcsAttachmentGenerator, tusAttachmentGenerator,
|
||||
experimentEnrollmentManager),
|
||||
new ArchiveController(backupAuthManager, backupManager),
|
||||
new CallRoutingController(rateLimiters, callRouter, turnTokenGenerator, experimentEnrollmentManager, cloudflareTurnCredentialsManager),
|
||||
new CallRoutingControllerV2(rateLimiters, callRouter, turnTokenGenerator, experimentEnrollmentManager, cloudflareTurnCredentialsManager),
|
||||
new ArchiveController(backupAuthManager, backupManager, backupMetrics),
|
||||
new CallRoutingControllerV2(rateLimiters, cloudflareTurnCredentialsManager),
|
||||
new CallLinkController(rateLimiters, callingGenericZkSecretParams),
|
||||
new CertificateController(new CertificateGenerator(config.getDeliveryCertificate().certificate().value(),
|
||||
config.getDeliveryCertificate().ecPrivateKey(), config.getDeliveryCertificate().expiresDays()),
|
||||
zkAuthOperations, callingGenericZkSecretParams, clock),
|
||||
new ChallengeController(rateLimitChallengeManager, challengeConstraintChecker),
|
||||
new DeviceController(accountsManager, clientPublicKeysManager, rateLimiters, config.getMaxDevices()),
|
||||
new DeviceController(accountsManager, clientPublicKeysManager, rateLimiters, persistentTimer, config.getMaxDevices()),
|
||||
new DeviceCheckController(clock, backupAuthManager, appleDeviceCheckManager, rateLimiters,
|
||||
config.getDeviceCheck().backupRedemptionLevel(),
|
||||
config.getDeviceCheck().backupRedemptionDuration()),
|
||||
new DirectoryV2Controller(directoryV2CredentialsGenerator),
|
||||
new DonationController(clock, zkReceiptOperations, redeemedReceiptsManager, accountsManager, config.getBadges(),
|
||||
ReceiptCredentialPresentation::new),
|
||||
new KeysController(rateLimiters, keysManager, accountsManager, zkSecretParams, Clock.systemUTC()),
|
||||
new KeyTransparencyController(keyTransparencyServiceClient),
|
||||
new MessageController(rateLimiters, messageByteLimitCardinalityEstimator, messageSender, receiptSender,
|
||||
accountsManager, messagesManager, pushNotificationManager, pushNotificationScheduler, reportMessageManager,
|
||||
multiRecipientMessageExecutor, messageDeliveryScheduler, clientReleaseManager,
|
||||
dynamicConfigurationManager, zkSecretParams, spamChecker, messageMetrics, messageDeliveryLoopMonitor,
|
||||
accountsManager, messagesManager, phoneNumberIdentifiers, pushNotificationManager, pushNotificationScheduler,
|
||||
reportMessageManager, messageDeliveryScheduler, clientReleaseManager,
|
||||
zkSecretParams, spamChecker, messageMetrics, messageDeliveryLoopMonitor,
|
||||
Clock.systemUTC()),
|
||||
new PaymentsController(currencyManager, paymentsCredentialsGenerator),
|
||||
new ProfileController(clock, rateLimiters, accountsManager, profilesManager, dynamicConfigurationManager,
|
||||
@@ -1112,13 +1107,13 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
new RemoteConfigController(remoteConfigsManager, config.getRemoteConfigConfiguration().globalConfig(), clock),
|
||||
new SecureStorageController(storageCredentialsGenerator),
|
||||
new SecureValueRecovery2Controller(svr2CredentialsGenerator, accountsManager),
|
||||
new SecureValueRecovery3Controller(svr3CredentialsGenerator, accountsManager),
|
||||
new StickerController(rateLimiters, config.getCdnConfiguration().credentials().accessKeyId().value(),
|
||||
config.getCdnConfiguration().credentials().secretAccessKey().value(), config.getCdnConfiguration().region(),
|
||||
config.getCdnConfiguration().bucket()),
|
||||
new VerificationController(registrationServiceClient, new VerificationSessionManager(verificationSessions),
|
||||
pushNotificationManager, registrationCaptchaManager, registrationRecoveryPasswordsManager, rateLimiters,
|
||||
accountsManager, registrationFraudChecker, dynamicConfigurationManager, clock)
|
||||
pushNotificationManager, registrationCaptchaManager, registrationRecoveryPasswordsManager,
|
||||
phoneNumberIdentifiers, rateLimiters, accountsManager, registrationFraudChecker,
|
||||
dynamicConfigurationManager, clock)
|
||||
);
|
||||
if (config.getSubscription() != null && config.getOneTimeDonations() != null) {
|
||||
SubscriptionManager subscriptionManager = new SubscriptionManager(subscriptions,
|
||||
@@ -1140,7 +1135,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
webSocketEnvironment.getRequestLog(), Duration.ofMillis(60000));
|
||||
provisioningEnvironment.jersey().register(new WebsocketRefreshApplicationEventListener(accountsManager,
|
||||
disconnectionRequestManager));
|
||||
provisioningEnvironment.setConnectListener(new ProvisioningConnectListener(provisioningManager));
|
||||
provisioningEnvironment.setConnectListener(new ProvisioningConnectListener(provisioningManager, provisioningWebsocketTimeoutExecutor, Duration.ofSeconds(90)));
|
||||
provisioningEnvironment.jersey().register(new MetricsApplicationEventListener(TrafficSource.WEBSOCKET, clientReleaseManager));
|
||||
provisioningEnvironment.jersey().register(new KeepAliveController(webSocketConnectionEventManager));
|
||||
provisioningEnvironment.jersey().register(new TimestampResponseFilter());
|
||||
@@ -1192,6 +1187,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
new ServerRejectedExceptionMapper(),
|
||||
new ImpossiblePhoneNumberExceptionMapper(),
|
||||
new NonNormalizedPhoneNumberExceptionMapper(),
|
||||
new ObsoletePhoneNumberFormatExceptionMapper(),
|
||||
new RegistrationServiceSenderExceptionMapper(),
|
||||
new SubscriptionExceptionMapper(),
|
||||
new JsonMappingExceptionMapper()
|
||||
|
||||
+26
-4
@@ -6,6 +6,8 @@
|
||||
package org.whispersystems.textsecuregcm.auth;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
import io.netty.resolver.dns.DnsNameResolver;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import java.io.IOException;
|
||||
@@ -13,6 +15,7 @@ import java.net.Inet6Address;
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
@@ -22,6 +25,7 @@ import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.configuration.CircuitBreakerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.RetryConfiguration;
|
||||
import org.whispersystems.textsecuregcm.http.FaultTolerantHttpClient;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
|
||||
@@ -29,6 +33,9 @@ public class CloudflareTurnCredentialsManager {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(CloudflareTurnCredentialsManager.class);
|
||||
|
||||
private static final String CREDENTIAL_FETCH_TIMER_NAME = MetricsUtil.name(CloudflareTurnCredentialsManager.class,
|
||||
"credentialFetchLatency");
|
||||
|
||||
private final List<String> cloudflareTurnUrls;
|
||||
private final List<String> cloudflareTurnUrlsWithIps;
|
||||
private final String cloudflareTurnHostname;
|
||||
@@ -51,8 +58,9 @@ public class CloudflareTurnCredentialsManager {
|
||||
public CloudflareTurnCredentialsManager(final String cloudflareTurnApiToken,
|
||||
final String cloudflareTurnEndpoint, final long cloudflareTurnTtl, final List<String> cloudflareTurnUrls,
|
||||
final List<String> cloudflareTurnUrlsWithIps, final String cloudflareTurnHostname,
|
||||
final CircuitBreakerConfiguration circuitBreaker, final ExecutorService executor, final RetryConfiguration retry,
|
||||
final ScheduledExecutorService retryExecutor, final DnsNameResolver dnsNameResolver) {
|
||||
final int cloudflareTurnNumHttpClients, final CircuitBreakerConfiguration circuitBreaker,
|
||||
final ExecutorService executor, final RetryConfiguration retry, final ScheduledExecutorService retryExecutor,
|
||||
final DnsNameResolver dnsNameResolver) {
|
||||
|
||||
this.cloudflareTurnClient = FaultTolerantHttpClient.newBuilder()
|
||||
.withName("cloudflare-turn")
|
||||
@@ -60,6 +68,7 @@ public class CloudflareTurnCredentialsManager {
|
||||
.withExecutor(executor)
|
||||
.withRetry(retry)
|
||||
.withRetryExecutor(retryExecutor)
|
||||
.withNumClients(cloudflareTurnNumHttpClients)
|
||||
.build();
|
||||
this.cloudflareTurnUrls = cloudflareTurnUrls;
|
||||
this.cloudflareTurnUrlsWithIps = cloudflareTurnUrlsWithIps;
|
||||
@@ -93,11 +102,20 @@ public class CloudflareTurnCredentialsManager {
|
||||
throw new IOException(e);
|
||||
}
|
||||
|
||||
final Timer.Sample sample = Timer.start();
|
||||
final HttpResponse<String> response;
|
||||
try {
|
||||
response = cloudflareTurnClient.sendAsync(request, HttpResponse.BodyHandlers.ofString()).join();
|
||||
sample.stop(Timer.builder(CREDENTIAL_FETCH_TIMER_NAME)
|
||||
.publishPercentileHistogram(true)
|
||||
.tags("outcome", "success")
|
||||
.register(Metrics.globalRegistry));
|
||||
} catch (CompletionException e) {
|
||||
logger.warn("failed to make http request to Cloudflare Turn: {}", e.getMessage());
|
||||
sample.stop(Timer.builder(CREDENTIAL_FETCH_TIMER_NAME)
|
||||
.publishPercentileHistogram(true)
|
||||
.tags("outcome", "failure")
|
||||
.register(Metrics.globalRegistry));
|
||||
throw new IOException(ExceptionUtils.unwrap(e));
|
||||
}
|
||||
|
||||
@@ -109,8 +127,12 @@ public class CloudflareTurnCredentialsManager {
|
||||
final CloudflareTurnResponse cloudflareTurnResponse = SystemMapper.jsonMapper()
|
||||
.readValue(response.body(), CloudflareTurnResponse.class);
|
||||
|
||||
return new TurnToken(cloudflareTurnResponse.iceServers().username(),
|
||||
return new TurnToken(
|
||||
cloudflareTurnResponse.iceServers().username(),
|
||||
cloudflareTurnResponse.iceServers().credential(),
|
||||
cloudflareTurnUrls, cloudflareTurnComposedUrls, cloudflareTurnHostname);
|
||||
cloudflareTurnUrls == null ? Collections.emptyList() : cloudflareTurnUrls,
|
||||
cloudflareTurnComposedUrls,
|
||||
cloudflareTurnHostname
|
||||
);
|
||||
}
|
||||
}
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.auth;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import org.eclipse.jetty.websocket.server.JettyServerUpgradeRequest;
|
||||
import org.eclipse.jetty.websocket.server.JettyServerUpgradeResponse;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.KeysManager;
|
||||
import org.whispersystems.websocket.ReusableAuth;
|
||||
import org.whispersystems.websocket.auth.AuthenticatedWebSocketUpgradeFilter;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
|
||||
public class IdlePrimaryDeviceAuthenticatedWebSocketUpgradeFilter implements
|
||||
AuthenticatedWebSocketUpgradeFilter<AuthenticatedDevice> {
|
||||
|
||||
private final KeysManager keysManager;
|
||||
|
||||
private final Duration minIdleDuration;
|
||||
private final Clock clock;
|
||||
|
||||
@VisibleForTesting
|
||||
static final String ALERT_HEADER = "X-Signal-Alert";
|
||||
|
||||
@VisibleForTesting
|
||||
static final String IDLE_PRIMARY_DEVICE_ALERT = "idle-primary-device";
|
||||
|
||||
@VisibleForTesting
|
||||
static final String CRITICAL_IDLE_PRIMARY_DEVICE_ALERT = "critical-idle-primary-device";
|
||||
|
||||
@VisibleForTesting
|
||||
static final Duration PQ_KEY_CHECK_THRESHOLD = Duration.ofDays(120);
|
||||
|
||||
private static final Counter IDLE_PRIMARY_WARNING_COUNTER = Metrics.counter(
|
||||
MetricsUtil.name(IdlePrimaryDeviceAuthenticatedWebSocketUpgradeFilter.class, "idlePrimaryDeviceWarning"),
|
||||
"critical", "false");
|
||||
|
||||
private static final Counter CRITICAL_IDLE_PRIMARY_WARNING_COUNTER = Metrics.counter(
|
||||
MetricsUtil.name(IdlePrimaryDeviceAuthenticatedWebSocketUpgradeFilter.class, "idlePrimaryDeviceWarning"),
|
||||
"critical", "true");
|
||||
|
||||
public IdlePrimaryDeviceAuthenticatedWebSocketUpgradeFilter(final KeysManager keysManager,
|
||||
final Duration minIdleDuration,
|
||||
final Clock clock) {
|
||||
|
||||
this.keysManager = keysManager;
|
||||
this.minIdleDuration = minIdleDuration;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleAuthentication(final ReusableAuth<AuthenticatedDevice> authenticated,
|
||||
final JettyServerUpgradeRequest request,
|
||||
final JettyServerUpgradeResponse response) {
|
||||
|
||||
// No action needed if the connection is unauthenticated (in which case we don't know when we've last seen the
|
||||
// primary device) or if the authenticated device IS the primary device
|
||||
authenticated.ref()
|
||||
.filter(authenticatedDevice -> !authenticatedDevice.getAuthenticatedDevice().isPrimary())
|
||||
.ifPresent(authenticatedDevice -> {
|
||||
final Instant primaryDeviceLastSeen =
|
||||
Instant.ofEpochMilli(authenticatedDevice.getAccount().getPrimaryDevice().getLastSeen());
|
||||
|
||||
if (primaryDeviceLastSeen.isBefore(clock.instant().minus(PQ_KEY_CHECK_THRESHOLD)) &&
|
||||
keysManager.getLastResort(authenticatedDevice.getAccount().getIdentifier(IdentityType.ACI), Device.PRIMARY_ID)
|
||||
.join().isEmpty()) {
|
||||
|
||||
response.addHeader(ALERT_HEADER, CRITICAL_IDLE_PRIMARY_DEVICE_ALERT);
|
||||
CRITICAL_IDLE_PRIMARY_WARNING_COUNTER.increment();
|
||||
} else if (primaryDeviceLastSeen.isBefore(clock.instant().minus(minIdleDuration))) {
|
||||
response.addHeader(ALERT_HEADER, IDLE_PRIMARY_DEVICE_ALERT);
|
||||
IDLE_PRIMARY_WARNING_COUNTER.increment();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
+7
-2
@@ -25,6 +25,7 @@ import org.whispersystems.textsecuregcm.entities.PhoneVerificationRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.RegistrationServiceSession;
|
||||
import org.whispersystems.textsecuregcm.registration.RegistrationServiceClient;
|
||||
import org.whispersystems.textsecuregcm.spam.RegistrationRecoveryChecker;
|
||||
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
|
||||
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
|
||||
|
||||
public class PhoneVerificationTokenManager {
|
||||
@@ -33,13 +34,17 @@ public class PhoneVerificationTokenManager {
|
||||
private static final Duration REGISTRATION_RPC_TIMEOUT = Duration.ofSeconds(15);
|
||||
private static final long VERIFICATION_TIMEOUT_SECONDS = REGISTRATION_RPC_TIMEOUT.plusSeconds(1).getSeconds();
|
||||
|
||||
private final PhoneNumberIdentifiers phoneNumberIdentifiers;
|
||||
|
||||
private final RegistrationServiceClient registrationServiceClient;
|
||||
private final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager;
|
||||
private final RegistrationRecoveryChecker registrationRecoveryChecker;
|
||||
|
||||
public PhoneVerificationTokenManager(final RegistrationServiceClient registrationServiceClient,
|
||||
public PhoneVerificationTokenManager(final PhoneNumberIdentifiers phoneNumberIdentifiers,
|
||||
final RegistrationServiceClient registrationServiceClient,
|
||||
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager,
|
||||
final RegistrationRecoveryChecker registrationRecoveryChecker) {
|
||||
this.phoneNumberIdentifiers = phoneNumberIdentifiers;
|
||||
this.registrationServiceClient = registrationServiceClient;
|
||||
this.registrationRecoveryPasswordsManager = registrationRecoveryPasswordsManager;
|
||||
this.registrationRecoveryChecker = registrationRecoveryChecker;
|
||||
@@ -109,7 +114,7 @@ public class PhoneVerificationTokenManager {
|
||||
throw new ForbiddenException("recoveryPassword couldn't be verified");
|
||||
}
|
||||
try {
|
||||
final boolean verified = registrationRecoveryPasswordsManager.verify(number, recoveryPassword)
|
||||
final boolean verified = registrationRecoveryPasswordsManager.verify(phoneNumberIdentifiers.getPhoneNumberIdentifier(number).join(), recoveryPassword)
|
||||
.get(VERIFICATION_TIMEOUT_SECONDS, TimeUnit.SECONDS);
|
||||
if (!verified) {
|
||||
throw new ForbiddenException("recoveryPassword couldn't be verified");
|
||||
|
||||
+3
-14
@@ -22,7 +22,7 @@ import org.apache.commons.lang3.StringUtils;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.entities.PhoneVerificationRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.RegistrationLockFailure;
|
||||
import org.whispersystems.textsecuregcm.entities.Svr3Credentials;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.push.NotPushRegisteredException;
|
||||
@@ -55,7 +55,6 @@ public class RegistrationLockVerificationManager {
|
||||
private final AccountsManager accounts;
|
||||
private final DisconnectionRequestManager disconnectionRequestManager;
|
||||
private final ExternalServiceCredentialsGenerator svr2CredentialGenerator;
|
||||
private final ExternalServiceCredentialsGenerator svr3CredentialGenerator;
|
||||
private final RateLimiters rateLimiters;
|
||||
private final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager;
|
||||
private final PushNotificationManager pushNotificationManager;
|
||||
@@ -64,14 +63,12 @@ public class RegistrationLockVerificationManager {
|
||||
final AccountsManager accounts,
|
||||
final DisconnectionRequestManager disconnectionRequestManager,
|
||||
final ExternalServiceCredentialsGenerator svr2CredentialGenerator,
|
||||
final ExternalServiceCredentialsGenerator svr3CredentialGenerator,
|
||||
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager,
|
||||
final PushNotificationManager pushNotificationManager,
|
||||
final RateLimiters rateLimiters) {
|
||||
this.accounts = accounts;
|
||||
this.disconnectionRequestManager = disconnectionRequestManager;
|
||||
this.svr2CredentialGenerator = svr2CredentialGenerator;
|
||||
this.svr3CredentialGenerator = svr3CredentialGenerator;
|
||||
this.registrationRecoveryPasswordsManager = registrationRecoveryPasswordsManager;
|
||||
this.pushNotificationManager = pushNotificationManager;
|
||||
this.rateLimiters = rateLimiters;
|
||||
@@ -156,7 +153,7 @@ public class RegistrationLockVerificationManager {
|
||||
// This allows users to re-register via registration recovery password
|
||||
// instead of always being forced to fall back to SMS verification.
|
||||
if (!phoneVerificationType.equals(PhoneVerificationRequest.VerificationType.RECOVERY_PASSWORD) || clientRegistrationLock != null) {
|
||||
registrationRecoveryPasswordsManager.removeForNumber(updatedAccount.getNumber());
|
||||
registrationRecoveryPasswordsManager.remove(updatedAccount.getIdentifier(IdentityType.PNI));
|
||||
}
|
||||
|
||||
final List<Byte> deviceIds = updatedAccount.getDevices().stream().map(Device::getId).toList();
|
||||
@@ -172,8 +169,7 @@ public class RegistrationLockVerificationManager {
|
||||
throw new WebApplicationException(Response.status(FAILURE_HTTP_STATUS)
|
||||
.entity(new RegistrationLockFailure(
|
||||
existingRegistrationLock.getTimeRemaining().toMillis(),
|
||||
svr2FailureCredentials(existingRegistrationLock, updatedAccount),
|
||||
svr3FailureCredentials(existingRegistrationLock, updatedAccount)))
|
||||
svr2FailureCredentials(existingRegistrationLock, updatedAccount)))
|
||||
.build());
|
||||
}
|
||||
|
||||
@@ -187,11 +183,4 @@ public class RegistrationLockVerificationManager {
|
||||
return svr2CredentialGenerator.generateForUuid(account.getUuid());
|
||||
}
|
||||
|
||||
private @Nullable Svr3Credentials svr3FailureCredentials(final StoredRegistrationLock existingRegistrationLock, final Account account) {
|
||||
if (!existingRegistrationLock.needsFailureCredentials()) {
|
||||
return null;
|
||||
}
|
||||
final ExternalServiceCredentials creds = svr3CredentialGenerator.generateForUuid(account.getUuid());
|
||||
return new Svr3Credentials(creds.username(), creds.password(), account.getSvr3ShareSet());
|
||||
}
|
||||
}
|
||||
@@ -5,9 +5,14 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.auth;
|
||||
|
||||
import javax.annotation.Nonnull;
|
||||
import javax.annotation.Nullable;
|
||||
import java.util.List;
|
||||
|
||||
public record TurnToken(String username, String password, List<String> urls, @Nullable List<String> urlsWithIps,
|
||||
@Nullable String hostname) {
|
||||
public record TurnToken(
|
||||
String username,
|
||||
String password,
|
||||
@Nonnull List<String> urls,
|
||||
@Nonnull List<String> urlsWithIps,
|
||||
@Nullable String hostname) {
|
||||
}
|
||||
@@ -1,93 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2020 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.auth;
|
||||
|
||||
import java.security.InvalidKeyException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.SecureRandom;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import org.whispersystems.textsecuregcm.calls.routing.TurnServerOptions;
|
||||
import org.whispersystems.textsecuregcm.configuration.TurnUriConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicTurnConfiguration;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
import org.whispersystems.textsecuregcm.util.WeightedRandomSelect;
|
||||
|
||||
public class TurnTokenGenerator {
|
||||
|
||||
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
|
||||
|
||||
private final byte[] turnSecret;
|
||||
|
||||
private static final String ALGORITHM = "HmacSHA1";
|
||||
|
||||
private static final String WithUrlsProtocol = "00";
|
||||
|
||||
private static final String WithIpsProtocol = "01";
|
||||
|
||||
public TurnTokenGenerator(final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
|
||||
final byte[] turnSecret) {
|
||||
this.dynamicConfigurationManager = dynamicConfigurationManager;
|
||||
this.turnSecret = turnSecret;
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public TurnToken generate(final UUID aci) {
|
||||
return generateToken(null, null, urls(aci));
|
||||
}
|
||||
|
||||
public TurnToken generateWithTurnServerOptions(TurnServerOptions options) {
|
||||
return generateToken(options.hostname(), options.urlsWithIps(), options.urlsWithHostname());
|
||||
}
|
||||
|
||||
private TurnToken generateToken(String hostname, List<String> urlsWithIps, List<String> urlsWithHostname) {
|
||||
try {
|
||||
final Mac mac = Mac.getInstance(ALGORITHM);
|
||||
final long validUntilSeconds = Instant.now().plus(Duration.ofDays(1)).getEpochSecond();
|
||||
final long user = Util.ensureNonNegativeInt(new SecureRandom().nextInt());
|
||||
final String userTime = validUntilSeconds + ":" + user;
|
||||
final String protocol = urlsWithIps != null && !urlsWithIps.isEmpty()
|
||||
? WithIpsProtocol
|
||||
: WithUrlsProtocol;
|
||||
final String protocolUserTime = userTime + "#" + protocol;
|
||||
|
||||
mac.init(new SecretKeySpec(turnSecret, ALGORITHM));
|
||||
final String password = Base64.getEncoder().encodeToString(mac.doFinal(protocolUserTime.getBytes()));
|
||||
|
||||
return new TurnToken(protocolUserTime, password, urlsWithHostname, urlsWithIps, hostname);
|
||||
} catch (final NoSuchAlgorithmException | InvalidKeyException e) {
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
}
|
||||
|
||||
private List<String> urls(final UUID aci) {
|
||||
final DynamicTurnConfiguration turnConfig = dynamicConfigurationManager.getConfiguration().getTurnConfiguration();
|
||||
|
||||
// Check if number is enrolled to test out specific turn servers
|
||||
final Optional<TurnUriConfiguration> enrolled = turnConfig.getUriConfigs().stream()
|
||||
.filter(config -> config.getEnrolledAcis().contains(aci))
|
||||
.findFirst();
|
||||
|
||||
if (enrolled.isPresent()) {
|
||||
return enrolled.get().getUris();
|
||||
}
|
||||
|
||||
// Otherwise, select from turn server sets by weighted choice
|
||||
return WeightedRandomSelect.select(turnConfig
|
||||
.getUriConfigs()
|
||||
.stream()
|
||||
.map(c -> new Pair<>(c.getUris(), c.getWeight())).toList());
|
||||
}
|
||||
}
|
||||
+41
@@ -7,6 +7,9 @@ package org.whispersystems.textsecuregcm.auth;
|
||||
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.Collection;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
public class UnidentifiedAccessUtil {
|
||||
|
||||
@@ -31,4 +34,42 @@ public class UnidentifiedAccessUtil {
|
||||
.map(targetUnidentifiedAccessKey -> MessageDigest.isEqual(targetUnidentifiedAccessKey, unidentifiedAccessKey))
|
||||
.orElse(false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether an action (e.g. sending a message or retrieving pre-keys) may be taken on the collection of target
|
||||
* accounts by an actor presenting the given combined unidentified access key.
|
||||
*
|
||||
* @param targetAccounts the accounts on which an actor wishes to take an action
|
||||
* @param combinedUnidentifiedAccessKey the unidentified access key presented by the actor
|
||||
*
|
||||
* @return {@code true} if an actor presenting the given unidentified access key has permission to take an action on
|
||||
* the target accounts or {@code false} otherwise
|
||||
*/
|
||||
public static boolean checkUnidentifiedAccess(final Collection<Account> targetAccounts, final byte[] combinedUnidentifiedAccessKey) {
|
||||
return MessageDigest.isEqual(getCombinedUnidentifiedAccessKey(targetAccounts), combinedUnidentifiedAccessKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates a combined unidentified access key for the given collection of accounts.
|
||||
*
|
||||
* @param accounts the accounts from which to derive a combined unidentified access key
|
||||
* @return a combined unidentified access key
|
||||
*
|
||||
* @throws IllegalArgumentException if one or more of the given accounts had an unidentified access key with an
|
||||
* unexpected length
|
||||
*/
|
||||
public static byte[] getCombinedUnidentifiedAccessKey(final Collection<Account> accounts) {
|
||||
return accounts.stream()
|
||||
.filter(Predicate.not(Account::isUnrestrictedUnidentifiedAccess))
|
||||
.map(account ->
|
||||
account.getUnidentifiedAccessKey()
|
||||
.filter(b -> b.length == UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH)
|
||||
.orElseThrow(IllegalArgumentException::new))
|
||||
.reduce(new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH],
|
||||
(a, b) -> {
|
||||
final byte[] xor = new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH];
|
||||
IntStream.range(0, UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH).forEach(i -> xor[i] = (byte) (a[i] ^ b[i]));
|
||||
return xor;
|
||||
});
|
||||
}
|
||||
}
|
||||
+45
-11
@@ -14,6 +14,7 @@ import java.time.temporal.ChronoUnit;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
import java.util.stream.Stream;
|
||||
import javax.annotation.Nullable;
|
||||
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
|
||||
@@ -114,9 +115,17 @@ public class BackupAuthManager {
|
||||
return CompletableFuture.completedFuture(null);
|
||||
}
|
||||
|
||||
return rateLimiters.forDescriptor(RateLimiters.For.SET_BACKUP_ID)
|
||||
.validateAsync(account.getUuid())
|
||||
.thenCompose(ignored -> this.accountsManager
|
||||
CompletionStage<Void> rateLimitFuture = rateLimiters
|
||||
.forDescriptor(RateLimiters.For.SET_BACKUP_ID)
|
||||
.validateAsync(account.getUuid());
|
||||
|
||||
if (!mediaCredentialRequestMatches && hasActiveVoucher(account)) {
|
||||
rateLimitFuture = rateLimitFuture.thenCombine(
|
||||
rateLimiters.forDescriptor(RateLimiters.For.SET_PAID_MEDIA_BACKUP_ID).validateAsync(account.getUuid()),
|
||||
(ignore1, ignore2) -> null);
|
||||
}
|
||||
|
||||
return rateLimitFuture.thenCompose(ignored -> this.accountsManager
|
||||
.updateAsync(account, a -> a.setBackupCredentialRequests(serializedMessageCredentialRequest, serializedMediaCredentialRequest))
|
||||
.thenRun(Util.NOOP))
|
||||
.toCompletableFuture();
|
||||
@@ -227,6 +236,12 @@ public class BackupAuthManager {
|
||||
.asRuntimeException();
|
||||
}
|
||||
|
||||
if (account.getBackupCredentialRequest(BackupCredentialType.MEDIA).isEmpty()) {
|
||||
throw Status.ABORTED
|
||||
.withDescription("account must have a backup-id commitment")
|
||||
.asRuntimeException();
|
||||
}
|
||||
|
||||
return redeemedReceiptsManager
|
||||
.put(receiptSerial, receiptExpiration.getEpochSecond(), receiptLevel, account.getUuid())
|
||||
.thenCompose(receiptAllowed -> {
|
||||
@@ -235,13 +250,28 @@ public class BackupAuthManager {
|
||||
.withDescription("receipt serial is already redeemed")
|
||||
.asRuntimeException();
|
||||
}
|
||||
return accountsManager.updateAsync(account, a -> {
|
||||
final Account.BackupVoucher newPayment = new Account.BackupVoucher(receiptLevel, receiptExpiration);
|
||||
final Account.BackupVoucher existingPayment = a.getBackupVoucher();
|
||||
a.setBackupVoucher(merge(existingPayment, newPayment));
|
||||
});
|
||||
})
|
||||
.thenRun(Util.NOOP);
|
||||
return extendBackupVoucher(account, new Account.BackupVoucher(receiptLevel, receiptExpiration));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Extend the duration of the backup voucher on an account.
|
||||
*
|
||||
* @param account The account to update
|
||||
* @param backupVoucher The backup voucher to apply to this account
|
||||
* @return A future that completes once the account has been updated to have at least the level and expiration
|
||||
* in the provided voucher.
|
||||
*/
|
||||
public CompletableFuture<Void> extendBackupVoucher(final Account account, final Account.BackupVoucher backupVoucher) {
|
||||
return accountsManager.updateAsync(account, a -> {
|
||||
// Receipt credential expirations must be day aligned. Make sure any manually set backupVoucher is also day
|
||||
// aligned
|
||||
final Account.BackupVoucher newPayment = new Account.BackupVoucher(
|
||||
backupVoucher.receiptLevel(),
|
||||
backupVoucher.expiration().truncatedTo(ChronoUnit.DAYS));
|
||||
final Account.BackupVoucher existingPayment = a.getBackupVoucher();
|
||||
a.setBackupVoucher(merge(existingPayment, newPayment));
|
||||
}).thenRun(Util.NOOP);
|
||||
}
|
||||
|
||||
private static Account.BackupVoucher merge(@Nullable final Account.BackupVoucher prev,
|
||||
@@ -265,8 +295,12 @@ public class BackupAuthManager {
|
||||
return next;
|
||||
}
|
||||
|
||||
private boolean hasActiveVoucher(final Account account) {
|
||||
return account.getBackupVoucher() != null && clock.instant().isBefore(account.getBackupVoucher().expiration());
|
||||
}
|
||||
|
||||
private boolean hasExpiredVoucher(final Account account) {
|
||||
return account.getBackupVoucher() != null && clock.instant().isAfter(account.getBackupVoucher().expiration());
|
||||
return account.getBackupVoucher() != null && !hasActiveVoucher(account);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -46,7 +46,7 @@ public class BackupManager {
|
||||
|
||||
static final String MESSAGE_BACKUP_NAME = "messageBackup";
|
||||
public static final long MAX_TOTAL_BACKUP_MEDIA_BYTES = DataSize.gibibytes(100).toBytes();
|
||||
static final long MAX_MEDIA_OBJECT_SIZE = DataSize.mebibytes(101).toBytes();
|
||||
public static final long MAX_MEDIA_OBJECT_SIZE = DataSize.mebibytes(101).toBytes();
|
||||
|
||||
// If the last media usage recalculation is over MAX_QUOTA_STALENESS, force a recalculation before quota enforcement.
|
||||
static final Duration MAX_QUOTA_STALENESS = Duration.ofDays(1);
|
||||
|
||||
-69
@@ -1,69 +0,0 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.calls.routing;
|
||||
|
||||
import org.whispersystems.textsecuregcm.configuration.TurnUriConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicTurnConfiguration;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import org.whispersystems.textsecuregcm.util.WeightedRandomSelect;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Random;
|
||||
import java.util.UUID;
|
||||
|
||||
/** Uses DynamicConfig to help route a turn request */
|
||||
public class DynamicConfigTurnRouter {
|
||||
|
||||
private static final Random rng = new Random();
|
||||
|
||||
public static final long RANDOMIZE_RATE_BASIS = 100_000;
|
||||
|
||||
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
|
||||
|
||||
public DynamicConfigTurnRouter(final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
|
||||
this.dynamicConfigurationManager = dynamicConfigurationManager;
|
||||
}
|
||||
|
||||
public List<String> targetedUrls(final UUID aci) {
|
||||
final DynamicTurnConfiguration turnConfig = dynamicConfigurationManager.getConfiguration().getTurnConfiguration();
|
||||
|
||||
final Optional<TurnUriConfiguration> enrolled = turnConfig.getUriConfigs().stream()
|
||||
.filter(config -> config.getEnrolledAcis().contains(aci))
|
||||
.findFirst();
|
||||
|
||||
return enrolled
|
||||
.map(turnUriConfiguration -> turnUriConfiguration.getUris().stream().toList())
|
||||
.orElse(Collections.emptyList());
|
||||
}
|
||||
|
||||
public List<String> randomUrls() {
|
||||
final DynamicTurnConfiguration turnConfig = dynamicConfigurationManager.getConfiguration().getTurnConfiguration();
|
||||
|
||||
// select from turn server sets by weighted choice
|
||||
return WeightedRandomSelect.select(turnConfig
|
||||
.getUriConfigs()
|
||||
.stream()
|
||||
.map(c -> new Pair<>(c.getUris(), c.getWeight())).toList());
|
||||
}
|
||||
|
||||
public String getHostname() {
|
||||
final DynamicTurnConfiguration turnConfig = dynamicConfigurationManager.getConfiguration().getTurnConfiguration();
|
||||
return turnConfig.getHostname();
|
||||
}
|
||||
|
||||
public long getRandomizeRate() {
|
||||
final DynamicTurnConfiguration turnConfig = dynamicConfigurationManager.getConfiguration().getTurnConfiguration();
|
||||
return turnConfig.getRandomizeRate();
|
||||
}
|
||||
|
||||
public boolean shouldRandomize() {
|
||||
long rate = getRandomizeRate();
|
||||
return rate >= RANDOMIZE_RATE_BASIS || rng.nextLong(0, DynamicConfigTurnRouter.RANDOMIZE_RATE_BASIS) < rate;
|
||||
}
|
||||
}
|
||||
-187
@@ -1,187 +0,0 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.calls.routing;
|
||||
|
||||
import com.maxmind.geoip2.DatabaseReader;
|
||||
import com.maxmind.geoip2.exception.GeoIp2Exception;
|
||||
import com.maxmind.geoip2.model.CityResponse;
|
||||
import org.apache.commons.lang3.tuple.Triple;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
import javax.annotation.Nonnull;
|
||||
import java.io.IOException;
|
||||
import java.net.InetAddress;
|
||||
import java.util.*;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* Returns routes based on performance tables, manually routing tables, and target routing. Falls back to a random Turn
|
||||
* instance that the server knows about.
|
||||
*/
|
||||
public class TurnCallRouter {
|
||||
|
||||
private final Logger logger = LoggerFactory.getLogger(TurnCallRouter.class);
|
||||
|
||||
private final Supplier<CallDnsRecords> callDnsRecords;
|
||||
private final Supplier<CallRoutingTable> performanceRouting;
|
||||
private final Supplier<CallRoutingTable> manualRouting;
|
||||
private final DynamicConfigTurnRouter configTurnRouter;
|
||||
private final Supplier<DatabaseReader> geoIp;
|
||||
// controls whether instance IPs are shuffled. using if & boolean is ~5x faster than a function pointer
|
||||
private final boolean stableSelect;
|
||||
|
||||
public TurnCallRouter(
|
||||
@Nonnull Supplier<CallDnsRecords> callDnsRecords,
|
||||
@Nonnull Supplier<CallRoutingTable> performanceRouting,
|
||||
@Nonnull Supplier<CallRoutingTable> manualRouting,
|
||||
@Nonnull DynamicConfigTurnRouter configTurnRouter,
|
||||
@Nonnull Supplier<DatabaseReader> geoIp,
|
||||
boolean stableSelect
|
||||
) {
|
||||
this.performanceRouting = performanceRouting;
|
||||
this.callDnsRecords = callDnsRecords;
|
||||
this.manualRouting = manualRouting;
|
||||
this.configTurnRouter = configTurnRouter;
|
||||
this.geoIp = geoIp;
|
||||
this.stableSelect = stableSelect;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets Turn Instance addresses. Returns both the IPv4 and IPv6 addresses. Prefers to match the IP protocol of the
|
||||
* client address in datacenter selection. Returns 2 instance options of the preferred protocol for every one instance
|
||||
* of the other.
|
||||
* @param aci aci of client
|
||||
* @param clientAddress IP address to base routing on
|
||||
* @param instanceLimit max instances to return options for
|
||||
* @return Up to two * instanceLimit options, half in ipv4, half in ipv6
|
||||
*/
|
||||
public TurnServerOptions getRoutingFor(
|
||||
@Nonnull final UUID aci,
|
||||
@Nonnull final Optional<InetAddress> clientAddress,
|
||||
final int instanceLimit
|
||||
) {
|
||||
try {
|
||||
return getRoutingForInner(aci, clientAddress, instanceLimit);
|
||||
} catch(Exception e) {
|
||||
logger.error("Failed to perform routing", e);
|
||||
return new TurnServerOptions(this.configTurnRouter.getHostname(), null, this.configTurnRouter.randomUrls());
|
||||
}
|
||||
}
|
||||
|
||||
TurnServerOptions getRoutingForInner(
|
||||
@Nonnull final UUID aci,
|
||||
@Nonnull final Optional<InetAddress> clientAddress,
|
||||
final int instanceLimit
|
||||
) {
|
||||
if (instanceLimit < 1) {
|
||||
throw new IllegalArgumentException("Limit cannot be less than one");
|
||||
}
|
||||
|
||||
String hostname = this.configTurnRouter.getHostname();
|
||||
|
||||
List<String> targetedUrls = this.configTurnRouter.targetedUrls(aci);
|
||||
if(!targetedUrls.isEmpty()) {
|
||||
return new TurnServerOptions(hostname, null, targetedUrls);
|
||||
}
|
||||
|
||||
if(clientAddress.isEmpty() || this.configTurnRouter.shouldRandomize()) {
|
||||
return new TurnServerOptions(hostname, null, this.configTurnRouter.randomUrls());
|
||||
}
|
||||
|
||||
CityResponse geoInfo;
|
||||
try {
|
||||
geoInfo = geoIp.get().city(clientAddress.get());
|
||||
} catch (IOException | GeoIp2Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
Optional<String> subdivision = !geoInfo.getSubdivisions().isEmpty()
|
||||
? Optional.of(geoInfo.getSubdivisions().getFirst().getIsoCode())
|
||||
: Optional.empty();
|
||||
|
||||
List<String> datacenters = this.manualRouting.get().getDatacentersFor(
|
||||
clientAddress.get(),
|
||||
geoInfo.getContinent().getCode(),
|
||||
geoInfo.getCountry().getIsoCode(),
|
||||
subdivision
|
||||
);
|
||||
|
||||
if (datacenters.isEmpty()){
|
||||
datacenters = this.performanceRouting.get().getDatacentersFor(
|
||||
clientAddress.get(),
|
||||
geoInfo.getContinent().getCode(),
|
||||
geoInfo.getCountry().getIsoCode(),
|
||||
subdivision
|
||||
);
|
||||
}
|
||||
|
||||
List<String> urlsWithIps = getUrlsForInstances(
|
||||
selectInstances(
|
||||
datacenters,
|
||||
instanceLimit
|
||||
));
|
||||
return new TurnServerOptions(hostname, urlsWithIps, minimalRandomUrls());
|
||||
}
|
||||
|
||||
// Includes only the udp options in the randomUrls
|
||||
private List<String> minimalRandomUrls(){
|
||||
return this.configTurnRouter.randomUrls().stream()
|
||||
.filter(s -> s.startsWith("turn:") && !s.endsWith("transport=tcp"))
|
||||
.toList();
|
||||
}
|
||||
|
||||
// returns balanced number of instances across provided datacenters, prioritizing the datacenters earlier in the list
|
||||
private List<String> selectInstances(List<String> datacenters, int instanceLimit) {
|
||||
if(datacenters.isEmpty() || instanceLimit == 0) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
CallDnsRecords dnsRecords = this.callDnsRecords.get();
|
||||
List<List<InetAddress>> ipv4Options = datacenters.stream()
|
||||
.map(dc -> randomNOf(dnsRecords.aByRegion().get(dc), instanceLimit, stableSelect))
|
||||
.toList();
|
||||
List<List<InetAddress>> ipv6Options = datacenters.stream()
|
||||
.map(dc -> randomNOf(dnsRecords.aaaaByRegion().get(dc), instanceLimit, stableSelect))
|
||||
.toList();
|
||||
|
||||
List<InetAddress> ipv4Selection = selectFromOptions(ipv4Options, instanceLimit);
|
||||
List<InetAddress> ipv6Selection = selectFromOptions(ipv6Options, instanceLimit);
|
||||
|
||||
return Stream.concat(
|
||||
ipv4Selection.stream().map(InetAddress::getHostAddress),
|
||||
// map ipv6 to RFC3986 format i.e. surrounded by brackets
|
||||
ipv6Selection.stream().map(i -> String.format("[%s]", i.getHostAddress()))
|
||||
).toList();
|
||||
}
|
||||
|
||||
private static List<InetAddress> selectFromOptions(List<List<InetAddress>> recordsByDc, int instanceLimit) {
|
||||
return IntStream.range(0, recordsByDc.size())
|
||||
.mapToObj(dcIndex -> IntStream.range(0, recordsByDc.get(dcIndex).size())
|
||||
.mapToObj(addressIndex -> Triple.of(addressIndex, dcIndex, recordsByDc.get(dcIndex).get(addressIndex))))
|
||||
.flatMap(i -> i)
|
||||
.sorted(Comparator.comparingInt((Triple<Integer, Integer, InetAddress> t) -> t.getLeft())
|
||||
.thenComparingInt(Triple::getMiddle))
|
||||
.limit(instanceLimit)
|
||||
.sorted(Comparator.comparingInt(Triple::getMiddle))
|
||||
.map(Triple::getRight)
|
||||
.toList();
|
||||
}
|
||||
|
||||
private static <E> List<E> randomNOf(List<E> values, int n, boolean stableSelect) {
|
||||
return stableSelect ? Util.randomNOfStable(values, n) : Util.randomNOfShuffled(values, n);
|
||||
}
|
||||
|
||||
private static List<String> getUrlsForInstances(List<String> instanceIps) {
|
||||
return instanceIps.stream().flatMap(ip -> Stream.of(
|
||||
String.format("turn:%s", ip),
|
||||
String.format("turn:%s:80?transport=tcp", ip),
|
||||
String.format("turns:%s:443?transport=tcp", ip)
|
||||
)
|
||||
).toList();
|
||||
}
|
||||
}
|
||||
+6
-1
@@ -6,6 +6,11 @@
|
||||
package org.whispersystems.textsecuregcm.calls.routing;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
public record TurnServerOptions(String hostname, List<String> urlsWithIps, List<String> urlsWithHostname) {
|
||||
public record TurnServerOptions(
|
||||
String hostname,
|
||||
Optional<List<String>> urlsWithIps,
|
||||
Optional<List<String>> urlsWithHostname
|
||||
) {
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import java.time.Duration;
|
||||
|
||||
/**
|
||||
* Configuration for Apple DeviceCheck
|
||||
*
|
||||
* @param production Whether this is for production or sandbox attestations
|
||||
* @param teamId The teamId to validate attestations against
|
||||
* @param bundleId The bundleId to validation attestations against
|
||||
*/
|
||||
public record AppleDeviceCheckConfiguration(
|
||||
boolean production,
|
||||
String teamId,
|
||||
String bundleId) {}
|
||||
-21
@@ -1,21 +0,0 @@
|
||||
/*
|
||||
* Copyright 2022 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import static org.apache.commons.lang3.ObjectUtils.firstNonNull;
|
||||
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import java.time.Duration;
|
||||
import org.whispersystems.textsecuregcm.configuration.secrets.SecretBytes;
|
||||
import org.whispersystems.textsecuregcm.util.ExactlySize;
|
||||
|
||||
public record ArtServiceConfiguration(@ExactlySize(32) SecretBytes userAuthenticationTokenSharedSecret,
|
||||
@NotNull SecretBytes userAuthenticationTokenUserIdSecret,
|
||||
@NotNull Duration tokenExpiration) {
|
||||
public ArtServiceConfiguration {
|
||||
tokenExpiration = firstNonNull(tokenExpiration, Duration.ofDays(1));
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -116,7 +116,8 @@ public class CircuitBreakerConfiguration {
|
||||
.permittedNumberOfCallsInHalfOpenState(getPermittedNumberOfCallsInHalfOpenState())
|
||||
.waitDurationInOpenState(getWaitDurationInOpenState())
|
||||
.slidingWindow(getSlidingWindowSize(), getSlidingWindowMinimumNumberOfCalls(),
|
||||
CircuitBreakerConfig.SlidingWindowType.COUNT_BASED)
|
||||
CircuitBreakerConfig.SlidingWindowType.COUNT_BASED,
|
||||
CircuitBreakerConfig.SlidingWindowSynchronizationStrategy.SYNCHRONIZED)
|
||||
.build();
|
||||
}
|
||||
}
|
||||
+6
-3
@@ -7,18 +7,21 @@ package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import java.util.List;
|
||||
import jakarta.validation.constraints.Positive;
|
||||
import org.whispersystems.textsecuregcm.configuration.secrets.SecretString;
|
||||
|
||||
public record CloudflareTurnConfiguration(@NotNull SecretString apiToken,
|
||||
@NotBlank String endpoint,
|
||||
@NotBlank long ttl,
|
||||
@NotBlank List<String> urls,
|
||||
@NotBlank List<String> urlsWithIps,
|
||||
@NotNull @NotEmpty @Valid List<@NotBlank String> urls,
|
||||
@NotNull @NotEmpty @Valid List<@NotBlank String> urlsWithIps,
|
||||
@NotNull @Valid CircuitBreakerConfiguration circuitBreaker,
|
||||
@NotNull @Valid RetryConfiguration retry,
|
||||
@NotBlank String hostname) {
|
||||
@NotBlank String hostname,
|
||||
@Positive int numHttpClients) {
|
||||
|
||||
public CloudflareTurnConfiguration {
|
||||
if (circuitBreaker == null) {
|
||||
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import java.time.Duration;
|
||||
|
||||
/**
|
||||
* Configuration for Device Check operations
|
||||
*
|
||||
* @param backupRedemptionDuration How long to grant backup access for redemptions via device check
|
||||
* @param backupRedemptionLevel What backup level to grant redemptions via device check
|
||||
*/
|
||||
public record DeviceCheckConfiguration(Duration backupRedemptionDuration, long backupRedemptionLevel) {}
|
||||
+18
@@ -48,6 +48,8 @@ public class DynamoDbTables {
|
||||
|
||||
private final AccountsTableConfiguration accounts;
|
||||
|
||||
private final Table appleDeviceChecks;
|
||||
private final Table appleDeviceCheckPublicKeys;
|
||||
private final Table backups;
|
||||
private final Table clientPublicKeys;
|
||||
private final Table clientReleases;
|
||||
@@ -74,6 +76,8 @@ public class DynamoDbTables {
|
||||
|
||||
public DynamoDbTables(
|
||||
@JsonProperty("accounts") final AccountsTableConfiguration accounts,
|
||||
@JsonProperty("appleDeviceChecks") final Table appleDeviceChecks,
|
||||
@JsonProperty("appleDeviceCheckPublicKeys") final Table appleDeviceCheckPublicKeys,
|
||||
@JsonProperty("backups") final Table backups,
|
||||
@JsonProperty("clientPublicKeys") final Table clientPublicKeys,
|
||||
@JsonProperty("clientReleases") final Table clientReleases,
|
||||
@@ -99,6 +103,8 @@ public class DynamoDbTables {
|
||||
@JsonProperty("verificationSessions") final Table verificationSessions) {
|
||||
|
||||
this.accounts = accounts;
|
||||
this.appleDeviceChecks = appleDeviceChecks;
|
||||
this.appleDeviceCheckPublicKeys = appleDeviceCheckPublicKeys;
|
||||
this.backups = backups;
|
||||
this.clientPublicKeys = clientPublicKeys;
|
||||
this.clientReleases = clientReleases;
|
||||
@@ -130,6 +136,18 @@ public class DynamoDbTables {
|
||||
return accounts;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
public Table getAppleDeviceChecks() {
|
||||
return appleDeviceChecks;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
public Table getAppleDeviceCheckPublicKeys() {
|
||||
return appleDeviceCheckPublicKeys;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
public Table getBackups() {
|
||||
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import java.time.Duration;
|
||||
|
||||
public record IdlePrimaryDeviceReminderConfiguration(Duration minIdleDuration) {
|
||||
}
|
||||
+16
-1
@@ -7,22 +7,37 @@ package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
|
||||
import org.whispersystems.textsecuregcm.util.EnumMapUtil;
|
||||
import java.time.Duration;
|
||||
import java.util.EnumMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class IssuedReceiptsTableConfiguration extends DynamoDbTables.TableWithExpiration {
|
||||
|
||||
private final byte[] generator;
|
||||
|
||||
/**
|
||||
* The maximum number of issued receipts the issued receipt manager should issue for a particular itemId
|
||||
*/
|
||||
private final EnumMap<PaymentProvider, Integer> maxIssuedReceiptsPerPaymentId;
|
||||
|
||||
public IssuedReceiptsTableConfiguration(
|
||||
@JsonProperty("tableName") final String tableName,
|
||||
@JsonProperty("expiration") final Duration expiration,
|
||||
@JsonProperty("generator") final byte[] generator) {
|
||||
@JsonProperty("generator") final byte[] generator,
|
||||
@JsonProperty("maxIssuedReceiptsPerPaymentId") final Map<PaymentProvider, Integer> maxIssuedReceiptsPerPaymentId) {
|
||||
super(tableName, expiration);
|
||||
this.generator = generator;
|
||||
this.maxIssuedReceiptsPerPaymentId = EnumMapUtil.toCompleteEnumMap(PaymentProvider.class, maxIssuedReceiptsPerPaymentId);
|
||||
}
|
||||
|
||||
@NotEmpty
|
||||
public byte[] getGenerator() {
|
||||
return generator;
|
||||
}
|
||||
|
||||
public EnumMap<PaymentProvider, Integer> getmaxIssuedReceiptsPerPaymentId() {
|
||||
return maxIssuedReceiptsPerPaymentId;
|
||||
}
|
||||
}
|
||||
+5
-5
@@ -12,13 +12,13 @@ import jakarta.validation.constraints.NotNull;
|
||||
import java.net.http.HttpClient;
|
||||
import java.util.Map;
|
||||
import org.whispersystems.textsecuregcm.configuration.secrets.SecretString;
|
||||
import org.whispersystems.textsecuregcm.currency.CoinMarketCapClient;
|
||||
import org.whispersystems.textsecuregcm.currency.CoinGeckoClient;
|
||||
import org.whispersystems.textsecuregcm.currency.FixerClient;
|
||||
|
||||
@JsonTypeName("default")
|
||||
public record PaymentsServiceClientsConfiguration(@NotNull SecretString coinMarketCapApiKey,
|
||||
public record PaymentsServiceClientsConfiguration(@NotNull SecretString coinGeckoApiKey,
|
||||
@NotNull SecretString fixerApiKey,
|
||||
@NotEmpty Map<@NotBlank String, Integer> coinMarketCapCurrencyIds) implements
|
||||
@NotEmpty Map<@NotBlank String, String> coinGeckoCurrencyIds) implements
|
||||
PaymentsServiceClientsFactory {
|
||||
|
||||
@Override
|
||||
@@ -27,7 +27,7 @@ public record PaymentsServiceClientsConfiguration(@NotNull SecretString coinMark
|
||||
}
|
||||
|
||||
@Override
|
||||
public CoinMarketCapClient buildCoinMarketCapClient(final HttpClient httpClient) {
|
||||
return new CoinMarketCapClient(httpClient, coinMarketCapApiKey.value(), coinMarketCapCurrencyIds);
|
||||
public CoinGeckoClient buildCoinGeckoClient(final HttpClient httpClient) {
|
||||
return new CoinGeckoClient(httpClient, coinGeckoApiKey.value(), coinGeckoCurrencyIds);
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -7,7 +7,7 @@ package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonTypeInfo;
|
||||
import io.dropwizard.jackson.Discoverable;
|
||||
import org.whispersystems.textsecuregcm.currency.CoinMarketCapClient;
|
||||
import org.whispersystems.textsecuregcm.currency.CoinGeckoClient;
|
||||
import org.whispersystems.textsecuregcm.currency.FixerClient;
|
||||
import java.net.http.HttpClient;
|
||||
|
||||
@@ -16,5 +16,5 @@ public interface PaymentsServiceClientsFactory extends Discoverable {
|
||||
|
||||
FixerClient buildFixerClient(final HttpClient httpClient);
|
||||
|
||||
CoinMarketCapClient buildCoinMarketCapClient(HttpClient httpClient);
|
||||
CoinGeckoClient buildCoinGeckoClient(HttpClient httpClient);
|
||||
}
|
||||
+5
-2
@@ -3,9 +3,11 @@ package org.whispersystems.textsecuregcm.configuration;
|
||||
import com.fasterxml.jackson.annotation.JsonTypeName;
|
||||
import io.dropwizard.core.setup.Environment;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import java.io.IOException;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import org.whispersystems.textsecuregcm.configuration.secrets.SecretBytes;
|
||||
import org.whispersystems.textsecuregcm.registration.IdentityTokenCallCredentials;
|
||||
import org.whispersystems.textsecuregcm.registration.RegistrationServiceClient;
|
||||
|
||||
@@ -14,7 +16,8 @@ public record RegistrationServiceConfiguration(@NotBlank String host,
|
||||
int port,
|
||||
@NotBlank String credentialConfigurationJson,
|
||||
@NotBlank String identityTokenAudience,
|
||||
@NotBlank String registrationCaCertificate) implements
|
||||
@NotBlank String registrationCaCertificate,
|
||||
@NotNull SecretBytes collationKeySalt) implements
|
||||
RegistrationServiceClientFactory {
|
||||
|
||||
@Override
|
||||
@@ -26,7 +29,7 @@ public record RegistrationServiceConfiguration(@NotBlank String host,
|
||||
|
||||
environment.lifecycle().manage(callCredentials);
|
||||
|
||||
return new RegistrationServiceClient(host, port, callCredentials, registrationCaCertificate,
|
||||
return new RegistrationServiceClient(host, port, callCredentials, registrationCaCertificate, collationKeySalt.value(),
|
||||
identityRefreshExecutor);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
|
||||
-32
@@ -1,32 +0,0 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import java.util.List;
|
||||
import org.whispersystems.textsecuregcm.configuration.secrets.SecretBytes;
|
||||
import org.whispersystems.textsecuregcm.util.ExactlySize;
|
||||
|
||||
public record SecureValueRecovery3Configuration(
|
||||
@NotBlank String uri,
|
||||
@ExactlySize(32) SecretBytes userAuthenticationTokenSharedSecret,
|
||||
@ExactlySize(32) SecretBytes userIdTokenSharedSecret,
|
||||
@NotEmpty List<@NotBlank String> svrCaCertificates,
|
||||
@NotNull @Valid CircuitBreakerConfiguration circuitBreaker,
|
||||
@NotNull @Valid RetryConfiguration retry) {
|
||||
|
||||
public SecureValueRecovery3Configuration {
|
||||
if (circuitBreaker == null) {
|
||||
circuitBreaker = new CircuitBreakerConfiguration();
|
||||
}
|
||||
|
||||
if (retry == null) {
|
||||
retry = new RetryConfiguration();
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-3
@@ -5,7 +5,5 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import org.whispersystems.textsecuregcm.configuration.secrets.SecretBytes;
|
||||
|
||||
public record TurnConfiguration(SecretBytes secret, CloudflareTurnConfiguration cloudflare) {
|
||||
public record TurnConfiguration(CloudflareTurnConfiguration cloudflare) {
|
||||
}
|
||||
+14
-20
@@ -6,6 +6,7 @@
|
||||
package org.whispersystems.textsecuregcm.configuration.dynamic;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.vdurmont.semver4j.Semver;
|
||||
import jakarta.validation.Valid;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
@@ -13,6 +14,7 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiterConfig;
|
||||
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
|
||||
|
||||
public class DynamicConfiguration {
|
||||
|
||||
@@ -22,7 +24,7 @@ public class DynamicConfiguration {
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
private Map<String, DynamicPreRegistrationExperimentEnrollmentConfiguration> preRegistrationExperiments = Collections.emptyMap();
|
||||
private Map<String, DynamicE164ExperimentEnrollmentConfiguration> e164Experiments = Collections.emptyMap();
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
@@ -40,10 +42,6 @@ public class DynamicConfiguration {
|
||||
@Valid
|
||||
private DynamicCaptchaConfiguration captcha = new DynamicCaptchaConfiguration();
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
private DynamicTurnConfiguration turn = new DynamicTurnConfiguration();
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
DynamicMessagePersisterConfiguration messagePersister = new DynamicMessagePersisterConfiguration();
|
||||
@@ -52,10 +50,6 @@ public class DynamicConfiguration {
|
||||
@Valid
|
||||
DynamicRateLimitPolicy rateLimitPolicy = new DynamicRateLimitPolicy(false);
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
DynamicInboundMessageByteLimitConfiguration inboundMessageByteLimit = new DynamicInboundMessageByteLimitConfiguration(true);
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
DynamicRegistrationConfiguration registrationConfiguration = new DynamicRegistrationConfiguration(false);
|
||||
@@ -66,20 +60,24 @@ public class DynamicConfiguration {
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
DynamicMetricsConfiguration metricsConfiguration = new DynamicMetricsConfiguration(false);
|
||||
DynamicMetricsConfiguration metricsConfiguration = new DynamicMetricsConfiguration(false, false);
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
List<String> svrStatusCodesToIgnoreForAccountDeletion = Collections.emptyList();
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
Map<ClientPlatform, Semver> minimumRestFreeVersion = Map.of();
|
||||
|
||||
public Optional<DynamicExperimentEnrollmentConfiguration> getExperimentEnrollmentConfiguration(
|
||||
final String experimentName) {
|
||||
return Optional.ofNullable(experiments.get(experimentName));
|
||||
}
|
||||
|
||||
public Optional<DynamicPreRegistrationExperimentEnrollmentConfiguration> getPreRegistrationEnrollmentConfiguration(
|
||||
public Optional<DynamicE164ExperimentEnrollmentConfiguration> getE164ExperimentEnrollmentConfiguration(
|
||||
final String experimentName) {
|
||||
return Optional.ofNullable(preRegistrationExperiments.get(experimentName));
|
||||
return Optional.ofNullable(e164Experiments.get(experimentName));
|
||||
}
|
||||
|
||||
public Map<String, RateLimiterConfig> getLimits() {
|
||||
@@ -98,10 +96,6 @@ public class DynamicConfiguration {
|
||||
return captcha;
|
||||
}
|
||||
|
||||
public DynamicTurnConfiguration getTurnConfiguration() {
|
||||
return turn;
|
||||
}
|
||||
|
||||
public DynamicMessagePersisterConfiguration getMessagePersisterConfiguration() {
|
||||
return messagePersister;
|
||||
}
|
||||
@@ -110,10 +104,6 @@ public class DynamicConfiguration {
|
||||
return rateLimitPolicy;
|
||||
}
|
||||
|
||||
public DynamicInboundMessageByteLimitConfiguration getInboundMessageByteLimitConfiguration() {
|
||||
return inboundMessageByteLimit;
|
||||
}
|
||||
|
||||
public DynamicRegistrationConfiguration getRegistrationConfiguration() {
|
||||
return registrationConfiguration;
|
||||
}
|
||||
@@ -130,4 +120,8 @@ public class DynamicConfiguration {
|
||||
return svrStatusCodesToIgnoreForAccountDeletion;
|
||||
}
|
||||
|
||||
public Map<ClientPlatform, Semver> minimumRestFreeVersion() {
|
||||
return minimumRestFreeVersion;
|
||||
}
|
||||
|
||||
}
|
||||
+1
-1
@@ -12,7 +12,7 @@ import jakarta.validation.constraints.Min;
|
||||
import java.util.Collections;
|
||||
import java.util.Set;
|
||||
|
||||
public class DynamicPreRegistrationExperimentEnrollmentConfiguration {
|
||||
public class DynamicE164ExperimentEnrollmentConfiguration {
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
-9
@@ -1,9 +0,0 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration.dynamic;
|
||||
|
||||
public record DynamicInboundMessageByteLimitConfiguration(boolean enforceInboundLimit) {
|
||||
}
|
||||
+20
@@ -6,13 +6,33 @@
|
||||
package org.whispersystems.textsecuregcm.configuration.dynamic;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
|
||||
public class DynamicMessagePersisterConfiguration {
|
||||
|
||||
@JsonProperty
|
||||
private boolean persistenceEnabled = true;
|
||||
|
||||
/**
|
||||
* If we have to trim a client's persisted queue to make room to persist from Redis to DynamoDB, how much extra room should we make
|
||||
*/
|
||||
@JsonProperty
|
||||
private double trimOversizedQueueExtraRoomRatio = 1.5;
|
||||
|
||||
public DynamicMessagePersisterConfiguration() {}
|
||||
|
||||
@VisibleForTesting
|
||||
public DynamicMessagePersisterConfiguration(final boolean persistenceEnabled, final double trimOversizedQueueExtraRoomRatio) {
|
||||
this.persistenceEnabled = persistenceEnabled;
|
||||
this.trimOversizedQueueExtraRoomRatio = trimOversizedQueueExtraRoomRatio;
|
||||
}
|
||||
|
||||
public boolean isPersistenceEnabled() {
|
||||
return persistenceEnabled;
|
||||
}
|
||||
|
||||
public double getTrimOversizedQueueExtraRoomRatio() {
|
||||
return trimOversizedQueueExtraRoomRatio;
|
||||
}
|
||||
|
||||
}
|
||||
+4
-2
@@ -6,8 +6,10 @@
|
||||
package org.whispersystems.textsecuregcm.configuration.dynamic;
|
||||
|
||||
/**
|
||||
* @param enableLettuceRemoteTag - whether the `remote` tag should be added. Note: although this is dynamic, meters are
|
||||
* @param enableLettuceRemoteTag whether the `remote` tag should be added. Note: although this is dynamic, meters are
|
||||
* cached after creation, so changes will only affect servers launched after the change.
|
||||
* @param enableAwsSdkMetrics whether to record AWS SDK metrics. Note: although this is dynamic, meters are cached after
|
||||
* creation, so changes will only affect servers launched after the change.
|
||||
*/
|
||||
public record DynamicMetricsConfiguration(boolean enableLettuceRemoteTag) {
|
||||
public record DynamicMetricsConfiguration(boolean enableLettuceRemoteTag, boolean enableAwsSdkMetrics) {
|
||||
}
|
||||
-40
@@ -1,40 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2020 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration.dynamic;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import jakarta.validation.Valid;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import org.whispersystems.textsecuregcm.configuration.TurnUriConfiguration;
|
||||
|
||||
public class DynamicTurnConfiguration {
|
||||
|
||||
@JsonProperty
|
||||
private String hostname;
|
||||
|
||||
/**
|
||||
* Rate at which to prioritize a random turn URL to exercise all endpoints.
|
||||
* Based on a 100,000 basis, where 100,000 == 100%.
|
||||
*/
|
||||
@JsonProperty
|
||||
private long randomizeRate = 5_000;
|
||||
|
||||
@JsonProperty
|
||||
private List<@Valid TurnUriConfiguration> uriConfigs = Collections.emptyList();
|
||||
|
||||
public List<TurnUriConfiguration> getUriConfigs() {
|
||||
return uriConfigs;
|
||||
}
|
||||
|
||||
public long getRandomizeRate() {
|
||||
return randomizeRate;
|
||||
}
|
||||
|
||||
public String getHostname() {
|
||||
return hostname;
|
||||
}
|
||||
}
|
||||
+7
-37
@@ -34,12 +34,10 @@ import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import javax.annotation.Nullable;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.signal.libsignal.usernames.BaseUsernameException;
|
||||
import org.whispersystems.textsecuregcm.auth.AccountAndAuthenticatedDeviceHolder;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
|
||||
import org.whispersystems.textsecuregcm.auth.TurnToken;
|
||||
import org.whispersystems.textsecuregcm.auth.TurnTokenGenerator;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountIdentifierResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountIdentityResponse;
|
||||
@@ -54,13 +52,13 @@ import org.whispersystems.textsecuregcm.entities.ReserveUsernameHashResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.UsernameHashResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.UsernameLinkHandle;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimitedByIp;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
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.RegistrationRecoveryPasswordsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.UsernameHashNotAvailableException;
|
||||
import org.whispersystems.textsecuregcm.storage.UsernameReservationNotFoundException;
|
||||
@@ -81,33 +79,20 @@ public class AccountController {
|
||||
|
||||
private final AccountsManager accounts;
|
||||
private final RateLimiters rateLimiters;
|
||||
private final TurnTokenGenerator turnTokenGenerator;
|
||||
private final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager;
|
||||
private final UsernameHashZkProofVerifier usernameHashZkProofVerifier;
|
||||
|
||||
public AccountController(
|
||||
AccountsManager accounts,
|
||||
RateLimiters rateLimiters,
|
||||
TurnTokenGenerator turnTokenGenerator,
|
||||
RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager,
|
||||
UsernameHashZkProofVerifier usernameHashZkProofVerifier) {
|
||||
this.accounts = accounts;
|
||||
this.rateLimiters = rateLimiters;
|
||||
this.turnTokenGenerator = turnTokenGenerator;
|
||||
this.registrationRecoveryPasswordsManager = registrationRecoveryPasswordsManager;
|
||||
this.usernameHashZkProofVerifier = usernameHashZkProofVerifier;
|
||||
}
|
||||
|
||||
// may be removed after 2024-07-16
|
||||
@Deprecated(forRemoval = true)
|
||||
@GET
|
||||
@Path("/turn/")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public TurnToken getTurnToken(@ReadOnly @Auth AuthenticatedDevice auth) throws RateLimitExceededException {
|
||||
rateLimiters.getTurnLimiter().validate(auth.getAccount().getUuid());
|
||||
return turnTokenGenerator.generate(auth.getAccount().getUuid());
|
||||
}
|
||||
|
||||
@PUT
|
||||
@Path("/gcm/")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@@ -248,7 +233,9 @@ public class AccountController {
|
||||
d.setName(attributes.getName());
|
||||
d.setLastSeen(Util.todayInMillis());
|
||||
d.setCapabilities(attributes.getCapabilities());
|
||||
d.setUserAgent(userAgent);
|
||||
if (StringUtils.isNotBlank(userAgent)) {
|
||||
d.setUserAgent(userAgent);
|
||||
}
|
||||
});
|
||||
|
||||
a.setRegistrationLockFromAttributes(attributes);
|
||||
@@ -259,31 +246,14 @@ public class AccountController {
|
||||
|
||||
// if registration recovery password was sent to us, store it (or refresh its expiration)
|
||||
attributes.recoveryPassword().ifPresent(registrationRecoveryPassword ->
|
||||
registrationRecoveryPasswordsManager.storeForCurrentNumber(updatedAccount.getNumber(), registrationRecoveryPassword));
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/me")
|
||||
@Deprecated() // use whoami
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public AccountIdentityResponse getMe(@ReadOnly @Auth AuthenticatedDevice auth) {
|
||||
return buildAccountIdentityResponse(auth);
|
||||
registrationRecoveryPasswordsManager.store(updatedAccount.getIdentifier(IdentityType.PNI), registrationRecoveryPassword));
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/whoami")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public AccountIdentityResponse whoAmI(@ReadOnly @Auth AuthenticatedDevice auth) {
|
||||
return buildAccountIdentityResponse(auth);
|
||||
}
|
||||
|
||||
private AccountIdentityResponse buildAccountIdentityResponse(AccountAndAuthenticatedDeviceHolder auth) {
|
||||
return new AccountIdentityResponse(auth.getAccount().getUuid(),
|
||||
auth.getAccount().getNumber(),
|
||||
auth.getAccount().getPhoneNumberIdentifier(),
|
||||
auth.getAccount().getUsernameHash().filter(h -> h.length > 0).orElse(null),
|
||||
auth.getAccount().getUsernameLinkHandle(),
|
||||
auth.getAccount().hasCapability(DeviceCapability.STORAGE));
|
||||
return AccountIdentityResponseBuilder.fromAccount(auth.getAccount());
|
||||
}
|
||||
|
||||
@DELETE
|
||||
|
||||
+45
-43
@@ -43,18 +43,18 @@ import org.whispersystems.textsecuregcm.auth.RegistrationLockVerificationManager
|
||||
import org.whispersystems.textsecuregcm.entities.AccountDataReportResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountIdentityResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.ChangeNumberRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.MismatchedDevices;
|
||||
import org.whispersystems.textsecuregcm.entities.MismatchedDevicesResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.PhoneNumberDiscoverabilityRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.PhoneNumberIdentityKeyDistributionRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.PhoneVerificationRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.RegistrationLockFailure;
|
||||
import org.whispersystems.textsecuregcm.entities.StaleDevices;
|
||||
import org.whispersystems.textsecuregcm.entities.StaleDevicesResponse;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.push.MessageTooLargeException;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ChangeNumberManager;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
|
||||
import org.whispersystems.websocket.auth.Mutable;
|
||||
import org.whispersystems.websocket.auth.ReadOnly;
|
||||
|
||||
@@ -93,8 +93,9 @@ public class AccountControllerV2 {
|
||||
@ApiResponse(responseCode = "200", description = "The phone number associated with the authenticated account was changed successfully", useReturnTypeSchema = true)
|
||||
@ApiResponse(responseCode = "401", description = "Account authentication check failed.")
|
||||
@ApiResponse(responseCode = "403", description = "Verification failed for the provided Registration Recovery Password")
|
||||
@ApiResponse(responseCode = "409", description = "Mismatched number of devices or device ids in 'devices to notify' list", content = @Content(schema = @Schema(implementation = MismatchedDevices.class)))
|
||||
@ApiResponse(responseCode = "410", description = "Mismatched registration ids in 'devices to notify' list", content = @Content(schema = @Schema(implementation = StaleDevices.class)))
|
||||
@ApiResponse(responseCode = "409", description = "Mismatched number of devices or device ids in 'devices to notify' list", content = @Content(schema = @Schema(implementation = MismatchedDevicesResponse.class)))
|
||||
@ApiResponse(responseCode = "410", description = "Mismatched registration ids in 'devices to notify' list", content = @Content(schema = @Schema(implementation = StaleDevicesResponse.class)))
|
||||
@ApiResponse(responseCode = "413", description = "One or more device messages was too large")
|
||||
@ApiResponse(responseCode = "422", description = "The request did not pass validation")
|
||||
@ApiResponse(responseCode = "423", content = @Content(schema = @Schema(implementation = RegistrationLockFailure.class)))
|
||||
@ApiResponse(responseCode = "429", description = "Too many attempts", headers = @Header(
|
||||
@@ -144,28 +145,27 @@ public class AccountControllerV2 {
|
||||
request.devicePniSignedPrekeys(),
|
||||
request.devicePniPqLastResortPrekeys(),
|
||||
request.deviceMessages(),
|
||||
request.pniRegistrationIds());
|
||||
request.pniRegistrationIds(),
|
||||
userAgentString);
|
||||
|
||||
return new AccountIdentityResponse(
|
||||
updatedAccount.getUuid(),
|
||||
updatedAccount.getNumber(),
|
||||
updatedAccount.getPhoneNumberIdentifier(),
|
||||
updatedAccount.getUsernameHash().orElse(null),
|
||||
updatedAccount.getUsernameLinkHandle(),
|
||||
updatedAccount.hasCapability(DeviceCapability.STORAGE));
|
||||
return AccountIdentityResponseBuilder.fromAccount(updatedAccount);
|
||||
} catch (MismatchedDevicesException e) {
|
||||
throw new WebApplicationException(Response.status(409)
|
||||
.type(MediaType.APPLICATION_JSON_TYPE)
|
||||
.entity(new MismatchedDevices(e.getMissingDevices(),
|
||||
e.getExtraDevices()))
|
||||
.build());
|
||||
} catch (StaleDevicesException e) {
|
||||
throw new WebApplicationException(Response.status(410)
|
||||
.type(MediaType.APPLICATION_JSON)
|
||||
.entity(new StaleDevices(e.getStaleDevices()))
|
||||
.build());
|
||||
if (!e.getMismatchedDevices().staleDeviceIds().isEmpty()) {
|
||||
throw new WebApplicationException(Response.status(410)
|
||||
.type(MediaType.APPLICATION_JSON)
|
||||
.entity(new StaleDevicesResponse(e.getMismatchedDevices().staleDeviceIds()))
|
||||
.build());
|
||||
} else {
|
||||
throw new WebApplicationException(Response.status(409)
|
||||
.type(MediaType.APPLICATION_JSON_TYPE)
|
||||
.entity(new MismatchedDevicesResponse(e.getMismatchedDevices().missingDeviceIds(),
|
||||
e.getMismatchedDevices().extraDeviceIds()))
|
||||
.build());
|
||||
}
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw new BadRequestException(e);
|
||||
} catch (MessageTooLargeException e) {
|
||||
throw new WebApplicationException(Response.Status.REQUEST_ENTITY_TOO_LARGE);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -180,9 +180,10 @@ public class AccountControllerV2 {
|
||||
@ApiResponse(responseCode = "403", description = "This endpoint can only be invoked from the account's primary device.")
|
||||
@ApiResponse(responseCode = "422", description = "The request body failed validation.")
|
||||
@ApiResponse(responseCode = "409", description = "The set of devices specified in the request does not match the set of devices active on the account.",
|
||||
content = @Content(schema = @Schema(implementation = MismatchedDevices.class)))
|
||||
content = @Content(schema = @Schema(implementation = MismatchedDevicesResponse.class)))
|
||||
@ApiResponse(responseCode = "410", description = "The registration IDs provided for some devices do not match those stored on the server.",
|
||||
content = @Content(schema = @Schema(implementation = StaleDevices.class)))
|
||||
content = @Content(schema = @Schema(implementation = StaleDevicesResponse.class)))
|
||||
@ApiResponse(responseCode = "413", description = "One or more device messages was too large")
|
||||
public AccountIdentityResponse distributePhoneNumberIdentityKeys(
|
||||
@Mutable @Auth final AuthenticatedDevice authenticatedDevice,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) @Nullable final String userAgentString,
|
||||
@@ -203,28 +204,27 @@ public class AccountControllerV2 {
|
||||
request.devicePniSignedPrekeys(),
|
||||
request.devicePniPqLastResortPrekeys(),
|
||||
request.deviceMessages(),
|
||||
request.pniRegistrationIds());
|
||||
request.pniRegistrationIds(),
|
||||
userAgentString);
|
||||
|
||||
return new AccountIdentityResponse(
|
||||
updatedAccount.getUuid(),
|
||||
updatedAccount.getNumber(),
|
||||
updatedAccount.getPhoneNumberIdentifier(),
|
||||
updatedAccount.getUsernameHash().orElse(null),
|
||||
updatedAccount.getUsernameLinkHandle(),
|
||||
updatedAccount.hasCapability(DeviceCapability.STORAGE));
|
||||
return AccountIdentityResponseBuilder.fromAccount(updatedAccount);
|
||||
} catch (MismatchedDevicesException e) {
|
||||
throw new WebApplicationException(Response.status(409)
|
||||
.type(MediaType.APPLICATION_JSON_TYPE)
|
||||
.entity(new MismatchedDevices(e.getMissingDevices(),
|
||||
e.getExtraDevices()))
|
||||
.build());
|
||||
} catch (StaleDevicesException e) {
|
||||
throw new WebApplicationException(Response.status(410)
|
||||
.type(MediaType.APPLICATION_JSON)
|
||||
.entity(new StaleDevices(e.getStaleDevices()))
|
||||
.build());
|
||||
if (!e.getMismatchedDevices().staleDeviceIds().isEmpty()) {
|
||||
throw new WebApplicationException(Response.status(410)
|
||||
.type(MediaType.APPLICATION_JSON)
|
||||
.entity(new StaleDevicesResponse(e.getMismatchedDevices().staleDeviceIds()))
|
||||
.build());
|
||||
} else {
|
||||
throw new WebApplicationException(Response.status(409)
|
||||
.type(MediaType.APPLICATION_JSON_TYPE)
|
||||
.entity(new MismatchedDevicesResponse(e.getMismatchedDevices().missingDeviceIds(),
|
||||
e.getMismatchedDevices().extraDeviceIds()))
|
||||
.build());
|
||||
}
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw new BadRequestException(e);
|
||||
} catch (MessageTooLargeException e) {
|
||||
throw new WebApplicationException(Response.Status.REQUEST_ENTITY_TOO_LARGE);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -232,6 +232,8 @@ public class AccountControllerV2 {
|
||||
@Path("/phone_number_discoverability")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Operation(summary = "Sets whether the account should be discoverable by phone number in the directory.")
|
||||
@ApiResponse(responseCode = "204", description = "The setting was successfully updated.")
|
||||
public void setPhoneNumberDiscoverability(
|
||||
@Mutable @Auth AuthenticatedDevice auth,
|
||||
@NotNull @Valid PhoneNumberDiscoverabilityRequest phoneNumberDiscoverability
|
||||
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountIdentityResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.Entitlements;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
|
||||
|
||||
public class AccountIdentityResponseBuilder {
|
||||
|
||||
private final Account account;
|
||||
private boolean storageCapable;
|
||||
private Clock clock;
|
||||
|
||||
public AccountIdentityResponseBuilder(Account account) {
|
||||
this.account = account;
|
||||
this.storageCapable = account.hasCapability(DeviceCapability.STORAGE);
|
||||
this.clock = Clock.systemUTC();
|
||||
}
|
||||
|
||||
public AccountIdentityResponseBuilder storageCapable(boolean storageCapable) {
|
||||
this.storageCapable = storageCapable;
|
||||
return this;
|
||||
}
|
||||
|
||||
public AccountIdentityResponseBuilder clock(Clock clock) {
|
||||
this.clock = clock;
|
||||
return this;
|
||||
}
|
||||
|
||||
public AccountIdentityResponse build() {
|
||||
final List<Entitlements.BadgeEntitlement> badges = account.getBadges()
|
||||
.stream()
|
||||
.filter(bv -> bv.expiration().isAfter(clock.instant()))
|
||||
.map(badge -> new Entitlements.BadgeEntitlement(badge.id(), badge.expiration(), badge.visible()))
|
||||
.toList();
|
||||
|
||||
final Entitlements.BackupEntitlement backupEntitlement = Optional
|
||||
.ofNullable(account.getBackupVoucher())
|
||||
.filter(bv -> bv.expiration().isAfter(clock.instant()))
|
||||
.map(bv -> new Entitlements.BackupEntitlement(bv.receiptLevel(), bv.expiration()))
|
||||
.orElse(null);
|
||||
|
||||
return new AccountIdentityResponse(account.getUuid(),
|
||||
account.getNumber(),
|
||||
account.getPhoneNumberIdentifier(),
|
||||
account.getUsernameHash().filter(h -> h.length > 0).orElse(null),
|
||||
account.getUsernameLinkHandle(),
|
||||
storageCapable,
|
||||
new Entitlements(badges, backupEntitlement));
|
||||
}
|
||||
|
||||
public static AccountIdentityResponse fromAccount(final Account account) {
|
||||
return new AccountIdentityResponseBuilder(account).build();
|
||||
}
|
||||
}
|
||||
+34
-9
@@ -5,6 +5,8 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonCreator;
|
||||
import com.fasterxml.jackson.annotation.JsonValue;
|
||||
import com.fasterxml.jackson.core.JsonParser;
|
||||
@@ -13,13 +15,16 @@ import com.fasterxml.jackson.databind.JsonDeserializer;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.common.net.HttpHeaders;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.media.Content;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.Max;
|
||||
import jakarta.validation.constraints.Min;
|
||||
@@ -69,6 +74,8 @@ import org.whispersystems.textsecuregcm.backup.CopyParameters;
|
||||
import org.whispersystems.textsecuregcm.backup.CopyResult;
|
||||
import org.whispersystems.textsecuregcm.backup.MediaEncryptionParameters;
|
||||
import org.whispersystems.textsecuregcm.entities.RemoteAttachment;
|
||||
import org.whispersystems.textsecuregcm.metrics.BackupMetrics;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.util.BackupAuthCredentialAdapter;
|
||||
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
|
||||
import org.whispersystems.textsecuregcm.util.ByteArrayBase64UrlAdapter;
|
||||
@@ -80,7 +87,7 @@ import org.whispersystems.websocket.auth.ReadOnly;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
@Path("/v1/archives")
|
||||
@Tag(name = "Archive")
|
||||
@io.swagger.v3.oas.annotations.tags.Tag(name = "Archive")
|
||||
public class ArchiveController {
|
||||
|
||||
public final static String X_SIGNAL_ZK_AUTH = "X-Signal-ZK-Auth";
|
||||
@@ -88,12 +95,15 @@ public class ArchiveController {
|
||||
|
||||
private final BackupAuthManager backupAuthManager;
|
||||
private final BackupManager backupManager;
|
||||
private final BackupMetrics backupMetrics;
|
||||
|
||||
public ArchiveController(
|
||||
final BackupAuthManager backupAuthManager,
|
||||
final BackupManager backupManager) {
|
||||
final BackupManager backupManager,
|
||||
final BackupMetrics backupMetrics) {
|
||||
this.backupAuthManager = backupAuthManager;
|
||||
this.backupManager = backupManager;
|
||||
this.backupMetrics = backupMetrics;
|
||||
}
|
||||
|
||||
public record SetBackupIdRequest(
|
||||
@@ -173,9 +183,13 @@ public class ArchiveController {
|
||||
|
||||
After successful redemption, subsequent requests to /v1/archive/auth will return credentials with the level on
|
||||
the provided receipt until the expiration time on the receipt.
|
||||
|
||||
Accounts must have an existing backup credential request in order to redeem a receipt. This request will fail
|
||||
if the account has not already set a backup credential request via PUT `/v1/archives/backupid`.
|
||||
""")
|
||||
@ApiResponse(responseCode = "204", description = "The receipt was redeemed")
|
||||
@ApiResponse(responseCode = "400", description = "The provided presentation or receipt was invalid")
|
||||
@ApiResponse(responseCode = "409", description = "The target account does not have a backup-id commitment")
|
||||
@ApiResponse(responseCode = "429", description = "Rate limited.")
|
||||
public CompletionStage<Response> redeemReceipt(
|
||||
@Mutable @Auth final AuthenticatedDevice account,
|
||||
@@ -243,6 +257,7 @@ public class ArchiveController {
|
||||
@ApiResponse(responseCode = "429", description = "Rate limited.")
|
||||
public CompletionStage<BackupAuthCredentialsResponse> getBackupZKCredentials(
|
||||
@Mutable @Auth AuthenticatedDevice auth,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
|
||||
@NotNull @QueryParam("redemptionStartSeconds") Long startSeconds,
|
||||
@NotNull @QueryParam("redemptionEndSeconds") Long endSeconds) {
|
||||
|
||||
@@ -254,11 +269,17 @@ public class ArchiveController {
|
||||
auth.getAccount(),
|
||||
credentialType,
|
||||
Instant.ofEpochSecond(startSeconds), Instant.ofEpochSecond(endSeconds))
|
||||
.thenAccept(credentials -> credentialsByType.put(credentialType, credentials.stream()
|
||||
.map(credential -> new BackupAuthCredentialsResponse.BackupAuthCredential(
|
||||
credential.credential().serialize(),
|
||||
credential.redemptionTime().getEpochSecond()))
|
||||
.toList())))
|
||||
.thenAccept(credentials -> {
|
||||
backupMetrics.updateGetCredentialCounter(
|
||||
UserAgentTagUtil.getPlatformTag(userAgent),
|
||||
credentialType,
|
||||
credentials.size());
|
||||
credentialsByType.put(credentialType, credentials.stream()
|
||||
.map(credential -> new BackupAuthCredentialsResponse.BackupAuthCredential(
|
||||
credential.credential().serialize(),
|
||||
credential.redemptionTime().getEpochSecond()))
|
||||
.toList());
|
||||
}))
|
||||
.toArray(CompletableFuture[]::new))
|
||||
.thenApply(ignored -> new BackupAuthCredentialsResponse(credentialsByType.entrySet().stream()
|
||||
.collect(Collectors.toMap(
|
||||
@@ -582,6 +603,7 @@ public class ArchiveController {
|
||||
@ApiResponseZkAuth
|
||||
public CompletionStage<CopyMediaResponse> copyMedia(
|
||||
@ReadOnly @Auth final Optional<AuthenticatedDevice> account,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
|
||||
|
||||
@Parameter(description = BackupAuthCredentialPresentationHeader.DESCRIPTION, schema = @Schema(implementation = String.class))
|
||||
@NotNull
|
||||
@@ -601,6 +623,7 @@ public class ArchiveController {
|
||||
.fromFuture(backupManager.authenticateBackupUser(presentation.presentation, signature.signature))
|
||||
.flatMap(backupUser -> backupManager.copyToBackup(backupUser, List.of(copyMediaRequest.toCopyParameters()))
|
||||
.next()
|
||||
.doOnNext(result -> backupMetrics.updateCopyCounter(result, UserAgentTagUtil.getPlatformTag(userAgent)))
|
||||
.map(copyResult -> switch (copyResult.outcome()) {
|
||||
case SUCCESS -> new CopyMediaResponse(copyResult.cdn());
|
||||
case SOURCE_WRONG_LENGTH -> throw new BadRequestException("Invalid length");
|
||||
@@ -679,6 +702,7 @@ public class ArchiveController {
|
||||
@ApiResponseZkAuth
|
||||
public CompletionStage<Response> copyMedia(
|
||||
@ReadOnly @Auth final Optional<AuthenticatedDevice> account,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
|
||||
|
||||
@Parameter(description = BackupAuthCredentialPresentationHeader.DESCRIPTION, schema = @Schema(implementation = String.class))
|
||||
@NotNull
|
||||
@@ -697,6 +721,7 @@ public class ArchiveController {
|
||||
final Stream<CopyParameters> copyParams = copyMediaRequest.items().stream().map(CopyMediaRequest::toCopyParameters);
|
||||
return Mono.fromFuture(backupManager.authenticateBackupUser(presentation.presentation, signature.signature))
|
||||
.flatMapMany(backupUser -> backupManager.copyToBackup(backupUser, copyParams.toList()))
|
||||
.doOnNext(result -> backupMetrics.updateCopyCounter(result, UserAgentTagUtil.getPlatformTag(userAgent)))
|
||||
.map(CopyMediaBatchResponse.Entry::fromCopyResult)
|
||||
.collectList()
|
||||
.map(list -> Response.status(207).entity(new CopyMediaBatchResponse(list)).build())
|
||||
@@ -832,7 +857,7 @@ public class ArchiveController {
|
||||
@Path("/media/delete")
|
||||
@Operation(summary = "Delete media objects",
|
||||
description = "Delete media objects stored with this backup-id")
|
||||
@ApiResponse(responseCode = "204")
|
||||
@ApiResponse(responseCode = "204", description = "The provided objects were successfully deleted or they do not exist")
|
||||
@ApiResponse(responseCode = "429", description = "Rate limited.")
|
||||
@ApiResponseZkAuth
|
||||
public CompletionStage<Response> deleteMedia(
|
||||
|
||||
@@ -1,52 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.ws.rs.GET;
|
||||
import jakarta.ws.rs.Path;
|
||||
import jakarta.ws.rs.Produces;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import java.util.UUID;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
|
||||
import org.whispersystems.textsecuregcm.configuration.ArtServiceConfiguration;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.websocket.auth.ReadOnly;
|
||||
|
||||
@Path("/v1/art")
|
||||
@Tag(name = "Art")
|
||||
public class ArtController {
|
||||
private final ExternalServiceCredentialsGenerator artServiceCredentialsGenerator;
|
||||
private final RateLimiters rateLimiters;
|
||||
|
||||
public static ExternalServiceCredentialsGenerator credentialsGenerator(final ArtServiceConfiguration cfg) {
|
||||
return ExternalServiceCredentialsGenerator
|
||||
.builder(cfg.userAuthenticationTokenSharedSecret())
|
||||
.withUserDerivationKey(cfg.userAuthenticationTokenUserIdSecret())
|
||||
.prependUsername(false)
|
||||
.truncateSignature(false)
|
||||
.build();
|
||||
}
|
||||
|
||||
public ArtController(final RateLimiters rateLimiters,
|
||||
final ExternalServiceCredentialsGenerator artServiceCredentialsGenerator) {
|
||||
this.artServiceCredentialsGenerator = artServiceCredentialsGenerator;
|
||||
this.rateLimiters = rateLimiters;
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/auth")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public ExternalServiceCredentials getAuth(final @ReadOnly @Auth AuthenticatedDevice auth)
|
||||
throws RateLimitExceededException {
|
||||
final UUID uuid = auth.getAccount().getUuid();
|
||||
rateLimiters.forDescriptor(RateLimiters.For.EXTERNAL_SERVICE_CREDENTIALS).validate(uuid);
|
||||
return artServiceCredentialsGenerator.generateForUuid(uuid);
|
||||
}
|
||||
}
|
||||
-103
@@ -1,103 +0,0 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import jakarta.ws.rs.GET;
|
||||
import jakarta.ws.rs.Path;
|
||||
import jakarta.ws.rs.Produces;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.ws.rs.core.Context;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import java.io.IOException;
|
||||
import java.net.InetAddress;
|
||||
import java.net.UnknownHostException;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.CloudflareTurnCredentialsManager;
|
||||
import org.whispersystems.textsecuregcm.auth.TurnToken;
|
||||
import org.whispersystems.textsecuregcm.auth.TurnTokenGenerator;
|
||||
import org.whispersystems.textsecuregcm.calls.routing.TurnCallRouter;
|
||||
import org.whispersystems.textsecuregcm.calls.routing.TurnServerOptions;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.filters.RemoteAddressFilter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.websocket.auth.ReadOnly;
|
||||
|
||||
@Path("/v1/calling")
|
||||
@io.swagger.v3.oas.annotations.tags.Tag(name = "Calling")
|
||||
public class CallRoutingController {
|
||||
|
||||
private static final int TURN_INSTANCE_LIMIT = 2;
|
||||
private static final Counter INVALID_IP_COUNTER = Metrics.counter(name(CallRoutingController.class, "invalidIP"));
|
||||
private static final Logger log = LoggerFactory.getLogger(CallRoutingController.class);
|
||||
private final RateLimiters rateLimiters;
|
||||
private final TurnCallRouter turnCallRouter;
|
||||
private final TurnTokenGenerator tokenGenerator;
|
||||
private final ExperimentEnrollmentManager experimentEnrollmentManager;
|
||||
private final CloudflareTurnCredentialsManager cloudflareTurnCredentialsManager;
|
||||
|
||||
public CallRoutingController(
|
||||
final RateLimiters rateLimiters,
|
||||
final TurnCallRouter turnCallRouter,
|
||||
final TurnTokenGenerator tokenGenerator,
|
||||
final ExperimentEnrollmentManager experimentEnrollmentManager,
|
||||
final CloudflareTurnCredentialsManager cloudflareTurnCredentialsManager
|
||||
) {
|
||||
this.rateLimiters = rateLimiters;
|
||||
this.turnCallRouter = turnCallRouter;
|
||||
this.tokenGenerator = tokenGenerator;
|
||||
this.experimentEnrollmentManager = experimentEnrollmentManager;
|
||||
this.cloudflareTurnCredentialsManager = cloudflareTurnCredentialsManager;
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/relays")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Operation(
|
||||
summary = "Get 1:1 calling relay options for the client",
|
||||
description = """
|
||||
Get 1:1 relay addresses in IpV4, Ipv6, and URL formats.
|
||||
"""
|
||||
)
|
||||
@ApiResponse(responseCode = "200", description = "`JSON` with call endpoints.", useReturnTypeSchema = true)
|
||||
@ApiResponse(responseCode = "400", description = "Invalid get call endpoint request.")
|
||||
@ApiResponse(responseCode = "401", description = "Account authentication check failed.")
|
||||
@ApiResponse(responseCode = "422", description = "Invalid request format.")
|
||||
@ApiResponse(responseCode = "429", description = "Rate limited.")
|
||||
public TurnToken getCallingRelays(
|
||||
final @ReadOnly @Auth AuthenticatedDevice auth,
|
||||
@Context ContainerRequestContext requestContext
|
||||
) throws RateLimitExceededException, IOException {
|
||||
UUID aci = auth.getAccount().getUuid();
|
||||
rateLimiters.getCallEndpointLimiter().validate(aci);
|
||||
|
||||
if (experimentEnrollmentManager.isEnrolled(auth.getAccount().getNumber(), aci, "cloudflareTurn")) {
|
||||
return cloudflareTurnCredentialsManager.retrieveFromCloudflare();
|
||||
}
|
||||
|
||||
Optional<InetAddress> address = Optional.empty();
|
||||
try {
|
||||
final String remoteAddress = (String) requestContext.getProperty(
|
||||
RemoteAddressFilter.REMOTE_ADDRESS_ATTRIBUTE_NAME);
|
||||
address = Optional.of(InetAddress.getByName(remoteAddress));
|
||||
} catch (UnknownHostException e) {
|
||||
INVALID_IP_COUNTER.increment();
|
||||
}
|
||||
|
||||
TurnServerOptions options = turnCallRouter.getRoutingFor(aci, address, TURN_INSTANCE_LIMIT);
|
||||
return tokenGenerator.generateWithTurnServerOptions(options);
|
||||
}
|
||||
}
|
||||
+6
-34
@@ -19,20 +19,12 @@ import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.ws.rs.core.Context;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import java.io.IOException;
|
||||
import java.net.InetAddress;
|
||||
import java.net.UnknownHostException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.CloudflareTurnCredentialsManager;
|
||||
import org.whispersystems.textsecuregcm.auth.TurnToken;
|
||||
import org.whispersystems.textsecuregcm.auth.TurnTokenGenerator;
|
||||
import org.whispersystems.textsecuregcm.calls.routing.TurnCallRouter;
|
||||
import org.whispersystems.textsecuregcm.calls.routing.TurnServerOptions;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.filters.RemoteAddressFilter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.websocket.auth.ReadOnly;
|
||||
|
||||
@@ -40,25 +32,15 @@ import org.whispersystems.websocket.auth.ReadOnly;
|
||||
@Path("/v2/calling")
|
||||
public class CallRoutingControllerV2 {
|
||||
|
||||
private static final int TURN_INSTANCE_LIMIT = 2;
|
||||
private static final Counter INVALID_IP_COUNTER = Metrics.counter(name(CallRoutingControllerV2.class, "invalidIP"));
|
||||
private static final Counter CLOUDFLARE_TURN_ERROR_COUNTER = Metrics.counter(name(CallRoutingControllerV2.class, "cloudflareTurnError"));
|
||||
private final RateLimiters rateLimiters;
|
||||
private final TurnCallRouter turnCallRouter;
|
||||
private final TurnTokenGenerator tokenGenerator;
|
||||
private final ExperimentEnrollmentManager experimentEnrollmentManager;
|
||||
private final CloudflareTurnCredentialsManager cloudflareTurnCredentialsManager;
|
||||
|
||||
public CallRoutingControllerV2(
|
||||
final RateLimiters rateLimiters,
|
||||
final TurnCallRouter turnCallRouter,
|
||||
final TurnTokenGenerator tokenGenerator,
|
||||
final ExperimentEnrollmentManager experimentEnrollmentManager,
|
||||
final CloudflareTurnCredentialsManager cloudflareTurnCredentialsManager
|
||||
) {
|
||||
this.rateLimiters = rateLimiters;
|
||||
this.turnCallRouter = turnCallRouter;
|
||||
this.tokenGenerator = tokenGenerator;
|
||||
this.experimentEnrollmentManager = experimentEnrollmentManager;
|
||||
this.cloudflareTurnCredentialsManager = cloudflareTurnCredentialsManager;
|
||||
}
|
||||
|
||||
@@ -77,29 +59,19 @@ public class CallRoutingControllerV2 {
|
||||
@ApiResponse(responseCode = "422", description = "Invalid request format.")
|
||||
@ApiResponse(responseCode = "429", description = "Rate limited.")
|
||||
public GetCallingRelaysResponse getCallingRelays(
|
||||
final @ReadOnly @Auth AuthenticatedDevice auth,
|
||||
@Context ContainerRequestContext requestContext
|
||||
final @ReadOnly @Auth AuthenticatedDevice auth
|
||||
) throws RateLimitExceededException, IOException {
|
||||
UUID aci = auth.getAccount().getUuid();
|
||||
rateLimiters.getCallEndpointLimiter().validate(aci);
|
||||
|
||||
List<TurnToken> tokens = new ArrayList<>();
|
||||
if (experimentEnrollmentManager.isEnrolled(auth.getAccount().getNumber(), aci, "cloudflareTurn")) {
|
||||
tokens.add(cloudflareTurnCredentialsManager.retrieveFromCloudflare());
|
||||
}
|
||||
|
||||
Optional<InetAddress> address = Optional.empty();
|
||||
try {
|
||||
final String remoteAddress = (String) requestContext.getProperty(
|
||||
RemoteAddressFilter.REMOTE_ADDRESS_ATTRIBUTE_NAME);
|
||||
address = Optional.of(InetAddress.getByName(remoteAddress));
|
||||
} catch (UnknownHostException e) {
|
||||
INVALID_IP_COUNTER.increment();
|
||||
tokens.add(cloudflareTurnCredentialsManager.retrieveFromCloudflare());
|
||||
} catch (Exception e) {
|
||||
CallRoutingControllerV2.CLOUDFLARE_TURN_ERROR_COUNTER.increment();
|
||||
throw e;
|
||||
}
|
||||
|
||||
TurnServerOptions options = turnCallRouter.getRoutingFor(aci, address, TURN_INSTANCE_LIMIT);
|
||||
tokens.add(tokenGenerator.generateWithTurnServerOptions(options));
|
||||
|
||||
return new GetCallingRelaysResponse(tokens);
|
||||
}
|
||||
|
||||
|
||||
+293
@@ -0,0 +1,293 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonCreator;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import io.swagger.v3.oas.annotations.parameters.RequestBody;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.ws.rs.Consumes;
|
||||
import jakarta.ws.rs.GET;
|
||||
import jakarta.ws.rs.POST;
|
||||
import jakarta.ws.rs.PUT;
|
||||
import jakarta.ws.rs.Path;
|
||||
import jakarta.ws.rs.Produces;
|
||||
import jakarta.ws.rs.QueryParam;
|
||||
import jakarta.ws.rs.WebApplicationException;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import java.io.IOException;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.util.Base64;
|
||||
import java.util.Locale;
|
||||
import org.glassfish.jersey.server.ManagedAsync;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupAuthManager;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.devicecheck.AppleDeviceCheckManager;
|
||||
import org.whispersystems.textsecuregcm.storage.devicecheck.ChallengeNotFoundException;
|
||||
import org.whispersystems.textsecuregcm.storage.devicecheck.DeviceCheckKeyIdNotFoundException;
|
||||
import org.whispersystems.textsecuregcm.storage.devicecheck.DeviceCheckVerificationFailedException;
|
||||
import org.whispersystems.textsecuregcm.storage.devicecheck.DuplicatePublicKeyException;
|
||||
import org.whispersystems.textsecuregcm.storage.devicecheck.RequestReuseException;
|
||||
import org.whispersystems.textsecuregcm.storage.devicecheck.TooManyKeysException;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
import org.whispersystems.websocket.auth.ReadOnly;
|
||||
|
||||
/**
|
||||
* Process platform device attestations.
|
||||
* <p>
|
||||
* Device attestations allow clients that can prove that they are running a signed signal build on valid Apple hardware.
|
||||
* Currently, this is only used to allow beta builds to access backup functionality, since in-app purchases are not
|
||||
* available iOS TestFlight builds.
|
||||
*/
|
||||
@Path("/v1/devicecheck")
|
||||
@io.swagger.v3.oas.annotations.tags.Tag(name = "DeviceCheck")
|
||||
public class DeviceCheckController {
|
||||
|
||||
private final Clock clock;
|
||||
private final BackupAuthManager backupAuthManager;
|
||||
private final AppleDeviceCheckManager deviceCheckManager;
|
||||
private final RateLimiters rateLimiters;
|
||||
private final long backupRedemptionLevel;
|
||||
private final Duration backupRedemptionDuration;
|
||||
|
||||
public DeviceCheckController(
|
||||
final Clock clock,
|
||||
final BackupAuthManager backupAuthManager,
|
||||
final AppleDeviceCheckManager deviceCheckManager,
|
||||
final RateLimiters rateLimiters,
|
||||
final long backupRedemptionLevel,
|
||||
final Duration backupRedemptionDuration) {
|
||||
this.clock = clock;
|
||||
this.backupAuthManager = backupAuthManager;
|
||||
this.deviceCheckManager = deviceCheckManager;
|
||||
this.backupRedemptionLevel = backupRedemptionLevel;
|
||||
this.backupRedemptionDuration = backupRedemptionDuration;
|
||||
this.rateLimiters = rateLimiters;
|
||||
}
|
||||
|
||||
public record ChallengeResponse(
|
||||
@Schema(description = "A challenge to use when generating attestations or assertions")
|
||||
String challenge) {}
|
||||
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/attest")
|
||||
@Operation(summary = "Fetch an attest challenge", description = """
|
||||
Retrieve a challenge to use in an attestation, which should be provided at `PUT /v1/devicecheck/attest`. To
|
||||
produce the clientDataHash for [attestKey](https://developer.apple.com/documentation/devicecheck/dcappattestservice/attestkey(_:clientdatahash:completionhandler:))
|
||||
take the SHA256 of the UTF-8 bytes of the returned challenge.
|
||||
|
||||
Repeat calls to retrieve a challenge may return the same challenge until it is used in a `PUT`. Callers should
|
||||
have a single outstanding challenge at any given time.
|
||||
""")
|
||||
@ApiResponse(responseCode = "200", description = "The response body includes a challenge")
|
||||
@ApiResponse(responseCode = "429", description = "Ratelimited.")
|
||||
@ManagedAsync
|
||||
public ChallengeResponse attestChallenge(@ReadOnly @Auth AuthenticatedDevice authenticatedDevice)
|
||||
throws RateLimitExceededException {
|
||||
rateLimiters.forDescriptor(RateLimiters.For.DEVICE_CHECK_CHALLENGE)
|
||||
.validate(authenticatedDevice.getAccount().getUuid());
|
||||
|
||||
return new ChallengeResponse(deviceCheckManager.createChallenge(
|
||||
AppleDeviceCheckManager.ChallengeType.ATTEST,
|
||||
authenticatedDevice.getAccount()));
|
||||
}
|
||||
|
||||
@PUT
|
||||
@Consumes(MediaType.APPLICATION_OCTET_STREAM)
|
||||
@Path("/attest")
|
||||
@Operation(summary = "Register a keyId", description = """
|
||||
Register a keyId with an attestation, which can be used to generate assertions from this account.
|
||||
|
||||
The attestation should use the SHA-256 of a challenge retrieved at `GET /v1/devicecheck/attest` as the
|
||||
`clientDataHash`
|
||||
|
||||
Registration is idempotent, and you should retry network errors with the same challenge as suggested by [device
|
||||
check](https://developer.apple.com/documentation/devicecheck/dcappattestservice/attestkey(_:clientdatahash:completionhandler:)#discussion),
|
||||
as long as your challenge has not expired (410). Even if your challenge is expired, you may continue to retry with
|
||||
your original keyId (and a fresh challenge).
|
||||
""")
|
||||
@ApiResponse(responseCode = "204", description = "The keyId was successfully added to the account")
|
||||
@ApiResponse(responseCode = "410", description = "There was no challenge associated with the account. It may have expired.")
|
||||
@ApiResponse(responseCode = "401", description = "The attestation could not be verified")
|
||||
@ApiResponse(responseCode = "413", description = "There are too many unique keyIds associated with this account. This is an unrecoverable error.")
|
||||
@ApiResponse(responseCode = "409", description = "The provided keyId has already been registered to a different account")
|
||||
@ManagedAsync
|
||||
public void attest(
|
||||
@ReadOnly @Auth final AuthenticatedDevice authenticatedDevice,
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@Parameter(description = "The keyId, encoded with padded url-safe base64")
|
||||
@QueryParam("keyId") final String keyId,
|
||||
|
||||
@RequestBody(description = "The attestation data, created by [attestKey](https://developer.apple.com/documentation/devicecheck/dcappattestservice/attestkey(_:clientdatahash:completionhandler:))")
|
||||
@NotNull final byte[] attestation) {
|
||||
|
||||
try {
|
||||
deviceCheckManager.registerAttestation(authenticatedDevice.getAccount(), parseKeyId(keyId), attestation);
|
||||
} catch (TooManyKeysException e) {
|
||||
throw new WebApplicationException(Response.status(413).build());
|
||||
} catch (ChallengeNotFoundException e) {
|
||||
throw new WebApplicationException(Response.status(410).build());
|
||||
} catch (DeviceCheckVerificationFailedException e) {
|
||||
throw new WebApplicationException(e.getMessage(), Response.status(401).build());
|
||||
} catch (DuplicatePublicKeyException e) {
|
||||
throw new WebApplicationException(Response.status(409).build());
|
||||
}
|
||||
}
|
||||
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/assert")
|
||||
@Operation(summary = "Fetch an assert challenge", description = """
|
||||
Retrieve a challenge to use in an attestation, which must be provided at `POST /v1/devicecheck/assert`. To produce
|
||||
the `clientDataHash` for [generateAssertion](https://developer.apple.com/documentation/devicecheck/dcappattestservice/generateassertion(_:clientdatahash:completionhandler:)),
|
||||
construct the request you intend to `POST` and include the returned challenge as the "challenge"
|
||||
field. Serialize the request as JSON and take the SHA256 of the request, as described [here](https://developer.apple.com/documentation/devicecheck/establishing-your-app-s-integrity#Assert-your-apps-validity-as-necessary).
|
||||
Note that the JSON body provided to the PUT must exactly match the input to the `clientDataHash` (field order,
|
||||
whitespace, etc matters)
|
||||
|
||||
Repeat calls to retrieve a challenge may return the same challenge until it is used in a `POST`. Callers should
|
||||
attempt to only have a single outstanding challenge at any given time.
|
||||
""")
|
||||
@ApiResponse(responseCode = "200", description = "The response body includes a challenge")
|
||||
@ApiResponse(responseCode = "429", description = "Ratelimited.")
|
||||
@ManagedAsync
|
||||
public ChallengeResponse assertChallenge(
|
||||
@ReadOnly @Auth AuthenticatedDevice authenticatedDevice,
|
||||
|
||||
@Parameter(schema = @Schema(description = "The type of action you will make an assertion for",
|
||||
allowableValues = {"backup"},
|
||||
implementation = String.class))
|
||||
@QueryParam("action") Action action) throws RateLimitExceededException {
|
||||
rateLimiters.forDescriptor(RateLimiters.For.DEVICE_CHECK_CHALLENGE)
|
||||
.validate(authenticatedDevice.getAccount().getUuid());
|
||||
return new ChallengeResponse(
|
||||
deviceCheckManager.createChallenge(toChallengeType(action),
|
||||
authenticatedDevice.getAccount()));
|
||||
}
|
||||
|
||||
@POST
|
||||
@Consumes(MediaType.APPLICATION_OCTET_STREAM)
|
||||
@Path("/assert")
|
||||
@Operation(summary = "Perform an attested action", description = """
|
||||
Specify some action to take on the account via the request field. The request must exactly match the request you
|
||||
provide when [generating the assertion](https://developer.apple.com/documentation/devicecheck/dcappattestservice/generateassertion(_:clientdatahash:completionhandler:)).
|
||||
The request must include a challenge previously retrieved from `GET /v1/devicecheck/assert`.
|
||||
|
||||
Each assertion increments the counter associated with the client's device key. This method enforces that no
|
||||
assertion with a counter lower than a counter we've already seen is allowed to execute. If a client issues
|
||||
multiple requests concurrently, or if they retry a request that had an indeterminate outcome, it's possible that
|
||||
the request will not be accepted because the server has already stored the updated counter. In this case the
|
||||
request may return 401, and the client should generate a fresh assert for the request.
|
||||
""")
|
||||
@ApiResponse(responseCode = "204", description = "The assertion was valid and the corresponding action was executed")
|
||||
@ApiResponse(responseCode = "404", description = "The provided keyId was not found")
|
||||
@ApiResponse(responseCode = "410", description = "There was no challenge associated with the account. It may have expired.")
|
||||
@ApiResponse(responseCode = "401", description = "The assertion could not be verified")
|
||||
@ManagedAsync
|
||||
public void assertion(
|
||||
@ReadOnly @Auth final AuthenticatedDevice authenticatedDevice,
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@Parameter(description = "The keyId, encoded with padded url-safe base64")
|
||||
@QueryParam("keyId") final String keyId,
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@Parameter(description = """
|
||||
The asserted JSON request data, encoded as a string in padded url-safe base64. This must exactly match the
|
||||
request you use when generating the assertion (including field ordering, whitespace, etc).
|
||||
""",
|
||||
schema = @Schema(implementation = AssertionRequest.class))
|
||||
@QueryParam("request") final DeviceCheckController.AssertionRequestWrapper request,
|
||||
|
||||
@RequestBody(description = "The assertion created by [generateAssertion](https://developer.apple.com/documentation/devicecheck/dcappattestservice/generateassertion(_:clientdatahash:completionhandler:))")
|
||||
@NotNull final byte[] assertion) {
|
||||
|
||||
try {
|
||||
deviceCheckManager.validateAssert(
|
||||
authenticatedDevice.getAccount(),
|
||||
parseKeyId(keyId),
|
||||
toChallengeType(request.assertionRequest().action()),
|
||||
request.assertionRequest().challenge(),
|
||||
request.rawJson(),
|
||||
assertion);
|
||||
} catch (ChallengeNotFoundException e) {
|
||||
throw new WebApplicationException(Response.status(410).build());
|
||||
} catch (DeviceCheckVerificationFailedException e) {
|
||||
throw new WebApplicationException(e.getMessage(), Response.status(401).build());
|
||||
} catch (DeviceCheckKeyIdNotFoundException | RequestReuseException e) {
|
||||
throw new WebApplicationException(Response.status(404).build());
|
||||
}
|
||||
|
||||
// The request assertion was validated, execute it
|
||||
switch (request.assertionRequest().action()) {
|
||||
case BACKUP -> backupAuthManager.extendBackupVoucher(
|
||||
authenticatedDevice.getAccount(),
|
||||
new Account.BackupVoucher(backupRedemptionLevel, clock.instant().plus(backupRedemptionDuration)))
|
||||
.join();
|
||||
}
|
||||
}
|
||||
|
||||
public enum Action {
|
||||
BACKUP;
|
||||
|
||||
@JsonCreator
|
||||
public static Action fromString(final String action) {
|
||||
for (final Action a : Action.values()) {
|
||||
if (a.name().toLowerCase(Locale.ROOT).equals(action)) {
|
||||
return a;
|
||||
}
|
||||
}
|
||||
throw new IllegalArgumentException("Invalid action: " + action);
|
||||
}
|
||||
}
|
||||
|
||||
public record AssertionRequest(
|
||||
@Schema(description = "The challenge retrieved at `GET /v1/devicecheck/assert`")
|
||||
String challenge,
|
||||
@Schema(description = "The type of action you'd like to perform with this assert",
|
||||
allowableValues = {"backup"}, implementation = String.class)
|
||||
Action action) {}
|
||||
|
||||
/*
|
||||
* Parses the base64 encoded AssertionRequest, but preserves the rawJson as well
|
||||
*/
|
||||
public record AssertionRequestWrapper(AssertionRequest assertionRequest, byte[] rawJson) {
|
||||
|
||||
public static AssertionRequestWrapper fromString(String requestBase64) throws IOException {
|
||||
final byte[] requestJson = Base64.getUrlDecoder().decode(requestBase64);
|
||||
final AssertionRequest requestData = SystemMapper.jsonMapper().readValue(requestJson, AssertionRequest.class);
|
||||
return new AssertionRequestWrapper(requestData, requestJson);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private static AppleDeviceCheckManager.ChallengeType toChallengeType(final Action action) {
|
||||
return switch (action) {
|
||||
case BACKUP -> AppleDeviceCheckManager.ChallengeType.ASSERT_BACKUP_REDEMPTION;
|
||||
};
|
||||
}
|
||||
|
||||
private static byte[] parseKeyId(final String base64KeyId) {
|
||||
try {
|
||||
return Base64.getUrlDecoder().decode(base64KeyId);
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw new WebApplicationException(Response.status(422).entity(e.getMessage()).build());
|
||||
}
|
||||
}
|
||||
}
|
||||
+101
-55
@@ -7,7 +7,6 @@ package org.whispersystems.textsecuregcm.controllers;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.common.net.HttpHeaders;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.lettuce.core.RedisException;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
@@ -43,7 +42,9 @@ import java.time.Instant;
|
||||
import java.util.Arrays;
|
||||
import java.util.EnumMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionException;
|
||||
@@ -51,6 +52,7 @@ import java.util.concurrent.CompletionStage;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.stream.Collectors;
|
||||
import javax.annotation.Nullable;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.glassfish.jersey.server.ContainerRequest;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.BasicAuthorizationHeader;
|
||||
@@ -65,6 +67,7 @@ import org.whispersystems.textsecuregcm.entities.LinkDeviceResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.PreKeySignatureValidator;
|
||||
import org.whispersystems.textsecuregcm.entities.ProvisioningMessage;
|
||||
import org.whispersystems.textsecuregcm.entities.RemoteAttachment;
|
||||
import org.whispersystems.textsecuregcm.entities.RemoteAttachmentError;
|
||||
import org.whispersystems.textsecuregcm.entities.RestoreAccountRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.SetPublicKeyRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.TransferArchiveUploadedRequest;
|
||||
@@ -80,6 +83,7 @@ import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceSpec;
|
||||
import org.whispersystems.textsecuregcm.storage.LinkDeviceTokenAlreadyUsedException;
|
||||
import org.whispersystems.textsecuregcm.storage.PersistentTimer;
|
||||
import org.whispersystems.textsecuregcm.util.DeviceCapabilityAdapter;
|
||||
import org.whispersystems.textsecuregcm.util.EnumMapUtil;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
@@ -99,6 +103,7 @@ public class DeviceController {
|
||||
private final AccountsManager accounts;
|
||||
private final ClientPublicKeysManager clientPublicKeysManager;
|
||||
private final RateLimiters rateLimiters;
|
||||
private final PersistentTimer persistentTimer;
|
||||
private final Map<String, Integer> maxDeviceConfiguration;
|
||||
|
||||
private final EnumMap<ClientPlatform, AtomicInteger> linkedDeviceListenersByPlatform;
|
||||
@@ -107,9 +112,15 @@ public class DeviceController {
|
||||
private static final String LINKED_DEVICE_LISTENER_GAUGE_NAME =
|
||||
MetricsUtil.name(DeviceController.class, "linkedDeviceListeners");
|
||||
|
||||
private static final String WAIT_FOR_LINKED_DEVICE_TIMER_NAMESPACE = "wait_for_linked_device";
|
||||
private static final String WAIT_FOR_LINKED_DEVICE_TIMER_NAME =
|
||||
MetricsUtil.name(DeviceController.class, "waitForLinkedDeviceDuration");
|
||||
|
||||
private static final String WAIT_FOR_TRANSFER_ARCHIVE_TIMER_NAMESPACE = "wait_for_transfer_archive";
|
||||
private static final String WAIT_FOR_TRANSFER_ARCHIVE_TIMER_NAME =
|
||||
MetricsUtil.name(DeviceController.class, "waitForTransferArchiveDuration");
|
||||
|
||||
|
||||
@VisibleForTesting
|
||||
static final int MIN_TOKEN_IDENTIFIER_LENGTH = 32;
|
||||
|
||||
@@ -119,11 +130,13 @@ public class DeviceController {
|
||||
public DeviceController(final AccountsManager accounts,
|
||||
final ClientPublicKeysManager clientPublicKeysManager,
|
||||
final RateLimiters rateLimiters,
|
||||
final PersistentTimer persistentTimer,
|
||||
final Map<String, Integer> maxDeviceConfiguration) {
|
||||
|
||||
this.accounts = accounts;
|
||||
this.clientPublicKeysManager = clientPublicKeysManager;
|
||||
this.rateLimiters = rateLimiters;
|
||||
this.persistentTimer = persistentTimer;
|
||||
this.maxDeviceConfiguration = maxDeviceConfiguration;
|
||||
|
||||
linkedDeviceListenersByPlatform =
|
||||
@@ -141,9 +154,13 @@ public class DeviceController {
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public DeviceInfoList getDevices(@ReadOnly @Auth AuthenticatedDevice auth) {
|
||||
return new DeviceInfoList(auth.getAccount().getDevices().stream()
|
||||
.map(DeviceInfo::forDevice)
|
||||
.toList());
|
||||
// Devices may change their own names (and primary devices may change the names of linked devices) and so the device
|
||||
// state associated with the authenticated account may be stale. Fetch a fresh copy to compensate.
|
||||
return accounts.getByAccountIdentifier(auth.getAccount().getIdentifier(IdentityType.ACI))
|
||||
.map(account -> new DeviceInfoList(account.getDevices().stream()
|
||||
.map(DeviceInfo::forDevice)
|
||||
.toList()))
|
||||
.orElseThrow(ForbiddenException::new);
|
||||
}
|
||||
|
||||
@DELETE
|
||||
@@ -334,7 +351,7 @@ public class DeviceController {
|
||||
@ApiResponse(responseCode = "204", description = "No device was linked to the account before the call completed; clients may repeat the call to continue waiting")
|
||||
@ApiResponse(responseCode = "400", description = "The given token identifier or timeout was invalid")
|
||||
@ApiResponse(responseCode = "429", description = "Rate-limited; try again after the prescribed delay")
|
||||
public CompletableFuture<Response> waitForLinkedDevice(
|
||||
public CompletionStage<Response> waitForLinkedDevice(
|
||||
@ReadOnly @Auth final AuthenticatedDevice authenticatedDevice,
|
||||
|
||||
@PathParam("tokenIdentifier")
|
||||
@@ -354,40 +371,33 @@ public class DeviceController {
|
||||
given amount of time, this endpoint will return a status of HTTP/204.
|
||||
""") final int timeoutSeconds,
|
||||
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) String userAgent) throws RateLimitExceededException {
|
||||
|
||||
rateLimiters.getWaitForLinkedDeviceLimiter().validate(authenticatedDevice.getAccount().getIdentifier(IdentityType.ACI));
|
||||
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) String userAgent) {
|
||||
final AtomicInteger linkedDeviceListenerCounter = getCounterForLinkedDeviceListeners(userAgent);
|
||||
linkedDeviceListenerCounter.incrementAndGet();
|
||||
|
||||
final Timer.Sample sample = Timer.start();
|
||||
try {
|
||||
return accounts.waitForNewLinkedDevice(authenticatedDevice.getAccount().getUuid(),
|
||||
authenticatedDevice.getAuthenticatedDevice(), tokenIdentifier, Duration.ofSeconds(timeoutSeconds))
|
||||
.thenApply(maybeDeviceInfo -> maybeDeviceInfo
|
||||
.map(deviceInfo -> Response.status(Response.Status.OK).entity(deviceInfo).build())
|
||||
.orElseGet(() -> Response.status(Response.Status.NO_CONTENT).build()))
|
||||
.exceptionally(ExceptionUtils.exceptionallyHandler(IllegalArgumentException.class,
|
||||
e -> Response.status(Response.Status.BAD_REQUEST).build()))
|
||||
.whenComplete((response, throwable) -> {
|
||||
linkedDeviceListenerCounter.decrementAndGet();
|
||||
return rateLimiters.getWaitForLinkedDeviceLimiter()
|
||||
.validateAsync(authenticatedDevice.getAccount().getIdentifier(IdentityType.ACI))
|
||||
.thenCompose(ignored -> persistentTimer.start(WAIT_FOR_LINKED_DEVICE_TIMER_NAMESPACE, tokenIdentifier))
|
||||
.thenCompose(sample -> accounts.waitForNewLinkedDevice(
|
||||
authenticatedDevice.getAccount().getUuid(),
|
||||
authenticatedDevice.getAuthenticatedDevice(),
|
||||
tokenIdentifier,
|
||||
Duration.ofSeconds(timeoutSeconds))
|
||||
.thenApply(maybeDeviceInfo -> maybeDeviceInfo
|
||||
.map(deviceInfo -> Response.status(Response.Status.OK).entity(deviceInfo).build())
|
||||
.orElseGet(() -> Response.status(Response.Status.NO_CONTENT).build()))
|
||||
.exceptionally(ExceptionUtils.exceptionallyHandler(IllegalArgumentException.class,
|
||||
e -> Response.status(Response.Status.BAD_REQUEST).build()))
|
||||
.whenComplete((response, throwable) -> {
|
||||
linkedDeviceListenerCounter.decrementAndGet();
|
||||
|
||||
if (response != null) {
|
||||
sample.stop(Timer.builder(WAIT_FOR_LINKED_DEVICE_TIMER_NAME)
|
||||
.publishPercentileHistogram(true)
|
||||
.tags(Tags.of(UserAgentTagUtil.getPlatformTag(userAgent),
|
||||
io.micrometer.core.instrument.Tag.of("deviceFound",
|
||||
String.valueOf(response.getStatus() == Response.Status.OK.getStatusCode()))))
|
||||
.register(Metrics.globalRegistry));
|
||||
}
|
||||
});
|
||||
} catch (final RedisException e) {
|
||||
// `waitForNewLinkedDevice` could fail synchronously if the Redis circuit breaker is open; prevent counter drift
|
||||
// if that happens
|
||||
linkedDeviceListenerCounter.decrementAndGet();
|
||||
throw e;
|
||||
}
|
||||
if (response != null && response.getStatus() == Response.Status.OK.getStatusCode()) {
|
||||
sample.stop(Timer.builder(WAIT_FOR_LINKED_DEVICE_TIMER_NAME)
|
||||
.publishPercentileHistogram(true)
|
||||
.tags(Tags.of(UserAgentTagUtil.getPlatformTag(userAgent)))
|
||||
.register(Metrics.globalRegistry));
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
private AtomicInteger getCounterForLinkedDeviceListeners(final String userAgent) {
|
||||
@@ -398,14 +408,6 @@ public class DeviceController {
|
||||
}
|
||||
}
|
||||
|
||||
@PUT
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/unauthenticated_delivery")
|
||||
public void setUnauthenticatedDelivery(@Mutable @Auth AuthenticatedDevice auth) {
|
||||
assert (auth.getAuthenticatedDevice() != null);
|
||||
// Deprecated
|
||||
}
|
||||
|
||||
@PUT
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/capabilities")
|
||||
@@ -522,8 +524,10 @@ public class DeviceController {
|
||||
@Operation(
|
||||
summary = "Signals that a transfer archive has been uploaded for a specific linked device",
|
||||
description = """
|
||||
Signals that a transfer archive has been uploaded for a specific linked device. Devices waiting via the "wait
|
||||
for transfer archive" endpoint will be notified that the new archive is available.
|
||||
Signals that a transfer archive has been uploaded or failed for a specific linked device. Devices waiting via
|
||||
the "wait for transfer archive" endpoint will be notified that the new archive is available.
|
||||
|
||||
If the uploader cannot upload the transfer archive, they must signal an error.
|
||||
""")
|
||||
@ApiResponse(responseCode = "204", description = "Success")
|
||||
@ApiResponse(responseCode = "422", description = "The request object could not be parsed or was otherwise invalid")
|
||||
@@ -531,7 +535,8 @@ public class DeviceController {
|
||||
public CompletionStage<Void> recordTransferArchiveUploaded(@ReadOnly @Auth final AuthenticatedDevice authenticatedDevice,
|
||||
@NotNull @Valid final TransferArchiveUploadedRequest transferArchiveUploadedRequest) {
|
||||
|
||||
return rateLimiters.getUploadTransferArchiveLimiter().validateAsync(authenticatedDevice.getAccount().getIdentifier(IdentityType.ACI))
|
||||
return rateLimiters.getUploadTransferArchiveLimiter()
|
||||
.validateAsync(authenticatedDevice.getAccount().getIdentifier(IdentityType.ACI))
|
||||
.thenCompose(ignored -> accounts.recordTransferArchiveUpload(authenticatedDevice.getAccount(),
|
||||
transferArchiveUploadedRequest.destinationDeviceId(),
|
||||
Instant.ofEpochMilli(transferArchiveUploadedRequest.destinationDeviceCreated()),
|
||||
@@ -546,8 +551,11 @@ public class DeviceController {
|
||||
Waits for a new transfer archive to be uploaded for the authenticated device and returns the location of the
|
||||
archive when available.
|
||||
""")
|
||||
@ApiResponse(responseCode = "200", description = "A new transfer archive was uploaded for the authenticated device",
|
||||
content = @Content(schema = @Schema(implementation = RemoteAttachment.class)))
|
||||
@ApiResponse(responseCode = "200", description = "Either a new transfer archive was uploaded for the authenticated device, or the upload has failed",
|
||||
content = @Content(schema = @Schema(description = """
|
||||
The location of the transfer archive if the archive was successfully uploaded, otherwise a error indicating that
|
||||
the upload has failed and the destination device should stop waiting
|
||||
""", oneOf = {RemoteAttachment.class, RemoteAttachmentError.class})))
|
||||
@ApiResponse(responseCode = "204", description = "No transfer archive was uploaded before the call completed; clients may repeat the call to continue waiting")
|
||||
@ApiResponse(responseCode = "400", description = "The given timeout was invalid")
|
||||
@ApiResponse(responseCode = "429", description = "Rate-limited; try again after the prescribed delay")
|
||||
@@ -563,17 +571,55 @@ public class DeviceController {
|
||||
description = """
|
||||
The amount of time (in seconds) to wait for a response. If a transfer archive for the authenticated
|
||||
device is not available within the given amount of time, this endpoint will return a status of HTTP/204.
|
||||
""") final int timeoutSeconds) {
|
||||
""") final int timeoutSeconds,
|
||||
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) @Nullable String userAgent) {
|
||||
|
||||
|
||||
final String rateLimiterKey = authenticatedDevice.getAccount().getIdentifier(IdentityType.ACI) +
|
||||
":" + authenticatedDevice.getAuthenticatedDevice().getId();
|
||||
|
||||
return rateLimiters.getWaitForTransferArchiveLimiter().validateAsync(rateLimiterKey)
|
||||
.thenCompose(ignored -> accounts.waitForTransferArchive(authenticatedDevice.getAccount(),
|
||||
authenticatedDevice.getAuthenticatedDevice(),
|
||||
Duration.ofSeconds(timeoutSeconds)))
|
||||
.thenApply(maybeTransferArchive -> maybeTransferArchive
|
||||
.map(transferArchive -> Response.status(Response.Status.OK).entity(transferArchive).build())
|
||||
.orElseGet(() -> Response.status(Response.Status.NO_CONTENT).build()));
|
||||
.thenCompose(ignored -> persistentTimer.start(WAIT_FOR_TRANSFER_ARCHIVE_TIMER_NAMESPACE, rateLimiterKey))
|
||||
.thenCompose(sample -> accounts.waitForTransferArchive(authenticatedDevice.getAccount(),
|
||||
authenticatedDevice.getAuthenticatedDevice(),
|
||||
Duration.ofSeconds(timeoutSeconds))
|
||||
.thenApply(maybeTransferArchive -> maybeTransferArchive
|
||||
.map(transferArchive -> Response.status(Response.Status.OK).entity(transferArchive).build())
|
||||
.orElseGet(() -> Response.status(Response.Status.NO_CONTENT).build()))
|
||||
.whenComplete((response, throwable) -> {
|
||||
if (response != null && response.getStatus() == Response.Status.OK.getStatusCode()) {
|
||||
sample.stop(Timer.builder(WAIT_FOR_TRANSFER_ARCHIVE_TIMER_NAME)
|
||||
.publishPercentileHistogram(true)
|
||||
.tags(Tags.of(
|
||||
UserAgentTagUtil.getPlatformTag(userAgent),
|
||||
primaryPlatformTag(authenticatedDevice.getAccount())))
|
||||
.register(Metrics.globalRegistry));
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
private static io.micrometer.core.instrument.Tag primaryPlatformTag(final Account account) {
|
||||
final Device primaryDevice = account.getPrimaryDevice();
|
||||
|
||||
Optional<ClientPlatform> clientPlatform = Optional.empty();
|
||||
if (StringUtils.isNotBlank(primaryDevice.getGcmId())) {
|
||||
clientPlatform = Optional.of(ClientPlatform.ANDROID);
|
||||
} else if (StringUtils.isNotBlank(primaryDevice.getApnId())) {
|
||||
clientPlatform = Optional.of(ClientPlatform.IOS);
|
||||
}
|
||||
clientPlatform = clientPlatform.or(() -> Optional.ofNullable(
|
||||
switch (primaryDevice.getUserAgent()) {
|
||||
case "OWA" -> ClientPlatform.ANDROID;
|
||||
case "OWI", "OWP" -> ClientPlatform.IOS;
|
||||
case "OWD" -> ClientPlatform.DESKTOP;
|
||||
case null, default -> null;
|
||||
}));
|
||||
|
||||
return io.micrometer.core.instrument.Tag.of(
|
||||
"primaryPlatform",
|
||||
clientPlatform
|
||||
.map(p -> p.name().toLowerCase(Locale.ROOT))
|
||||
.orElse("unknown"));
|
||||
}
|
||||
}
|
||||
+12
-4
@@ -6,12 +6,13 @@ package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.ws.rs.GET;
|
||||
import jakarta.ws.rs.Path;
|
||||
import jakarta.ws.rs.Produces;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import java.time.Clock;
|
||||
import java.util.UUID;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
@@ -48,9 +49,16 @@ public class DirectoryV2Controller {
|
||||
@GET
|
||||
@Path("/auth")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public Response getAuthToken(final @ReadOnly @Auth AuthenticatedDevice auth) {
|
||||
@Operation(
|
||||
summary = "Generate credentials for Contact Discovery Service",
|
||||
description = """
|
||||
Generate Contact Discovery Service credentials. Generated credentials have an expiration time of 24 hours\s
|
||||
(however, the TTL is fully controlled by the server and may change even for already generated credentials).
|
||||
"""
|
||||
)
|
||||
@ApiResponse(responseCode = "200", description = "`JSON` with generated credentials.", useReturnTypeSchema = true)
|
||||
public ExternalServiceCredentials getAuthToken(final @ReadOnly @Auth AuthenticatedDevice auth) {
|
||||
final UUID uuid = auth.getAccount().getUuid();
|
||||
final ExternalServiceCredentials credentials = directoryServiceTokenGenerator.generateForUuid(uuid);
|
||||
return Response.ok().entity(credentials).build();
|
||||
return directoryServiceTokenGenerator.generateForUuid(uuid);
|
||||
}
|
||||
}
|
||||
+3
-3
@@ -151,21 +151,21 @@ public class KeyTransparencyController {
|
||||
try {
|
||||
final AciMonitorRequest aciMonitorRequest = AciMonitorRequest.newBuilder()
|
||||
.setAci(ByteString.copyFrom(request.aci().value().toCompactByteArray()))
|
||||
.addAllEntries(request.aci().positions())
|
||||
.setEntryPosition(request.aci().entryPosition())
|
||||
.setCommitmentIndex(ByteString.copyFrom(request.aci().commitmentIndex()))
|
||||
.build();
|
||||
|
||||
final Optional<UsernameHashMonitorRequest> usernameHashMonitorRequest = request.usernameHash().map(usernameHash ->
|
||||
UsernameHashMonitorRequest.newBuilder()
|
||||
.setUsernameHash(ByteString.copyFrom(usernameHash.value()))
|
||||
.addAllEntries(usernameHash.positions())
|
||||
.setEntryPosition(usernameHash.entryPosition())
|
||||
.setCommitmentIndex(ByteString.copyFrom(usernameHash.commitmentIndex()))
|
||||
.build());
|
||||
|
||||
final Optional<E164MonitorRequest> e164MonitorRequest = request.e164().map(e164 ->
|
||||
E164MonitorRequest.newBuilder()
|
||||
.setE164(e164.value())
|
||||
.addAllEntries(e164.positions())
|
||||
.setEntryPosition(e164.entryPosition())
|
||||
.setCommitmentIndex(ByteString.copyFrom(e164.commitmentIndex()))
|
||||
.build());
|
||||
|
||||
|
||||
+2
-1
@@ -381,7 +381,8 @@ public class KeysController {
|
||||
Metrics.counter(GET_KEYS_COUNTER_NAME, Tags.of(
|
||||
UserAgentTagUtil.getPlatformTag(userAgent),
|
||||
Tag.of(IDENTITY_TYPE_TAG_NAME, targetIdentifier.identityType().name()),
|
||||
Tag.of("oneTimeEcKeyAvailable", String.valueOf(unsignedEcPreKey != null))))
|
||||
Tag.of("oneTimeEcKeyAvailable", String.valueOf(unsignedEcPreKey != null)),
|
||||
Tag.of("pqKeyAvailable", String.valueOf(pqPreKey != null))))
|
||||
.increment();
|
||||
|
||||
if (signedEcPreKey != null || unsignedEcPreKey != null || pqPreKey != null) {
|
||||
|
||||
+267
-465
File diff suppressed because it is too large.
Load diff
+11
@@ -0,0 +1,11 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
public record MismatchedDevices(Set<Byte> missingDeviceIds, Set<Byte> extraDeviceIds, Set<Byte> staleDeviceIds) {
|
||||
}
|
||||
+5
-13
@@ -5,23 +5,15 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class MismatchedDevicesException extends Exception {
|
||||
|
||||
private final List<Byte> missingDevices;
|
||||
private final List<Byte> extraDevices;
|
||||
private final MismatchedDevices mismatchedDevices;
|
||||
|
||||
public MismatchedDevicesException(List<Byte> missingDevices, List<Byte> extraDevices) {
|
||||
this.missingDevices = missingDevices;
|
||||
this.extraDevices = extraDevices;
|
||||
public MismatchedDevicesException(final MismatchedDevices mismatchedDevices) {
|
||||
this.mismatchedDevices = mismatchedDevices;
|
||||
}
|
||||
|
||||
public List<Byte> getMissingDevices() {
|
||||
return missingDevices;
|
||||
}
|
||||
|
||||
public List<Byte> getExtraDevices() {
|
||||
return extraDevices;
|
||||
public MismatchedDevices getMismatchedDevices() {
|
||||
return mismatchedDevices;
|
||||
}
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import java.util.Map;
|
||||
|
||||
public class MultiRecipientMismatchedDevicesException extends Exception {
|
||||
|
||||
private final Map<ServiceIdentifier, MismatchedDevices> mismatchedDevicesByServiceIdentifier;
|
||||
|
||||
public MultiRecipientMismatchedDevicesException(
|
||||
final Map<ServiceIdentifier, MismatchedDevices> mismatchedDevicesByServiceIdentifier) {
|
||||
|
||||
this.mismatchedDevicesByServiceIdentifier = mismatchedDevicesByServiceIdentifier;
|
||||
}
|
||||
|
||||
public Map<ServiceIdentifier, MismatchedDevices> getMismatchedDevicesByServiceIdentifier() {
|
||||
return mismatchedDevicesByServiceIdentifier;
|
||||
}
|
||||
}
|
||||
+39
-5
@@ -10,6 +10,11 @@ import io.dropwizard.auth.Auth;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.StringToClassMapItem;
|
||||
import io.swagger.v3.oas.annotations.media.Content;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.Min;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
@@ -109,25 +114,54 @@ public class OneTimeDonationController {
|
||||
|
||||
public static class CreateBoostRequest {
|
||||
|
||||
@Schema(required = true, maxLength = 3, minLength = 3)
|
||||
@NotEmpty
|
||||
@ExactlySize(3)
|
||||
public String currency;
|
||||
|
||||
@Schema(required = true, minimum = "1", description = "The amount to pay in the [currency's minor unit](https://docs.stripe.com/currencies#minor-units)")
|
||||
@Min(1)
|
||||
public long amount;
|
||||
|
||||
@Schema(description = "The level for the boost payment. Assumed to be the boost level if missing")
|
||||
public Long level;
|
||||
|
||||
@Schema(description = "The payment method", defaultValue = "CARD")
|
||||
public PaymentMethod paymentMethod = PaymentMethod.CARD;
|
||||
}
|
||||
|
||||
public record CreateBoostResponse(String clientSecret) {}
|
||||
public record CreateBoostResponse(
|
||||
@Schema(description = "A client secret that can be used to complete a stripe PaymentIntent")
|
||||
String clientSecret) {}
|
||||
|
||||
|
||||
/**
|
||||
* Creates a Stripe PaymentIntent with the requested amount and currency
|
||||
*/
|
||||
@POST
|
||||
@Path("/create")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Operation(summary = "Create a Stripe payment intent", description = """
|
||||
Create a Stripe PaymentIntent and return a client secret that can be used to complete the payment.
|
||||
|
||||
Once the payment is complete, the paymentIntentId can be used at /v1/subscriptions/receipt_credentials
|
||||
""")
|
||||
@ApiResponse(responseCode = "200", description = "Payment Intent created", content = @Content(schema = @Schema(implementation = CreateBoostResponse.class)))
|
||||
@ApiResponse(responseCode = "403", description = "The request was made on an authenticated channel")
|
||||
@ApiResponse(responseCode = "400", description = """
|
||||
Invalid argument. The response body may include an error code with more specific information. If the error code
|
||||
is `amount_below_currency_minimum` the body will also include the `minimum` field indicating the minimum amount
|
||||
for the currency. If the error code is `amount_above_sepa_limit` the body will also include the `maximum`
|
||||
field indicating the maximum amount for a SEPA transaction.
|
||||
""",
|
||||
content = @Content(schema = @Schema(
|
||||
type = "object",
|
||||
properties = {
|
||||
@StringToClassMapItem(key = "error", value = String.class)
|
||||
})))
|
||||
@ApiResponse(responseCode = "409", description = "Provided level does not match the currency/amount combination",
|
||||
content = @Content(schema = @Schema(
|
||||
type = "object",
|
||||
properties = {
|
||||
@StringToClassMapItem(key = "error", value = String.class)
|
||||
})))
|
||||
public CompletableFuture<Response> createBoostPaymentIntent(
|
||||
@ReadOnly @Auth Optional<AuthenticatedDevice> authenticatedAccount,
|
||||
@NotNull @Valid CreateBoostRequest request,
|
||||
|
||||
+13
-4
@@ -9,8 +9,8 @@ import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.google.common.base.Preconditions;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
@@ -79,6 +79,7 @@ import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.s3.PolicySigner;
|
||||
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
@@ -121,7 +122,7 @@ public class ProfileController {
|
||||
|
||||
private static final String EXPIRING_PROFILE_KEY_CREDENTIAL_TYPE = "expiringProfileKey";
|
||||
|
||||
private static final Counter VERSION_NOT_FOUND_COUNTER = Metrics.counter(name(ProfileController.class, "versionNotFound"));
|
||||
private static final String VERSION_NOT_FOUND_COUNTER_NAME = name(ProfileController.class, "versionNotFound");
|
||||
|
||||
public ProfileController(
|
||||
Clock clock,
|
||||
@@ -237,6 +238,7 @@ public class ProfileController {
|
||||
return buildVersionedProfileResponse(targetAccount,
|
||||
version,
|
||||
maybeRequester.map(requester -> ProfileHelper.isSelfProfileRequest(requester.getUuid(), accountIdentifier)).orElse(false),
|
||||
false,
|
||||
containerRequestContext);
|
||||
}
|
||||
|
||||
@@ -390,20 +392,27 @@ public class ProfileController {
|
||||
.orElse(null);
|
||||
|
||||
return new ExpiringProfileKeyCredentialProfileResponse(
|
||||
buildVersionedProfileResponse(account, version, isSelf, containerRequestContext),
|
||||
buildVersionedProfileResponse(account, version, isSelf, true, containerRequestContext),
|
||||
expiringProfileKeyCredentialResponse);
|
||||
}
|
||||
|
||||
private VersionedProfileResponse buildVersionedProfileResponse(final Account account,
|
||||
final String version,
|
||||
final boolean isSelf,
|
||||
final boolean hasCredentialRequest,
|
||||
final ContainerRequestContext containerRequestContext) {
|
||||
|
||||
final Optional<VersionedProfile> maybeProfile = profilesManager.get(account.getUuid(), version);
|
||||
|
||||
if (maybeProfile.isEmpty()) {
|
||||
// Hypothesis: this should basically never happen since clients can't delete versions
|
||||
VERSION_NOT_FOUND_COUNTER.increment();
|
||||
Metrics.counter(
|
||||
VERSION_NOT_FOUND_COUNTER_NAME,
|
||||
Tags.of(
|
||||
"self", String.valueOf(isSelf),
|
||||
"credential_request", String.valueOf(hasCredentialRequest),
|
||||
"platform", UserAgentTagUtil.getPlatformTag(containerRequestContext.getHeaderString("User-Agent")).getValue()))
|
||||
.increment();
|
||||
}
|
||||
|
||||
final byte[] name = maybeProfile.map(VersionedProfile::name).orElse(null);
|
||||
|
||||
+10
-7
@@ -36,6 +36,7 @@ import java.util.Optional;
|
||||
import org.whispersystems.textsecuregcm.auth.BasicAuthorizationHeader;
|
||||
import org.whispersystems.textsecuregcm.auth.PhoneVerificationTokenManager;
|
||||
import org.whispersystems.textsecuregcm.auth.RegistrationLockVerificationManager;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountCreationResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountIdentityResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.PhoneVerificationRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.RegistrationLockFailure;
|
||||
@@ -100,7 +101,7 @@ public class RegistrationController {
|
||||
@ApiResponse(responseCode = "429", description = "Too many attempts", headers = @Header(
|
||||
name = "Retry-After",
|
||||
description = "If present, an positive integer indicating the number of seconds before a subsequent attempt could succeed"))
|
||||
public AccountIdentityResponse register(
|
||||
public AccountCreationResponse register(
|
||||
@HeaderParam(HttpHeaders.AUTHORIZATION) @NotNull final BasicAuthorizationHeader authorizationHeader,
|
||||
@HeaderParam(HeaderUtils.X_SIGNAL_AGENT) final String signalAgent,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
|
||||
@@ -166,12 +167,14 @@ public class RegistrationController {
|
||||
Tag.of(VERIFICATION_TYPE_TAG_NAME, verificationType.name())))
|
||||
.increment();
|
||||
|
||||
return new AccountIdentityResponse(account.getUuid(),
|
||||
account.getNumber(),
|
||||
account.getPhoneNumberIdentifier(),
|
||||
account.getUsernameHash().orElse(null),
|
||||
account.getUsernameLinkHandle(),
|
||||
existingAccount.map(a -> a.hasCapability(DeviceCapability.STORAGE)).orElse(false));
|
||||
final AccountIdentityResponse identityResponse = new AccountIdentityResponseBuilder(account)
|
||||
// If there was an existing account, return whether it could have had something in the storage service
|
||||
.storageCapable(existingAccount
|
||||
.map(a -> a.hasCapability(DeviceCapability.STORAGE))
|
||||
.orElse(false))
|
||||
.build();
|
||||
|
||||
return new AccountCreationResponse(identityResponse, existingAccount.isPresent());
|
||||
}
|
||||
|
||||
}
|
||||
+12
@@ -7,6 +7,8 @@ package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.ws.rs.GET;
|
||||
import jakarta.ws.rs.Path;
|
||||
@@ -52,6 +54,16 @@ public class RemoteConfigController {
|
||||
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Operation(
|
||||
summary = "Fetch remote configuration",
|
||||
description = """
|
||||
Remote configuration is a list of namespaced keys that clients may use for consistent configuration or behavior.
|
||||
|
||||
Configuration values change over time, and the list should be refreshed periodically, typically at client
|
||||
launch and every few hours thereafter.
|
||||
"""
|
||||
)
|
||||
@ApiResponse(responseCode = "200", description = "Remote configuration values for the authenticated user", useReturnTypeSchema = true)
|
||||
public UserRemoteConfigList getAll(@ReadOnly @Auth AuthenticatedDevice auth) {
|
||||
try {
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA1");
|
||||
|
||||
+10
@@ -6,6 +6,8 @@
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.ws.rs.GET;
|
||||
import jakarta.ws.rs.Path;
|
||||
@@ -37,6 +39,14 @@ public class SecureStorageController {
|
||||
@GET
|
||||
@Path("/auth")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Operation(
|
||||
summary = "Generate credentials for Storage Service",
|
||||
description = """
|
||||
Generate Storage Service credentials. Generated credentials have an expiration time of 24 hours\s
|
||||
(however, the TTL is fully controlled by the server and may change even for already generated credentials).
|
||||
"""
|
||||
)
|
||||
@ApiResponse(responseCode = "200", description = "`JSON` with generated credentials.", useReturnTypeSchema = true)
|
||||
public ExternalServiceCredentials getAuth(@ReadOnly @Auth AuthenticatedDevice auth) {
|
||||
return storageServiceCredentialsGenerator.generateForUuid(auth.getAccount().getUuid());
|
||||
}
|
||||
|
||||
-161
@@ -1,161 +0,0 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.ws.rs.Consumes;
|
||||
import jakarta.ws.rs.GET;
|
||||
import jakarta.ws.rs.POST;
|
||||
import jakarta.ws.rs.PUT;
|
||||
import jakarta.ws.rs.Path;
|
||||
import jakarta.ws.rs.Produces;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import java.time.Clock;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.Collectors;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsSelector;
|
||||
import org.whispersystems.textsecuregcm.configuration.SecureValueRecovery3Configuration;
|
||||
import org.whispersystems.textsecuregcm.entities.AuthCheckRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.AuthCheckResponseV3;
|
||||
import org.whispersystems.textsecuregcm.entities.SetShareSetRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.Svr3Credentials;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimitedByIp;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.util.Optionals;
|
||||
import org.whispersystems.websocket.auth.Mutable;
|
||||
import org.whispersystems.websocket.auth.ReadOnly;
|
||||
|
||||
@Path("/v3/backup")
|
||||
@Tag(name = "Secure Value Recovery")
|
||||
public class SecureValueRecovery3Controller {
|
||||
|
||||
private static final long MAX_AGE_SECONDS = TimeUnit.DAYS.toSeconds(30);
|
||||
|
||||
public static ExternalServiceCredentialsGenerator credentialsGenerator(final SecureValueRecovery3Configuration cfg) {
|
||||
return credentialsGenerator(cfg, Clock.systemUTC());
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
public static ExternalServiceCredentialsGenerator credentialsGenerator(final SecureValueRecovery3Configuration cfg,
|
||||
final Clock clock) {
|
||||
return ExternalServiceCredentialsGenerator
|
||||
.builder(cfg.userAuthenticationTokenSharedSecret())
|
||||
.withUserDerivationKey(cfg.userIdTokenSharedSecret().value())
|
||||
.prependUsername(false)
|
||||
.withDerivedUsernameTruncateLength(16)
|
||||
.withClock(clock)
|
||||
.build();
|
||||
}
|
||||
|
||||
private final ExternalServiceCredentialsGenerator backupServiceCredentialGenerator;
|
||||
private final AccountsManager accountsManager;
|
||||
|
||||
public SecureValueRecovery3Controller(final ExternalServiceCredentialsGenerator backupServiceCredentialGenerator,
|
||||
final AccountsManager accountsManager) {
|
||||
this.backupServiceCredentialGenerator = backupServiceCredentialGenerator;
|
||||
this.accountsManager = accountsManager;
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/auth")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Operation(
|
||||
summary = "Generate credentials for SVR3",
|
||||
description = """
|
||||
Generate SVR3 service credentials. Generated credentials have an expiration time of 30 days
|
||||
(however, the TTL is fully controlled by the server side and may change even for already generated credentials).
|
||||
|
||||
If a share-set has been previously set via /v3/backups/share-set, it will be included in the response
|
||||
""")
|
||||
@ApiResponse(responseCode = "200", description = "`JSON` with generated credentials and share-set", useReturnTypeSchema = true)
|
||||
@ApiResponse(responseCode = "401", description = "Account authentication check failed.")
|
||||
public Svr3Credentials getAuth(@ReadOnly @Auth final AuthenticatedDevice auth) {
|
||||
final ExternalServiceCredentials creds = backupServiceCredentialGenerator.generateFor(
|
||||
auth.getAccount().getUuid().toString());
|
||||
return new Svr3Credentials(creds.username(), creds.password(), auth.getAccount().getSvr3ShareSet());
|
||||
}
|
||||
|
||||
@PUT
|
||||
@Path("/share-set")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Operation(
|
||||
summary = "Set a share-set for the account",
|
||||
description = """
|
||||
Add a share-set to the account that can later be retrieved at v3/backups/auth or during registration. After
|
||||
storing a value with SVR3, clients must store the returned share-set so the value can be restored later.
|
||||
""")
|
||||
@ApiResponse(responseCode = "204", description = "Successfully set share-set")
|
||||
@ApiResponse(responseCode = "401", description = "Account authentication check failed.")
|
||||
public void setShareSet(
|
||||
@Mutable @Auth final AuthenticatedDevice auth,
|
||||
@NotNull @Valid final SetShareSetRequest request) {
|
||||
accountsManager.update(auth.getAccount(), account -> account.setSvr3ShareSet(request.shareSet()));
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/auth/check")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@RateLimitedByIp(RateLimiters.For.BACKUP_AUTH_CHECK)
|
||||
@Operation(
|
||||
summary = "Check SVR3 credentials",
|
||||
description = """
|
||||
Over time, clients may wind up with multiple sets of SVR3 authentication credentials in cloud storage.
|
||||
To determine which set is most current and should be used to communicate with SVR3 to retrieve a master key
|
||||
(from which a registration recovery password can be derived), clients should call this endpoint
|
||||
with a list of stored credentials. The response will identify which (if any) set of credentials are
|
||||
appropriate for communicating with SVR3.
|
||||
""")
|
||||
@ApiResponse(responseCode = "200", description = "`JSON` with the check results.", useReturnTypeSchema = true)
|
||||
@ApiResponse(responseCode = "422", description = "Provided list of SVR3 credentials could not be parsed")
|
||||
@ApiResponse(responseCode = "400", description = "`POST` request body is not a valid `JSON`")
|
||||
public AuthCheckResponseV3 authCheck(@NotNull @Valid final AuthCheckRequest request) {
|
||||
final List<ExternalServiceCredentialsSelector.CredentialInfo> credentials = ExternalServiceCredentialsSelector.check(
|
||||
request.tokens(),
|
||||
backupServiceCredentialGenerator,
|
||||
MAX_AGE_SECONDS);
|
||||
|
||||
final Optional<Account> account = accountsManager.getByE164(request.number());
|
||||
|
||||
// the username associated with the provided number
|
||||
final Optional<String> matchingUsername = account
|
||||
.map(Account::getUuid)
|
||||
.map(backupServiceCredentialGenerator::generateForUuid)
|
||||
.map(ExternalServiceCredentials::username);
|
||||
|
||||
return new AuthCheckResponseV3(credentials.stream().collect(Collectors.toMap(
|
||||
ExternalServiceCredentialsSelector.CredentialInfo::token,
|
||||
info -> {
|
||||
if (!info.valid()) {
|
||||
// This isn't a valid credential (could be for a different SVR service, expired, etc)
|
||||
return AuthCheckResponseV3.Result.invalid();
|
||||
}
|
||||
final String credUsername = info.credentials().username();
|
||||
|
||||
return Optionals
|
||||
// If the account exists, and the account's username matches this credential's username, return a match
|
||||
.zipWith(account, matchingUsername.filter(credUsername::equals), (a, ignored) ->
|
||||
AuthCheckResponseV3.Result.match(a.getSvr3ShareSet()))
|
||||
// Otherwise, return no-match
|
||||
.orElseGet(AuthCheckResponseV3.Result::noMatch);
|
||||
}
|
||||
)));
|
||||
}
|
||||
}
|
||||
-22
@@ -1,22 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2020 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
|
||||
public class StaleDevicesException extends Exception {
|
||||
|
||||
private final List<Byte> staleDevices;
|
||||
|
||||
public StaleDevicesException(List<Byte> staleDevices) {
|
||||
this.staleDevices = staleDevices;
|
||||
}
|
||||
|
||||
public List<Byte> getStaleDevices() {
|
||||
return staleDevices;
|
||||
}
|
||||
}
|
||||
+16
@@ -343,9 +343,14 @@ public class SubscriptionController {
|
||||
public record Error(SetSubscriptionLevelErrorResponse.Error.Type type, String message) {
|
||||
|
||||
public enum Type {
|
||||
// The requested level was invalid
|
||||
UNSUPPORTED_LEVEL,
|
||||
// The requested currency was invalid
|
||||
UNSUPPORTED_CURRENCY,
|
||||
// The card could not be charged
|
||||
PAYMENT_REQUIRES_ACTION,
|
||||
// The request arguments were invalid representing a programmer error
|
||||
INVALID_ARGUMENTS
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -391,6 +396,12 @@ public class SubscriptionController {
|
||||
SetSubscriptionLevelErrorResponse.Error.Type.PAYMENT_REQUIRES_ACTION, null))))
|
||||
.build());
|
||||
}))
|
||||
.exceptionally(ExceptionUtils.exceptionallyHandler(SubscriptionException.InvalidArguments.class, e -> {
|
||||
throw new BadRequestException(Response.status(Response.Status.BAD_REQUEST)
|
||||
.entity(new SetSubscriptionLevelErrorResponse(List.of(new SetSubscriptionLevelErrorResponse.Error(
|
||||
SetSubscriptionLevelErrorResponse.Error.Type.INVALID_ARGUMENTS, e.getMessage()))))
|
||||
.build());
|
||||
}))
|
||||
.thenApply(unused -> Response.ok(new SetSubscriptionLevelSuccessResponse(level)).build());
|
||||
}
|
||||
|
||||
@@ -701,6 +712,11 @@ public class SubscriptionController {
|
||||
// a missing customer ID indicates the client made requests out of order,
|
||||
// and needs to call create_payment_method to create a customer for the given payment method
|
||||
new ClientErrorException(Status.CONFLICT)))
|
||||
.exceptionally(ExceptionUtils.exceptionallyHandler(SubscriptionException.InvalidArguments.class, e -> {
|
||||
// Here, invalid arguments must mean that the client has made requests out of order, and needs to finish
|
||||
// setting up the paymentMethod first
|
||||
throw new ClientErrorException(Status.CONFLICT);
|
||||
}))
|
||||
.thenApply(customer -> Response.ok().build());
|
||||
}
|
||||
|
||||
|
||||
+126
-15
@@ -15,6 +15,13 @@ import io.grpc.StatusRuntimeException;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.enums.ParameterIn;
|
||||
import io.swagger.v3.oas.annotations.headers.Header;
|
||||
import io.swagger.v3.oas.annotations.media.Content;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.ws.rs.BadRequestException;
|
||||
@@ -68,6 +75,7 @@ import org.whispersystems.textsecuregcm.entities.VerificationCodeRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.VerificationSessionResponse;
|
||||
import org.whispersystems.textsecuregcm.filters.RemoteAddressFilter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.mappers.RegistrationServiceSenderExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotification;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
|
||||
@@ -83,9 +91,11 @@ import org.whispersystems.textsecuregcm.spam.RegistrationFraudChecker;
|
||||
import org.whispersystems.textsecuregcm.spam.RegistrationFraudChecker.VerificationCheck;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
|
||||
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.VerificationSessionManager;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.ObsoletePhoneNumberFormatException;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
@@ -116,6 +126,7 @@ public class VerificationController {
|
||||
private final PushNotificationManager pushNotificationManager;
|
||||
private final RegistrationCaptchaManager registrationCaptchaManager;
|
||||
private final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager;
|
||||
private final PhoneNumberIdentifiers phoneNumberIdentifiers;
|
||||
private final RateLimiters rateLimiters;
|
||||
private final AccountsManager accountsManager;
|
||||
private final RegistrationFraudChecker registrationFraudChecker;
|
||||
@@ -127,6 +138,7 @@ public class VerificationController {
|
||||
final PushNotificationManager pushNotificationManager,
|
||||
final RegistrationCaptchaManager registrationCaptchaManager,
|
||||
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager,
|
||||
final PhoneNumberIdentifiers phoneNumberIdentifiers,
|
||||
final RateLimiters rateLimiters,
|
||||
final AccountsManager accountsManager,
|
||||
final RegistrationFraudChecker registrationFraudChecker,
|
||||
@@ -137,6 +149,7 @@ public class VerificationController {
|
||||
this.pushNotificationManager = pushNotificationManager;
|
||||
this.registrationCaptchaManager = registrationCaptchaManager;
|
||||
this.registrationRecoveryPasswordsManager = registrationRecoveryPasswordsManager;
|
||||
this.phoneNumberIdentifiers = phoneNumberIdentifiers;
|
||||
this.rateLimiters = rateLimiters;
|
||||
this.accountsManager = accountsManager;
|
||||
this.registrationFraudChecker = registrationFraudChecker;
|
||||
@@ -148,22 +161,37 @@ public class VerificationController {
|
||||
@Path("/session")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public VerificationSessionResponse createSession(@NotNull @Valid CreateVerificationSessionRequest request)
|
||||
throws RateLimitExceededException {
|
||||
@Operation(
|
||||
summary = "Creates a new verification session for a specific phone number",
|
||||
description = """
|
||||
Initiates a session to be able to verify the phone number for account registration. Check the response and
|
||||
submit requested information at PATCH /session/{sessionId}
|
||||
""")
|
||||
@ApiResponse(responseCode = "200", description = "The verification session was created successfully", useReturnTypeSchema = true)
|
||||
@ApiResponse(responseCode = "422", description = "The request did not pass validation")
|
||||
@ApiResponse(responseCode = "429", description = "Too many attempts", headers = @Header(
|
||||
name = "Retry-After",
|
||||
description = "If present, an positive integer indicating the number of seconds before a subsequent attempt could succeed",
|
||||
schema = @Schema(implementation = Integer.class)))
|
||||
public VerificationSessionResponse createSession(@NotNull @Valid final CreateVerificationSessionRequest request,
|
||||
@Context final ContainerRequestContext requestContext)
|
||||
throws RateLimitExceededException, ObsoletePhoneNumberFormatException {
|
||||
|
||||
final Pair<String, PushNotification.TokenType> pushTokenAndType = validateAndExtractPushToken(
|
||||
request.getUpdateVerificationSessionRequest());
|
||||
|
||||
final Phonenumber.PhoneNumber phoneNumber;
|
||||
try {
|
||||
phoneNumber = PhoneNumberUtil.getInstance().parse(request.getNumber(), null);
|
||||
phoneNumber = Util.canonicalizePhoneNumber(PhoneNumberUtil.getInstance().parse(request.getNumber(), null));
|
||||
} catch (final NumberParseException e) {
|
||||
throw new ServerErrorException("could not parse already validated number", Response.Status.INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
|
||||
final RegistrationServiceSession registrationServiceSession;
|
||||
try {
|
||||
registrationServiceSession = registrationServiceClient.createRegistrationSession(phoneNumber,
|
||||
final String sourceHost = (String) requestContext.getProperty(RemoteAddressFilter.REMOTE_ADDRESS_ATTRIBUTE_NAME);
|
||||
|
||||
registrationServiceSession = registrationServiceClient.createRegistrationSession(phoneNumber, sourceHost,
|
||||
accountsManager.getByE164(request.getNumber()).isPresent(),
|
||||
REGISTRATION_RPC_TIMEOUT).join();
|
||||
} catch (final CancellationException e) {
|
||||
@@ -196,12 +224,28 @@ public class VerificationController {
|
||||
@Path("/session/{sessionId}")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Operation(
|
||||
summary = "Update a registration verification session",
|
||||
description = """
|
||||
Updates the session with requested information like an answer to a push challenge or captcha.
|
||||
If `requestedInformation` in the response is empty, and `allowedToRequestCode` is `true`, proceed to call
|
||||
`POST /session/{sessionId}/code`. If `requestedInformation` is empty and `allowedToRequestCode` is `false`,
|
||||
then the caller must create a new verification session.
|
||||
""")
|
||||
@ApiResponse(responseCode = "200", description = "Session was updated successfully with the information provided", useReturnTypeSchema = true)
|
||||
@ApiResponse(responseCode = "403", description = "The information provided was not accepted (e.g push challenge or captcha verification failed)")
|
||||
@ApiResponse(responseCode = "422", description = "The request did not pass validation")
|
||||
@ApiResponse(responseCode = "429", description = "Too many attempts",
|
||||
content = @Content(schema = @Schema(implementation = VerificationSessionResponse.class)),
|
||||
headers = @Header(
|
||||
name = "Retry-After",
|
||||
description = "If present, an positive integer indicating the number of seconds before a subsequent attempt could succeed",
|
||||
schema = @Schema(implementation = Integer.class)))
|
||||
public VerificationSessionResponse updateSession(
|
||||
@PathParam("sessionId") final String encodedSessionId,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
|
||||
@Context ContainerRequestContext requestContext,
|
||||
@NotNull @Valid final UpdateVerificationSessionRequest updateVerificationSessionRequest,
|
||||
@Context ContainerRequestContext context) {
|
||||
@Context final ContainerRequestContext requestContext,
|
||||
@NotNull @Valid final UpdateVerificationSessionRequest updateVerificationSessionRequest) {
|
||||
|
||||
final String sourceHost = (String) requestContext.getProperty(RemoteAddressFilter.REMOTE_ADDRESS_ATTRIBUTE_NAME);
|
||||
|
||||
@@ -212,7 +256,7 @@ public class VerificationController {
|
||||
VerificationSession verificationSession = retrieveVerificationSession(registrationServiceSession);
|
||||
|
||||
final VerificationCheck verificationCheck = registrationFraudChecker.checkVerificationAttempt(
|
||||
context,
|
||||
requestContext,
|
||||
verificationSession,
|
||||
registrationServiceSession.number(),
|
||||
updateVerificationSessionRequest);
|
||||
@@ -429,6 +473,15 @@ public class VerificationController {
|
||||
@GET
|
||||
@Path("/session/{sessionId}")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Operation(
|
||||
summary = "Get a registration verification session",
|
||||
description = """
|
||||
Retrieve metadata of the registration verification session with the specified ID
|
||||
""")
|
||||
@ApiResponse(responseCode = "200", description = "Session was retrieved successfully", useReturnTypeSchema = true)
|
||||
@ApiResponse(responseCode = "400", description = "Invalid session ID")
|
||||
@ApiResponse(responseCode = "404", description = "Session with the specified ID could not be found")
|
||||
@ApiResponse(responseCode = "422", description = "Malformed session ID encoding")
|
||||
public VerificationSessionResponse getSession(@PathParam("sessionId") final String encodedSessionId) {
|
||||
|
||||
final RegistrationServiceSession registrationServiceSession = retrieveRegistrationServiceSession(encodedSessionId);
|
||||
@@ -441,10 +494,45 @@ public class VerificationController {
|
||||
@Path("/session/{sessionId}/code")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Operation(
|
||||
summary = "Request a verification code",
|
||||
description = """
|
||||
Sends a verification code to the phone number associated with the specified session via SMS or phone call.
|
||||
This endpoint can only be called when the session metadata includes "allowedToRequestCode = true"
|
||||
""")
|
||||
@ApiResponse(responseCode = "200", description = "Verification code was successfully sent", useReturnTypeSchema = true)
|
||||
@ApiResponse(responseCode = "400", description = "Invalid session ID")
|
||||
@ApiResponse(responseCode = "404", description = "Session with the specified ID could not be found")
|
||||
@ApiResponse(responseCode = "409", description = "The session is already verified or not in a state to request a code because requested information hasn't been provided yet",
|
||||
content = @Content(schema = @Schema(implementation = VerificationSessionResponse.class)))
|
||||
@ApiResponse(responseCode = "418", description = "The request to send a verification code with the given transport could not be fulfilled, but may succeed with a different transport",
|
||||
content = @Content(schema = @Schema(implementation = VerificationSessionResponse.class)))
|
||||
@ApiResponse(responseCode = "422", description = "Request did not pass validation")
|
||||
@ApiResponse(responseCode = "429", description = """
|
||||
Too may attempts; the caller is not permitted to send a verification code via the requested channel at this time
|
||||
and may need to wait before trying again; if the session metadata does not specify a time at which the caller may
|
||||
try again, then the caller has exhausted their permitted attempts and must either try a different transport or
|
||||
create a new verification session.
|
||||
""",
|
||||
content = @Content(schema = @Schema(implementation = VerificationSessionResponse.class)),
|
||||
headers = @Header(
|
||||
name = "Retry-After",
|
||||
description = "If present, an positive integer indicating the number of seconds before a subsequent attempt could succeed",
|
||||
schema = @Schema(implementation = Integer.class)
|
||||
))
|
||||
@ApiResponse(responseCode = "440", description = """
|
||||
The attempt to send a verification code failed because an external service (e.g. the SMS provider) refused to
|
||||
deliver the code. This may be a temporary or permanent failure, as indicated in the response body. If temporary,
|
||||
clients may try again after a reasonable delay. If permanent, clients should not retry the request and should
|
||||
communicate the permanent failure to the end user. Permanent failures may result in the server disallowing all
|
||||
future attempts to request or submit verification codes (since those attempts would be all but guaranteed to fail).
|
||||
""",
|
||||
content = @Content(schema = @Schema(implementation = RegistrationServiceSenderExceptionMapper.SendVerificationCodeFailureResponse.class)))
|
||||
public VerificationSessionResponse requestVerificationCode(@PathParam("sessionId") final String encodedSessionId,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
|
||||
@HeaderParam(HttpHeaders.ACCEPT_LANGUAGE) Optional<String> acceptLanguage,
|
||||
@NotNull @Valid VerificationCodeRequest verificationCodeRequest) throws Throwable {
|
||||
@Parameter(in = ParameterIn.HEADER, description = "Ordered list of languages in which the client prefers to receive SMS or voice verification messages") @HeaderParam(HttpHeaders.ACCEPT_LANGUAGE)
|
||||
final Optional<String> acceptLanguage,
|
||||
@NotNull @Valid final VerificationCodeRequest verificationCodeRequest) throws Throwable {
|
||||
|
||||
final RegistrationServiceSession registrationServiceSession = retrieveRegistrationServiceSession(encodedSessionId);
|
||||
final VerificationSession verificationSession = retrieveVerificationSession(registrationServiceSession);
|
||||
@@ -546,8 +634,31 @@ public class VerificationController {
|
||||
@Path("/session/{sessionId}/code")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Operation(
|
||||
summary = "Submit a verification code",
|
||||
description = """
|
||||
Submits a verification code received via SMS or voice for verification
|
||||
""")
|
||||
@ApiResponse(responseCode = "200", description = """
|
||||
The request to check a verification code was processed (though the submitted code may not be the correct code);
|
||||
the session metadata will indicate whether the submitted code was correct
|
||||
""", useReturnTypeSchema = true)
|
||||
@ApiResponse(responseCode = "400", description = "Invalid session ID or verification code")
|
||||
@ApiResponse(responseCode = "404", description = "Session with the specified ID could not be found")
|
||||
@ApiResponse(responseCode = "409", description = "The session is already verified or no code has been requested yet for this session",
|
||||
content = @Content(schema = @Schema(implementation = VerificationSessionResponse.class)))
|
||||
@ApiResponse(responseCode = "429", description = """
|
||||
Too many attempts; the caller is not permitted to submit a verification code at this time and may need to wait
|
||||
before trying again; if the session metadata does not specify a time at which the caller may try again, then the
|
||||
caller has exhausted their permitted attempts and must create a new verification session.
|
||||
""",
|
||||
content = @Content(schema = @Schema(implementation = VerificationSessionResponse.class)),
|
||||
headers = @Header(
|
||||
name = "Retry-After",
|
||||
description = "If present, an positive integer indicating the number of seconds before a subsequent attempt could succeed",
|
||||
schema = @Schema(implementation = Integer.class)))
|
||||
public VerificationSessionResponse verifyCode(@PathParam("sessionId") final String encodedSessionId,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) String userAgent,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
|
||||
@NotNull @Valid final SubmitVerificationCodeRequest submitVerificationCodeRequest)
|
||||
throws RateLimitExceededException {
|
||||
|
||||
@@ -598,7 +709,7 @@ public class VerificationController {
|
||||
}
|
||||
|
||||
if (resultSession.verified()) {
|
||||
registrationRecoveryPasswordsManager.removeForNumber(registrationServiceSession.number());
|
||||
registrationRecoveryPasswordsManager.remove(phoneNumberIdentifiers.getPhoneNumberIdentifier(registrationServiceSession.number()).join());
|
||||
}
|
||||
|
||||
Metrics.counter(VERIFIED_COUNTER_NAME, Tags.of(
|
||||
@@ -626,8 +737,8 @@ public class VerificationController {
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws ClientErrorException with {@code 422} status if the ID cannot be decoded
|
||||
* @throws javax.ws.rs.NotFoundException if the ID cannot be found
|
||||
* @throws ClientErrorException with {@code 422} status if the ID cannot be decoded
|
||||
* @throws NotFoundException if the ID cannot be found
|
||||
*/
|
||||
private RegistrationServiceSession retrieveRegistrationServiceSession(final String encodedSessionId) {
|
||||
final byte[] sessionId;
|
||||
@@ -644,7 +755,7 @@ public class VerificationController {
|
||||
.orElseThrow(NotFoundException::new);
|
||||
|
||||
if (registrationServiceSession.verified()) {
|
||||
registrationRecoveryPasswordsManager.removeForNumber(registrationServiceSession.number());
|
||||
registrationRecoveryPasswordsManager.remove(phoneNumberIdentifiers.getPhoneNumberIdentifier(registrationServiceSession.number()).join());
|
||||
}
|
||||
|
||||
return registrationServiceSession;
|
||||
|
||||
+23
-25
@@ -5,8 +5,8 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.currency;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import java.io.IOException;
|
||||
import java.math.BigDecimal;
|
||||
@@ -14,26 +14,23 @@ import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
|
||||
public class CoinMarketCapClient {
|
||||
public class CoinGeckoClient {
|
||||
|
||||
private final HttpClient httpClient;
|
||||
private final String apiKey;
|
||||
private final Map<String, Integer> currencyIdsBySymbol;
|
||||
private final Map<String, String> currencyIdsBySymbol;
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(CoinMarketCapClient.class);
|
||||
private static final Logger logger = LoggerFactory.getLogger(CoinGeckoClient.class);
|
||||
|
||||
record CoinMarketCapResponse(@JsonProperty("data") PriceConversionResponse priceConversionResponse) {};
|
||||
private static final TypeReference<Map<String, Map<String, BigDecimal>>> RESPONSE_TYPE = new TypeReference<>() {};
|
||||
|
||||
record PriceConversionResponse(int id, String symbol, Map<String, PriceConversionQuote> quote) {};
|
||||
|
||||
record PriceConversionQuote(BigDecimal price) {};
|
||||
|
||||
public CoinMarketCapClient(final HttpClient httpClient, final String apiKey, final Map<String, Integer> currencyIdsBySymbol) {
|
||||
public CoinGeckoClient(final HttpClient httpClient, final String apiKey, final Map<String, String> currencyIdsBySymbol) {
|
||||
this.httpClient = httpClient;
|
||||
this.apiKey = apiKey;
|
||||
this.currencyIdsBySymbol = currencyIdsBySymbol;
|
||||
@@ -45,40 +42,41 @@ public class CoinMarketCapClient {
|
||||
}
|
||||
|
||||
final URI quoteUri = URI.create(
|
||||
String.format("https://pro-api.coinmarketcap.com/v2/tools/price-conversion?amount=1&id=%d&convert=%s",
|
||||
currencyIdsBySymbol.get(currency), base));
|
||||
String.format("https://pro-api.coingecko.com/api/v3/simple/price?ids=%s&vs_currencies=%s",
|
||||
currencyIdsBySymbol.get(currency), base.toLowerCase(Locale.ROOT)));
|
||||
|
||||
try {
|
||||
final HttpResponse<String> response = httpClient.send(HttpRequest.newBuilder()
|
||||
.GET()
|
||||
.uri(quoteUri)
|
||||
.header("X-CMC_PRO_API_KEY", apiKey)
|
||||
.build(),
|
||||
HttpResponse.BodyHandlers.ofString());
|
||||
.GET()
|
||||
.uri(quoteUri)
|
||||
.header("Accept", "application/json")
|
||||
.header("x-cg-pro-api-key", apiKey)
|
||||
.build(),
|
||||
HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
if (response.statusCode() < 200 || response.statusCode() >= 300) {
|
||||
logger.warn("CoinMarketCapRequest failed with response: {}", response);
|
||||
throw new IOException("CoinMarketCap request failed with status code " + response.statusCode());
|
||||
logger.warn("CoinGecko request failed with response: {}", response);
|
||||
throw new IOException("CoinGecko request failed with status code " + response.statusCode());
|
||||
}
|
||||
|
||||
return extractConversionRate(parseResponse(response.body()), base);
|
||||
return extractConversionRate(parseResponse(response.body()).get(currencyIdsBySymbol.get(currency)), base.toLowerCase(Locale.ROOT));
|
||||
} catch (final InterruptedException e) {
|
||||
throw new IOException("Interrupted while waiting for a response", e);
|
||||
}
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static CoinMarketCapResponse parseResponse(final String responseJson) throws JsonProcessingException {
|
||||
return SystemMapper.jsonMapper().readValue(responseJson, CoinMarketCapResponse.class);
|
||||
static Map<String, Map<String,BigDecimal>> parseResponse(final String responseJson) throws JsonProcessingException {
|
||||
return SystemMapper.jsonMapper().readValue(responseJson, RESPONSE_TYPE);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static BigDecimal extractConversionRate(final CoinMarketCapResponse response, final String destinationCurrency)
|
||||
static BigDecimal extractConversionRate(final Map<String,BigDecimal> response, final String destinationCurrency)
|
||||
throws IOException {
|
||||
if (!response.priceConversionResponse().quote.containsKey(destinationCurrency)) {
|
||||
if (!response.containsKey(destinationCurrency)) {
|
||||
throw new IOException("Response does not contain conversion rate for " + destinationCurrency);
|
||||
}
|
||||
|
||||
return response.priceConversionResponse().quote.get(destinationCurrency).price();
|
||||
return response.get(destinationCurrency);
|
||||
}
|
||||
}
|
||||
+22
-22
@@ -36,16 +36,16 @@ public class CurrencyConversionManager implements Managed {
|
||||
@VisibleForTesting
|
||||
static final Duration FIXER_REFRESH_INTERVAL = Duration.ofHours(2);
|
||||
|
||||
private static final Duration COIN_MARKET_CAP_REFRESH_INTERVAL = Duration.ofMinutes(5);
|
||||
private static final Duration COIN_GECKO_CAP_REFRESH_INTERVAL = Duration.ofMinutes(5);
|
||||
|
||||
@VisibleForTesting
|
||||
static final String COIN_MARKET_CAP_SHARED_CACHE_CURRENT_KEY = "CurrencyConversionManager::CoinMarketCapCacheCurrent";
|
||||
static final String COIN_GECKO_CAP_SHARED_CACHE_CURRENT_KEY = "CurrencyConversionManager::CoinGeckoCacheCurrent";
|
||||
|
||||
private static final String COIN_MARKET_CAP_SHARED_CACHE_DATA_KEY = "CurrencyConversionManager::CoinMarketCapCacheData";
|
||||
private static final String COIN_GECKO_SHARED_CACHE_DATA_KEY = "CurrencyConversionManager::CoinGeckoCacheData";
|
||||
|
||||
private final FixerClient fixerClient;
|
||||
|
||||
private final CoinMarketCapClient coinMarketCapClient;
|
||||
private final CoinGeckoClient coinGeckoClient;
|
||||
|
||||
private final FaultTolerantRedisClusterClient cacheCluster;
|
||||
|
||||
@@ -61,18 +61,18 @@ public class CurrencyConversionManager implements Managed {
|
||||
|
||||
private Map<String, BigDecimal> cachedFixerValues;
|
||||
|
||||
private Map<String, BigDecimal> cachedCoinMarketCapValues;
|
||||
private Map<String, BigDecimal> cachedCoinGeckoValues;
|
||||
|
||||
|
||||
public CurrencyConversionManager(
|
||||
final FixerClient fixerClient,
|
||||
final CoinMarketCapClient coinMarketCapClient,
|
||||
final CoinGeckoClient coinGeckoClient,
|
||||
final FaultTolerantRedisClusterClient cacheCluster,
|
||||
final List<String> currencies,
|
||||
final ScheduledExecutorService executor,
|
||||
final Clock clock) {
|
||||
this.fixerClient = fixerClient;
|
||||
this.coinMarketCapClient = coinMarketCapClient;
|
||||
this.coinGeckoClient = coinGeckoClient;
|
||||
this.cacheCluster = cacheCluster;
|
||||
this.currencies = currencies;
|
||||
this.executor = executor;
|
||||
@@ -102,49 +102,49 @@ public class CurrencyConversionManager implements Managed {
|
||||
}
|
||||
|
||||
{
|
||||
final Map<String, BigDecimal> coinMarketCapValuesFromSharedCache = cacheCluster.withCluster(connection -> {
|
||||
final Map<String, BigDecimal> CoinGeckoValuesFromSharedCache = cacheCluster.withCluster(connection -> {
|
||||
final Map<String, BigDecimal> parsedSharedCacheData = new HashMap<>();
|
||||
|
||||
connection.sync().hgetall(COIN_MARKET_CAP_SHARED_CACHE_DATA_KEY).forEach((currency, conversionRate) ->
|
||||
connection.sync().hgetall(COIN_GECKO_SHARED_CACHE_DATA_KEY).forEach((currency, conversionRate) ->
|
||||
parsedSharedCacheData.put(currency, new BigDecimal(conversionRate)));
|
||||
|
||||
return parsedSharedCacheData;
|
||||
});
|
||||
|
||||
if (coinMarketCapValuesFromSharedCache != null && !coinMarketCapValuesFromSharedCache.isEmpty()) {
|
||||
cachedCoinMarketCapValues = coinMarketCapValuesFromSharedCache;
|
||||
if (CoinGeckoValuesFromSharedCache != null && !CoinGeckoValuesFromSharedCache.isEmpty()) {
|
||||
cachedCoinGeckoValues = CoinGeckoValuesFromSharedCache;
|
||||
}
|
||||
}
|
||||
|
||||
final boolean shouldUpdateSharedCache = cacheCluster.withCluster(connection ->
|
||||
"OK".equals(connection.sync().set(COIN_MARKET_CAP_SHARED_CACHE_CURRENT_KEY,
|
||||
"OK".equals(connection.sync().set(COIN_GECKO_CAP_SHARED_CACHE_CURRENT_KEY,
|
||||
"true",
|
||||
SetArgs.Builder.nx().ex(COIN_MARKET_CAP_REFRESH_INTERVAL))));
|
||||
SetArgs.Builder.nx().ex(COIN_GECKO_CAP_REFRESH_INTERVAL))));
|
||||
|
||||
if (shouldUpdateSharedCache || cachedCoinMarketCapValues == null) {
|
||||
final Map<String, BigDecimal> conversionRatesFromCoinMarketCap = new HashMap<>(currencies.size());
|
||||
if (shouldUpdateSharedCache || cachedCoinGeckoValues == null) {
|
||||
final Map<String, BigDecimal> conversionRatesFromCoinGecko = new HashMap<>(currencies.size());
|
||||
|
||||
for (final String currency : currencies) {
|
||||
conversionRatesFromCoinMarketCap.put(currency, coinMarketCapClient.getSpotPrice(currency, "USD"));
|
||||
conversionRatesFromCoinGecko.put(currency, coinGeckoClient.getSpotPrice(currency, "USD"));
|
||||
}
|
||||
|
||||
cachedCoinMarketCapValues = conversionRatesFromCoinMarketCap;
|
||||
cachedCoinGeckoValues = conversionRatesFromCoinGecko;
|
||||
|
||||
if (shouldUpdateSharedCache) {
|
||||
cacheCluster.useCluster(connection -> {
|
||||
final Map<String, String> sharedCoinMarketCapValues = new HashMap<>();
|
||||
final Map<String, String> sharedCoinGeckoValues = new HashMap<>();
|
||||
|
||||
cachedCoinMarketCapValues.forEach((currency, conversionRate) ->
|
||||
sharedCoinMarketCapValues.put(currency, conversionRate.toString()));
|
||||
cachedCoinGeckoValues.forEach((currency, conversionRate) ->
|
||||
sharedCoinGeckoValues.put(currency, conversionRate.toString()));
|
||||
|
||||
connection.sync().hset(COIN_MARKET_CAP_SHARED_CACHE_DATA_KEY, sharedCoinMarketCapValues);
|
||||
connection.sync().hset(COIN_GECKO_SHARED_CACHE_DATA_KEY, sharedCoinGeckoValues);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
List<CurrencyConversionEntity> entities = new LinkedList<>();
|
||||
|
||||
for (Map.Entry<String, BigDecimal> currency : cachedCoinMarketCapValues.entrySet()) {
|
||||
for (Map.Entry<String, BigDecimal> currency : cachedCoinGeckoValues.entrySet()) {
|
||||
BigDecimal usdValue = stripTrailingZerosAfterDecimal(currency.getValue());
|
||||
|
||||
Map<String, BigDecimal> values = new HashMap<>();
|
||||
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonUnwrapped;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
|
||||
// Note, this class cannot be converted into a record because @JsonUnwrapped does not work with records until 2.19. We are on 2.18 until Dropwizard’s BOM updates.
|
||||
// https://github.com/FasterXML/jackson-databind/issues/1467
|
||||
public class AccountCreationResponse {
|
||||
|
||||
@JsonUnwrapped
|
||||
private AccountIdentityResponse identityResponse;
|
||||
|
||||
@Schema(description = "If true, there was an existing account registered for this number")
|
||||
private boolean reregistration;
|
||||
|
||||
public AccountCreationResponse() {
|
||||
}
|
||||
|
||||
public AccountCreationResponse(AccountIdentityResponse identityResponse, boolean reregistration) {
|
||||
this.identityResponse = identityResponse;
|
||||
this.reregistration = reregistration;
|
||||
}
|
||||
|
||||
public boolean isReregistration() {
|
||||
return reregistration;
|
||||
}
|
||||
}
|
||||
+4
-1
@@ -31,5 +31,8 @@ public record AccountIdentityResponse(
|
||||
@Nullable UUID usernameLinkHandle,
|
||||
|
||||
@Schema(description="whether any of this account's devices support storage")
|
||||
boolean storageCapable) {
|
||||
boolean storageCapable,
|
||||
|
||||
@Schema(description = "entitlements for this account and their current expirations")
|
||||
Entitlements entitlements) {
|
||||
}
|
||||
+1
-1
@@ -14,5 +14,5 @@ public record AccountMismatchedDevices(@JsonSerialize(using = ServiceIdentifierA
|
||||
@JsonDeserialize(using = ServiceIdentifierAdapter.ServiceIdentifierDeserializer.class)
|
||||
ServiceIdentifier uuid,
|
||||
|
||||
MismatchedDevices devices) {
|
||||
MismatchedDevicesResponse devices) {
|
||||
}
|
||||
+1
-1
@@ -14,5 +14,5 @@ public record AccountStaleDevices(@JsonSerialize(using = ServiceIdentifierAdapte
|
||||
@JsonDeserialize(using = ServiceIdentifierAdapter.ServiceIdentifierDeserializer.class)
|
||||
ServiceIdentifier uuid,
|
||||
|
||||
StaleDevices devices) {
|
||||
StaleDevicesResponse devices) {
|
||||
}
|
||||
+2
@@ -20,6 +20,7 @@ import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
|
||||
import org.whispersystems.textsecuregcm.util.E164;
|
||||
import org.whispersystems.textsecuregcm.util.IdentityKeyAdapter;
|
||||
import org.whispersystems.textsecuregcm.util.RegistrationIdValidator;
|
||||
|
||||
@@ -34,6 +35,7 @@ public record ChangeNumberRequest(
|
||||
Must not be combined with `sessionId`.""")
|
||||
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class) byte[] recoveryPassword,
|
||||
|
||||
@E164
|
||||
@Schema(description="the new phone number for this account")
|
||||
@NotBlank String number,
|
||||
|
||||
|
||||
+2
@@ -8,6 +8,7 @@ package org.whispersystems.textsecuregcm.entities;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.annotation.JsonUnwrapped;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import org.whispersystems.textsecuregcm.util.E164;
|
||||
@@ -16,6 +17,7 @@ import org.whispersystems.textsecuregcm.util.E164;
|
||||
// https://github.com/FasterXML/jackson-databind/issues/1497
|
||||
public final class CreateVerificationSessionRequest {
|
||||
|
||||
@Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = "The e164-formatted phone number to be verified")
|
||||
@E164
|
||||
@NotBlank
|
||||
@JsonProperty
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import org.whispersystems.textsecuregcm.util.InstantAdapter;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
|
||||
public record Entitlements(
|
||||
@Schema(description = "Active badges added via /v1/donation/redeem-receipt")
|
||||
List<BadgeEntitlement> badges,
|
||||
@Schema(description = "If present, the backup level set via /v1/archives/redeem-receipt")
|
||||
@Nullable BackupEntitlement backup) {
|
||||
|
||||
public record BadgeEntitlement(
|
||||
@Schema(description = "The badge id")
|
||||
String id,
|
||||
|
||||
@Schema(description = "When the badge expires, in number of seconds since epoch", implementation = Long.class)
|
||||
@JsonSerialize(using = InstantAdapter.EpochSecondSerializer.class)
|
||||
@JsonFormat(shape = JsonFormat.Shape.NUMBER_INT)
|
||||
@JsonProperty("expirationSeconds")
|
||||
Instant expiration,
|
||||
|
||||
@Schema(description = "Whether the badge is currently configured to be visible")
|
||||
boolean visible) {
|
||||
}
|
||||
|
||||
public record BackupEntitlement(
|
||||
@Schema(description = "The backup level of the account")
|
||||
long backupLevel,
|
||||
|
||||
@Schema(description = "When the backup entitlement expires, in number of seconds since epoch", implementation = Long.class)
|
||||
@JsonSerialize(using = InstantAdapter.EpochSecondSerializer.class)
|
||||
@JsonFormat(shape = JsonFormat.Shape.NUMBER_INT)
|
||||
@JsonProperty("expirationSeconds")
|
||||
Instant expiration) {
|
||||
}
|
||||
}
|
||||
+53
-13
@@ -4,37 +4,53 @@
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import com.google.protobuf.ByteString;
|
||||
import java.util.Base64;
|
||||
import com.webauthn4j.converter.jackson.deserializer.json.ByteArrayBase64Deserializer;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import jakarta.validation.constraints.AssertTrue;
|
||||
import javax.annotation.Nullable;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import java.util.Arrays;
|
||||
import java.util.Objects;
|
||||
|
||||
public record IncomingMessage(int type, byte destinationDeviceId, int destinationRegistrationId, String content) {
|
||||
public record IncomingMessage(int type,
|
||||
byte destinationDeviceId,
|
||||
int destinationRegistrationId,
|
||||
|
||||
@JsonDeserialize(using = ByteArrayBase64Deserializer.class)
|
||||
@NotNull
|
||||
// Note that max size is validated elsewhere in the interest of controlling responses and
|
||||
// reporting additional metrics.
|
||||
@Size(min = 1)
|
||||
byte[] content) {
|
||||
|
||||
private static final String REJECT_INVALID_ENVELOPE_TYPE_COUNTER_NAME =
|
||||
MetricsUtil.name(IncomingMessage.class, "rejectInvalidEnvelopeType");
|
||||
|
||||
public MessageProtos.Envelope toEnvelope(final ServiceIdentifier destinationIdentifier,
|
||||
@Nullable Account sourceAccount,
|
||||
@Nullable Byte sourceDeviceId,
|
||||
final long timestamp,
|
||||
final boolean story,
|
||||
final boolean ephemeral,
|
||||
final boolean urgent,
|
||||
@Nullable byte[] reportSpamToken) {
|
||||
|
||||
final MessageProtos.Envelope.Type envelopeType = MessageProtos.Envelope.Type.forNumber(type());
|
||||
|
||||
if (envelopeType == null) {
|
||||
throw new IllegalArgumentException("Bad envelope type: " + type());
|
||||
}
|
||||
|
||||
final MessageProtos.Envelope.Builder envelopeBuilder = MessageProtos.Envelope.newBuilder();
|
||||
|
||||
envelopeBuilder.setType(envelopeType)
|
||||
envelopeBuilder
|
||||
.setType(MessageProtos.Envelope.Type.forNumber(type))
|
||||
.setClientTimestamp(timestamp)
|
||||
.setServerTimestamp(System.currentTimeMillis())
|
||||
.setDestinationServiceId(destinationIdentifier.toServiceIdentifierString())
|
||||
.setStory(story)
|
||||
.setEphemeral(ephemeral)
|
||||
.setUrgent(urgent);
|
||||
|
||||
if (sourceAccount != null && sourceDeviceId != null) {
|
||||
@@ -47,10 +63,34 @@ public record IncomingMessage(int type, byte destinationDeviceId, int destinatio
|
||||
envelopeBuilder.setReportSpamToken(ByteString.copyFrom(reportSpamToken));
|
||||
}
|
||||
|
||||
if (StringUtils.isNotEmpty(content())) {
|
||||
envelopeBuilder.setContent(ByteString.copyFrom(Base64.getDecoder().decode(content())));
|
||||
}
|
||||
envelopeBuilder.setContent(ByteString.copyFrom(content()));
|
||||
|
||||
return envelopeBuilder.build();
|
||||
}
|
||||
|
||||
@AssertTrue
|
||||
public boolean isValidEnvelopeType() {
|
||||
if (type() == MessageProtos.Envelope.Type.SERVER_DELIVERY_RECEIPT_VALUE ||
|
||||
MessageProtos.Envelope.Type.forNumber(type()) == null) {
|
||||
|
||||
Metrics.counter(REJECT_INVALID_ENVELOPE_TYPE_COUNTER_NAME).increment();
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(final Object o) {
|
||||
if (!(o instanceof IncomingMessage(int otherType, byte otherDeviceId, int otherRegistrationId, byte[] otherContent)))
|
||||
return false;
|
||||
return type == otherType && destinationDeviceId == otherDeviceId
|
||||
&& destinationRegistrationId == otherRegistrationId && Objects.deepEquals(content, otherContent);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(type, destinationDeviceId, destinationRegistrationId, Arrays.hashCode(content));
|
||||
}
|
||||
}
|
||||
+21
-8
@@ -8,19 +8,28 @@ import static com.codahale.metrics.MetricRegistry.name;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonCreator;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
import org.whispersystems.textsecuregcm.controllers.MessageController;
|
||||
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
|
||||
import java.util.List;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.AssertTrue;
|
||||
import jakarta.validation.constraints.Max;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.PositiveOrZero;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import org.whispersystems.textsecuregcm.controllers.MessageController;
|
||||
|
||||
public record IncomingMessageList(@NotNull @Valid List<@NotNull IncomingMessage> messages,
|
||||
boolean online, boolean urgent, long timestamp) {
|
||||
public record IncomingMessageList(@NotNull
|
||||
@Valid
|
||||
List<@NotNull @Valid IncomingMessage> messages,
|
||||
|
||||
boolean online,
|
||||
|
||||
boolean urgent,
|
||||
|
||||
@PositiveOrZero
|
||||
@Max(MessageController.MAX_TIMESTAMP)
|
||||
long timestamp) {
|
||||
|
||||
private static final Counter REJECT_DUPLICATE_RECIPIENT_COUNTER =
|
||||
Metrics.counter(
|
||||
@@ -38,10 +47,14 @@ public record IncomingMessageList(@NotNull @Valid List<@NotNull IncomingMessage>
|
||||
|
||||
@AssertTrue
|
||||
public boolean hasNoDuplicateRecipients() {
|
||||
boolean valid = messages.stream().filter(m -> m != null).map(IncomingMessage::destinationDeviceId).distinct().count() == messages.size();
|
||||
final boolean valid = messages.stream()
|
||||
.filter(Objects::nonNull)
|
||||
.map(IncomingMessage::destinationDeviceId).distinct().count() == messages.size();
|
||||
|
||||
if (!valid) {
|
||||
REJECT_DUPLICATE_RECIPIENT_COUNTER.increment();
|
||||
}
|
||||
|
||||
return valid;
|
||||
}
|
||||
}
|
||||
+9
-15
@@ -13,7 +13,6 @@ import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Positive;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
|
||||
@@ -49,11 +48,9 @@ public record KeyTransparencyMonitorRequest(
|
||||
@Schema(description = "The aci identifier to monitor")
|
||||
AciServiceIdentifier value,
|
||||
|
||||
@Schema(description = "A list of log tree positions maintained by the client for the aci search key.")
|
||||
@Valid
|
||||
@NotNull
|
||||
@NotEmpty
|
||||
List<@Positive Long> positions,
|
||||
@Schema(description = "A log tree position maintained by the client for the aci.")
|
||||
@Positive
|
||||
long entryPosition,
|
||||
|
||||
@Schema(description = "The commitment index derived from a previous search request, encoded in standard unpadded base64")
|
||||
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
|
||||
@@ -68,11 +65,9 @@ public record KeyTransparencyMonitorRequest(
|
||||
@NotBlank
|
||||
String value,
|
||||
|
||||
@Schema(description = "A list of log tree positions maintained by the client for the e164 search key.")
|
||||
@NotNull
|
||||
@NotEmpty
|
||||
@Valid
|
||||
List<@Positive Long> positions,
|
||||
@Schema(description = "A log tree position maintained by the client for the e164.")
|
||||
@Positive
|
||||
long entryPosition,
|
||||
|
||||
@Schema(description = "The commitment index derived from a previous search request, encoded in standard unpadded base64")
|
||||
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
|
||||
@@ -91,10 +86,9 @@ public record KeyTransparencyMonitorRequest(
|
||||
@NotEmpty
|
||||
byte[] value,
|
||||
|
||||
@Schema(description = "A list of log tree positions maintained by the client for the username hash search key.")
|
||||
@NotNull
|
||||
@NotEmpty
|
||||
@Valid List<@Positive Long> positions,
|
||||
@Schema(description = "A log tree position maintained by the client for the username hash.")
|
||||
@Positive
|
||||
long entryPosition,
|
||||
|
||||
@Schema(description = "The commitment index derived from a previous search request, encoded in standard unpadded base64")
|
||||
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
|
||||
|
||||
@@ -6,6 +6,7 @@ import com.fasterxml.jackson.annotation.JsonUnwrapped;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.AssertTrue;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import java.util.Optional;
|
||||
|
||||
@@ -13,6 +14,7 @@ public record LinkDeviceRequest(@Schema(requiredMode = Schema.RequiredMode.REQUI
|
||||
The verification code associated with this device. Must match the verification code
|
||||
provided by the server when provisioning this device.
|
||||
""")
|
||||
@NotBlank
|
||||
String verificationCode,
|
||||
|
||||
@Valid
|
||||
|
||||
-20
@@ -1,20 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2020 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public record MismatchedDevices(@JsonProperty
|
||||
@Schema(description = "Devices present on the account but absent in the request")
|
||||
List<Byte> missingDevices,
|
||||
|
||||
@JsonProperty
|
||||
@Schema(description = "Devices absent on the request but present in the account")
|
||||
List<Byte> extraDevices) {
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
/*
|
||||
* Copyright 2013-2020 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
public record MismatchedDevicesResponse(@JsonProperty
|
||||
@Schema(description = "Devices present on the account but absent in the request")
|
||||
Set<Byte> missingDevices,
|
||||
|
||||
@JsonProperty
|
||||
@Schema(description = "Devices absent on the request but present in the account")
|
||||
Set<Byte> extraDevices) {
|
||||
}
|
||||
+3
-3
@@ -6,6 +6,7 @@
|
||||
package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import javax.annotation.Nullable;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
|
||||
|
||||
@Schema(description = """
|
||||
@@ -16,7 +17,6 @@ public record RegistrationLockFailure(
|
||||
@Schema(description = "Time remaining in milliseconds before the existing registration lock expires")
|
||||
long timeRemaining,
|
||||
@Schema(description = "Credentials that can be used with SVR2")
|
||||
ExternalServiceCredentials svr2Credentials,
|
||||
@Schema(description = "Credentials that can be used with SVR3")
|
||||
Svr3Credentials svr3Credentials) {
|
||||
@Nullable
|
||||
ExternalServiceCredentials svr2Credentials) {
|
||||
}
|
||||
+5
-2
@@ -9,8 +9,11 @@ import java.util.Base64;
|
||||
import javax.annotation.Nullable;
|
||||
import org.signal.registration.rpc.RegistrationSessionMetadata;
|
||||
|
||||
public record RegistrationServiceSession(byte[] id, String number, boolean verified,
|
||||
@Nullable Long nextSms, @Nullable Long nextVoiceCall,
|
||||
public record RegistrationServiceSession(byte[] id,
|
||||
String number,
|
||||
boolean verified,
|
||||
@Nullable Long nextSms,
|
||||
@Nullable Long nextVoiceCall,
|
||||
@Nullable Long nextVerificationAttempt,
|
||||
long expiration) {
|
||||
|
||||
|
||||
+4
-3
@@ -8,6 +8,7 @@ package org.whispersystems.textsecuregcm.entities;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import org.whispersystems.textsecuregcm.util.ValidBase64URLString;
|
||||
|
||||
public record RemoteAttachment(
|
||||
@@ -17,6 +18,6 @@ public record RemoteAttachment(
|
||||
|
||||
@NotBlank
|
||||
@ValidBase64URLString
|
||||
@Schema(description = "The attachment key")
|
||||
String key) {
|
||||
}
|
||||
@Size(max = 64)
|
||||
@Schema(description = "The attachment key", maxLength = 64)
|
||||
String key) implements TransferArchiveResult {}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
|
||||
@Schema(description = "Indicates an attachment failed to upload")
|
||||
public record RemoteAttachmentError(
|
||||
@Schema(description = "The type of error encountered")
|
||||
@Valid @NotNull ErrorType error)
|
||||
implements TransferArchiveResult {
|
||||
|
||||
public enum ErrorType {
|
||||
RELINK_REQUESTED,
|
||||
CONTINUE_WITHOUT_UPLOAD;
|
||||
}
|
||||
}
|
||||
+13
-1
@@ -5,8 +5,13 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import javax.annotation.Nullable;
|
||||
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
|
||||
|
||||
@Schema(description = """
|
||||
Represents a request from a new device to restore account data by some method.
|
||||
@@ -14,7 +19,14 @@ import jakarta.validation.constraints.NotNull;
|
||||
public record RestoreAccountRequest(
|
||||
@NotNull
|
||||
@Schema(description = "The method by which the new device has requested account data restoration")
|
||||
Method method) {
|
||||
Method method,
|
||||
|
||||
@Schema(description = "Additional data to use to bootstrap a connection between devices, in standard unpadded base64.",
|
||||
implementation = String.class)
|
||||
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
|
||||
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
|
||||
@Size(max = 4096)
|
||||
@Nullable byte[] deviceTransferBootstrap) {
|
||||
|
||||
public enum Method {
|
||||
@Schema(description = "Restore account data from a remote message history backup")
|
||||
|
||||
+9
-7
@@ -5,16 +5,18 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
|
||||
import java.util.List;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.util.ServiceIdentifierAdapter;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
public record SendMultiRecipientMessageResponse(@JsonSerialize(contentUsing = ServiceIdentifierAdapter.ServiceIdentifierSerializer.class)
|
||||
@JsonDeserialize(contentUsing = ServiceIdentifierAdapter.ServiceIdentifierDeserializer.class)
|
||||
List<ServiceIdentifier> uuids404) {
|
||||
public record SendMultiRecipientMessageResponse(
|
||||
@Schema(description = "a list of the service identifiers in the request that do not correspond to registered Signal users; will only be present if a group send endorsement was supplied for the request")
|
||||
@JsonSerialize(contentUsing = ServiceIdentifierAdapter.ServiceIdentifierSerializer.class)
|
||||
@JsonDeserialize(contentUsing = ServiceIdentifierAdapter.ServiceIdentifierDeserializer.class)
|
||||
List<ServiceIdentifier> uuids404) {
|
||||
}
|
||||
-22
@@ -1,22 +0,0 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
|
||||
import org.whispersystems.textsecuregcm.util.ExactlySize;
|
||||
|
||||
public record SetShareSetRequest(
|
||||
@Schema(description = """
|
||||
A share-set generated by a client after storing a value in SVR3, serialized in un-padded standard base64
|
||||
""", implementation = String.class)
|
||||
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
|
||||
@NotEmpty
|
||||
@ExactlySize(SHARE_SET_SIZE)
|
||||
byte[] shareSet) {
|
||||
public static final int SHARE_SET_SIZE = 169;
|
||||
}
|
||||
+4
-4
@@ -8,9 +8,9 @@ package org.whispersystems.textsecuregcm.entities;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
public record StaleDevices(@JsonProperty
|
||||
@Schema(description = "Devices that are no longer active")
|
||||
List<Byte> staleDevices) {
|
||||
public record StaleDevicesResponse(@JsonProperty
|
||||
@Schema(description = "Devices that are no longer active")
|
||||
Set<Byte> staleDevices) {
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import javax.annotation.Nullable;
|
||||
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
|
||||
|
||||
@Schema(description = """
|
||||
A time limited external service credential that can be used to authenticate and restore from SVR3.
|
||||
""")
|
||||
public record Svr3Credentials(
|
||||
|
||||
@Schema(description = "The credential username")
|
||||
String username,
|
||||
|
||||
@Schema(description = "The credential password")
|
||||
String password,
|
||||
|
||||
@Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED, description = """
|
||||
If present, a shareSet previously stored for this account via /v3/backups/shareSet. Required to restore a value
|
||||
from SVR3. Encoded in standard un-padded base64.
|
||||
""", implementation = String.class)
|
||||
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
|
||||
@Nullable byte[] shareSet) {}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonSubTypes;
|
||||
import com.fasterxml.jackson.annotation.JsonTypeInfo;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
|
||||
@JsonTypeInfo(use = JsonTypeInfo.Id.DEDUCTION)
|
||||
@JsonSubTypes({
|
||||
@JsonSubTypes.Type(value = RemoteAttachment.class, name = "success"),
|
||||
@JsonSubTypes.Type(value = RemoteAttachmentError.class, name = "error"),
|
||||
})
|
||||
public sealed interface TransferArchiveResult permits RemoteAttachment, RemoteAttachmentError {}
|
||||
+16
-11
@@ -9,19 +9,24 @@ import io.swagger.v3.oas.annotations.media.Schema;
|
||||
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 org.whispersystems.textsecuregcm.storage.Device;
|
||||
|
||||
public record TransferArchiveUploadedRequest(@Min(1)
|
||||
@Max(Device.MAXIMUM_DEVICE_ID)
|
||||
@Schema(description = "The ID of the device for which the transfer archive has been prepared")
|
||||
byte destinationDeviceId,
|
||||
public record TransferArchiveUploadedRequest(
|
||||
@Min(1)
|
||||
@Max(Device.MAXIMUM_DEVICE_ID)
|
||||
@Schema(description = "The ID of the device for which the transfer archive has been prepared")
|
||||
byte destinationDeviceId,
|
||||
|
||||
@Positive
|
||||
@Schema(description = "The timestamp, in milliseconds since the epoch, at which the destination device was created")
|
||||
long destinationDeviceCreated,
|
||||
@Positive
|
||||
@Schema(description = "The timestamp, in milliseconds since the epoch, at which the destination device was created")
|
||||
long destinationDeviceCreated,
|
||||
|
||||
@Schema(description = "The location of the transfer archive")
|
||||
@Valid
|
||||
RemoteAttachment transferArchive) {
|
||||
}
|
||||
@NotNull
|
||||
@Valid
|
||||
@Schema(description = """
|
||||
The location of the transfer archive if the archive was successfully uploaded, otherwise a error indicating that
|
||||
the upload has failed and the destination device should stop waiting
|
||||
""", oneOf = {RemoteAttachment.class, RemoteAttachmentError.class})
|
||||
TransferArchiveResult transferArchive) {}
|
||||
+18
-6
@@ -7,14 +7,26 @@ package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import javax.annotation.Nullable;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotification;
|
||||
|
||||
public record UpdateVerificationSessionRequest(@Nullable String pushToken,
|
||||
@Nullable PushTokenType pushTokenType,
|
||||
@Nullable String pushChallenge,
|
||||
@Nullable String captcha,
|
||||
@Nullable String mcc,
|
||||
@Nullable String mnc) {
|
||||
public record UpdateVerificationSessionRequest(
|
||||
@Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED, description = "The APNs or FCM device token to which a push challenge can be sent")
|
||||
@Nullable String pushToken,
|
||||
@Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED, description = "The type of push token")
|
||||
@Nullable PushTokenType pushTokenType,
|
||||
|
||||
@Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED, description = "Value received by the device in the push challenge")
|
||||
@Nullable String pushChallenge,
|
||||
|
||||
@Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED, description = "Captcha token returned after solving a captcha challenge")
|
||||
@Nullable String captcha,
|
||||
|
||||
@Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED, description = "Mobile country code of the phone subscriber")
|
||||
@Nullable String mcc,
|
||||
|
||||
@Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED, description = "Mobile network code of the phone subscriber")
|
||||
@Nullable String mnc) {
|
||||
|
||||
public enum PushTokenType {
|
||||
@JsonProperty("apn")
|
||||
|
||||
+10
-5
@@ -6,24 +6,29 @@
|
||||
package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
|
||||
public class UserRemoteConfig {
|
||||
|
||||
@JsonProperty
|
||||
private String name;
|
||||
@Schema(description = "Name of the configuration", example = "android.exampleFeature")
|
||||
private String name;
|
||||
|
||||
@JsonProperty
|
||||
@Schema(description = "Whether the configuration is enabled for the user")
|
||||
private boolean enabled;
|
||||
|
||||
@JsonProperty
|
||||
private String value;
|
||||
@Schema(description = "The value to be used for the configuration, if it is a non-boolean type")
|
||||
private String value;
|
||||
|
||||
public UserRemoteConfig() {}
|
||||
public UserRemoteConfig() {
|
||||
}
|
||||
|
||||
public UserRemoteConfig(String name, boolean enabled, String value) {
|
||||
this.name = name;
|
||||
this.name = name;
|
||||
this.enabled = enabled;
|
||||
this.value = value;
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
|
||||
+6
@@ -10,16 +10,22 @@ import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import org.whispersystems.textsecuregcm.util.InstantAdapter;
|
||||
|
||||
public class UserRemoteConfigList {
|
||||
|
||||
@JsonProperty
|
||||
@Schema(description = "List of remote configurations applicable to the user")
|
||||
private List<UserRemoteConfig> config;
|
||||
|
||||
@JsonProperty
|
||||
@JsonSerialize(using = InstantAdapter.EpochSecondSerializer.class)
|
||||
@JsonFormat(shape = JsonFormat.Shape.NUMBER_INT)
|
||||
@Schema(description = """
|
||||
Timestamp when the configuration was generated. Deprecated in favor of `X-Signal-Timestamp` response header.
|
||||
""", deprecated = true)
|
||||
@Deprecated
|
||||
private Instant serverEpochTime;
|
||||
|
||||
public UserRemoteConfigList() {}
|
||||
|
||||
+6
-1
@@ -6,10 +6,15 @@
|
||||
package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import org.whispersystems.textsecuregcm.registration.MessageTransport;
|
||||
|
||||
public record VerificationCodeRequest(@NotNull Transport transport, @NotNull String client) {
|
||||
public record VerificationCodeRequest(@Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = "Transport via which to send the verification code")
|
||||
@NotNull Transport transport,
|
||||
|
||||
@Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = "Client type to facilitate platform-specific SMS verification")
|
||||
@NotNull String client) {
|
||||
|
||||
public enum Transport {
|
||||
@JsonProperty("sms")
|
||||
|
||||
+22
-4
@@ -7,11 +7,29 @@ package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import java.util.List;
|
||||
import javax.annotation.Nullable;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import org.whispersystems.textsecuregcm.registration.VerificationSession;
|
||||
|
||||
public record VerificationSessionResponse(String id, @Nullable Long nextSms, @Nullable Long nextCall,
|
||||
@Nullable Long nextVerificationAttempt, boolean allowedToRequestCode,
|
||||
List<VerificationSession.Information> requestedInformation,
|
||||
boolean verified) {
|
||||
public record VerificationSessionResponse(
|
||||
@Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = "A URL-safe ID for the session")
|
||||
String id,
|
||||
|
||||
@Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED, description = "Duration in seconds after which next SMS can be requested for this session")
|
||||
@Nullable Long nextSms,
|
||||
|
||||
@Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED, description = "Duration in seconds after which next voice call can be requested for this session")
|
||||
@Nullable Long nextCall,
|
||||
|
||||
@Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED, description = "Duration in seconds after which the client can submit a verification code for this session")
|
||||
@Nullable Long nextVerificationAttempt,
|
||||
|
||||
@Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = "Whether it is allowed to request a verification code for this session")
|
||||
boolean allowedToRequestCode,
|
||||
|
||||
@Schema(description = "A list of requested information that the client needs to submit before requesting code delivery")
|
||||
List<VerificationSession.Information> requestedInformation,
|
||||
|
||||
@Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = "Whether this session is verified")
|
||||
boolean verified) {
|
||||
|
||||
}
|
||||
Loaded 100 of 341 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user