Compare commits

...
Author SHA1 Message Date
Ravi Khadiwala 7489c62fb7 Avoid attribute modification errors on numberless accounts 2026-09-02 16:17:26 -05:00
Ravi Khadiwala 23932b1087 Update constructors in UpdateGambiaPniMappingsCommandTest 2026-09-02 16:15:37 -05:00
Ravi Khadiwala 6b3f66ddc1 Forbid idempotent numberless registration retries if MFA keys are present 2026-09-02 16:56:11 -04:00
Jon Chambers 77e3675fc9 Add a command to map alternate forms of existing Gambian phone numbers to the same PNI 2026-09-02 16:55:49 -04:00
Jon Chambers 2f712b3f93 Add an alternate number form generator for Gambia 2026-09-02 16:55:49 -04:00
Jon Chambers 9b5ad238cf Introduce the AlternatePhoneNumberFormGenerator interface 2026-09-02 16:55:49 -04:00
Ravi Khadiwala 8c62a7f819 Add delay to TOTP confirmation validation 2026-09-02 16:55:35 -04:00
Jonathan Klabunde Tomer 3a75f705c2 Simplify list-MFA-keys RPC
Turns out clients only actually want the metadata, repeating the crypto
parameters is useless
2026-09-02 16:55:26 -04:00
Ameya Lokare d79e37230e Return 401 if receipt credential fails verification, is expired or is
already redeemed
2026-09-02 16:54:12 -04:00
Ameya Lokare 7bc8b93c18 Remove use of account lock executor in
ClearOrphanedFoundationDbQueuesCommand
2026-09-02 16:53:51 -04:00
Ravi Khadiwala b6bed9d772 Remove confusing subscriber_id_mismatch response 2026-09-02 16:34:48 -04:00
Ravi Khadiwala 18e58dd21f Improve error response documentation in subscription.proto 2026-09-02 16:34:48 -04:00
Ravi Khadiwala 6ab0acadfd Document RPCs that require an Accept-Language header 2026-09-02 16:34:48 -04:00
Ravi Khadiwala 6209466d1d Fix accidental renumbering in login_purchase.proto 2026-09-02 16:34:17 -04:00
Ameya Lokare 9483f358cd Remove executor for acquiring locks in AccountLockManager 2026-09-02 16:33:49 -04:00
Ameya Lokare 1c28620b65 Re-use ACI / clear account queues under a pessimistic ACI lock 2026-09-02 16:33:29 -04:00
dependabot[bot] cc50ff7074 Bump the minor-java-dependencies group across 4 directories with 6 updates
Bumps the minor-java-dependencies group with 5 updates in the /api-doc directory:

| Package | From | To |
| --- | --- | --- |
| [com.google.cloud:libraries-bom](https://github.com/googleapis/google-cloud-java) | `26.86.0` | `26.87.0` |
| software.amazon.awssdk:bom | `2.54.5` | `2.54.7` |
| [com.googlecode.libphonenumber:libphonenumber](https://github.com/google/libphonenumber) | `9.0.37` | `9.0.38` |
| [com.stripe:stripe-java](https://github.com/stripe/stripe-java) | `33.3.0` | `33.4.0` |
| [org.signal:libsignal-server](https://github.com/signalapp/libsignal) | `0.101.0` | `0.101.2` |

Bumps the minor-java-dependencies group with 5 updates in the /integration-tests directory:

| Package | From | To |
| --- | --- | --- |
| [com.google.cloud:libraries-bom](https://github.com/googleapis/google-cloud-java) | `26.86.0` | `26.87.0` |
| software.amazon.awssdk:bom | `2.54.5` | `2.54.7` |
| [com.googlecode.libphonenumber:libphonenumber](https://github.com/google/libphonenumber) | `9.0.37` | `9.0.38` |
| [com.stripe:stripe-java](https://github.com/stripe/stripe-java) | `33.3.0` | `33.4.0` |
| [org.signal:libsignal-server](https://github.com/signalapp/libsignal) | `0.101.0` | `0.101.2` |

Bumps the minor-java-dependencies group with 6 updates in the /service directory:

| Package | From | To |
| --- | --- | --- |
| [com.google.cloud:libraries-bom](https://github.com/googleapis/google-cloud-java) | `26.86.0` | `26.87.0` |
| software.amazon.awssdk:bom | `2.54.5` | `2.54.7` |
| [com.googlecode.libphonenumber:libphonenumber](https://github.com/google/libphonenumber) | `9.0.37` | `9.0.38` |
| [com.stripe:stripe-java](https://github.com/stripe/stripe-java) | `33.3.0` | `33.4.0` |
| [org.signal:libsignal-server](https://github.com/signalapp/libsignal) | `0.101.0` | `0.101.2` |
| [com.googlecode.libphonenumber:geocoder](https://github.com/google/libphonenumber) | `3.37` | `3.38` |

Bumps the minor-java-dependencies group with 5 updates in the /websocket-resources directory:

| Package | From | To |
| --- | --- | --- |
| [com.google.cloud:libraries-bom](https://github.com/googleapis/google-cloud-java) | `26.86.0` | `26.87.0` |
| software.amazon.awssdk:bom | `2.54.5` | `2.54.7` |
| [com.googlecode.libphonenumber:libphonenumber](https://github.com/google/libphonenumber) | `9.0.37` | `9.0.38` |
| [com.stripe:stripe-java](https://github.com/stripe/stripe-java) | `33.3.0` | `33.4.0` |
| [org.signal:libsignal-server](https://github.com/signalapp/libsignal) | `0.101.0` | `0.101.2` |



Updates `com.google.cloud:libraries-bom` from 26.86.0 to 26.87.0
- [Release notes](https://github.com/googleapis/google-cloud-java/releases)
- [Changelog](https://github.com/googleapis/google-cloud-java/blob/main/CHANGELOG.md)
- [Commits](https://github.com/googleapis/google-cloud-java/compare/libraries-bom/v26.86.0...libraries-bom/v26.87.0)

Updates `software.amazon.awssdk:bom` from 2.54.5 to 2.54.7

Updates `com.googlecode.libphonenumber:libphonenumber` from 9.0.37 to 9.0.38
- [Release notes](https://github.com/google/libphonenumber/releases)
- [Changelog](https://github.com/google/libphonenumber/blob/master/release_notes.txt)
- [Commits](https://github.com/google/libphonenumber/compare/v9.0.37...v9.0.38)

Updates `com.stripe:stripe-java` from 33.3.0 to 33.4.0
- [Release notes](https://github.com/stripe/stripe-java/releases)
- [Changelog](https://github.com/stripe/stripe-java/blob/master/CHANGELOG.md)
- [Commits](https://github.com/stripe/stripe-java/compare/v33.3.0...v33.4.0)

Updates `org.signal:libsignal-server` from 0.101.0 to 0.101.2
- [Release notes](https://github.com/signalapp/libsignal/releases)
- [Changelog](https://github.com/signalapp/libsignal/blob/main/RELEASE_NOTES.md)
- [Commits](https://github.com/signalapp/libsignal/compare/v0.101.0...v0.101.2)

Updates `com.google.cloud:libraries-bom` from 26.86.0 to 26.87.0
- [Release notes](https://github.com/googleapis/google-cloud-java/releases)
- [Changelog](https://github.com/googleapis/google-cloud-java/blob/main/CHANGELOG.md)
- [Commits](https://github.com/googleapis/google-cloud-java/compare/libraries-bom/v26.86.0...libraries-bom/v26.87.0)

Updates `software.amazon.awssdk:bom` from 2.54.5 to 2.54.7

Updates `com.googlecode.libphonenumber:libphonenumber` from 9.0.37 to 9.0.38
- [Release notes](https://github.com/google/libphonenumber/releases)
- [Changelog](https://github.com/google/libphonenumber/blob/master/release_notes.txt)
- [Commits](https://github.com/google/libphonenumber/compare/v9.0.37...v9.0.38)

Updates `com.stripe:stripe-java` from 33.3.0 to 33.4.0
- [Release notes](https://github.com/stripe/stripe-java/releases)
- [Changelog](https://github.com/stripe/stripe-java/blob/master/CHANGELOG.md)
- [Commits](https://github.com/stripe/stripe-java/compare/v33.3.0...v33.4.0)

Updates `org.signal:libsignal-server` from 0.101.0 to 0.101.2
- [Release notes](https://github.com/signalapp/libsignal/releases)
- [Changelog](https://github.com/signalapp/libsignal/blob/main/RELEASE_NOTES.md)
- [Commits](https://github.com/signalapp/libsignal/compare/v0.101.0...v0.101.2)

Updates `com.google.cloud:libraries-bom` from 26.86.0 to 26.87.0
- [Release notes](https://github.com/googleapis/google-cloud-java/releases)
- [Changelog](https://github.com/googleapis/google-cloud-java/blob/main/CHANGELOG.md)
- [Commits](https://github.com/googleapis/google-cloud-java/compare/libraries-bom/v26.86.0...libraries-bom/v26.87.0)

Updates `software.amazon.awssdk:bom` from 2.54.5 to 2.54.7

Updates `com.googlecode.libphonenumber:libphonenumber` from 9.0.37 to 9.0.38
- [Release notes](https://github.com/google/libphonenumber/releases)
- [Changelog](https://github.com/google/libphonenumber/blob/master/release_notes.txt)
- [Commits](https://github.com/google/libphonenumber/compare/v9.0.37...v9.0.38)

Updates `com.stripe:stripe-java` from 33.3.0 to 33.4.0
- [Release notes](https://github.com/stripe/stripe-java/releases)
- [Changelog](https://github.com/stripe/stripe-java/blob/master/CHANGELOG.md)
- [Commits](https://github.com/stripe/stripe-java/compare/v33.3.0...v33.4.0)

Updates `org.signal:libsignal-server` from 0.101.0 to 0.101.2
- [Release notes](https://github.com/signalapp/libsignal/releases)
- [Changelog](https://github.com/signalapp/libsignal/blob/main/RELEASE_NOTES.md)
- [Commits](https://github.com/signalapp/libsignal/compare/v0.101.0...v0.101.2)

Updates `com.googlecode.libphonenumber:geocoder` from 3.37 to 3.38
- [Release notes](https://github.com/google/libphonenumber/releases)
- [Changelog](https://github.com/google/libphonenumber/blob/master/release_notes.txt)
- [Commits](https://github.com/google/libphonenumber/commits)

Updates `com.google.cloud:libraries-bom` from 26.86.0 to 26.87.0
- [Release notes](https://github.com/googleapis/google-cloud-java/releases)
- [Changelog](https://github.com/googleapis/google-cloud-java/blob/main/CHANGELOG.md)
- [Commits](https://github.com/googleapis/google-cloud-java/compare/libraries-bom/v26.86.0...libraries-bom/v26.87.0)

Updates `software.amazon.awssdk:bom` from 2.54.5 to 2.54.7

Updates `com.googlecode.libphonenumber:libphonenumber` from 9.0.37 to 9.0.38
- [Release notes](https://github.com/google/libphonenumber/releases)
- [Changelog](https://github.com/google/libphonenumber/blob/master/release_notes.txt)
- [Commits](https://github.com/google/libphonenumber/compare/v9.0.37...v9.0.38)

Updates `com.stripe:stripe-java` from 33.3.0 to 33.4.0
- [Release notes](https://github.com/stripe/stripe-java/releases)
- [Changelog](https://github.com/stripe/stripe-java/blob/master/CHANGELOG.md)
- [Commits](https://github.com/stripe/stripe-java/compare/v33.3.0...v33.4.0)

Updates `org.signal:libsignal-server` from 0.101.0 to 0.101.2
- [Release notes](https://github.com/signalapp/libsignal/releases)
- [Changelog](https://github.com/signalapp/libsignal/blob/main/RELEASE_NOTES.md)
- [Commits](https://github.com/signalapp/libsignal/compare/v0.101.0...v0.101.2)

---
updated-dependencies:
- dependency-name: com.google.cloud:libraries-bom
  dependency-version: 26.87.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: software.amazon.awssdk:bom
  dependency-version: 2.54.7
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: com.googlecode.libphonenumber:libphonenumber
  dependency-version: 9.0.38
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: com.stripe:stripe-java
  dependency-version: 33.4.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: org.signal:libsignal-server
  dependency-version: 0.101.2
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: com.google.cloud:libraries-bom
  dependency-version: 26.87.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: software.amazon.awssdk:bom
  dependency-version: 2.54.7
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: com.googlecode.libphonenumber:libphonenumber
  dependency-version: 9.0.38
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: com.stripe:stripe-java
  dependency-version: 33.4.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: org.signal:libsignal-server
  dependency-version: 0.101.2
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: com.google.cloud:libraries-bom
  dependency-version: 26.87.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: software.amazon.awssdk:bom
  dependency-version: 2.54.7
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: com.googlecode.libphonenumber:libphonenumber
  dependency-version: 9.0.38
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: com.stripe:stripe-java
  dependency-version: 33.4.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: org.signal:libsignal-server
  dependency-version: 0.101.2
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: com.googlecode.libphonenumber:geocoder
  dependency-version: '3.38'
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: com.google.cloud:libraries-bom
  dependency-version: 26.87.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: software.amazon.awssdk:bom
  dependency-version: 2.54.7
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: com.googlecode.libphonenumber:libphonenumber
  dependency-version: 9.0.38
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: com.stripe:stripe-java
  dependency-version: 33.4.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: org.signal:libsignal-server
  dependency-version: 0.101.2
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-09-02 16:29:21 -04:00
Katherine Yen c60ba6677a Lower queue sizes to 3 MB total 2026-09-02 16:26:37 -04:00
Jon Chambers 32fc76fd47 Install gpg with sudo for integration tests 2026-09-01 17:02:56 -04:00
dependabot[bot] 370c3a9992 Bump actions/setup-java from 5.7.0 to 6.0.0
Bumps [actions/setup-java](https://github.com/actions/setup-java) from 5.7.0 to 6.0.0.
- [Release notes](https://github.com/actions/setup-java/releases)
- [Commits](https://github.com/actions/setup-java/compare/b6effb05e454b25005698d916606bdc6ffcbf961...dd06d9cba3e5552c54d9f8ea23572deb30010f7c)

---
updated-dependencies:
- dependency-name: actions/setup-java
  dependency-version: 6.0.0
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-08-31 16:58:10 -04:00
Jon Chambers b3506b186d Install gpg before running setup-java 2026-08-31 16:58:10 -04:00
56 changed files with 983 additions and 350 deletions

No files matched your search

+7 -6
View File
@@ -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
+6 -1
View File
@@ -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
+4 -4
View File
@@ -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
+5 -5
View File
@@ -45,7 +45,7 @@
</modules>
<properties>
<aws.sdk2.version>2.54.5</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>
@@ -55,7 +55,7 @@
<foundationdb.version>7.3.76</foundationdb.version>
<foundationdb.api-version>730</foundationdb.api-version>
<foundationdb.client-library-sha256>af099848721d08904ff9e5d38fade0de24d92e86451ea491d9ab5ce84adcf62a</foundationdb.client-library-sha256>
<google-cloud-libraries.version>26.86.0</google-cloud-libraries.version>
<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.7.1-jre</guava.version>
@@ -72,7 +72,7 @@
<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>
@@ -87,7 +87,7 @@
<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>
<stripe.version>33.4.0</stripe.version>
<swagger.version>2.2.54</swagger.version>
<testcontainers.version>2.0.5</testcontainers.version>
@@ -317,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>
+1 -1
View File
@@ -15,7 +15,7 @@
<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>
@@ -348,6 +348,7 @@ import org.whispersystems.textsecuregcm.workers.SetUserDiscoverabilityCommand;
import org.whispersystems.textsecuregcm.workers.TrimOversizedFoundationDbMessageQueuesCommand;
import org.whispersystems.textsecuregcm.workers.UnlinkDeviceCommand;
import org.whispersystems.textsecuregcm.workers.UnlinkDevicesWithIdlePrimaryCommand;
import org.whispersystems.textsecuregcm.workers.UpdateGambiaPniMappingsCommand;
import org.whispersystems.textsecuregcm.workers.ZkParamsCommand;
import org.whispersystems.websocket.WebSocketResourceProviderFactory;
import org.whispersystems.websocket.setup.WebSocketEnvironment;
@@ -416,6 +417,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
bootstrap.addCommand(new PopulateAccountRecoveryPasswordsCommand());
bootstrap.addCommand(new UpdateGambiaPniMappingsCommand());
ServiceLoader.load(SpamFilter.class)
.stream()
.map(ServiceLoader.Provider::get)
@@ -668,10 +671,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)
@@ -801,10 +800,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());
@@ -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());
@@ -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")
@@ -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");
}
}
@@ -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;
}
}
@@ -53,6 +53,7 @@ import org.signal.chat.account.GetEntitlementsRequest;
import org.signal.chat.account.GetEntitlementsResponse;
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.RemoveMfaKeyRequest;
import org.signal.chat.account.RemoveMfaKeyResponse;
@@ -612,14 +613,13 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
getAuthenticatedAccount().getMfaKeys().forEach((keyId, mfaKey) -> {
assert mfaKey.metadataCiphertext() != null;
ListMfaKeysResponse.MfaKeyMetadata.Builder metadataBuilder = ListMfaKeysResponse.MfaKeyMetadata.newBuilder()
.setMetadataCiphertext(ByteString.copyFrom(mfaKey.metadataCiphertext()));
switch (mfaKey) {
case AnnotatedTotpKey k -> metadataBuilder.setTotpParameters(toGrpcTotpParameters(k.totpKey().totpParameters()));
}
responseBuilder.putKeys(keyId, metadataBuilder.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();
@@ -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();
}
}
@@ -475,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");
}
@@ -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();
}
@@ -468,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(
@@ -1094,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());
@@ -50,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;
@@ -142,7 +141,6 @@ 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;
@@ -299,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,
@@ -318,7 +315,6 @@ 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);
@@ -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) {
@@ -2084,7 +2086,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
final TotpKey pendingTotpKey = maybePendingTotpKey.get();
try {
if (TOTP.validateOneTimePassword(pendingTotpKey, timestamp, oneTimePassword)) {
if (verifyTotp(pendingTotpKey, timestamp, oneTimePassword)) {
final AtomicInteger keyId = new AtomicInteger();
update(accountIdentifier, account -> {
@@ -2127,7 +2129,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
.max(Map.Entry.comparingByKey())
.filter(entry -> {
try {
return TOTP.validateOneTimePassword((AnnotatedTotpKey) 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;
@@ -2147,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 : totpKeys) {
try {
if (TOTP.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;
}
}
@@ -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");
@@ -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
@@ -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;
}
@@ -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);
}
}
@@ -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);
}
@@ -25,7 +25,10 @@ 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;
@@ -37,8 +40,10 @@ 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.FoundationDbMessageStore;
import org.whispersystems.textsecuregcm.util.ManagedExecutors;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.util.retry.Retry;
@@ -132,26 +137,32 @@ public class ClearOrphanedFoundationDbQueuesCommand extends AbstractCommandWithD
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);
chunksPerShard,
commandDependencies.accountLockManager(),
executorService);
}
@VisibleForTesting
void clearOrphanedQueues(final Stream<Database> databases, final AccountsManager accountsManager,
final int concurrency, final boolean dryRun, final int maxAcisPerTransaction, final long transactionRetryLimit,
final Duration transactionTimeout, final int numChunks) {
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))
transactionRetryLimit, transactionTimeout, numChunks, accountLockManager, executor))
.then()
.block();
}
private Mono<Void> crawlAcisInShard(final Database database, final AccountsManager accountsManager,
final int concurrency, final boolean dryRun, final int maxAcisPerTransaction, final long transactionRetryLimit,
final Duration transactionTimeout, final int numChunks) {
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()))
@@ -172,7 +183,8 @@ public class ClearOrphanedFoundationDbQueuesCommand extends AbstractCommandWithD
logger.info("Would have cleared queue for ACI: {}", aci.uuid());
return Mono.just(true);
}
return clearQueue(database, aci, transactionRetryLimit, transactionTimeout)
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);
@@ -185,15 +197,30 @@ public class ClearOrphanedFoundationDbQueuesCommand extends AbstractCommandWithD
.then();
}
private Mono<Void> clearQueue(final Database database, final AciServiceIdentifier aci,
final long transactionRetryLimit, final Duration transactionTimeout) {
return Mono.fromFuture(() -> database.runAsync(transaction -> {
private Mono<Void> clearQueueWithAciLock(final Database 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 Database 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 CompletableFuture.completedFuture(null);
}));
return null;
});
}
@VisibleForTesting
@@ -126,7 +126,8 @@ public record CommandDependencies(
DynamoDbClient dynamoDbClient,
PhoneNumberIdentifiers phoneNumberIdentifiers,
DynamoDbRecoveryManager dynamoDbRecoveryManager,
FDB fdb) {
FDB fdb,
AccountLockManager accountLockManager) {
static CommandDependencies build(
final String name,
@@ -205,8 +206,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<>())
@@ -357,7 +356,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);
@@ -460,8 +459,8 @@ public record CommandDependencies(
dynamoDbClient,
phoneNumberIdentifiers,
dynamoDbRecoveryManager,
fdb
);
fdb,
accountLockManager);
}
}
@@ -0,0 +1,43 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.workers;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Metrics;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
import org.whispersystems.textsecuregcm.util.Util;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
public class UpdateGambiaPniMappingsCommand extends AbstractSinglePassCrawlAccountsCommand {
public UpdateGambiaPniMappingsCommand() {
super("update-gambia-pni-mappings", "Maps legacy Gambian phone numbers and their new forms to the same PNI");
}
@Override
protected void crawlAccounts(final Flux<Account> accounts) {
final PhoneNumberIdentifiers phoneNumberIdentifiers = getCommandDependencies().phoneNumberIdentifiers();
final Counter updatedPniMappingCounter = Metrics.counter(MetricsUtil.name(getClass(), "updatedPniMapping"));
accounts
.filter(account -> "GM".equalsIgnoreCase(Util.getRegion(account)))
.flatMap(accountWithGambianNumber -> {
final String e164 = accountWithGambianNumber.getNumber().orElseThrow();
return Mono.fromFuture(() -> phoneNumberIdentifiers.setPni(e164,
Util.getAlternateForms(e164),
accountWithGambianNumber.getPhoneNumberIdentifier().orElseThrow()));
})
.doOnNext(_ -> updatedPniMappingCounter.increment())
.then()
.block();
}
}
@@ -575,13 +575,16 @@ message ListMfaKeysRequest {}
message ListMfaKeysResponse {
message MfaKeyMetadata {
// The user-provided ciphertext for metadata associated with this MFA key
enum MfaKeyType {
MFA_KEY_TYPE_UNSPECIFIED = 0;
MFA_KEY_TYPE_TOTP = 1;
}
/// The user-provided ciphertext for metadata associated with this MFA key
bytes metadata_ciphertext = 1 [(require.exactlySize) = 160];
oneof mfa_key {
// The TOTP parameters associated with this key, which is a TOTP key
TotpParameters totp_parameters = 2;
}
/// The type of MFA factor this key is for
MfaKeyType type = 2;
}
map<uint32, MfaKeyMetadata> keys = 1;
@@ -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
@@ -91,7 +91,7 @@ message LoginConfiguration {
// 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 = 5;
string play_option_id = 4;
// The App Store productID associated with a Signal Login purchase
string app_store_product_id = 4;
string app_store_product_id = 3;
}
@@ -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"];
}
}
@@ -869,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()
@@ -67,8 +67,10 @@ 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;
@@ -102,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;
@@ -147,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
@@ -880,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);
@@ -923,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);
@@ -932,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)
);
}
@@ -1123,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,
@@ -1145,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());
}
}
@@ -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());
}
}
@@ -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;
@@ -1236,15 +1237,9 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
final ListMfaKeysResponse response =
authenticatedServiceStub().listMfaKeys(ListMfaKeysRequest.getDefaultInstance());
final TotpParameters expectedTotpParameters = TotpParameters.newBuilder()
.setAlgorithm(AccountsManager.TOTP.getAlgorithm())
.setPasswordLength(AccountsManager.TOTP.getPasswordLength())
.setTimeStepSeconds(Math.toIntExact(AccountsManager.TOTP.getTimeStep().toSeconds()))
.build();
final Map<Integer, ListMfaKeysResponse.MfaKeyMetadata> expectedTotpKeys = totpKeys.entrySet().stream()
.collect(Collectors.toMap(entry -> entry.getKey().intValue(), entry -> ListMfaKeysResponse.MfaKeyMetadata.newBuilder()
.setTotpParameters(expectedTotpParameters)
.setType(MfaKeyType.MFA_KEY_TYPE_TOTP)
.setMetadataCiphertext(ByteString.copyFrom(entry.getValue().metadataCiphertext()))
.build()));
@@ -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
@@ -173,7 +173,6 @@ public class AccountCreationDeletionIntegrationTest {
phoneNumberRecoveryPasswordsManager,
executor,
executor,
executor,
CLOCK,
"link-device-secret".getBytes(StandardCharsets.UTF_8),
AccountsManager.TOTP.getTimeStep().dividedBy(2));
@@ -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());
}
@@ -37,6 +37,7 @@ 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;
@@ -108,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),
@@ -153,7 +153,6 @@ class AccountsManagerChangeNumberIntegrationTest {
phoneNumberRecoveryPasswordsManager,
executor,
executor,
executor,
mock(Clock.class),
"link-device-secret".getBytes(StandardCharsets.UTF_8),
AccountsManager.TOTP.getTimeStep().dividedBy(2));
@@ -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,7 +132,6 @@ class AccountsManagerConcurrentModificationIntegrationTest {
mock(SecureValueRecoveryClient.class),
mock(DisconnectionRequestManager.class),
phoneNumberRecoveryPasswordsManager,
mock(Executor.class),
mock(ScheduledExecutorService.class),
mock(ScheduledExecutorService.class),
mock(Clock.class),
@@ -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,7 +67,6 @@ public class AccountsManagerDeviceTransferIntegrationTest {
mock(SecureValueRecoveryClient.class),
mock(DisconnectionRequestManager.class),
mock(PhoneNumberRecoveryPasswordsManager.class),
mock(ExecutorService.class),
mock(ScheduledExecutorService.class),
mock(ScheduledExecutorService.class),
Clock.systemUTC(),
@@ -139,7 +139,6 @@ public class AccountsManagerMigrateRecoveryPasswordIntegrationTest {
phoneNumberRecoveryPasswordsManager,
executor,
executor,
executor,
mock(Clock.class),
"link-device-secret".getBytes(StandardCharsets.UTF_8),
AccountsManager.TOTP.getTimeStep().dividedBy(2));
@@ -58,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;
@@ -210,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);
@@ -251,7 +250,6 @@ class AccountsManagerTest {
svr2Client,
disconnectionRequestManager,
phoneNumberRecoveryPasswordsManager,
mock(Executor.class),
mock(ScheduledExecutorService.class),
mock(ScheduledExecutorService.class),
CLOCK,
@@ -1996,6 +1994,41 @@ class AccountsManagerTest {
verify(account).setPendingTotpKey(null);
}
@Test
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();
@@ -2150,10 +2183,7 @@ class AccountsManagerTest {
final Account account = mock(Account.class);
when(account.getMfaKeys()).thenReturn(Map.of((byte) 1, totpKey));
final Instant beginningOfTotpWindow =
Instant.ofEpochMilli((Instant.now().toEpochMilli() / AccountsManager.TOTP.getTimeStep().toMillis()) *
AccountsManager.TOTP.getTimeStep().toMillis());
final Instant beginningOfTotpWindow = totpWindowStart(Instant.now());
final int oneTimePassword = AccountsManager.TOTP.generateOneTimePassword(totpKey, beginningOfTotpWindow);
assertTrue(accountsManager.verifyTotp(account, beginningOfTotpWindow, oneTimePassword),
@@ -2170,4 +2200,9 @@ class AccountsManagerTest {
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());
}
}
@@ -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,7 +153,6 @@ class AccountsManagerUsernameIntegrationTest {
mock(SecureValueRecoveryClient.class),
disconnectionRequestManager,
phoneNumberRecoveryPasswordsManager,
Executors.newSingleThreadExecutor(),
Executors.newSingleThreadScheduledExecutor(),
Executors.newSingleThreadScheduledExecutor(),
Clock.systemUTC(),
@@ -556,6 +556,31 @@ 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
@@ -588,7 +613,15 @@ class AccountsTest {
if (number != null) {
reclaimAccount(secondAccount);
} else {
reclaimNumberlessAccount(secondAccount, receiptCredentialPresentation, accountRecoveryPassword);
// 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();
@@ -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,7 +152,6 @@ public class AddRemoveDeviceIntegrationTest {
svr2Client,
mock(DisconnectionRequestManager.class),
phoneNumberRecoveryPasswordsManager,
accountLockExecutor,
scheduledExecutorService,
scheduledExecutorService,
clock,
@@ -170,11 +164,6 @@ public class AddRemoveDeviceIntegrationTest {
@AfterEach
void tearDown() throws InterruptedException {
accountsManager.stop();
accountLockExecutor.shutdown();
//noinspection ResultOfMethodCallIgnored
accountLockExecutor.awaitTermination(1, TimeUnit.SECONDS);
}
@Test
@@ -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);
@@ -56,7 +56,6 @@ import javax.annotation.Nullable;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import org.junit.jupiter.api.extension.RegisterExtension;
@@ -1147,10 +1146,9 @@ class FoundationDbMessageStoreTest {
.block();
}
@ParameterizedTest
@ValueSource(ints = {5, 10, 20})
@Disabled("flaky, will hit the 5 second timeout")
void estimateQueueSizeAndSplitPoints(final long totalQueueSizeMb) {
@Test
void estimateQueueSizeAndSplitPoints() {
final long totalQueueSizeMb = 3;
final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID());
final byte deviceId = Device.PRIMARY_ID;
final AtomicLong serialTimestamp = new AtomicLong();
@@ -1165,28 +1163,21 @@ class FoundationDbMessageStoreTest {
generateAndInsertMessages(aci, deviceId, FoundationDbMessageStoreTest.FUTURE_EPOCH, numMessagesPerEpoch, serialTimestamp::incrementAndGet, contentSize);
generateAndInsertMessages(aci, deviceId, FoundationDbMessageStoreTest.DEFAULT_EPOCH, numMessagesPerEpoch, serialTimestamp::incrementAndGet, contentSize);
final long rangeSplitChunkBytes = DataSize.megabytes(1).toBytes();
final long rangeSplitChunkBytes = DataSize.kilobytes(500).toBytes();
final FoundationDbMessageStore.QueueSizeAndRangeSplitPoints queueSizeAndSplitPoints = foundationDbMessageStore.estimateQueueSizeAndSplitPoints(aci, deviceId, rangeSplitChunkBytes).block();
assertNotNull(queueSizeAndSplitPoints);
// The docs assert that if the returned size is larger than 3 MB, it can be considered accurate.
// Our queue sizes are greater than that, but even so, provide a 5% margin for error.
// Our queue sizes per FDB instance are smaller than that, so provide a margin of error.
assertEquals(totalQueueSize, queueSizeAndSplitPoints.estimatedQueueSize(), totalQueueSize * 0.05);
queueSizeAndSplitPoints.splitPointsByDatabase().forEach((_, splitPointKeys) -> {
// FoundationDB's getRangeSplitPoints appears to use the provided chunk size as an exclusive upper bound
// on the bytes covered by each pair of split points.
// Splitting an x MB range with a 1 MB chunk size will generate chunk sizes < 1 MB,
// which in turn generates x+1 chunks or x+2 split point keys.
final long expectedNumChunks = Math.toIntExact(Math.ceilDiv(totalQueueSizePerEpoch, rangeSplitChunkBytes - DataSize.bytes(1).toBytes()));
assertEquals(expectedNumChunks + 1, splitPointKeys.size());
queueSizeAndSplitPoints.splitPointsByDatabase().forEach((db, splitPointKeys) -> {
assertTrue(splitPointKeys.size() >= 2);
});
}
@ParameterizedTest
@ValueSource(ints = {1, 2})
@Disabled("flaky, will hit the 5 second timeout")
void trimQueue(final long rangeSplitSizeMb) {
@Test
void trimQueue() {
final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID());
final Device device = mock(Device.class);
final byte deviceId = Device.PRIMARY_ID;
@@ -1196,23 +1187,24 @@ class FoundationDbMessageStoreTest {
// FoundationDB values must be less than 100 KB
final int contentSize = Math.toIntExact(DataSize.kilobytes(50).toBytes());
final long totalQueueSize = DataSize.megabytes(10).toBytes();
final long totalQueueSize = DataSize.megabytes(3).toBytes();
final long totalQueueSizePerEpoch = totalQueueSize / 2;
final int numMessagesPerEpoch = (int) totalQueueSizePerEpoch / contentSize;
final List<MessageProtos.Envelope> inactiveEpochMessages = generateAndInsertMessages(aci, deviceId, FoundationDbMessageStoreTest.FUTURE_EPOCH, numMessagesPerEpoch, serialTimestamp::incrementAndGet, contentSize);
generateAndInsertMessages(aci, deviceId, FoundationDbMessageStoreTest.DEFAULT_EPOCH, numMessagesPerEpoch, serialTimestamp::incrementAndGet, contentSize);
final long maxQueueSizeBytes = DataSize.megabytes(4).toBytes();
final long targetQueueSizeBytes = DataSize.megabytes(3).toBytes();
final long rangeSplitSizeBytes = DataSize.megabytes(rangeSplitSizeMb).toBytes();
final long maxQueueSizeBytes = DataSize.megabytes(1).toBytes();
final long targetQueueSizeBytes = DataSize.kilobytes(900).toBytes();
final long rangeSplitSizeBytes = DataSize.kilobytes(500).toBytes();
// Trim all the messages in the non-active epoch and ~2 MB worth of messages in the active epoch
// Trim all the messages in the non-active epoch and ~600 KB worth of messages in the active epoch
foundationDbMessageStore.trimQueue(aci, device, maxQueueSizeBytes, targetQueueSizeBytes, rangeSplitSizeBytes, UnaryOperator.identity()).block();
final Long remainingQueueSize = foundationDbMessageStore.estimateQueueSize(aci, deviceId).block();
// We expect to be within a delta of the target queue size, where the delta is upper bounded by the range split chunk size.
// FoundationDB's docs assert that estimates are accurate above 3 MB, but our queue sizes are smaller
// than that to meet the 5s timeout threshold, so we allow for a margin of error.
assertNotNull(remainingQueueSize);
assertEquals(targetQueueSizeBytes, remainingQueueSize, rangeSplitSizeBytes);
@@ -0,0 +1,63 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.util;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.google.i18n.phonenumbers.NumberParseException;
import java.util.List;
import java.util.Optional;
import javax.annotation.Nullable;
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;
class GambiaAlternateFormGeneratorTest {
@ParameterizedTest
@MethodSource
void getAlternateForms(final String e164, final List<String> alternateForms) throws NumberParseException {
assertEquals(alternateForms, new GambiaAlternateFormGenerator().getAlternateForms(e164));
}
private static List<Arguments> getAlternateForms() {
return List.of(
Arguments.argumentSet("Legacy Qcell number", "+2203123456", List.of("+2203123456", "+220833123456")),
Arguments.argumentSet("Legacy Comium number", "+2206123456", List.of("+2206123456", "+220866123456")),
Arguments.argumentSet("Legacy Africell number", "+2202123456", List.of("+2202123456", "+220872123456")),
Arguments.argumentSet("Legacy Gamcel number", "+2209123456", List.of("+2209123456")),
Arguments.argumentSet("New-style Qcell number", "+220833123456", List.of("+220833123456", "+2203123456")),
Arguments.argumentSet("New-style Comium number", "+220866123456", List.of("+220866123456", "+2206123456")),
Arguments.argumentSet("New-style Africell number", "+220872123456", List.of("+220872123456", "+2202123456"))
);
}
@ParameterizedTest
@CsvSource({
"3123456,QCELL",
"5012345,QCELL",
"5612345,",
"835700011,QCELL",
"2123456,AFRICELL",
"7123456,AFRICELL",
"4012345,AFRICELL",
"4212345,",
"872123456,AFRICELL",
"6123456,COMIUM",
"8712345,COMIUM",
"8812345,",
"868712345,COMIUM",
"881234567,"
})
void getCarrier(final String nationalSignificantNumber,
@Nullable final GambiaAlternateFormGenerator.Carrier expectedCarrier) {
assertEquals(Optional.ofNullable(expectedCarrier),
GambiaAlternateFormGenerator.getCarrier(nationalSignificantNumber));
}
}
@@ -44,7 +44,9 @@ class UtilTest {
Arguments.of(usE164, List.of(usE164)),
Arguments.of(NEW_FORMAT_BENIN_E164_STRING, List.of(NEW_FORMAT_BENIN_E164_STRING, OLD_FORMAT_BENIN_E164_STRING)),
Arguments.of(OLD_FORMAT_BENIN_E164_STRING, List.of(OLD_FORMAT_BENIN_E164_STRING, NEW_FORMAT_BENIN_E164_STRING)),
Arguments.of(TEN_DIGIT_NATIONAL_SIGNIFICANT_BENIN_E164, List.of(TEN_DIGIT_NATIONAL_SIGNIFICANT_BENIN_E164))
Arguments.of(TEN_DIGIT_NATIONAL_SIGNIFICANT_BENIN_E164, List.of(TEN_DIGIT_NATIONAL_SIGNIFICANT_BENIN_E164)),
// Please see `GambiaAlternateFormGeneratorTest` for more comprehensive coverage
Arguments.argumentSet("Gambia alternate forms", "+220872123456", List.of("+220872123456", "+2202123456"))
);
}
@@ -22,7 +22,6 @@ import net.sourceforge.argparse4j.inf.Namespace;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.MessagesManager;
@@ -45,7 +44,8 @@ class ClearExpiredFoundationDbMessagesCommandTest {
super(clock);
this.commandDependencies = new CommandDependencies(null, null, null, null, messagesManager, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null);
this.commandDependencies = new CommandDependencies(null, null, null, null, messagesManager, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null,
null);
this.dryRun = dryRun;
}
@@ -7,6 +7,7 @@ package org.whispersystems.textsecuregcm.workers;
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.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -38,12 +39,14 @@ import org.junit.jupiter.api.extension.RegisterExtension;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountLockManager;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.FoundationDbClusterExtension;
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStore;
import org.whispersystems.textsecuregcm.storage.foundationdb.VersionstampUUIDCipher;
import org.whispersystems.textsecuregcm.util.TestClock;
import org.whispersystems.textsecuregcm.util.ThrowingSupplier;
class ClearOrphanedFoundationDbQueuesCommandTest {
@@ -54,6 +57,9 @@ class ClearOrphanedFoundationDbQueuesCommandTest {
private FoundationDbMessageStore foundationDbMessageStore;
private AccountsManager accountsManager;
private AccountLockManager accountLockManager;
@BeforeEach
void setup() {
final byte[] versionstampCipherKey = new byte[16];
@@ -61,6 +67,15 @@ class ClearOrphanedFoundationDbQueuesCommandTest {
final List<Database> databases = Arrays.asList(FOUNDATION_DB_EXTENSION.getDatabases());
accountsManager = mock(AccountsManager.class);
accountLockManager = mock(AccountLockManager.class);
when(accountLockManager.withLock(any(), any())).thenAnswer(invocation -> {
//noinspection rawtypes
final ThrowingSupplier supplier = invocation.getArgument(1);
return supplier.get();
});
foundationDbMessageStore = new FoundationDbMessageStore(
Map.of(0, databases),
0,
@@ -85,7 +100,6 @@ class ClearOrphanedFoundationDbQueuesCommandTest {
// Assume that a subset of accounts are deleted
final Set<AciServiceIdentifier> deletedAccounts = new HashSet<>(accounts.subList(0, 3));
final AccountsManager accountsManager = mock(AccountsManager.class);
when(accountsManager.getByAccountIdentifierAsync(any()))
.thenReturn(CompletableFuture.completedFuture(Optional.of(mock(Account.class))));
for (final AciServiceIdentifier deletedAccount : deletedAccounts) {
@@ -98,7 +112,10 @@ class ClearOrphanedFoundationDbQueuesCommandTest {
Arrays.stream(FOUNDATION_DB_EXTENSION.getDatabases()), accountsManager, 16, false, 8,
3,
Duration.ofSeconds(2),
2);
2,
accountLockManager,
Executors.newVirtualThreadPerTaskExecutor()
);
for (final AciServiceIdentifier aci : accounts) {
assertEquals(!deletedAccounts.contains(aci), queueExists(FoundationDbMessageStore.getAccountSubspace(aci)));
@@ -110,15 +127,18 @@ class ClearOrphanedFoundationDbQueuesCommandTest {
// create accounts in a test subspace that doesn't conflict with the main messages subspace
final Subspace testMessagesSubspace = new Subspace(
Tuple.from("MT"));
final ClearOrphanedFoundationDbQueuesCommand command = new ClearOrphanedFoundationDbQueuesCommand(testMessagesSubspace);
final ClearOrphanedFoundationDbQueuesCommand command = new ClearOrphanedFoundationDbQueuesCommand(
testMessagesSubspace);
final List<AciServiceIdentifier> acis = IntStream.range(0, 128)
.mapToObj(_ -> new AciServiceIdentifier(UUID.randomUUID()))
.toList();
final Database database = FOUNDATION_DB_EXTENSION.getDatabases()[0];
database.run(transaction -> {
acis.forEach(aci -> {
transaction.set(FoundationDbMessageStore.getAccountSubspace(testMessagesSubspace, aci).pack(Tuple.from("foo")), new byte[]{42});
transaction.set(FoundationDbMessageStore.getAccountSubspace(testMessagesSubspace, aci).pack(Tuple.from("bar")), new byte[]{43});
transaction.set(FoundationDbMessageStore.getAccountSubspace(testMessagesSubspace, aci).pack(Tuple.from("foo")),
new byte[]{42});
transaction.set(FoundationDbMessageStore.getAccountSubspace(testMessagesSubspace, aci).pack(Tuple.from("bar")),
new byte[]{43});
});
return null;
});
@@ -129,6 +149,31 @@ class ClearOrphanedFoundationDbQueuesCommandTest {
assertEquals(new HashSet<>(acis), new HashSet<>(fetchedAcis));
}
@Test
void aciReusedAfterExistenceCheck() {
final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID());
foundationDbMessageStore.insert(aci, Map.of(Device.PRIMARY_ID, generateRandomMessage())).join();
foundationDbMessageStore.insert(aci, Map.of(Device.PRIMARY_ID, generateRandomMessage())).join();
// Stub that the initial existence check returns empty, but the second check under the ACI lock returns present i.e the ACI has been re-used
// since the initial check
when(accountsManager.getByAccountIdentifierAsync(aci.uuid()))
.thenReturn(CompletableFuture.completedFuture(Optional.empty()));
when(accountsManager.getByAccountIdentifier(aci.uuid())).thenReturn(Optional.of(mock(Account.class)));
final ClearOrphanedFoundationDbQueuesCommand command = new ClearOrphanedFoundationDbQueuesCommand();
command.clearOrphanedQueues(
Arrays.stream(FOUNDATION_DB_EXTENSION.getDatabases()), accountsManager, 16, false, 8,
3,
Duration.ofSeconds(2),
2,
accountLockManager,
Executors.newVirtualThreadPerTaskExecutor()
);
assertTrue(queueExists(FoundationDbMessageStore.getAccountSubspace(aci)));
}
/// Returns whether any key exists under the account's prefix in any shard
private boolean queueExists(final Subspace accountSpace) {
final Range accountRange = accountSpace.range();
@@ -88,6 +88,7 @@ class FinishPushNotificationExperimentCommandTest {
null,
null,
null,
null,
null);
//noinspection unchecked
@@ -18,7 +18,6 @@ import net.sourceforge.argparse4j.inf.Namespace;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.push.IdleDeviceNotificationScheduler;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.Device;
@@ -69,6 +68,7 @@ class NotifyIdleDevicesCommandTest {
null,
null,
null,
null,
null);
this.idleDeviceNotificationScheduler = idleDeviceNotificationScheduler;
@@ -55,6 +55,7 @@ class RegenerateSecondaryDynamoDbTableDataCommandTest {
null,
null,
dynamoDbRecoveryManager,
null,
null);
namespace = new Namespace(Map.of(
@@ -22,7 +22,6 @@ import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.whispersystems.textsecuregcm.experiment.PushNotificationExperiment;
import org.whispersystems.textsecuregcm.experiment.PushNotificationExperimentSamples;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.Device;
import reactor.core.publisher.Flux;
@@ -77,6 +76,7 @@ class StartPushNotificationExperimentCommandTest {
null,
null,
null,
null,
null);
}
@@ -20,7 +20,6 @@ import net.sourceforge.argparse4j.inf.Namespace;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.MessagesManager;
@@ -40,7 +39,7 @@ public class TrimOversizedFoundationDbMessageQueuesCommandTest {
final boolean dryRun) {
super();
this.commandDependencies = new CommandDependencies(null, null, null, null, messagesManager, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null);
this.commandDependencies = new CommandDependencies(null, null, null, null, messagesManager, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null);
this.dryRun = dryRun;
}
@@ -0,0 +1,211 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.workers;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import java.nio.charset.StandardCharsets;
import java.time.Clock;
import java.time.Duration;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
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;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestManager;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient;
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecoveryClient;
import org.whispersystems.textsecuregcm.storage.AccountLockManager;
import org.whispersystems.textsecuregcm.storage.Accounts;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.ChangeNumberWaitingPeriodManager;
import org.whispersystems.textsecuregcm.storage.DynamoDbExtension;
import org.whispersystems.textsecuregcm.storage.DynamoDbExtensionSchema;
import org.whispersystems.textsecuregcm.storage.KeysManager;
import org.whispersystems.textsecuregcm.storage.MessagesManager;
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
import org.whispersystems.textsecuregcm.storage.PhoneNumberRecoveryPasswords;
import org.whispersystems.textsecuregcm.storage.PhoneNumberRecoveryPasswordsManager;
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
import org.whispersystems.textsecuregcm.storage.RedeemedReceiptsManager;
import org.whispersystems.textsecuregcm.storage.S3LocalStackExtension;
import org.whispersystems.textsecuregcm.tests.util.AccountsHelper;
import org.whispersystems.textsecuregcm.util.AttributeValues;
import org.whispersystems.textsecuregcm.util.Util;
import reactor.core.scheduler.Schedulers;
import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest;
import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
class UpdateGambiaPniMappingsCommandTest {
@RegisterExtension
static final DynamoDbExtension DYNAMO_DB_EXTENSION = new DynamoDbExtension(
DynamoDbExtensionSchema.Tables.ACCOUNTS,
DynamoDbExtensionSchema.Tables.DELETED_ACCOUNTS,
DynamoDbExtensionSchema.Tables.DELETED_ACCOUNTS_LOCK,
DynamoDbExtensionSchema.Tables.NUMBERS,
DynamoDbExtensionSchema.Tables.PNI,
DynamoDbExtensionSchema.Tables.PNI_ASSIGNMENTS,
DynamoDbExtensionSchema.Tables.USERNAMES,
DynamoDbExtensionSchema.Tables.PHONE_NUMBER_RECOVERY_PASSWORDS,
DynamoDbExtensionSchema.Tables.REDEEMED_RECEIPTS);
@RegisterExtension
static final RedisClusterExtension CACHE_CLUSTER_EXTENSION = RedisClusterExtension.builder().build();
@RegisterExtension
static final S3LocalStackExtension S3_EXTENSION = new S3LocalStackExtension("testbucket");
private ScheduledExecutorService executor;
private AccountsManager accountsManager;
private TestUpdateGambiaPniMappingsCommand updateGambiaPniMappingsCommand;
private static class TestUpdateGambiaPniMappingsCommand extends UpdateGambiaPniMappingsCommand {
private final PhoneNumberIdentifiers phoneNumberIdentifiers;
private TestUpdateGambiaPniMappingsCommand(final PhoneNumberIdentifiers phoneNumberIdentifiers) {
this.phoneNumberIdentifiers = phoneNumberIdentifiers;
}
@Override
protected CommandDependencies getCommandDependencies() {
return new CommandDependencies(null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
phoneNumberIdentifiers,
null,
null,
null);
}
}
@BeforeEach
void setup() {
final Accounts accounts = new Accounts(
Clock.systemUTC(),
DYNAMO_DB_EXTENSION.getDynamoDbClient(),
DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(),
new RedeemedReceiptsManager(Clock.systemUTC(), DynamoDbExtensionSchema.Tables.REDEEMED_RECEIPTS.tableName(),
DYNAMO_DB_EXTENSION.getDynamoDbClient()),
DynamoDbExtensionSchema.Tables.ACCOUNTS.tableName(),
DynamoDbExtensionSchema.Tables.NUMBERS.tableName(),
DynamoDbExtensionSchema.Tables.PNI_ASSIGNMENTS.tableName(),
DynamoDbExtensionSchema.Tables.USERNAMES.tableName(),
DynamoDbExtensionSchema.Tables.DELETED_ACCOUNTS.tableName(),
DynamoDbExtensionSchema.Tables.USED_LINK_DEVICE_TOKENS.tableName());
executor = Executors.newSingleThreadScheduledExecutor();
final AccountLockManager accountLockManager = new AccountLockManager(DYNAMO_DB_EXTENSION.getDynamoDbClient(),
DynamoDbExtensionSchema.Tables.DELETED_ACCOUNTS_LOCK.tableName());
final PhoneNumberIdentifiers phoneNumberIdentifiers =
new PhoneNumberIdentifiers(DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(),
DynamoDbExtensionSchema.Tables.PNI.tableName());
final PhoneNumberRecoveryPasswords phoneNumberRecoveryPasswords =
new PhoneNumberRecoveryPasswords(DynamoDbExtensionSchema.Tables.PHONE_NUMBER_RECOVERY_PASSWORDS.tableName(),
Duration.ofDays(1),
DYNAMO_DB_EXTENSION.getDynamoDbClient(),
Clock.systemUTC());
final PhoneNumberRecoveryPasswordsManager phoneNumberRecoveryPasswordsManager =
new PhoneNumberRecoveryPasswordsManager(phoneNumberRecoveryPasswords);
accountsManager = new AccountsManager(
accounts,
phoneNumberIdentifiers,
CACHE_CLUSTER_EXTENSION.getRedisCluster(),
mock(FaultTolerantRedisClient.class),
accountLockManager,
mock(KeysManager.class),
mock(MessagesManager.class),
mock(ProfilesManager.class),
mock(ChangeNumberWaitingPeriodManager.class),
mock(SecureStorageClient.class),
mock(SecureValueRecoveryClient.class),
mock(DisconnectionRequestManager.class),
phoneNumberRecoveryPasswordsManager,
executor,
executor,
mock(Clock.class),
"link-device-secret".getBytes(StandardCharsets.UTF_8),
AccountsManager.TOTP.getTimeStep().dividedBy(2));
updateGambiaPniMappingsCommand = new TestUpdateGambiaPniMappingsCommand(phoneNumberIdentifiers);
}
@AfterEach
void tearDown() throws InterruptedException {
executor.shutdown();
//noinspection ResultOfMethodCallIgnored
executor.awaitTermination(1, TimeUnit.SECONDS);
}
@Test
void crawlAccounts() {
final String legacyGambianNumber = "+2203123456";
final Set<String> alternateForms = new HashSet<>(Util.getAlternateForms(legacyGambianNumber));
alternateForms.remove(legacyGambianNumber);
assertFalse(alternateForms.isEmpty());
AccountsHelper.createAccount(accountsManager, legacyGambianNumber);
// To simulate existing numbers with only a single form mapped to a PNI, artificially remove alternate PNI mappings
alternateForms.forEach(e164 -> DYNAMO_DB_EXTENSION.getDynamoDbClient().deleteItem(DeleteItemRequest.builder()
.tableName(DynamoDbExtensionSchema.Tables.PNI.tableName())
.key(Map.of(PhoneNumberIdentifiers.KEY_E164, AttributeValues.fromString(e164)))
.build()));
alternateForms.forEach(e164 -> assertFalse(DYNAMO_DB_EXTENSION.getDynamoDbClient().getItem(GetItemRequest.builder()
.tableName(DynamoDbExtensionSchema.Tables.PNI.tableName())
.key(Map.of(PhoneNumberIdentifiers.KEY_E164, AttributeValues.fromString(e164)))
.build())
.hasItem()));
updateGambiaPniMappingsCommand.crawlAccounts(accountsManager.streamAllFromDynamo(1, Schedulers.boundedElastic()));
alternateForms.forEach(e164 -> assertTrue(DYNAMO_DB_EXTENSION.getDynamoDbClient().getItem(GetItemRequest.builder()
.tableName(DynamoDbExtensionSchema.Tables.PNI.tableName())
.key(Map.of(PhoneNumberIdentifiers.KEY_E164, AttributeValues.fromString(e164)))
.build())
.hasItem()));
assertTrue(accountsManager.getByE164(legacyGambianNumber).isPresent());
}
}