mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-12-01 15:26:47 +00:00
Compare commits
79
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
100ab61c82 | ||
|
|
4d48c40ce1 | ||
|
|
93ade07c57 | ||
|
|
c1d8ca3c14 | ||
|
|
38707313d7 | ||
|
|
8eb2f5cec6 | ||
|
|
a7d66cb8e6 | ||
|
|
9db804f7c0 | ||
|
|
e93395e334 | ||
|
|
c9b8645469 | ||
|
|
f92681dbae | ||
|
|
7489c62fb7 | ||
|
|
23932b1087 | ||
|
|
6b3f66ddc1 | ||
|
|
77e3675fc9 | ||
|
|
2f712b3f93 | ||
|
|
9b5ad238cf | ||
|
|
8c62a7f819 | ||
|
|
3a75f705c2 | ||
|
|
d79e37230e | ||
|
|
7bc8b93c18 | ||
|
|
b6bed9d772 | ||
|
|
18e58dd21f | ||
|
|
6ab0acadfd | ||
|
|
6209466d1d | ||
|
|
9483f358cd | ||
|
|
1c28620b65 | ||
|
|
cc50ff7074 | ||
|
|
c60ba6677a | ||
|
|
32fc76fd47 | ||
|
|
370c3a9992 | ||
|
|
b3506b186d | ||
|
|
a91585d3c0 | ||
|
|
5469341fd6 | ||
|
|
9ee081ef28 | ||
|
|
33bf9ccae5 | ||
|
|
2321f42e20 | ||
|
|
355d95c6c6 | ||
|
|
3dde05de8a | ||
|
|
1ed282a790 | ||
|
|
d1ec5d7d9c | ||
|
|
c09e167f3f | ||
|
|
eaa3c5f20f | ||
|
|
eb0ffb0c4d | ||
|
|
31b34ed06f | ||
|
|
b247fc24c1 | ||
|
|
56a91f104e | ||
|
|
461fce800a | ||
|
|
7f08e8bf4e | ||
|
|
08ca97ba00 | ||
|
|
4577a4aa9b | ||
|
|
8fac5de9af | ||
|
|
1dd7383af0 | ||
|
|
5f66f1c51d | ||
|
|
867ec4a3df | ||
|
|
a5f2f7f3e5 | ||
|
|
4c2cd0c999 | ||
|
|
14fb2fb29d | ||
|
|
c612bd4b73 | ||
|
|
4157cadf44 | ||
|
|
0cabb53aed | ||
|
|
f04e716347 | ||
|
|
558649ba65 | ||
|
|
43dc9d11fd | ||
|
|
9547655a9c | ||
|
|
547bde4869 | ||
|
|
fe1082d8ba | ||
|
|
7c77dd20bc | ||
|
|
f0370b75af | ||
|
|
ed08d1dc23 | ||
|
|
369ca0b514 | ||
|
|
218a1cd75f | ||
|
|
b04e41803a | ||
|
|
e92c3bb8aa | ||
|
|
2bcecc7f7d | ||
|
|
e8979082a7 | ||
|
|
5c99b03eb2 | ||
|
|
9814fee556 | ||
|
|
5b18ecafaa |
No files matched your search
@@ -19,6 +19,27 @@ updates:
|
||||
update-types:
|
||||
- version-update:semver-major
|
||||
- version-update:semver-minor
|
||||
# Ignore the latest pre-release version
|
||||
versions: ["<=7.3.79"]
|
||||
|
||||
# Temporary exclusions, pending upstream fixes
|
||||
# https://github.com/dropwizard/dropwizard/pull/11273
|
||||
- dependency-name: "ch.qos.logback:*"
|
||||
versions: [">=1.6.0"]
|
||||
# https://github.com/jetty/jetty.project/issues/15657
|
||||
- dependency-name: "org.eclipse.jetty:*"
|
||||
versions: ["<=12.1.12"]
|
||||
- dependency-name: "org.eclipse.jetty.ee10:*"
|
||||
versions: ["<=12.1.12"]
|
||||
|
||||
# Temporary exclusions, pending adaptation to upstream changes
|
||||
- dependency-name: "io.lettuce:lettuce-core"
|
||||
versions: [">=7.7.0.RELEASE"]
|
||||
|
||||
# Dependency convergence sentinels, pinned to specific versions
|
||||
- dependency-name: "tools.jackson.core:jackson-databind"
|
||||
- dependency-name: "com.squareup.okio:okio-jvm"
|
||||
|
||||
groups:
|
||||
minor-java-dependencies:
|
||||
# Java: Only group minor and patch updates (we want to carefully review major updates)
|
||||
|
||||
@@ -12,16 +12,17 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5.7.0
|
||||
- name: Install APT packages
|
||||
run: |
|
||||
sudo apt-get update
|
||||
# setup-java requires gpg
|
||||
sudo apt-get install -y protobuf-compiler gpg
|
||||
pip install sabledocs
|
||||
- uses: actions/setup-java@dd06d9cba3e5552c54d9f8ea23572deb30010f7c # v6.0.0
|
||||
with:
|
||||
distribution: 'temurin'
|
||||
java-version-file: .java-version
|
||||
cache: 'maven'
|
||||
- name: Install gRPC documentation tooling
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y protobuf-compiler
|
||||
pip install sabledocs
|
||||
- name: Generate OpenAPI documentation
|
||||
run: ./mvnw compile
|
||||
- name: Generate gRPC documentation
|
||||
|
||||
@@ -20,7 +20,12 @@ jobs:
|
||||
issues: write
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5.7.0
|
||||
- name: Install APT packages
|
||||
run: |
|
||||
# setup-java requires gpg
|
||||
sudo apt update
|
||||
sudo apt install -y gpg
|
||||
- uses: actions/setup-java@dd06d9cba3e5552c54d9f8ea23572deb30010f7c # v6.0.0
|
||||
with:
|
||||
distribution: 'temurin'
|
||||
java-version-file: .java-version
|
||||
|
||||
@@ -32,11 +32,11 @@ jobs:
|
||||
- name: Install APT packages
|
||||
# ca-certificates: required for AWS CRT client
|
||||
run: |
|
||||
# Add Docker's official GPG key:
|
||||
apt update
|
||||
apt install -y ca-certificates curl
|
||||
# Maven Wrapper requires `unzip`; see https://github.com/apache/maven-wrapper/issues/425
|
||||
apt install -y unzip
|
||||
# setup-java requires gpg
|
||||
apt install -y ca-certificates curl gpg unzip
|
||||
# Add Docker's official GPG key:
|
||||
install -m 0755 -d /etc/apt/keyrings
|
||||
curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc
|
||||
chmod a+r /etc/apt/keyrings/docker.asc
|
||||
@@ -50,7 +50,7 @@ jobs:
|
||||
# ca-certificates: required for AWS CRT client
|
||||
apt update && apt install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin ca-certificates
|
||||
- name: Set up JDK
|
||||
uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5.7.0
|
||||
uses: actions/setup-java@dd06d9cba3e5552c54d9f8ea23572deb30010f7c # v6.0.0
|
||||
with:
|
||||
distribution: 'temurin'
|
||||
java-version-file: .java-version
|
||||
|
||||
@@ -10,10 +10,6 @@
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>integration-tests</artifactId>
|
||||
|
||||
<properties>
|
||||
<jetty.http2-client.version>12.1.12</jetty.http2-client.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.whispersystems.textsecure</groupId>
|
||||
@@ -39,7 +35,6 @@
|
||||
<dependency>
|
||||
<groupId>org.eclipse.jetty.http2</groupId>
|
||||
<artifactId>jetty-http2-client-transport</artifactId>
|
||||
<version>${jetty.http2-client.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
|
||||
@@ -61,7 +61,7 @@ public class MessagingTest {
|
||||
assertDoesNotThrow(() -> WebsocketClientSession.decode(SendMessageResponse.class, responseMessage));
|
||||
|
||||
final WebsocketClientSession websocketB = Operations.authenticatedWebsocket(userB, Device.PRIMARY_ID);
|
||||
assertTimeoutPreemptively(Duration.ofSeconds(5), websocketB::waitForQueueEmpty);
|
||||
assertTimeoutPreemptively(Duration.ofSeconds(15), websocketB::waitForQueueEmpty);
|
||||
|
||||
assertEquals(1, websocketB.getReceivedEnvelopes().size());
|
||||
final MessageProtos.Envelope envelope = websocketB.getReceivedEnvelopes().getFirst();
|
||||
|
||||
@@ -45,50 +45,50 @@
|
||||
</modules>
|
||||
|
||||
<properties>
|
||||
<aws.sdk2.version>2.51.4</aws.sdk2.version>
|
||||
<aws.sdk2.version>2.54.7</aws.sdk2.version>
|
||||
<braintree.version>3.53.0</braintree.version>
|
||||
<commons-csv.version>1.14.1</commons-csv.version>
|
||||
<commons-io.version>2.22.0</commons-io.version>
|
||||
<dropwizard.version>5.0.2</dropwizard.version>
|
||||
<!-- Note: We use x86_64 builds without AVX instructions enabled (i.e. FoundationDB versions with even-numbered
|
||||
patch versions). Also when updating FoundationDB, make sure to update the version of FoundationDBused by GitHub
|
||||
Actions. -->
|
||||
<foundationdb.version>7.3.68</foundationdb.version>
|
||||
patch versions). -->
|
||||
<foundationdb.version>7.3.76</foundationdb.version>
|
||||
<foundationdb.api-version>730</foundationdb.api-version>
|
||||
<foundationdb.client-library-sha256>8c96a1f7ab561cd38e16e4c269c5e50ae0fd8063854e0d72c89339a7ac1b6873</foundationdb.client-library-sha256>
|
||||
<google-cloud-libraries.version>26.86.0</google-cloud-libraries.version>
|
||||
<foundationdb.client-library-sha256>af099848721d08904ff9e5d38fade0de24d92e86451ea491d9ab5ce84adcf62a</foundationdb.client-library-sha256>
|
||||
<google-cloud-libraries.version>26.87.0</google-cloud-libraries.version>
|
||||
<grpc.version>1.76.3</grpc.version> <!-- should be kept in sync with the value from Google libraries-bom -->
|
||||
<gson.version>2.14.0</gson.version>
|
||||
<guava.version>33.6.0-jre</guava.version>
|
||||
<guava.version>33.7.1-jre</guava.version>
|
||||
<!-- several libraries (AWS, Google Cloud) use Apache http components transitively, and we need to align them -->
|
||||
<httpcore.version>4.4.16</httpcore.version>
|
||||
<httpclient.version>4.5.14</httpclient.version>
|
||||
<jackson.version>2.22.2</jackson.version>
|
||||
<java-otp.version>1.0.0</java-otp.version>
|
||||
<jetty.version>12.1.9</jetty.version>
|
||||
<junit-pioneer.version>2.3.0</junit-pioneer.version>
|
||||
<jsr305.version>3.0.2</jsr305.version>
|
||||
<kotlin.version>2.4.10</kotlin.version>
|
||||
<!-- dropwizard references a constant removed in 1.6 -->
|
||||
<!-- dropwizard references a constant removed in 1.6. See also: dependabot.yml -->
|
||||
<logback.version>1.5.38</logback.version>
|
||||
<logback-access-common.version>2.0.15</logback-access-common.version>
|
||||
<lettuce.version>7.6.0.RELEASE</lettuce.version>
|
||||
<libphonenumber.version>9.0.37</libphonenumber.version>
|
||||
<libphonenumber.version>9.0.38</libphonenumber.version>
|
||||
<logstash.logback.version>9.0</logstash.logback.version>
|
||||
<log4j-bom.version>2.26.1</log4j-bom.version>
|
||||
<luajava.version>4.1.0</luajava.version>
|
||||
<micrometer.version>1.17.0</micrometer.version>
|
||||
<micrometer.version>1.17.1</micrometer.version>
|
||||
<netty.version>4.2.17.Final</netty.version>
|
||||
<!-- must be greater than or equal to the value from Google libraries-bom, see https://protobuf.dev/support/cross-version-runtime-guarantee/ -->
|
||||
<!-- the latest 4.x should be fine https://central.sonatype.com/artifact/com.google.protobuf/protobuf-java/versions -->
|
||||
<protobuf.version>4.35.1</protobuf.version>
|
||||
<protobuf.version>4.36.0</protobuf.version>
|
||||
<pushy.version>0.15.6</pushy.version>
|
||||
<reactor-bom.version>2025.0.6</reactor-bom.version> <!-- 3.8.4, see https://github.com/reactor/reactor#bom-versioning-scheme -->
|
||||
<reactor-bom.version>2025.0.7</reactor-bom.version> <!-- 3.8.4, see https://github.com/reactor/reactor#bom-versioning-scheme -->
|
||||
<resilience4j.version>2.4.0</resilience4j.version>
|
||||
<semver4j.version>3.1.0</semver4j.version>
|
||||
<simple-grpc.version>0.2.1</simple-grpc.version>
|
||||
<slf4j.version>2.0.18</slf4j.version>
|
||||
<stripe.version>33.3.0</stripe.version>
|
||||
<swagger.version>2.2.46</swagger.version>
|
||||
<stripe.version>33.4.0</stripe.version>
|
||||
<swagger.version>2.2.54</swagger.version>
|
||||
<testcontainers.version>2.0.5</testcontainers.version>
|
||||
|
||||
<!-- images to use in tests via testcontainers -->
|
||||
@@ -97,7 +97,7 @@
|
||||
<redis.image>redis:7.4-alpine@sha256:6ab0b6e7381779332f97b8ca76193e45b0756f38d4c0dcda72dbb3c32061ab99</redis.image>
|
||||
<redis-cluster.image>docker.io/bitnamilegacy/redis-cluster:7.4.3@sha256:a53d023fdfaf8a8d7ddc58da040d3494e4cb45772644618ffa44c42dcd32b9af</redis-cluster.image>
|
||||
|
||||
<docker.image>eclipse-temurin:25-jre-resolute@sha256:17ddcc32b1f296155738c4b2f689208e46bf0cf4eb0b215c717717deb8b74b90</docker.image>
|
||||
<docker.image>eclipse-temurin:25-jre-resolute@sha256:71bfb73662d4146bdc9ee2f97418a764d5ab4e83f4e90baec3b3dcda14071007</docker.image>
|
||||
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
</properties>
|
||||
@@ -107,7 +107,9 @@
|
||||
<version>JGITVER</version>
|
||||
|
||||
<dependencyManagement>
|
||||
<!-- note: order matters, and earlier declarations take precedence -->
|
||||
<dependencies>
|
||||
<!-- use a pinned version of jackson, rather than Dropwizard's BOM -->
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson</groupId>
|
||||
<artifactId>jackson-bom</artifactId>
|
||||
@@ -115,19 +117,21 @@
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<!-- use a pinned version of jetty, rather than Dropwizard's BOM -->
|
||||
<dependency>
|
||||
<groupId>io.dropwizard</groupId>
|
||||
<artifactId>dropwizard-dependencies</artifactId>
|
||||
<version>${dropwizard.version}</version>
|
||||
<groupId>org.eclipse.jetty</groupId>
|
||||
<artifactId>jetty-bom</artifactId>
|
||||
<version>${jetty.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<!-- Needed for gRPC with Java 9+ -->
|
||||
<!-- use a pinned version of jetty, rather than Dropwizard's BOM -->
|
||||
<dependency>
|
||||
<groupId>org.apache.tomcat</groupId>
|
||||
<artifactId>annotations-api</artifactId>
|
||||
<version>6.0.53</version>
|
||||
<scope>provided</scope>
|
||||
<groupId>org.eclipse.jetty.ee10</groupId>
|
||||
<artifactId>jetty-ee10-bom</artifactId>
|
||||
<version>${jetty.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.netty</groupId>
|
||||
@@ -136,13 +140,6 @@
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>software.amazon.awssdk</groupId>
|
||||
<artifactId>bom</artifactId>
|
||||
<version>${aws.sdk2.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.protobuf</groupId>
|
||||
<artifactId>protobuf-bom</artifactId>
|
||||
@@ -157,6 +154,27 @@
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>software.amazon.awssdk</groupId>
|
||||
<artifactId>bom</artifactId>
|
||||
<version>${aws.sdk2.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.dropwizard</groupId>
|
||||
<artifactId>dropwizard-dependencies</artifactId>
|
||||
<version>${dropwizard.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<!-- Needed for gRPC with Java 9+ -->
|
||||
<dependency>
|
||||
<groupId>org.apache.tomcat</groupId>
|
||||
<artifactId>annotations-api</artifactId>
|
||||
<version>6.0.53</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.github.resilience4j</groupId>
|
||||
<artifactId>resilience4j-bom</artifactId>
|
||||
@@ -181,7 +199,7 @@
|
||||
<dependency>
|
||||
<groupId>io.opentelemetry.instrumentation</groupId>
|
||||
<artifactId>opentelemetry-instrumentation-bom</artifactId>
|
||||
<version>2.30.0</version>
|
||||
<version>2.31.1</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
@@ -299,7 +317,7 @@
|
||||
<dependency>
|
||||
<groupId>org.signal</groupId>
|
||||
<artifactId>libsignal-server</artifactId>
|
||||
<version>0.101.0</version>
|
||||
<version>0.101.2</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.signal</groupId>
|
||||
|
||||
@@ -79,7 +79,8 @@ storageService.userAuthenticationTokenSharedSecret: AAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
||||
|
||||
zkConfig-libsignal-0.42.serverSecret: ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdef
|
||||
|
||||
callingZkConfig.serverSecret: ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzAA==
|
||||
callingZkConfigPreV101.serverSecret: ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzAA==
|
||||
callingZkConfigV101.serverSecret: ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzAA==
|
||||
chatZkConfig.serverSecret: ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzAA==
|
||||
|
||||
paymentsService.userAuthenticationTokenSharedSecret: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= # base64-encoded 32-byte secret shared with MobileCoin services used to generate auth tokens for Signal users
|
||||
|
||||
@@ -315,8 +315,11 @@ storageService:
|
||||
AAAAAAAAAAAAAAAAAAAA
|
||||
-----END CERTIFICATE-----
|
||||
|
||||
callingZkConfigPreV101:
|
||||
serverSecret: secret://callingZkConfigPreV101.serverSecret
|
||||
|
||||
callingZkConfig:
|
||||
serverSecret: secret://callingZkConfig.serverSecret
|
||||
serverSecret: secret://callingZkConfigV101.serverSecret
|
||||
|
||||
chatZkConfig:
|
||||
serverSecret: secret://chatZkConfig.serverSecret
|
||||
@@ -384,6 +387,7 @@ subscription: # configuration for Stripe subscriptions
|
||||
|
||||
loginPurchase:
|
||||
playProductId: login_example
|
||||
playOptionId: login_option_example
|
||||
appStoreProductId: login_example
|
||||
|
||||
oneTimeDonations:
|
||||
|
||||
+4
-16
@@ -15,15 +15,14 @@
|
||||
<commons-compress.version>1.28.0</commons-compress.version>
|
||||
<dynamodb-lock-client.version>1.5.0</dynamodb-lock-client.version>
|
||||
<firebase-admin.version>9.10.0</firebase-admin.version>
|
||||
<libphonenumber-geocoder.version>3.37</libphonenumber-geocoder.version>
|
||||
<libphonenumber-geocoder.version>3.38</libphonenumber-geocoder.version>
|
||||
<google-androidpublisher.version>v3-rev20250904-2.0.0</google-androidpublisher.version>
|
||||
<java-jwt.version>4.6.0</java-jwt.version>
|
||||
<java-uuid-generator.version>5.2.0</java-uuid-generator.version>
|
||||
<!-- *all* opentelemetry-logback-appender versions are "alpha" despite the advanced version number -->
|
||||
<opentelemetry-logback-appender-1.0.version>2.30.0-alpha</opentelemetry-logback-appender-1.0.version>
|
||||
<opentelemetry-logback-appender-1.0.version>2.31.1-alpha</opentelemetry-logback-appender-1.0.version>
|
||||
<storekit.version>5.2.0</storekit.version>
|
||||
<webauthn4j.version>0.31.9.RELEASE</webauthn4j.version>
|
||||
<jetty.http2-client.version>12.1.12</jetty.http2-client.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
@@ -147,7 +146,6 @@
|
||||
<groupId>org.eclipse.jetty.http2</groupId>
|
||||
<artifactId>jetty-http2-client-transport</artifactId>
|
||||
<scope>test</scope>
|
||||
<version>${jetty.http2-client.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.dropwizard</groupId>
|
||||
@@ -190,6 +188,7 @@
|
||||
<dependency>
|
||||
<groupId>tools.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
<!-- update dependabot.yml when this dependency is removed -->
|
||||
<version>3.2.1</version>
|
||||
</dependency>
|
||||
|
||||
@@ -311,18 +310,6 @@
|
||||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.google.cloud</groupId>
|
||||
<artifactId>google-cloud-firestore</artifactId>
|
||||
<exclusions>
|
||||
<!-- incubator packages aren't included in the opentelemetry BOM, and we don't use them -->
|
||||
<exclusion>
|
||||
<groupId>io.opentelemetry.instrumentation</groupId>
|
||||
<artifactId>opentelemetry-instrumentation-api-incubator</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.google.code.findbugs</groupId>
|
||||
<artifactId>jsr305</artifactId>
|
||||
@@ -653,6 +640,7 @@
|
||||
<dependency>
|
||||
<groupId>com.squareup.okio</groupId>
|
||||
<artifactId>okio-jvm</artifactId>
|
||||
<!-- update dependabot.yml when this dependency is removed -->
|
||||
<version>3.17.0</version>
|
||||
</dependency>
|
||||
|
||||
|
||||
+10
@@ -228,6 +228,11 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
@JsonProperty
|
||||
private PaymentsServiceConfiguration paymentsService;
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
private GenericZkConfig callingZkConfigPreV101;
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
@@ -514,6 +519,11 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
return chatZkConfig;
|
||||
}
|
||||
|
||||
/// ZK secret shared with Calling Service
|
||||
public GenericZkConfig getCallingZkConfigPreV101() {
|
||||
return callingZkConfigPreV101;
|
||||
}
|
||||
|
||||
/// ZK secret shared with Calling Service
|
||||
public GenericZkConfig getCallingZkConfig() {
|
||||
return callingZkConfig;
|
||||
|
||||
@@ -207,7 +207,6 @@ import org.whispersystems.textsecuregcm.limits.RedisMessageDeliveryLoopMonitor;
|
||||
import org.whispersystems.textsecuregcm.mappers.BackupExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.CompletionExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.DeviceLimitExceededExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.GrpcStatusRuntimeExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.IOExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.IllegalStateExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.ImpossiblePhoneNumberExceptionMapper;
|
||||
@@ -273,14 +272,14 @@ import org.whispersystems.textsecuregcm.storage.OneTimeDonationsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.PagedSingleUseKEMPreKeyStore;
|
||||
import org.whispersystems.textsecuregcm.storage.PersistentTimer;
|
||||
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
|
||||
import org.whispersystems.textsecuregcm.storage.PhoneNumberRecoveryPasswords;
|
||||
import org.whispersystems.textsecuregcm.storage.PhoneNumberRecoveryPasswordsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ProfileAvatars;
|
||||
import org.whispersystems.textsecuregcm.storage.Profiles;
|
||||
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ProfilesV2;
|
||||
import org.whispersystems.textsecuregcm.storage.PushChallengeDynamoDb;
|
||||
import org.whispersystems.textsecuregcm.storage.RedeemedReceiptsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.PhoneNumberRecoveryPasswords;
|
||||
import org.whispersystems.textsecuregcm.storage.PhoneNumberRecoveryPasswordsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.RemoteConfigs;
|
||||
import org.whispersystems.textsecuregcm.storage.RemoteConfigsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.RepeatedUseECSignedPreKeyStore;
|
||||
@@ -295,7 +294,9 @@ 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.storage.foundationdb.FaultTolerantDatabase;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStore;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDBWarmup;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.VersionstampUUIDCipher;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.AppleAppStoreClient;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.AppleAppStoreManager;
|
||||
@@ -328,12 +329,12 @@ import org.whispersystems.textsecuregcm.workers.CertificateCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.CheckDynamicConfigurationCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.ClearExpiredFoundationDbMessagesCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.ClearIssuedReceiptRedemptionsCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.ClearOrphanedFoundationDbQueuesCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.CopyToS3Command;
|
||||
import org.whispersystems.textsecuregcm.workers.DeleteUserCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.IdleDeviceNotificationSchedulerFactory;
|
||||
import org.whispersystems.textsecuregcm.workers.MessagePersisterServiceCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.NotifyIdleDevicesCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.PopulateAccountRecoveryPasswordsCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.ProcessScheduledJobsServiceCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.RegenerateSecondaryDynamoDbTableDataCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.RemoveExpiredAccountsCommand;
|
||||
@@ -406,6 +407,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
bootstrap.addCommand(new CopyToS3Command());
|
||||
bootstrap.addCommand(new ClearExpiredFoundationDbMessagesCommand(Clock.systemUTC()));
|
||||
bootstrap.addCommand(new TrimOversizedFoundationDbMessageQueuesCommand());
|
||||
bootstrap.addCommand(new ClearOrphanedFoundationDbQueuesCommand());
|
||||
|
||||
bootstrap.addCommand(new ProcessScheduledJobsServiceCommand("process-idle-device-notification-jobs",
|
||||
"Processes scheduled jobs to send notifications to idle devices",
|
||||
@@ -413,8 +415,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
|
||||
bootstrap.addCommand(new RegenerateSecondaryDynamoDbTableDataCommand());
|
||||
|
||||
bootstrap.addCommand(new PopulateAccountRecoveryPasswordsCommand());
|
||||
|
||||
ServiceLoader.load(SpamFilter.class)
|
||||
.stream()
|
||||
.map(ServiceLoader.Provider::get)
|
||||
@@ -500,9 +500,9 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
// we'd like, but is the least bad option given current constraints.
|
||||
fdb.disableShutdownHook();
|
||||
|
||||
final Map<Integer, List<Database>> messageDatabasesByEpoch;
|
||||
final Map<Integer, List<FaultTolerantDatabase>> messageDatabasesByEpoch;
|
||||
{
|
||||
final Map<String, Database> databasesByName =
|
||||
final Map<String, FaultTolerantDatabase> faultTolerantDatabasesByName =
|
||||
config.getFoundationDbMessagesConfiguration().clusters().entrySet().stream()
|
||||
.collect(Collectors.toUnmodifiableMap(Map.Entry::getKey,
|
||||
entry -> {
|
||||
@@ -514,7 +514,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
database.options().setTransactionRetryLimit(
|
||||
config.getFoundationDbMessagesConfiguration().transactionRetryLimit());
|
||||
|
||||
return database;
|
||||
return new FaultTolerantDatabase(database, entry.getKey(),
|
||||
config.getFoundationDbMessagesConfiguration().circuitBreakerConfigurationName());
|
||||
} catch (final IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
@@ -523,8 +524,10 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
messageDatabasesByEpoch = config.getFoundationDbMessagesConfiguration().epochs().entrySet().stream()
|
||||
.collect(Collectors.toUnmodifiableMap(Map.Entry::getKey,
|
||||
entry -> entry.getValue().stream()
|
||||
.map(databasesByName::get)
|
||||
.map(faultTolerantDatabasesByName::get)
|
||||
.toList()));
|
||||
|
||||
environment.lifecycle().manage(new FoundationDBWarmup(faultTolerantDatabasesByName));
|
||||
}
|
||||
|
||||
final AwsCredentialsProvider cdnCredentialsProvider = config.getCdnConfiguration().credentials().build();
|
||||
@@ -667,10 +670,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
.workQueue(receiptSenderQueue)
|
||||
.rejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy())
|
||||
.build();
|
||||
ExecutorService accountLockExecutor = ExecutorServiceBuilder.of(environment, "accountLock")
|
||||
.minThreads(8)
|
||||
.maxThreads(8)
|
||||
.build();
|
||||
// unbounded executor (same as cachedThreadPool)
|
||||
ExecutorService remoteStorageHttpExecutor = ExecutorServiceBuilder.of(environment, "remoteStorage")
|
||||
.minThreads(0)
|
||||
@@ -800,10 +799,10 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
changeNumberWaitingPeriods, config.getChangeNumber().postRegistrationWaitingPeriod(), clock);
|
||||
AccountLockManager accountLockManager = new AccountLockManager(dynamoDbClient,
|
||||
config.getDynamoDbTables().getDeletedAccountsLock().getTableName());
|
||||
AccountsManager accountsManager = new AccountsManager(accounts, phoneNumberIdentifiers, cacheCluster,
|
||||
final AccountsManager accountsManager = new AccountsManager(accounts, phoneNumberIdentifiers, cacheCluster,
|
||||
pubsubClient, accountLockManager, keysManager, messagesManager, profilesManager,
|
||||
changeNumberWaitingPeriodManager, secureStorageClient, secureValueRecovery2Client, disconnectionRequestManager,
|
||||
phoneNumberRecoveryPasswordsManager, accountLockExecutor, messagePollExecutor,
|
||||
phoneNumberRecoveryPasswordsManager, messagePollExecutor,
|
||||
retryExecutor, clock, config.getLinkDeviceSecretConfiguration().secret().value(),
|
||||
config.getRegistrationTotpConfiguration().maxValidationDelay());
|
||||
RemoteConfigsManager remoteConfigsManager = new RemoteConfigsManager(remoteConfigs, config.getRemoteConfigConfiguration().globalConfig());
|
||||
@@ -939,6 +938,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
config.getCdnConfiguration().credentials().secretAccessKey().value());
|
||||
|
||||
ServerSecretParams groupZkSecretParams = new ServerSecretParams(config.getGroupsZkConfig().serverSecret().value());
|
||||
GenericServerSecretParams callingPreV101GenericZkSecretParams = new GenericServerSecretParams(config.getCallingZkConfigPreV101().serverSecret().value());
|
||||
GenericServerSecretParams callingGenericZkSecretParams = new GenericServerSecretParams(config.getCallingZkConfig().serverSecret().value());
|
||||
GenericServerSecretParams chatGenericZkSecretParams = new GenericServerSecretParams(config.getChatZkConfig().serverSecret().value());
|
||||
ServerZkProfileOperations zkProfileOperations = new ServerZkProfileOperations(groupZkSecretParams);
|
||||
@@ -1180,11 +1180,14 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
unauthenticatedServices.forEach(serverBuilder::addService);
|
||||
final ManagedGrpcServer localGrpcServer = new ManagedGrpcServer(serverBuilder.build());
|
||||
|
||||
final String websocketServletPath = "/v1/websocket/";
|
||||
final String provisioningWebsocketServletPath = "/v1/websocket/provisioning/";
|
||||
|
||||
final SocketAddress websocketAddress =
|
||||
new InetSocketAddress(config.getGrpc().websocketAddress(), config.getGrpc().websocketPort());
|
||||
final OmnibusRouter omnibusRouter = new OmnibusRouter(List.of(
|
||||
new OmnibusRouter.OmnibusRoute("/v1/websocket", websocketAddress),
|
||||
new OmnibusRouter.OmnibusRoute("/v1/provisioning", websocketAddress)),
|
||||
final OmnibusRouter omnibusRouter = new OmnibusRouter(Map.of(
|
||||
websocketServletPath, websocketAddress,
|
||||
provisioningWebsocketServletPath, websocketAddress),
|
||||
grpcLocalAddress);
|
||||
@Nullable final Mapping<String, SslContext> sniMapping = config.getGrpc().h2c()
|
||||
? null
|
||||
@@ -1215,9 +1218,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
.setAuthenticator(accountAuthenticator)
|
||||
.buildAuthFilter();
|
||||
|
||||
final String websocketServletPath = "/v1/websocket/";
|
||||
final String provisioningWebsocketServletPath = "/v1/websocket/provisioning/";
|
||||
|
||||
MetricsHttpEventHandler.configure(environment, Metrics.globalRegistry, clientReleaseManager, Set.of(websocketServletPath, provisioningWebsocketServletPath, "/health-check"));
|
||||
|
||||
// BufferingInterceptor is needed on the base environment but not the WebSocketEnvironment,
|
||||
@@ -1267,9 +1267,9 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
experimentEnrollmentManager, config.getAttachments().maxAttachmentUploadSizeInBytes()),
|
||||
new ArchiveController(accountsManager, backupAuthManager, backupManager, backupMetrics, config.getAttachments().maxAttachmentUploadSizeInBytes(), config.getAttachments().maxMessageBackupUploadSizeInBytes()),
|
||||
new CallRoutingControllerV2(rateLimiters, cloudflareTurnCredentialsManager),
|
||||
new CallLinkController(rateLimiters, callingGenericZkSecretParams),
|
||||
new CallLinkController(rateLimiters, callingGenericZkSecretParams, callingPreV101GenericZkSecretParams),
|
||||
new CallQualitySurveyController(callQualitySurveyManager),
|
||||
new CertificateController(accountsManager, certificateGenerator, zkAuthOperations, callingGenericZkSecretParams, clock),
|
||||
new CertificateController(accountsManager, certificateGenerator, zkAuthOperations, callingGenericZkSecretParams, callingPreV101GenericZkSecretParams, clock),
|
||||
new ChallengeController(accountsManager, rateLimitChallengeManager, challengeConstraintChecker),
|
||||
new DeviceController(accountsManager, rateLimiters, persistentTimer),
|
||||
new DeviceCheckController(clock, accountsManager, backupAuthManager, appleDeviceCheckManager, rateLimiters,
|
||||
@@ -1364,7 +1364,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
List.of(
|
||||
new LoggingUnhandledExceptionMapper(),
|
||||
new CompletionExceptionMapper(),
|
||||
new GrpcStatusRuntimeExceptionMapper(),
|
||||
new IOExceptionMapper(),
|
||||
new RateLimitExceededExceptionMapper(),
|
||||
new InvalidWebsocketAddressExceptionMapper(),
|
||||
|
||||
+3
-1
@@ -5,6 +5,7 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import jakarta.annotation.Nullable;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.AssertTrue;
|
||||
import jakarta.validation.constraints.Max;
|
||||
@@ -33,7 +34,8 @@ public record FoundationDbMessagesConfiguration(@NotEmpty Map<String, @Valid Fou
|
||||
@NotNull Duration transactionTimeout,
|
||||
@PositiveOrZero long transactionRetryLimit,
|
||||
@NotNull Duration batchPriorityTransactionTimeout,
|
||||
@PositiveOrZero long batchPriorityTransactionRetryLimit) {
|
||||
@PositiveOrZero long batchPriorityTransactionRetryLimit,
|
||||
@Nullable String circuitBreakerConfigurationName) {
|
||||
|
||||
public static final long DEFAULT_MAX_WATCHES_PER_CLIENT = 10_000;
|
||||
public static final Duration DEFAULT_TRANSACTION_TIMEOUT = Duration.ofSeconds(1);
|
||||
|
||||
+2
@@ -12,7 +12,9 @@ import java.time.Duration;
|
||||
/// Configuration for one-time Signal Login purchases
|
||||
///
|
||||
/// @param playProductId the Google Play Billing productId clients should purchase to obtain a Signal Login
|
||||
/// @param playOptionId the Google Play Billing optionId clients should purchase to obtain a Signal Login
|
||||
/// @param appStoreProductId the App Store productId clients should purchase to obtain a Signal Login
|
||||
public record LoginPurchaseConfiguration(
|
||||
@NotEmpty String playProductId,
|
||||
@NotEmpty String playOptionId,
|
||||
@NotEmpty String appStoreProductId) {}
|
||||
+1
@@ -18,6 +18,7 @@ public record OpenTelemetryConfiguration(
|
||||
@JsonProperty Duration shutdownWaitDuration,
|
||||
@JsonProperty int maxBucketCount,
|
||||
@JsonProperty Map<String, Integer> maxBucketsPerMeter,
|
||||
@JsonProperty boolean publishMaxGaugeForHistograms,
|
||||
@JsonAnyGetter @JsonAnySetter Map<String, String> otlpConfig
|
||||
) implements OtlpConfig {
|
||||
|
||||
|
||||
+4
@@ -239,6 +239,10 @@ public class AccountController {
|
||||
}
|
||||
});
|
||||
|
||||
if (StringUtils.isNotEmpty(attributes.getRegistrationLock()) && a.getNumber().isEmpty()) {
|
||||
throw new BadRequestException("account does not have a phone number");
|
||||
}
|
||||
|
||||
a.setRegistrationLockFromAttributes(attributes);
|
||||
a.setUnidentifiedAccessKey(attributes.getUnidentifiedAccessKey());
|
||||
a.setUnrestrictedUnidentifiedAccess(attributes.isUnrestrictedUnidentifiedAccess());
|
||||
|
||||
+10
-3
@@ -2,6 +2,7 @@ package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
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.responses.ApiResponse;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
@@ -9,6 +10,7 @@ import jakarta.ws.rs.BadRequestException;
|
||||
import jakarta.ws.rs.POST;
|
||||
import jakarta.ws.rs.Path;
|
||||
import jakarta.ws.rs.Produces;
|
||||
import jakarta.ws.rs.QueryParam;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
@@ -26,13 +28,16 @@ import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
public class CallLinkController {
|
||||
private final RateLimiters rateLimiters;
|
||||
private final GenericServerSecretParams genericServerSecretParams;
|
||||
private final GenericServerSecretParams genericServerSecretParamsPreV101;
|
||||
|
||||
public CallLinkController(
|
||||
final RateLimiters rateLimiters,
|
||||
final GenericServerSecretParams genericServerSecretParams
|
||||
final GenericServerSecretParams genericServerSecretParams,
|
||||
final GenericServerSecretParams genericServerSecretParamsPreV101
|
||||
) {
|
||||
this.rateLimiters = rateLimiters;
|
||||
this.genericServerSecretParams = genericServerSecretParams;
|
||||
this.genericServerSecretParamsPreV101 = genericServerSecretParamsPreV101;
|
||||
}
|
||||
|
||||
@POST
|
||||
@@ -52,7 +57,9 @@ public class CallLinkController {
|
||||
@ApiResponse(responseCode = "429", description = "Ratelimited.")
|
||||
public CreateCallLinkCredential getCreateAuth(
|
||||
final @Auth AuthenticatedDevice auth,
|
||||
final @NotNull @Valid GetCreateCallLinkCredentialsRequest request
|
||||
final @NotNull @Valid GetCreateCallLinkCredentialsRequest request,
|
||||
@Parameter(description = "Whether to use libsignal v0.101.0+ secret params")
|
||||
final @QueryParam("v101") boolean v101
|
||||
) throws RateLimitExceededException {
|
||||
|
||||
rateLimiters.getCreateCallLinkLimiter().validate(auth.accountIdentifier());
|
||||
@@ -67,7 +74,7 @@ public class CallLinkController {
|
||||
}
|
||||
|
||||
return new CreateCallLinkCredential(
|
||||
createCallLinkCredentialRequest.issueCredential(new ServiceId.Aci(auth.accountIdentifier()), truncatedDayTimestamp, genericServerSecretParams).serialize(),
|
||||
createCallLinkCredentialRequest.issueCredential(new ServiceId.Aci(auth.accountIdentifier()), truncatedDayTimestamp, v101 ? genericServerSecretParams : genericServerSecretParamsPreV101).serialize(),
|
||||
truncatedDayTimestamp.getEpochSecond()
|
||||
);
|
||||
}
|
||||
|
||||
+8
-2
@@ -10,6 +10,7 @@ import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.ws.rs.BadRequestException;
|
||||
import jakarta.ws.rs.DefaultValue;
|
||||
@@ -49,6 +50,7 @@ public class CertificateController {
|
||||
private final CertificateGenerator certificateGenerator;
|
||||
private final ServerZkAuthOperations serverZkAuthOperations;
|
||||
private final GenericServerSecretParams genericServerSecretParams;
|
||||
private final GenericServerSecretParams genericServerSecretParamsPreV101;
|
||||
private final Clock clock;
|
||||
|
||||
@VisibleForTesting
|
||||
@@ -61,12 +63,14 @@ public class CertificateController {
|
||||
@Nonnull CertificateGenerator certificateGenerator,
|
||||
@Nonnull ServerZkAuthOperations serverZkAuthOperations,
|
||||
@Nonnull GenericServerSecretParams genericServerSecretParams,
|
||||
@Nonnull GenericServerSecretParams genericServerSecretParamsPreV101,
|
||||
@Nonnull Clock clock) {
|
||||
|
||||
this.accountsManager = accountsManager;
|
||||
this.certificateGenerator = Objects.requireNonNull(certificateGenerator);
|
||||
this.serverZkAuthOperations = Objects.requireNonNull(serverZkAuthOperations);
|
||||
this.genericServerSecretParams = genericServerSecretParams;
|
||||
this.genericServerSecretParamsPreV101 = genericServerSecretParamsPreV101;
|
||||
this.clock = Objects.requireNonNull(clock);
|
||||
}
|
||||
|
||||
@@ -95,7 +99,9 @@ public class CertificateController {
|
||||
public GroupCredentials getGroupAuthenticationCredentials(
|
||||
@Auth AuthenticatedDevice auth,
|
||||
@QueryParam("redemptionStartSeconds") long startSeconds,
|
||||
@QueryParam("redemptionEndSeconds") long endSeconds) {
|
||||
@QueryParam("redemptionEndSeconds") long endSeconds,
|
||||
@Parameter(description = "Whether to use libsignal v0.101.0+ secret params")
|
||||
@QueryParam("v101") boolean v101) {
|
||||
|
||||
final RedemptionRange redemptionRange;
|
||||
try {
|
||||
@@ -127,7 +133,7 @@ public class CertificateController {
|
||||
(int) redemption.getEpochSecond()));
|
||||
|
||||
callLinkAuthCredentials.add(new GroupCredentials.CallLinkAuthCredential(
|
||||
CallLinkAuthCredentialResponse.issueCredential(aci, redemption, genericServerSecretParams).serialize(),
|
||||
CallLinkAuthCredentialResponse.issueCredential(aci, redemption, v101 ? genericServerSecretParams : genericServerSecretParamsPreV101).serialize(),
|
||||
redemption.getEpochSecond()));
|
||||
}
|
||||
|
||||
|
||||
+9
-9
@@ -141,7 +141,7 @@ public class RegistrationController {
|
||||
""")
|
||||
@ApiResponse(responseCode = "200", description = "Account creation succeeded", useReturnTypeSchema = true)
|
||||
@ApiResponse(responseCode = "400", description = "Invalid session ID or receipt credential presentation")
|
||||
@ApiResponse(responseCode = "401", description = "The session identified in the request is not verified")
|
||||
@ApiResponse(responseCode = "401", description = "The session identified in the request is not verified, or the receipt credential presented fails verification, is expired, or is already redeemed")
|
||||
@ApiResponse(responseCode = "403", description = "Verification failed for the provided Registration Recovery Password")
|
||||
@ApiResponse(responseCode = "409", description = "The caller has not explicitly elected to skip transferring data from another device, but a device transfer is technically possible")
|
||||
@ApiResponse(responseCode = "422", description = "The request did not pass validation")
|
||||
@@ -226,8 +226,6 @@ public class RegistrationController {
|
||||
throw new WebApplicationException("PNI keys and registration ID must be provided", 422);
|
||||
}
|
||||
|
||||
rateLimiters.getRegistrationLimiter().validate(number);
|
||||
|
||||
final PhoneVerificationRequest.VerificationType verificationType;
|
||||
try {
|
||||
verificationType = phoneVerificationTokenManager.verify(
|
||||
@@ -247,6 +245,8 @@ public class RegistrationController {
|
||||
throw new ForbiddenException("recovery password could not be verified");
|
||||
}
|
||||
|
||||
rateLimiters.getRegistrationLimiter().validate(number);
|
||||
|
||||
// There can be at most one existing account for a set of numbers in the same equivalence class, so it's sufficient
|
||||
// to find the first one.
|
||||
final Optional<Account> existingAccount = Util.getAlternateForms(number)
|
||||
@@ -334,9 +334,9 @@ public class RegistrationController {
|
||||
throw new BadRequestException("login purchases are not enabled");
|
||||
}
|
||||
|
||||
if (registrationRequest.accountAttributes().recoveryPassword().isEmpty()) {
|
||||
throw new WebApplicationException("Account recovery password is required", 422);
|
||||
}
|
||||
registrationRequest.accountAttributes().recoveryPassword()
|
||||
.filter(ArrayUtils::isNotEmpty)
|
||||
.orElseThrow(() -> new WebApplicationException("Account recovery password is required", 422));
|
||||
|
||||
final ReceiptCredentialPresentation receiptCredentialPresentation;
|
||||
try {
|
||||
@@ -348,12 +348,12 @@ public class RegistrationController {
|
||||
try {
|
||||
serverZkReceiptOperations.verifyReceiptCredentialPresentation(receiptCredentialPresentation);
|
||||
} catch (VerificationFailedException _) {
|
||||
throw new BadRequestException("Receipt credential presentation verification failed");
|
||||
throw new NotAuthorizedException("Receipt credential presentation verification failed");
|
||||
}
|
||||
|
||||
final Instant receiptExpiration = Instant.ofEpochSecond(receiptCredentialPresentation.getReceiptExpirationTime());
|
||||
if (clock.instant().isAfter(receiptExpiration)) {
|
||||
throw new BadRequestException("Receipt is already expired");
|
||||
throw new NotAuthorizedException("Receipt is already expired");
|
||||
}
|
||||
|
||||
final long receiptLevel = receiptCredentialPresentation.getReceiptLevel();
|
||||
@@ -386,7 +386,7 @@ public class RegistrationController {
|
||||
final AccountIdentityResponse accountIdentityResponse = new AccountIdentityResponseBuilder(account).build();
|
||||
return new AccountCreationResponse(accountIdentityResponse, false);
|
||||
} catch (ReceiptAlreadyRedeemedException _) {
|
||||
throw new BadRequestException("Receipt already redeemed");
|
||||
throw new NotAuthorizedException("Receipt already redeemed");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+5
-1
@@ -171,7 +171,9 @@ public class SubscriptionController {
|
||||
buildDonationLevelsConfiguration(subscriptionConfiguration, oneTimeDonationConfiguration, badgeTranslator,
|
||||
acceptableLanguages),
|
||||
new BackupConfiguration(backupLevels, subscriptionConfiguration.getbackupFreeTierMediaDuration().toDays()),
|
||||
new LoginConfiguration(ReceiptLevel.LOGIN.getValue(), loginPurchaseConfiguration.playProductId(),
|
||||
new LoginConfiguration(ReceiptLevel.LOGIN.getValue(),
|
||||
loginPurchaseConfiguration.playProductId(),
|
||||
loginPurchaseConfiguration.playOptionId(),
|
||||
loginPurchaseConfiguration.appStoreProductId()),
|
||||
oneTimeDonationConfiguration.sepaMaximumEuros());
|
||||
}
|
||||
@@ -549,6 +551,8 @@ public class SubscriptionController {
|
||||
long level,
|
||||
@Schema(description = "The play billing productID associated with a Signal Login purchase")
|
||||
String playProductId,
|
||||
@Schema(description = "The play billing optionID to use to purchase a Signal Login")
|
||||
String playOptionId,
|
||||
@Schema(description = "The App Store productID associated with a Signal Login purchase")
|
||||
String appStoreProductId) {}
|
||||
|
||||
|
||||
+2
-1
@@ -14,6 +14,7 @@ import jakarta.validation.constraints.AssertTrue;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import javax.annotation.Nullable;
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
|
||||
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
|
||||
@@ -103,7 +104,7 @@ public class AccountAttributes {
|
||||
}
|
||||
|
||||
public Optional<byte[]> recoveryPassword() {
|
||||
return Optional.ofNullable(recoveryPassword);
|
||||
return Optional.ofNullable(recoveryPassword).filter(ArrayUtils::isNotEmpty);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
|
||||
+12
-2
@@ -18,6 +18,7 @@ import java.util.List;
|
||||
import java.util.stream.Stream;
|
||||
import javax.annotation.Nullable;
|
||||
import jakarta.validation.constraints.PositiveOrZero;
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
|
||||
import org.whispersystems.textsecuregcm.util.IdentityKeyAdapter;
|
||||
@@ -45,13 +46,15 @@ public record RegistrationRequest(@Schema(requiredMode = Schema.RequiredMode.NOT
|
||||
@Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED, description = """
|
||||
A base64-encoded receipt credential presentation that allows for redeeming a Signal Login.
|
||||
Must be provided if `sessionId` and `recoveryPassword` are not provided;
|
||||
must not be provided if `sessionId` or `recoveryPassword` is provided.
|
||||
must not be provided if `sessionId` or `recoveryPassword` is provided. Must not be
|
||||
provided if recovering a previously used account.
|
||||
""")
|
||||
@Nullable
|
||||
byte[] receiptCredentialPresentation,
|
||||
|
||||
@Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED, description = """
|
||||
A TOTP one-time password; required if recovering an account that has TOTP keys.
|
||||
A TOTP one-time password; required if recovering an account that has TOTP keys. Must
|
||||
not be provided if `receiptCredentialPresentation` is provided.
|
||||
""")
|
||||
@PositiveOrZero
|
||||
@Nullable
|
||||
@@ -142,4 +145,11 @@ public record RegistrationRequest(@Schema(requiredMode = Schema.RequiredMode.NOT
|
||||
deviceActivationRequest().pniPqLastResortPreKey().isPresent())
|
||||
.allMatch(present -> present == expectPresence);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
@AssertTrue
|
||||
@Schema(hidden = true)
|
||||
boolean isMfaAbsentWhenUsingReceipt() {
|
||||
return ArrayUtils.isEmpty(receiptCredentialPresentation) || totp == null;
|
||||
}
|
||||
}
|
||||
+73
-45
@@ -51,11 +51,12 @@ import org.signal.chat.account.GetCapabilitiesRequest;
|
||||
import org.signal.chat.account.GetCapabilitiesResponse;
|
||||
import org.signal.chat.account.GetEntitlementsRequest;
|
||||
import org.signal.chat.account.GetEntitlementsResponse;
|
||||
import org.signal.chat.account.ListTotpKeysRequest;
|
||||
import org.signal.chat.account.ListTotpKeysResponse;
|
||||
import org.signal.chat.account.ListMfaKeysRequest;
|
||||
import org.signal.chat.account.ListMfaKeysResponse;
|
||||
import org.signal.chat.account.ListMfaKeysResponse.MfaKeyMetadata.MfaKeyType;
|
||||
import org.signal.chat.account.RegistrationLockFailure;
|
||||
import org.signal.chat.account.RemoveTotpKeyRequest;
|
||||
import org.signal.chat.account.RemoveTotpKeyResponse;
|
||||
import org.signal.chat.account.RemoveMfaKeyRequest;
|
||||
import org.signal.chat.account.RemoveMfaKeyResponse;
|
||||
import org.signal.chat.account.ReserveUsernameHashRequest;
|
||||
import org.signal.chat.account.ReserveUsernameHashResponse;
|
||||
import org.signal.chat.account.SetDiscoverableByPhoneNumberRequest;
|
||||
@@ -64,8 +65,8 @@ import org.signal.chat.account.SetRegistrationLockRequest;
|
||||
import org.signal.chat.account.SetRegistrationLockResponse;
|
||||
import org.signal.chat.account.SetRegistrationRecoveryPasswordRequest;
|
||||
import org.signal.chat.account.SetRegistrationRecoveryPasswordResponse;
|
||||
import org.signal.chat.account.SetTotpKeyMetadataRequest;
|
||||
import org.signal.chat.account.SetTotpKeyMetadataResponse;
|
||||
import org.signal.chat.account.SetMfaKeyMetadataRequest;
|
||||
import org.signal.chat.account.SetMfaKeyMetadataResponse;
|
||||
import org.signal.chat.account.SetUsernameLinkRequest;
|
||||
import org.signal.chat.account.SetUsernameLinkResponse;
|
||||
import org.signal.chat.account.SetZkCredentialKeyRequest;
|
||||
@@ -104,10 +105,12 @@ import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.push.MessageTooLargeException;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.AnnotatedMfaKey;
|
||||
import org.whispersystems.textsecuregcm.storage.AnnotatedTotpKey;
|
||||
import org.whispersystems.textsecuregcm.storage.ChangeNumberManager;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
|
||||
import org.whispersystems.textsecuregcm.storage.PhoneNumberRecoveryPasswordsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.TooManyMfaKeysException;
|
||||
import org.whispersystems.textsecuregcm.storage.TooManyTotpKeysException;
|
||||
import org.whispersystems.textsecuregcm.storage.TotpKey;
|
||||
import org.whispersystems.textsecuregcm.storage.UsernameHashNotAvailableException;
|
||||
@@ -131,7 +134,7 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
|
||||
private final Clock clock;
|
||||
private final ChangeNumberManager changeNumberManager;
|
||||
|
||||
private static class TotpKeyNotFoundException extends NoStackTraceRuntimeException {
|
||||
private static class MfaKeyNotFoundException extends NoStackTraceRuntimeException {
|
||||
}
|
||||
|
||||
public AccountsGrpcService(final AccountsManager accountsManager,
|
||||
@@ -568,83 +571,108 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
|
||||
.setTotpParameters(toGrpcTotpParameters(pendingTotpKey.totpParameters()))
|
||||
.build())
|
||||
.build();
|
||||
} catch (final TooManyTotpKeysException e) {
|
||||
} catch (final TooManyTotpKeysException _) {
|
||||
return GenerateTotpKeyResponse.newBuilder()
|
||||
.setTooManyTotpKeys(FailedPrecondition.getDefaultInstance())
|
||||
.build();
|
||||
} catch (final TooManyMfaKeysException _) {
|
||||
return GenerateTotpKeyResponse.newBuilder()
|
||||
.setTooManyMfaKeys(FailedPrecondition.getDefaultInstance())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public ConfirmTotpKeyResponse confirmTotpKey(final ConfirmTotpKeyRequest request) {
|
||||
final Optional<Integer> maybeConfirmedTotpKeyId =
|
||||
accountsManager.confirmPendingTotpKey(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier(),
|
||||
request.getOneTimePassword(),
|
||||
clock.instant(),
|
||||
request.getMetadataCiphertext().toByteArray());
|
||||
try {
|
||||
final Optional<Byte> maybeConfirmedTotpKeyId =
|
||||
accountsManager.confirmPendingTotpKey(
|
||||
AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier(),
|
||||
request.getOneTimePassword(),
|
||||
clock.instant(),
|
||||
request.getMetadataCiphertext().toByteArray());
|
||||
|
||||
return maybeConfirmedTotpKeyId.map(keyId -> ConfirmTotpKeyResponse.newBuilder()
|
||||
.setKeyConfirmed(ConfirmTotpKeyResponse.KeyConfirmed.newBuilder()
|
||||
.setKeyId(keyId)
|
||||
.build())
|
||||
.build()).orElseGet(() -> ConfirmTotpKeyResponse.newBuilder()
|
||||
.setOneTimePasswordNotVerified(FailedPrecondition.getDefaultInstance())
|
||||
.build());
|
||||
return maybeConfirmedTotpKeyId.map(keyId -> ConfirmTotpKeyResponse.newBuilder()
|
||||
.setKeyConfirmed(ConfirmTotpKeyResponse.KeyConfirmed.newBuilder()
|
||||
.setKeyId(keyId)
|
||||
.build())
|
||||
.build()).orElseGet(() -> ConfirmTotpKeyResponse.newBuilder()
|
||||
.setOneTimePasswordNotVerified(FailedPrecondition.getDefaultInstance())
|
||||
.build());
|
||||
} catch (TooManyMfaKeysException _) {
|
||||
return ConfirmTotpKeyResponse.newBuilder()
|
||||
.setTooManyMfaKeys(FailedPrecondition.getDefaultInstance())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public ListTotpKeysResponse listTotpKeys(final ListTotpKeysRequest request) {
|
||||
final ListTotpKeysResponse.Builder responseBuilder = ListTotpKeysResponse.newBuilder();
|
||||
public ListMfaKeysResponse listMfaKeys(final ListMfaKeysRequest request) {
|
||||
final ListMfaKeysResponse.Builder responseBuilder = ListMfaKeysResponse.newBuilder();
|
||||
|
||||
getAuthenticatedAccount().getTotpKeys().forEach((keyId, totpKey) -> {
|
||||
assert totpKey.metadataCiphertext() != null;
|
||||
getAuthenticatedAccount().getMfaKeys().forEach((keyId, mfaKey) -> {
|
||||
assert mfaKey.metadataCiphertext() != null;
|
||||
|
||||
responseBuilder.putKeys(keyId, ListTotpKeysResponse.TotpKeyMetadata.newBuilder()
|
||||
.setMetadataCiphertext(ByteString.copyFrom(totpKey.metadataCiphertext()))
|
||||
.setTotpParameters(toGrpcTotpParameters(totpKey.totpKey().totpParameters()))
|
||||
.build());
|
||||
responseBuilder.putKeys(
|
||||
keyId,
|
||||
ListMfaKeysResponse.MfaKeyMetadata.newBuilder()
|
||||
.setMetadataCiphertext(ByteString.copyFrom(mfaKey.metadataCiphertext()))
|
||||
.setType(switch (mfaKey) {
|
||||
case AnnotatedTotpKey _ -> MfaKeyType.MFA_KEY_TYPE_TOTP;
|
||||
}).build());
|
||||
});
|
||||
|
||||
return responseBuilder.build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public SetTotpKeyMetadataResponse setTotpKeyMetadata(final SetTotpKeyMetadataRequest request) {
|
||||
public SetMfaKeyMetadataResponse setMfaKeyMetadata(final SetMfaKeyMetadataRequest request) {
|
||||
final byte keyId = validateMfaKeyId(request.getKeyId());
|
||||
|
||||
try {
|
||||
accountsManager.update(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier(), account -> {
|
||||
final Map<Integer, AnnotatedTotpKey> totpKeys = new HashMap<>(account.getTotpKeys());
|
||||
@Nullable final AnnotatedTotpKey existingKey = totpKeys.get(request.getKeyId());
|
||||
final Map<Byte, AnnotatedMfaKey> mfaKeys = new HashMap<>(account.getMfaKeys());
|
||||
@Nullable final AnnotatedMfaKey existingKey = mfaKeys.get(keyId);
|
||||
|
||||
if (existingKey == null) {
|
||||
throw new TotpKeyNotFoundException();
|
||||
throw new MfaKeyNotFoundException();
|
||||
}
|
||||
|
||||
totpKeys.put(request.getKeyId(),
|
||||
new AnnotatedTotpKey(existingKey.totpKey(), request.getMetadataCiphertext().toByteArray()));
|
||||
mfaKeys.put(keyId, existingKey.withMetadataCiphertext(request.getMetadataCiphertext().toByteArray()));
|
||||
|
||||
account.setTotpKeys(totpKeys);
|
||||
account.setMfaKeys(mfaKeys);
|
||||
});
|
||||
|
||||
return SetTotpKeyMetadataResponse.newBuilder()
|
||||
.setMetadataUpdated(SetTotpKeyMetadataResponse.MetadataUpdated.getDefaultInstance())
|
||||
return SetMfaKeyMetadataResponse.newBuilder()
|
||||
.setMetadataUpdated(SetMfaKeyMetadataResponse.MetadataUpdated.getDefaultInstance())
|
||||
.build();
|
||||
} catch (final TotpKeyNotFoundException _) {
|
||||
return SetTotpKeyMetadataResponse.newBuilder()
|
||||
} catch (final MfaKeyNotFoundException _) {
|
||||
return SetMfaKeyMetadataResponse.newBuilder()
|
||||
.setKeyNotFound(NotFound.getDefaultInstance())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public RemoveTotpKeyResponse removeTotpKey(final RemoveTotpKeyRequest request) {
|
||||
accountsManager.update(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier(), account -> {
|
||||
final Map<Integer, AnnotatedTotpKey> totpKeys = new HashMap<>(account.getTotpKeys());
|
||||
totpKeys.remove(request.getKeyId());
|
||||
public RemoveMfaKeyResponse removeMfaKey(final RemoveMfaKeyRequest request) {
|
||||
final byte keyId = validateMfaKeyId(request.getKeyId());
|
||||
|
||||
account.setTotpKeys(totpKeys);
|
||||
accountsManager.update(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier(), account -> {
|
||||
final Map<Byte, AnnotatedMfaKey> mfaKeys = new HashMap<>(account.getMfaKeys());
|
||||
mfaKeys.remove(keyId);
|
||||
|
||||
account.setMfaKeys(mfaKeys);
|
||||
});
|
||||
|
||||
return RemoveTotpKeyResponse.getDefaultInstance();
|
||||
return RemoveMfaKeyResponse.getDefaultInstance();
|
||||
}
|
||||
|
||||
private byte validateMfaKeyId(final int keyId) {
|
||||
if (keyId < 0 || keyId > Account.MAX_MFA_KEY_ID) {
|
||||
throw GrpcExceptions.invalidArguments("MFA key ID out of range");
|
||||
}
|
||||
|
||||
return (byte) keyId;
|
||||
}
|
||||
|
||||
private static TotpParameters toGrpcTotpParameters(final org.whispersystems.textsecuregcm.storage.TotpParameters totpParameters) {
|
||||
|
||||
+2
-2
@@ -62,7 +62,7 @@ public class ErrorMappingInterceptor implements ServerInterceptor {
|
||||
}
|
||||
case IllegalStateException e -> {
|
||||
ImpossibleEvents.logImpossible(log, e.getMessage(), e);
|
||||
yield GrpcExceptions.unavailable(e.getMessage());
|
||||
yield GrpcExceptions.unavailable();
|
||||
}
|
||||
case null -> {
|
||||
log.error("RPC {} finished with status UNKNOWN: {}",
|
||||
@@ -72,7 +72,7 @@ public class ErrorMappingInterceptor implements ServerInterceptor {
|
||||
default -> {
|
||||
log.error("RPC {} finished with status UNKNOWN",
|
||||
call.getMethodDescriptor().getFullMethodName(), status.getCause());
|
||||
yield GrpcExceptions.unavailable(status.getCause().getMessage());
|
||||
yield GrpcExceptions.unavailable();
|
||||
}
|
||||
};
|
||||
super.close(statusException.getStatus(), statusException.getTrailers());
|
||||
|
||||
+1
@@ -95,6 +95,7 @@ public class ProductConfigurationGrpcService extends SimpleProductConfigurationG
|
||||
return LoginConfiguration.newBuilder()
|
||||
.setLevel(ReceiptLevel.LOGIN.getValue())
|
||||
.setPlayProductId(loginPurchaseConfiguration.playProductId())
|
||||
.setPlayOptionId(loginPurchaseConfiguration.playOptionId())
|
||||
.setAppStoreProductId(loginPurchaseConfiguration.appStoreProductId())
|
||||
.build();
|
||||
}
|
||||
|
||||
@@ -16,11 +16,11 @@ import java.util.HexFormat;
|
||||
import java.util.Optional;
|
||||
import org.bouncycastle.crypto.digests.TupleHash;
|
||||
import org.signal.chat.common.S3UploadForm;
|
||||
import org.signal.chat.profile.AccountInfo;
|
||||
import org.signal.chat.profile.GetExpiringProfileKeyCredentialResult;
|
||||
import org.signal.chat.profile.LegacyProfileResult;
|
||||
import org.signal.chat.profile.ProfileResult;
|
||||
import org.signal.chat.profile.ProfileResultOrBuilder;
|
||||
import org.signal.chat.profile.LegacyProfileResult;
|
||||
import org.signal.chat.profile.AccountInfo;
|
||||
import org.signal.libsignal.protocol.ServiceId;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.VerificationFailedException;
|
||||
@@ -30,7 +30,6 @@ import org.signal.libsignal.zkgroup.profiles.ProfileKeyCredentialRequest;
|
||||
import org.signal.libsignal.zkgroup.profiles.ServerZkProfileOperations;
|
||||
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessChecksum;
|
||||
import org.whispersystems.textsecuregcm.badges.ProfileBadgeConverter;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
|
||||
@@ -60,12 +59,20 @@ public class ProfileGrpcHelper {
|
||||
final VersionedProfileV1 v1Profile = maybeV1Profile.get();
|
||||
|
||||
final LegacyProfileResult.Builder builder = LegacyProfileResult.newBuilder()
|
||||
.setAccountInfo(buildAccountInfo(profileBadgeConverter, account))
|
||||
.setName(ByteString.copyFrom(v1Profile.name()))
|
||||
.setAbout(ByteString.copyFrom(v1Profile.about()))
|
||||
.setAboutEmoji(ByteString.copyFrom(v1Profile.aboutEmoji()))
|
||||
.setPhoneNumberSharing(ByteString.copyFrom(v1Profile.phoneNumberSharing()));
|
||||
.setAccountInfo(buildAccountInfo(profileBadgeConverter, account));
|
||||
|
||||
if (v1Profile.name() != null) {
|
||||
builder.setName(ByteString.copyFrom(v1Profile.name()));
|
||||
}
|
||||
if (v1Profile.about() != null) {
|
||||
builder.setAbout(ByteString.copyFrom(v1Profile.about()));
|
||||
}
|
||||
if (v1Profile.aboutEmoji() != null) {
|
||||
builder.setAboutEmoji(ByteString.copyFrom(v1Profile.aboutEmoji()));
|
||||
}
|
||||
if (v1Profile.phoneNumberSharing() != null) {
|
||||
builder.setPhoneNumberSharing(ByteString.copyFrom(v1Profile.phoneNumberSharing()));
|
||||
}
|
||||
if (v1Profile.avatar() != null) {
|
||||
builder.setAvatar(v1Profile.avatar());
|
||||
}
|
||||
|
||||
+33
-2
@@ -31,6 +31,8 @@ import org.signal.chat.profile.SetProfileRequest;
|
||||
import org.signal.chat.profile.SetProfileResponse;
|
||||
import org.signal.chat.profile.SetProfileResult;
|
||||
import org.signal.chat.profile.SetProfileV1Request.AvatarChange;
|
||||
import org.signal.chat.profile.SetV1AvatarRequest;
|
||||
import org.signal.chat.profile.SetV1AvatarResponse;
|
||||
import org.signal.chat.profile.SimpleProfileGrpc;
|
||||
import org.signal.libsignal.protocol.ServiceId;
|
||||
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
|
||||
@@ -107,7 +109,7 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
|
||||
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
|
||||
|
||||
final Account account = accountsManager.getByAccountIdentifier(authenticatedDevice.accountIdentifier())
|
||||
.orElseThrow(() -> GrpcExceptions.invalidArguments("Account not found"));
|
||||
.orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials"));
|
||||
|
||||
if (!account.hasCapability(DeviceCapability.PROFILES_V2)) {
|
||||
return SetProfileResponse.newBuilder()
|
||||
@@ -224,7 +226,7 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
|
||||
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
|
||||
|
||||
final Account account = accountsManager.getByAccountIdentifier(authenticatedDevice.accountIdentifier())
|
||||
.orElseThrow(() -> GrpcExceptions.invalidCredentials("account not found"));
|
||||
.orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials"));
|
||||
|
||||
if (account.getZkCredentialKey().isEmpty()) {
|
||||
return GetAvatarCredentialsResponse.newBuilder()
|
||||
@@ -275,6 +277,35 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
|
||||
.orElseGet(() -> GetProfileResponse.newBuilder().setNotFound(NotFound.getDefaultInstance()).build());
|
||||
}
|
||||
|
||||
@Override
|
||||
public SetV1AvatarResponse setV1Avatar(final SetV1AvatarRequest request) {
|
||||
|
||||
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
|
||||
|
||||
final String version = request.getVersion();
|
||||
final Optional<VersionedProfileV1> maybeV1Profile = profilesManager.getV1(authenticatedDevice.accountIdentifier(),
|
||||
version);
|
||||
|
||||
if (maybeV1Profile.isEmpty() && request.getCommitment().isEmpty()) {
|
||||
throw GrpcExceptions.fieldViolation("commitment", "Commitment is required for new profile versions");
|
||||
}
|
||||
|
||||
maybeV1Profile.map(VersionedProfileV1::avatar).filter(a -> a.startsWith("profiles/"))
|
||||
.ifPresent(profilesManager::deleteAvatar);
|
||||
|
||||
final byte[] commitment = maybeV1Profile.map(VersionedProfileV1::commitment).orElseGet(request.getCommitment()::toByteArray);
|
||||
|
||||
final String updateAvatarObjectName = ProfileHelper.generateAvatarObjectName();
|
||||
|
||||
profilesManager.setV1Avatar(authenticatedDevice.accountIdentifier(), version, updateAvatarObjectName, commitment);
|
||||
|
||||
return SetV1AvatarResponse.newBuilder()
|
||||
.setForm(ProfileGrpcHelper.generateAvatarUploadForm(updateAvatarObjectName,
|
||||
ProfileHelper.MAX_PROFILE_AVATAR_SIZE_BYTES,
|
||||
policyGenerator, clock))
|
||||
.build();
|
||||
}
|
||||
|
||||
private Optional<Account> validateRateLimitAndGetAccount(final UUID requesterUuid,
|
||||
final ServiceIdentifier targetIdentifier) throws RateLimitExceededException {
|
||||
rateLimiters.getProfileLimiter().validate(requesterUuid);
|
||||
|
||||
+22
-42
@@ -140,9 +140,8 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
|
||||
|
||||
subscriptionManager.updateSubscriber(subscriberCredentials, creationPermitted);
|
||||
return UpdateSubscriberResponse.newBuilder().setSuccess(Empty.getDefaultInstance()).build();
|
||||
} catch (final SubscriptionForbiddenException e) {
|
||||
return UpdateSubscriberResponse.newBuilder().setSubscriberIdMismatch(
|
||||
FailedUnidentifiedAuthorization.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
|
||||
} catch (final SubscriptionForbiddenException _) {
|
||||
throw GrpcExceptions.invalidArguments("subscriber-ids must be randomly generated");
|
||||
} catch (SubscriberIdCreationNotPermittedException _) {
|
||||
if (request.getDonationPermit().isEmpty()) {
|
||||
throw GrpcExceptions.invalidArguments("donation permit is required to create a subscriber ID");
|
||||
@@ -206,11 +205,8 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
|
||||
return CreatePaymentMethodResponse.newBuilder().setResult(
|
||||
CreatePaymentMethodResponse.CreatePaymentMethodResult.newBuilder().setClientSecret(token)
|
||||
.setPaymentProvider(customerAwareSubscriptionPaymentProcessor.getProvider().toProto()).build()).build();
|
||||
} catch (final SubscriptionNotFoundException e) {
|
||||
} catch (final SubscriptionNotFoundException | SubscriptionForbiddenException _) {
|
||||
return CreatePaymentMethodResponse.newBuilder().setSubscriberNotFound(NotFound.newBuilder()).build();
|
||||
} catch (final SubscriptionForbiddenException e) {
|
||||
return CreatePaymentMethodResponse.newBuilder().setSubscriberIdMismatch(
|
||||
FailedUnidentifiedAuthorization.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
|
||||
} catch (final SubscriptionProcessorConflictException e) {
|
||||
return CreatePaymentMethodResponse.newBuilder().setSubscriptionProcessorConflict(
|
||||
FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
|
||||
@@ -231,12 +227,9 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
|
||||
return CreatePayPalPaymentMethodResponse.newBuilder().setResult(
|
||||
CreatePayPalPaymentMethodResponse.CreatePayPalPaymentMethodResult.newBuilder()
|
||||
.setApprovalUrl(details.approvalUrl()).setToken(details.billingAgreementToken()).build()).build();
|
||||
} catch (final SubscriptionNotFoundException e) {
|
||||
} catch (final SubscriptionNotFoundException | SubscriptionForbiddenException _) {
|
||||
return CreatePayPalPaymentMethodResponse.newBuilder().setSubscriberNotFound(NotFound.newBuilder().build())
|
||||
.build();
|
||||
} catch (final SubscriptionForbiddenException e) {
|
||||
return CreatePayPalPaymentMethodResponse.newBuilder().setSubscriberIdMismatch(
|
||||
FailedUnidentifiedAuthorization.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
|
||||
} catch (final SubscriptionProcessorConflictException e) {
|
||||
return CreatePayPalPaymentMethodResponse.newBuilder().setSubscriptionProcessorConflict(
|
||||
FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
|
||||
@@ -267,22 +260,20 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
|
||||
};
|
||||
|
||||
final Subscriptions.Record record = subscriptionManager.getSubscriber(subscriberCredentials);
|
||||
return record.getProcessorCustomer().map(
|
||||
processorCustomer -> setDefaultPaymentMethodForCustomer(manager, processorCustomer, paymentMethodId,
|
||||
record.subscriptionId)).orElseGet(() ->
|
||||
return record.getProcessorCustomer()
|
||||
.map(processorCustomer ->
|
||||
setDefaultPaymentMethodForCustomer(manager, processorCustomer, paymentMethodId, record.subscriptionId))
|
||||
// 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
|
||||
SetDefaultPaymentMethodResponse.newBuilder().setPaymentMethodNotSetUp(FailedPrecondition.newBuilder().build())
|
||||
.orElseGet(() -> SetDefaultPaymentMethodResponse.newBuilder()
|
||||
.setPaymentMethodNotSetUp(FailedPrecondition.newBuilder().build())
|
||||
.build());
|
||||
} catch (final SubscriptionNotFoundException e) {
|
||||
} catch (final SubscriptionNotFoundException | SubscriptionForbiddenException _) {
|
||||
return SetDefaultPaymentMethodResponse.newBuilder().setSubscriberNotFound(NotFound.newBuilder().build()).build();
|
||||
} catch (final SubscriptionForbiddenException e) {
|
||||
return SetDefaultPaymentMethodResponse.newBuilder().setSubscriberIdMismatch(
|
||||
FailedUnidentifiedAuthorization.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
|
||||
} catch (final SubscriptionProcessorConflictException e) {
|
||||
} catch (final SubscriptionProcessorConflictException _) {
|
||||
return SetDefaultPaymentMethodResponse.newBuilder()
|
||||
.setSubscriptionProcessorConflict(
|
||||
FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
|
||||
.setPaymentMethodNotSetUp(FailedPrecondition.newBuilder().build())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -310,16 +301,14 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
|
||||
request.getSubscriberId().toByteArray(), clock);
|
||||
try {
|
||||
final Subscriptions.Record record = subscriptionManager.getSubscriber(subscriberCredentials);
|
||||
return record.getProcessorCustomer().map(
|
||||
processorCustomer -> setSubscriptionLevelForCustomer(processorCustomer, subscriberCredentials, record,
|
||||
request)).orElseGet(() -> SetSubscriptionLevelResponse.newBuilder()
|
||||
.setPaymentMethodNotSetUp(FailedPrecondition.newBuilder().build()).build());
|
||||
return record.getProcessorCustomer().map(processorCustomer ->
|
||||
setSubscriptionLevelForCustomer(processorCustomer, subscriberCredentials, record, request))
|
||||
.orElseGet(() -> SetSubscriptionLevelResponse.newBuilder()
|
||||
.setPaymentMethodNotSetUp(FailedPrecondition.newBuilder().build())
|
||||
.build());
|
||||
|
||||
} catch (final SubscriptionNotFoundException e) {
|
||||
} catch (final SubscriptionNotFoundException | SubscriptionForbiddenException _) {
|
||||
return SetSubscriptionLevelResponse.newBuilder().setSubscriberNotFound(NotFound.newBuilder().build()).build();
|
||||
} catch (final SubscriptionForbiddenException e) {
|
||||
return SetSubscriptionLevelResponse.newBuilder().setSubscriberIdMismatch(
|
||||
FailedUnidentifiedAuthorization.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -394,11 +383,8 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
|
||||
};
|
||||
return SetIapSubscriptionResponse.newBuilder()
|
||||
.setSuccess(SetIapSubscriptionResponse.SetIapSubscriptionResult.newBuilder().setLevel(level).build()).build();
|
||||
} catch (final SubscriptionNotFoundException e) {
|
||||
} catch (final SubscriptionNotFoundException | SubscriptionForbiddenException _) {
|
||||
return SetIapSubscriptionResponse.newBuilder().setSubscriberNotFound(NotFound.newBuilder().build()).build();
|
||||
} catch (final SubscriptionForbiddenException e) {
|
||||
return SetIapSubscriptionResponse.newBuilder().setSubscriberIdMismatch(
|
||||
FailedUnidentifiedAuthorization.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
|
||||
} catch (final SubscriptionProcessorConflictException e) {
|
||||
return SetIapSubscriptionResponse.newBuilder().setSubscriptionProcessorConflict(
|
||||
FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
|
||||
@@ -422,12 +408,9 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
|
||||
.map(SubscriptionsGrpcService::buildSubscriptionInformationResponse).orElseGet(
|
||||
() -> GetSubscriptionInformationResponse.newBuilder().setNoSubscription(Empty.getDefaultInstance())
|
||||
.build());
|
||||
} catch (final SubscriptionNotFoundException e) {
|
||||
} catch (final SubscriptionNotFoundException | SubscriptionForbiddenException _) {
|
||||
return GetSubscriptionInformationResponse.newBuilder().setSubscriberNotFound(NotFound.newBuilder().build())
|
||||
.build();
|
||||
} catch (final SubscriptionForbiddenException e) {
|
||||
return GetSubscriptionInformationResponse.newBuilder().setSubscriberIdMismatch(
|
||||
FailedUnidentifiedAuthorization.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -487,11 +470,8 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
|
||||
} catch (final SubscriptionReceiptAlreadyRedeemedException e) {
|
||||
return GetReceiptCredentialsResponse.newBuilder().setAlreadyRedeemed(FailedPrecondition.newBuilder().build())
|
||||
.build();
|
||||
} catch (final SubscriptionNotFoundException e) {
|
||||
} catch (final SubscriptionNotFoundException | SubscriptionForbiddenException _) {
|
||||
return GetReceiptCredentialsResponse.newBuilder().setSubscriberNotFound(NotFound.newBuilder().build()).build();
|
||||
} catch (final SubscriptionForbiddenException e) {
|
||||
return GetReceiptCredentialsResponse.newBuilder().setSubscriberIdMismatch(
|
||||
FailedUnidentifiedAuthorization.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,26 +5,21 @@
|
||||
package org.whispersystems.textsecuregcm.grpc.net;
|
||||
|
||||
import java.net.SocketAddress;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class OmnibusRouter {
|
||||
|
||||
public record OmnibusRoute(String prefix, SocketAddress backend) {}
|
||||
|
||||
private final List<OmnibusRoute> prefixRoutes;
|
||||
private final Map<String, SocketAddress> routes;
|
||||
private final SocketAddress defaultBackend;
|
||||
|
||||
public OmnibusRouter(final List<OmnibusRoute> prefixRoutes, final SocketAddress defaultBackend) {
|
||||
this.prefixRoutes = prefixRoutes;
|
||||
public OmnibusRouter(final Map<String, SocketAddress> routes, final SocketAddress defaultBackend) {
|
||||
this.routes = routes;
|
||||
this.defaultBackend = defaultBackend;
|
||||
}
|
||||
|
||||
SocketAddress match(final String path) {
|
||||
for (final OmnibusRoute route : prefixRoutes) {
|
||||
if (path.startsWith(route.prefix)) {
|
||||
return route.backend;
|
||||
}
|
||||
}
|
||||
return defaultBackend;
|
||||
SocketAddress match(final String fullPath) {
|
||||
final int queryIndex = fullPath.indexOf('?');
|
||||
final String path = queryIndex >= 0 ? fullPath.substring(0, queryIndex) : fullPath;
|
||||
return routes.getOrDefault(path, defaultBackend);
|
||||
}
|
||||
}
|
||||
+3
-1
@@ -4,6 +4,7 @@
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.grpc.net;
|
||||
|
||||
import com.google.common.net.InetAddresses;
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.channel.ChannelInboundHandlerAdapter;
|
||||
import io.netty.handler.codec.haproxy.HAProxyMessage;
|
||||
@@ -30,7 +31,8 @@ class ProxyMessageAttributeSetterHandler extends ChannelInboundHandlerAdapter {
|
||||
try {
|
||||
final String sourceAddress = proxyMessage.sourceAddress();
|
||||
if (sourceAddress != null) {
|
||||
ctx.channel().attr(PROXY_REMOTE_ADDRESS).set(InetAddress.getByName(sourceAddress));
|
||||
// Assume that the server has been configured to only allow access from a trusted PPv2 provider
|
||||
ctx.channel().attr(PROXY_REMOTE_ADDRESS).set(InetAddresses.forString(sourceAddress));
|
||||
} else {
|
||||
logger.warn("PROXY protocol message has no source address");
|
||||
}
|
||||
|
||||
+16
-2
@@ -5,17 +5,17 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.jetty;
|
||||
|
||||
import org.eclipse.jetty.http.HttpHeader;
|
||||
import org.eclipse.jetty.http2.server.HTTP2ServerConnectionFactory;
|
||||
import org.eclipse.jetty.server.ConnectionFactory;
|
||||
import org.eclipse.jetty.server.Connector;
|
||||
import org.eclipse.jetty.server.ForwardedRequestCustomizer;
|
||||
import org.eclipse.jetty.server.HttpConfiguration;
|
||||
import org.eclipse.jetty.server.HttpConnectionFactory;
|
||||
import org.eclipse.jetty.util.component.Container;
|
||||
import org.eclipse.jetty.util.component.LifeCycle;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.binder.jetty.JettyConnectionMetrics;
|
||||
|
||||
/**
|
||||
* Uses {@link Container.Listener} to update {@link org.eclipse.jetty.server.HttpConfiguration}
|
||||
@@ -38,6 +38,20 @@ public class JettyHttpConfigurationCustomizer implements Container.Listener, Lif
|
||||
// see https://github.com/jetty/jetty.project/issues/1891
|
||||
logger.info("setNotifyRemoteAsyncErrors(false) for {}", cf);
|
||||
httpConfiguration.setNotifyRemoteAsyncErrors(false);
|
||||
|
||||
httpConfiguration.getCustomizers().stream()
|
||||
.filter(ForwardedRequestCustomizer.class::isInstance)
|
||||
.map(ForwardedRequestCustomizer.class::cast)
|
||||
.forEach(forwardedRequestCustomizer -> {
|
||||
// If this http configuration supports using proxy-supplied headers, only use X-Forwarded-For
|
||||
|
||||
// Disable all headers except for 'Forwarded'
|
||||
forwardedRequestCustomizer.setForwardedOnly(true);
|
||||
// Disable 'Forwarded'
|
||||
forwardedRequestCustomizer.setForwardedHeader(null);
|
||||
// Enable 'X-Forwarded-For'
|
||||
forwardedRequestCustomizer.setForwardedForHeader(HttpHeader.X_FORWARDED_FOR.toString());
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
-36
@@ -1,36 +0,0 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.mappers;
|
||||
|
||||
import io.dropwizard.jersey.errors.ErrorMessage;
|
||||
import io.grpc.StatusRuntimeException;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import jakarta.ws.rs.ext.ExceptionMapper;
|
||||
import jakarta.ws.rs.ext.Provider;
|
||||
|
||||
@Provider
|
||||
public class GrpcStatusRuntimeExceptionMapper implements ExceptionMapper<StatusRuntimeException> {
|
||||
|
||||
@Override
|
||||
public Response toResponse(final StatusRuntimeException exception) {
|
||||
int httpCode = switch (exception.getStatus().getCode()) {
|
||||
case OK -> 200;
|
||||
case INVALID_ARGUMENT, FAILED_PRECONDITION, OUT_OF_RANGE -> 400;
|
||||
case UNAUTHENTICATED -> 401;
|
||||
case PERMISSION_DENIED -> 403;
|
||||
case NOT_FOUND -> 404;
|
||||
case ALREADY_EXISTS, ABORTED -> 409;
|
||||
case CANCELLED -> 499;
|
||||
case UNKNOWN, UNIMPLEMENTED, DEADLINE_EXCEEDED, RESOURCE_EXHAUSTED, INTERNAL, UNAVAILABLE, DATA_LOSS -> 500;
|
||||
};
|
||||
|
||||
return Response.status(httpCode)
|
||||
.entity(new ErrorMessage(httpCode, exception.getMessage()))
|
||||
.type(MediaType.APPLICATION_JSON_TYPE)
|
||||
.build();
|
||||
}
|
||||
}
|
||||
@@ -22,12 +22,15 @@ import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.IntStream;
|
||||
import javax.annotation.Nullable;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
@@ -46,6 +49,8 @@ import org.whispersystems.textsecuregcm.util.ZkCredentialPublicKeyAdapter;
|
||||
@JsonFilter("Account")
|
||||
public class Account {
|
||||
|
||||
public static final int MAX_MFA_KEY_ID = Byte.MAX_VALUE;
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(Account.class);
|
||||
|
||||
@JsonProperty
|
||||
@@ -160,8 +165,8 @@ public class Account {
|
||||
@Nullable
|
||||
private TotpKey pendingTotpKey;
|
||||
|
||||
@JsonProperty("totp")
|
||||
private Map<Integer, AnnotatedTotpKey> totpKeys = Collections.emptyMap();
|
||||
@JsonProperty("mfa")
|
||||
private Map<Byte, AnnotatedMfaKey> mfaKeys = Collections.emptyMap();
|
||||
|
||||
@JsonIgnore
|
||||
private boolean stale;
|
||||
@@ -470,10 +475,11 @@ public class Account {
|
||||
}
|
||||
}
|
||||
|
||||
public void setRegistrationLock(final String registrationLock, final String registrationLockSalt) {
|
||||
public void setRegistrationLock(@Nullable final String registrationLock, @Nullable final String registrationLockSalt) {
|
||||
requireNotStale();
|
||||
|
||||
if (number == null) {
|
||||
// Accounts without a phone number can't set a registration lock
|
||||
if (number == null && (registrationLock != null || registrationLockSalt != null)) {
|
||||
throw new IllegalArgumentException("Cannot set registration lock on account with no phone number");
|
||||
}
|
||||
|
||||
@@ -668,23 +674,25 @@ public class Account {
|
||||
return Optional.ofNullable(pendingTotpKey);
|
||||
}
|
||||
|
||||
public int getNextTotpKeyId() {
|
||||
public byte getNextMfaKeyId() {
|
||||
requireNotStale();
|
||||
|
||||
return totpKeys.keySet().stream()
|
||||
.mapToInt(i -> i)
|
||||
.max()
|
||||
.orElse(-1) + 1;
|
||||
final Set<Byte> usedKeys = new HashSet<>(mfaKeys.keySet());
|
||||
|
||||
return (byte) IntStream.range(0, MAX_MFA_KEY_ID + 1)
|
||||
.filter(b -> !usedKeys.contains((byte) b))
|
||||
.findFirst()
|
||||
.orElseThrow(IllegalStateException::new);
|
||||
}
|
||||
|
||||
public Map<Integer, AnnotatedTotpKey> getTotpKeys() {
|
||||
public Map<Byte, AnnotatedMfaKey> getMfaKeys() {
|
||||
requireNotStale();
|
||||
return totpKeys;
|
||||
return mfaKeys;
|
||||
}
|
||||
|
||||
public void setTotpKeys(final Map<Integer, AnnotatedTotpKey> totpKeys) {
|
||||
public void setMfaKeys(final Map<Byte, AnnotatedMfaKey> mfaKeys) {
|
||||
requireNotStale();
|
||||
this.totpKeys = totpKeys;
|
||||
this.mfaKeys = mfaKeys;
|
||||
}
|
||||
|
||||
public void markStale() {
|
||||
|
||||
+17
-34
@@ -10,9 +10,6 @@ import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import org.whispersystems.textsecuregcm.util.ThrowingSupplier;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
|
||||
@@ -47,15 +44,12 @@ public class AccountLockManager {
|
||||
///
|
||||
/// @param phoneNumberIdentifiers the phone number identifiers for which to acquire a distributed, pessimistic lock
|
||||
/// @param task the task to execute once locks have been acquired
|
||||
/// @param lockAcquisitionExecutor the executor on which to run blocking lock acquire/release tasks. this executor
|
||||
/// should not use virtual threads.
|
||||
///
|
||||
/// @return the value returned by the given {@code task}
|
||||
///
|
||||
/// @throws E if an exception is thrown by the given {@code task}
|
||||
public <V, E extends Exception> V withLock(final Set<UUID> phoneNumberIdentifiers,
|
||||
final ThrowingSupplier<V, E> task,
|
||||
final Executor lockAcquisitionExecutor) throws E {
|
||||
final ThrowingSupplier<V, E> task) throws E {
|
||||
|
||||
if (phoneNumberIdentifiers.isEmpty()) {
|
||||
throw new IllegalArgumentException("List of PNIs to lock must not be empty");
|
||||
@@ -64,30 +58,22 @@ public class AccountLockManager {
|
||||
final List<LockItem> lockItems = new ArrayList<>(phoneNumberIdentifiers.size());
|
||||
|
||||
try {
|
||||
// Offload the acquire/release tasks to the dedicated lock acquisition executor. The lock client performs blocking
|
||||
// operations while holding locks which forces thread pinning when this method runs on a virtual thread.
|
||||
// https://github.com/awslabs/amazon-dynamodb-lock-client/issues/97
|
||||
CompletableFuture.runAsync(() -> {
|
||||
for (final UUID pni : phoneNumberIdentifiers) {
|
||||
try {
|
||||
lockItems.add(lockClient.acquireLock(AcquireLockOptions.builder(pni.toString())
|
||||
.withAcquireReleasedLocksConsistently(true)
|
||||
.build()));
|
||||
} catch (final InterruptedException e) {
|
||||
throw new CompletionException(e);
|
||||
}
|
||||
for (final UUID pni : phoneNumberIdentifiers) {
|
||||
try {
|
||||
lockItems.add(lockClient.acquireLock(AcquireLockOptions.builder(pni.toString())
|
||||
.withAcquireReleasedLocksConsistently(true)
|
||||
.build()));
|
||||
} catch (final InterruptedException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}, lockAcquisitionExecutor).join();
|
||||
|
||||
}
|
||||
return task.get();
|
||||
} finally {
|
||||
CompletableFuture.runAsync(() -> {
|
||||
for (final LockItem lockItem : lockItems) {
|
||||
lockClient.releaseLock(ReleaseLockOptions.builder(lockItem)
|
||||
.withBestEffort(true)
|
||||
.build());
|
||||
}
|
||||
}, lockAcquisitionExecutor).join();
|
||||
for (final LockItem lockItem : lockItems) {
|
||||
lockClient.releaseLock(ReleaseLockOptions.builder(lockItem)
|
||||
.withBestEffort(true)
|
||||
.build());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -104,15 +90,12 @@ public class AccountLockManager {
|
||||
///
|
||||
/// @param account the account for which to acquire a distributed, pessimistic lock
|
||||
/// @param task the task to execute once locks have been acquired
|
||||
/// @param lockAcquisitionExecutor the executor on which to run blocking lock acquire/release tasks. this executor
|
||||
/// should not use virtual threads.
|
||||
///
|
||||
/// @return the value returned by the given {@code task}
|
||||
///
|
||||
/// @throws E if an exception is thrown by the given {@code task}
|
||||
public <V, E extends Exception> V withSingleAccountLock(Account account,
|
||||
final ThrowingSupplier<V, E> task,
|
||||
final Executor lockAcquisitionExecutor) throws E {
|
||||
return withLock(Set.of(account.getPhoneNumberIdentifier().orElse(account.getAccountIdentifier())), task, lockAcquisitionExecutor);
|
||||
public <V, E extends Exception> V withSingleAccountLock(final Account account,
|
||||
final ThrowingSupplier<V, E> task) throws E {
|
||||
return withLock(Set.of(account.getPhoneNumberIdentifier().orElse(account.getAccountIdentifier())), task);
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,6 @@ package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static java.util.Objects.requireNonNull;
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
import static org.whispersystems.textsecuregcm.util.Util.getAlternateForms;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectWriter;
|
||||
@@ -339,12 +338,18 @@ public class Accounts {
|
||||
// The account was already deleted, and we don't allow re-registering with the same receipt
|
||||
.orElseThrow(ReceiptAlreadyRedeemedException::new);
|
||||
|
||||
// If the account recovery password in the request matches the existing account, this is likely a client retry,
|
||||
// and we continue to allow for idempotency, otherwise this is an attempt to double-redeem a receipt
|
||||
final boolean isRetry = existingAccount.getAccountRecoveryPassword()
|
||||
final boolean accountRecoveryPasswordMatches = existingAccount.getAccountRecoveryPassword()
|
||||
.map(arp -> PhoneNumberRecoveryPasswordsManager.verify(arp, accountRecoveryPasswordInRequest))
|
||||
.orElse(false);
|
||||
|
||||
// Determine if this request is safe to idempotently succeed. It's safe if:
|
||||
// - The account recovery password in the request matches the existing account's
|
||||
// - The existing account does not have any MFA keys. If MFA keys were added to the account the caller should
|
||||
// have used numberless account recovery rather than using their original receipt
|
||||
//
|
||||
// If either of these conditions are not met, the caller is incorrectly using an already redeemed receipt.
|
||||
final boolean isRetry = accountRecoveryPasswordMatches && existingAccount.getMfaKeys().isEmpty();
|
||||
|
||||
if (!isRetry) {
|
||||
throw new ReceiptAlreadyRedeemedException();
|
||||
}
|
||||
@@ -410,6 +415,10 @@ public class Accounts {
|
||||
accountToCreate.setZkCredentialKey(existingAccount.getZkCredentialKey().orElse(null));
|
||||
accountToCreate.setZkCredentialKeyRotationId(existingAccount.getZkCredentialKeyRotationId());
|
||||
|
||||
// Carry over any existing MFA keys to the new account; we don't need to copy the pending TOTP key since that's
|
||||
// just a temporary holding place for essentially ephemeral data
|
||||
accountToCreate.setMfaKeys(new HashMap<>(existingAccount.getMfaKeys()));
|
||||
|
||||
final List<TransactWriteItem> writeItems = new ArrayList<>();
|
||||
|
||||
// If we're reclaiming an account that already has a username, we'd like to give the re-registering client
|
||||
@@ -464,7 +473,7 @@ public class Accounts {
|
||||
&& accountToCreate.getNumber().isPresent()) {
|
||||
final String existingAccountNumber = existingAccount.getNumber().get();
|
||||
final String accountToCreateNumber = accountToCreate.getNumber().get();
|
||||
if (getAlternateForms(existingAccountNumber).contains(accountToCreateNumber)) {
|
||||
if (Util.getAlternateForms(existingAccountNumber).contains(accountToCreateNumber)) {
|
||||
final AttributeValue uuidAttr = AttributeValues.fromUUID(existingAccount.getAccountIdentifier());
|
||||
final AttributeValue numberAttr = AttributeValues.fromString(accountToCreateNumber);
|
||||
final TransactWriteItem phoneNumberConstraintPut = buildConstraintTablePutIfAbsent(
|
||||
@@ -1090,7 +1099,7 @@ public class Accounts {
|
||||
setClauses.add("#number = :number");
|
||||
|
||||
final MembershipExpression membershipExpression = maybeExpectedExistingE164
|
||||
.map(e164 -> MembershipExpression.build(getAlternateForms(e164)))
|
||||
.map(e164 -> MembershipExpression.build(Util.getAlternateForms(e164)))
|
||||
.orElseThrow(() -> new IllegalArgumentException("E164 must be present on existing account"));
|
||||
|
||||
attrValues.putAll(membershipExpression.values());
|
||||
|
||||
+80
-56
@@ -8,7 +8,6 @@ package org.whispersystems.textsecuregcm.storage;
|
||||
import static java.util.Objects.requireNonNull;
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.eatthepath.otp.HmacOneTimePasswordGenerator;
|
||||
import com.eatthepath.otp.TimeBasedOneTimePasswordGenerator;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectWriter;
|
||||
@@ -51,7 +50,6 @@ import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
@@ -61,7 +59,6 @@ import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
import javax.annotation.Nullable;
|
||||
import javax.crypto.KeyGenerator;
|
||||
import javax.crypto.Mac;
|
||||
@@ -144,14 +141,12 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
private final SecureValueRecoveryClient secureValueRecovery2Client;
|
||||
private final DisconnectionRequestManager disconnectionRequestManager;
|
||||
private final PhoneNumberRecoveryPasswordsManager phoneNumberRecoveryPasswordsManager;
|
||||
private final Executor accountLockExecutor;
|
||||
private final ScheduledExecutorService messagesPollExecutor;
|
||||
private final ScheduledExecutorService retryExecutor;
|
||||
private final Clock clock;
|
||||
private final Duration maxTotpValidationDelay;
|
||||
|
||||
private final KeyGenerator totpKeyGenerator;
|
||||
private final TimeBasedOneTimePasswordGenerator totpGenerator;
|
||||
|
||||
private final Key verificationTokenKey;
|
||||
|
||||
@@ -207,15 +202,13 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
static final String LINK_DEVICE_VERIFICATION_TOKEN_ALGORITHM = "HmacSHA256";
|
||||
|
||||
@VisibleForTesting
|
||||
static final int TOTP_KEY_LENGTH_BITS = 256;
|
||||
public static final TimeBasedOneTimePasswordGenerator TOTP = new TimeBasedOneTimePasswordGenerator();
|
||||
|
||||
@VisibleForTesting
|
||||
public static final TotpParameters TOTP_PARAMETERS = new TotpParameters(
|
||||
TimeBasedOneTimePasswordGenerator.TOTP_ALGORITHM_HMAC_SHA256,
|
||||
HmacOneTimePasswordGenerator.DEFAULT_PASSWORD_LENGTH,
|
||||
TimeBasedOneTimePasswordGenerator.DEFAULT_TIME_STEP);
|
||||
private static final TotpParameters TOTP_PARAMETERS =
|
||||
new TotpParameters(TOTP.getAlgorithm(), TOTP.getPasswordLength(), TOTP.getTimeStep());
|
||||
|
||||
public static final int MAX_TOTP_KEYS = 2;
|
||||
public static final int MAX_MFA_KEYS = 10;
|
||||
|
||||
public enum DeletionReason {
|
||||
ADMIN_DELETED("admin"),
|
||||
@@ -288,6 +281,9 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
private static class UncheckedTooManyTotpKeysException extends NoStackTraceRuntimeException {
|
||||
}
|
||||
|
||||
private static class UncheckedTooManyMfaKeysException extends NoStackTraceRuntimeException {
|
||||
}
|
||||
|
||||
public AccountsManager(final Accounts accounts,
|
||||
final PhoneNumberIdentifiers phoneNumberIdentifiers,
|
||||
final FaultTolerantRedisClusterClient cacheCluster,
|
||||
@@ -301,7 +297,6 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
final SecureValueRecoveryClient secureValueRecovery2Client,
|
||||
final DisconnectionRequestManager disconnectionRequestManager,
|
||||
final PhoneNumberRecoveryPasswordsManager phoneNumberRecoveryPasswordsManager,
|
||||
final Executor accountLockExecutor,
|
||||
final ScheduledExecutorService messagesPollExecutor,
|
||||
final ScheduledExecutorService retryExecutor,
|
||||
final Clock clock,
|
||||
@@ -320,12 +315,11 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
this.secureValueRecovery2Client = secureValueRecovery2Client;
|
||||
this.disconnectionRequestManager = disconnectionRequestManager;
|
||||
this.phoneNumberRecoveryPasswordsManager = requireNonNull(phoneNumberRecoveryPasswordsManager);
|
||||
this.accountLockExecutor = accountLockExecutor;
|
||||
this.messagesPollExecutor = messagesPollExecutor;
|
||||
this.retryExecutor = retryExecutor;
|
||||
this.clock = requireNonNull(clock);
|
||||
|
||||
if (maxTotpValidationDelay.compareTo(TOTP_PARAMETERS.timeStep()) > 0) {
|
||||
if (maxTotpValidationDelay.compareTo(TOTP.getTimeStep()) > 0) {
|
||||
throw new IllegalArgumentException("Max TOTP validation delay must be less than or equal to TOTP time step");
|
||||
}
|
||||
|
||||
@@ -341,23 +335,25 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
}
|
||||
|
||||
try {
|
||||
this.totpKeyGenerator = KeyGenerator.getInstance(TOTP_PARAMETERS.algorithm());
|
||||
totpKeyGenerator.init(TOTP_KEY_LENGTH_BITS);
|
||||
this.totpKeyGenerator = KeyGenerator.getInstance(TOTP.getAlgorithm());
|
||||
totpKeyGenerator.init(getTotpKeyLengthBits());
|
||||
} catch (final NoSuchAlgorithmException e) {
|
||||
throw new AssertionError("Every implementation of the Java platform is required to support the HmacSHA256 KeyGenerator algorithm", e);
|
||||
}
|
||||
|
||||
try {
|
||||
this.totpGenerator = new TimeBasedOneTimePasswordGenerator(TOTP_PARAMETERS.timeStep(),
|
||||
TOTP_PARAMETERS.passwordLength(),
|
||||
TOTP_PARAMETERS.algorithm());
|
||||
} catch (final NoSuchAlgorithmException e) {
|
||||
throw new AssertionError("Every implementation of the Java platform is required to support the HmacSHA256 MAC algorithm", e);
|
||||
}
|
||||
|
||||
this.pubSubConnection = pubSubRedisClient.createPubSubConnection();
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static int getTotpKeyLengthBits() {
|
||||
try {
|
||||
// The HOTP/TOTP spec recommends using a key length that's the same as the HMAC block length
|
||||
return Mac.getInstance(TOTP.getAlgorithm()).getMacLength() * 8;
|
||||
} catch (final NoSuchAlgorithmException e) {
|
||||
throw new AssertionError("Algorithm used by TOTP generator not found", e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void start() {
|
||||
pubSubConnection.usePubSubConnection(connection -> {
|
||||
@@ -454,7 +450,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
return Metrics.timer(CREATE_TIMER_NAME, HAS_NUMBER_TAG_NAME, "true").record(() -> {
|
||||
try {
|
||||
return accountLockManager.withLock(Set.of(pni),
|
||||
() -> create(Optional.of(number), Optional.of(pni), Optional.empty(), Optional.empty(), accountAttributes, aciIdentityKey, Optional.of(pniIdentityKey), primaryDeviceSpec, userAgent), accountLockExecutor);
|
||||
() -> create(Optional.of(number), Optional.of(pni), Optional.empty(), Optional.empty(), accountAttributes, aciIdentityKey, Optional.of(pniIdentityKey), primaryDeviceSpec, userAgent));
|
||||
} catch (final ReceiptAlreadyRedeemedException e) {
|
||||
throw new AssertionError("ReceiptAlreadyRedeemedException must never be thrown for accounts with numbers");
|
||||
} catch (final RuntimeException e) {
|
||||
@@ -522,7 +518,15 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
additionalWriteItems.add(phoneNumberRecoveryPasswordsManager.buildTransactWriteItemForStorePassword(phoneNumberIdentifier, phoneNumberRecoveryPassword))));
|
||||
|
||||
if (maybeNumber.isPresent()) {
|
||||
accounts.create(account, additionalWriteItems);
|
||||
if (maybeRecentlyDeletedAccountIdentifier.isPresent()) {
|
||||
// If we are re-using a recently deleted ACI, also obtain a lock for it so that clearing queues for the ACI synchronize against it
|
||||
accountLockManager.withLock(Set.of(maybeRecentlyDeletedAccountIdentifier.get()), () -> {
|
||||
accounts.create(account, additionalWriteItems);
|
||||
return null;
|
||||
});
|
||||
} else {
|
||||
accounts.create(account, additionalWriteItems);
|
||||
}
|
||||
} else {
|
||||
assert accountAttributes.recoveryPassword().isPresent();
|
||||
accounts.create(account,
|
||||
@@ -605,7 +609,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
reclaimAccount(account, existingAccount, primaryDeviceSpec, accountAttributes);
|
||||
|
||||
return account;
|
||||
}, accountLockExecutor);
|
||||
});
|
||||
|
||||
final PushTokenType pushTokenType = PushTokenType.fromDeviceSpec(primaryDeviceSpec);
|
||||
final PushTokenType previousPushTokenType = PushTokenType.fromDevice(existingAccount.getPrimaryDevice());
|
||||
@@ -703,8 +707,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
.orElseThrow(() -> new IllegalArgumentException("Account not found: " + accountIdentifier));
|
||||
|
||||
return accountLockManager.withSingleAccountLock(account,
|
||||
() -> addDevice(accountIdentifier, deviceSpec, linkDeviceToken, MAX_UPDATE_ATTEMPTS),
|
||||
accountLockExecutor);
|
||||
() -> addDevice(accountIdentifier, deviceSpec, linkDeviceToken, MAX_UPDATE_ATTEMPTS));
|
||||
}
|
||||
|
||||
private Pair<Account, Device> addDevice(final UUID accountIdentifier, final DeviceSpec deviceSpec, final String linkDeviceToken, final int retries)
|
||||
@@ -901,8 +904,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
.orElseThrow(() -> new IllegalArgumentException("Account not found: " + accountIdentifier));
|
||||
|
||||
return accountLockManager.withSingleAccountLock(account,
|
||||
() -> removeDevice(accountIdentifier, deviceId, MAX_UPDATE_ATTEMPTS),
|
||||
accountLockExecutor);
|
||||
() -> removeDevice(accountIdentifier, deviceId, MAX_UPDATE_ATTEMPTS));
|
||||
}
|
||||
|
||||
private Account removeDevice(final UUID accountIdentifier, final byte deviceId, final int retries) {
|
||||
@@ -968,7 +970,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
|
||||
try {
|
||||
return accountLockManager.withLock(new HashSet<>(List.of(originalPhoneNumberIdentifier, targetPhoneNumberIdentifier)),
|
||||
() -> changeNumber(account, targetNumber, targetPhoneNumberIdentifier, pniIdentityKey, pniSignedPreKeys, pniPqLastResortPreKeys, pniRegistrationIds), accountLockExecutor);
|
||||
() -> changeNumber(account, targetNumber, targetPhoneNumberIdentifier, pniIdentityKey, pniSignedPreKeys, pniPqLastResortPreKeys, pniRegistrationIds));
|
||||
} catch (final RuntimeException e) {
|
||||
logger.error("Unexpected exception when changing phone number", e);
|
||||
throw e;
|
||||
@@ -1272,7 +1274,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
}
|
||||
|
||||
return maybeUpdatedAccount;
|
||||
}, accountLockExecutor);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1480,7 +1482,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
accountLockManager.withSingleAccountLock(account, () -> {
|
||||
delete(account);
|
||||
return null;
|
||||
}, accountLockExecutor);
|
||||
});
|
||||
|
||||
Metrics.counter(DELETE_COUNTER_NAME,
|
||||
COUNTRY_CODE_TAG_NAME, Util.getCountryCode(account),
|
||||
@@ -1994,7 +1996,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
accountLockManager.withSingleAccountLock(account, () -> {
|
||||
migrateAccountRecoveryPassword(account.getAccountIdentifier(), MAX_UPDATE_ATTEMPTS);
|
||||
return null;
|
||||
}, accountLockExecutor);
|
||||
});
|
||||
}
|
||||
|
||||
private void migrateAccountRecoveryPassword(final UUID accountIdentifier, final int retries) {
|
||||
@@ -2029,20 +2031,25 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
/// @see [#confirmPendingTotpKey(UUID, int, Instant, byte[])
|
||||
///
|
||||
/// @throws TooManyTotpKeysException if the target account already has at least [#MAX_TOTP_KEYS] TOTP keys
|
||||
public TotpKey generatePendingTotpKey(final UUID accountIdentifier) throws TooManyTotpKeysException {
|
||||
/// @throws TooManyMfaKeysException if the target account already has at least [#MAX_MFA_KEYS] total MFA keys
|
||||
public TotpKey generatePendingTotpKey(final UUID accountIdentifier) throws TooManyTotpKeysException, TooManyMfaKeysException {
|
||||
final SecretKey secretKey = totpKeyGenerator.generateKey();
|
||||
final TotpKey pendingTotpKey = new TotpKey(TOTP_PARAMETERS, secretKey.getEncoded());
|
||||
|
||||
try {
|
||||
update(accountIdentifier, account -> {
|
||||
if (account.getTotpKeys().size() >= MAX_TOTP_KEYS) {
|
||||
if (account.getMfaKeys().values().stream().filter(AnnotatedTotpKey.class::isInstance).count() >= MAX_TOTP_KEYS) {
|
||||
throw new UncheckedTooManyTotpKeysException();
|
||||
} else if (account.getMfaKeys().size() >= MAX_MFA_KEYS) {
|
||||
throw new UncheckedTooManyMfaKeysException();
|
||||
}
|
||||
|
||||
account.setPendingTotpKey(pendingTotpKey);
|
||||
});
|
||||
} catch (final UncheckedTooManyTotpKeysException _) {
|
||||
throw new TooManyTotpKeysException();
|
||||
} catch (final UncheckedTooManyMfaKeysException _) {
|
||||
throw new TooManyMfaKeysException();
|
||||
}
|
||||
|
||||
return pendingTotpKey;
|
||||
@@ -2059,11 +2066,13 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
/// TOTP password for the given account or for a one-time password previously verified for the given account or empty
|
||||
/// otherwise
|
||||
///
|
||||
/// @throws TooManyMfaKeysException if the target account already has at least [#MAX_MFA_KEYS] total MFA keys
|
||||
///
|
||||
/// @see [#generatePendingTotpKey(UUID)
|
||||
public Optional<Integer> confirmPendingTotpKey(final UUID accountIdentifier,
|
||||
public Optional<Byte> confirmPendingTotpKey(final UUID accountIdentifier,
|
||||
final int oneTimePassword,
|
||||
final Instant timestamp,
|
||||
final byte[] metadataCiphertext) {
|
||||
final byte[] metadataCiphertext) throws TooManyMfaKeysException {
|
||||
|
||||
final Optional<Account> maybeAccount = accounts.getByAccountIdentifier(accountIdentifier);
|
||||
|
||||
@@ -2077,25 +2086,31 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
final TotpKey pendingTotpKey = maybePendingTotpKey.get();
|
||||
|
||||
try {
|
||||
if (totpGenerator.validateOneTimePassword(pendingTotpKey, timestamp, oneTimePassword)) {
|
||||
if (verifyTotp(pendingTotpKey, timestamp, oneTimePassword)) {
|
||||
final AtomicInteger keyId = new AtomicInteger();
|
||||
|
||||
update(accountIdentifier, account -> {
|
||||
final Map<Integer, AnnotatedTotpKey> updatedTotpKeys = new HashMap<>(account.getTotpKeys());
|
||||
final Map<Byte, AnnotatedMfaKey> updatedMfaKeys = new HashMap<>(account.getMfaKeys());
|
||||
|
||||
keyId.set(account.getNextTotpKeyId());
|
||||
if (updatedMfaKeys.size() >= MAX_MFA_KEYS) {
|
||||
throw new UncheckedTooManyMfaKeysException();
|
||||
}
|
||||
|
||||
updatedTotpKeys.put(keyId.get(),
|
||||
keyId.set(account.getNextMfaKeyId());
|
||||
|
||||
updatedMfaKeys.put((byte) keyId.get(),
|
||||
new AnnotatedTotpKey(new TotpKey(pendingTotpKey.totpParameters(), pendingTotpKey.encodedKey()), metadataCiphertext));
|
||||
|
||||
account.setPendingTotpKey(null);
|
||||
account.setTotpKeys(updatedTotpKeys);
|
||||
account.setMfaKeys(updatedMfaKeys);
|
||||
});
|
||||
|
||||
return Optional.of(keyId.get());
|
||||
return Optional.of((byte) keyId.get());
|
||||
}
|
||||
} catch (final InvalidKeyException e) {
|
||||
ImpossibleEvents.logImpossible(logger, "Invalid pending TOTP key for account {}", accountIdentifier, e);
|
||||
} catch (final UncheckedTooManyMfaKeysException _) {
|
||||
throw new TooManyMfaKeysException();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2109,11 +2124,12 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
// possible that a user will have iterated through so many keys that they've wrapped around into negative integers,
|
||||
// but that's not really a practical concern.
|
||||
return getByAccountIdentifier(accountIdentifier)
|
||||
.flatMap(account -> account.getTotpKeys().entrySet().stream()
|
||||
.flatMap(account -> account.getMfaKeys().entrySet().stream()
|
||||
.filter(entry -> entry.getValue() instanceof AnnotatedTotpKey)
|
||||
.max(Map.Entry.comparingByKey())
|
||||
.filter(entry -> {
|
||||
try {
|
||||
return totpGenerator.validateOneTimePassword(entry.getValue(), timestamp, oneTimePassword);
|
||||
return verifyTotp((AnnotatedTotpKey) entry.getValue(), timestamp, oneTimePassword);
|
||||
} catch (final InvalidKeyException e) {
|
||||
ImpossibleEvents.logImpossible(logger, "Invalid TOTP key for account {}", accountIdentifier, e);
|
||||
return false;
|
||||
@@ -2123,7 +2139,8 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
}
|
||||
|
||||
public boolean verifyTotp(final Account account, final Instant validationTimestamp, @Nullable final Integer oneTimePassword) {
|
||||
if (account.getTotpKeys().isEmpty()) {
|
||||
final List<AnnotatedTotpKey> totpKeys = account.getMfaKeys().values().stream().filter(AnnotatedTotpKey.class::isInstance).map(AnnotatedTotpKey.class::cast).toList();
|
||||
if (totpKeys.isEmpty()) {
|
||||
return oneTimePassword == null;
|
||||
}
|
||||
|
||||
@@ -2132,18 +2149,25 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
return false;
|
||||
}
|
||||
|
||||
for (final Instant timestamp : new Instant[] { validationTimestamp, validationTimestamp.minus(maxTotpValidationDelay) }) {
|
||||
for (final SecretKey totpKey : account.getTotpKeys().values()) {
|
||||
try {
|
||||
if (totpGenerator.validateOneTimePassword(totpKey, timestamp, oneTimePassword)) {
|
||||
return true;
|
||||
}
|
||||
} catch (final InvalidKeyException e) {
|
||||
ImpossibleEvents.logImpossible(logger, "Invalid TOTP key for account {}", account.getAccountIdentifier(), e);
|
||||
for (final SecretKey totpKey : totpKeys) {
|
||||
try {
|
||||
if (verifyTotp(totpKey, validationTimestamp, oneTimePassword)) {
|
||||
return true;
|
||||
}
|
||||
} catch (final InvalidKeyException e) {
|
||||
ImpossibleEvents.logImpossible(logger, "Invalid TOTP key for account {}", account.getAccountIdentifier(), e);
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private boolean verifyTotp(final SecretKey totpKey, final Instant validationTimestamp, final int oneTimePassword) throws InvalidKeyException {
|
||||
for (final Instant timestamp : new Instant[]{validationTimestamp, validationTimestamp.minus(maxTotpValidationDelay)}) {
|
||||
if (TOTP.validateOneTimePassword(totpKey, timestamp, oneTimePassword)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonSubTypes;
|
||||
import com.fasterxml.jackson.annotation.JsonTypeInfo;
|
||||
|
||||
@JsonTypeInfo(use=JsonTypeInfo.Id.NAME, property = "type")
|
||||
@JsonSubTypes({@JsonSubTypes.Type(value=AnnotatedTotpKey.class, name = "totp")})
|
||||
public sealed interface AnnotatedMfaKey permits AnnotatedTotpKey {
|
||||
byte[] metadataCiphertext();
|
||||
AnnotatedMfaKey withMetadataCiphertext(byte[] newCiphertext);
|
||||
}
|
||||
+6
-1
@@ -15,7 +15,7 @@ public record AnnotatedTotpKey(@JsonUnwrapped
|
||||
TotpKey totpKey,
|
||||
|
||||
@JsonProperty("metadata")
|
||||
byte[] metadataCiphertext) implements SecretKey {
|
||||
byte[] metadataCiphertext) implements SecretKey, AnnotatedMfaKey {
|
||||
|
||||
@Override
|
||||
public String getAlgorithm() {
|
||||
@@ -45,4 +45,9 @@ public record AnnotatedTotpKey(@JsonUnwrapped
|
||||
public int hashCode() {
|
||||
return Objects.hash(totpKey, Arrays.hashCode(metadataCiphertext));
|
||||
}
|
||||
|
||||
@Override
|
||||
public AnnotatedMfaKey withMetadataCiphertext(byte[] newCiphertext) {
|
||||
return new AnnotatedTotpKey(totpKey(), newCiphertext);
|
||||
}
|
||||
}
|
||||
@@ -34,11 +34,11 @@ import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStore;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import reactor.core.observability.micrometer.Micrometer;
|
||||
import reactor.core.publisher.Flux;
|
||||
@@ -132,7 +132,7 @@ public class MessagesManager {
|
||||
foundationDbInsertFuture =
|
||||
foundationDbMessageStore.insert(new AciServiceIdentifier(accountIdentifier), minimizedMessagesByDeviceId)
|
||||
.exceptionally(e -> {
|
||||
if (e instanceof FDBException fdbException) {
|
||||
if (ExceptionUtils.unwrap(e) instanceof final FDBException fdbException) {
|
||||
Metrics.counter(INSERT_FDB_EXCEPTIONS_COUNTER_NAME, "code", String.valueOf(fdbException.getCode()))
|
||||
.increment();
|
||||
} else {
|
||||
@@ -142,7 +142,7 @@ public class MessagesManager {
|
||||
e);
|
||||
}
|
||||
|
||||
return Collections.emptyMap();
|
||||
throw ExceptionUtils.wrap(e);
|
||||
});
|
||||
} else {
|
||||
foundationDbInsertFuture = CompletableFuture.completedFuture(Collections.emptyMap());
|
||||
|
||||
+216
-15
@@ -5,14 +5,27 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import com.google.common.hash.HashCode;
|
||||
import com.google.common.hash.Hashing;
|
||||
import com.google.protobuf.CodedOutputStream;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Flow;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import jakarta.annotation.Nullable;
|
||||
import org.reactivestreams.Subscription;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
@@ -20,6 +33,7 @@ import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessage
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import reactor.adapter.JdkFlowAdapter;
|
||||
import reactor.core.publisher.BaseSubscriber;
|
||||
import reactor.core.publisher.SignalType;
|
||||
|
||||
/// A temporary message stream that can mirror message acknowledgements (deletion requests) to FoundationDB
|
||||
public class MirroringMessageStream implements MessageStream {
|
||||
@@ -36,12 +50,62 @@ public class MirroringMessageStream implements MessageStream {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(MirroringMessageStream.class);
|
||||
|
||||
private static class FoundationDbSubscriber extends BaseSubscriber<MessageStreamEntry> {
|
||||
private static final Counter MESSAGE_MISMATCHES_COUNTER =
|
||||
Metrics.counter(MetricsUtil.name(MirroringMessageStream.class, "messageMismatches"));
|
||||
|
||||
private static final String STREAM_AGREEMENTS = MetricsUtil.name(MirroringMessageStream.class, "streamAgreements");
|
||||
|
||||
private static final String MISSING_MESSAGES_COUNTER =
|
||||
MetricsUtil.name(MirroringMessageStream.class, "missingMessages");
|
||||
|
||||
private static final int MAX_WINDOW_SIZE = 1024;
|
||||
|
||||
private final Map<UUID, HashCode> redisDynamoMessageWindow = new HashMap<>();
|
||||
private final Map<UUID, HashCode> foundationDbMessageWindow = new HashMap<>();
|
||||
|
||||
private boolean stopAgreementVerification = false;
|
||||
|
||||
@Nullable
|
||||
private Tags agreementFailureTags;
|
||||
|
||||
private final Set<UUID> recentFoundationDbUuids = Collections.newSetFromMap(new LinkedHashMap<>() {
|
||||
@Override
|
||||
protected boolean removeEldestEntry(final Map.Entry<UUID, Boolean> eldest) {
|
||||
return size() > MAX_WINDOW_SIZE;
|
||||
}
|
||||
});
|
||||
|
||||
private final Set<UUID> recentRedisDynamoEphemeralUuids = Collections.newSetFromMap(new LinkedHashMap<>() {
|
||||
@Override
|
||||
protected boolean removeEldestEntry(final Map.Entry<UUID, Boolean> eldest) {
|
||||
return size() > MAX_WINDOW_SIZE;
|
||||
}
|
||||
});
|
||||
|
||||
private enum Stream {
|
||||
REDIS_DYNAMO("redisDynamo"),
|
||||
FOUNDATION_DB("foundationDb");
|
||||
|
||||
private final String name;
|
||||
|
||||
Stream(final String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
||||
|
||||
private final FoundationDbSubscriber subscriber = new FoundationDbSubscriber();
|
||||
|
||||
private class FoundationDbSubscriber extends BaseSubscriber<MessageStreamEntry> {
|
||||
|
||||
public void handleRedisDynamoDbMessageStreamEntry(final MessageStreamEntry messageStreamEntry) {
|
||||
final boolean isMirroredMessage = switch (messageStreamEntry) {
|
||||
case MessageStreamEntry.Envelope envelopeEntry ->
|
||||
UUIDUtil.fromByteString(envelopeEntry.message().getServerGuid()).version() == 8;
|
||||
case final MessageStreamEntry.Envelope envelopeEntry -> {
|
||||
final boolean isUUIDv8 = UUIDUtil.fromByteString(envelopeEntry.message().getServerGuid()).version() == 8;
|
||||
if (isUUIDv8) {
|
||||
verifyMessageAgreement(envelopeEntry, Stream.REDIS_DYNAMO);
|
||||
}
|
||||
yield isUUIDv8;
|
||||
}
|
||||
|
||||
case MessageStreamEntry.QueueEmpty _ -> true;
|
||||
};
|
||||
@@ -64,8 +128,21 @@ public class MirroringMessageStream implements MessageStream {
|
||||
default -> super.hookOnError(throwable);
|
||||
}
|
||||
}
|
||||
|
||||
protected void hookOnNext(final MessageStreamEntry messageStreamEntry) {
|
||||
if (messageStreamEntry instanceof final MessageStreamEntry.Envelope envelope) {
|
||||
verifyMessageAgreement(envelope, Stream.FOUNDATION_DB);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void hookFinally(final SignalType type) {
|
||||
super.hookFinally(type);
|
||||
publishStreamAgreementMetrics();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public MirroringMessageStream(final RedisDynamoDbMessageStream redisDynamoDbMessageStream,
|
||||
final FoundationDbMessageStream foundationDbMessageStream,
|
||||
final ExperimentEnrollmentManager experimentEnrollmentManager,
|
||||
@@ -82,9 +159,9 @@ public class MirroringMessageStream implements MessageStream {
|
||||
|
||||
@Override
|
||||
public Flow.Publisher<MessageStreamEntry> getMessages() {
|
||||
final FoundationDbSubscriber subscriber = new FoundationDbSubscriber();
|
||||
|
||||
if (experimentEnrollmentManager.isEnrolled(accountIdentifier.uuid(), MessagesManager.MIRROR_READS_EXPERIMENT_NAME)) {
|
||||
if (experimentEnrollmentManager.isEnrolled(accountIdentifier.uuid(),
|
||||
MessagesManager.MIRROR_READS_EXPERIMENT_NAME)) {
|
||||
JdkFlowAdapter.flowPublisherToFlux(foundationDbMessageStream.getMessages())
|
||||
.subscribe(subscriber);
|
||||
|
||||
@@ -107,17 +184,141 @@ public class MirroringMessageStream implements MessageStream {
|
||||
// All messages stored in FoundationDB use version 8 UUIDs; if a message has a version 4 UUID, then it only exists
|
||||
// in Redis/DynamoDB
|
||||
if (messageGuid.version() == 8 &&
|
||||
experimentEnrollmentManager.isEnrolled(accountIdentifier.uuid(), MessagesManager.MIRROR_DELETIONS_EXPERIMENT_NAME)) {
|
||||
experimentEnrollmentManager.isEnrolled(accountIdentifier.uuid(),
|
||||
MessagesManager.MIRROR_DELETIONS_EXPERIMENT_NAME)) {
|
||||
|
||||
foundationDbMessageStream.acknowledgeMessage(messageGuid, serverTimestamp)
|
||||
.whenComplete((_, throwable) -> {
|
||||
if (throwable != null) {
|
||||
logger.warn("Failed to delete message {}/{}/{} from FoundationDb", accountIdentifier.uuid(), deviceId,
|
||||
messageGuid, throwable);
|
||||
}
|
||||
});
|
||||
if (experimentEnrollmentManager.isEnrolled(accountIdentifier.uuid(), MessagesManager.MIRROR_READS_EXPERIMENT_NAME)
|
||||
&&
|
||||
messageNotDeliveredOnFoundationDbStream(messageGuid)) {
|
||||
foundationDbMessageStream.acknowledgeAndGetMessage(messageGuid)
|
||||
.thenAccept(deleteMessage -> {
|
||||
if (deleteMessage.isEmpty()) {
|
||||
handleMissingFoundationDbMessage(messageGuid);
|
||||
return;
|
||||
}
|
||||
verifyMessageAgreement(deleteMessage.get(), Stream.FOUNDATION_DB);
|
||||
})
|
||||
.whenComplete((_, throwable) -> {
|
||||
if (throwable != null) {
|
||||
logger.warn("Failed to delete message {}/{}/{} from FoundationDb", accountIdentifier.uuid(), deviceId,
|
||||
messageGuid, throwable);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
foundationDbMessageStream.acknowledgeMessage(messageGuid, serverTimestamp)
|
||||
.whenComplete((_, throwable) -> {
|
||||
if (throwable != null) {
|
||||
logger.warn("Failed to delete message {}/{}/{} from FoundationDb", accountIdentifier.uuid(), deviceId,
|
||||
messageGuid, throwable);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return redisDynamoDbMessageStream.acknowledgeMessage(messageGuid, serverTimestamp);
|
||||
}
|
||||
|
||||
private synchronized void verifyMessageAgreement(final MessageStreamEntry.Envelope envelope,
|
||||
final Stream stream) {
|
||||
|
||||
if (stopAgreementVerification) {
|
||||
return;
|
||||
}
|
||||
|
||||
final UUID messageUUID = UUIDUtil.fromByteString(envelope.message().getServerGuid());
|
||||
|
||||
if (envelope.message().getEphemeral()) {
|
||||
// We don't compare ephemeral messages across streams because the two systems have different ways of handling and
|
||||
// delivering ephemeral messages. However, we track recently seen ephemeral UUIDs on the Redis/Dynamo stream
|
||||
// to answer whether a message missing from FoundationDB was ephemeral or not.
|
||||
if (stream == Stream.REDIS_DYNAMO) {
|
||||
recentRedisDynamoEphemeralUuids.add(messageUUID);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// There could be a race where a FoundationDB message is delivered on the stream right after it was acknowledged,
|
||||
// so we don't want to add it to the window again; check it against a set of recently seen UUIDs before adding.
|
||||
if (Stream.FOUNDATION_DB == stream && !recentFoundationDbUuids.add(messageUUID)) {
|
||||
return;
|
||||
}
|
||||
|
||||
final Map<UUID, HashCode> thisStreamWindow;
|
||||
final Map<UUID, HashCode> otherStreamWindow;
|
||||
if (Stream.REDIS_DYNAMO == stream) {
|
||||
thisStreamWindow = redisDynamoMessageWindow;
|
||||
otherStreamWindow = foundationDbMessageWindow;
|
||||
} else {
|
||||
thisStreamWindow = foundationDbMessageWindow;
|
||||
otherStreamWindow = redisDynamoMessageWindow;
|
||||
}
|
||||
|
||||
final HashCode thisStreamMessageHashCode = hashCode(envelope.message());
|
||||
|
||||
final HashCode otherStreamMessageHashCode = otherStreamWindow.remove(messageUUID);
|
||||
if (otherStreamMessageHashCode != null) {
|
||||
if (!otherStreamMessageHashCode.equals(thisStreamMessageHashCode)) {
|
||||
MESSAGE_MISMATCHES_COUNTER.increment();
|
||||
}
|
||||
} else {
|
||||
thisStreamWindow.put(messageUUID, thisStreamMessageHashCode);
|
||||
if (thisStreamWindow.size() >= MAX_WINDOW_SIZE) {
|
||||
// Stream is way ahead of the other, stop comparing further
|
||||
stopAgreementVerification = true;
|
||||
thisStreamWindow.clear();
|
||||
otherStreamWindow.clear();
|
||||
recentFoundationDbUuids.clear();
|
||||
setAgreementFailure(Tags.of("reason", "overflow", "stream", stream.name));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized boolean messageNotDeliveredOnFoundationDbStream(final UUID messageGuid) {
|
||||
return redisDynamoMessageWindow.containsKey(messageGuid);
|
||||
}
|
||||
|
||||
private synchronized void setAgreementFailure(final Tags tags) {
|
||||
if (agreementFailureTags == null) {
|
||||
agreementFailureTags = tags;
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void publishStreamAgreementMetrics() {
|
||||
|
||||
Tags tags = Tags.of("success", String.valueOf(agreementFailureTags == null));
|
||||
if (agreementFailureTags != null) {
|
||||
tags = tags.and(agreementFailureTags);
|
||||
}
|
||||
|
||||
Metrics.counter(STREAM_AGREEMENTS, tags).increment();
|
||||
}
|
||||
|
||||
private synchronized void handleMissingFoundationDbMessage(final UUID messageGuid) {
|
||||
final Boolean ephemeral;
|
||||
if (redisDynamoMessageWindow.containsKey(messageGuid)) {
|
||||
// The comparison window always contains non-ephemeral messages since we ignore ephemeral messages for comparison
|
||||
ephemeral = false;
|
||||
} else if (recentRedisDynamoEphemeralUuids.contains(messageGuid)) {
|
||||
ephemeral = true;
|
||||
} else {
|
||||
ephemeral = null;
|
||||
}
|
||||
setAgreementFailure(Tags.of("reason", "missingMessages"));
|
||||
Metrics.counter(MISSING_MESSAGES_COUNTER, "ephemeral", ephemeral == null ? "unknown" : ephemeral.toString())
|
||||
.increment();
|
||||
}
|
||||
|
||||
private static HashCode hashCode(final MessageProtos.Envelope envelope) {
|
||||
final byte[] serialized = new byte[envelope.getSerializedSize()];
|
||||
final CodedOutputStream codedOutputStream = CodedOutputStream.newInstance(serialized);
|
||||
codedOutputStream.useDeterministicSerialization();
|
||||
try {
|
||||
envelope.writeTo(codedOutputStream);
|
||||
codedOutputStream.flush();
|
||||
} catch (final IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
return Hashing.murmur3_128().hashBytes(serialized);
|
||||
}
|
||||
|
||||
}
|
||||
+3
-2
@@ -43,7 +43,7 @@ public class PhoneNumberIdentifiers {
|
||||
private final String tableName;
|
||||
|
||||
@VisibleForTesting
|
||||
static final String KEY_E164 = "P";
|
||||
public static final String KEY_E164 = "P";
|
||||
@VisibleForTesting
|
||||
static final String INDEX_NAME = "pni_to_p";
|
||||
@VisibleForTesting
|
||||
@@ -183,7 +183,8 @@ public class PhoneNumberIdentifiers {
|
||||
* @return The provided PNI if the update occurred, or the existing PNI associated with originalPhoneNumber
|
||||
*/
|
||||
@VisibleForTesting
|
||||
CompletableFuture<UUID> setPni(final String originalPhoneNumber, final List<String> allPhoneNumberForms,
|
||||
public CompletableFuture<UUID> setPni(final String originalPhoneNumber,
|
||||
final List<String> allPhoneNumberForms,
|
||||
final UUID pni) {
|
||||
if (!originalPhoneNumber.equals(allPhoneNumberForms.getFirst())) {
|
||||
throw new IllegalArgumentException("allPhoneNumberForms must start with the target phoneNumber");
|
||||
|
||||
@@ -29,9 +29,11 @@ import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.GetItemResponse;
|
||||
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ReturnValue;
|
||||
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem;
|
||||
import software.amazon.awssdk.services.dynamodb.model.Update;
|
||||
import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.UpdateItemResponse;
|
||||
|
||||
public class Profiles {
|
||||
|
||||
@@ -282,4 +284,28 @@ public class Profiles {
|
||||
.doOnError(ignored -> sample.stop(Metrics.timer(DELETE_PROFILES_TIMER_NAME, "outcome", "error")))
|
||||
.toFuture();
|
||||
}
|
||||
|
||||
/**
|
||||
* Upserts the avatar for a v1 profile
|
||||
*/
|
||||
public VersionedProfileV1 setAvatar(UUID accountIdentifier, String version, String avatar, byte[] commitment) {
|
||||
final UpdateItemResponse response = SET_PROFILES_TIMER.record(() ->
|
||||
dynamoDbClient.updateItem(UpdateItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.key(buildPrimaryKey(accountIdentifier, version))
|
||||
.updateExpression("SET #avatar = :avatar, #commitment = if_not_exists(#commitment, :commitment)")
|
||||
.expressionAttributeNames(Map.of(
|
||||
"#avatar", ATTR_AVATAR,
|
||||
"#commitment", ATTR_COMMITMENT
|
||||
))
|
||||
.expressionAttributeValues(Map.of(
|
||||
":avatar", AttributeValues.s(avatar),
|
||||
":commitment", AttributeValues.b(commitment)
|
||||
))
|
||||
.returnValues(ReturnValue.ALL_NEW)
|
||||
.build())
|
||||
);
|
||||
|
||||
return fromItem(response.attributes());
|
||||
}
|
||||
}
|
||||
@@ -338,4 +338,14 @@ public class ProfilesManager {
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void setV1Avatar(UUID accountIdentifier, String version, String avatar, byte[] commitment) {
|
||||
ResilienceUtil.getGeneralRedisRetry(RETRY_NAME)
|
||||
.executeRunnable(() -> cacheCluster.withBinaryCluster(
|
||||
connection -> connection.sync().del(getCacheKeyV1(accountIdentifier))));
|
||||
|
||||
final VersionedProfileV1 versionedProfileV1 = profilesV1.setAvatar(accountIdentifier, version, avatar, commitment);
|
||||
|
||||
redisSet(accountIdentifier, null, versionedProfileV1);
|
||||
}
|
||||
}
|
||||
+5
-5
@@ -248,8 +248,7 @@ public class SubscriptionManager {
|
||||
* @param <E> An exception thrown by the paymentSetupFunction
|
||||
* @return The return value of the paymentSetupFunction
|
||||
* @throws SubscriptionForbiddenException if the subscriber credentials were incorrect
|
||||
* @throws SubscriptionNotFoundException if the subscriber did not exist or did not have a subscription
|
||||
* attached
|
||||
* @throws SubscriptionNotFoundException if the subscriber did not exist
|
||||
* @throws SubscriptionProcessorConflictException if the new payment processor does not match the existing processor associated with
|
||||
* the subscriberId
|
||||
*/
|
||||
@@ -373,8 +372,8 @@ public class SubscriptionManager {
|
||||
* play store
|
||||
* @return the subscription level for the accepted subscription
|
||||
* @throws SubscriptionForbiddenException if the subscriber credentials were incorrect
|
||||
* @throws SubscriptionNotFoundException if the subscriber did not exist or did not have a subscription
|
||||
* attached
|
||||
* @throws SubscriptionNotFoundException if the subscriber did not exist, or the purchaseToken was not found
|
||||
* in the play store
|
||||
* @throws SubscriptionProcessorConflictException if the new payment processor does not match the existing processor associated with
|
||||
* the subscriberId
|
||||
* @throws SubscriptionPaymentRequiredException if the subscription is not in a state that grants the user an
|
||||
@@ -426,7 +425,8 @@ public class SubscriptionManager {
|
||||
* the app store
|
||||
* @return the subscription level for the accepted subscription
|
||||
* @throws SubscriptionForbiddenException if the subscriber credentials are incorrect
|
||||
* @throws SubscriptionNotFoundException if the originalTransactionId does not exist
|
||||
* @throws SubscriptionNotFoundException if the subscriber did not exist, or the originalTransactionId does
|
||||
* not exist
|
||||
* @throws SubscriptionProcessorConflictException if the new payment processor does not match the existing processor associated with
|
||||
* the subscriber
|
||||
* @throws SubscriptionInvalidArgumentsException if the originalTransactionId is malformed or does not represent a
|
||||
|
||||
@@ -30,8 +30,6 @@ import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ConditionalCheckFailedException;
|
||||
import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.GetItemResponse;
|
||||
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.QueryResponse;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ReturnValue;
|
||||
import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.UpdateItemResponse;
|
||||
@@ -168,37 +166,6 @@ public class Subscriptions {
|
||||
this.client = Objects.requireNonNull(client);
|
||||
}
|
||||
|
||||
/**
|
||||
* Looks in the GSI for a record with the given customer id and returns the user id.
|
||||
*/
|
||||
public byte[] getSubscriberUserByProcessorCustomer(ProcessorCustomer processorCustomer) {
|
||||
QueryRequest query = QueryRequest.builder()
|
||||
.tableName(table)
|
||||
.indexName(INDEX_NAME)
|
||||
.keyConditionExpression("#processor_customer_id = :processor_customer_id")
|
||||
.projectionExpression("#user")
|
||||
.expressionAttributeNames(Map.of(
|
||||
"#processor_customer_id", KEY_PROCESSOR_ID_CUSTOMER_ID,
|
||||
"#user", KEY_USER))
|
||||
.expressionAttributeValues(Map.of(
|
||||
":processor_customer_id", b(processorCustomer.toDynamoBytes())))
|
||||
.build();
|
||||
final QueryResponse queryResponse = client.query(query);
|
||||
|
||||
int count = queryResponse.count();
|
||||
if (count == 0) {
|
||||
return null;
|
||||
} else if (count > 1) {
|
||||
logger.error("expected invariant of 1-1 subscriber-customer violated for customer {} ({})",
|
||||
processorCustomer.customerId(), processorCustomer.processor());
|
||||
throw new IllegalStateException(
|
||||
"expected invariant of 1-1 subscriber-customer violated for customer " + processorCustomer);
|
||||
} else {
|
||||
Map<String, AttributeValue> result = queryResponse.items().getFirst();
|
||||
return result.get(KEY_USER).b().asByteArray();
|
||||
}
|
||||
}
|
||||
|
||||
public static class GetResult {
|
||||
|
||||
public static final GetResult NOT_STORED = new GetResult(Type.NOT_STORED, null);
|
||||
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import org.whispersystems.textsecuregcm.util.NoStackTraceException;
|
||||
|
||||
public class TooManyMfaKeysException extends NoStackTraceException {
|
||||
}
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage.foundationdb;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbUtil.TRANSACTION_ERRORS_COUNTER;
|
||||
|
||||
import com.apple.foundationdb.Database;
|
||||
import com.apple.foundationdb.FDBException;
|
||||
import com.apple.foundationdb.ReadTransaction;
|
||||
import com.apple.foundationdb.Transaction;
|
||||
import io.github.resilience4j.circuitbreaker.CircuitBreaker;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import jakarta.annotation.Nullable;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.Function;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.ResilienceUtil;
|
||||
|
||||
public class FaultTolerantDatabase {
|
||||
private final Database database;
|
||||
private final CircuitBreaker circuitBreaker;
|
||||
|
||||
public FaultTolerantDatabase(
|
||||
final Database database,
|
||||
final String circuitBreakerName,
|
||||
@Nullable final String circuitBreakerConfigurationName) {
|
||||
this.database = database;
|
||||
this.circuitBreaker = circuitBreakerConfigurationName != null
|
||||
? ResilienceUtil.getCircuitBreakerRegistry().circuitBreaker(circuitBreakerName, circuitBreakerConfigurationName)
|
||||
: ResilienceUtil.getCircuitBreakerRegistry().circuitBreaker(circuitBreakerName);
|
||||
}
|
||||
|
||||
public <T> T run(final Function<? super Transaction, T> retryable) {
|
||||
return circuitBreaker.executeSupplier(() -> database.run(retryable));
|
||||
}
|
||||
|
||||
/// Returns a cancellation-safe version of the result from [Database#runAsync(Function)]. Since the final stage
|
||||
/// of the result from [Database#runAsync(Function)] is a cleanup stage that closes the transaction, the
|
||||
/// transaction leaks if the future gets cancelled and the cleanup stage is skipped. So, we add another dummy stage
|
||||
/// that serves as the cancellation target and the cleanup can proceed as normal.
|
||||
///
|
||||
/// @param retryable the block of transaction logic to execute
|
||||
/// @param <T> the return type of retryable
|
||||
/// @return a cancellation-safe version of the future returned from [Database#runAsync(Function)]
|
||||
public <T> CompletableFuture<T> runAsync(final Function<? super Transaction, ? extends CompletableFuture<T>> retryable,
|
||||
final FoundationDbUtil.Context context) {
|
||||
return circuitBreaker.executeCompletionStage(() -> database.runAsync(retryable)
|
||||
.whenComplete((_, throwable) -> {
|
||||
if (throwable != null && ExceptionUtils.unwrap(throwable) instanceof final FDBException fdbException) {
|
||||
Metrics.counter(TRANSACTION_ERRORS_COUNTER,
|
||||
"context", context.getName(),
|
||||
"code", String.valueOf(fdbException.getCode())
|
||||
).increment();
|
||||
}
|
||||
})
|
||||
.thenApply(Function.identity()))
|
||||
.toCompletableFuture();
|
||||
}
|
||||
|
||||
public <T> T read(final Function<? super ReadTransaction, T> retryable) {
|
||||
return circuitBreaker.executeSupplier(() -> database.read(retryable));
|
||||
}
|
||||
|
||||
public <T> CompletableFuture<T> readAsync(
|
||||
final Function<? super ReadTransaction, ? extends CompletableFuture<T>> retryable) {
|
||||
return circuitBreaker.executeCompletionStage(() -> database.readAsync(retryable))
|
||||
.toCompletableFuture();
|
||||
}
|
||||
}
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
package org.whispersystems.textsecuregcm.storage.foundationdb;
|
||||
|
||||
import com.apple.foundationdb.Database;
|
||||
import io.dropwizard.lifecycle.Managed;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.Map;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
|
||||
public class FoundationDBWarmup implements Managed {
|
||||
|
||||
private final Map<String, FaultTolerantDatabase> databasesByName;
|
||||
|
||||
private static final Duration RETRY_DELAY = Duration.ofMillis(500);
|
||||
private static final int MAX_ATTEMPTS = 3;
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(FoundationDBWarmup.class);
|
||||
|
||||
private static final Timer WARMUP_TIMER = Metrics.timer(MetricsUtil.name(FoundationDBWarmup.class, "warmupTimer"));
|
||||
|
||||
private static final byte[] STATUS_JSON_KEY;
|
||||
|
||||
static {
|
||||
final byte[] suffix = "/status/json".getBytes(StandardCharsets.US_ASCII);
|
||||
STATUS_JSON_KEY = new byte[suffix.length + 2];
|
||||
STATUS_JSON_KEY[0] = (byte) 0xff;
|
||||
STATUS_JSON_KEY[1] = (byte) 0xff;
|
||||
System.arraycopy(suffix, 0, STATUS_JSON_KEY, 2, suffix.length);
|
||||
}
|
||||
|
||||
public FoundationDBWarmup(final Map<String, FaultTolerantDatabase> databasesByName) {
|
||||
this.databasesByName = databasesByName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void start() throws Exception {
|
||||
databasesByName.forEach(this::readStatusKey);
|
||||
}
|
||||
|
||||
/// Warm up the connection to a FoundationDB database by reading its status key. We retry a limited number of times so
|
||||
/// that we don't block the readiness probe in case a single shard is unavailable.
|
||||
///
|
||||
/// @param databaseName the name of the database to read from
|
||||
/// @param database the FoundationDB [Database] instance
|
||||
private void readStatusKey(final String databaseName, final FaultTolerantDatabase database) {
|
||||
int attempts = 0;
|
||||
final Timer.Sample sample = Timer.start();
|
||||
while (true) {
|
||||
try {
|
||||
database.readAsync(transaction -> transaction.get(STATUS_JSON_KEY)).join();
|
||||
sample.stop(WARMUP_TIMER);
|
||||
return;
|
||||
} catch (final Exception e) {
|
||||
attempts++;
|
||||
if (attempts == MAX_ATTEMPTS) {
|
||||
LOGGER.warn("Failed to read status key at startup for shard {}", databaseName, e);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
Thread.sleep(RETRY_DELAY);
|
||||
} catch (final InterruptedException ex) {
|
||||
throw new RuntimeException(ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+10
-11
@@ -1,6 +1,5 @@
|
||||
package org.whispersystems.textsecuregcm.storage.foundationdb;
|
||||
|
||||
import com.apple.foundationdb.Database;
|
||||
import com.apple.foundationdb.KeySelector;
|
||||
import com.apple.foundationdb.StreamingMode;
|
||||
import com.apple.foundationdb.Transaction;
|
||||
@@ -35,7 +34,7 @@ import reactor.core.publisher.Mono;
|
||||
/// catching up to end-of-queue,and an infinite stream for live updates.
|
||||
class FoundationDbMessagePublisher {
|
||||
|
||||
private final Database database;
|
||||
private final FaultTolerantDatabase database;
|
||||
private final Clock clock;
|
||||
/// Keeps track of the key from which to start reading on the next iteration
|
||||
private volatile KeySelector beginKeyCursor;
|
||||
@@ -128,7 +127,7 @@ class FoundationDbMessagePublisher {
|
||||
}
|
||||
|
||||
FoundationDbMessagePublisher(
|
||||
final Database database,
|
||||
final FaultTolerantDatabase database,
|
||||
final Clock clock,
|
||||
final KeySelector beginKeyInclusive,
|
||||
final KeySelector endKeyExclusive,
|
||||
@@ -175,7 +174,7 @@ class FoundationDbMessagePublisher {
|
||||
/// cases when callers need to "catch up" on stored messages without following fresh updates (for example, when a
|
||||
/// client first connects and needs to load stored messages before receiving a "live" stream of new messages).
|
||||
public static FoundationDbMessagePublisher createFinitePublisher(
|
||||
final Database database,
|
||||
final FaultTolerantDatabase database,
|
||||
final Clock clock,
|
||||
final KeySelector beginKeyInclusive,
|
||||
final KeySelector endKeyExclusive) {
|
||||
@@ -195,7 +194,7 @@ class FoundationDbMessagePublisher {
|
||||
/// It waits for new messages and publishes them in a loop. Useful when a client has finished receiving its stored
|
||||
/// messages and is now waiting for a live stream of new messages.
|
||||
public static FoundationDbMessagePublisher createInfinitePublisher(
|
||||
final Database database,
|
||||
final FaultTolerantDatabase database,
|
||||
final Clock clock,
|
||||
final KeySelector beginKeyInclusive,
|
||||
final KeySelector endKeyExclusive,
|
||||
@@ -312,7 +311,7 @@ class FoundationDbMessagePublisher {
|
||||
throw new IllegalArgumentException("Max messages must be positive");
|
||||
}
|
||||
|
||||
return FoundationDbUtil.safeRunAsync(database, transaction -> {
|
||||
return database.runAsync(transaction -> {
|
||||
final CompletableFuture<Void> checkPresenceFuture;
|
||||
|
||||
if (!terminateOnQueueEmpty) {
|
||||
@@ -339,7 +338,7 @@ class FoundationDbMessagePublisher {
|
||||
|
||||
return keyValues;
|
||||
});
|
||||
})
|
||||
}, FoundationDbUtil.Context.GET_MESSAGES_BATCH)
|
||||
.thenApply(keyValues -> {
|
||||
if (keyValues.size() < maxMessages) {
|
||||
transitionStateOnEvent(Event.FETCHED_ALL_AVAILABLE_MESSAGES);
|
||||
@@ -489,10 +488,10 @@ class FoundationDbMessagePublisher {
|
||||
return CompletableFuture.failedFuture(new IllegalStateException("Publisher already terminated"));
|
||||
}
|
||||
|
||||
return FoundationDbUtil.safeRunAsync(database, transaction -> {
|
||||
return database.runAsync(transaction -> {
|
||||
transaction.set(presenceKey, FoundationDbMessageStore.getPresenceValue(clock.instant(), streamId));
|
||||
return CompletableFuture.completedFuture(null);
|
||||
});
|
||||
}, FoundationDbUtil.Context.SET_PRESENCE);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
@@ -501,11 +500,11 @@ class FoundationDbMessagePublisher {
|
||||
renewPresenceFuture.cancel(true);
|
||||
|
||||
renewPresenceFuture.whenComplete((_, _) ->
|
||||
FoundationDbUtil.safeRunAsync(database, transaction -> transaction.get(presenceKey).thenAccept(presenceValue -> {
|
||||
database.runAsync(transaction -> transaction.get(presenceKey).thenAccept(presenceValue -> {
|
||||
if (!isPresenceContested(presenceValue)) {
|
||||
transaction.clear(presenceKey);
|
||||
}
|
||||
}))
|
||||
}), FoundationDbUtil.Context.CLEAR_PRESENCE)
|
||||
.whenComplete((_, throwable) -> {
|
||||
if (throwable != null) {
|
||||
LOGGER.warn("Failed to clear presence on disposal", throwable);
|
||||
|
||||
+63
-29
@@ -2,7 +2,6 @@ package org.whispersystems.textsecuregcm.storage.foundationdb;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.apple.foundationdb.Database;
|
||||
import com.apple.foundationdb.KeyArrayResult;
|
||||
import com.apple.foundationdb.MutationType;
|
||||
import com.apple.foundationdb.Range;
|
||||
@@ -12,6 +11,7 @@ import com.apple.foundationdb.tuple.Tuple;
|
||||
import com.apple.foundationdb.tuple.Versionstamp;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.common.hash.Hashing;
|
||||
import com.google.protobuf.InvalidProtocolBufferException;
|
||||
import io.dropwizard.util.DataSize;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.DistributionSummary;
|
||||
@@ -19,6 +19,7 @@ import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
@@ -70,8 +71,8 @@ import reactor.util.function.Tuples;
|
||||
/// * {versionstamp_2} => envelope_2
|
||||
public class FoundationDbMessageStore {
|
||||
|
||||
private final Database[][] databasesByEpoch;
|
||||
private final Map<Database, VersionstampClock> versionstampClocks;
|
||||
private final FaultTolerantDatabase[][] databasesByEpoch;
|
||||
private final Map<FaultTolerantDatabase, VersionstampClock> versionstampClocks;
|
||||
private final int[] liveEpochs;
|
||||
private final int activeEpoch;
|
||||
private final VersionstampUUIDCipher versionstampUUIDCipher;
|
||||
@@ -85,7 +86,7 @@ public class FoundationDbMessageStore {
|
||||
private static final byte[] SERVER_ID = UUIDUtil.toBytes(UUID.randomUUID());
|
||||
private static final int PRESENCE_VALUE_LENGTH = 28;
|
||||
|
||||
private static final Subspace MESSAGES_SUBSPACE = new Subspace(Tuple.from("M"));
|
||||
public static final Subspace MESSAGES_SUBSPACE = new Subspace(Tuple.from("M"));
|
||||
|
||||
@VisibleForTesting
|
||||
static final Duration PRESENCE_STALE_THRESHOLD = Duration.ofMinutes(5);
|
||||
@@ -130,7 +131,7 @@ public class FoundationDbMessageStore {
|
||||
boolean present) {
|
||||
}
|
||||
|
||||
public FoundationDbMessageStore(final Map<Integer, List<Database>> databasesByEpochMap,
|
||||
public FoundationDbMessageStore(final Map<Integer, List<FaultTolerantDatabase>> databasesByEpochMap,
|
||||
final int activeEpoch,
|
||||
final VersionstampUUIDCipher versionstampUUIDCipher,
|
||||
final ScheduledExecutorService presenceRenewalExecutorService,
|
||||
@@ -138,10 +139,10 @@ public class FoundationDbMessageStore {
|
||||
final Duration batchPriorityTransactionTimeout,
|
||||
final long batchPriorityTransactionRetryLimit) {
|
||||
|
||||
final Database[][] databasesByEpochArray = new Database[MAX_EPOCHS][];
|
||||
final FaultTolerantDatabase[][] databasesByEpochArray = new FaultTolerantDatabase[MAX_EPOCHS][];
|
||||
|
||||
databasesByEpochMap.forEach((epoch, databases) ->
|
||||
databasesByEpochArray[epoch] = databases.toArray(Database[]::new));
|
||||
databasesByEpochArray[epoch] = databases.toArray(FaultTolerantDatabase[]::new));
|
||||
|
||||
this.databasesByEpoch = databasesByEpochArray;
|
||||
this.liveEpochs = IntStream.range(0, MAX_EPOCHS).filter(e -> databasesByEpochArray[e] != null).toArray();
|
||||
@@ -303,7 +304,7 @@ public class FoundationDbMessageStore {
|
||||
}
|
||||
return CompletableFuture.completedFuture(Optional.<Versionstamp>empty());
|
||||
});
|
||||
})
|
||||
}, FoundationDbUtil.Context.INSERT_MESSAGE_BATCH)
|
||||
.thenCompose(Function.identity())
|
||||
.thenApply(maybeVersionstamp -> insertFuturesByAci.entrySet().stream()
|
||||
.collect(Collectors.toMap(Map.Entry::getKey, entry -> {
|
||||
@@ -394,13 +395,42 @@ public class FoundationDbMessageStore {
|
||||
return databasesByEpoch[getConfigurationEpoch(versionstamp)][getShardId(versionstamp)].runAsync(transaction -> {
|
||||
transaction.clear(messageKey);
|
||||
return CompletableFuture.completedFuture(null);
|
||||
})
|
||||
}, FoundationDbUtil.Context.DELETE_MESSAGE)
|
||||
.thenRun(() -> {
|
||||
sample.stop(DELETE_MESSAGE_TIMER);
|
||||
DELETE_MESSAGE_COUNTER.increment();
|
||||
});
|
||||
}
|
||||
|
||||
CompletableFuture<Optional<FoundationDbMessageStreamEntry.Message>> deleteAndGet(final AciServiceIdentifier aci, final byte deviceId, final UUID messageGuid) {
|
||||
return deleteAndGet(aci, deviceId, versionstampUUIDCipher.decryptVersionstamp(messageGuid, aci.uuid(), deviceId));
|
||||
}
|
||||
|
||||
CompletableFuture<Optional<FoundationDbMessageStreamEntry.Message>> deleteAndGet(final AciServiceIdentifier aci, final byte deviceId, final Versionstamp versionstamp) {
|
||||
final Timer.Sample sample = Timer.start();
|
||||
|
||||
final byte[] messageKey = getDeviceQueueSubspace(aci, deviceId).pack(Tuple.from(versionstamp));
|
||||
|
||||
return databasesByEpoch[getConfigurationEpoch(versionstamp)][getShardId(versionstamp)].runAsync(
|
||||
transaction -> transaction.get(messageKey)
|
||||
.thenApply(value -> {
|
||||
if (value == null) {
|
||||
return Optional.<byte[]>empty();
|
||||
}
|
||||
transaction.clear(messageKey);
|
||||
return Optional.of(value);
|
||||
}), FoundationDbUtil.Context.DELETE_MESSAGE)
|
||||
.whenComplete((_, _) -> sample.stop(DELETE_MESSAGE_TIMER))
|
||||
.thenApply(maybeValue -> maybeValue.map(value -> {
|
||||
DELETE_MESSAGE_COUNTER.increment();
|
||||
try {
|
||||
return new FoundationDbMessageStreamEntry.Message(versionstamp, MessageProtos.Envelope.parseFrom(value));
|
||||
} catch (final InvalidProtocolBufferException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
public void clearAll(final AciServiceIdentifier aci) {
|
||||
doForAllDatabasesWithMessages(aci, database -> database.run(transaction -> {
|
||||
transaction.clear(getAccountSubspace(aci).range());
|
||||
@@ -415,7 +445,7 @@ public class FoundationDbMessageStore {
|
||||
}));
|
||||
}
|
||||
|
||||
private void doForAllDatabasesWithMessages(final AciServiceIdentifier aci, final Consumer<Database> action) {
|
||||
private void doForAllDatabasesWithMessages(final AciServiceIdentifier aci, final Consumer<FaultTolerantDatabase> action) {
|
||||
IntStream.range(0, databasesByEpoch.length)
|
||||
.filter(epoch -> databasesByEpoch[epoch] != null)
|
||||
.mapToObj(epoch -> databasesByEpoch[epoch][hashAciToShardNumber(aci, epoch)])
|
||||
@@ -427,9 +457,9 @@ public class FoundationDbMessageStore {
|
||||
return getMessages(aci, deviceId, Util.NOOP);
|
||||
}
|
||||
|
||||
Database[] getDatabasesByEpochForAci(final AciServiceIdentifier aci) {
|
||||
FaultTolerantDatabase[] getDatabasesByEpochForAci(final AciServiceIdentifier aci) {
|
||||
// For each configured database epoch, which database held (or holds) the messages for this ACI/device pair?
|
||||
final Database[] databasesForQueueByEpoch = new Database[databasesByEpoch.length];
|
||||
final FaultTolerantDatabase[] databasesForQueueByEpoch = new FaultTolerantDatabase[databasesByEpoch.length];
|
||||
|
||||
for (final int epoch : liveEpochs) {
|
||||
databasesForQueueByEpoch[epoch] = getShardForAci(aci, epoch);
|
||||
@@ -443,7 +473,7 @@ public class FoundationDbMessageStore {
|
||||
final byte deviceId,
|
||||
final Runnable doAfterCleanup) {
|
||||
|
||||
final Database[] databasesForQueueByEpoch = getDatabasesByEpochForAci(aci);
|
||||
final FaultTolerantDatabase[] databasesForQueueByEpoch = getDatabasesByEpochForAci(aci);
|
||||
|
||||
return new FoundationDbMessageStream(this,
|
||||
aci,
|
||||
@@ -489,7 +519,7 @@ public class FoundationDbMessageStore {
|
||||
/// after it will not be. Deletion depends on the underlying [versionstamp clocks][VersionstampClock] being kept up to
|
||||
/// date.
|
||||
public void deleteMessagesBefore(final Map<AciServiceIdentifier, List<Byte>> accountDeviceIdentifiers, final Instant cutoffTime) {
|
||||
final Map<Database, List<Subspace>> queueSubspacesToTrimByDatabase = new IdentityHashMap<>();
|
||||
final Map<FaultTolerantDatabase, List<Subspace>> queueSubspacesToTrimByDatabase = new IdentityHashMap<>();
|
||||
|
||||
accountDeviceIdentifiers.forEach((aci, deviceIds) -> {
|
||||
for (final byte deviceId : deviceIds) {
|
||||
@@ -524,15 +554,14 @@ public class FoundationDbMessageStore {
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
Database getShardForAci(final AciServiceIdentifier aci, final int epoch) {
|
||||
FaultTolerantDatabase getShardForAci(final AciServiceIdentifier aci, final int epoch) {
|
||||
return getDatabases(epoch)[hashAciToShardNumber(aci, epoch)];
|
||||
}
|
||||
|
||||
private Database[] getDatabases(final int epoch) {
|
||||
private FaultTolerantDatabase[] getDatabases(final int epoch) {
|
||||
if (databasesByEpoch[epoch] == null) {
|
||||
throw new IllegalStateException("Epoch (%d) not in static configuration".formatted(epoch));
|
||||
}
|
||||
|
||||
return databasesByEpoch[epoch];
|
||||
}
|
||||
|
||||
@@ -575,9 +604,9 @@ public class FoundationDbMessageStore {
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
record QueueSizeAndRangeSplitPoints(long estimatedQueueSize, Map<Database, List<byte[]>> splitPointsByDatabase) {}
|
||||
record QueueSizeAndRangeSplitPoints(long estimatedQueueSize, Map<FaultTolerantDatabase, List<byte[]>> splitPointsByDatabase) {}
|
||||
|
||||
private Flux<Database> getDistinctDatabasesForAci(final AciServiceIdentifier aci) {
|
||||
private Flux<FaultTolerantDatabase> getDistinctDatabasesForAci(final AciServiceIdentifier aci) {
|
||||
return Flux.fromStream(Arrays.stream(getDatabasesByEpochForAci(aci)).filter(Objects::nonNull).distinct());
|
||||
}
|
||||
|
||||
@@ -590,7 +619,7 @@ public class FoundationDbMessageStore {
|
||||
final Range deviceQueueRange = getDeviceQueueSubspace(aci, deviceId).range();
|
||||
|
||||
return getDistinctDatabasesForAci(aci)
|
||||
.flatMap(database -> Mono.fromFuture(() -> FoundationDbUtil.safeRunAsync(database, transaction -> transaction.getEstimatedRangeSizeBytes(deviceQueueRange))))
|
||||
.flatMap(database -> Mono.fromFuture(() -> database.runAsync(transaction -> transaction.getEstimatedRangeSizeBytes(deviceQueueRange), FoundationDbUtil.Context.ESTIMATE_QUEUE_SIZE)))
|
||||
.reduce(0L, Long::sum);
|
||||
}
|
||||
|
||||
@@ -615,17 +644,17 @@ public class FoundationDbMessageStore {
|
||||
}
|
||||
|
||||
private CompletableFuture<Pair<Long, KeyArrayResult>> estimateQueueSizeAndRangeSplitsForDatabase(
|
||||
final Database database,
|
||||
final FaultTolerantDatabase database,
|
||||
final AciServiceIdentifier aci,
|
||||
final byte deviceId,
|
||||
final long rangeSplitChunkSize) {
|
||||
return FoundationDbUtil.safeRunAsync(database, transaction -> {
|
||||
return database.runAsync( transaction -> {
|
||||
final Range deviceQueueRange = getDeviceQueueSubspace(aci, deviceId).range();
|
||||
final CompletableFuture<Long> estimatedQueueSizeFuture = transaction.getEstimatedRangeSizeBytes(deviceQueueRange);
|
||||
|
||||
final CompletableFuture<KeyArrayResult> rangeSplitPointsFuture = transaction.getRangeSplitPoints(deviceQueueRange, rangeSplitChunkSize);
|
||||
return estimatedQueueSizeFuture.thenCombine(rangeSplitPointsFuture, Pair::new);
|
||||
});
|
||||
}, FoundationDbUtil.Context.ESTIMATE_QUEUE_SIZE_AND_RANGE_SPLITS);
|
||||
}
|
||||
|
||||
public Mono<Void> trimQueue(final AciServiceIdentifier aci,
|
||||
@@ -650,7 +679,7 @@ public class FoundationDbMessageStore {
|
||||
return Mono.empty();
|
||||
}
|
||||
|
||||
final List<Database> orderedDatabases;
|
||||
final List<FaultTolerantDatabase> orderedDatabases;
|
||||
{
|
||||
// Trim messages from the database(s) in the inactive epoch(s) before trimming from the database in the active epoch
|
||||
final List<Integer> orderedEpochsToTrim = new ArrayList<>(Arrays.stream(liveEpochs)
|
||||
@@ -707,18 +736,23 @@ public class FoundationDbMessageStore {
|
||||
});
|
||||
}
|
||||
|
||||
private CompletableFuture<Void> trimQueue(final Database database, final Range range) {
|
||||
return FoundationDbUtil.safeRunAsync(database, transaction -> {
|
||||
private CompletableFuture<Void> trimQueue(final FaultTolerantDatabase database, final Range range) {
|
||||
return database.runAsync(transaction -> {
|
||||
transaction.options().setPriorityBatch();
|
||||
transaction.options().setTimeout(batchPriorityTransactionTimeout.toMillis());
|
||||
transaction.options().setRetryLimit(batchPriorityTransactionRetryLimit);
|
||||
transaction.clear(range);
|
||||
return CompletableFuture.completedFuture(null);
|
||||
});
|
||||
}, FoundationDbUtil.Context.TRIM_QUEUE);
|
||||
}
|
||||
|
||||
private static Subspace getAccountSubspace(final AciServiceIdentifier aci) {
|
||||
return MESSAGES_SUBSPACE.get(aci.uuid());
|
||||
@VisibleForTesting
|
||||
public static Subspace getAccountSubspace(final AciServiceIdentifier aci) {
|
||||
return getAccountSubspace(MESSAGES_SUBSPACE, aci);
|
||||
}
|
||||
|
||||
public static Subspace getAccountSubspace(final Subspace messagesSubspace, final AciServiceIdentifier aci) {
|
||||
return messagesSubspace.get(aci.uuid());
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
|
||||
+21
-9
@@ -2,7 +2,6 @@ package org.whispersystems.textsecuregcm.storage.foundationdb;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.apple.foundationdb.Database;
|
||||
import com.apple.foundationdb.KeySelector;
|
||||
import com.apple.foundationdb.StreamingMode;
|
||||
import com.apple.foundationdb.subspace.Subspace;
|
||||
@@ -42,7 +41,7 @@ public class FoundationDbMessageStream implements MessageStream {
|
||||
private final Subspace deviceQueueSubspace;
|
||||
private final byte[] presenceKey;
|
||||
private final byte[] messagesAvailableWatchKey;
|
||||
private final Database[] databasesByEpoch;
|
||||
private final FaultTolerantDatabase[] databasesByEpoch;
|
||||
private final MessageGuidCodec messageGuidCodec;
|
||||
/// The maximum number of messages we will fetch per range query operation to avoid excessive memory consumption
|
||||
private final Flow.Publisher<MessageStreamEntry> messageStreamPublisher;
|
||||
@@ -71,7 +70,7 @@ public class FoundationDbMessageStream implements MessageStream {
|
||||
FoundationDbMessageStream(final FoundationDbMessageStore foundationDbMessageStore,
|
||||
final AciServiceIdentifier aciServiceIdentifier,
|
||||
final byte deviceId,
|
||||
final Database[] databasesByEpoch,
|
||||
final FaultTolerantDatabase[] databasesByEpoch,
|
||||
final MessageGuidCodec messageGuidCodec,
|
||||
final Runnable doAfterCleanup,
|
||||
final ScheduledExecutorService presenceRenewalExecutorService,
|
||||
@@ -126,7 +125,7 @@ public class FoundationDbMessageStream implements MessageStream {
|
||||
private Flux<FoundationDbMessageStreamEntry> createFoundationDbMessagePublisher() {
|
||||
// This may seem like an odd construction since it looks like we could also just do `Flux#fromArray`, but
|
||||
// `Flux#fromArray` cannot handle `null` elements
|
||||
final List<Database> databases = Arrays.stream(databasesByEpoch).filter(Objects::nonNull).distinct().toList();
|
||||
final List<FaultTolerantDatabase> databases = Arrays.stream(databasesByEpoch).filter(Objects::nonNull).distinct().toList();
|
||||
|
||||
return Flux.fromIterable(databases)
|
||||
.flatMap(database -> Mono.fromFuture(() -> getEndOfQueueKeyExclusive(database))
|
||||
@@ -136,7 +135,7 @@ public class FoundationDbMessageStream implements MessageStream {
|
||||
@SuppressWarnings("unchecked") final Flux<FoundationDbMessageStreamEntry.Message>[] finitePublishers =
|
||||
endOfQueueKeysByDatabase.entrySet().stream()
|
||||
.map(entry -> {
|
||||
final Database database = entry.getKey();
|
||||
final FaultTolerantDatabase database = entry.getKey();
|
||||
final Optional<KeySelector> maybeEndOfQueueKeyExclusive = entry.getValue();
|
||||
|
||||
return maybeEndOfQueueKeyExclusive
|
||||
@@ -165,7 +164,7 @@ public class FoundationDbMessageStream implements MessageStream {
|
||||
@SuppressWarnings("unchecked") final Flux<FoundationDbMessageStreamEntry.Message>[] infinitePublishers =
|
||||
endOfQueueKeysByDatabase.entrySet().stream()
|
||||
.map(entry -> {
|
||||
final Database database = entry.getKey();
|
||||
final FaultTolerantDatabase database = entry.getKey();
|
||||
final Optional<KeySelector> maybeEndOfQueueKeyExclusive = entry.getValue();
|
||||
|
||||
final KeySelector infinitePublisherBeginKey = maybeEndOfQueueKeyExclusive
|
||||
@@ -204,9 +203,9 @@ public class FoundationDbMessageStream implements MessageStream {
|
||||
/// subsequent scan.
|
||||
///
|
||||
/// @return a [KeySelector] for the first key greater than the current greatest key in the device queue.
|
||||
private CompletableFuture<Optional<KeySelector>> getEndOfQueueKeyExclusive(final Database database) {
|
||||
return FoundationDbUtil.safeRunAsync(database, transaction ->
|
||||
transaction.getRange(deviceQueueSubspace.range(), 1, true, StreamingMode.EXACT).asList())
|
||||
private CompletableFuture<Optional<KeySelector>> getEndOfQueueKeyExclusive(final FaultTolerantDatabase database) {
|
||||
return database.runAsync(transaction ->
|
||||
transaction.getRange(deviceQueueSubspace.range(), 1, true, StreamingMode.EXACT).asList(), FoundationDbUtil.Context.GET_END_OF_QUEUE)
|
||||
.<Optional<KeySelector>>thenApply(items -> {
|
||||
if (items.isEmpty()) {
|
||||
return Optional.empty();
|
||||
@@ -227,4 +226,17 @@ public class FoundationDbMessageStream implements MessageStream {
|
||||
|
||||
return foundationDbMessageStore.delete(aciServiceIdentifier, deviceId, messageGuid);
|
||||
}
|
||||
|
||||
public CompletableFuture<Optional<MessageStreamEntry.Envelope>> acknowledgeAndGetMessage(final UUID messageGuid) {
|
||||
messageAcknowledgedCounter.increment();
|
||||
|
||||
return foundationDbMessageStore.deleteAndGet(aciServiceIdentifier, deviceId, messageGuid)
|
||||
.thenApply(foundationDbMessageStreamEntry -> foundationDbMessageStreamEntry.map(m -> {
|
||||
final MessageStreamEntry messageStreamEntry = m.toMessageStreamEntry(messageGuidCodec);
|
||||
if (!(messageStreamEntry instanceof MessageStreamEntry.Envelope)) {
|
||||
throw new AssertionError("Expected MessageStreamEntry.Envelope, got " + messageStreamEntry);
|
||||
}
|
||||
return (MessageStreamEntry.Envelope) messageStreamEntry;
|
||||
}));
|
||||
}
|
||||
}
|
||||
+25
-17
@@ -1,24 +1,32 @@
|
||||
package org.whispersystems.textsecuregcm.storage.foundationdb;
|
||||
|
||||
import com.apple.foundationdb.Database;
|
||||
import com.apple.foundationdb.Transaction;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.Function;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
|
||||
public class FoundationDbUtil {
|
||||
|
||||
/// Returns a cancellation-safe version of the result from [Database#runAsync(Function)]. Since the final stage
|
||||
/// of the result from [Database#runAsync(Function)] is a cleanup stage that closes the transaction, the
|
||||
/// transaction leaks if the future gets cancelled and the cleanup stage is skipped. So, we add another dummy stage
|
||||
/// that serves as the cancellation target and the cleanup can proceed as normal.
|
||||
///
|
||||
/// @param database the FoundationDB database instance
|
||||
/// @param retryable the block of transaction logic to execute
|
||||
/// @param <T> the return type of retryable
|
||||
/// @return a cancellation-safe version of the future returned from [Database#runAsync(Function)]
|
||||
public static <T> CompletableFuture<T> safeRunAsync(final Database database,
|
||||
final Function<? super Transaction, ? extends CompletableFuture<T>> retryable) {
|
||||
return database.runAsync(retryable)
|
||||
.thenApply(Function.identity());
|
||||
public enum Context {
|
||||
INSERT_MESSAGE_BATCH("insertMessageBatch"),
|
||||
GET_MESSAGES_BATCH("getMessagesBatch"),
|
||||
SET_PRESENCE("setPresence"),
|
||||
GET_PRESENCE("getPresence"),
|
||||
CLEAR_PRESENCE("clearPresence"),
|
||||
GET_END_OF_QUEUE("getEndOfQueue"),
|
||||
ESTIMATE_QUEUE_SIZE("estimateQueueSize"),
|
||||
ESTIMATE_QUEUE_SIZE_AND_RANGE_SPLITS("estimateQueueSizeAndRangeSplits"),
|
||||
GET_RANGE_SPLITS("getRangeSplits"),
|
||||
TRIM_QUEUE("trimQueue"),
|
||||
DELETE_MESSAGE("deleteMessage");
|
||||
|
||||
private final String name;
|
||||
|
||||
Context(final String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
}
|
||||
|
||||
static final String TRANSACTION_ERRORS_COUNTER = MetricsUtil.name(FoundationDbUtil.class, "transactionErrors");
|
||||
}
|
||||
+3
-4
@@ -5,7 +5,6 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage.foundationdb;
|
||||
|
||||
import com.apple.foundationdb.Database;
|
||||
import com.apple.foundationdb.KeyValue;
|
||||
import com.apple.foundationdb.MutationType;
|
||||
import com.apple.foundationdb.subspace.Subspace;
|
||||
@@ -29,15 +28,15 @@ public class VersionstampClock {
|
||||
@VisibleForTesting
|
||||
static final Subspace SUBSPACE = new Subspace(Tuple.from("V"));
|
||||
|
||||
private final Database database;
|
||||
private final FaultTolerantDatabase database;
|
||||
private final Clock clock;
|
||||
|
||||
public VersionstampClock(final Database database) {
|
||||
public VersionstampClock(final FaultTolerantDatabase database) {
|
||||
this(database, Clock.systemUTC());
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
public VersionstampClock(final Database database, final Clock clock) {
|
||||
public VersionstampClock(final FaultTolerantDatabase database, final Clock clock) {
|
||||
this.database = database;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.util;
|
||||
|
||||
import com.google.i18n.phonenumbers.NumberParseException;
|
||||
import java.util.List;
|
||||
|
||||
/// An alternate phone number form generator produces a list of equivalent phone numbers to the given phone number. This
|
||||
/// is useful in cases where a numbering authority has changed the numbering format for a region or in cases where
|
||||
/// multiple formats of a number may be valid in different circumstances. Numbers are considered equivalent if a
|
||||
/// call/message sent to each number will generally arrive at the same device.
|
||||
public interface AlternatePhoneNumberFormGenerator {
|
||||
|
||||
AlternatePhoneNumberFormGenerator IDENTITY = List::of;
|
||||
|
||||
/// Returns a list of equivalent phone numbers to the given phone number.
|
||||
///
|
||||
/// @apiNote This method is intended to support number format transitions in cases where we do not already have
|
||||
/// multiple accounts registered with different forms of the same number. As a result, this method does not cover all
|
||||
/// possible cases of equivalent formats, but instead focuses on the cases where we can and choose to prevent multiple
|
||||
/// accounts from using different formats of the same number.
|
||||
///
|
||||
/// @param number the e164-formatted phone number for which to find equivalent forms
|
||||
///
|
||||
/// @return a list of phone numbers equivalent to the given phone number, including the given number. The given number
|
||||
/// will always be the first element of the list.
|
||||
///
|
||||
/// @throws NumberParseException if `number` could not be parsed as a phone number for any reason
|
||||
List<String> getAlternateForms(String number) throws NumberParseException;
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.util;
|
||||
|
||||
import com.google.i18n.phonenumbers.NumberParseException;
|
||||
import com.google.i18n.phonenumbers.PhoneNumberUtil;
|
||||
import com.google.i18n.phonenumbers.Phonenumber;
|
||||
import org.apache.commons.lang3.Strings;
|
||||
import java.util.List;
|
||||
|
||||
// Benin changed phone number formats from +229 XXXXXXXX to +229 01XXXXXXXX on November 30, 2024
|
||||
class BeninAlternateFormGenerator implements AlternatePhoneNumberFormGenerator {
|
||||
|
||||
@Override
|
||||
public List<String> getAlternateForms(final String number) throws NumberParseException {
|
||||
final Phonenumber.PhoneNumber phoneNumber = PhoneNumberUtil.getInstance().parse(number, null);
|
||||
|
||||
final String nationalSignificantNumber = PhoneNumberUtil.getInstance().getNationalSignificantNumber(phoneNumber);
|
||||
final String alternateE164;
|
||||
|
||||
if (nationalSignificantNumber.length() == 10) {
|
||||
// This is a new-format number; we can get the old-format version by stripping the leading "01" from the
|
||||
// national number
|
||||
alternateE164 = "+229" + Strings.CS.removeStart(nationalSignificantNumber, "01");
|
||||
} else {
|
||||
// This is an old-format number; we can get the new-format version by adding a "01" prefix to the national
|
||||
// number
|
||||
alternateE164 = "+22901" + nationalSignificantNumber;
|
||||
}
|
||||
|
||||
return number.equals(alternateE164) ? List.of(number) : List.of(number, alternateE164);
|
||||
}
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.util;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.i18n.phonenumbers.NumberParseException;
|
||||
import com.google.i18n.phonenumbers.PhoneNumberUtil;
|
||||
import com.google.i18n.phonenumbers.Phonenumber;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/// Generates alternate forms of Gambian phone numbers as [specified by
|
||||
/// PURA](https://pura.gm/public-notice-migration-of-the-national-mobile-numbering-plan-from-7-digit-to-9-digit-format/).
|
||||
class GambiaAlternateFormGenerator implements AlternatePhoneNumberFormGenerator {
|
||||
|
||||
// Please see https://pura.gm/wp-content/uploads/2026/07/PURA_Website_NNP_Migration_Public_Notice.pdf for number
|
||||
// format details.
|
||||
enum Carrier {
|
||||
QCELL("83", Pattern.compile("^(3\\d{6})|(5[012345789]\\d{5})$")),
|
||||
COMIUM("86", Pattern.compile("^(6\\d{6})|(8[4567]\\d{5})$")),
|
||||
AFRICELL("87", Pattern.compile("^([27]\\d{6})|(4[015]\\d{5})$"));
|
||||
|
||||
private final String newPrefix;
|
||||
private final Pattern legacyNumberPattern;
|
||||
|
||||
Carrier(final String newPrefix, final Pattern legacyNumberPattern) {
|
||||
this.newPrefix = newPrefix;
|
||||
this.legacyNumberPattern = legacyNumberPattern;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> getAlternateForms(final String number) throws NumberParseException {
|
||||
final Phonenumber.PhoneNumber phoneNumber = PhoneNumberUtil.getInstance().parse(number, null);
|
||||
final String nationalSignificantNumber = PhoneNumberUtil.getInstance().getNationalSignificantNumber(phoneNumber);
|
||||
|
||||
final Optional<String> maybeAlternateForm = getCarrier(nationalSignificantNumber)
|
||||
.map(carrier -> {
|
||||
if (nationalSignificantNumber.length() == 7) {
|
||||
// This is a legacy number, and we need to add the carrier's prefix to get the updated form
|
||||
return "+220" + carrier.newPrefix + nationalSignificantNumber;
|
||||
} else {
|
||||
// This is a new-style number, and we need to strip the carrier's prefix to get the legacy form
|
||||
return "+220" + nationalSignificantNumber.substring(carrier.newPrefix.length());
|
||||
}
|
||||
});
|
||||
|
||||
return maybeAlternateForm
|
||||
.map(alternateForm -> List.of(number, alternateForm))
|
||||
.orElseGet(() -> List.of(number));
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static Optional<Carrier> getCarrier(final String nationalSignificantNumber) {
|
||||
if (nationalSignificantNumber.length() == 9) {
|
||||
// This might be a new-style number; see if we can find a carrier by prefix
|
||||
return Arrays.stream(Carrier.values())
|
||||
.filter(carrier -> nationalSignificantNumber.startsWith(carrier.newPrefix))
|
||||
.findFirst();
|
||||
} else if (nationalSignificantNumber.length() == 7) {
|
||||
// This might be an old-style number belonging to a carrier with a new prefix; match by pattern if we can
|
||||
return Arrays.stream(Carrier.values())
|
||||
.filter(carrier -> carrier.legacyNumberPattern.matcher(nationalSignificantNumber).matches())
|
||||
.findFirst();
|
||||
}
|
||||
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
@@ -15,16 +15,17 @@ import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Locale.LanguageRange;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.commons.lang3.Strings;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
|
||||
public class Util {
|
||||
@@ -36,6 +37,14 @@ public class Util {
|
||||
public static final String COUNTRY_CODE_NOT_APPLICABLE = "n/a";
|
||||
public static final String REGION_NOT_APPLICABLE = "n/a";
|
||||
|
||||
// We use a `HashMap` because `HashMap` allows for null keys at query time, and `PhoneNumberUtil` may return a null
|
||||
// region code for some phone numbers
|
||||
private static final Map<String, AlternatePhoneNumberFormGenerator> ALTERNATE_FORM_GENERATORS_BY_REGION =
|
||||
new HashMap<>(Map.of(
|
||||
"BJ", new BeninAlternateFormGenerator(),
|
||||
"GM", new GambiaAlternateFormGenerator()
|
||||
));
|
||||
|
||||
// Use `CompletableFuture#thenApply(ASYNC_EMPTY_RESPONSE) to convert futures to
|
||||
// CompletableFuture<Response> instead of using NOOP to convert them to CompletableFuture<Void>
|
||||
// for jersey controllers; https://github.com/eclipse-ee4j/jersey/issues/3901 causes controllers
|
||||
@@ -131,25 +140,9 @@ public class Util {
|
||||
try {
|
||||
final PhoneNumber phoneNumber = PHONE_NUMBER_UTIL.parse(number, null);
|
||||
|
||||
// Benin changed phone number formats from +229 XXXXXXXX to +229 01XXXXXXXX on November 30, 2024
|
||||
if ("BJ".equals(PHONE_NUMBER_UTIL.getRegionCodeForNumber(phoneNumber))) {
|
||||
final String nationalSignificantNumber = PHONE_NUMBER_UTIL.getNationalSignificantNumber(phoneNumber);
|
||||
final String alternateE164;
|
||||
|
||||
if (nationalSignificantNumber.length() == 10) {
|
||||
// This is a new-format number; we can get the old-format version by stripping the leading "01" from the
|
||||
// national number
|
||||
alternateE164 = "+229" + Strings.CS.removeStart(nationalSignificantNumber, "01");
|
||||
} else {
|
||||
// This is an old-format number; we can get the new-format version by adding a "01" prefix to the national
|
||||
// number
|
||||
alternateE164 = "+22901" + nationalSignificantNumber;
|
||||
}
|
||||
|
||||
return number.equals(alternateE164) ? List.of(number) : List.of(number, alternateE164);
|
||||
}
|
||||
|
||||
return List.of(number);
|
||||
return ALTERNATE_FORM_GENERATORS_BY_REGION.getOrDefault(PHONE_NUMBER_UTIL.getRegionCodeForNumber(phoneNumber),
|
||||
AlternatePhoneNumberFormGenerator.IDENTITY)
|
||||
.getAlternateForms(number);
|
||||
} catch (final NumberParseException e) {
|
||||
return List.of(number);
|
||||
}
|
||||
|
||||
+324
@@ -0,0 +1,324 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.workers;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStore.getAccountSubspace;
|
||||
|
||||
import com.apple.foundationdb.FDB;
|
||||
import com.apple.foundationdb.KeySelector;
|
||||
import com.apple.foundationdb.Range;
|
||||
import com.apple.foundationdb.ReadTransaction;
|
||||
import com.apple.foundationdb.async.AsyncUtil;
|
||||
import com.apple.foundationdb.subspace.Subspace;
|
||||
import com.apple.foundationdb.tuple.ByteArrayUtil;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.dropwizard.core.Application;
|
||||
import io.dropwizard.core.setup.Environment;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Stream;
|
||||
import net.sourceforge.argparse4j.inf.Namespace;
|
||||
import net.sourceforge.argparse4j.inf.Subparser;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountLockManager;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.FaultTolerantDatabase;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStore;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbUtil;
|
||||
import org.whispersystems.textsecuregcm.util.ManagedExecutors;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.util.retry.Retry;
|
||||
|
||||
public class ClearOrphanedFoundationDbQueuesCommand extends AbstractCommandWithDependencies {
|
||||
|
||||
private final Logger logger = LoggerFactory.getLogger(getClass());
|
||||
|
||||
private final Subspace messagesSubspace;
|
||||
|
||||
private static final String DRY_RUN_ARGUMENT = "dry-run";
|
||||
|
||||
private static final String CONCURRENCY_ARGUMENT = "concurrency";
|
||||
private static final int DEFAULT_CONCURRENCY = 16;
|
||||
|
||||
private static final String MAX_ACIS_PER_TRANSACTION_ARGUMENT = "max-acis-per-transaction";
|
||||
private static final int DEFAULT_MAX_ACIS_PER_TRANSACTION = 128;
|
||||
|
||||
private static final String CHUNKS_PER_SHARD_ARGUMENT = "chunks-per-shard";
|
||||
private static final int DEFAULT_CHUNKS_PER_SHARD = 100;
|
||||
|
||||
private static final String ACCOUNTS_CRAWLED_COUNTER = MetricsUtil.name(ClearOrphanedFoundationDbQueuesCommand.class,
|
||||
"accountsCrawled");
|
||||
private static final String ORPHANED_QUEUES_CLEARED = MetricsUtil.name(ClearOrphanedFoundationDbQueuesCommand.class,
|
||||
"orphanedQueuesCleared");
|
||||
|
||||
|
||||
public ClearOrphanedFoundationDbQueuesCommand() {
|
||||
this(FoundationDbMessageStore.MESSAGES_SUBSPACE);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
public ClearOrphanedFoundationDbQueuesCommand(final Subspace messagesSubspace) {
|
||||
super(new Application<>() {
|
||||
@Override
|
||||
public void run(final WhisperServerConfiguration configuration, final Environment environment) {
|
||||
}
|
||||
}, "clear-orphaned-foundationdb-queues", "Clear FoundationDB queues that have no active account");
|
||||
this.messagesSubspace = messagesSubspace;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configure(final Subparser subparser) {
|
||||
super.configure(subparser);
|
||||
|
||||
subparser.addArgument("--concurrency")
|
||||
.type(Integer.class)
|
||||
.dest(CONCURRENCY_ARGUMENT)
|
||||
.required(false)
|
||||
.setDefault(DEFAULT_CONCURRENCY)
|
||||
.help("The maximum number of parallel dynamodb operations to process concurrently");
|
||||
|
||||
subparser.addArgument("--dry-run")
|
||||
.type(Boolean.class)
|
||||
.dest(DRY_RUN_ARGUMENT)
|
||||
.required(false)
|
||||
.setDefault(true)
|
||||
.help("If true, don't actually clear orphaned queues");
|
||||
|
||||
subparser.addArgument("--max-acis-per-transaction")
|
||||
.type(Integer.class)
|
||||
.dest(MAX_ACIS_PER_TRANSACTION_ARGUMENT)
|
||||
.required(false)
|
||||
.setDefault(DEFAULT_MAX_ACIS_PER_TRANSACTION)
|
||||
.help("The maximum number of ACIs to read per FoundationDB transaction");
|
||||
|
||||
subparser.addArgument("--chunks-per-shard")
|
||||
.type(Integer.class)
|
||||
.dest(CHUNKS_PER_SHARD_ARGUMENT)
|
||||
.required(false)
|
||||
.setDefault(DEFAULT_CHUNKS_PER_SHARD)
|
||||
.help("The number of chunks to split the the key-space into, each of which will be crawled in parallel");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void run(final Environment environment, final Namespace namespace,
|
||||
final WhisperServerConfiguration configuration, final CommandDependencies commandDependencies) throws Exception {
|
||||
|
||||
final int concurrency = Objects.requireNonNull(namespace.getInt(CONCURRENCY_ARGUMENT));
|
||||
final boolean dryRun = Objects.requireNonNull(namespace.getBoolean(DRY_RUN_ARGUMENT));
|
||||
final int maxAcisPerTransaction = Objects.requireNonNull(namespace.getInt(MAX_ACIS_PER_TRANSACTION_ARGUMENT));
|
||||
final int chunksPerShard = Objects.requireNonNull(namespace.getInt(CHUNKS_PER_SHARD_ARGUMENT));
|
||||
|
||||
final FDB fdb = commandDependencies.fdb();
|
||||
|
||||
final Stream<FaultTolerantDatabase> databases = configuration.getFoundationDbMessagesConfiguration().clusters().entrySet().stream()
|
||||
.map(entry -> {
|
||||
try {
|
||||
return new FaultTolerantDatabase(entry.getValue().build(fdb), entry.getKey(),
|
||||
configuration.getFoundationDbMessagesConfiguration().circuitBreakerConfigurationName());
|
||||
} catch (final IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
});
|
||||
final ExecutorService executorService = ManagedExecutors.newVirtualThreadPerTaskExecutor("clearOrphanedQueues",
|
||||
configuration.getVirtualThreadConfiguration().maxConcurrentThreadsPerExecutor(), environment);
|
||||
clearOrphanedQueues(databases, commandDependencies.accountsManager(), concurrency, dryRun, maxAcisPerTransaction,
|
||||
configuration.getFoundationDbMessagesConfiguration().batchPriorityTransactionRetryLimit(),
|
||||
configuration.getFoundationDbMessagesConfiguration().batchPriorityTransactionTimeout(),
|
||||
chunksPerShard,
|
||||
commandDependencies.accountLockManager(),
|
||||
executorService);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
void clearOrphanedQueues(final Stream<FaultTolerantDatabase> databases, final AccountsManager accountsManager,
|
||||
final int concurrency, final boolean dryRun, final int maxAcisPerTransaction, final long transactionRetryLimit,
|
||||
final Duration transactionTimeout, final int numChunks, final AccountLockManager accountLockManager,
|
||||
final Executor executor) {
|
||||
Flux.fromStream(databases)
|
||||
.flatMap(database -> crawlAcisInShard(database, accountsManager, concurrency, dryRun, maxAcisPerTransaction,
|
||||
transactionRetryLimit, transactionTimeout, numChunks, accountLockManager, executor))
|
||||
.then()
|
||||
.block();
|
||||
}
|
||||
|
||||
private Mono<Void> crawlAcisInShard(final FaultTolerantDatabase database, final AccountsManager accountsManager,
|
||||
final int concurrency, final boolean dryRun, final int maxAcisPerTransaction, final long transactionRetryLimit,
|
||||
final Duration transactionTimeout, final int numChunks, final AccountLockManager accountLockManager,
|
||||
final Executor executor) {
|
||||
return getAcisInShard(database, maxAcisPerTransaction, transactionRetryLimit, transactionTimeout, numChunks)
|
||||
.doOnNext(_ -> Metrics.counter(ACCOUNTS_CRAWLED_COUNTER, "dryRun", String.valueOf(dryRun)).increment())
|
||||
.flatMap(aci -> Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(aci.uuid()))
|
||||
.flatMap(maybeAccount -> {
|
||||
if (maybeAccount.isEmpty()) {
|
||||
return Mono.just(aci);
|
||||
}
|
||||
return Mono.empty();
|
||||
})
|
||||
.retryWhen(Retry.backoff(2, Duration.ofSeconds(1)))
|
||||
.onErrorResume(t -> {
|
||||
logger.warn("Failed to fetch account by ACI", t);
|
||||
return Mono.empty();
|
||||
})
|
||||
, concurrency)
|
||||
.flatMap(aci -> {
|
||||
if (dryRun) {
|
||||
logger.info("Would have cleared queue for ACI: {}", aci.uuid());
|
||||
return Mono.just(true);
|
||||
}
|
||||
return clearQueueWithAciLock(database, aci, transactionRetryLimit, transactionTimeout, accountsManager,
|
||||
accountLockManager, executor)
|
||||
.thenReturn(true)
|
||||
.onErrorResume(t -> {
|
||||
logger.error("Failed to clear orphaned queue for ACI: {}", aci.uuid(), t);
|
||||
return Mono.just(false);
|
||||
});
|
||||
})
|
||||
.doOnNext(success -> Metrics.counter(ORPHANED_QUEUES_CLEARED,
|
||||
"dryRun", String.valueOf(dryRun),
|
||||
"success", String.valueOf(success)).increment())
|
||||
.then();
|
||||
}
|
||||
|
||||
private Mono<Void> clearQueueWithAciLock(final FaultTolerantDatabase database, final AciServiceIdentifier aci,
|
||||
final long transactionRetryLimit, final Duration transactionTimeout, final AccountsManager accountsManager,
|
||||
final AccountLockManager accountLockManager,
|
||||
final Executor executor) {
|
||||
return Mono.fromFuture(
|
||||
() -> CompletableFuture.runAsync(() -> accountLockManager.withLock(Set.of(aci.uuid()), () -> {
|
||||
if (accountsManager.getByAccountIdentifier(aci.uuid()).isPresent()) {
|
||||
logger.info("ACI re-used after we checked for existence, not clearing its queues: {}", aci.uuid());
|
||||
return null;
|
||||
}
|
||||
clearQueue(database, aci, transactionRetryLimit, transactionTimeout);
|
||||
return null;
|
||||
}), executor));
|
||||
}
|
||||
|
||||
private void clearQueue(final FaultTolerantDatabase database, final AciServiceIdentifier aci, final long transactionRetryLimit,
|
||||
final Duration transactionTimeout) {
|
||||
database.run(transaction -> {
|
||||
transaction.options().setPriorityBatch();
|
||||
transaction.options().setRetryLimit(transactionRetryLimit);
|
||||
transaction.options().setTimeout(transactionTimeout.toMillis());
|
||||
transaction.clear(getAccountSubspace(messagesSubspace, aci).range());
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
Flux<AciServiceIdentifier> getAcisInShard(final FaultTolerantDatabase database, final int maxAcisPerTransaction,
|
||||
final long transactionRetryLimit, final Duration transactionTimeout, final int numChunks) {
|
||||
return Mono.fromFuture(() -> splitSubspace(database, numChunks))
|
||||
.flatMapIterable(Function.identity())
|
||||
.flatMap(
|
||||
range -> getAcisInChunk(database, maxAcisPerTransaction, transactionRetryLimit, transactionTimeout, range));
|
||||
}
|
||||
|
||||
/// Split the messages subspace into roughly equally sized \`numChunks\` chunks, each of which can be crawled in
|
||||
/// parallel
|
||||
///
|
||||
/// @param database the FDB instance
|
||||
/// @param numChunks the number of chunks to split the subspace into
|
||||
/// @return a list of key [Range]s representing chunk boundaries
|
||||
CompletableFuture<List<Range>> splitSubspace(final FaultTolerantDatabase database, final int numChunks) {
|
||||
return database.runAsync(transaction -> transaction.getEstimatedRangeSizeBytes(messagesSubspace.range())
|
||||
.thenCompose(rangeSize -> {
|
||||
final long chunkSize = Math.ceilDiv(rangeSize, numChunks);
|
||||
return transaction.getRangeSplitPoints(messagesSubspace.range(), chunkSize);
|
||||
}), FoundationDbUtil.Context.GET_RANGE_SPLITS)
|
||||
.thenApply(result -> splitPointsToRanges(result.getKeys()));
|
||||
}
|
||||
|
||||
private static List<Range> splitPointsToRanges(final List<byte[]> splitPoints) {
|
||||
if (splitPoints.size() < 2) {
|
||||
throw new IllegalArgumentException("Expected at least two split points");
|
||||
}
|
||||
final int numSplitPoints = splitPoints.size();
|
||||
final List<Range> ranges = new ArrayList<>();
|
||||
for (int i = 0; i < numSplitPoints - 1; i++) {
|
||||
ranges.add(new Range(splitPoints.get(i), splitPoints.get(i + 1)));
|
||||
}
|
||||
return ranges;
|
||||
}
|
||||
|
||||
Flux<AciServiceIdentifier> getAcisInChunk(final FaultTolerantDatabase database, final int maxAcisPerTransaction,
|
||||
final long transactionRetryLimit, final Duration transactionTimeout, final Range range) {
|
||||
return readAciBatch(database, range.begin, range.end, maxAcisPerTransaction, transactionRetryLimit,
|
||||
transactionTimeout)
|
||||
.expand(result -> {
|
||||
if (result.acis().isEmpty()) {
|
||||
return Mono.empty();
|
||||
}
|
||||
return readAciBatch(database, result.cursor(), range.end, maxAcisPerTransaction, transactionRetryLimit,
|
||||
transactionTimeout);
|
||||
})
|
||||
.limitRate(1)
|
||||
.flatMapIterable(BatchReadResult::acis);
|
||||
}
|
||||
|
||||
private record BatchReadResult(List<AciServiceIdentifier> acis, byte[] cursor) {}
|
||||
|
||||
private Mono<BatchReadResult> readAciBatch(
|
||||
final FaultTolerantDatabase database,
|
||||
final byte[] beginInclusive,
|
||||
final byte[] endExclusive,
|
||||
final int maxAcisPerTransaction,
|
||||
final long transactionRetryLimit,
|
||||
final Duration transactionTimeout) {
|
||||
|
||||
final AtomicReference<byte[]> cursor = new AtomicReference<>(beginInclusive);
|
||||
final AtomicInteger numAcisRead = new AtomicInteger();
|
||||
return Mono.fromFuture(() -> database.readAsync(transaction -> {
|
||||
final ReadTransaction readTransaction = transaction.snapshot();
|
||||
readTransaction.options().setPriorityBatch();
|
||||
readTransaction.options().setRetryLimit(transactionRetryLimit);
|
||||
readTransaction.options().setTimeout(transactionTimeout.toMillis());
|
||||
final List<AciServiceIdentifier> acis = new ArrayList<>();
|
||||
return AsyncUtil.whileTrue(() -> {
|
||||
if (ByteArrayUtil.compareUnsigned(cursor.get(), endExclusive) >= 0) {
|
||||
return CompletableFuture.completedFuture(false);
|
||||
}
|
||||
return readTransaction.getKey(KeySelector.firstGreaterOrEqual(cursor.get())).thenApply(key -> {
|
||||
if (ByteArrayUtil.compareUnsigned(key, endExclusive) >= 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
final AciServiceIdentifier aci = getAciFromKey(key);
|
||||
acis.add(aci);
|
||||
// Skip the specified ACI's entire subspace by incrementing the account prefix; this way,
|
||||
// [KeySelector#firstGreaterOrEqual] should resolve to the next available ACI (if one exists)
|
||||
cursor.set(ByteArrayUtil.strinc(getAccountSubspace(messagesSubspace, aci).getKey()));
|
||||
return numAcisRead.incrementAndGet() < maxAcisPerTransaction;
|
||||
});
|
||||
})
|
||||
.thenApply(_ -> acis);
|
||||
})
|
||||
.thenApply(acis -> new BatchReadResult(acis, cursor.get()))
|
||||
);
|
||||
}
|
||||
|
||||
public AciServiceIdentifier getAciFromKey(final byte[] key) {
|
||||
return new AciServiceIdentifier(messagesSubspace.unpack(key).getUUID(0));
|
||||
}
|
||||
|
||||
}
|
||||
+15
-12
@@ -69,12 +69,12 @@ import org.whispersystems.textsecuregcm.storage.MessagesDynamoDb;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesManager;
|
||||
import org.whispersystems.textsecuregcm.storage.PagedSingleUseKEMPreKeyStore;
|
||||
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
|
||||
import org.whispersystems.textsecuregcm.storage.PhoneNumberRecoveryPasswords;
|
||||
import org.whispersystems.textsecuregcm.storage.PhoneNumberRecoveryPasswordsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ProfileAvatars;
|
||||
import org.whispersystems.textsecuregcm.storage.Profiles;
|
||||
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ProfilesV2;
|
||||
import org.whispersystems.textsecuregcm.storage.PhoneNumberRecoveryPasswords;
|
||||
import org.whispersystems.textsecuregcm.storage.PhoneNumberRecoveryPasswordsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.RedeemedReceiptsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.RepeatedUseECSignedPreKeyStore;
|
||||
import org.whispersystems.textsecuregcm.storage.RepeatedUseKEMSignedPreKeyStore;
|
||||
@@ -83,6 +83,7 @@ import org.whispersystems.textsecuregcm.storage.ReportMessageManager;
|
||||
import org.whispersystems.textsecuregcm.storage.SingleUseECPreKeyStore;
|
||||
import org.whispersystems.textsecuregcm.storage.SubscriptionManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Subscriptions;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.FaultTolerantDatabase;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStore;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.VersionstampUUIDCipher;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.AppleAppStoreClient;
|
||||
@@ -125,7 +126,9 @@ public record CommandDependencies(
|
||||
DynamoDbAsyncClient dynamoDbAsyncClient,
|
||||
DynamoDbClient dynamoDbClient,
|
||||
PhoneNumberIdentifiers phoneNumberIdentifiers,
|
||||
DynamoDbRecoveryManager dynamoDbRecoveryManager) {
|
||||
DynamoDbRecoveryManager dynamoDbRecoveryManager,
|
||||
FDB fdb,
|
||||
AccountLockManager accountLockManager) {
|
||||
|
||||
static CommandDependencies build(
|
||||
final String name,
|
||||
@@ -148,9 +151,9 @@ public record CommandDependencies(
|
||||
// we'd like, but is the least bad option given current constraints.
|
||||
fdb.disableShutdownHook();
|
||||
|
||||
final Map<Integer, List<Database>> messageDatabasesByEpoch;
|
||||
final Map<Integer, List<FaultTolerantDatabase>> messageDatabasesByEpoch;
|
||||
{
|
||||
final Map<String, Database> databasesByName =
|
||||
final Map<String, FaultTolerantDatabase> faultTolerantDatabasesByName =
|
||||
configuration.getFoundationDbMessagesConfiguration().clusters().entrySet().stream()
|
||||
.collect(Collectors.toUnmodifiableMap(Map.Entry::getKey,
|
||||
entry -> {
|
||||
@@ -162,7 +165,8 @@ public record CommandDependencies(
|
||||
database.options().setTransactionRetryLimit(
|
||||
configuration.getFoundationDbMessagesConfiguration().transactionRetryLimit());
|
||||
|
||||
return database;
|
||||
return new FaultTolerantDatabase(database, entry.getKey(),
|
||||
configuration.getFoundationDbMessagesConfiguration().circuitBreakerConfigurationName());
|
||||
} catch (final IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
@@ -171,7 +175,7 @@ public record CommandDependencies(
|
||||
messageDatabasesByEpoch = configuration.getFoundationDbMessagesConfiguration().epochs().entrySet().stream()
|
||||
.collect(Collectors.toUnmodifiableMap(Map.Entry::getKey,
|
||||
entry -> entry.getValue().stream()
|
||||
.map(databasesByName::get)
|
||||
.map(faultTolerantDatabasesByName::get)
|
||||
.toList()));
|
||||
}
|
||||
|
||||
@@ -204,8 +208,6 @@ public record CommandDependencies(
|
||||
.maxThreads(8).minThreads(8).build();
|
||||
ExecutorService storageServiceExecutor = ExecutorServiceBuilder.of(environment, "storageService")
|
||||
.maxThreads(8).minThreads(8).build();
|
||||
ExecutorService accountLockExecutor = ExecutorServiceBuilder.of(environment, "accountLock")
|
||||
.minThreads(8).maxThreads(8).build();
|
||||
ExecutorService remoteStorageHttpExecutor = ExecutorServiceBuilder.of(environment, "remoteStorage")
|
||||
|
||||
.minThreads(0).maxThreads(Integer.MAX_VALUE).workQueue(new SynchronousQueue<>())
|
||||
@@ -356,7 +358,7 @@ public record CommandDependencies(
|
||||
AccountsManager accountsManager = new AccountsManager(accounts, phoneNumberIdentifiers, cacheCluster,
|
||||
pubsubClient, accountLockManager, keys, messagesManager, profilesManager,
|
||||
changeNumberWaitingPeriodManager, secureStorageClient, secureValueRecovery2Client, disconnectionRequestManager,
|
||||
phoneNumberRecoveryPasswordsManager, accountLockExecutor, messagePollExecutor,
|
||||
phoneNumberRecoveryPasswordsManager, messagePollExecutor,
|
||||
retryExecutor, clock, configuration.getLinkDeviceSecretConfiguration().secret().value(),
|
||||
configuration.getRegistrationTotpConfiguration().maxValidationDelay());
|
||||
RateLimiters rateLimiters = RateLimiters.create(dynamicConfigurationManager, rateLimitersCluster, retryExecutor);
|
||||
@@ -458,8 +460,9 @@ public record CommandDependencies(
|
||||
dynamoDbAsyncClient,
|
||||
dynamoDbClient,
|
||||
phoneNumberIdentifiers,
|
||||
dynamoDbRecoveryManager
|
||||
);
|
||||
dynamoDbRecoveryManager,
|
||||
fdb,
|
||||
accountLockManager);
|
||||
}
|
||||
|
||||
}
|
||||
-81
@@ -1,81 +0,0 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.workers;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import net.sourceforge.argparse4j.inf.Subparser;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.core.scheduler.Schedulers;
|
||||
|
||||
public class PopulateAccountRecoveryPasswordsCommand extends AbstractSinglePassCrawlAccountsCommand {
|
||||
|
||||
@VisibleForTesting
|
||||
static final String DRY_RUN_ARGUMENT = "dry-run";
|
||||
|
||||
@VisibleForTesting
|
||||
static final String MAX_CONCURRENCY_ARGUMENT = "max-concurrency";
|
||||
|
||||
private static final String ACCOUNTS_MIGRATED_COUNTER_NAME =
|
||||
MetricsUtil.name(PopulateAccountRecoveryPasswordsCommand.class, "accountsMigrated");
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(PopulateAccountRecoveryPasswordsCommand.class);
|
||||
|
||||
public PopulateAccountRecoveryPasswordsCommand() {
|
||||
super("populate-account-recovery-passwords", "Copies phone number recovery passwords as account recovery passwords");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configure(final Subparser subparser) {
|
||||
super.configure(subparser);
|
||||
|
||||
subparser.addArgument("--dry-run")
|
||||
.type(Boolean.class)
|
||||
.dest(DRY_RUN_ARGUMENT)
|
||||
.required(false)
|
||||
.setDefault(true)
|
||||
.help("If true, don't actually migrate any passwords");
|
||||
|
||||
subparser.addArgument("--max-concurrency")
|
||||
.type(Integer.class)
|
||||
.dest(MAX_CONCURRENCY_ARGUMENT)
|
||||
.required(false)
|
||||
.setDefault(64)
|
||||
.help("Max concurrency for migration operations");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void crawlAccounts(final Flux<Account> accounts) {
|
||||
final AccountsManager accountsManager = getCommandDependencies().accountsManager();
|
||||
|
||||
final boolean dryRun = getNamespace().getBoolean(DRY_RUN_ARGUMENT);
|
||||
final int maxConcurrency = getNamespace().getInt(MAX_CONCURRENCY_ARGUMENT);
|
||||
|
||||
final Counter accountsMigratedCounter =
|
||||
Metrics.counter(ACCOUNTS_MIGRATED_COUNTER_NAME, "dryRun", String.valueOf(dryRun));
|
||||
|
||||
accounts.flatMap(account -> (dryRun
|
||||
? Mono.<Void>empty()
|
||||
: Mono.<Void>fromRunnable(() -> accountsManager.migrateAccountRecoveryPassword(account)))
|
||||
.onErrorResume(throwable -> {
|
||||
logger.warn("Failed to migrate account recovery password for account {}",
|
||||
account.getAccountIdentifier(), throwable);
|
||||
|
||||
return Mono.empty();
|
||||
})
|
||||
.subscribeOn(Schedulers.boundedElastic())
|
||||
.doOnSuccess(_ -> accountsMigratedCounter.increment()), maxConcurrency)
|
||||
.then()
|
||||
.block();
|
||||
}
|
||||
}
|
||||
@@ -87,15 +87,15 @@ service Accounts {
|
||||
// key for the caller's account
|
||||
rpc ConfirmTotpKey(ConfirmTotpKeyRequest) returns (ConfirmTotpKeyResponse) {}
|
||||
|
||||
// Returns a list of confirmed TOTP keys for the authenticated account
|
||||
rpc ListTotpKeys(ListTotpKeysRequest) returns (ListTotpKeysResponse) {}
|
||||
// Returns a list of confirmed MFA keys for the authenticated account
|
||||
rpc ListMfaKeys(ListMfaKeysRequest) returns (ListMfaKeysResponse) {}
|
||||
|
||||
// Updates encrypted, user-supplied metadata (e.g. a human-readable name and
|
||||
// creation timestamp) for an existing, confirmed TOTP key
|
||||
rpc SetTotpKeyMetadata(SetTotpKeyMetadataRequest) returns (SetTotpKeyMetadataResponse) {}
|
||||
// creation timestamp) for an existing, confirmed MFA key
|
||||
rpc SetMfaKeyMetadata(SetMfaKeyMetadataRequest) returns (SetMfaKeyMetadataResponse) {}
|
||||
|
||||
// Removes a TOTP from the authenticated account
|
||||
rpc RemoveTotpKey(RemoveTotpKeyRequest) returns (RemoveTotpKeyResponse) {}
|
||||
// Removes an MFA key from the authenticated account
|
||||
rpc RemoveMfaKey(RemoveMfaKeyRequest) returns (RemoveMfaKeyResponse) {}
|
||||
}
|
||||
|
||||
// Provides methods for looking up Signal accounts. Callers must not provide
|
||||
@@ -533,6 +533,10 @@ message GenerateTotpKeyResponse {
|
||||
// The authenticated account already has too many TOTP keys, and the caller
|
||||
// must remove one before adding more
|
||||
errors.FailedPrecondition too_many_totp_keys = 2 [(tag.reason) = "too_many_totp_keys"];
|
||||
|
||||
// The authenticated account already has too many MFA keys of all types, and
|
||||
// the caller must remove one before adding more
|
||||
errors.FailedPrecondition too_many_mfa_keys = 3 [(tag.reason) = "too_many_mfa_keys"];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -549,7 +553,7 @@ message ConfirmTotpKeyRequest {
|
||||
message ConfirmTotpKeyResponse {
|
||||
message KeyConfirmed {
|
||||
// The account-specific identifier for the newly-confirmed TOTP key
|
||||
uint32 key_id = 1;
|
||||
uint32 key_id = 1 [(require.range) = {min: 0, max: 127}];
|
||||
}
|
||||
|
||||
oneof response {
|
||||
@@ -560,33 +564,42 @@ message ConfirmTotpKeyResponse {
|
||||
// The provided one-time password was not valid for any reason (including
|
||||
// incorrect passwords, misaligned clocks, or missing account records)
|
||||
errors.FailedPrecondition one_time_password_not_verified = 2 [(tag.reason) = "one_time_password_not_verified"];
|
||||
|
||||
// The authenticated account already has too many MFA keys of all types, and
|
||||
// the caller must remove one before adding more
|
||||
errors.FailedPrecondition too_many_mfa_keys = 3 [(tag.reason) = "too_many_mfa_keys"];
|
||||
}
|
||||
}
|
||||
|
||||
message ListTotpKeysRequest {}
|
||||
message ListMfaKeysRequest {}
|
||||
|
||||
message ListTotpKeysResponse {
|
||||
message TotpKeyMetadata {
|
||||
// The user-provided ciphertext for metadata associated with this TOTP key
|
||||
bytes metadata_ciphertext = 1;
|
||||
message ListMfaKeysResponse {
|
||||
message MfaKeyMetadata {
|
||||
enum MfaKeyType {
|
||||
MFA_KEY_TYPE_UNSPECIFIED = 0;
|
||||
MFA_KEY_TYPE_TOTP = 1;
|
||||
}
|
||||
|
||||
// The TOTP parameters associated with this key
|
||||
TotpParameters totp_parameters = 2;
|
||||
/// The user-provided ciphertext for metadata associated with this MFA key
|
||||
bytes metadata_ciphertext = 1 [(require.exactlySize) = 160];
|
||||
|
||||
/// The type of MFA factor this key is for
|
||||
MfaKeyType type = 2;
|
||||
}
|
||||
|
||||
map<int32, TotpKeyMetadata> keys = 1;
|
||||
map<uint32, MfaKeyMetadata> keys = 1;
|
||||
}
|
||||
|
||||
message SetTotpKeyMetadataRequest {
|
||||
// The account-specific identifier of the TOTP key to modify
|
||||
uint32 key_id = 1;
|
||||
message SetMfaKeyMetadataRequest {
|
||||
// The account-specific identifier of the MFA key to modify
|
||||
uint32 key_id = 1 [(require.range) = {min: 0, max: 127}];
|
||||
|
||||
// The ciphertext of the new user-provided metadata to be attached to the
|
||||
// identified key
|
||||
bytes metadata_ciphertext = 2 [(require.exactlySize) = 160];
|
||||
}
|
||||
|
||||
message SetTotpKeyMetadataResponse {
|
||||
message SetMfaKeyMetadataResponse {
|
||||
message MetadataUpdated {
|
||||
}
|
||||
|
||||
@@ -599,10 +612,10 @@ message SetTotpKeyMetadataResponse {
|
||||
}
|
||||
}
|
||||
|
||||
message RemoveTotpKeyRequest {
|
||||
// The account-specific identifier of the TOTP key to remove
|
||||
uint32 key_id = 1;
|
||||
message RemoveMfaKeyRequest {
|
||||
// The account-specific identifier of the MFA key to remove
|
||||
uint32 key_id = 1 [(require.range) = {min: 0, max: 127}];
|
||||
}
|
||||
|
||||
message RemoveTotpKeyResponse {
|
||||
message RemoveMfaKeyResponse {
|
||||
}
|
||||
@@ -25,7 +25,14 @@ service OneTimeDonations {
|
||||
rpc CreateBoost(CreateBoostRequest) returns (CreateBoostResponse) {}
|
||||
|
||||
// Create a PayPal one-time payment.
|
||||
// Once the payment is complete, call ConfirmPayPalBoost with the payment ID and token
|
||||
//
|
||||
// Once the payment is complete, call ConfirmPayPalBoost with the payment ID
|
||||
// and token.
|
||||
//
|
||||
// The PayPal approval page presented to the user may be localized. Callers
|
||||
// should set their language preferences via an "Accept-Language" header on
|
||||
// the request:
|
||||
// https://datatracker.ietf.org/doc/html/rfc3282#section-3
|
||||
rpc CreatePayPalBoost(CreatePayPalBoostRequest) returns (CreatePayPalBoostResponse) {}
|
||||
|
||||
// Confirm a PayPal one-time payment
|
||||
|
||||
@@ -90,6 +90,8 @@ message LoginConfiguration {
|
||||
uint64 level = 1;
|
||||
// The play billing productID associated with a Signal Login purchase
|
||||
string play_product_id = 2;
|
||||
// The play billing optionID to use to purchase a Signal Login
|
||||
string play_option_id = 4;
|
||||
// The App Store productID associated with a Signal Login purchase
|
||||
string app_store_product_id = 3;
|
||||
}
|
||||
@@ -31,6 +31,17 @@ service Profile {
|
||||
//
|
||||
// Note: `Accounts.SetZkCredentialKey` is a pre-requisite for this RPC
|
||||
rpc GetAvatarCredentials(GetAvatarCredentialsRequest) returns (GetAvatarCredentialsResponse) {}
|
||||
|
||||
// Returns credentials used by clients to upload a v1 avatar, deleting any current avatar.
|
||||
//
|
||||
// This RPC streamlines avatar changes during the v1 -> v2 transition by minimizing uploads:
|
||||
// 1. SetV1Avatar
|
||||
// 2. Upload to CDN
|
||||
// 3. SetProfile with v1 `AVATAR_CHANGE_UNCHANGED` and the v1 avatar in the v2 profile body
|
||||
//
|
||||
// Clients that do this will be required to upload current avatars using `ProfilesAnonymous.GetAvatarUploadFormRequest`
|
||||
// once v1 Profile APIs are no longer supported.
|
||||
rpc SetV1Avatar(SetV1AvatarRequest) returns (SetV1AvatarResponse) {}
|
||||
}
|
||||
|
||||
// Provides methods for working with profiles and profile-related data using "unidentified access"
|
||||
@@ -90,6 +101,19 @@ message SetProfileV1Request {
|
||||
bytes phone_number_sharing = 6 [(require.exactlySize) = 29];
|
||||
}
|
||||
|
||||
message SetV1AvatarRequest {
|
||||
// The profile version. Required.
|
||||
string version = 1 [(require.exactlySize) = 64];
|
||||
|
||||
// The profile key commitment. Required if this is a new profile version.
|
||||
bytes commitment = 2 [(require.exactlySize) = 0, (require.exactlySize) = 97];
|
||||
}
|
||||
|
||||
message SetV1AvatarResponse {
|
||||
// the policy and credential used by clients to upload an avatar to the CDN
|
||||
common.S3UploadForm form = 1;
|
||||
}
|
||||
|
||||
message SetProfileRequest {
|
||||
|
||||
// The profile version. Required.
|
||||
@@ -374,6 +398,7 @@ message GetAvatarUploadFormRequest {
|
||||
|
||||
message GetAvatarUploadFormResponse {
|
||||
oneof response {
|
||||
// the policy and credential used by clients to upload an avatar to the CDN
|
||||
common.S3UploadForm avatar_upload_form = 1;
|
||||
|
||||
errors.FailedZkAuthentication invalid_credentials_presentation = 2 [(tag.reason) = "invalid_credentials_presentation"];
|
||||
|
||||
@@ -21,7 +21,7 @@ import "org/signal/chat/tag.proto";
|
||||
service Subscriptions {
|
||||
option (require.auth) = AUTH_ONLY_ANONYMOUS;
|
||||
// Creates a subscriber record if it does not exist, otherwise refreshes its last access time.
|
||||
|
||||
//
|
||||
// Subscribers MUST periodically hit this endpoint to update the access time on the subscription record. Subscribers
|
||||
// SHOULD attempt to make an update call approximately every 3 days. Not accessing this endpoint for an extended
|
||||
// period of time will result in the subscription being canceled.
|
||||
@@ -37,6 +37,10 @@ service Subscriptions {
|
||||
rpc CreatePaymentMethod(CreatePaymentMethodRequest) returns (CreatePaymentMethodResponse) {}
|
||||
|
||||
// Returns a PayPal billing agreement approval URL and token that can be used to set up PayPal as a payment method.
|
||||
//
|
||||
// The presented billing agreement may be localized. Callers should set their
|
||||
// language preferences via an "Accept-Language" header on the request:
|
||||
// https://datatracker.ietf.org/doc/html/rfc3282#section-3
|
||||
rpc CreatePayPalPaymentMethod(CreatePayPalPaymentMethodRequest) returns (CreatePayPalPaymentMethodResponse) {}
|
||||
|
||||
// Sets the default payment method for a subscriber.
|
||||
@@ -102,11 +106,16 @@ service Subscriptions {
|
||||
// associated with the old purchaseToken will be cancelled.
|
||||
rpc SetIapSubscription(SetIapSubscriptionRequest) returns (SetIapSubscriptionResponse) {}
|
||||
|
||||
// Returns a localized bank mandate for the specified bank transfer type
|
||||
// Returns a localized bank mandate for the specified bank transfer type.
|
||||
//
|
||||
// Callers should set their language preferences via an "Accept-Language"
|
||||
// header on the request:
|
||||
// https://datatracker.ietf.org/doc/html/rfc3282#section-3
|
||||
rpc GetBankMandate(GetBankMandateRequest) returns (GetBankMandateResponse) {}
|
||||
}
|
||||
|
||||
message UpdateSubscriberRequest {
|
||||
// New subscriber-ids must be a randomly-generated 32 byte byte-string.
|
||||
bytes subscriber_id = 1 [(require.exactlySize) = 32];
|
||||
// A libsignal DonationPermit from rpc Donations.CreateDonationPermit.
|
||||
// Not required if the subscriber already exists.
|
||||
@@ -116,10 +125,8 @@ message UpdateSubscriberRequest {
|
||||
message UpdateSubscriberResponse {
|
||||
oneof response {
|
||||
google.protobuf.Empty success = 1;
|
||||
// subscriberId authentication failure
|
||||
errors.FailedUnidentifiedAuthorization subscriber_id_mismatch = 2 [(tag.reason) = "subscriber_id_mismatch"];
|
||||
// The donation permit was expired or already spent
|
||||
errors.FailedZkAuthentication permit_rejected = 3 [(tag.reason) = "permit_rejected"];
|
||||
errors.FailedZkAuthentication permit_rejected = 2 [(tag.reason) = "permit_rejected"];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -130,6 +137,7 @@ message DeleteSubscriberRequest {
|
||||
message DeleteSubscriberResponse {
|
||||
oneof response {
|
||||
google.protobuf.Empty success = 1;
|
||||
// The subscriber did not exist
|
||||
errors.NotFound subscriber_not_found = 2 [(tag.reason) = "subscriber_not_found"];
|
||||
// The associated subscription is not a type that can be cancelled by the server. Cancel client-side, and then retry.
|
||||
errors.FailedPrecondition cannot_cancel_subscription = 3 [(tag.reason) = "cannot_cancel_subscription"];
|
||||
@@ -189,13 +197,13 @@ message CreatePaymentMethodResponse {
|
||||
|
||||
oneof response {
|
||||
CreatePaymentMethodResult result = 1;
|
||||
// The subscriber did not exist
|
||||
errors.NotFound subscriber_not_found = 2 [(tag.reason) = "subscriber_not_found"];
|
||||
// subscriberId authentication failure
|
||||
errors.FailedUnidentifiedAuthorization subscriber_id_mismatch = 3 [(tag.reason) = "subscriber_id_mismatch"];
|
||||
// New payment processor does not match existing processor associated with the subscription
|
||||
errors.FailedPrecondition subscription_processor_conflict = 4 [(tag.reason) = "subscription_processor_conflict"];
|
||||
// New payment processor does not match existing processor associated with
|
||||
// the subscription
|
||||
errors.FailedPrecondition subscription_processor_conflict = 3 [(tag.reason) = "subscription_processor_conflict"];
|
||||
// The donation permit was expired or already spent
|
||||
errors.FailedZkAuthentication permit_rejected = 5 [(tag.reason) = "permit_rejected"];
|
||||
errors.FailedZkAuthentication permit_rejected = 4 [(tag.reason) = "permit_rejected"];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -217,11 +225,11 @@ message CreatePayPalPaymentMethodResponse {
|
||||
|
||||
oneof response {
|
||||
CreatePayPalPaymentMethodResult result = 1;
|
||||
// The subscriber did not exist
|
||||
errors.NotFound subscriber_not_found = 2 [(tag.reason) = "subscriber_not_found"];
|
||||
// subscriberId authentication failure
|
||||
errors.FailedUnidentifiedAuthorization subscriber_id_mismatch = 3 [(tag.reason) = "subscriber_id_mismatch"];
|
||||
// New payment processor does not match existing processor associated with the subscription
|
||||
errors.FailedPrecondition subscription_processor_conflict = 4 [(tag.reason) = "subscription_processor_conflict"];
|
||||
// New payment processor does not match existing processor associated with
|
||||
// the subscription
|
||||
errors.FailedPrecondition subscription_processor_conflict = 3 [(tag.reason) = "subscription_processor_conflict"];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -247,12 +255,11 @@ message SetDefaultPaymentMethodRequest {
|
||||
message SetDefaultPaymentMethodResponse {
|
||||
oneof response {
|
||||
google.protobuf.Empty success = 1;
|
||||
// The subscriber did not exist, or the referenced setup intent was not found
|
||||
errors.NotFound subscriber_not_found = 2 [(tag.reason) = "subscriber_not_found"];
|
||||
// subscriberId authentication failure
|
||||
errors.FailedUnidentifiedAuthorization subscriber_id_mismatch = 3 [(tag.reason) = "subscriber_id_mismatch"];
|
||||
errors.FailedPrecondition payment_method_not_set_up = 4 [(tag.reason) = "payment_method_not_set_up"];
|
||||
// Payment processor does not match existing processor associated with the subscription
|
||||
errors.FailedPrecondition subscription_processor_conflict = 5 [(tag.reason) = "subscription_processor_conflict"];
|
||||
// No payment method has been created for the subscriber, or the provided
|
||||
// payment method has not finished being set up with the processor
|
||||
errors.FailedPrecondition payment_method_not_set_up = 3 [(tag.reason) = "payment_method_not_set_up"];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -307,26 +314,27 @@ message SetSubscriptionLevelResponse {
|
||||
|
||||
oneof response {
|
||||
SetSubscriptionLevelResult success = 1;
|
||||
// The subscriber did not exist
|
||||
errors.NotFound subscriber_not_found = 2 [(tag.reason) = "subscriber_not_found"];
|
||||
// subscriberId authentication failure
|
||||
errors.FailedUnidentifiedAuthorization subscriber_id_mismatch = 3 [(tag.reason) = "subscriber_id_mismatch"];
|
||||
// New payment processor does not match existing processor associated with the subscription
|
||||
errors.FailedPrecondition subscription_processor_conflict = 4 [(tag.reason) = "subscription_processor_conflict"];
|
||||
errors.FailedPrecondition payment_method_not_set_up = 5 [(tag.reason) = "payment_method_not_set_up"];
|
||||
// New payment processor does not match existing processor associated with
|
||||
// the subscription
|
||||
errors.FailedPrecondition subscription_processor_conflict = 3 [(tag.reason) = "subscription_processor_conflict"];
|
||||
// No payment method has been created for the subscriber
|
||||
errors.FailedPrecondition payment_method_not_set_up = 4 [(tag.reason) = "payment_method_not_set_up"];
|
||||
// The payment processor does not support this operation
|
||||
errors.FailedPrecondition unsupported_operation = 6 [(tag.reason) = "unsupported_operation"];
|
||||
errors.FailedPrecondition unsupported_operation = 5 [(tag.reason) = "unsupported_operation"];
|
||||
// The requested level was invalid
|
||||
errors.FailedPrecondition unsupported_level = 7 [(tag.reason) = "unsupported_level"];
|
||||
errors.FailedPrecondition unsupported_level = 6 [(tag.reason) = "unsupported_level"];
|
||||
// The requested currency was invalid
|
||||
errors.FailedPrecondition unsupported_currency = 8 [(tag.reason) = "unsupported_currency"];
|
||||
errors.FailedPrecondition unsupported_currency = 7 [(tag.reason) = "unsupported_currency"];
|
||||
// The card could not be charged
|
||||
errors.FailedPrecondition payment_requires_action = 9 [(tag.reason) = "payment_requires_action"];
|
||||
errors.FailedPrecondition payment_requires_action = 8 [(tag.reason) = "payment_requires_action"];
|
||||
// Cannot transition from existing level to the requested level
|
||||
errors.FailedPrecondition invalid_level_transition = 10 [(tag.reason) = "invalid_level_transition"];
|
||||
errors.FailedPrecondition invalid_level_transition = 9 [(tag.reason) = "invalid_level_transition"];
|
||||
// The idempotency key was invalid or re-used with a modified request
|
||||
errors.FailedPrecondition invalid_idempotency_key = 11 [(tag.reason) = "invalid_idempotency_key"];
|
||||
errors.FailedPrecondition invalid_idempotency_key = 10 [(tag.reason) = "invalid_idempotency_key"];
|
||||
// The payment failed; see charge failure details
|
||||
ChargeFailure charge_failure = 12 [(tag.reason) = "charge_failure"];
|
||||
ChargeFailure charge_failure = 11 [(tag.reason) = "charge_failure"];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -352,13 +360,17 @@ message SetIapSubscriptionResponse {
|
||||
|
||||
oneof response {
|
||||
SetIapSubscriptionResult success = 1;
|
||||
// The subscriber did not exist or the provided purchase identifier does not exist
|
||||
errors.NotFound subscriber_not_found = 2 [(tag.reason) = "subscriber_not_found"];
|
||||
// subscriberId authentication failure
|
||||
errors.FailedUnidentifiedAuthorization subscriber_id_mismatch = 3 [(tag.reason) = "subscriber_id_mismatch"];
|
||||
// New payment processor does not match existing processor associated with the subscription
|
||||
errors.FailedPrecondition subscription_processor_conflict = 4 [(tag.reason) = "subscription_processor_conflict"];
|
||||
errors.FailedPrecondition payment_required = 5 [(tag.reason) = "payment_required"];
|
||||
errors.FailedPrecondition invalid_transaction = 6 [(tag.reason) = "invalid_transaction"];
|
||||
// New payment processor does not match existing processor associated with
|
||||
// the subscription
|
||||
errors.FailedPrecondition subscription_processor_conflict = 3 [(tag.reason) = "subscription_processor_conflict"];
|
||||
// The subscription is not in a purchase state that grants the user an
|
||||
// entitlement
|
||||
errors.FailedPrecondition payment_required = 4 [(tag.reason) = "payment_required"];
|
||||
// The provided purchase identifier is malformed or the identified
|
||||
// transaction is not supported for use at this endpoint
|
||||
errors.FailedPrecondition invalid_transaction = 5 [(tag.reason) = "invalid_transaction"];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -374,15 +386,14 @@ message GetReceiptCredentialsResponse {
|
||||
|
||||
oneof response {
|
||||
GetReceiptCredentialsResult success = 1;
|
||||
// The subscriber did not exist or it did not have an associated subscription
|
||||
errors.NotFound subscriber_not_found = 2 [(tag.reason) = "subscriber_not_found"];
|
||||
// subscriberId authentication failure
|
||||
errors.FailedUnidentifiedAuthorization subscriber_id_mismatch = 3 [(tag.reason) = "subscriber_id_mismatch"];
|
||||
// No invoice has been issued for this subscription OR invoice is in 'draft' or 'open' state
|
||||
errors.FailedPrecondition no_paid_invoice = 4 [(tag.reason) = "no_paid_invoice"];
|
||||
errors.FailedPrecondition no_paid_invoice = 3 [(tag.reason) = "no_paid_invoice"];
|
||||
// Invoice is in any state other than 'draft', 'open', or 'paid'; Charge failure details may be present
|
||||
PaymentRequired payment_required = 5 [(tag.reason) = "payment_required"];
|
||||
PaymentRequired payment_required = 4 [(tag.reason) = "payment_required"];
|
||||
// Latest paid receipt on subscription was already redeemed for a receipt credential but with a different GetReceiptCredentialRequest
|
||||
errors.FailedPrecondition already_redeemed = 6 [(tag.reason) = "already_redeemed"];
|
||||
errors.FailedPrecondition already_redeemed = 5 [(tag.reason) = "already_redeemed"];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -420,10 +431,10 @@ message GetSubscriptionInformationResponse {
|
||||
|
||||
oneof response {
|
||||
Subscription success = 1;
|
||||
// The subscriber exists but has no subscription with a payment processor
|
||||
google.protobuf.Empty no_subscription = 2;
|
||||
// The subscriber did not exist
|
||||
errors.NotFound subscriber_not_found = 3 [(tag.reason) = "subscriber_not_found"];
|
||||
// subscriberId authentication failure
|
||||
errors.FailedUnidentifiedAuthorization subscriber_id_mismatch = 4 [(tag.reason) = "subscriber_id_mismatch"];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+18
-17
@@ -31,9 +31,7 @@ import org.eclipse.jetty.client.HttpClient;
|
||||
import org.eclipse.jetty.http2.client.HTTP2Client;
|
||||
import org.eclipse.jetty.http2.client.transport.HttpClientTransportOverHTTP2;
|
||||
import org.eclipse.jetty.io.ClientConnector;
|
||||
import org.eclipse.jetty.util.component.LifeCycle;
|
||||
import org.eclipse.jetty.websocket.api.Session;
|
||||
import org.eclipse.jetty.websocket.api.StatusCode;
|
||||
import org.eclipse.jetty.websocket.client.WebSocketClient;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
@@ -87,7 +85,9 @@ class WhisperServerServiceTest {
|
||||
public static final DynamoDbExtension DYNAMO_DB_EXTENSION = new DynamoDbExtension(DynamoDbExtensionSchema.Tables.values());
|
||||
|
||||
@AfterAll
|
||||
static void teardown() {
|
||||
static void teardown() throws Exception {
|
||||
h2WebSocketClient.stop();
|
||||
webSocketClient.stop();
|
||||
System.clearProperty("secrets.bundle.filename");
|
||||
}
|
||||
|
||||
@@ -132,23 +132,24 @@ class WhisperServerServiceTest {
|
||||
|
||||
final TestWebsocketListener testWebsocketListener = new TestWebsocketListener();
|
||||
|
||||
// Session is Closeable, but we intentionally keep it open so that we can confirm the container Lifecycle behavior
|
||||
final Session session = (useH2 ? h2WebSocketClient : webSocketClient).connect(testWebsocketListener,
|
||||
try(Session session = (useH2 ? h2WebSocketClient : webSocketClient).connect(testWebsocketListener,
|
||||
URI.create(String.format("ws://localhost:%d/v1/websocket/", EXTENSION.getLocalPort())))
|
||||
.join();
|
||||
final long sessionTimestamp = Long.parseLong(session.getUpgradeResponse().getHeader(HeaderUtils.TIMESTAMP_HEADER));
|
||||
assertTrue(sessionTimestamp >= start);
|
||||
.join()) {
|
||||
final long sessionTimestamp = Long.parseLong(
|
||||
session.getUpgradeResponse().getHeader(HeaderUtils.TIMESTAMP_HEADER));
|
||||
assertTrue(sessionTimestamp >= start);
|
||||
|
||||
final WebSocketResponseMessage keepAlive = testWebsocketListener.doGet("/v1/keepalive").join();
|
||||
assertEquals(200, keepAlive.getStatus());
|
||||
final long keepAliveTimestamp = Long.parseLong(
|
||||
keepAlive.getHeaders().get(HeaderUtils.TIMESTAMP_HEADER.toLowerCase()));
|
||||
assertTrue(keepAliveTimestamp >= start);
|
||||
final WebSocketResponseMessage keepAlive = testWebsocketListener.doGet("/v1/keepalive").join();
|
||||
assertEquals(200, keepAlive.getStatus());
|
||||
final long keepAliveTimestamp = Long.parseLong(
|
||||
keepAlive.getHeaders().get(HeaderUtils.TIMESTAMP_HEADER.toLowerCase()));
|
||||
assertTrue(keepAliveTimestamp >= start);
|
||||
|
||||
final WebSocketResponseMessage whoami = testWebsocketListener.doGet("/v1/accounts/whoami").join();
|
||||
assertEquals(401, whoami.getStatus());
|
||||
final long whoamiTimestamp = Long.parseLong(whoami.getHeaders().get(HeaderUtils.TIMESTAMP_HEADER.toLowerCase()));
|
||||
assertTrue(whoamiTimestamp >= start);
|
||||
final WebSocketResponseMessage whoami = testWebsocketListener.doGet("/v1/accounts/whoami").join();
|
||||
assertEquals(401, whoami.getStatus());
|
||||
final long whoamiTimestamp = Long.parseLong(whoami.getHeaders().get(HeaderUtils.TIMESTAMP_HEADER.toLowerCase()));
|
||||
assertTrue(whoamiTimestamp >= start);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+16
-8
@@ -28,7 +28,8 @@ class FoundationDbMessagesConfigurationTest {
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_TIMEOUT,
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT,
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_TIMEOUT.multipliedBy(2),
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT * 2
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT * 2,
|
||||
null
|
||||
).isEveryEpochClusterConfigured());
|
||||
|
||||
assertFalse(new FoundationDbMessagesConfiguration(
|
||||
@@ -41,7 +42,8 @@ class FoundationDbMessagesConfigurationTest {
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_TIMEOUT,
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT,
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_TIMEOUT.multipliedBy(2),
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT * 2
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT * 2,
|
||||
null
|
||||
).isEveryEpochClusterConfigured());
|
||||
}
|
||||
|
||||
@@ -57,7 +59,8 @@ class FoundationDbMessagesConfigurationTest {
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_TIMEOUT,
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT,
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_TIMEOUT.multipliedBy(2),
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT * 2
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT * 2,
|
||||
null
|
||||
).isEveryEpochFreeOfDuplicates());
|
||||
|
||||
assertFalse(new FoundationDbMessagesConfiguration(
|
||||
@@ -70,7 +73,8 @@ class FoundationDbMessagesConfigurationTest {
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_TIMEOUT,
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT,
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_TIMEOUT.multipliedBy(2),
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT * 2
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT * 2,
|
||||
null
|
||||
).isEveryEpochFreeOfDuplicates());
|
||||
}
|
||||
|
||||
@@ -86,7 +90,8 @@ class FoundationDbMessagesConfigurationTest {
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_TIMEOUT,
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT,
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_TIMEOUT.multipliedBy(2),
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT * 2
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT * 2,
|
||||
null
|
||||
).isActiveEpochConfigured());
|
||||
|
||||
assertFalse(new FoundationDbMessagesConfiguration(
|
||||
@@ -99,7 +104,8 @@ class FoundationDbMessagesConfigurationTest {
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_TIMEOUT,
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT,
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_TIMEOUT.multipliedBy(2),
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT * 2
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT * 2,
|
||||
null
|
||||
).isActiveEpochConfigured());
|
||||
}
|
||||
|
||||
@@ -115,7 +121,8 @@ class FoundationDbMessagesConfigurationTest {
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_TIMEOUT,
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT,
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_TIMEOUT.multipliedBy(2),
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT * 2
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT * 2,
|
||||
null
|
||||
).isCurrentVersionstampCipherKeyConfigured());
|
||||
|
||||
assertFalse(new FoundationDbMessagesConfiguration(
|
||||
@@ -128,7 +135,8 @@ class FoundationDbMessagesConfigurationTest {
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_TIMEOUT,
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT,
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_TIMEOUT.multipliedBy(2),
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT * 2
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT * 2,
|
||||
null
|
||||
).isCurrentVersionstampCipherKeyConfigured());
|
||||
}
|
||||
}
|
||||
+25
-5
@@ -46,6 +46,7 @@ import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.stream.Stream;
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
import org.glassfish.jersey.server.ServerProperties;
|
||||
import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
@@ -868,6 +869,19 @@ class AccountControllerTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSetAccountAttributesRegistrationLockWithNoNumber() {
|
||||
try (final Response response = resources.getJerseyTest()
|
||||
.target("/v1/accounts/attributes/")
|
||||
.request()
|
||||
.header(HttpHeaders.AUTHORIZATION, AuthHelper.getAuthHeader(AuthHelper.NUMBERLESS_UUID, AuthHelper.NUMBERLESS_PASSWORD))
|
||||
.put(Entity.json(new AccountAttributes(false, 2222, 3333, null, "1234", false, null, null)
|
||||
.setUnidentifiedAccessKey(new byte[16])))) {
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(422);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSetAccountAttributesEnableDiscovery() {
|
||||
try (final Response response = resources.getJerseyTest()
|
||||
@@ -881,10 +895,13 @@ class AccountControllerTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testAccountsAttributesUpdateRecoveryPassword() {
|
||||
final byte[] recoveryPassword = TestRandomUtil.nextBytes(32);
|
||||
static Stream<byte[]> testAccountsAttributesUpdateRecoveryPassword() {
|
||||
return Stream.of(null, new byte[]{}, TestRandomUtil.nextBytes(32));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void testAccountsAttributesUpdateRecoveryPassword(final byte[] recoveryPassword) {
|
||||
try (final Response response = resources.getJerseyTest()
|
||||
.target("/v1/accounts/attributes/")
|
||||
.request()
|
||||
@@ -893,9 +910,12 @@ class AccountControllerTest {
|
||||
.setUnidentifiedAccessKey(new byte[16])
|
||||
.setRecoveryPassword(recoveryPassword)))) {
|
||||
|
||||
final int expectedRrpUpdates = ArrayUtils.isEmpty(recoveryPassword) ? 0 : 1;
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(204);
|
||||
verify(accountsManager).update(eq(AuthHelper.UNDISCOVERABLE_UUID), any(), argThat(additionWriteItems -> additionWriteItems.size() == 1));
|
||||
verify(AuthHelper.UNDISCOVERABLE_ACCOUNT).setAccountRecoveryPassword(recoveryPassword);
|
||||
verify(accountsManager).update(eq(AuthHelper.UNDISCOVERABLE_UUID), any(), argThat(additionWriteItems -> additionWriteItems.size() == expectedRrpUpdates));
|
||||
|
||||
verify(AuthHelper.UNDISCOVERABLE_ACCOUNT, times(expectedRrpUpdates)).setAccountRecoveryPassword(recoveryPassword);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
-2
@@ -79,7 +79,6 @@ import org.whispersystems.textsecuregcm.backup.CopyResult;
|
||||
import org.whispersystems.textsecuregcm.entities.RemoteAttachment;
|
||||
import org.whispersystems.textsecuregcm.mappers.BackupExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.CompletionExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.GrpcStatusRuntimeExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.metrics.BackupMetrics;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
@@ -104,7 +103,6 @@ public class ArchiveControllerTest {
|
||||
.addProvider(AuthHelper.getAuthFilter())
|
||||
.addProvider(new AuthValueFactoryProvider.Binder<>(AuthenticatedDevice.class))
|
||||
.addProvider(new CompletionExceptionMapper())
|
||||
.addResource(new GrpcStatusRuntimeExceptionMapper())
|
||||
.addResource(new BackupExceptionMapper())
|
||||
.addProvider(new RateLimitExceededExceptionMapper())
|
||||
.setMapper(SystemMapper.jsonMapper())
|
||||
|
||||
+35
-3
@@ -19,9 +19,17 @@ import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.NullSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.signal.libsignal.protocol.ServiceId;
|
||||
import org.signal.libsignal.protocol.util.Hex;
|
||||
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
|
||||
import org.signal.libsignal.zkgroup.calllinks.CallLinkSecretParams;
|
||||
import org.signal.libsignal.zkgroup.calllinks.CreateCallLinkCredential;
|
||||
import org.signal.libsignal.zkgroup.calllinks.CreateCallLinkCredentialPresentation;
|
||||
import org.signal.libsignal.zkgroup.calllinks.CreateCallLinkCredentialRequestContext;
|
||||
import org.signal.libsignal.zkgroup.calllinks.CreateCallLinkCredentialResponse;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.entities.GetCreateCallLinkCredentialsRequest;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiter;
|
||||
@@ -29,10 +37,12 @@ import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
|
||||
|
||||
@ExtendWith(DropwizardExtensionsSupport.class)
|
||||
public class CallLinkControllerTest {
|
||||
private static final GenericServerSecretParams genericServerSecretParams = GenericServerSecretParams.generate();
|
||||
private static final GenericServerSecretParams genericServerSecretParamsPreV101 = GenericServerSecretParams.generate();
|
||||
private static final RateLimiters rateLimiters = mock(RateLimiters.class);
|
||||
private static final RateLimiter createCallLinkLimiter = mock(RateLimiter.class);
|
||||
private static final byte[] roomId = Hex.fromStringCondensedAssert("c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7");
|
||||
@@ -45,7 +55,7 @@ public class CallLinkControllerTest {
|
||||
.addProvider(new RateLimitExceededExceptionMapper())
|
||||
.setMapper(SystemMapper.jsonMapper())
|
||||
.setTestContainerFactory(new GrizzlyWebTestContainerFactory())
|
||||
.addResource(new CallLinkController(rateLimiters, genericServerSecretParams))
|
||||
.addResource(new CallLinkController(rateLimiters, genericServerSecretParams, genericServerSecretParamsPreV101))
|
||||
.build();
|
||||
|
||||
@BeforeEach
|
||||
@@ -53,14 +63,36 @@ public class CallLinkControllerTest {
|
||||
when(rateLimiters.getCreateCallLinkLimiter()).thenReturn(createCallLinkLimiter);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetCreateAuth() {
|
||||
@ParameterizedTest
|
||||
@NullSource
|
||||
@ValueSource(booleans = {true, false})
|
||||
void testGetCreateAuth(final Boolean v101) throws Exception {
|
||||
try (Response response = resources.getJerseyTest()
|
||||
.target("/v1/call-link/create-auth")
|
||||
// a null value will exclude the parameter altogether, rather than sending `?v101=`
|
||||
.queryParam("v101", v101)
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.post(Entity.json(new GetCreateCallLinkCredentialsRequest(createCallLinkRequestSerialized)))) {
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
|
||||
final GenericServerSecretParams verificationParams = v101 != null && v101
|
||||
? genericServerSecretParams
|
||||
: genericServerSecretParamsPreV101;
|
||||
|
||||
final byte[] serializedCredential = response.readEntity(
|
||||
org.whispersystems.textsecuregcm.entities.CreateCallLinkCredential.class).credential();
|
||||
final CreateCallLinkCredentialResponse credentialResponse = new CreateCallLinkCredentialResponse(serializedCredential);
|
||||
|
||||
final ServiceId.Aci aci = new ServiceId.Aci(AuthHelper.VALID_UUID);
|
||||
final CreateCallLinkCredential credential = createCallLinkRequestContext.receiveResponse(credentialResponse, aci,
|
||||
verificationParams.getPublicParams());
|
||||
final CallLinkSecretParams callLinkSecretParams = CallLinkSecretParams.deriveFromRootKey(TestRandomUtil.nextBytes(16));
|
||||
|
||||
final CreateCallLinkCredentialPresentation presentation = credential.present(roomId,
|
||||
aci, verificationParams.getPublicParams(), callLinkSecretParams);
|
||||
|
||||
presentation.verify(roomId, verificationParams, callLinkSecretParams.getPublicParams());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+25
-7
@@ -68,6 +68,7 @@ class CertificateControllerTest {
|
||||
private static final ServerSecretParams SERVER_SECRET_PARAMS = ServerSecretParams.generate();
|
||||
|
||||
private static final GenericServerSecretParams genericServerSecretParams = GenericServerSecretParams.generate();
|
||||
private static final GenericServerSecretParams genericServerSecretParamsPreV101 = GenericServerSecretParams.generate();
|
||||
|
||||
private static final ServerZkAuthOperations SERVER_ZK_AUTH_OPERATIONS;
|
||||
private static final Clock clock = Clock.fixed(Instant.now(), ZoneId.systemDefault());
|
||||
@@ -96,7 +97,7 @@ class CertificateControllerTest {
|
||||
.addProvider(new AuthValueFactoryProvider.Binder<>(AuthenticatedDevice.class))
|
||||
.setMapper(SystemMapper.jsonMapper())
|
||||
.setTestContainerFactory(new GrizzlyWebTestContainerFactory())
|
||||
.addResource(new CertificateController(AuthHelper.ACCOUNTS_MANAGER, CERTIFICATE_GENERATOR, SERVER_ZK_AUTH_OPERATIONS, genericServerSecretParams, clock))
|
||||
.addResource(new CertificateController(AuthHelper.ACCOUNTS_MANAGER, CERTIFICATE_GENERATOR, SERVER_ZK_AUTH_OPERATIONS, genericServerSecretParams, genericServerSecretParamsPreV101, clock))
|
||||
.build();
|
||||
|
||||
@Test
|
||||
@@ -237,7 +238,8 @@ class CertificateControllerTest {
|
||||
final UUID aci,
|
||||
final String password,
|
||||
@Nullable UUID pni,
|
||||
@Nullable byte[] authCredentialSalt) {
|
||||
@Nullable byte[] authCredentialSalt,
|
||||
@Nullable Boolean v101) {
|
||||
|
||||
final Instant startOfDay = clock.instant().truncatedTo(ChronoUnit.DAYS);
|
||||
|
||||
@@ -245,6 +247,8 @@ class CertificateControllerTest {
|
||||
.target("/v1/certificate/auth/group")
|
||||
.queryParam("redemptionStartSeconds", startOfDay.getEpochSecond())
|
||||
.queryParam("redemptionEndSeconds", startOfDay.getEpochSecond())
|
||||
// a null value will exclude the parameter altogether, rather than sending `?v101=`
|
||||
.queryParam("v101", v101)
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(aci, password))
|
||||
.get(GroupCredentials.class);
|
||||
@@ -276,16 +280,24 @@ class CertificateControllerTest {
|
||||
|
||||
}
|
||||
|
||||
final GenericServerSecretParams verificationParams = v101 != null && v101
|
||||
? genericServerSecretParams
|
||||
: genericServerSecretParamsPreV101;
|
||||
|
||||
assertDoesNotThrow(() -> {
|
||||
new CallLinkAuthCredentialResponse(credentials.callLinkAuthCredentials().getFirst().credential())
|
||||
.receive(new ServiceId.Aci(aci), startOfDay, genericServerSecretParams.getPublicParams());
|
||||
.receive(new ServiceId.Aci(aci), startOfDay, verificationParams.getPublicParams());
|
||||
});
|
||||
}
|
||||
|
||||
static Collection<Arguments> getGroupCredentials() {
|
||||
return List.of(
|
||||
Arguments.argumentSet("account with phone number", true, AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD, AuthHelper.VALID_PNI, null),
|
||||
Arguments.argumentSet("account without phone number", false, AuthHelper.NUMBERLESS_UUID, AuthHelper.NUMBERLESS_PASSWORD, null, AuthHelper.NUMBERLESS_AUTH_CREDENTIAL_SALT)
|
||||
Arguments.argumentSet("account with phone number", true, AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD, AuthHelper.VALID_PNI, null, null),
|
||||
Arguments.argumentSet("account with phone number - v101 = false", true, AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD, AuthHelper.VALID_PNI, null, false),
|
||||
Arguments.argumentSet("account with phone number - v101 = true", true, AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD, AuthHelper.VALID_PNI, null, true),
|
||||
Arguments.argumentSet("account without phone number", false, AuthHelper.NUMBERLESS_UUID, AuthHelper.NUMBERLESS_PASSWORD, null, AuthHelper.NUMBERLESS_AUTH_CREDENTIAL_SALT, null),
|
||||
Arguments.argumentSet("account without phone number - v101 = false", false, AuthHelper.NUMBERLESS_UUID, AuthHelper.NUMBERLESS_PASSWORD, null, AuthHelper.NUMBERLESS_AUTH_CREDENTIAL_SALT, false),
|
||||
Arguments.argumentSet("account without phone number - v101 = true", false, AuthHelper.NUMBERLESS_UUID, AuthHelper.NUMBERLESS_PASSWORD, null, AuthHelper.NUMBERLESS_AUTH_CREDENTIAL_SALT, true)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -295,13 +307,15 @@ class CertificateControllerTest {
|
||||
final UUID aci,
|
||||
final String password,
|
||||
@Nullable UUID pni,
|
||||
@Nullable byte[] authCredentialSalt) {
|
||||
@Nullable byte[] authCredentialSalt,
|
||||
@Nullable Boolean v101) {
|
||||
final Instant startOfDay = clock.instant().truncatedTo(ChronoUnit.DAYS);
|
||||
|
||||
final GroupCredentials credentials = resources.getJerseyTest()
|
||||
.target("/v1/certificate/auth/group")
|
||||
.queryParam("redemptionStartSeconds", startOfDay.getEpochSecond())
|
||||
.queryParam("redemptionEndSeconds", startOfDay.plus(Duration.ofDays(7)).getEpochSecond())
|
||||
.queryParam("v101", v101)
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(aci, password))
|
||||
.get(GroupCredentials.class);
|
||||
@@ -336,9 +350,13 @@ class CertificateControllerTest {
|
||||
new AuthCredentialWithPniResponse(credentials.credentials().getFirst().credential())));
|
||||
}
|
||||
|
||||
final GenericServerSecretParams verificationParams = v101 != null && v101
|
||||
? genericServerSecretParams
|
||||
: genericServerSecretParamsPreV101;
|
||||
|
||||
assertDoesNotThrow(() -> {
|
||||
new CallLinkAuthCredentialResponse(credentials.callLinkAuthCredentials().get(index).credential())
|
||||
.receive(new ServiceId.Aci(aci), redemptionTime, genericServerSecretParams.getPublicParams());
|
||||
.receive(new ServiceId.Aci(aci), redemptionTime, verificationParams.getPublicParams());
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
-2
@@ -43,7 +43,6 @@ import org.whispersystems.textsecuregcm.backup.BackupAuthManager;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.mappers.CompletionExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.GrpcStatusRuntimeExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.devicecheck.AppleDeviceCheckManager;
|
||||
@@ -73,7 +72,6 @@ class DeviceCheckControllerTest {
|
||||
.addProvider(AuthHelper.getAuthFilter())
|
||||
.addProvider(new AuthValueFactoryProvider.Binder<>(AuthenticatedDevice.class))
|
||||
.addProvider(new CompletionExceptionMapper())
|
||||
.addResource(new GrpcStatusRuntimeExceptionMapper())
|
||||
.addProvider(new RateLimitExceededExceptionMapper())
|
||||
.setMapper(SystemMapper.jsonMapper())
|
||||
.setTestContainerFactory(new GrizzlyWebTestContainerFactory())
|
||||
|
||||
+26
-13
@@ -60,14 +60,17 @@ import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.junit.jupiter.params.provider.NullSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.junitpioneer.jupiter.cartesian.ArgumentSets;
|
||||
import org.junitpioneer.jupiter.cartesian.CartesianTest;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.signal.libsignal.protocol.ecc.ECKeyPair;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.ServerSecretParams;
|
||||
import org.signal.libsignal.zkgroup.VerificationFailedException;
|
||||
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialPresentation;
|
||||
import org.signal.libsignal.zkgroup.receipts.ReceiptSerial;
|
||||
import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations;
|
||||
import org.whispersystems.textsecuregcm.auth.InvalidRegistrationSessionException;
|
||||
import org.whispersystems.textsecuregcm.auth.PhoneVerificationTokenManager;
|
||||
@@ -101,6 +104,7 @@ import org.whispersystems.textsecuregcm.storage.DeviceIdentityInfo;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceSpec;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ReceiptAlreadyRedeemedException;
|
||||
import org.whispersystems.textsecuregcm.storage.ReceiptCredentialTestUtil;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
|
||||
import org.whispersystems.textsecuregcm.tests.util.KeysHelper;
|
||||
@@ -146,8 +150,8 @@ class RegistrationControllerTest {
|
||||
.setMapper(SystemMapper.jsonMapper())
|
||||
.setTestContainerFactory(new GrizzlyWebTestContainerFactory())
|
||||
.addResource(new RegistrationController(accountsManager, phoneVerificationTokenManager,
|
||||
registrationLockVerificationManager, rateLimiters, registrationFraudChecker, ReceiptCredentialPresentation::new, mock(
|
||||
ServerZkReceiptOperations.class), CLOCK, DYNAMIC_CONFIGURATION_MANAGER))
|
||||
registrationLockVerificationManager, rateLimiters, registrationFraudChecker, ReceiptCredentialPresentation::new,
|
||||
new ServerZkReceiptOperations(ReceiptCredentialTestUtil.RECEIPT_PARAMS), CLOCK, DYNAMIC_CONFIGURATION_MANAGER))
|
||||
.build();
|
||||
|
||||
@BeforeEach
|
||||
@@ -879,7 +883,7 @@ class RegistrationControllerTest {
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void registerAccountBadReceipt(final byte[] receiptCredentialPresentation) {
|
||||
void registerAccountBadReceipt(final byte[] receiptCredentialPresentation, final int expectedStatusCode) {
|
||||
final ECKeyPair aciIdentityKeyPair = ECKeyPair.generate();
|
||||
final IdentityKey aciIdentityKey = new IdentityKey(aciIdentityKeyPair.getPublicKey());
|
||||
final ECSignedPreKey aciSignedPreKey = KeysHelper.signedECPreKey(1, aciIdentityKeyPair);
|
||||
@@ -922,7 +926,7 @@ class RegistrationControllerTest {
|
||||
.header(HttpHeaders.AUTHORIZATION, AuthHelper.getProvisioningAuthHeader(NUMBER, PASSWORD));
|
||||
|
||||
try (Response response = request.post(Entity.json(requestToJson(registrationRequest)))) {
|
||||
assertEquals(400, response.getStatus());
|
||||
assertEquals(expectedStatusCode, response.getStatus());
|
||||
}
|
||||
|
||||
verifyNoInteractions(phoneVerificationTokenManager);
|
||||
@@ -931,9 +935,14 @@ class RegistrationControllerTest {
|
||||
|
||||
static Stream<Arguments> registerAccountBadReceipt() throws InvalidInputException, VerificationFailedException {
|
||||
return Stream.of(
|
||||
Arguments.argumentSet("malformed receipt", new byte[]{0, 0}),
|
||||
Arguments.argumentSet("expired receipt", receiptPresentation(CLOCK.instant().minusSeconds(5), ReceiptLevel.LOGIN.getValue()).serialize()),
|
||||
Arguments.argumentSet("wrong receipt level", receiptPresentation(CLOCK.instant().plus(Duration.ofDays(30)), ReceiptLevel.BACKUP_PAID.getValue()).serialize())
|
||||
Arguments.argumentSet("malformed receipt", new byte[]{0, 0}, 400),
|
||||
Arguments.argumentSet("expired receipt",
|
||||
receiptPresentation(CLOCK.instant().minusSeconds(5), ReceiptLevel.LOGIN.getValue()).serialize(), 401),
|
||||
Arguments.argumentSet("receipt signed by wrong params", receiptPresentation(
|
||||
ServerSecretParams.generate(), new ReceiptSerial(TestRandomUtil.nextBytes(ReceiptSerial.SIZE)),
|
||||
CLOCK.instant().plus(Duration.ofDays(30)), ReceiptLevel.LOGIN.getValue()).serialize(), 401),
|
||||
Arguments.argumentSet("wrong receipt level", receiptPresentation(CLOCK.instant().plus(Duration.ofDays(30)),
|
||||
ReceiptLevel.BACKUP_PAID.getValue()).serialize(), 400)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1022,19 +1031,22 @@ class RegistrationControllerTest {
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
void registerAccountMissingRecoveryPassword() throws Exception {
|
||||
@ParameterizedTest
|
||||
@NullSource
|
||||
@ValueSource(ints = 0)
|
||||
void registerAccountMissingRecoveryPassword(@Nullable final Integer recoveryPasswordLength) throws Exception {
|
||||
final ECKeyPair aciIdentityKeyPair = ECKeyPair.generate();
|
||||
final IdentityKey aciIdentityKey = new IdentityKey(aciIdentityKeyPair.getPublicKey());
|
||||
|
||||
final AccountAttributes accountAttributes =
|
||||
new AccountAttributes(true, 1, null, "test".getBytes(StandardCharsets.UTF_8), null, false,
|
||||
DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES, null)
|
||||
DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES,
|
||||
recoveryPasswordLength == null ? null : new byte[recoveryPasswordLength])
|
||||
.setUnidentifiedAccessKey(TestRandomUtil.nextBytes(16));
|
||||
|
||||
final RegistrationRequest registrationRequest = new RegistrationRequest(null,
|
||||
new byte[0],
|
||||
receiptPresentation(CLOCK.instant().plus(Duration.ofDays(30)), 1).serialize(),
|
||||
receiptPresentation(CLOCK.instant().plus(Duration.ofDays(30)), ReceiptLevel.LOGIN.getValue()).serialize(),
|
||||
null,
|
||||
accountAttributes,
|
||||
true,
|
||||
@@ -1119,7 +1131,7 @@ class RegistrationControllerTest {
|
||||
|
||||
final RegistrationRequest registrationRequest = new RegistrationRequest(null,
|
||||
new byte[0],
|
||||
receiptPresentation(CLOCK.instant().plus(Duration.ofDays(30)), 1).serialize(),
|
||||
receiptPresentation(CLOCK.instant().plus(Duration.ofDays(30)), ReceiptLevel.LOGIN.getValue()).serialize(),
|
||||
null,
|
||||
accountAttributes,
|
||||
true,
|
||||
@@ -1141,7 +1153,8 @@ class RegistrationControllerTest {
|
||||
.header(HttpHeaders.AUTHORIZATION, AuthHelper.getProvisioningAuthHeader(NUMBER, PASSWORD));
|
||||
|
||||
try (Response response = request.post(Entity.json(requestToJson(registrationRequest)))) {
|
||||
assertEquals(400, response.getStatus());
|
||||
assertEquals(401, response.getStatus());
|
||||
verify(accountsManager).create(any(), any(), any(), any(), any());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+2
-1
@@ -112,7 +112,7 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest {
|
||||
private static final BadgeTranslator BADGE_TRANSLATOR = mock(BadgeTranslator.class);
|
||||
private static final BankMandateTranslator BANK_MANDATE_TRANSLATOR = mock(BankMandateTranslator.class);
|
||||
private static final LoginPurchaseConfiguration LOGIN_PURCHASE_CONFIG =
|
||||
new LoginPurchaseConfiguration("testLoginPlayProductId", "testLoginAppStoreProductId");
|
||||
new LoginPurchaseConfiguration("testLoginPlayProductId", "testLoginPlayOptionId", "testLoginAppStoreProductId");
|
||||
private final static SubscriptionController SUBSCRIPTION_CONTROLLER = new SubscriptionController(CLOCK,
|
||||
SUBSCRIPTION_CONFIG, ONETIME_CONFIG, LOGIN_PURCHASE_CONFIG,
|
||||
new SubscriptionManager(SUBSCRIPTIONS, List.of(STRIPE_MANAGER, BRAINTREE_MANAGER, PLAY_MANAGER, APPSTORE_MANAGER),
|
||||
@@ -1080,6 +1080,7 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest {
|
||||
|
||||
assertThat(response.login().level()).isEqualTo(ReceiptLevel.LOGIN.getValue());
|
||||
assertThat(response.login().playProductId()).isEqualTo(LOGIN_PURCHASE_CONFIG.playProductId());
|
||||
assertThat(response.login().playOptionId()).isEqualTo(LOGIN_PURCHASE_CONFIG.playOptionId());
|
||||
assertThat(response.login().appStoreProductId()).isEqualTo(LOGIN_PURCHASE_CONFIG.appStoreProductId());
|
||||
|
||||
// check the badge vs purchasable badge fields
|
||||
|
||||
+24
@@ -18,6 +18,7 @@ import org.junitpioneer.jupiter.cartesian.CartesianTest;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.signal.libsignal.protocol.ecc.ECKeyPair;
|
||||
import org.whispersystems.textsecuregcm.tests.util.KeysHelper;
|
||||
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
|
||||
|
||||
class RegistrationRequestTest {
|
||||
|
||||
@@ -179,4 +180,27 @@ class RegistrationRequestTest {
|
||||
|
||||
assertEquals(expectAllPresentOrAbsent, registrationRequest.isAllOrNoPhoneNumberInformationProvided());
|
||||
}
|
||||
|
||||
@CartesianTest
|
||||
void isMfaAbsentWhenUsingReceipt(
|
||||
@CartesianTest.Values(booleans = {false, true}) boolean hasTotp,
|
||||
@CartesianTest.Values(booleans = {false, true}) boolean hasReceipt) {
|
||||
final RegistrationRequest registrationRequest = new RegistrationRequest(null,
|
||||
null,
|
||||
hasReceipt ? TestRandomUtil.nextBytes(32) : null,
|
||||
hasTotp ? 12345 : null,
|
||||
new AccountAttributes(true, 1, null, null, null, false, Collections.emptySet(), null),
|
||||
true,
|
||||
null,
|
||||
null,
|
||||
new DeviceActivationRequest(null,
|
||||
Optional.empty(),
|
||||
null,
|
||||
Optional.empty(),
|
||||
Optional.empty(),
|
||||
Optional.empty()));
|
||||
|
||||
final boolean expectFailure = hasReceipt && hasTotp;
|
||||
assertEquals(!expectFailure, registrationRequest.isMfaAbsentWhenUsingReceipt());
|
||||
}
|
||||
}
|
||||
+80
-1
@@ -6,11 +6,14 @@
|
||||
package org.whispersystems.textsecuregcm.filters;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assumptions.assumeTrue;
|
||||
|
||||
import com.google.common.net.HttpHeaders;
|
||||
import io.dropwizard.core.Application;
|
||||
import io.dropwizard.core.Configuration;
|
||||
import io.dropwizard.core.setup.Environment;
|
||||
import io.dropwizard.testing.ConfigOverride;
|
||||
import io.dropwizard.testing.junit5.DropwizardAppExtension;
|
||||
import io.dropwizard.testing.junit5.DropwizardExtensionsSupport;
|
||||
import jakarta.ws.rs.GET;
|
||||
@@ -36,6 +39,7 @@ import org.eclipse.jetty.ee10.websocket.server.config.JettyWebSocketServletConta
|
||||
import org.eclipse.jetty.util.HostPort;
|
||||
import org.eclipse.jetty.websocket.api.Callback;
|
||||
import org.eclipse.jetty.websocket.api.Session;
|
||||
import org.eclipse.jetty.websocket.client.ClientUpgradeRequest;
|
||||
import org.eclipse.jetty.websocket.client.WebSocketClient;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
@@ -44,6 +48,7 @@ import org.junit.jupiter.api.Timeout;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.whispersystems.textsecuregcm.jetty.JettyHttpConfigurationCustomizer;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
import org.whispersystems.websocket.WebSocketResourceProviderFactory;
|
||||
import org.whispersystems.websocket.configuration.WebSocketConfiguration;
|
||||
@@ -64,7 +69,9 @@ class RemoteAddressFilterIntegrationTest {
|
||||
// in jersey-test-framework-provider-jetty doesn’t easily support @Context HttpServletRequest, so this test runs a
|
||||
// full Jetty server in a separate process
|
||||
private static final DropwizardAppExtension<Configuration> EXTENSION = new DropwizardAppExtension<>(
|
||||
TestApplication.class);
|
||||
TestApplication.class, null,
|
||||
ConfigOverride.config("server.applicationConnectors[0].type", "h2c"),
|
||||
ConfigOverride.config("server.applicationConnectors[0].useForwardedHeaders", "true"));
|
||||
|
||||
@Nested
|
||||
class Rest {
|
||||
@@ -87,6 +94,37 @@ class RemoteAddressFilterIntegrationTest {
|
||||
|
||||
assertEquals(ip, response.remoteAddress());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"127.0.0.3", "0:0:0:0:0:0:dead:beef"})
|
||||
void testForwardedForHeader(final String ip) throws Exception {
|
||||
final Client client = EXTENSION.client();
|
||||
|
||||
final RemoteAddressFilterIntegrationTest.TestResponse response = client.target(
|
||||
String.format("http://%s:%d%s", "localhost", EXTENSION.getLocalPort(), REMOTE_ADDRESS_PATH))
|
||||
.request("application/json")
|
||||
.header(HttpHeaders.X_FORWARDED_FOR, ip)
|
||||
.get(RemoteAddressFilterIntegrationTest.TestResponse.class);
|
||||
|
||||
assertEquals(ip, response.remoteAddress());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"Forwarded", "X-Forwarded-Host", "X-Forwarded-Server", "X-Forwarded-Proto"})
|
||||
void testOtherHeadersIgnored(final String header) throws Exception {
|
||||
final Client client = EXTENSION.client();
|
||||
|
||||
final String ip = "127.0.0.3";
|
||||
|
||||
final RemoteAddressFilterIntegrationTest.TestResponse response = client.target(
|
||||
String.format("http://%s:%d%s", "localhost", EXTENSION.getLocalPort(), REMOTE_ADDRESS_PATH))
|
||||
.request("application/json")
|
||||
.header(header, ip)
|
||||
.get(RemoteAddressFilterIntegrationTest.TestResponse.class);
|
||||
|
||||
assertNotEquals(ip, response.remoteAddress(), "header " + header + " should be ignored");
|
||||
assertEquals("127.0.0.1", response.remoteAddress());
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
@@ -128,6 +166,45 @@ class RemoteAddressFilterIntegrationTest {
|
||||
|
||||
assertEquals(ip, response.remoteAddress());
|
||||
}
|
||||
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"127.0.0.3", "0:0:0:0:0:0:dead:beef"})
|
||||
void testForwardedForHeader(final String ip) throws Exception {
|
||||
final CompletableFuture<byte[]> responseFuture = new CompletableFuture<>();
|
||||
final ClientEndpoint clientEndpoint = new ClientEndpoint(WS_REQUEST_PATH, responseFuture);
|
||||
final ClientUpgradeRequest upgradeRequest = new ClientUpgradeRequest(URI.create(String.format("ws://%s:%d%s",
|
||||
"localhost",
|
||||
EXTENSION.getLocalPort(),
|
||||
WEBSOCKET_PREFIX + REMOTE_ADDRESS_PATH)));
|
||||
upgradeRequest.setHeader(HttpHeaders.X_FORWARDED_FOR, ip);
|
||||
client.connect(clientEndpoint, upgradeRequest);
|
||||
|
||||
final byte[] responseBytes = responseFuture.get(1, TimeUnit.SECONDS);
|
||||
final TestResponse response = SystemMapper.jsonMapper().readValue(responseBytes, TestResponse.class);
|
||||
assertEquals(ip, response.remoteAddress());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"Forwarded", "X-Forwarded-Host", "X-Forwarded-Server", "X-Forwarded-Proto"})
|
||||
void testOtherHeadersIgnored(final String header) throws Exception {
|
||||
final String ip = "127.0.0.3";
|
||||
|
||||
final CompletableFuture<byte[]> responseFuture = new CompletableFuture<>();
|
||||
final ClientEndpoint clientEndpoint = new ClientEndpoint(WS_REQUEST_PATH, responseFuture);
|
||||
final ClientUpgradeRequest upgradeRequest = new ClientUpgradeRequest(URI.create(String.format("ws://%s:%d%s",
|
||||
"localhost",
|
||||
EXTENSION.getLocalPort(),
|
||||
WEBSOCKET_PREFIX + REMOTE_ADDRESS_PATH)));
|
||||
upgradeRequest.setHeader(header, ip);
|
||||
client.connect(clientEndpoint, upgradeRequest);
|
||||
|
||||
final byte[] responseBytes = responseFuture.get(1, TimeUnit.SECONDS);
|
||||
final TestResponse response = SystemMapper.jsonMapper().readValue(responseBytes, TestResponse.class);
|
||||
|
||||
assertNotEquals(ip, response.remoteAddress(), "header " + header + " should be ignored");
|
||||
assertEquals("127.0.0.1", response.remoteAddress());
|
||||
}
|
||||
}
|
||||
|
||||
public static class ClientEndpoint implements Session.Listener.AutoDemanding {
|
||||
@@ -216,6 +293,8 @@ class RemoteAddressFilterIntegrationTest {
|
||||
webSocketEnvironment, TestPrincipal.class,
|
||||
RemoteAddressFilter.REMOTE_ADDRESS_ATTRIBUTE_NAME);
|
||||
|
||||
environment.lifecycle().addEventListener(new JettyHttpConfigurationCustomizer());
|
||||
|
||||
JettyWebSocketServletContainerInitializer.configure(environment.getApplicationContext(), (servletContext, container) -> {
|
||||
container.addMapping(WEBSOCKET_PREFIX + REMOTE_ADDRESS_PATH, webSocketServlet);
|
||||
PriorityFilter.ensureFilter(servletContext, new RemoteAddressFilter());
|
||||
|
||||
+104
-57
@@ -73,18 +73,18 @@ import org.signal.chat.account.GetCapabilitiesRequest;
|
||||
import org.signal.chat.account.GetCapabilitiesResponse;
|
||||
import org.signal.chat.account.GetEntitlementsRequest;
|
||||
import org.signal.chat.account.GetEntitlementsResponse;
|
||||
import org.signal.chat.account.ListTotpKeysRequest;
|
||||
import org.signal.chat.account.ListTotpKeysResponse;
|
||||
import org.signal.chat.account.ListMfaKeysRequest;
|
||||
import org.signal.chat.account.ListMfaKeysResponse;
|
||||
import org.signal.chat.account.RegistrationLockFailure;
|
||||
import org.signal.chat.account.RemoveTotpKeyRequest;
|
||||
import org.signal.chat.account.RemoveMfaKeyRequest;
|
||||
import org.signal.chat.account.ReserveUsernameHashRequest;
|
||||
import org.signal.chat.account.ReserveUsernameHashResponse;
|
||||
import org.signal.chat.account.SetDiscoverableByPhoneNumberRequest;
|
||||
import org.signal.chat.account.SetRegistrationLockRequest;
|
||||
import org.signal.chat.account.SetRegistrationLockResponse;
|
||||
import org.signal.chat.account.SetRegistrationRecoveryPasswordRequest;
|
||||
import org.signal.chat.account.SetTotpKeyMetadataRequest;
|
||||
import org.signal.chat.account.SetTotpKeyMetadataResponse;
|
||||
import org.signal.chat.account.SetMfaKeyMetadataRequest;
|
||||
import org.signal.chat.account.SetMfaKeyMetadataResponse;
|
||||
import org.signal.chat.account.SetUsernameLinkRequest;
|
||||
import org.signal.chat.account.SetUsernameLinkResponse;
|
||||
import org.signal.chat.account.SetZkCredentialKeyRequest;
|
||||
@@ -92,6 +92,7 @@ import org.signal.chat.account.SetZkCredentialKeyResponse;
|
||||
import org.signal.chat.account.StaleDevices;
|
||||
import org.signal.chat.account.TotpParameters;
|
||||
import org.signal.chat.account.UsernameNotAvailable;
|
||||
import org.signal.chat.account.ListMfaKeysResponse.MfaKeyMetadata.MfaKeyType;
|
||||
import org.signal.chat.common.AccountIdentifiers;
|
||||
import org.signal.chat.common.EcSignedPreKey;
|
||||
import org.signal.chat.common.KemSignedPreKey;
|
||||
@@ -123,6 +124,7 @@ import org.whispersystems.textsecuregcm.push.MessageTooLargeException;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountBadge;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.AnnotatedMfaKey;
|
||||
import org.whispersystems.textsecuregcm.storage.AnnotatedTotpKey;
|
||||
import org.whispersystems.textsecuregcm.storage.ChangeNumberManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
@@ -130,6 +132,7 @@ import org.whispersystems.textsecuregcm.storage.DeviceCapability;
|
||||
import org.whispersystems.textsecuregcm.storage.KeyIdUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.PhoneNumberRecoveryPasswordsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.TooManyTotpKeysException;
|
||||
import org.whispersystems.textsecuregcm.storage.TooManyMfaKeysException;
|
||||
import org.whispersystems.textsecuregcm.storage.TotpKey;
|
||||
import org.whispersystems.textsecuregcm.storage.UsernameHashNotAvailableException;
|
||||
import org.whispersystems.textsecuregcm.storage.UsernameReservationNotFoundException;
|
||||
@@ -161,7 +164,13 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
|
||||
@Mock
|
||||
private ChangeNumberManager changeNumberManager;
|
||||
|
||||
private static final int TOTP_KEY_METADATA_SIZE = 160;
|
||||
private static final org.whispersystems.textsecuregcm.storage.TotpParameters TOTP_PARAMETERS =
|
||||
new org.whispersystems.textsecuregcm.storage.TotpParameters(
|
||||
AccountsManager.TOTP.getAlgorithm(),
|
||||
AccountsManager.TOTP.getPasswordLength(),
|
||||
AccountsManager.TOTP.getTimeStep());
|
||||
|
||||
private static final int MFA_KEY_METADATA_SIZE = 160;
|
||||
|
||||
@Override
|
||||
protected AccountsGrpcService createServiceBeforeEachTest() {
|
||||
@@ -1118,11 +1127,11 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
|
||||
}
|
||||
|
||||
@Test
|
||||
void generateTotpKey() throws TooManyTotpKeysException {
|
||||
void generateTotpKey() throws TooManyTotpKeysException, TooManyMfaKeysException {
|
||||
final byte[] encodedKey = TestRandomUtil.nextBytes(16);
|
||||
|
||||
when(accountsManager.generatePendingTotpKey(AUTHENTICATED_ACI))
|
||||
.thenReturn(new TotpKey(AccountsManager.TOTP_PARAMETERS, encodedKey));
|
||||
.thenReturn(new TotpKey(TOTP_PARAMETERS, encodedKey));
|
||||
|
||||
final GenerateTotpKeyResponse response =
|
||||
authenticatedServiceStub().generateTotpKey(GenerateTotpKeyRequest.getDefaultInstance());
|
||||
@@ -1130,13 +1139,13 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
|
||||
assertEquals(GenerateTotpKeyResponse.ResponseCase.KEY_GENERATED, response.getResponseCase());
|
||||
|
||||
assertArrayEquals(encodedKey, response.getKeyGenerated().getKey().toByteArray());
|
||||
assertEquals(AccountsManager.TOTP_PARAMETERS.algorithm(), response.getKeyGenerated().getTotpParameters().getAlgorithm());
|
||||
assertEquals(AccountsManager.TOTP_PARAMETERS.passwordLength(), response.getKeyGenerated().getTotpParameters().getPasswordLength());
|
||||
assertEquals(AccountsManager.TOTP_PARAMETERS.timeStep().toSeconds(), response.getKeyGenerated().getTotpParameters().getTimeStepSeconds());
|
||||
assertEquals(AccountsManager.TOTP.getAlgorithm(), response.getKeyGenerated().getTotpParameters().getAlgorithm());
|
||||
assertEquals(AccountsManager.TOTP.getPasswordLength(), response.getKeyGenerated().getTotpParameters().getPasswordLength());
|
||||
assertEquals(AccountsManager.TOTP.getTimeStep().toSeconds(), response.getKeyGenerated().getTotpParameters().getTimeStepSeconds());
|
||||
}
|
||||
|
||||
@Test
|
||||
void generateTotpKeyTooManyKeys() throws TooManyTotpKeysException {
|
||||
void generateTotpKeyTooManyKeys() throws TooManyTotpKeysException, TooManyMfaKeysException {
|
||||
when(accountsManager.generatePendingTotpKey(AUTHENTICATED_ACI))
|
||||
.thenThrow(TooManyTotpKeysException.class);
|
||||
|
||||
@@ -1147,10 +1156,22 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
|
||||
}
|
||||
|
||||
@Test
|
||||
void confirmTotpKey() {
|
||||
final int keyId = 17;
|
||||
void generateTotpKeyTooManyNonTotpKeys() throws TooManyTotpKeysException, TooManyMfaKeysException {
|
||||
when(accountsManager.generatePendingTotpKey(AUTHENTICATED_ACI))
|
||||
.thenThrow(TooManyMfaKeysException.class);
|
||||
|
||||
final GenerateTotpKeyResponse response =
|
||||
authenticatedServiceStub().generateTotpKey(GenerateTotpKeyRequest.getDefaultInstance());
|
||||
|
||||
assertEquals(GenerateTotpKeyResponse.ResponseCase.TOO_MANY_MFA_KEYS, response.getResponseCase());
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
void confirmTotpKey() throws TooManyMfaKeysException {
|
||||
final byte keyId = 17;
|
||||
final int oneTimePassword = 123456;
|
||||
final byte[] metadataCiphertext = TestRandomUtil.nextBytes(TOTP_KEY_METADATA_SIZE);
|
||||
final byte[] metadataCiphertext = TestRandomUtil.nextBytes(MFA_KEY_METADATA_SIZE);
|
||||
|
||||
when(accountsManager.confirmPendingTotpKey(AUTHENTICATED_ACI, oneTimePassword, testClock.instant(), metadataCiphertext))
|
||||
.thenReturn(Optional.of(keyId));
|
||||
@@ -1169,47 +1190,56 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
|
||||
GrpcTestUtils.assertStatusInvalidArgument(
|
||||
() -> authenticatedServiceStub().confirmTotpKey(ConfirmTotpKeyRequest.newBuilder()
|
||||
.setOneTimePassword(123456)
|
||||
.setMetadataCiphertext(ByteString.copyFrom(TestRandomUtil.nextBytes(TOTP_KEY_METADATA_SIZE + 1)))
|
||||
.setMetadataCiphertext(ByteString.copyFrom(TestRandomUtil.nextBytes(MFA_KEY_METADATA_SIZE + 1)))
|
||||
.build()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void confirmTotpKeyPasswordNotVerified() {
|
||||
void confirmTotpKeyPasswordNotVerified() throws TooManyMfaKeysException {
|
||||
when(accountsManager.confirmPendingTotpKey(any(), anyInt(), any(), any()))
|
||||
.thenReturn(Optional.empty());
|
||||
|
||||
final ConfirmTotpKeyResponse response = authenticatedServiceStub().confirmTotpKey(ConfirmTotpKeyRequest.newBuilder()
|
||||
.setOneTimePassword(123456)
|
||||
.setMetadataCiphertext(ByteString.copyFrom(TestRandomUtil.nextBytes(TOTP_KEY_METADATA_SIZE)))
|
||||
.setMetadataCiphertext(ByteString.copyFrom(TestRandomUtil.nextBytes(MFA_KEY_METADATA_SIZE)))
|
||||
.build());
|
||||
|
||||
assertEquals(ConfirmTotpKeyResponse.ResponseCase.ONE_TIME_PASSWORD_NOT_VERIFIED, response.getResponseCase());
|
||||
}
|
||||
|
||||
@Test
|
||||
void confirmTotpKeyTooManyNonTotpKeys() throws TooManyTotpKeysException, TooManyMfaKeysException {
|
||||
when(accountsManager.confirmPendingTotpKey(any(), anyInt(), any(), any()))
|
||||
.thenThrow(TooManyMfaKeysException.class);
|
||||
|
||||
final ConfirmTotpKeyResponse response =
|
||||
authenticatedServiceStub().confirmTotpKey(ConfirmTotpKeyRequest.newBuilder()
|
||||
.setOneTimePassword(123456)
|
||||
.setMetadataCiphertext(ByteString.copyFrom(TestRandomUtil.nextBytes(MFA_KEY_METADATA_SIZE)))
|
||||
.build());
|
||||
|
||||
assertEquals(ConfirmTotpKeyResponse.ResponseCase.TOO_MANY_MFA_KEYS, response.getResponseCase());
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
void listTotpKeys() {
|
||||
final Map<Integer, AnnotatedTotpKey> totpKeys = Map.of(
|
||||
1, generateRandomAnnotatedTotpKey(),
|
||||
2, generateRandomAnnotatedTotpKey());
|
||||
final Map<Byte, AnnotatedMfaKey> totpKeys = Map.of(
|
||||
(byte) 1, generateRandomAnnotatedTotpKey(),
|
||||
(byte) 2, generateRandomAnnotatedTotpKey());
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
when(account.getTotpKeys()).thenReturn(totpKeys);
|
||||
when(account.getMfaKeys()).thenReturn(totpKeys);
|
||||
|
||||
when(accountsManager.getByAccountIdentifier(AUTHENTICATED_ACI))
|
||||
.thenReturn(Optional.of(account));
|
||||
|
||||
final ListTotpKeysResponse response =
|
||||
authenticatedServiceStub().listTotpKeys(ListTotpKeysRequest.getDefaultInstance());
|
||||
final ListMfaKeysResponse response =
|
||||
authenticatedServiceStub().listMfaKeys(ListMfaKeysRequest.getDefaultInstance());
|
||||
|
||||
final TotpParameters expectedTotpParameters = TotpParameters.newBuilder()
|
||||
.setAlgorithm(AccountsManager.TOTP_PARAMETERS.algorithm())
|
||||
.setPasswordLength(AccountsManager.TOTP_PARAMETERS.passwordLength())
|
||||
.setTimeStepSeconds(Math.toIntExact(AccountsManager.TOTP_PARAMETERS.timeStep().toSeconds()))
|
||||
.build();
|
||||
|
||||
final Map<Integer, ListTotpKeysResponse.TotpKeyMetadata> expectedTotpKeys = totpKeys.entrySet().stream()
|
||||
.collect(Collectors.toMap(Map.Entry::getKey, entry -> ListTotpKeysResponse.TotpKeyMetadata.newBuilder()
|
||||
.setTotpParameters(expectedTotpParameters)
|
||||
final Map<Integer, ListMfaKeysResponse.MfaKeyMetadata> expectedTotpKeys = totpKeys.entrySet().stream()
|
||||
.collect(Collectors.toMap(entry -> entry.getKey().intValue(), entry -> ListMfaKeysResponse.MfaKeyMetadata.newBuilder()
|
||||
.setType(MfaKeyType.MFA_KEY_TYPE_TOTP)
|
||||
.setMetadataCiphertext(ByteString.copyFrom(entry.getValue().metadataCiphertext()))
|
||||
.build()));
|
||||
|
||||
@@ -1218,77 +1248,94 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
|
||||
|
||||
@Test
|
||||
void setTotpKeyMetadata() {
|
||||
final int keyId = ThreadLocalRandom.current().nextInt();
|
||||
final byte[] updatedMetadata = TestRandomUtil.nextBytes(TOTP_KEY_METADATA_SIZE);
|
||||
final AnnotatedTotpKey existingTotpKey = generateRandomAnnotatedTotpKey();
|
||||
final byte keyId = (byte) ThreadLocalRandom.current().nextInt(Account.MAX_MFA_KEY_ID);
|
||||
final byte[] updatedMetadata = TestRandomUtil.nextBytes(MFA_KEY_METADATA_SIZE);
|
||||
final AnnotatedMfaKey existingTotpKey = generateRandomAnnotatedTotpKey();
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
when(account.getTotpKeys()).thenReturn(Map.of(keyId, existingTotpKey));
|
||||
when(account.getMfaKeys()).thenReturn(Map.of(keyId, existingTotpKey));
|
||||
|
||||
when(accountsManager.getByAccountIdentifier(AUTHENTICATED_ACI))
|
||||
.thenReturn(Optional.of(account));
|
||||
|
||||
final SetTotpKeyMetadataResponse response =
|
||||
authenticatedServiceStub().setTotpKeyMetadata(SetTotpKeyMetadataRequest.newBuilder()
|
||||
final SetMfaKeyMetadataResponse response =
|
||||
authenticatedServiceStub().setMfaKeyMetadata(SetMfaKeyMetadataRequest.newBuilder()
|
||||
.setKeyId(keyId)
|
||||
.setMetadataCiphertext(ByteString.copyFrom(updatedMetadata))
|
||||
.build());
|
||||
|
||||
assertEquals(SetTotpKeyMetadataResponse.ResponseCase.METADATA_UPDATED, response.getResponseCase());
|
||||
verify(account).setTotpKeys(Map.of(keyId, new AnnotatedTotpKey(existingTotpKey.totpKey(), updatedMetadata)));
|
||||
assertEquals(SetMfaKeyMetadataResponse.ResponseCase.METADATA_UPDATED, response.getResponseCase());
|
||||
verify(account).setMfaKeys(Map.of(keyId, existingTotpKey.withMetadataCiphertext(updatedMetadata)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void setTotpKeyMetadataKeyNotFound() {
|
||||
final Account account = mock(Account.class);
|
||||
when(account.getTotpKeys()).thenReturn(Collections.emptyMap());
|
||||
when(account.getMfaKeys()).thenReturn(Collections.emptyMap());
|
||||
|
||||
when(accountsManager.getByAccountIdentifier(AUTHENTICATED_ACI))
|
||||
.thenReturn(Optional.of(account));
|
||||
|
||||
final SetTotpKeyMetadataResponse response =
|
||||
authenticatedServiceStub().setTotpKeyMetadata(SetTotpKeyMetadataRequest.newBuilder()
|
||||
.setKeyId(ThreadLocalRandom.current().nextInt())
|
||||
.setMetadataCiphertext(ByteString.copyFrom(TestRandomUtil.nextBytes(TOTP_KEY_METADATA_SIZE)))
|
||||
final SetMfaKeyMetadataResponse response =
|
||||
authenticatedServiceStub().setMfaKeyMetadata(SetMfaKeyMetadataRequest.newBuilder()
|
||||
.setKeyId(ThreadLocalRandom.current().nextInt(Account.MAX_MFA_KEY_ID))
|
||||
.setMetadataCiphertext(ByteString.copyFrom(TestRandomUtil.nextBytes(MFA_KEY_METADATA_SIZE)))
|
||||
.build());
|
||||
|
||||
assertEquals(SetTotpKeyMetadataResponse.ResponseCase.KEY_NOT_FOUND, response.getResponseCase());
|
||||
assertEquals(SetMfaKeyMetadataResponse.ResponseCase.KEY_NOT_FOUND, response.getResponseCase());
|
||||
}
|
||||
|
||||
@Test
|
||||
void setTotpKeyMetadataIncorrectMetadataSize() {
|
||||
GrpcTestUtils.assertStatusInvalidArgument(
|
||||
() -> authenticatedServiceStub().setTotpKeyMetadata(SetTotpKeyMetadataRequest.newBuilder()
|
||||
() -> authenticatedServiceStub().setMfaKeyMetadata(SetMfaKeyMetadataRequest.newBuilder()
|
||||
.setKeyId(1)
|
||||
.setMetadataCiphertext(ByteString.copyFrom(TestRandomUtil.nextBytes(TOTP_KEY_METADATA_SIZE + 1)))
|
||||
.setMetadataCiphertext(ByteString.copyFrom(TestRandomUtil.nextBytes(MFA_KEY_METADATA_SIZE + 1)))
|
||||
.build()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void setTotpKeyMetadataKeyIdOutOfRange() {
|
||||
GrpcTestUtils.assertStatusInvalidArgument(
|
||||
() -> authenticatedServiceStub().setMfaKeyMetadata(SetMfaKeyMetadataRequest.newBuilder()
|
||||
.setKeyId(Account.MAX_MFA_KEY_ID + 1)
|
||||
.setMetadataCiphertext(ByteString.copyFrom(TestRandomUtil.nextBytes(MFA_KEY_METADATA_SIZE)))
|
||||
.build()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void removeTotpKey() {
|
||||
final int retainedKeyId = 1;
|
||||
final int removedKeyId = 2;
|
||||
final byte retainedKeyId = 1;
|
||||
final byte removedKeyId = 2;
|
||||
|
||||
final Map<Integer, AnnotatedTotpKey> initialKeys = Map.of(
|
||||
final Map<Byte, AnnotatedMfaKey> initialKeys = Map.of(
|
||||
retainedKeyId, generateRandomAnnotatedTotpKey(),
|
||||
removedKeyId, generateRandomAnnotatedTotpKey());
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
when(account.getTotpKeys()).thenReturn(initialKeys);
|
||||
when(account.getMfaKeys()).thenReturn(initialKeys);
|
||||
|
||||
when(accountsManager.getByAccountIdentifier(AUTHENTICATED_ACI))
|
||||
.thenReturn(Optional.of(account));
|
||||
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
authenticatedServiceStub().removeTotpKey(RemoveTotpKeyRequest.newBuilder()
|
||||
authenticatedServiceStub().removeMfaKey(RemoveMfaKeyRequest.newBuilder()
|
||||
.setKeyId(removedKeyId)
|
||||
.build());
|
||||
|
||||
verify(account).setTotpKeys(Map.of(retainedKeyId, initialKeys.get(retainedKeyId)));
|
||||
verify(account).setMfaKeys(Map.of(retainedKeyId, initialKeys.get(retainedKeyId)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void removeTotpKeyIdOutOfRange() {
|
||||
GrpcTestUtils.assertStatusInvalidArgument(
|
||||
() -> authenticatedServiceStub().removeMfaKey(RemoveMfaKeyRequest.newBuilder()
|
||||
.setKeyId(Account.MAX_MFA_KEY_ID + 1)
|
||||
.build()));
|
||||
}
|
||||
|
||||
private static AnnotatedTotpKey generateRandomAnnotatedTotpKey() {
|
||||
return new AnnotatedTotpKey(new TotpKey(AccountsManager.TOTP_PARAMETERS, TestRandomUtil.nextBytes(32)),
|
||||
TestRandomUtil.nextBytes(TOTP_KEY_METADATA_SIZE));
|
||||
return new AnnotatedTotpKey(new TotpKey(TOTP_PARAMETERS, TestRandomUtil.nextBytes(32)),
|
||||
TestRandomUtil.nextBytes(MFA_KEY_METADATA_SIZE));
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -40,7 +40,7 @@ public class ProductConfigurationGrpcServiceTest extends
|
||||
SubscriptionConfigTestHelper.getOneTimeConfig();
|
||||
|
||||
private static final LoginPurchaseConfiguration LOGIN_PURCHASE_CONFIGURATION =
|
||||
new LoginPurchaseConfiguration("testLoginPlayProductId", "testLoginAppStoreProductId");
|
||||
new LoginPurchaseConfiguration("testLoginPlayProductId", "testLoginPlayOptionId", "testLoginAppStoreProductId");
|
||||
|
||||
@Mock
|
||||
private StripeManager stripeManager;
|
||||
@@ -135,6 +135,7 @@ public class ProductConfigurationGrpcServiceTest extends
|
||||
|
||||
assertEquals(ReceiptLevel.LOGIN.getValue(), configuration.getLogin().getLevel());
|
||||
assertEquals(LOGIN_PURCHASE_CONFIGURATION.playProductId(), configuration.getLogin().getPlayProductId());
|
||||
assertEquals(LOGIN_PURCHASE_CONFIGURATION.playOptionId(), configuration.getLogin().getPlayOptionId());
|
||||
assertEquals(LOGIN_PURCHASE_CONFIGURATION.appStoreProductId(), configuration.getLogin().getAppStoreProductId());
|
||||
}
|
||||
|
||||
|
||||
+87
-4
@@ -8,6 +8,7 @@ package org.whispersystems.textsecuregcm.grpc;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.AdditionalMatchers.aryEq;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
@@ -41,6 +42,7 @@ import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
@@ -57,6 +59,7 @@ import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Mock;
|
||||
import org.signal.chat.common.IdentityType;
|
||||
import org.signal.chat.common.ServiceIdentifier;
|
||||
import org.signal.chat.profile.AccountInfo;
|
||||
import org.signal.chat.profile.GetAvatarCredentialsRequest;
|
||||
import org.signal.chat.profile.GetAvatarCredentialsResponse;
|
||||
import org.signal.chat.profile.GetProfileRequest;
|
||||
@@ -64,12 +67,13 @@ import org.signal.chat.profile.GetProfileResponse;
|
||||
import org.signal.chat.profile.LegacyProfileResult;
|
||||
import org.signal.chat.profile.ProfileGrpc;
|
||||
import org.signal.chat.profile.ProfileResult;
|
||||
import org.signal.chat.profile.AccountInfo;
|
||||
import org.signal.chat.profile.SetProfileRequest;
|
||||
import org.signal.chat.profile.SetProfileResponse;
|
||||
import org.signal.chat.profile.SetProfileResult;
|
||||
import org.signal.chat.profile.SetProfileV1Request;
|
||||
import org.signal.chat.profile.SetProfileV1Request.AvatarChange;
|
||||
import org.signal.chat.profile.SetV1AvatarRequest;
|
||||
import org.signal.chat.profile.SetV1AvatarResponse;
|
||||
import org.signal.chat.profile.test.PlaintextProfileData;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.signal.libsignal.protocol.ServiceId;
|
||||
@@ -195,8 +199,6 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
|
||||
when(accountsManager.getByAccountIdentifier(AUTHENTICATED_ACI)).thenReturn(Optional.of(account));
|
||||
when(accountsManager.getByServiceIdentifier(new AciServiceIdentifier(AUTHENTICATED_ACI))).thenReturn(Optional.of(account));
|
||||
|
||||
when(profilesManager.getV1(any(), any())).thenReturn(Optional.of(profile));
|
||||
|
||||
when(dynamicConfigurationManager.getConfiguration()).thenReturn(dynamicConfiguration);
|
||||
when(dynamicConfiguration.getPaymentsConfiguration()).thenReturn(dynamicPaymentsConfiguration);
|
||||
when(dynamicPaymentsConfiguration.disallowedPrefixes()).thenReturn(Collections.emptyList());
|
||||
@@ -376,6 +378,23 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
|
||||
assertTrue(response.hasProfilesV2CapabilityRequired());
|
||||
}
|
||||
|
||||
@Test
|
||||
void setProfileUnauthenticated() {
|
||||
|
||||
when(accountsManager.getByAccountIdentifier(AUTHENTICATED_ACI)).thenReturn(Optional.empty());
|
||||
|
||||
final SetProfileRequest request = SetProfileRequest.newBuilder()
|
||||
.setVersion(ByteString.copyFrom(VERSION))
|
||||
.setData(ByteString.copyFrom(VALID_DATA))
|
||||
.setExpectedCurrentDataHash(ByteString.copyFrom(TestRandomUtil.nextBytes(32)))
|
||||
.setV1Request(V1_REQUEST)
|
||||
.build();
|
||||
|
||||
final StatusRuntimeException statusRuntimeException = assertStatusException(Status.UNAUTHENTICATED,
|
||||
() -> authenticatedServiceStub().setProfile(request));
|
||||
assertEquals("invalid credentials", statusRuntimeException.getStatus().getDescription());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void setProfileUpload(final AvatarChange avatarChange, final boolean hasPreviousProfile,
|
||||
@@ -862,7 +881,7 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
|
||||
|
||||
final StatusRuntimeException statusRuntimeException = assertStatusException(Status.UNAUTHENTICATED,
|
||||
() -> authenticatedServiceStub().getAvatarCredentials(GetAvatarCredentialsRequest.getDefaultInstance()));
|
||||
assertEquals("account not found", statusRuntimeException.getStatus().getDescription());
|
||||
assertEquals("invalid credentials", statusRuntimeException.getStatus().getDescription());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -902,6 +921,70 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
|
||||
assertEquals("invalid credential request", statusRuntimeException.getStatus().getDescription());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void setV1Avatar(boolean hasAvatar) {
|
||||
final String version = HexFormat.of().formatHex(TestRandomUtil.nextBytes(32));
|
||||
|
||||
final VersionedProfileV1 profile = new VersionedProfileV1(version,
|
||||
TestRandomUtil.nextBytes(81),
|
||||
hasAvatar ? "profiles/old-avatar" : null,
|
||||
null,
|
||||
TestRandomUtil.nextBytes(156),
|
||||
null,
|
||||
TestRandomUtil.nextBytes(582),
|
||||
TestRandomUtil.nextBytes(32)
|
||||
);
|
||||
|
||||
when(profilesManager.getV1(AUTHENTICATED_ACI, profile.version()))
|
||||
.thenReturn(Optional.of(profile));
|
||||
|
||||
final SetV1AvatarResponse response = authenticatedServiceStub().setV1Avatar(
|
||||
SetV1AvatarRequest.newBuilder()
|
||||
.setVersion(version)
|
||||
.build());
|
||||
|
||||
verify(profilesManager).setV1Avatar(eq(AUTHENTICATED_ACI), eq(version), anyString(), aryEq(profile.commitment()));
|
||||
|
||||
assertTrue(response.hasForm());
|
||||
assertTrue(response.getForm().getKey().startsWith("profiles/"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void setV1AvatarNewVersion() throws Exception {
|
||||
final ProfileKey profileKey = new ProfileKey(new byte[32]);
|
||||
final byte[] commitment = profileKey.getCommitment(new ServiceId.Aci(AUTHENTICATED_ACI)).serialize();
|
||||
final String version = profileKey.getProfileKeyVersion(new ServiceId.Aci(AUTHENTICATED_ACI)).serialize();
|
||||
|
||||
when(profilesManager.getV1(eq(AUTHENTICATED_ACI), anyString()))
|
||||
.thenReturn(Optional.empty());
|
||||
|
||||
final SetV1AvatarResponse response = authenticatedServiceStub().setV1Avatar(
|
||||
SetV1AvatarRequest.newBuilder()
|
||||
.setVersion(version)
|
||||
.setCommitment(ByteString.copyFrom(commitment))
|
||||
.build());
|
||||
|
||||
verify(profilesManager).setV1Avatar(eq(AUTHENTICATED_ACI), eq(version), anyString(), aryEq(commitment));
|
||||
|
||||
assertTrue(response.hasForm());
|
||||
assertTrue(response.getForm().getKey().startsWith("profiles/"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void setV1AvatarNewVersionMissingCommitment() {
|
||||
when(profilesManager.getV1(eq(AUTHENTICATED_ACI), anyString()))
|
||||
.thenReturn(Optional.empty());
|
||||
|
||||
final StatusRuntimeException statusRuntimeException = assertStatusInvalidArgument(
|
||||
() -> authenticatedServiceStub().setV1Avatar(
|
||||
SetV1AvatarRequest.newBuilder().setVersion(HexFormat.of().formatHex(TestRandomUtil.nextBytes(32)))
|
||||
.build()));
|
||||
|
||||
assertNotNull(statusRuntimeException.getStatus().getDescription());
|
||||
assertTrue(statusRuntimeException.getStatus().getDescription().toLowerCase(Locale.ROOT).contains("commitment"));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(ints = {0, 1, 16, 32})
|
||||
void testProfileSerialized(int aboutEmojiLength) {
|
||||
|
||||
+4
-3
@@ -8,6 +8,7 @@ package org.whispersystems.textsecuregcm.grpc;
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyBoolean;
|
||||
@@ -29,6 +30,7 @@ import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.stream.Stream;
|
||||
import io.grpc.Status;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
@@ -193,11 +195,10 @@ public class SubscriptionsGrpcServiceTest extends
|
||||
void updateSubscriberIdMismatch() throws SubscriptionException {
|
||||
doThrow(new SubscriptionForbiddenException("subscriberId mismatch"))
|
||||
.when(subscriptionManager).updateSubscriber(any(), anyBoolean());
|
||||
final UpdateSubscriberResponse response = unauthenticatedServiceStub().updateSubscriber(
|
||||
GrpcTestUtils.assertStatusException(Status.INVALID_ARGUMENT, () -> unauthenticatedServiceStub().updateSubscriber(
|
||||
UpdateSubscriberRequest.newBuilder()
|
||||
.setSubscriberId(SUBSCRIBER_ID)
|
||||
.build());
|
||||
assertEquals(UpdateSubscriberResponse.ResponseCase.SUBSCRIBER_ID_MISMATCH, response.getResponseCase());
|
||||
.build()));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+18
-20
@@ -55,7 +55,6 @@ import io.netty.util.ReferenceCountUtil;
|
||||
import io.netty.util.test.LeakPresenceExtension;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.InputStream;
|
||||
import java.math.BigDecimal;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
@@ -71,6 +70,7 @@ import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
import javax.annotation.Nullable;
|
||||
import javax.net.ssl.SSLException;
|
||||
@@ -88,9 +88,9 @@ import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicOmnibusConf
|
||||
|
||||
@ExtendWith(LeakPresenceExtension.class)
|
||||
class OmnibusH2ServerTest {
|
||||
// Paths that start with PREFIX should go to the prefix backend, everything else to default.
|
||||
private static final String PREFIX_BACKEND_IDENTITY = "prefix-backend";
|
||||
private static final String PREFIX = "/v1/prefix";
|
||||
// URIs targeting PATH should go to the path backend, everything else to default.
|
||||
private static final String PATH_BACKEND_IDENTITY = "path-backend";
|
||||
private static final String PATH = "/v1/path/";
|
||||
private static final String DEFAULT_BACKEND_IDENTITY = "default-backend";
|
||||
|
||||
private static NioEventLoopGroup nioEventLoopGroup;
|
||||
@@ -152,7 +152,7 @@ class OmnibusH2ServerTest {
|
||||
@ValueSource(booleans = {true, false})
|
||||
void defaultBackend(final boolean localChannel) throws Exception {
|
||||
final OmnibusH2Server server = startOmnibusServer(
|
||||
Map.of(PREFIX, startBackendServer(localChannel, PREFIX_BACKEND_IDENTITY)),
|
||||
Map.of(PATH, startBackendServer(localChannel, PATH_BACKEND_IDENTITY)),
|
||||
startBackendServer(localChannel, DEFAULT_BACKEND_IDENTITY));
|
||||
final String response = sendRequestThroughOmnibus(connectToOmnibus(server), "/a/different/path");
|
||||
assertEquals(DEFAULT_BACKEND_IDENTITY, response);
|
||||
@@ -172,14 +172,14 @@ class OmnibusH2ServerTest {
|
||||
}
|
||||
|
||||
@CartesianTest
|
||||
void prefixBackend(
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean localChannel,
|
||||
@CartesianTest.Values(strings = {"/v1/prefix", "/v1/prefix/", "/v1/prefix/other"}) final String path) throws Exception {
|
||||
void pathBackend(
|
||||
@CartesianTest.Values(booleans = {false, true}) final boolean localChannel,
|
||||
@CartesianTest.Values(strings = {"/v1/path/", "/v1/path/?foo=bar", "/v1/path/?foo=bar&baz=quux"}) final String path) throws Exception {
|
||||
final OmnibusH2Server server = startOmnibusServer(
|
||||
Map.of(PREFIX, startBackendServer(localChannel, PREFIX_BACKEND_IDENTITY)),
|
||||
Map.of(PATH, startBackendServer(localChannel, PATH_BACKEND_IDENTITY)),
|
||||
startBackendServer(true, DEFAULT_BACKEND_IDENTITY));
|
||||
final String response = sendRequestThroughOmnibus(connectToOmnibus(server), path);
|
||||
assertEquals(PREFIX_BACKEND_IDENTITY, response);
|
||||
assertEquals(PATH_BACKEND_IDENTITY, response);
|
||||
}
|
||||
|
||||
@CartesianTest
|
||||
@@ -187,7 +187,7 @@ class OmnibusH2ServerTest {
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean defaultLocalChannel,
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean prefixLocalChannel) throws Exception {
|
||||
final OmnibusH2Server server = startOmnibusServer(
|
||||
Map.of(PREFIX, startBackendServer(prefixLocalChannel, PREFIX_BACKEND_IDENTITY)),
|
||||
Map.of(PATH, startBackendServer(prefixLocalChannel, PATH_BACKEND_IDENTITY)),
|
||||
startBackendServer(defaultLocalChannel, DEFAULT_BACKEND_IDENTITY));
|
||||
final Channel h2Connection = connectToOmnibus(server);
|
||||
final int numStreams = 10;
|
||||
@@ -198,14 +198,14 @@ class OmnibusH2ServerTest {
|
||||
.mapToObj(i -> CompletableFuture.supplyAsync(() ->
|
||||
sendRequestThroughOmnibus(
|
||||
h2Connection,
|
||||
i % 2 == 0 ? PREFIX : "/v1/other")))
|
||||
i % 2 == 0 ? PATH : "/v1/other")))
|
||||
.toArray(CompletableFuture[]::new);
|
||||
|
||||
// Ensure we get the response from the correct backend for each stream
|
||||
CompletableFuture.allOf(futures).join();
|
||||
for (int i = 0; i < numStreams; i++) {
|
||||
assertEquals(
|
||||
i % 2 == 0 ? PREFIX_BACKEND_IDENTITY : DEFAULT_BACKEND_IDENTITY,
|
||||
i % 2 == 0 ? PATH_BACKEND_IDENTITY : DEFAULT_BACKEND_IDENTITY,
|
||||
futures[i].resultNow());
|
||||
}
|
||||
}
|
||||
@@ -438,7 +438,7 @@ class OmnibusH2ServerTest {
|
||||
void loadShed() throws Exception {
|
||||
dynamicConfiguration.set(new DynamicOmnibusConfiguration(BigDecimal.ONE));
|
||||
final OmnibusH2Server server = startOmnibusServer(
|
||||
Map.of(PREFIX, startBackendServer(true, PREFIX_BACKEND_IDENTITY)),
|
||||
Map.of(PATH, startBackendServer(true, PATH_BACKEND_IDENTITY)),
|
||||
startBackendServer(true, DEFAULT_BACKEND_IDENTITY));
|
||||
|
||||
final CompletableFuture<Http2GoAwayFrame> goAwayFuture = new CompletableFuture<>();
|
||||
@@ -475,9 +475,6 @@ class OmnibusH2ServerTest {
|
||||
/// @param defaultBackend The target backend if no prefix routes match the request path
|
||||
/// @param timeout The omnibus idle timeout
|
||||
private OmnibusH2Server startOmnibusServer(final Map<String, Channel> routes, final Channel defaultBackend, final Duration timeout) throws Exception {
|
||||
// self-signed TLS context for the frontend loaded from test keyStore
|
||||
final InputStream keyStore = OmnibusH2ServerTest.class.getResourceAsStream("omnibus-h2-server-test-keystore.p12");
|
||||
|
||||
backendChannelsToShutDown.addAll(routes.values());
|
||||
backendChannelsToShutDown.add(defaultBackend);
|
||||
|
||||
@@ -486,8 +483,9 @@ class OmnibusH2ServerTest {
|
||||
nioEventLoopGroup,
|
||||
localEventLoopGroup,
|
||||
new InetSocketAddress("127.0.0.1", 0),
|
||||
new OmnibusRouter(
|
||||
routes.entrySet().stream().map(entry -> new OmnibusRouter.OmnibusRoute(entry.getKey(), entry.getValue().localAddress())).toList(),
|
||||
new OmnibusRouter(routes.entrySet().stream().collect(Collectors.toMap(
|
||||
Map.Entry::getKey,
|
||||
e -> e.getValue().localAddress())),
|
||||
defaultBackend.localAddress()),
|
||||
dynamicConfiguration::get,
|
||||
timeout);
|
||||
@@ -538,7 +536,7 @@ class OmnibusH2ServerTest {
|
||||
return startBackendServer(localChannel, identity, _ -> {}, _ -> {});
|
||||
}
|
||||
|
||||
/// Makes an H2 connection to the omnibus at [this#server] on which new H2 streams can be opened
|
||||
/// Makes an H2 connection to the omnibus at `server` on which new H2 streams can be opened
|
||||
private Channel connectToOmnibus(final OmnibusH2Server server, @Nullable final HAProxyMessage proxyHeader) {
|
||||
final SslContext clientSsl = sslContext();
|
||||
|
||||
|
||||
-103
@@ -1,103 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.mappers;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import io.dropwizard.jersey.errors.ErrorMessage;
|
||||
import io.dropwizard.testing.junit5.DropwizardExtensionsSupport;
|
||||
import io.dropwizard.testing.junit5.ResourceExtension;
|
||||
import io.grpc.Status;
|
||||
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.util.stream.Stream;
|
||||
import org.glassfish.jersey.server.ServerProperties;
|
||||
import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
|
||||
@ExtendWith(DropwizardExtensionsSupport.class)
|
||||
class GrpcStatusRuntimeExceptionMapperTest {
|
||||
|
||||
private static final GrpcStatusRuntimeExceptionMapper exceptionMapper = new GrpcStatusRuntimeExceptionMapper();
|
||||
private static final TestController testController = new TestController();
|
||||
|
||||
private static final ResourceExtension resources = ResourceExtension.builder()
|
||||
.addProperty(ServerProperties.UNWRAP_COMPLETION_STAGE_IN_WRITER_ENABLE, Boolean.TRUE)
|
||||
.addProvider(new CompletionExceptionMapper())
|
||||
.addProvider(exceptionMapper)
|
||||
.setTestContainerFactory(new GrizzlyWebTestContainerFactory())
|
||||
.addResource(testController)
|
||||
.build();
|
||||
|
||||
@BeforeEach
|
||||
public void setUp() {
|
||||
testController.exception = null;
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"json", "text"})
|
||||
public void responseBody(final String path) throws JsonProcessingException {
|
||||
testController.exception = Status.INVALID_ARGUMENT.withDescription("oofta").asRuntimeException();
|
||||
final Response response = resources.getJerseyTest().target("/v1/test/" + path).request().get();
|
||||
assertThat(response.getStatus()).isEqualTo(Response.Status.BAD_REQUEST.getStatusCode());
|
||||
final ErrorMessage body = SystemMapper.jsonMapper().readValue(
|
||||
response.readEntity(String.class),
|
||||
ErrorMessage.class);
|
||||
|
||||
assertThat(body.getMessage()).isEqualTo(testController.exception.getMessage());
|
||||
assertThat(body.getCode()).isEqualTo(Response.Status.BAD_REQUEST.getStatusCode());
|
||||
}
|
||||
|
||||
public static Stream<Arguments> errorMapping() {
|
||||
return Stream.of(
|
||||
Arguments.of(Status.INVALID_ARGUMENT, 400),
|
||||
Arguments.of(Status.NOT_FOUND, 404),
|
||||
Arguments.of(Status.UNAVAILABLE, 500));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
public void errorMapping(final Status status, final int expectedHttpCode) {
|
||||
testController.exception = status.asRuntimeException();
|
||||
final Response response = resources.getJerseyTest().target("/v1/test/json").request().get();
|
||||
assertThat(response.getStatus()).isEqualTo(expectedHttpCode);
|
||||
}
|
||||
|
||||
@Path("/v1/test")
|
||||
public static class TestController {
|
||||
|
||||
volatile RuntimeException exception = null;
|
||||
|
||||
@GET
|
||||
@Path("/text")
|
||||
public Response plaintext() {
|
||||
if (exception != null) {
|
||||
throw exception;
|
||||
}
|
||||
return Response.ok().build();
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/json")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public Response json() {
|
||||
if (exception != null) {
|
||||
throw exception;
|
||||
}
|
||||
return Response.ok().build();
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-2
@@ -173,10 +173,9 @@ public class AccountCreationDeletionIntegrationTest {
|
||||
phoneNumberRecoveryPasswordsManager,
|
||||
executor,
|
||||
executor,
|
||||
executor,
|
||||
CLOCK,
|
||||
"link-device-secret".getBytes(StandardCharsets.UTF_8),
|
||||
AccountsManager.TOTP_PARAMETERS.timeStep().dividedBy(2));
|
||||
AccountsManager.TOTP.getTimeStep().dividedBy(2));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
|
||||
+5
-21
@@ -15,17 +15,12 @@ import java.util.Collections;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class AccountLockManagerTest {
|
||||
|
||||
private AmazonDynamoDBLockClient lockClient;
|
||||
private ExecutorService executor;
|
||||
|
||||
private AccountLockManager accountLockManager;
|
||||
|
||||
@@ -36,22 +31,12 @@ class AccountLockManagerTest {
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
lockClient = mock(AmazonDynamoDBLockClient.class);
|
||||
executor = Executors.newSingleThreadExecutor();
|
||||
|
||||
accountLockManager = new AccountLockManager(lockClient);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() throws InterruptedException {
|
||||
executor.shutdown();
|
||||
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
executor.awaitTermination(1, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@Test
|
||||
void withLock() throws Exception {
|
||||
accountLockManager.withLock(Set.of(FIRST_PNI, SECOND_PNI), () -> null, executor);
|
||||
accountLockManager.withLock(Set.of(FIRST_PNI, SECOND_PNI), () -> null);
|
||||
|
||||
verify(lockClient, times(2)).acquireLock(any());
|
||||
verify(lockClient, times(2)).releaseLock(any(ReleaseLockOptions.class));
|
||||
@@ -61,7 +46,7 @@ class AccountLockManagerTest {
|
||||
void withLockTaskThrowsException() throws InterruptedException {
|
||||
assertThrows(RuntimeException.class, () -> accountLockManager.withLock(Set.of(FIRST_PNI, SECOND_PNI), () -> {
|
||||
throw new RuntimeException();
|
||||
}, executor));
|
||||
}));
|
||||
|
||||
verify(lockClient, times(2)).acquireLock(any());
|
||||
verify(lockClient, times(2)).releaseLock(any(ReleaseLockOptions.class));
|
||||
@@ -71,8 +56,7 @@ class AccountLockManagerTest {
|
||||
void withLockEmptyList() {
|
||||
final Runnable task = mock(Runnable.class);
|
||||
|
||||
assertThrows(IllegalArgumentException.class, () -> accountLockManager.withLock(Collections.emptySet(), () -> null,
|
||||
executor));
|
||||
assertThrows(IllegalArgumentException.class, () -> accountLockManager.withLock(Collections.emptySet(), () -> null));
|
||||
verify(task, never()).run();
|
||||
}
|
||||
|
||||
@@ -82,7 +66,7 @@ class AccountLockManagerTest {
|
||||
when(account.getAccountIdentifier()).thenReturn(ACI);
|
||||
when(account.getPhoneNumberIdentifier()).thenReturn(Optional.of(FIRST_PNI));
|
||||
|
||||
accountLockManager.withSingleAccountLock(account, () -> null, executor);
|
||||
accountLockManager.withSingleAccountLock(account, () -> null);
|
||||
verify(lockClient, times(1)).acquireLock(
|
||||
AcquireLockOptions.builder(FIRST_PNI.toString()).withAcquireReleasedLocksConsistently(true).build());
|
||||
}
|
||||
@@ -93,7 +77,7 @@ class AccountLockManagerTest {
|
||||
when(account.getAccountIdentifier()).thenReturn(ACI);
|
||||
when(account.getPhoneNumberIdentifier()).thenReturn(Optional.empty());
|
||||
|
||||
accountLockManager.withSingleAccountLock(account, () -> null, executor);
|
||||
accountLockManager.withSingleAccountLock(account, () -> null);
|
||||
verify(lockClient, times(1)).acquireLock(
|
||||
AcquireLockOptions.builder(ACI.toString()).withAcquireReleasedLocksConsistently(true).build());
|
||||
}
|
||||
|
||||
@@ -27,12 +27,17 @@ import java.util.Base64;
|
||||
import java.util.Collections;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.whispersystems.textsecuregcm.auth.StoredRegistrationLock;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AccountsHelper;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
import org.whispersystems.textsecuregcm.util.TestClock;
|
||||
@@ -104,6 +109,20 @@ class AccountTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSetRegistrationLockWithNoPhoneNumber() {
|
||||
final Account numberlessAccount =
|
||||
AccountsHelper.generateTestAccount(null, UUID.randomUUID(), null, List.of(recentPrimaryDevice), null);
|
||||
|
||||
assertThrows(IllegalArgumentException.class, () -> numberlessAccount.setRegistrationLock("hash", "salt"),
|
||||
"Accounts without phone numbers should never have a registration lock");
|
||||
|
||||
assertDoesNotThrow(() -> numberlessAccount.setRegistrationLock(null, null),
|
||||
"Clearing a registration lock an account never had should be a no-op");
|
||||
|
||||
assertEquals(StoredRegistrationLock.Status.ABSENT, numberlessAccount.getRegistrationLock().getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDiscoverableByPhoneNumber() {
|
||||
final Account account = AccountsHelper.generateTestAccount("+14152222222", UUID.randomUUID(), UUID.randomUUID(), List.of(recentPrimaryDevice),
|
||||
@@ -282,21 +301,52 @@ class AccountTest {
|
||||
assertThat(deserializedBase64Cpv.getCurrentProfileVersion()).isPresent().hasValue(version);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void getNextTotpKeyId(final List<Byte> existingKeyIds, final byte expectedNextKeyId) {
|
||||
final Account account = new Account();
|
||||
account.setMfaKeys(existingKeyIds.stream()
|
||||
.collect(Collectors.toMap(keyId -> keyId, _ -> new AnnotatedTotpKey(new TotpKey(
|
||||
new TotpParameters(
|
||||
TimeBasedOneTimePasswordGenerator.TOTP_ALGORITHM_HMAC_SHA256,
|
||||
HmacOneTimePasswordGenerator.DEFAULT_PASSWORD_LENGTH,
|
||||
TimeBasedOneTimePasswordGenerator.DEFAULT_TIME_STEP),
|
||||
TestRandomUtil.nextBytes(16)),
|
||||
TestRandomUtil.nextBytes(16)))));
|
||||
|
||||
assertEquals(expectedNextKeyId, account.getNextMfaKeyId());
|
||||
}
|
||||
|
||||
private static List<Arguments> getNextTotpKeyId() {
|
||||
final byte unclaimedId = 17;
|
||||
|
||||
final List<Byte> mostIdsTaken = IntStream.range(0, Account.MAX_MFA_KEY_ID)
|
||||
.filter(i -> i != unclaimedId)
|
||||
.mapToObj(i -> (byte) i)
|
||||
.toList();
|
||||
|
||||
return List.of(
|
||||
Arguments.argumentSet("No existing keys", List.of(), (byte) 0),
|
||||
Arguments.argumentSet("Single existing key", List.of((byte) 0), (byte) 1),
|
||||
Arguments.argumentSet("Multiple existing keys", List.of((byte) 0, (byte) 1), (byte) 2),
|
||||
Arguments.argumentSet("ID wraparound", List.of((byte) 0, (byte) 255), (byte) 1),
|
||||
Arguments.argumentSet("Most IDs taken", mostIdsTaken, unclaimedId)
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getNextTotpKeyId() {
|
||||
assertEquals(0, new Account().getNextTotpKeyId());
|
||||
void getNextTotpKeyNoneAvailable() {
|
||||
final Account account = new Account();
|
||||
account.setMfaKeys(IntStream.range(0, Account.MAX_MFA_KEY_ID + 1)
|
||||
.mapToObj(i -> (byte) i)
|
||||
.collect(Collectors.toMap(keyId -> keyId, _ -> new AnnotatedTotpKey(new TotpKey(
|
||||
new TotpParameters(
|
||||
TimeBasedOneTimePasswordGenerator.TOTP_ALGORITHM_HMAC_SHA1,
|
||||
HmacOneTimePasswordGenerator.DEFAULT_PASSWORD_LENGTH,
|
||||
TimeBasedOneTimePasswordGenerator.DEFAULT_TIME_STEP),
|
||||
TestRandomUtil.nextBytes(16)),
|
||||
TestRandomUtil.nextBytes(16)))));
|
||||
|
||||
final AnnotatedTotpKey totpKey = new AnnotatedTotpKey(new TotpKey(
|
||||
new TotpParameters(
|
||||
TimeBasedOneTimePasswordGenerator.TOTP_ALGORITHM_HMAC_SHA256,
|
||||
HmacOneTimePasswordGenerator.DEFAULT_PASSWORD_LENGTH,
|
||||
TimeBasedOneTimePasswordGenerator.DEFAULT_TIME_STEP),
|
||||
TestRandomUtil.nextBytes(16)),
|
||||
TestRandomUtil.nextBytes(16));
|
||||
|
||||
final Account accountWithTotpKey = new Account();
|
||||
accountWithTotpKey.setTotpKeys(Map.of(0, totpKey));
|
||||
|
||||
assertEquals(1, accountWithTotpKey.getNextTotpKeyId());
|
||||
assertThrows(IllegalStateException.class, account::getNextMfaKeyId);
|
||||
}
|
||||
}
|
||||
+1
-2
@@ -153,10 +153,9 @@ class AccountsManagerChangeNumberIntegrationTest {
|
||||
phoneNumberRecoveryPasswordsManager,
|
||||
executor,
|
||||
executor,
|
||||
executor,
|
||||
mock(Clock.class),
|
||||
"link-device-secret".getBytes(StandardCharsets.UTF_8),
|
||||
AccountsManager.TOTP_PARAMETERS.timeStep().dividedBy(2));
|
||||
AccountsManager.TOTP.getTimeStep().dividedBy(2));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+2
-3
@@ -105,7 +105,7 @@ class AccountsManagerConcurrentModificationIntegrationTest {
|
||||
doAnswer(invocation -> {
|
||||
final ThrowingSupplier<?, ?> task = invocation.getArgument(1);
|
||||
return task.get();
|
||||
}).when(accountLockManager).withLock(anySet(), any(), any());
|
||||
}).when(accountLockManager).withLock(anySet(), any());
|
||||
|
||||
final PhoneNumberIdentifiers phoneNumberIdentifiers = mock(PhoneNumberIdentifiers.class);
|
||||
when(phoneNumberIdentifiers.getPhoneNumberIdentifier(anyString()))
|
||||
@@ -132,12 +132,11 @@ class AccountsManagerConcurrentModificationIntegrationTest {
|
||||
mock(SecureValueRecoveryClient.class),
|
||||
mock(DisconnectionRequestManager.class),
|
||||
phoneNumberRecoveryPasswordsManager,
|
||||
mock(Executor.class),
|
||||
mock(ScheduledExecutorService.class),
|
||||
mock(ScheduledExecutorService.class),
|
||||
mock(Clock.class),
|
||||
"link-device-secret".getBytes(StandardCharsets.UTF_8),
|
||||
AccountsManager.TOTP_PARAMETERS.timeStep().dividedBy(2)
|
||||
AccountsManager.TOTP.getTimeStep().dividedBy(2)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
+1
-3
@@ -18,7 +18,6 @@ import java.util.Base64;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import org.apache.commons.lang3.RandomStringUtils;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
@@ -68,12 +67,11 @@ public class AccountsManagerDeviceTransferIntegrationTest {
|
||||
mock(SecureValueRecoveryClient.class),
|
||||
mock(DisconnectionRequestManager.class),
|
||||
mock(PhoneNumberRecoveryPasswordsManager.class),
|
||||
mock(ExecutorService.class),
|
||||
mock(ScheduledExecutorService.class),
|
||||
mock(ScheduledExecutorService.class),
|
||||
Clock.systemUTC(),
|
||||
"link-device-secret".getBytes(StandardCharsets.UTF_8),
|
||||
AccountsManager.TOTP_PARAMETERS.timeStep().dividedBy(2));
|
||||
AccountsManager.TOTP.getTimeStep().dividedBy(2));
|
||||
|
||||
accountsManager.start();
|
||||
}
|
||||
|
||||
+1
-2
@@ -139,10 +139,9 @@ public class AccountsManagerMigrateRecoveryPasswordIntegrationTest {
|
||||
phoneNumberRecoveryPasswordsManager,
|
||||
executor,
|
||||
executor,
|
||||
executor,
|
||||
mock(Clock.class),
|
||||
"link-device-secret".getBytes(StandardCharsets.UTF_8),
|
||||
AccountsManager.TOTP_PARAMETERS.timeStep().dividedBy(2));
|
||||
AccountsManager.TOTP.getTimeStep().dividedBy(2));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+90
-83
@@ -33,7 +33,6 @@ import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.verifyNoMoreInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.eatthepath.otp.TimeBasedOneTimePasswordGenerator;
|
||||
import com.google.i18n.phonenumbers.PhoneNumberUtil;
|
||||
import io.lettuce.core.RedisException;
|
||||
import io.lettuce.core.api.async.RedisAsyncCommands;
|
||||
@@ -59,7 +58,6 @@ import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import java.util.function.Consumer;
|
||||
@@ -127,7 +125,11 @@ class AccountsManagerTest {
|
||||
|
||||
private static final byte[] LINK_DEVICE_SECRET = "link-device-secret".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
private static final Duration MAX_TOTP_VALIDATION_DELAY = AccountsManager.TOTP_PARAMETERS.timeStep().dividedBy(2);
|
||||
private static final Duration MAX_TOTP_VALIDATION_DELAY = AccountsManager.TOTP.getTimeStep().dividedBy(2);
|
||||
|
||||
private static final TotpParameters TOTP_PARAMETERS = new TotpParameters(AccountsManager.TOTP.getAlgorithm(),
|
||||
AccountsManager.TOTP.getPasswordLength(),
|
||||
AccountsManager.TOTP.getTimeStep());
|
||||
|
||||
private static TestClock CLOCK;
|
||||
|
||||
@@ -207,12 +209,12 @@ class AccountsManagerTest {
|
||||
doAnswer(invocation -> {
|
||||
final ThrowingSupplier<?, ?> task = invocation.getArgument(1);
|
||||
return task.get();
|
||||
}).when(accountLockManager).withLock(anySet(), any(), any());
|
||||
}).when(accountLockManager).withLock(anySet(), any());
|
||||
|
||||
doAnswer(invocation -> {
|
||||
final ThrowingSupplier<?, ?> task = invocation.getArgument(1);
|
||||
return task.get();
|
||||
}).when(accountLockManager).withSingleAccountLock(any(Account.class), any(), any());
|
||||
}).when(accountLockManager).withSingleAccountLock(any(Account.class), any());
|
||||
|
||||
final PhoneNumberRecoveryPasswordsManager phoneNumberRecoveryPasswordsManager =
|
||||
mock(PhoneNumberRecoveryPasswordsManager.class);
|
||||
@@ -248,7 +250,6 @@ class AccountsManagerTest {
|
||||
svr2Client,
|
||||
disconnectionRequestManager,
|
||||
phoneNumberRecoveryPasswordsManager,
|
||||
mock(Executor.class),
|
||||
mock(ScheduledExecutorService.class),
|
||||
mock(ScheduledExecutorService.class),
|
||||
CLOCK,
|
||||
@@ -1296,7 +1297,6 @@ class AccountsManagerTest {
|
||||
verify(accounts, expectUpdate ? times(1) : never()).update(account);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
private static Stream<Arguments> testUpdateDeviceLastSeen() {
|
||||
return Stream.of(
|
||||
Arguments.of(true, 1, 2),
|
||||
@@ -1934,7 +1934,7 @@ class AccountsManagerTest {
|
||||
class Totp {
|
||||
|
||||
@Test
|
||||
void generatePendingTotpKey() throws TooManyTotpKeysException {
|
||||
void generatePendingTotpKey() throws TooManyTotpKeysException, TooManyMfaKeysException {
|
||||
final UUID accountIdentifier = UUID.randomUUID();
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
@@ -1955,10 +1955,10 @@ class AccountsManagerTest {
|
||||
final Account account = mock(Account.class);
|
||||
when(account.getAccountIdentifier()).thenReturn(accountIdentifier);
|
||||
|
||||
when(account.getTotpKeys()).thenReturn(IntStream.range(0, AccountsManager.MAX_TOTP_KEYS)
|
||||
when(account.getMfaKeys()).thenReturn(IntStream.range(0, AccountsManager.MAX_TOTP_KEYS)
|
||||
.boxed()
|
||||
.collect(Collectors.toMap(keyId -> keyId, _ -> new AnnotatedTotpKey(
|
||||
new TotpKey(AccountsManager.TOTP_PARAMETERS, TestRandomUtil.nextBytes(16)),
|
||||
.collect(Collectors.toMap(Integer::byteValue, _ -> new AnnotatedTotpKey(
|
||||
new TotpKey(TOTP_PARAMETERS, TestRandomUtil.nextBytes(16)),
|
||||
TestRandomUtil.nextBytes(16)))));
|
||||
|
||||
when(accounts.getByAccountIdentifier(accountIdentifier))
|
||||
@@ -1969,7 +1969,7 @@ class AccountsManagerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void confirmPendingTotpKey() throws InvalidKeyException, TooManyTotpKeysException, NoSuchAlgorithmException {
|
||||
void confirmPendingTotpKey() throws InvalidKeyException, TooManyTotpKeysException, TooManyMfaKeysException, NoSuchAlgorithmException {
|
||||
final UUID accountIdentifier = UUID.randomUUID();
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
@@ -1979,20 +1979,15 @@ class AccountsManagerTest {
|
||||
.thenReturn(Optional.of(account));
|
||||
|
||||
final TotpKey pendingTotpKey = accountsManager.generatePendingTotpKey(accountIdentifier);
|
||||
final int nextTotpKeyId = ThreadLocalRandom.current().nextInt();
|
||||
final byte nextTotpKeyId = (byte) ThreadLocalRandom.current().nextInt();
|
||||
|
||||
when(account.getPendingTotpKey()).thenReturn(Optional.of(pendingTotpKey));
|
||||
when(account.getNextTotpKeyId()).thenReturn(nextTotpKeyId);
|
||||
|
||||
final TimeBasedOneTimePasswordGenerator totpGenerator =
|
||||
new TimeBasedOneTimePasswordGenerator(AccountsManager.TOTP_PARAMETERS.timeStep(),
|
||||
AccountsManager.TOTP_PARAMETERS.passwordLength(),
|
||||
AccountsManager.TOTP_PARAMETERS.algorithm());
|
||||
when(account.getNextMfaKeyId()).thenReturn(nextTotpKeyId);
|
||||
|
||||
final Instant timestamp = Instant.now();
|
||||
|
||||
assertEquals(Optional.of(nextTotpKeyId), accountsManager.confirmPendingTotpKey(accountIdentifier,
|
||||
totpGenerator.generateOneTimePassword(pendingTotpKey, timestamp),
|
||||
AccountsManager.TOTP.generateOneTimePassword(pendingTotpKey, timestamp),
|
||||
timestamp,
|
||||
TestRandomUtil.nextBytes(16)));
|
||||
|
||||
@@ -2000,7 +1995,42 @@ class AccountsManagerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void confirmPendingTotpKeyPreviouslyConfirmed() throws InvalidKeyException, NoSuchAlgorithmException {
|
||||
void confirmPendingTotpKeyWithDelay() throws InvalidKeyException, TooManyTotpKeysException, TooManyMfaKeysException, NoSuchAlgorithmException {
|
||||
final UUID accountIdentifier = UUID.randomUUID();
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
when(account.getAccountIdentifier()).thenReturn(accountIdentifier);
|
||||
|
||||
when(accounts.getByAccountIdentifier(accountIdentifier))
|
||||
.thenReturn(Optional.of(account));
|
||||
|
||||
final TotpKey pendingTotpKey = accountsManager.generatePendingTotpKey(accountIdentifier);
|
||||
final byte nextTotpKeyId = (byte) ThreadLocalRandom.current().nextInt();
|
||||
|
||||
when(account.getPendingTotpKey()).thenReturn(Optional.of(pendingTotpKey));
|
||||
when(account.getNextMfaKeyId()).thenReturn(nextTotpKeyId);
|
||||
|
||||
final Instant beginningOfTotpWindow = totpWindowStart(Instant.now());
|
||||
final int oneTimePassword = AccountsManager.TOTP.generateOneTimePassword(pendingTotpKey, beginningOfTotpWindow);
|
||||
|
||||
// Should be rejected since even after delay allowance, our otp is from the previous window
|
||||
assertEquals(Optional.empty(), accountsManager.confirmPendingTotpKey(accountIdentifier,
|
||||
oneTimePassword,
|
||||
beginningOfTotpWindow.plus(AccountsManager.TOTP.getTimeStep()).plus(MAX_TOTP_VALIDATION_DELAY),
|
||||
TestRandomUtil.nextBytes(16)));
|
||||
|
||||
// Should still be accepted as MAX_TOTP_VALIDATION_DELAY delay brings us to the otp's window
|
||||
assertEquals(Optional.of(nextTotpKeyId), accountsManager.confirmPendingTotpKey(accountIdentifier,
|
||||
oneTimePassword,
|
||||
beginningOfTotpWindow.plus(AccountsManager.TOTP.getTimeStep())
|
||||
.plus(MAX_TOTP_VALIDATION_DELAY)
|
||||
.minus(Duration.ofMillis(1)),
|
||||
TestRandomUtil.nextBytes(16)));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
void confirmPendingTotpKeyPreviouslyConfirmed() throws InvalidKeyException, NoSuchAlgorithmException, TooManyMfaKeysException {
|
||||
final UUID accountIdentifier = UUID.randomUUID();
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
@@ -2011,36 +2041,31 @@ class AccountsManagerTest {
|
||||
|
||||
final AnnotatedTotpKey confirmedTotpKey;
|
||||
{
|
||||
final KeyGenerator totpKeyGenerator = KeyGenerator.getInstance(AccountsManager.TOTP_PARAMETERS.algorithm());
|
||||
totpKeyGenerator.init(AccountsManager.TOTP_KEY_LENGTH_BITS);
|
||||
final KeyGenerator totpKeyGenerator = KeyGenerator.getInstance(AccountsManager.TOTP.getAlgorithm());
|
||||
totpKeyGenerator.init(AccountsManager.getTotpKeyLengthBits());
|
||||
|
||||
confirmedTotpKey = new AnnotatedTotpKey(
|
||||
new TotpKey(AccountsManager.TOTP_PARAMETERS, totpKeyGenerator.generateKey().getEncoded()),
|
||||
new TotpKey(TOTP_PARAMETERS, totpKeyGenerator.generateKey().getEncoded()),
|
||||
TestRandomUtil.nextBytes(16));
|
||||
}
|
||||
|
||||
final int keyId = 17;
|
||||
final byte keyId = 17;
|
||||
|
||||
when(account.getPendingTotpKey()).thenReturn(Optional.empty());
|
||||
when(account.getTotpKeys()).thenReturn(Map.of(
|
||||
keyId - 1, confirmedTotpKey,
|
||||
when(account.getMfaKeys()).thenReturn(Map.of(
|
||||
(byte) (keyId - 1), confirmedTotpKey,
|
||||
keyId, confirmedTotpKey));
|
||||
|
||||
final TimeBasedOneTimePasswordGenerator totpGenerator =
|
||||
new TimeBasedOneTimePasswordGenerator(AccountsManager.TOTP_PARAMETERS.timeStep(),
|
||||
AccountsManager.TOTP_PARAMETERS.passwordLength(),
|
||||
AccountsManager.TOTP_PARAMETERS.algorithm());
|
||||
|
||||
final Instant timestamp = Instant.now();
|
||||
|
||||
assertEquals(Optional.of(keyId), accountsManager.confirmPendingTotpKey(accountIdentifier,
|
||||
totpGenerator.generateOneTimePassword(confirmedTotpKey, timestamp),
|
||||
AccountsManager.TOTP.generateOneTimePassword(confirmedTotpKey, timestamp),
|
||||
timestamp,
|
||||
TestRandomUtil.nextBytes(16)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void confirmPendingTotpKeyNoKeys() throws InvalidKeyException, TooManyTotpKeysException, NoSuchAlgorithmException {
|
||||
void confirmPendingTotpKeyNoKeys() throws InvalidKeyException, TooManyTotpKeysException, TooManyMfaKeysException, NoSuchAlgorithmException {
|
||||
final UUID accountIdentifier = UUID.randomUUID();
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
@@ -2052,24 +2077,19 @@ class AccountsManagerTest {
|
||||
final TotpKey pendingTotpKey = accountsManager.generatePendingTotpKey(accountIdentifier);
|
||||
|
||||
when(account.getPendingTotpKey()).thenReturn(Optional.empty());
|
||||
when(account.getTotpKeys()).thenReturn(Collections.emptyMap());
|
||||
|
||||
final TimeBasedOneTimePasswordGenerator totpGenerator =
|
||||
new TimeBasedOneTimePasswordGenerator(AccountsManager.TOTP_PARAMETERS.timeStep(),
|
||||
AccountsManager.TOTP_PARAMETERS.passwordLength(),
|
||||
AccountsManager.TOTP_PARAMETERS.algorithm());
|
||||
when(account.getMfaKeys()).thenReturn(Collections.emptyMap());
|
||||
|
||||
final Instant timestamp = Instant.now();
|
||||
|
||||
assertEquals(Optional.empty(), accountsManager.confirmPendingTotpKey(accountIdentifier,
|
||||
totpGenerator.generateOneTimePassword(pendingTotpKey, timestamp),
|
||||
AccountsManager.TOTP.generateOneTimePassword(pendingTotpKey, timestamp),
|
||||
timestamp,
|
||||
TestRandomUtil.nextBytes(16)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void confirmPendingTotpKeyIncorrectPassword()
|
||||
throws InvalidKeyException, TooManyTotpKeysException, NoSuchAlgorithmException {
|
||||
throws InvalidKeyException, TooManyTotpKeysException, TooManyMfaKeysException, NoSuchAlgorithmException {
|
||||
final UUID accountIdentifier = UUID.randomUUID();
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
@@ -2079,18 +2099,13 @@ class AccountsManagerTest {
|
||||
.thenReturn(Optional.of(account));
|
||||
|
||||
final TotpKey pendingTotpKey = accountsManager.generatePendingTotpKey(accountIdentifier);
|
||||
final int nextTotpKeyId = ThreadLocalRandom.current().nextInt();
|
||||
final byte nextTotpKeyId = (byte) ThreadLocalRandom.current().nextInt();
|
||||
|
||||
when(account.getPendingTotpKey()).thenReturn(Optional.of(pendingTotpKey));
|
||||
when(account.getNextTotpKeyId()).thenReturn(nextTotpKeyId);
|
||||
|
||||
final TimeBasedOneTimePasswordGenerator totpGenerator =
|
||||
new TimeBasedOneTimePasswordGenerator(AccountsManager.TOTP_PARAMETERS.timeStep(),
|
||||
AccountsManager.TOTP_PARAMETERS.passwordLength(),
|
||||
AccountsManager.TOTP_PARAMETERS.algorithm());
|
||||
when(account.getNextMfaKeyId()).thenReturn(nextTotpKeyId);
|
||||
|
||||
final Instant timestamp = Instant.now();
|
||||
final int incorrectPassword = totpGenerator.generateOneTimePassword(pendingTotpKey, timestamp) + 1;
|
||||
final int incorrectPassword = AccountsManager.TOTP.generateOneTimePassword(pendingTotpKey, timestamp) + 1;
|
||||
|
||||
assertEquals(Optional.empty(), accountsManager.confirmPendingTotpKey(accountIdentifier,
|
||||
incorrectPassword,
|
||||
@@ -2103,13 +2118,13 @@ class AccountsManagerTest {
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void verifyTotp(final Map<Integer, AnnotatedTotpKey> totpKeys,
|
||||
void verifyTotp(final Map<Byte, AnnotatedMfaKey> mfaKeys,
|
||||
final Instant timestamp,
|
||||
@Nullable final Integer oneTimePassword,
|
||||
final boolean expectVerified) {
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
when(account.getTotpKeys()).thenReturn(totpKeys);
|
||||
when(account.getMfaKeys()).thenReturn(mfaKeys);
|
||||
|
||||
assertEquals(expectVerified, accountsManager.verifyTotp(account, timestamp, oneTimePassword));
|
||||
}
|
||||
@@ -2120,23 +2135,18 @@ class AccountsManagerTest {
|
||||
final AnnotatedTotpKey totpKey;
|
||||
final AnnotatedTotpKey secondTotpKey;
|
||||
{
|
||||
final KeyGenerator totpKeyGenerator = KeyGenerator.getInstance(AccountsManager.TOTP_PARAMETERS.algorithm());
|
||||
totpKeyGenerator.init(AccountsManager.TOTP_KEY_LENGTH_BITS);
|
||||
final KeyGenerator totpKeyGenerator = KeyGenerator.getInstance(AccountsManager.TOTP.getAlgorithm());
|
||||
totpKeyGenerator.init(AccountsManager.getTotpKeyLengthBits());
|
||||
|
||||
totpKey = new AnnotatedTotpKey(
|
||||
new TotpKey(AccountsManager.TOTP_PARAMETERS, totpKeyGenerator.generateKey().getEncoded()),
|
||||
new TotpKey(TOTP_PARAMETERS, totpKeyGenerator.generateKey().getEncoded()),
|
||||
TestRandomUtil.nextBytes(16));
|
||||
|
||||
secondTotpKey = new AnnotatedTotpKey(
|
||||
new TotpKey(AccountsManager.TOTP_PARAMETERS, totpKeyGenerator.generateKey().getEncoded()),
|
||||
new TotpKey(TOTP_PARAMETERS, totpKeyGenerator.generateKey().getEncoded()),
|
||||
TestRandomUtil.nextBytes(16));
|
||||
}
|
||||
|
||||
final TimeBasedOneTimePasswordGenerator totpGenerator =
|
||||
new TimeBasedOneTimePasswordGenerator(AccountsManager.TOTP_PARAMETERS.timeStep(),
|
||||
AccountsManager.TOTP_PARAMETERS.passwordLength(),
|
||||
AccountsManager.TOTP_PARAMETERS.algorithm());
|
||||
|
||||
return List.of(
|
||||
Arguments.argumentSet("No keys, no password provided",
|
||||
Collections.emptyMap(), timestamp, null, true),
|
||||
@@ -2145,57 +2155,54 @@ class AccountsManagerTest {
|
||||
Collections.emptyMap(), timestamp, 123456, false),
|
||||
|
||||
Arguments.argumentSet("Has key, correct password provided",
|
||||
Map.of(1, totpKey), timestamp, totpGenerator.generateOneTimePassword(totpKey, timestamp), true),
|
||||
Map.of((byte) 1, totpKey), timestamp, AccountsManager.TOTP.generateOneTimePassword(totpKey, timestamp), true),
|
||||
|
||||
Arguments.argumentSet("Has key, incorrect password provided",
|
||||
Map.of(1, totpKey), timestamp, totpGenerator.generateOneTimePassword(totpKey, timestamp) + 1, false),
|
||||
Map.of((byte) 1, totpKey), timestamp, AccountsManager.TOTP.generateOneTimePassword(totpKey, timestamp) + 1, false),
|
||||
|
||||
Arguments.argumentSet("Has key, no password provided",
|
||||
Map.of(1, totpKey), timestamp, null, false),
|
||||
Map.of((byte) 1, totpKey), timestamp, null, false),
|
||||
|
||||
Arguments.argumentSet("Has multiple keys, correct password provided for one key",
|
||||
Map.of(1, totpKey, 2, secondTotpKey), timestamp, totpGenerator.generateOneTimePassword(totpKey, timestamp), true)
|
||||
Map.of((byte) 1, totpKey, (byte) 2, secondTotpKey), timestamp, AccountsManager.TOTP.generateOneTimePassword(totpKey, timestamp), true)
|
||||
);
|
||||
}
|
||||
|
||||
@RepeatedTest(value = 10, failureThreshold = 2)
|
||||
void verifyTotpWithDelay() throws NoSuchAlgorithmException, InvalidKeyException {
|
||||
void verifyTotpWithDelay() throws NoSuchAlgorithmException, InvalidKeyException, TooManyMfaKeysException {
|
||||
final AnnotatedTotpKey totpKey;
|
||||
{
|
||||
final KeyGenerator totpKeyGenerator = KeyGenerator.getInstance(AccountsManager.TOTP_PARAMETERS.algorithm());
|
||||
totpKeyGenerator.init(AccountsManager.TOTP_KEY_LENGTH_BITS);
|
||||
final KeyGenerator totpKeyGenerator = KeyGenerator.getInstance(AccountsManager.TOTP.getAlgorithm());
|
||||
totpKeyGenerator.init(AccountsManager.getTotpKeyLengthBits());
|
||||
|
||||
totpKey = new AnnotatedTotpKey(
|
||||
new TotpKey(AccountsManager.TOTP_PARAMETERS, totpKeyGenerator.generateKey().getEncoded()),
|
||||
new TotpKey(TOTP_PARAMETERS, totpKeyGenerator.generateKey().getEncoded()),
|
||||
TestRandomUtil.nextBytes(16));
|
||||
}
|
||||
|
||||
final TimeBasedOneTimePasswordGenerator totpGenerator =
|
||||
new TimeBasedOneTimePasswordGenerator(AccountsManager.TOTP_PARAMETERS.timeStep(),
|
||||
AccountsManager.TOTP_PARAMETERS.passwordLength(),
|
||||
AccountsManager.TOTP_PARAMETERS.algorithm());
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
when(account.getTotpKeys()).thenReturn(Map.of(1, totpKey));
|
||||
when(account.getMfaKeys()).thenReturn(Map.of((byte) 1, totpKey));
|
||||
|
||||
final Instant beginningOfTotpWindow =
|
||||
Instant.ofEpochMilli((Instant.now().toEpochMilli() / AccountsManager.TOTP_PARAMETERS.timeStep().toMillis()) *
|
||||
AccountsManager.TOTP_PARAMETERS.timeStep().toMillis());
|
||||
|
||||
final int oneTimePassword = totpGenerator.generateOneTimePassword(totpKey, beginningOfTotpWindow);
|
||||
final Instant beginningOfTotpWindow = totpWindowStart(Instant.now());
|
||||
final int oneTimePassword = AccountsManager.TOTP.generateOneTimePassword(totpKey, beginningOfTotpWindow);
|
||||
|
||||
assertTrue(accountsManager.verifyTotp(account, beginningOfTotpWindow, oneTimePassword),
|
||||
"One-time password should be valid at the start of the window in which it was generated");
|
||||
|
||||
assertTrue(accountsManager.verifyTotp(account, beginningOfTotpWindow.plus(AccountsManager.TOTP_PARAMETERS.timeStep()), oneTimePassword),
|
||||
assertTrue(accountsManager.verifyTotp(account, beginningOfTotpWindow.plus(AccountsManager.TOTP.getTimeStep()), oneTimePassword),
|
||||
"One-time password should be valid at the start of the window after which it was generated");
|
||||
|
||||
assertTrue(accountsManager.verifyTotp(account, beginningOfTotpWindow.plus(AccountsManager.TOTP_PARAMETERS.timeStep()).plus(MAX_TOTP_VALIDATION_DELAY).minusMillis(1), oneTimePassword),
|
||||
assertTrue(accountsManager.verifyTotp(account, beginningOfTotpWindow.plus(AccountsManager.TOTP.getTimeStep()).plus(MAX_TOTP_VALIDATION_DELAY).minusMillis(1), oneTimePassword),
|
||||
"One-time password should be valid up until max delay after end of current TOTP window");
|
||||
|
||||
// With six-digit OTPs, there's a one-in-a-million chance of this returning a false positive, and so we repeat the
|
||||
// test several allowing for failure
|
||||
assertFalse(accountsManager.verifyTotp(account, beginningOfTotpWindow.plus(AccountsManager.TOTP_PARAMETERS.timeStep()).plus(MAX_TOTP_VALIDATION_DELAY), oneTimePassword),
|
||||
assertFalse(accountsManager.verifyTotp(account, beginningOfTotpWindow.plus(AccountsManager.TOTP.getTimeStep()).plus(MAX_TOTP_VALIDATION_DELAY), oneTimePassword),
|
||||
"One-time password should not be valid after max delay past end of current TOTP window");
|
||||
}
|
||||
|
||||
private static Instant totpWindowStart(final Instant instant) {
|
||||
return Instant.ofEpochMilli((instant.toEpochMilli() / AccountsManager.TOTP.getTimeStep().toMillis()) *
|
||||
AccountsManager.TOTP.getTimeStep().toMillis());
|
||||
}
|
||||
}
|
||||
+2
-3
@@ -119,7 +119,7 @@ class AccountsManagerUsernameIntegrationTest {
|
||||
doAnswer(invocation -> {
|
||||
final ThrowingSupplier<?, ?> task = invocation.getArgument(1);
|
||||
return task.get();
|
||||
}).when(accountLockManager).withLock(anySet(), any(), any());
|
||||
}).when(accountLockManager).withLock(anySet(), any());
|
||||
|
||||
final PhoneNumberIdentifiers phoneNumberIdentifiers =
|
||||
new PhoneNumberIdentifiers(DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(), Tables.PNI.tableName());
|
||||
@@ -153,12 +153,11 @@ class AccountsManagerUsernameIntegrationTest {
|
||||
mock(SecureValueRecoveryClient.class),
|
||||
disconnectionRequestManager,
|
||||
phoneNumberRecoveryPasswordsManager,
|
||||
Executors.newSingleThreadExecutor(),
|
||||
Executors.newSingleThreadScheduledExecutor(),
|
||||
Executors.newSingleThreadScheduledExecutor(),
|
||||
Clock.systemUTC(),
|
||||
"link-device-secret".getBytes(StandardCharsets.UTF_8),
|
||||
AccountsManager.TOTP_PARAMETERS.timeStep().dividedBy(2));
|
||||
AccountsManager.TOTP.getTimeStep().dividedBy(2));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -23,6 +23,8 @@ import static org.mockito.Mockito.when;
|
||||
import static org.whispersystems.textsecuregcm.storage.ReceiptCredentialTestUtil.receiptPresentation;
|
||||
import static org.whispersystems.textsecuregcm.util.CompletableFutureTestUtil.assertFailsWithCause;
|
||||
|
||||
import com.eatthepath.otp.HmacOneTimePasswordGenerator;
|
||||
import com.eatthepath.otp.TimeBasedOneTimePasswordGenerator;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.google.i18n.phonenumbers.PhoneNumberUtil;
|
||||
import jakarta.annotation.Nullable;
|
||||
@@ -112,7 +114,6 @@ class AccountsTest {
|
||||
|
||||
private static final AtomicInteger ACCOUNT_COUNTER = new AtomicInteger(1);
|
||||
|
||||
|
||||
@RegisterExtension
|
||||
static final DynamoDbExtension DYNAMO_DB_EXTENSION = new DynamoDbExtension(
|
||||
Tables.ACCOUNTS,
|
||||
@@ -480,7 +481,6 @@ class AccountsTest {
|
||||
assertThat(account.getReservedUsernameHash()).isEmpty();
|
||||
}
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
static ArgumentSets reclaimAccountWithNoUsername() {
|
||||
return ArgumentSets.argumentsForFirstParameter(UsernameStatus.values())
|
||||
// number
|
||||
@@ -556,6 +556,79 @@ class AccountsTest {
|
||||
assertThat(reclaimed.getZkCredentialKey()).hasValue(existingAccount.getZkCredentialKey().orElseThrow());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testIdempotentCreationWithMfaFails() throws Exception {
|
||||
final UUID existingUuid = UUID.randomUUID();
|
||||
final byte[] accountRecoveryPassword = TestRandomUtil.nextBytes(16);
|
||||
final Account existingAccount =
|
||||
generateAccount(null, existingUuid, null, List.of(generateDevice(DEVICE_ID_1)), accountRecoveryPassword);
|
||||
|
||||
existingAccount.setMfaKeys(Map.of((byte) 1, new AnnotatedTotpKey(new TotpKey(
|
||||
new TotpParameters(
|
||||
TimeBasedOneTimePasswordGenerator.TOTP_ALGORITHM_HMAC_SHA1,
|
||||
HmacOneTimePasswordGenerator.DEFAULT_PASSWORD_LENGTH,
|
||||
TimeBasedOneTimePasswordGenerator.DEFAULT_TIME_STEP),
|
||||
TestRandomUtil.nextBytes(16)),
|
||||
TestRandomUtil.nextBytes(16))));
|
||||
|
||||
final ReceiptCredentialPresentation receiptCredentialPresentation = receiptPresentation();
|
||||
createNumberlessAccount(existingAccount, receiptCredentialPresentation, accountRecoveryPassword);
|
||||
|
||||
final Account secondAccount =
|
||||
generateAccount(null, UUID.randomUUID(), null, List.of(generateDevice(DEVICE_ID_1)), accountRecoveryPassword);
|
||||
assertThrows(ReceiptAlreadyRedeemedException.class,
|
||||
() -> accounts.create(secondAccount, receiptCredentialPresentation, accountRecoveryPassword,
|
||||
Collections.emptyList()));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"+14151112222"})
|
||||
@NullSource
|
||||
void testReclaimAccountPreservesTotpKeys(@Nullable final String number) throws Exception {
|
||||
final UUID existingUuid = UUID.randomUUID();
|
||||
final byte[] accountRecoveryPassword = TestRandomUtil.nextBytes(16);
|
||||
final Account existingAccount =
|
||||
generateAccount(number, existingUuid, number == null ? null : UUID.randomUUID(),
|
||||
List.of(generateDevice(DEVICE_ID_1)), accountRecoveryPassword);
|
||||
|
||||
existingAccount.setMfaKeys(Map.of((byte) 1, new AnnotatedTotpKey(new TotpKey(
|
||||
new TotpParameters(
|
||||
TimeBasedOneTimePasswordGenerator.TOTP_ALGORITHM_HMAC_SHA1,
|
||||
HmacOneTimePasswordGenerator.DEFAULT_PASSWORD_LENGTH,
|
||||
TimeBasedOneTimePasswordGenerator.DEFAULT_TIME_STEP),
|
||||
TestRandomUtil.nextBytes(16)),
|
||||
TestRandomUtil.nextBytes(16))));
|
||||
|
||||
final ReceiptCredentialPresentation receiptCredentialPresentation = receiptPresentation();
|
||||
if (number != null) {
|
||||
createAccount(existingAccount);
|
||||
} else {
|
||||
createNumberlessAccount(existingAccount, receiptCredentialPresentation, accountRecoveryPassword);
|
||||
}
|
||||
|
||||
final Account secondAccount =
|
||||
generateAccount(number, UUID.randomUUID(), number == null ? null : UUID.randomUUID(),
|
||||
List.of(generateDevice(DEVICE_ID_1)), accountRecoveryPassword);
|
||||
|
||||
if (number != null) {
|
||||
reclaimAccount(secondAccount);
|
||||
} else {
|
||||
// There are essentially two modes of 'reclamation' for a numberless account:
|
||||
// - Try to create an account and then reclaim it on conflict to allow for idempotent retries of creation
|
||||
// - Explicitly recover the account, since we know from the API if the client is trying to recover
|
||||
// Only the second case works here, because we forbid idempotent retries if the account has already set an
|
||||
// MFA key.
|
||||
secondAccount.setAccountIdentifier(existingAccount.getAccountIdentifier());
|
||||
accounts.reclaimAccount(existingAccount,
|
||||
secondAccount,
|
||||
Collections.emptyList()).toCompletableFuture().join();
|
||||
}
|
||||
|
||||
final Account reclaimed = accounts.getByAccountIdentifier(existingUuid).orElseThrow();
|
||||
|
||||
assertThat(reclaimed.getMfaKeys()).isEqualTo(existingAccount.getMfaKeys());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"+14151112222"})
|
||||
@NullSource
|
||||
|
||||
+1
-12
@@ -21,10 +21,7 @@ import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -72,7 +69,6 @@ public class AddRemoveDeviceIntegrationTest {
|
||||
@RegisterExtension
|
||||
static final S3LocalStackExtension S3_EXTENSION = new S3LocalStackExtension("testbucket");
|
||||
|
||||
private ExecutorService accountLockExecutor;
|
||||
private ScheduledExecutorService scheduledExecutorService;
|
||||
|
||||
private KeysManager keysManager;
|
||||
@@ -109,7 +105,6 @@ public class AddRemoveDeviceIntegrationTest {
|
||||
DynamoDbExtensionSchema.Tables.DELETED_ACCOUNTS.tableName(),
|
||||
DynamoDbExtensionSchema.Tables.USED_LINK_DEVICE_TOKENS.tableName());
|
||||
|
||||
accountLockExecutor = Executors.newSingleThreadExecutor();
|
||||
scheduledExecutorService = mock(ScheduledExecutorService.class);
|
||||
|
||||
final AccountLockManager accountLockManager = new AccountLockManager(DYNAMO_DB_EXTENSION.getDynamoDbClient(),
|
||||
@@ -157,12 +152,11 @@ public class AddRemoveDeviceIntegrationTest {
|
||||
svr2Client,
|
||||
mock(DisconnectionRequestManager.class),
|
||||
phoneNumberRecoveryPasswordsManager,
|
||||
accountLockExecutor,
|
||||
scheduledExecutorService,
|
||||
scheduledExecutorService,
|
||||
clock,
|
||||
"link-device-secret".getBytes(StandardCharsets.UTF_8),
|
||||
AccountsManager.TOTP_PARAMETERS.timeStep().dividedBy(2));
|
||||
AccountsManager.TOTP.getTimeStep().dividedBy(2));
|
||||
|
||||
accountsManager.start();
|
||||
}
|
||||
@@ -170,11 +164,6 @@ public class AddRemoveDeviceIntegrationTest {
|
||||
@AfterEach
|
||||
void tearDown() throws InterruptedException {
|
||||
accountsManager.stop();
|
||||
|
||||
accountLockExecutor.shutdown();
|
||||
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
accountLockExecutor.awaitTermination(1, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+6
-7
@@ -5,21 +5,20 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import com.apple.foundationdb.Database;
|
||||
import com.apple.foundationdb.FDB;
|
||||
import java.io.IOException;
|
||||
import org.junit.jupiter.api.extension.BeforeAllCallback;
|
||||
import org.junit.jupiter.api.extension.ExtensionContext;
|
||||
|
||||
import java.io.IOException;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.FaultTolerantDatabase;
|
||||
|
||||
public class FoundationDbClusterExtension implements BeforeAllCallback, ExtensionContext.Store.CloseableResource {
|
||||
|
||||
private FoundationDbDatabaseLifecycleManager[] databaseLifecycleManagers;
|
||||
private Database[] databases;
|
||||
private FaultTolerantDatabase[] databases;
|
||||
|
||||
public FoundationDbClusterExtension(final int numInstances) {
|
||||
this.databaseLifecycleManagers = new FoundationDbDatabaseLifecycleManager[numInstances];
|
||||
this.databases = new Database[numInstances];
|
||||
this.databases = new FaultTolerantDatabase[numInstances];
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -33,13 +32,13 @@ public class FoundationDbClusterExtension implements BeforeAllCallback, Extensio
|
||||
: new TestcontainersFoundationDbDatabaseLifecycleManager();
|
||||
databaseLifecycleManager.initializeDatabase(FDB.selectAPIVersion(FoundationDbVersion.getFoundationDbApiVersion()));
|
||||
databaseLifecycleManagers[i] = databaseLifecycleManager;
|
||||
databases[i] = databaseLifecycleManager.getDatabase();
|
||||
databases[i] = new FaultTolerantDatabase(databaseLifecycleManager.getDatabase(), String.format("messages-%d", i), null);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
public Database[] getDatabases() {
|
||||
public FaultTolerantDatabase[] getDatabases() {
|
||||
return databases;
|
||||
}
|
||||
|
||||
|
||||
+9
-3
@@ -6,6 +6,8 @@
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyByte;
|
||||
import static org.mockito.ArgumentMatchers.argThat;
|
||||
@@ -29,6 +31,7 @@ import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import java.util.stream.Collectors;
|
||||
@@ -44,7 +47,6 @@ import org.signal.libsignal.protocol.ServiceId;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStore;
|
||||
@@ -141,10 +143,14 @@ class MessagesManagerTest {
|
||||
|
||||
final UUID destinationUuid = UUID.randomUUID();
|
||||
|
||||
messagesManager.insert(destinationUuid, Map.of(Device.PRIMARY_ID, message));
|
||||
final CompletionException completionException =
|
||||
assertThrows(CompletionException.class,
|
||||
() -> messagesManager.insert(destinationUuid, Map.of(Device.PRIMARY_ID, message)));
|
||||
|
||||
assertInstanceOf(RuntimeException.class, completionException.getCause());
|
||||
|
||||
verify(foundationDbMessageStore).insert(any(), any());
|
||||
verify(messagesCache)
|
||||
verify(messagesCache, never())
|
||||
.insert(argThat(messageGuid -> messageGuid.version() == 4),
|
||||
eq(destinationUuid),
|
||||
eq(Device.PRIMARY_ID),
|
||||
|
||||
+27
@@ -556,6 +556,33 @@ public class ProfilesManagerTest {
|
||||
verifyNoInteractions(s3Client);
|
||||
}
|
||||
|
||||
@Test
|
||||
void setV1Avatar() {
|
||||
final UUID uuid = UUID.randomUUID();
|
||||
final String version = HexFormat.of().formatHex(TestRandomUtil.nextBytes(32));
|
||||
final String avatar = "avatar";
|
||||
final byte[] commitment = TestRandomUtil.nextBytes(97);
|
||||
|
||||
final VersionedProfileV1 profile = mock(VersionedProfileV1.class);
|
||||
when(profile.version()).thenReturn(version);
|
||||
when(profile.commitment()).thenReturn(commitment);
|
||||
when(profile.avatar()).thenReturn(avatar);
|
||||
|
||||
when(profilesV1.setAvatar(any(UUID.class), anyString(), anyString(), any(byte[].class)))
|
||||
.thenReturn(profile);
|
||||
|
||||
profilesManager.setV1Avatar(uuid, version, avatar, commitment);
|
||||
|
||||
verify(commands).del(aryEq(ProfilesManager.getCacheKeyV1(uuid)));
|
||||
verify(profilesV1).setAvatar(uuid, version, avatar, commitment);
|
||||
verify(setLuaScript).executeBinary(
|
||||
argThat(keys ->
|
||||
Arrays.equals(keys.get(0), ProfilesManager.getCacheKeyV1(uuid))),
|
||||
argThat(args ->
|
||||
Arrays.equals(args.get(0), version.getBytes())));
|
||||
verifyNoMoreInteractions(setLuaScript);
|
||||
}
|
||||
|
||||
@Nested
|
||||
class Redis {
|
||||
|
||||
|
||||
@@ -6,7 +6,9 @@
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -384,4 +386,41 @@ public class ProfilesTest {
|
||||
Map.of(":commitment", AttributeValues.fromByteArray(commitment)))
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void setAvatarInsert() {
|
||||
final String avatar = "avatar";
|
||||
final String version = "version";
|
||||
final byte[] commitment = TestRandomUtil.nextBytes(97);
|
||||
|
||||
final VersionedProfileV1 profile = profiles.setAvatar(UUID.randomUUID(), version, avatar,
|
||||
commitment);
|
||||
|
||||
assertEquals(version, profile.version());
|
||||
assertEquals(avatar, profile.avatar());
|
||||
assertArrayEquals(commitment, profile.commitment());
|
||||
assertNull(profile.name());
|
||||
}
|
||||
|
||||
@Test
|
||||
void setAvatarUpdate() {
|
||||
final String version = "version";
|
||||
final byte[] commitment = TestRandomUtil.nextBytes(97);
|
||||
final byte[] name = TestRandomUtil.nextBytes(81);
|
||||
final UUID uuid = UUID.randomUUID();
|
||||
{
|
||||
final VersionedProfileV1 initialProfile = new VersionedProfileV1(version, name, null, null, null, null, null,
|
||||
commitment);
|
||||
|
||||
profiles.set(uuid, initialProfile);
|
||||
}
|
||||
final String avatar = "avatar";
|
||||
|
||||
final VersionedProfileV1 profile = profiles.setAvatar(uuid, version, avatar, commitment);
|
||||
|
||||
assertEquals(version, profile.version());
|
||||
assertEquals(avatar, profile.avatar());
|
||||
assertArrayEquals(commitment, profile.commitment());
|
||||
assertArrayEquals(name, profile.name());
|
||||
}
|
||||
}
|
||||
+8
-4
@@ -15,7 +15,7 @@ import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
|
||||
public class ReceiptCredentialTestUtil {
|
||||
private static final ServerSecretParams RECEIPT_PARAMS = ServerSecretParams.generate();
|
||||
public static final ServerSecretParams RECEIPT_PARAMS = ServerSecretParams.generate();
|
||||
|
||||
public static ReceiptCredentialPresentation receiptPresentation()
|
||||
throws InvalidInputException, VerificationFailedException {
|
||||
@@ -30,12 +30,16 @@ public class ReceiptCredentialTestUtil {
|
||||
return receiptPresentation(new ReceiptSerial(TestRandomUtil.nextBytes(ReceiptSerial.SIZE)), expiresAt, receiptLevel);
|
||||
}
|
||||
|
||||
public static ReceiptCredentialPresentation receiptPresentation(final ReceiptSerial receiptSerial, final Instant expiresAt, final long receiptLevel)
|
||||
public static ReceiptCredentialPresentation receiptPresentation(final ReceiptSerial receiptSerial, final Instant expiresAt, final long receiptLevel) throws VerificationFailedException {
|
||||
return receiptPresentation(RECEIPT_PARAMS, receiptSerial, expiresAt, receiptLevel);
|
||||
}
|
||||
|
||||
public static ReceiptCredentialPresentation receiptPresentation(final ServerSecretParams receiptParams, final ReceiptSerial receiptSerial, final Instant expiresAt, final long receiptLevel)
|
||||
throws VerificationFailedException {
|
||||
|
||||
final ServerZkReceiptOperations serverOperations = new ServerZkReceiptOperations(RECEIPT_PARAMS);
|
||||
final ServerZkReceiptOperations serverOperations = new ServerZkReceiptOperations(receiptParams);
|
||||
final ClientZkReceiptOperations clientOperations =
|
||||
new ClientZkReceiptOperations(RECEIPT_PARAMS.getPublicParams());
|
||||
new ClientZkReceiptOperations(receiptParams.getPublicParams());
|
||||
|
||||
final ReceiptCredentialRequestContext requestContext =
|
||||
clientOperations.createReceiptCredentialRequestContext(receiptSerial);
|
||||
|
||||
+27
-6
@@ -11,11 +11,14 @@ import static org.assertj.core.api.Fail.fail;
|
||||
import static org.whispersystems.textsecuregcm.storage.Subscriptions.GetResult.Type.FOUND;
|
||||
import static org.whispersystems.textsecuregcm.storage.Subscriptions.GetResult.Type.NOT_STORED;
|
||||
import static org.whispersystems.textsecuregcm.storage.Subscriptions.GetResult.Type.PASSWORD_MISMATCH;
|
||||
import static org.whispersystems.textsecuregcm.util.AttributeValues.b;
|
||||
|
||||
import jakarta.ws.rs.ClientErrorException;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.function.Consumer;
|
||||
import javax.annotation.Nonnull;
|
||||
@@ -29,6 +32,8 @@ import org.whispersystems.textsecuregcm.storage.Subscriptions.Record;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.ProcessorCustomer;
|
||||
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
|
||||
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.QueryResponse;
|
||||
|
||||
class SubscriptionsTest {
|
||||
|
||||
@@ -138,9 +143,8 @@ class SubscriptionsTest {
|
||||
.isInstanceOf(ClientErrorException.class)
|
||||
.satisfies(clientError409Condition);
|
||||
|
||||
assertThat(subscriptions.getSubscriberUserByProcessorCustomer(
|
||||
new ProcessorCustomer(customer, PaymentProvider.STRIPE)))
|
||||
.isEqualTo(user);
|
||||
assertThat(getSubscriberUsersByProcessorCustomer(new ProcessorCustomer(customer, PaymentProvider.STRIPE)))
|
||||
.containsExactly(user);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -154,9 +158,8 @@ class SubscriptionsTest {
|
||||
subscriptions.setProcessorAndCustomerId(userRecord,
|
||||
new ProcessorCustomer(customer, PaymentProvider.STRIPE),
|
||||
subscriptionUpdated);
|
||||
assertThat(subscriptions.getSubscriberUserByProcessorCustomer(
|
||||
new ProcessorCustomer(customer, PaymentProvider.STRIPE)))
|
||||
.isEqualTo(user);
|
||||
assertThat(getSubscriberUsersByProcessorCustomer(new ProcessorCustomer(customer, PaymentProvider.STRIPE)))
|
||||
.containsExactly(user);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -372,4 +375,22 @@ class SubscriptionsTest {
|
||||
assertThat(record.currentPeriodEndsAt).isNull();
|
||||
};
|
||||
}
|
||||
|
||||
private List<byte[]> getSubscriberUsersByProcessorCustomer(final ProcessorCustomer processorCustomer) {
|
||||
final QueryResponse queryResponse = DYNAMO_DB_EXTENSION.getDynamoDbClient().query(QueryRequest.builder()
|
||||
.tableName(Tables.SUBSCRIPTIONS.tableName())
|
||||
.indexName(Subscriptions.INDEX_NAME)
|
||||
.keyConditionExpression("#processor_customer_id = :processor_customer_id")
|
||||
.projectionExpression("#user")
|
||||
.expressionAttributeNames(Map.of(
|
||||
"#processor_customer_id", Subscriptions.KEY_PROCESSOR_ID_CUSTOMER_ID,
|
||||
"#user", Subscriptions.KEY_USER))
|
||||
.expressionAttributeValues(Map.of(":processor_customer_id", b(processorCustomer.toDynamoBytes())))
|
||||
.build());
|
||||
|
||||
return queryResponse.items().stream()
|
||||
.map(item -> item.get(Subscriptions.KEY_USER).b().asByteArray())
|
||||
.toList();
|
||||
}
|
||||
|
||||
}
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage.foundationdb;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.apple.foundationdb.Database;
|
||||
import com.apple.foundationdb.FDBException;
|
||||
import io.github.resilience4j.circuitbreaker.CallNotPermittedException;
|
||||
import java.time.Duration;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.whispersystems.textsecuregcm.configuration.CircuitBreakerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.util.ResilienceUtil;
|
||||
|
||||
public class FaultTolerantDatabaseTest {
|
||||
private Database database;
|
||||
private FaultTolerantDatabase ftDatabase;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
database = mock(Database.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void circuitBreaker() throws InterruptedException {
|
||||
final String circuitBreakerConfigurationName = "testCircuitBreaker";
|
||||
final CircuitBreakerConfiguration circuitBreakerConfiguration = new CircuitBreakerConfiguration();
|
||||
|
||||
circuitBreakerConfiguration.setSlidingWindowSize(2);
|
||||
circuitBreakerConfiguration.setSlidingWindowMinimumNumberOfCalls(2);
|
||||
circuitBreakerConfiguration.setPermittedNumberOfCallsInHalfOpenState(1);
|
||||
circuitBreakerConfiguration.setFailureRateThreshold(50);
|
||||
circuitBreakerConfiguration.setWaitDurationInOpenState(Duration.ofSeconds(1));
|
||||
|
||||
ResilienceUtil.getCircuitBreakerRegistry()
|
||||
.addConfiguration(circuitBreakerConfigurationName, circuitBreakerConfiguration.toCircuitBreakerConfig());
|
||||
ftDatabase = new FaultTolerantDatabase(database, getClass().getSimpleName() + "testCircuitBreaker",
|
||||
circuitBreakerConfigurationName);
|
||||
|
||||
when(database.read(any())).thenThrow(new FDBException("error", 1031));
|
||||
|
||||
assertThrows(FDBException.class, () -> ftDatabase.read(t ->
|
||||
t.get("test_key".getBytes())));
|
||||
|
||||
assertThrows(FDBException.class, () -> ftDatabase.read(t ->
|
||||
t.get("test_key".getBytes())));
|
||||
|
||||
assertThrows(CallNotPermittedException.class, () -> ftDatabase.read(t ->
|
||||
t.get("test_key".getBytes())));
|
||||
|
||||
Thread.sleep(1001);
|
||||
|
||||
assertThrows(FDBException.class, () -> ftDatabase.read(t ->
|
||||
t.get("test_key".getBytes())));
|
||||
|
||||
assertThrows(CallNotPermittedException.class, () -> ftDatabase.read(t ->
|
||||
t.get("test_key".getBytes())));
|
||||
}
|
||||
}
|
||||
Loaded 100 of 114 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user