Compare commits

...
Author SHA1 Message Date
Jonathan Klabunde Tomer 48fd25f01e Support linking devices to accounts without phone numbers 2026-08-12 12:18:27 -04:00
Chris Eager 2c18e4aa1f Ensure AuthHelper mocks are Strictness.LENIENT 2026-08-12 11:31:46 -04:00
Chris Eager f8e049bb6c Replace unnecessary use of AuthHelper.VALID_UUID 2026-08-12 11:31:46 -04:00
Jon Chambers 8ba7da0568 Move responsibility for copying badges on account reclamation to AccountsManager 2026-08-12 09:37:30 -04:00
Katherine 30c642324a Clear PNI single use prekeys on device removal 2026-08-12 09:23:08 -04:00
Jon Chambers 647b25b87c Set phone number recovery password transactionally when creating accounts 2026-08-12 09:11:43 -04:00
Ravi Khadiwala e7ec47aa25 Increase DeviceCheck key limit 2026-08-12 09:10:04 -04:00
Jon Chambers 7d39f2952b Update AccountControllerTest for accounts that may not have phone numbers 2026-08-12 09:09:29 -04:00
Chris Eager 7ec1f78406 Add numberless case to AccountsManagerConcurrentModificationIntegrationTest 2026-08-12 09:08:51 -04:00
Ravi Khadiwala 9d601047c8 Add numberless variants to username tests 2026-08-12 09:07:42 -04:00
Ravi Khadiwala d99515e31e Avoid calling method when mocking a stub from another class 2026-08-11 15:56:28 -05:00
Jon Chambers edce40958b Update to the latest version of the spam filter 2026-08-11 12:13:34 -04:00
Jon Chambers 4d431fbdbf Update AccountsManagerChangeNumberIntegrationTest for accounts that may not have phone numbers 2026-08-11 12:11:41 -04:00
Chris Eager fcf12face8 Add explicit check for recovery password in AccountsManger#create 2026-08-11 09:10:57 -07:00
Jon Chambers e36e740bc0 Update AccountTest for cases where accounts may not have phone numbers 2026-08-11 09:08:13 -07:00
Katherine Yen 10c98c5f87 Update Redis account retrieval tests in AccountsManager 2026-08-11 09:03:18 -07:00
Katherine Yen 8d0ea9f67a Don't assume phone number identifier presence in parsing account JSON or writing accounts to Redis 2026-08-11 09:03:18 -07:00
Chris Eager 9870accbae Use AccountLockManager#withSingleAccountLock when appropriate 2026-08-11 09:00:20 -07:00
Ameya Lokare 6610c37fea Pass missing argument to AccounstTest#createNumberless 2026-08-11 08:52:47 -07:00
Jon Chambers 2d705a23f5 Update number discoverability tests/behavior for accounts without numbers in AccountControllerV2 2026-08-11 08:44:21 -07:00
Ravi Khadiwala 5c29072212 Paramterize some username tests on e164 presence 2026-08-11 10:43:06 -05:00
Ravi Khadiwala af6e2c2f2b Don't assume presence of phone numbers in account deletion 2026-08-11 10:40:19 -05:00
Ameya Lokare 713ab0314e Allow registration of Signal Logins 2026-08-11 08:28:34 -07:00
Katherine 3201ab324e Don't assume the presence of phone number-related fields in account creation or reclamation 2026-08-11 11:24:18 -04:00
Jon Chambers 5eb1a76e99 Update AccountIdentityResponseBuilderTest for accounts that may not have phone numbers 2026-08-11 09:16:46 -04:00
Jon Chambers 132c9531e1 Update account gRPC tests for accounts that may not have phone numbers 2026-08-11 09:16:46 -04:00
Jon Chambers a86cd5dcf5 Update AccountChangeValidator and tests for accounts that may not have phone numbers 2026-08-11 09:14:43 -04:00
Chris Eager 65175c16d0 Use getAccountIdentifier in AccountAuthenticator 2026-08-11 09:12:36 -04:00
Chris Eager f6ea81cf5e Use UUIDs in WebSocketAccountAuthenticatorTest 2026-08-11 09:12:36 -04:00
Chris Eager 1c12a9a258 Use getAccountIdentifier in RemoveExpiredAccountsCommand 2026-08-11 09:12:36 -04:00
Chris Eager b63f176ad7 Use getAccountIdentifier in device transfer context 2026-08-11 09:12:36 -04:00
Jon Chambers d69a5f1f33 Actually use the deviceId parameter in AccountsGrpcServiceTest#clearRegistrationLock 2026-08-11 09:11:50 -04:00
Jon Chambers 101fa4010d Avoid duplicate alternate forms of Benin phone numbers 2026-08-11 09:10:28 -04:00
Jon Chambers fba6037e3a Add a (failing!) test for Benin numbers that have ten-digit national significant numbers 2026-08-11 09:10:28 -04:00
Ravi Khadiwala 7e863e9dba Add some details to unexpectedly unacked purchaseTokens 2026-08-07 14:39:44 -05:00
Ravi Khadiwala 1ebb4177fe Move some level configuration to an enum 2026-08-07 14:39:13 -05:00
Ravi Khadiwala 3e5ccb82de Calculate the IssuedReceipt TTL from the receipt expiration 2026-08-07 14:39:13 -05:00
Ravi Khadiwala 6e3106297b Scope multi-attempt configuration in IssuedReceiptsManager to subscriptions only 2026-08-07 14:39:13 -05:00
Ravi Khadiwala d6b80dfd16 Add LoginPurchaseController 2026-08-07 14:39:13 -05:00
Ravi Khadiwala 7a34493d53 Add LoginPurchaseManager 2026-08-07 14:39:13 -05:00
Ravi Khadiwala 894cd8e0a3 Implement claimOneTimePurchase in IAP processors 2026-08-07 14:18:00 -05:00
Chris Eager 674d03ef0c Add issueAuthCredentialZkcWithoutPni to GroupCredentials issuance 2026-08-07 14:36:58 -04:00
Chris Eager f8a5e59a30 Update to libsignal 0.100.0 2026-08-07 14:36:58 -04:00
Jon Chambers 5f465a9f32 Replace trivial update with a ConditionCheck for recovery password migration 2026-08-07 14:36:33 -04:00
Jon Chambers 4e329ae48f Fix inverted argument order for account recovery passwords 2026-08-07 14:36:22 -04:00
Jon Chambers 2dd46b3b85 Add temporary plumbing and a command to migrate account recovery passwords 2026-08-05 15:10:19 -04:00
Jon Chambers 57c3fe949e Update to the latest version of the spam filter 2026-08-05 15:07:58 -04:00
Jon Chambers 453222ba17 Set/remove account recovery passwords alongside phone number recovery passwords 2026-08-05 14:50:00 -04:00
Jon Chambers c64aeec36a Add a public "update account with additional write items" method 2026-08-05 14:50:00 -04:00
Jon Chambers 8cbc8b0ce6 Add accountRecoveryPassword to accounts 2026-08-05 14:50:00 -04:00
Jon Chambers f4f2ffff21 Reframe "registration recovery passwords" as "phone number recovery passwords" 2026-08-05 14:50:00 -04:00
Ravi Khadiwala 5b6d6f28c9 Add an interface for one-time purchase retrieval 2026-08-05 13:24:14 -05:00
Ravi Khadiwala e4b09112f1 Make grpc ListMedia limit optional 2026-08-05 13:20:09 -05:00
Ravi Khadiwala cbc89f541c Tag OneTimeDonationsManager metric with provider 2026-08-05 13:19:46 -05:00
Jon Chambers 8c86e2e5ef Update to the latest version of the spam filter 2026-08-03 10:35:56 -04:00
dependabot[bot] 376f3b22d7 Bump the minor-actions-dependencies group with 3 updates
Bumps the minor-actions-dependencies group with 3 updates: [actions/checkout](https://github.com/actions/checkout), [actions/setup-java](https://github.com/actions/setup-java) and [aws-actions/configure-aws-credentials](https://github.com/aws-actions/configure-aws-credentials).


Updates `actions/checkout` from 7.0.0 to 7.0.1
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0...3d3c42e5aac5ba805825da76410c181273ba90b1)

Updates `actions/setup-java` from 5.4.0 to 5.6.0
- [Release notes](https://github.com/actions/setup-java/releases)
- [Commits](https://github.com/actions/setup-java/compare/1bcf9fb12cf4aa7d266a90ae39939e61372fe520...03ad4de0992f5dab5e18fcb136590ce7c4a0ac95)

Updates `aws-actions/configure-aws-credentials` from 6.2.1 to 6.2.3
- [Release notes](https://github.com/aws-actions/configure-aws-credentials/releases)
- [Changelog](https://github.com/aws-actions/configure-aws-credentials/blob/main/CHANGELOG.md)
- [Commits](https://github.com/aws-actions/configure-aws-credentials/compare/254c19bd240aabef8777f48595e9d2d7b972184b...e6de054238d6b7531b4efff3b6587d9aade6a06c)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-version: 7.0.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-actions-dependencies
- dependency-name: actions/setup-java
  dependency-version: 5.6.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-actions-dependencies
- dependency-name: aws-actions/configure-aws-credentials
  dependency-version: 6.2.3
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-actions-dependencies
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-08-03 10:35:00 -04:00
Ravi Khadiwala 1e2a873753 Remove test subscriber-id 2026-08-03 10:01:12 -04:00
Jon Chambers e60daa75a8 Don't assume presence of phone numbers for spam reports 2026-08-03 09:39:44 -04:00
Ameya Lokare a3d01a94d4 Update metrics for spam reports from numberless accounts 2026-08-03 09:16:59 -04:00
Katherine Yen 0117ed1a0b Register KeyTransparencyGrpcService 2026-08-03 09:16:37 -04:00
Jonathan Klabunde Tomer f3194cf45b Update to the latest version of the spam filter 2026-07-29 16:15:34 -07:00
ravi-signal 29c5f8b218 Do not allow accounts without phone numbers to perform PNI key operations 2026-07-29 16:13:16 -07:00
Jonathan Klabunde Tomer d7447b111d Add support for pessimistic locking of phone-number-less accounts 2026-07-29 15:44:31 -07:00
Jon Chambers 850286dbfc Don't assume presence of phone numbers when regenerating secondary tables 2026-07-29 15:42:13 -07:00
ravi-signal f55a0af55e Add deprecation annotation to getIdentityKey 2026-07-29 15:42:02 -07:00
Jon Chambers 2f1843d5d2 Don't assume presence of phone numbers when checking for prohibited payment regions 2026-07-29 15:41:51 -07:00
Jon Chambers 78e7e992da Add utility methods for getting country/region codes for accounts that may not have phone numbers 2026-07-29 15:41:40 -07:00
ameya-signal ef2d25704e Don't allow or set registration lock on accounts with no phone number 2026-07-29 15:41:22 -07:00
Jon Chambers fc44fb1235 Fix a comparison between incompatible types 2026-07-29 17:09:16 -04:00
Jon Chambers 20dc6390b9 Don't set phone number identity keys in tests unless a phone number is also present 2026-07-29 15:06:37 -04:00
Jon Chambers 262f7de742 Update to the latest version of the spam filter 2026-07-29 14:46:40 -04:00
Jon Chambers fad055aa44 Reject attempts to change phone numbers if the account doesn't have a number in the first place 2026-07-29 14:44:58 -04:00
Jon Chambers 9426d0bd9e Revert "Reject attempts to change phone numbers if the account doesn't have a number in the first place"
This reverts commit 87cdc6f84a8323c4dce6a85e3f8337cf8e1d94cd.
2026-07-29 14:44:58 -04:00
Jon Chambers e1d2b3aac7 Reject attempts to change phone numbers if the account doesn't have a number in the first place 2026-07-29 14:44:58 -04:00
Jonathan Klabunde Tomer d415a3365a add optional getter for PNI identity key 2026-07-29 14:42:43 -04:00
Jon Chambers 8fc63dd4d6 Don't generate "includes e164" delivery certificates for accounts without phone numbers 2026-07-29 14:42:04 -04:00
Jon Chambers ac4d61978b Don't assume presence of phone numbers when generating account identity responses 2026-07-29 14:41:26 -04:00
Jon Chambers 79935ea22a Don't assume presence of phone numbers in integration tests 2026-07-29 14:41:26 -04:00
Jon Chambers 478a4bda7d Don't assume presence of phone numbers in account data reports 2026-07-29 14:40:08 -04:00
Jon Chambers 70d0bda779 Make "discoverable by phone number" contingent upon having a phone number in the first place 2026-07-29 14:40:08 -04:00
Ameya Lokare 4f4284d1cc Don't assume destination account phone number exists when updating spam report metrics 2026-07-29 14:39:37 -04:00
Ameya Lokare c12206ace0 Only update parsed time zone metric if the phone number was present 2026-07-29 14:38:39 -04:00
Ameya Lokare d46818e465 Default to preferred server-local time if account has no phone number 2026-07-29 14:38:39 -04:00
Jon Chambers 4440022796 Update to the latest version of the spam filter 2026-07-28 17:45:43 -04:00
Jon Chambers f1d2ce2814 Add methods for getting phone numbers and phone number identifiers that do not assume presence 2026-07-28 17:30:06 -04:00
Jon Chambers 1072d9d39b Convert Account documentation to Markdown 2026-07-28 17:30:06 -04:00
Jon Chambers 20cf3d7429 Rename Account#getUUID() to Account#getAccountIdentifier() 2026-07-28 17:30:06 -04:00
Jon Chambers 7b472afbcb Remove an ancient test 2026-07-28 17:30:06 -04:00
Katherine Yen c6619c7488 Adjust metric name in TrimOversizedFoundationDbMessageQueuesCommand 2026-07-28 17:29:39 -04:00
Jon Chambers 751b4b6ecc Detect and measure FoundationDB message consumer conflicts 2026-07-28 17:28:58 -04:00
Ravi Khadiwala 888b746294 Remove badges from product configuration 2026-07-28 16:20:05 -05:00
Ravi Khadiwala 8e9253181c Add badges to remote config 2026-07-28 16:20:05 -05:00
Ravi Khadiwala 257dd76b68 Implement grpc remote config 2026-07-28 16:13:16 -05:00
Ravi Khadiwala 76ca81d9f1 Sink remote config logic down a layer 2026-07-28 16:13:16 -05:00
Jon Chambers 0eeb6605db Use a programmatically-generated keystore in OmnibusH2ServerTest 2026-07-24 09:26:06 -04:00
Jon Chambers ac8d5f81bf Use a programmatically-generated keystore in SniMapperTest 2026-07-24 09:26:06 -04:00
Jon Chambers 3447345d02 Update to the latest version of the spam filter 2026-07-23 16:49:40 -04:00
Jon Chambers ab0235a574 Update to Ubuntu 26.04 as a base image 2026-07-23 16:49:05 -04:00
Jon Chambers 38c5a292fb Update test container images 2026-07-23 16:49:05 -04:00
Jon Chambers 35663956b5 Update deployment base image and specify full image rather than just the SHA256 2026-07-23 16:49:05 -04:00
Jon Chambers d5a0c63de8 Update Maven Wrapper 2026-07-23 16:49:05 -04:00
ravi-signal 2f0a081d2e Handle duplicated tokens in /v2/svr/auth/check 2026-07-23 15:48:33 -05:00
Chris Eager adfab44ed6 Opt out of anonymous Stripe telemetry_id 2026-07-23 16:48:09 -04:00
Katherine Yen 24cea1926a Add timeout, retries, and priority to trimQueue operation 2026-07-23 16:47:56 -04:00
Ravi Khadiwala 242a5f6a78 Allow ignoring the return value of status asserts 2026-07-23 16:47:40 -04:00
Katherine Yen 45dab47ea8 Disable flaky FoundationDbMessageStoreTest#trimQueue 2026-07-22 15:15:55 -04:00
Katherine Yen 0587a08017 Disable flaky FoundationDbMessageStoreTest#estimateQueueSizeAndSplitPoints 2026-07-22 15:11:38 -04:00
Ravi Khadiwala 02d6138848 Add marker for unexpected error logs 2026-07-22 14:35:17 -04:00
Jon Chambers 07444bffb4 Limit message range size based on outstanding demand 2026-07-22 14:32:26 -04:00
Katherine 4f8ca893f0 Add a crawler to trim oversized queues in FoundationDB 2026-07-22 11:43:22 -04:00
Ravi Khadiwala 7bb94bc99e Drop username_hash from ConfirmUsernameResponse 2026-07-22 10:34:44 -05:00
Ravi Khadiwala f6ca5e55a5 Make timeout for storage usage queries configurable 2026-07-22 10:34:23 -05:00
Andrew 4e2bca886e Specify AccountIdentifiers contract more tightly 2026-07-22 10:33:55 -05:00
ameya-signal 088037b412 Fix watch leak when watch is set after subscription is disposed 2026-07-21 10:26:38 -05:00
ameya-signal 548c688df2 Add counter for FoundationDB watch operations 2026-07-21 10:26:29 -05:00
Chris Eager 8b103030ed Update to the latest version of the spam filter 2026-07-21 10:26:18 -05:00
Ravi Khadiwala 6a8bf7f78e Temporarily disable flaky test 2026-07-17 13:44:14 -05:00
265 changed files with 9932 additions and 4086 deletions

No files matched your search

+2 -2
View File
@@ -11,8 +11,8 @@ jobs:
contents: write
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
- uses: actions/setup-java@1bcf9fb12cf4aa7d266a90ae39939e61372fe520 # v5.4.0
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: actions/setup-java@03ad4de0992f5dab5e18fcb136590ce7c4a0ac95 # v5.6.0
with:
distribution: 'temurin'
java-version-file: .java-version
+3 -3
View File
@@ -19,13 +19,13 @@ jobs:
contents: read
issues: write
steps:
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
- uses: actions/setup-java@1bcf9fb12cf4aa7d266a90ae39939e61372fe520 # v5.4.0
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: actions/setup-java@03ad4de0992f5dab5e18fcb136590ce7c4a0ac95 # v5.6.0
with:
distribution: 'temurin'
java-version-file: .java-version
cache: 'maven'
- uses: aws-actions/configure-aws-credentials@254c19bd240aabef8777f48595e9d2d7b972184b # v6.2.1
- uses: aws-actions/configure-aws-credentials@e6de054238d6b7531b4efff3b6587d9aade6a06c # v6.2.3
name: Configure AWS credentials from Test account
with:
role-to-assume: ${{ vars.AWS_ROLE }}
+14 -12
View File
@@ -12,7 +12,7 @@ on:
jobs:
build:
runs-on: ubuntu-latest
container: ubuntu:24.04
container: ubuntu:26.04
timeout-minutes: 20
services:
@@ -28,23 +28,15 @@ jobs:
options: --name foundationdb1
steps:
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
- name: Set up JDK
uses: actions/setup-java@1bcf9fb12cf4aa7d266a90ae39939e61372fe520 # v5.4.0
with:
distribution: 'temurin'
java-version-file: .java-version
cache: 'maven'
env:
# work around an issue with actions/runner setting an incorrect HOME in containers, which breaks maven caching
# https://github.com/actions/setup-java/issues/356
HOME: /root
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- 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
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
@@ -57,6 +49,16 @@ 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@03ad4de0992f5dab5e18fcb136590ce7c4a0ac95 # v5.6.0
with:
distribution: 'temurin'
java-version-file: .java-version
cache: 'maven'
env:
# work around an issue with actions/runner setting an incorrect HOME in containers, which breaks maven caching
# https://github.com/actions/setup-java/issues/356
HOME: /root
- name: Configure FoundationDB0 database
run: docker exec foundationdb0 /usr/bin/fdbcli --exec 'configure new single memory'
- name: Configure FoundationDB1 database
BIN
View File
Binary file not shown.
+4 -3
View File
@@ -14,7 +14,8 @@
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.14/apache-maven-3.9.14-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.3.4/maven-wrapper-3.3.4.jar
distributionSha256Sum=55fadd669532a3205d5db95f490bf13971d8b0843526f407f29db0e61f074ab3
wrapperVersion=3.3.4
distributionType=only-script
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.16/apache-maven-3.9.16-bin.zip
distributionSha256Sum=5af3b743dd8b876b5c45da33b676251e5f1687712644abb4ee519ca56e1d89ce
wrapperSha256Sum=4e2fbf6554bc8a4702cdfdd3bef464f423393d784ddbb037216320ce55d5e4e1
@@ -17,8 +17,8 @@ import org.whispersystems.textsecuregcm.metrics.NoopAwsSdkMetricPublisher;
import org.whispersystems.textsecuregcm.registration.VerificationSession;
import org.whispersystems.textsecuregcm.storage.ChangeNumberWaitingPeriods;
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswords;
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
import org.whispersystems.textsecuregcm.storage.PhoneNumberRecoveryPasswords;
import org.whispersystems.textsecuregcm.storage.PhoneNumberRecoveryPasswordsManager;
import org.whispersystems.textsecuregcm.storage.VerificationSessionManager;
import org.whispersystems.textsecuregcm.storage.VerificationSessions;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
@@ -28,7 +28,7 @@ import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
public class IntegrationTools {
private final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager;
private final PhoneNumberRecoveryPasswordsManager phoneNumberRecoveryPasswordsManager;
private final VerificationSessionManager verificationSessionManager;
@@ -45,14 +45,14 @@ public class IntegrationTools {
final DynamoDbClient dynamoDbClient =
config.dynamoDbClient().buildSyncClient(credentialsProvider, new NoopAwsSdkMetricPublisher());
final RegistrationRecoveryPasswords registrationRecoveryPasswords = new RegistrationRecoveryPasswords(
final PhoneNumberRecoveryPasswords phoneNumberRecoveryPasswords = new PhoneNumberRecoveryPasswords(
config.dynamoDbTables().registrationRecovery(), Duration.ofDays(1), dynamoDbClient, Clock.systemUTC());
final VerificationSessions verificationSessions = new VerificationSessions(
dynamoDbClient, config.dynamoDbTables().verificationSessions(), Clock.systemUTC());
return new IntegrationTools(
new RegistrationRecoveryPasswordsManager(registrationRecoveryPasswords),
new PhoneNumberRecoveryPasswordsManager(phoneNumberRecoveryPasswords),
new VerificationSessionManager(verificationSessions),
new PhoneNumberIdentifiers(dynamoDbAsyncClient, config.dynamoDbTables().phoneNumberIdentifiers()),
new ChangeNumberWaitingPeriods(config.dynamoDbTables().changeNumberWaitingPeriods(), dynamoDbClient)
@@ -60,11 +60,11 @@ public class IntegrationTools {
}
private IntegrationTools(
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager,
final PhoneNumberRecoveryPasswordsManager phoneNumberRecoveryPasswordsManager,
final VerificationSessionManager verificationSessionManager,
final PhoneNumberIdentifiers phoneNumberIdentifiers,
final ChangeNumberWaitingPeriods changeNumberWaitingPeriods) {
this.registrationRecoveryPasswordsManager = registrationRecoveryPasswordsManager;
this.phoneNumberRecoveryPasswordsManager = phoneNumberRecoveryPasswordsManager;
this.verificationSessionManager = verificationSessionManager;
this.phoneNumberIdentifiers = phoneNumberIdentifiers;
this.changeNumberWaitingPeriods = changeNumberWaitingPeriods;
@@ -74,7 +74,7 @@ public class IntegrationTools {
try {
final UUID pni = phoneNumberIdentifiers
.getPhoneNumberIdentifier(phoneNumber).get(5, TimeUnit.SECONDS);
registrationRecoveryPasswordsManager.store(pni, password);
phoneNumberRecoveryPasswordsManager.store(pni, password);
} catch (ExecutionException | InterruptedException | TimeoutException e) {
throw new RuntimeException("failed to get pni", e);
}
@@ -96,14 +96,15 @@ public final class Operations {
// register account
final RegistrationRequest registrationRequest = new RegistrationRequest(null,
registrationPassword,
null,
accountAttributes,
true,
new IdentityKey(aciIdentityKeyPair.getPublicKey()),
new IdentityKey(pniIdentityKeyPair.getPublicKey()),
new DeviceActivationRequest(generateSignedECPreKey(1, aciIdentityKeyPair),
generateSignedECPreKey(2, pniIdentityKeyPair),
Optional.of(generateSignedECPreKey(2, pniIdentityKeyPair)),
generateSignedKEMPreKey(3, aciIdentityKeyPair),
generateSignedKEMPreKey(4, pniIdentityKeyPair),
Optional.of(generateSignedKEMPreKey(4, pniIdentityKeyPair)),
Optional.empty(),
Optional.empty()));
@@ -112,7 +113,7 @@ public final class Operations {
.executeExpectSuccess(AccountIdentityResponse.class);
user.setAciUuid(registrationResponse.uuid());
user.setPniUuid(registrationResponse.pni());
registrationResponse.pni().ifPresent(user::setPniUuid);
return user;
}
@@ -14,6 +14,7 @@ import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import org.signal.libsignal.protocol.IdentityKey;
@@ -26,6 +27,7 @@ import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import javax.annotation.Nullable;
public class TestUser {
@@ -39,8 +41,10 @@ public class TestUser {
private final byte[] unidentifiedAccessKey;
@Nullable
private String phoneNumber;
@Nullable
private IdentityKeyPair pniIdentityKey;
private String accountPassword;
@@ -49,6 +53,7 @@ public class TestUser {
private UUID aciUuid;
@Nullable
private UUID pniUuid;
@@ -103,12 +108,12 @@ public class TestUser {
return aciIdentityKey;
}
public String phoneNumber() {
return phoneNumber;
public Optional<String> phoneNumber() {
return Optional.ofNullable(phoneNumber);
}
public IdentityKeyPair pniIdentityKey() {
return pniIdentityKey;
public Optional<IdentityKeyPair> pniIdentityKey() {
return Optional.ofNullable(pniIdentityKey);
}
public String accountPassword() {
@@ -123,13 +128,13 @@ public class TestUser {
return aciUuid;
}
public UUID pniUuid() {
return pniUuid;
public Optional<UUID> pniUuid() {
return Optional.ofNullable(pniUuid);
}
public AccountAttributes accountAttributes() {
return new AccountAttributes(true, registrationId, pniRegistrationId, "".getBytes(StandardCharsets.UTF_8), "", true,
DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES)
DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES, null)
.setUnidentifiedAccessKey(unidentifiedAccessKey)
.setRecoveryPassword(registrationPassword);
}
@@ -138,15 +143,15 @@ public class TestUser {
this.aciUuid = aciUuid;
}
public void setPniUuid(final UUID pniUuid) {
public void setPniUuid(@Nullable final UUID pniUuid) {
this.pniUuid = pniUuid;
}
public void setPhoneNumber(final String phoneNumber) {
public void setPhoneNumber(@Nullable final String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public void setPniIdentityKey(final IdentityKeyPair pniIdentityKey) {
public void setPniIdentityKey(@Nullable final IdentityKeyPair pniIdentityKey) {
this.pniIdentityKey = pniIdentityKey;
}
@@ -13,6 +13,7 @@ import java.util.Base64;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.http.HttpStatus;
import org.junit.jupiter.api.Test;
@@ -72,7 +73,7 @@ public class AccountTest {
assertEquals(user.aciUuid(), accountIdentityResponse.uuid());
assertNotEquals(user.pniUuid(), accountIdentityResponse.pni());
assertEquals(targetNumber, accountIdentityResponse.number());
assertEquals(Optional.of(targetNumber), accountIdentityResponse.number());
} finally {
Operations.deleteUser(user);
}
@@ -11,20 +11,16 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
import com.google.common.net.HttpHeaders;
import jakarta.ws.rs.core.MediaType;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import jakarta.ws.rs.core.MediaType;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.entities.IncomingMessage;
import org.whispersystems.textsecuregcm.entities.IncomingMessageList;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
Vendored
+234 -247
View File
@@ -19,290 +19,277 @@
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Apache Maven Wrapper startup batch script, version 3.2.0
#
# Required ENV vars:
# ------------------
# JAVA_HOME - location of a JDK home dir
# Apache Maven Wrapper startup batch script, version 3.3.4
#
# Optional ENV vars
# -----------------
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
# e.g. to debug Maven itself, use
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
# JAVA_HOME - location of a JDK home dir, required when download maven via java source
# MVNW_REPOURL - repo url base for downloading maven distribution
# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output
# ----------------------------------------------------------------------------
if [ -z "$MAVEN_SKIP_RC" ] ; then
set -euf
[ "${MVNW_VERBOSE-}" != debug ] || set -x
if [ -f /usr/local/etc/mavenrc ] ; then
. /usr/local/etc/mavenrc
fi
if [ -f /etc/mavenrc ] ; then
. /etc/mavenrc
fi
if [ -f "$HOME/.mavenrc" ] ; then
. "$HOME/.mavenrc"
fi
fi
# OS specific support. $var _must_ be set to either true or false.
cygwin=false;
darwin=false;
mingw=false
# OS specific support.
native_path() { printf %s\\n "$1"; }
case "$(uname)" in
CYGWIN*) cygwin=true ;;
MINGW*) mingw=true;;
Darwin*) darwin=true
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
if [ -z "$JAVA_HOME" ]; then
if [ -x "/usr/libexec/java_home" ]; then
JAVA_HOME="$(/usr/libexec/java_home)"; export JAVA_HOME
else
JAVA_HOME="/Library/Java/Home"; export JAVA_HOME
fi
fi
;;
CYGWIN* | MINGW*)
[ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")"
native_path() { cygpath --path --windows "$1"; }
;;
esac
if [ -z "$JAVA_HOME" ] ; then
if [ -r /etc/gentoo-release ] ; then
JAVA_HOME=$(java-config --jre-home)
fi
fi
# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin ; then
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=$(cygpath --unix "$JAVA_HOME")
[ -n "$CLASSPATH" ] &&
CLASSPATH=$(cygpath --path --unix "$CLASSPATH")
fi
# For Mingw, ensure paths are in UNIX format before anything is touched
if $mingw ; then
[ -n "$JAVA_HOME" ] && [ -d "$JAVA_HOME" ] &&
JAVA_HOME="$(cd "$JAVA_HOME" || (echo "cannot cd into $JAVA_HOME."; exit 1); pwd)"
fi
if [ -z "$JAVA_HOME" ]; then
javaExecutable="$(which javac)"
if [ -n "$javaExecutable" ] && ! [ "$(expr "\"$javaExecutable\"" : '\([^ ]*\)')" = "no" ]; then
# readlink(1) is not available as standard on Solaris 10.
readLink=$(which readlink)
if [ ! "$(expr "$readLink" : '\([^ ]*\)')" = "no" ]; then
if $darwin ; then
javaHome="$(dirname "\"$javaExecutable\"")"
javaExecutable="$(cd "\"$javaHome\"" && pwd -P)/javac"
else
javaExecutable="$(readlink -f "\"$javaExecutable\"")"
fi
javaHome="$(dirname "\"$javaExecutable\"")"
javaHome=$(expr "$javaHome" : '\(.*\)/bin')
JAVA_HOME="$javaHome"
export JAVA_HOME
fi
fi
fi
if [ -z "$JAVACMD" ] ; then
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# set JAVACMD and JAVACCMD
set_java_home() {
# For Cygwin and MinGW, ensure paths are in Unix format before anything is touched
if [ -n "${JAVA_HOME-}" ]; then
if [ -x "$JAVA_HOME/jre/sh/java" ]; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
JAVACCMD="$JAVA_HOME/jre/sh/javac"
else
JAVACMD="$JAVA_HOME/bin/java"
JAVACCMD="$JAVA_HOME/bin/javac"
if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then
echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2
echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2
return 1
fi
fi
else
JAVACMD="$(\unset -f command 2>/dev/null; \command -v java)"
fi
fi
JAVACMD="$(
'set' +e
'unset' -f command 2>/dev/null
'command' -v java
)" || :
JAVACCMD="$(
'set' +e
'unset' -f command 2>/dev/null
'command' -v javac
)" || :
if [ ! -x "$JAVACMD" ] ; then
echo "Error: JAVA_HOME is not defined correctly." >&2
echo " We cannot execute $JAVACMD" >&2
exit 1
fi
if [ -z "$JAVA_HOME" ] ; then
echo "Warning: JAVA_HOME environment variable is not set."
fi
# traverses directory structure from process work directory to filesystem root
# first directory with .mvn subdirectory is considered project base directory
find_maven_basedir() {
if [ -z "$1" ]
then
echo "Path not specified to find_maven_basedir"
return 1
fi
basedir="$1"
wdir="$1"
while [ "$wdir" != '/' ] ; do
if [ -d "$wdir"/.mvn ] ; then
basedir=$wdir
break
if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then
echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2
return 1
fi
# workaround for JBEAP-8937 (on Solaris 10/Sparc)
if [ -d "${wdir}" ]; then
wdir=$(cd "$wdir/.." || exit 1; pwd)
fi
# end of workaround
fi
}
# hash string like Java String::hashCode
hash_string() {
str="${1:-}" h=0
while [ -n "$str" ]; do
char="${str%"${str#?}"}"
h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296))
str="${str#?}"
done
printf '%s' "$(cd "$basedir" || exit 1; pwd)"
printf %x\\n $h
}
# concatenates all lines of a file
concat_lines() {
if [ -f "$1" ]; then
# Remove \r in case we run on Windows within Git Bash
# and check out the repository with auto CRLF management
# enabled. Otherwise, we may read lines that are delimited with
# \r\n and produce $'-Xarg\r' rather than -Xarg due to word
# splitting rules.
tr -s '\r\n' ' ' < "$1"
fi
verbose() { :; }
[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; }
die() {
printf %s\\n "$1" >&2
exit 1
}
log() {
if [ "$MVNW_VERBOSE" = true ]; then
printf '%s\n' "$1"
fi
trim() {
# MWRAPPER-139:
# Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds.
# Needed for removing poorly interpreted newline sequences when running in more
# exotic environments such as mingw bash on Windows.
printf "%s" "${1}" | tr -d '[:space:]'
}
BASE_DIR=$(find_maven_basedir "$(dirname "$0")")
if [ -z "$BASE_DIR" ]; then
exit 1;
fi
scriptDir="$(dirname "$0")"
scriptName="$(basename "$0")"
MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}; export MAVEN_PROJECTBASEDIR
log "$MAVEN_PROJECTBASEDIR"
##########################################################################################
# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
# This allows using the maven wrapper in projects that prohibit checking in binary data.
##########################################################################################
wrapperJarPath="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar"
if [ -r "$wrapperJarPath" ]; then
log "Found $wrapperJarPath"
else
log "Couldn't find $wrapperJarPath, downloading it ..."
if [ -n "$MVNW_REPOURL" ]; then
wrapperUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar"
else
wrapperUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar"
fi
while IFS="=" read -r key value; do
# Remove '\r' from value to allow usage on windows as IFS does not consider '\r' as a separator ( considers space, tab, new line ('\n'), and custom '=' )
safeValue=$(echo "$value" | tr -d '\r')
case "$key" in (wrapperUrl) wrapperUrl="$safeValue"; break ;;
esac
done < "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.properties"
log "Downloading from: $wrapperUrl"
if $cygwin; then
wrapperJarPath=$(cygpath --path --windows "$wrapperJarPath")
fi
if command -v wget > /dev/null; then
log "Found wget ... using wget"
[ "$MVNW_VERBOSE" = true ] && QUIET="" || QUIET="--quiet"
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
wget $QUIET "$wrapperUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath"
else
wget $QUIET --http-user="$MVNW_USERNAME" --http-password="$MVNW_PASSWORD" "$wrapperUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath"
fi
elif command -v curl > /dev/null; then
log "Found curl ... using curl"
[ "$MVNW_VERBOSE" = true ] && QUIET="" || QUIET="--silent"
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
curl $QUIET -o "$wrapperJarPath" "$wrapperUrl" -f -L || rm -f "$wrapperJarPath"
else
curl $QUIET --user "$MVNW_USERNAME:$MVNW_PASSWORD" -o "$wrapperJarPath" "$wrapperUrl" -f -L || rm -f "$wrapperJarPath"
fi
else
log "Falling back to using Java to download"
javaSource="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/MavenWrapperDownloader.java"
javaClass="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/MavenWrapperDownloader.class"
# For Cygwin, switch paths to Windows format before running javac
if $cygwin; then
javaSource=$(cygpath --path --windows "$javaSource")
javaClass=$(cygpath --path --windows "$javaClass")
fi
if [ -e "$javaSource" ]; then
if [ ! -e "$javaClass" ]; then
log " - Compiling MavenWrapperDownloader.java ..."
("$JAVA_HOME/bin/javac" "$javaSource")
fi
if [ -e "$javaClass" ]; then
log " - Running MavenWrapperDownloader.java ..."
("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$wrapperUrl" "$wrapperJarPath") || rm -f "$wrapperJarPath"
fi
fi
fi
fi
##########################################################################################
# End of extension
##########################################################################################
# If specified, validate the SHA-256 sum of the Maven wrapper jar file
wrapperSha256Sum=""
# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties
while IFS="=" read -r key value; do
case "$key" in (wrapperSha256Sum) wrapperSha256Sum=$value; break ;;
case "${key-}" in
distributionUrl) distributionUrl=$(trim "${value-}") ;;
distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;;
esac
done < "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.properties"
if [ -n "$wrapperSha256Sum" ]; then
wrapperSha256Result=false
if command -v sha256sum > /dev/null; then
if echo "$wrapperSha256Sum $wrapperJarPath" | sha256sum -c - > /dev/null 2>&1; then
wrapperSha256Result=true
done <"$scriptDir/.mvn/wrapper/maven-wrapper.properties"
[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
case "${distributionUrl##*/}" in
maven-mvnd-*bin.*)
MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/
case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in
*AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;;
:Darwin*x86_64) distributionPlatform=darwin-amd64 ;;
:Darwin*arm64) distributionPlatform=darwin-aarch64 ;;
:Linux*x86_64*) distributionPlatform=linux-amd64 ;;
*)
echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2
distributionPlatform=linux-amd64
;;
esac
distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip"
;;
maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;;
*) MVN_CMD="mvn${scriptName#mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;;
esac
# apply MVNW_REPOURL and calculate MAVEN_HOME
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}"
distributionUrlName="${distributionUrl##*/}"
distributionUrlNameMain="${distributionUrlName%.*}"
distributionUrlNameMain="${distributionUrlNameMain%-bin}"
MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}"
MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")"
exec_maven() {
unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || :
exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD"
}
if [ -d "$MAVEN_HOME" ]; then
verbose "found existing MAVEN_HOME at $MAVEN_HOME"
exec_maven "$@"
fi
case "${distributionUrl-}" in
*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;;
*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;;
esac
# prepare tmp dir
if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then
clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; }
trap clean HUP INT TERM EXIT
else
die "cannot create temp dir"
fi
mkdir -p -- "${MAVEN_HOME%/*}"
# Download and Install Apache Maven
verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
verbose "Downloading from: $distributionUrl"
verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
# select .zip or .tar.gz
if ! command -v unzip >/dev/null; then
distributionUrl="${distributionUrl%.zip}.tar.gz"
distributionUrlName="${distributionUrl##*/}"
fi
# verbose opt
__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR=''
[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v
# normalize http auth
case "${MVNW_PASSWORD:+has-password}" in
'') MVNW_USERNAME='' MVNW_PASSWORD='' ;;
has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;;
esac
if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then
verbose "Found wget ... using wget"
wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl"
elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then
verbose "Found curl ... using curl"
curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl"
elif set_java_home; then
verbose "Falling back to use Java to download"
javaSource="$TMP_DOWNLOAD_DIR/Downloader.java"
targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName"
cat >"$javaSource" <<-END
public class Downloader extends java.net.Authenticator
{
protected java.net.PasswordAuthentication getPasswordAuthentication()
{
return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() );
}
public static void main( String[] args ) throws Exception
{
setDefault( new Downloader() );
java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() );
}
}
END
# For Cygwin/MinGW, switch paths to Windows format before running javac and java
verbose " - Compiling Downloader.java ..."
"$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java"
verbose " - Running Downloader.java ..."
"$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")"
fi
# If specified, validate the SHA-256 sum of the Maven distribution zip file
if [ -n "${distributionSha256Sum-}" ]; then
distributionSha256Result=false
if [ "$MVN_CMD" = mvnd.sh ]; then
echo "Checksum validation is not supported for maven-mvnd." >&2
echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
exit 1
elif command -v sha256sum >/dev/null; then
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c - >/dev/null 2>&1; then
distributionSha256Result=true
fi
elif command -v shasum > /dev/null; then
if echo "$wrapperSha256Sum $wrapperJarPath" | shasum -a 256 -c > /dev/null 2>&1; then
wrapperSha256Result=true
elif command -v shasum >/dev/null; then
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then
distributionSha256Result=true
fi
else
echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available."
echo "Please install either command, or disable validation by removing 'wrapperSha256Sum' from your maven-wrapper.properties."
echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2
echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
exit 1
fi
if [ $wrapperSha256Result = false ]; then
echo "Error: Failed to validate Maven wrapper SHA-256, your Maven wrapper might be compromised." >&2
echo "Investigate or delete $wrapperJarPath to attempt a clean download." >&2
echo "If you updated your Maven version, you need to update the specified wrapperSha256Sum property." >&2
if [ $distributionSha256Result = false ]; then
echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2
echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2
exit 1
fi
fi
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=$(cygpath --path --windows "$JAVA_HOME")
[ -n "$CLASSPATH" ] &&
CLASSPATH=$(cygpath --path --windows "$CLASSPATH")
[ -n "$MAVEN_PROJECTBASEDIR" ] &&
MAVEN_PROJECTBASEDIR=$(cygpath --path --windows "$MAVEN_PROJECTBASEDIR")
# unzip and move
if command -v unzip >/dev/null; then
unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip"
else
tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar"
fi
# Provide a "standardized" way to retrieve the CLI args that will
# work with both Windows and non-Windows executions.
MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $*"
export MAVEN_CMD_LINE_ARGS
# Find the actual extracted directory name (handles snapshots where filename != directory name)
actualDistributionDir=""
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
# First try the expected directory name (for regular distributions)
if [ -d "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" ]; then
if [ -f "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/bin/$MVN_CMD" ]; then
actualDistributionDir="$distributionUrlNameMain"
fi
fi
# shellcheck disable=SC2086 # safe args
exec "$JAVACMD" \
$MAVEN_OPTS \
$MAVEN_DEBUG_OPTS \
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
"-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"
# If not found, search for any directory with the Maven executable (for snapshots)
if [ -z "$actualDistributionDir" ]; then
# enable globbing to iterate over items
set +f
for dir in "$TMP_DOWNLOAD_DIR"/*; do
if [ -d "$dir" ]; then
if [ -f "$dir/bin/$MVN_CMD" ]; then
actualDistributionDir="$(basename "$dir")"
break
fi
fi
done
set -f
fi
if [ -z "$actualDistributionDir" ]; then
verbose "Contents of $TMP_DOWNLOAD_DIR:"
verbose "$(ls -la "$TMP_DOWNLOAD_DIR")"
die "Could not find Maven distribution directory in extracted archive"
fi
verbose "Found extracted Maven distribution directory: $actualDistributionDir"
printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$actualDistributionDir/mvnw.url"
mv -- "$TMP_DOWNLOAD_DIR/$actualDistributionDir" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME"
clean || :
exec_maven "$@"
Vendored
+154 -170
View File
@@ -1,3 +1,4 @@
<# : batch portion
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@@ -7,7 +8,7 @@
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM http://www.apache.org/licenses/LICENSE-2.0
@REM https://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@@ -18,188 +19,171 @@
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Apache Maven Wrapper startup batch script, version 3.2.0
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM Apache Maven Wrapper startup batch script, version 3.3.4
@REM
@REM Optional ENV vars
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM MVNW_REPOURL - repo url base for downloading maven distribution
@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM set title of command window
title %0
@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %*
if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %*
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
set WRAPPER_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar"
FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperUrl" SET WRAPPER_URL=%%B
@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0)
@SET __MVNW_CMD__=
@SET __MVNW_ERROR__=
@SET __MVNW_PSMODULEP_SAVE=%PSModulePath%
@SET PSModulePath=
@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @(
IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B)
)
@SET PSModulePath=%__MVNW_PSMODULEP_SAVE%
@SET __MVNW_PSMODULEP_SAVE=
@SET __MVNW_ARG0_NAME__=
@SET MVNW_USERNAME=
@SET MVNW_PASSWORD=
@IF NOT "%__MVNW_CMD__%"=="" ("%__MVNW_CMD__%" %*)
@echo Cannot start maven from wrapper >&2 && exit /b 1
@GOTO :EOF
: end batch / begin powershell #>
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
if exist %WRAPPER_JAR% (
if "%MVNW_VERBOSE%" == "true" (
echo Found %WRAPPER_JAR%
)
) else (
if not "%MVNW_REPOURL%" == "" (
SET WRAPPER_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar"
)
if "%MVNW_VERBOSE%" == "true" (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %WRAPPER_URL%
)
$ErrorActionPreference = "Stop"
if ($env:MVNW_VERBOSE -eq "true") {
$VerbosePreference = "Continue"
}
powershell -Command "&{"^
"$webclient = new-object System.Net.WebClient;"^
"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
"}"^
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%WRAPPER_URL%', '%WRAPPER_JAR%')"^
"}"
if "%MVNW_VERBOSE%" == "true" (
echo Finished downloading %WRAPPER_JAR%
)
)
@REM End of extension
# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties
$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl
if (!$distributionUrl) {
Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
}
@REM If specified, validate the SHA-256 sum of the Maven wrapper jar file
SET WRAPPER_SHA_256_SUM=""
FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperSha256Sum" SET WRAPPER_SHA_256_SUM=%%B
)
IF NOT %WRAPPER_SHA_256_SUM%=="" (
powershell -Command "&{"^
"$hash = (Get-FileHash \"%WRAPPER_JAR%\" -Algorithm SHA256).Hash.ToLower();"^
"If('%WRAPPER_SHA_256_SUM%' -ne $hash){"^
" Write-Output 'Error: Failed to validate Maven wrapper SHA-256, your Maven wrapper might be compromised.';"^
" Write-Output 'Investigate or delete %WRAPPER_JAR% to attempt a clean download.';"^
" Write-Output 'If you updated your Maven version, you need to update the specified wrapperSha256Sum property.';"^
" exit 1;"^
"}"^
"}"
if ERRORLEVEL 1 goto error
)
switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) {
"maven-mvnd-*" {
$USE_MVND = $true
$distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip"
$MVN_CMD = "mvnd.cmd"
break
}
default {
$USE_MVND = $false
$MVN_CMD = $script -replace '^mvnw','mvn'
break
}
}
@REM Provide a "standardized" way to retrieve the CLI args that will
@REM work with both Windows and non-Windows executions.
set MAVEN_CMD_LINE_ARGS=%*
# apply MVNW_REPOURL and calculate MAVEN_HOME
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
if ($env:MVNW_REPOURL) {
$MVNW_REPO_PATTERN = if ($USE_MVND -eq $False) { "/org/apache/maven/" } else { "/maven/mvnd/" }
$distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace "^.*$MVNW_REPO_PATTERN",'')"
}
$distributionUrlName = $distributionUrl -replace '^.*/',''
$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$',''
%MAVEN_JAVA_EXE% ^
%JVM_CONFIG_MAVEN_PROPS% ^
%MAVEN_OPTS% ^
%MAVEN_DEBUG_OPTS% ^
-classpath %WRAPPER_JAR% ^
"-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^
%WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end
$MAVEN_M2_PATH = "$HOME/.m2"
if ($env:MAVEN_USER_HOME) {
$MAVEN_M2_PATH = "$env:MAVEN_USER_HOME"
}
:error
set ERROR_CODE=1
if (-not (Test-Path -Path $MAVEN_M2_PATH)) {
New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null
}
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
$MAVEN_WRAPPER_DISTS = $null
if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) {
$MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists"
} else {
$MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists"
}
if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat"
if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd"
:skipRcPost
$MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain"
$MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join ''
$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME"
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%"=="on" pause
if (Test-Path -Path "$MAVEN_HOME" -PathType Container) {
Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME"
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
exit $?
}
if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE%
if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) {
Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl"
}
cmd /C exit /B %ERROR_CODE%
# prepare tmp dir
$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile
$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir"
$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null
trap {
if ($TMP_DOWNLOAD_DIR.Exists) {
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
}
}
New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null
# Download and Install Apache Maven
Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
Write-Verbose "Downloading from: $distributionUrl"
Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
$webclient = New-Object System.Net.WebClient
if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) {
$webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD)
}
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null
# If specified, validate the SHA-256 sum of the Maven distribution zip file
$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum
if ($distributionSha256Sum) {
if ($USE_MVND) {
Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties."
}
Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash
if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) {
Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property."
}
}
# unzip and move
Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null
# Find the actual extracted directory name (handles snapshots where filename != directory name)
$actualDistributionDir = ""
# First try the expected directory name (for regular distributions)
$expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain"
$expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD"
if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) {
$actualDistributionDir = $distributionUrlNameMain
}
# If not found, search for any directory with the Maven executable (for snapshots)
if (!$actualDistributionDir) {
Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object {
$testPath = Join-Path $_.FullName "bin/$MVN_CMD"
if (Test-Path -Path $testPath -PathType Leaf) {
$actualDistributionDir = $_.Name
}
}
}
if (!$actualDistributionDir) {
Write-Error "Could not find Maven distribution directory in extracted archive"
}
Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir"
Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -NewName $MAVEN_HOME_NAME | Out-Null
try {
Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null
} catch {
if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) {
Write-Error "fail to move MAVEN_HOME"
}
} finally {
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
}
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
+4 -5
View File
@@ -91,12 +91,11 @@
<!-- images to use in tests via testcontainers -->
<dynamodb.image>amazon/dynamodb-local:3.3.0@sha256:d89f8fcc6b1a39cb35976c248ed42a28c66ae00dc043099210f5571e42648ab4</dynamodb.image>
<localstack.image>localstack/localstack:4.13@sha256:46302bcb91a7e8008e6394be8afafdbfa40fb77a54d4046a38be35992042d5de</localstack.image>
<redis.image>redis:7.4-alpine@sha256:af1d0fc3f63b02b13ff7906c9baf7c5b390b8881ca08119cd570677fe2f60b55</redis.image>
<localstack.image>localstack/localstack:4.14@sha256:3ebc37595918b8accb852f8048fef2aff047d465167edd655528065b07bc364a</localstack.image>
<redis.image>redis:7.4-alpine@sha256:6ab0b6e7381779332f97b8ca76193e45b0756f38d4c0dcda72dbb3c32061ab99</redis.image>
<redis-cluster.image>docker.io/bitnamilegacy/redis-cluster:7.4.3@sha256:a53d023fdfaf8a8d7ddc58da040d3494e4cb45772644618ffa44c42dcd32b9af</redis-cluster.image>
<!-- eclipse-temurin:25.0.2_10-jre-noble (note: always use the multi-arch manifest *LIST* here) -->
<docker.image.sha256>d2975fcad8dc9ac2180c0c278c8ae7b3443d36cb80845cb0811c20d9463f5fee</docker.image.sha256>
<docker.image>eclipse-temurin:25-jre-resolute@sha256:17ddcc32b1f296155738c4b2f689208e46bf0cf4eb0b215c717717deb8b74b90</docker.image>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
@@ -286,7 +285,7 @@
<dependency>
<groupId>org.signal</groupId>
<artifactId>libsignal-server</artifactId>
<version>0.96.2</version>
<version>0.100.0</version>
</dependency>
<dependency>
<groupId>org.signal</groupId>
+6 -6
View File
@@ -74,7 +74,6 @@ appleDeviceCheck:
deviceCheck:
backupRedemptionDuration: P30D
backupRedemptionLevel: 201
dynamoDbClient:
region: us-west-2 # AWS Region
@@ -105,9 +104,8 @@ dynamoDbTables:
expiration: P7D # Duration of time until rows expire
issuedReceipts:
tableName: Example_IssuedReceipts
expiration: P30D # Duration of time until rows expire
generator: abcdefg12345678= # random base64-encoded binary sequence
maxIssuedReceiptsPerPaymentId:
maxReceiptsPerSubscriptionPayment:
STRIPE: 1
BRAINTREE: 1
GOOGLE_PLAY_BILLING: 1
@@ -366,7 +364,7 @@ badges:
- light: example-light.svg
dark: example-dark.svg
receiptLevels:
'1': TEST
ONE_TIME_DONATION: TEST
subscription: # configuration for Stripe subscriptions
badgeExpiration: P30D
@@ -385,14 +383,16 @@ subscription: # configuration for Stripe subscriptions
STRIPE: price_example # stripe Price ID
BRAINTREE: plan_example # braintree Plan ID
loginPurchase:
playProductId: login_example
appStoreProductId: login_example
oneTimeDonations:
sepaMaximumEuros: '10000'
boost:
level: 1
expiration: P90D
badge: EXAMPLE
gift:
level: 10
expiration: P90D
badge: EXAMPLE
currencies:
+7 -1
View File
@@ -492,6 +492,12 @@
<classifier>linux-x86_64</classifier>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-pkitesting</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-testsuite-common</artifactId>
@@ -726,7 +732,7 @@
</executions>
<configuration>
<from>
<image>eclipse-temurin@sha256:${docker.image.sha256}</image>
<image>${docker.image}</image>
<platforms>
<platform>
<architecture>amd64</architecture>
@@ -44,6 +44,7 @@ import org.whispersystems.textsecuregcm.configuration.HlrLookupConfiguration;
import org.whispersystems.textsecuregcm.configuration.IdlePrimaryDeviceReminderConfiguration;
import org.whispersystems.textsecuregcm.configuration.KeyTransparencyServiceConfiguration;
import org.whispersystems.textsecuregcm.configuration.LinkDeviceSecretConfiguration;
import org.whispersystems.textsecuregcm.configuration.LoginPurchaseConfiguration;
import org.whispersystems.textsecuregcm.configuration.MessageByteLimitCardinalityEstimatorConfiguration;
import org.whispersystems.textsecuregcm.configuration.MessageCacheConfiguration;
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration;
@@ -266,6 +267,11 @@ public class WhisperServerConfiguration extends Configuration {
@NotNull
private OneTimeDonationConfiguration oneTimeDonations;
@Valid
@JsonProperty
@NotNull
private LoginPurchaseConfiguration loginPurchase;
@Valid
@JsonProperty
@NotNull
@@ -532,6 +538,10 @@ public class WhisperServerConfiguration extends Configuration {
return oneTimeDonations;
}
public LoginPurchaseConfiguration getLoginPurchase() {
return loginPurchase;
}
public PagedSingleUseKEMPreKeyStoreConfiguration getPagedSingleUseKEMPreKeyStore() {
return pagedSingleUseKEMPreKeyStore;
}
@@ -110,6 +110,7 @@ import org.whispersystems.textsecuregcm.captcha.CaptchaChecker;
import org.whispersystems.textsecuregcm.captcha.CaptchaClient;
import org.whispersystems.textsecuregcm.captcha.RegistrationCaptchaManager;
import org.whispersystems.textsecuregcm.captcha.ShortCodeExpander;
import org.whispersystems.textsecuregcm.configuration.BadgeConfiguration;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.configuration.secrets.SecretStore;
import org.whispersystems.textsecuregcm.configuration.secrets.SecretsModule;
@@ -129,6 +130,7 @@ import org.whispersystems.textsecuregcm.controllers.DonationController;
import org.whispersystems.textsecuregcm.controllers.KeepAliveController;
import org.whispersystems.textsecuregcm.controllers.KeyTransparencyController;
import org.whispersystems.textsecuregcm.controllers.KeysController;
import org.whispersystems.textsecuregcm.controllers.LoginPurchaseController;
import org.whispersystems.textsecuregcm.controllers.MessageController;
import org.whispersystems.textsecuregcm.controllers.OneTimeDonationController;
import org.whispersystems.textsecuregcm.controllers.PaymentsController;
@@ -170,6 +172,7 @@ import org.whispersystems.textsecuregcm.grpc.ErrorMappingInterceptor;
import org.whispersystems.textsecuregcm.grpc.ExternalServiceDefinitions;
import org.whispersystems.textsecuregcm.grpc.GroupSendTokenUtil;
import org.whispersystems.textsecuregcm.grpc.GrpcAllowListInterceptor;
import org.whispersystems.textsecuregcm.grpc.KeyTransparencyGrpcService;
import org.whispersystems.textsecuregcm.grpc.KeysAnonymousGrpcService;
import org.whispersystems.textsecuregcm.grpc.KeysGrpcService;
import org.whispersystems.textsecuregcm.grpc.MessageDispatcher;
@@ -181,6 +184,7 @@ import org.whispersystems.textsecuregcm.grpc.PaymentsGrpcService;
import org.whispersystems.textsecuregcm.grpc.ProductConfigurationGrpcService;
import org.whispersystems.textsecuregcm.grpc.ProfileAnonymousGrpcService;
import org.whispersystems.textsecuregcm.grpc.ProfileGrpcService;
import org.whispersystems.textsecuregcm.grpc.RemoteConfigurationGrpcService;
import org.whispersystems.textsecuregcm.grpc.RequestAttributesInterceptor;
import org.whispersystems.textsecuregcm.grpc.SubscriptionsGrpcService;
import org.whispersystems.textsecuregcm.grpc.ValidatingInterceptor;
@@ -204,6 +208,7 @@ import org.whispersystems.textsecuregcm.mappers.CompletionExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.DeviceLimitExceededExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.GrpcStatusRuntimeExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.IOExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.IllegalStateExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.ImpossiblePhoneNumberExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.InvalidWebsocketAddressExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.JsonMappingExceptionMapper;
@@ -273,8 +278,8 @@ import org.whispersystems.textsecuregcm.storage.ProfilesManager;
import org.whispersystems.textsecuregcm.storage.ProfilesV2;
import org.whispersystems.textsecuregcm.storage.PushChallengeDynamoDb;
import org.whispersystems.textsecuregcm.storage.RedeemedReceiptsManager;
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswords;
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
import org.whispersystems.textsecuregcm.storage.PhoneNumberRecoveryPasswords;
import org.whispersystems.textsecuregcm.storage.PhoneNumberRecoveryPasswordsManager;
import org.whispersystems.textsecuregcm.storage.RemoteConfigs;
import org.whispersystems.textsecuregcm.storage.RemoteConfigsManager;
import org.whispersystems.textsecuregcm.storage.RepeatedUseECSignedPreKeyStore;
@@ -296,7 +301,9 @@ import org.whispersystems.textsecuregcm.subscriptions.AppleAppStoreManager;
import org.whispersystems.textsecuregcm.subscriptions.BankMandateTranslator;
import org.whispersystems.textsecuregcm.subscriptions.BraintreeManager;
import org.whispersystems.textsecuregcm.subscriptions.GooglePlayBillingManager;
import org.whispersystems.textsecuregcm.subscriptions.LoginPurchaseManager;
import org.whispersystems.textsecuregcm.subscriptions.PayPalDonationsTranslator;
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
import org.whispersystems.textsecuregcm.subscriptions.StripeManager;
import org.whispersystems.textsecuregcm.telephony.CarrierDataProvider;
import org.whispersystems.textsecuregcm.telephony.hlrlookup.HlrLookupCarrierDataProvider;
@@ -325,6 +332,7 @@ import org.whispersystems.textsecuregcm.workers.DeleteUserCommand;
import org.whispersystems.textsecuregcm.workers.IdleDeviceNotificationSchedulerFactory;
import org.whispersystems.textsecuregcm.workers.MessagePersisterServiceCommand;
import org.whispersystems.textsecuregcm.workers.NotifyIdleDevicesCommand;
import org.whispersystems.textsecuregcm.workers.PopulateAccountRecoveryPasswordsCommand;
import org.whispersystems.textsecuregcm.workers.ProcessScheduledJobsServiceCommand;
import org.whispersystems.textsecuregcm.workers.RegenerateSecondaryDynamoDbTableDataCommand;
import org.whispersystems.textsecuregcm.workers.RemoveExpiredAccountsCommand;
@@ -336,6 +344,7 @@ import org.whispersystems.textsecuregcm.workers.ScheduledApnPushNotificationSend
import org.whispersystems.textsecuregcm.workers.ServerVersionCommand;
import org.whispersystems.textsecuregcm.workers.SetRequestLoggingEnabledTask;
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.ZkParamsCommand;
@@ -395,6 +404,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
bootstrap.addCommand(new ClearIssuedReceiptRedemptionsCommand());
bootstrap.addCommand(new CopyToS3Command());
bootstrap.addCommand(new ClearExpiredFoundationDbMessagesCommand(Clock.systemUTC()));
bootstrap.addCommand(new TrimOversizedFoundationDbMessageQueuesCommand());
bootstrap.addCommand(new ProcessScheduledJobsServiceCommand("process-idle-device-notification-jobs",
"Processes scheduled jobs to send notifications to idle devices",
@@ -402,6 +412,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
bootstrap.addCommand(new RegenerateSecondaryDynamoDbTableDataCommand());
bootstrap.addCommand(new PopulateAccountRecoveryPasswordsCommand());
ServiceLoader.load(SpamFilter.class)
.stream()
.map(ServiceLoader.Provider::get)
@@ -530,10 +542,16 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
.allowCoreThreadTimeOut(true)
.workQueue(messageDeletionQueue).build();
RedeemedReceiptsManager redeemedReceiptsManager = new RedeemedReceiptsManager(clock,
config.getDynamoDbTables().getRedeemedReceipts().getTableName(),
dynamoDbClient,
config.getDynamoDbTables().getRedeemedReceipts().getExpiration());
Accounts accounts = new Accounts(
clock,
dynamoDbClient,
dynamoDbAsyncClient,
redeemedReceiptsManager,
config.getDynamoDbTables().getAccounts().getTableName(),
config.getDynamoDbTables().getAccounts().getPhoneNumberTableName(),
config.getDynamoDbTables().getAccounts().getPhoneNumberIdentifierTableName(),
@@ -575,7 +593,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
ReportMessageDynamoDb reportMessageDynamoDb = new ReportMessageDynamoDb(dynamoDbClient, dynamoDbAsyncClient,
config.getDynamoDbTables().getReportMessage().getTableName(),
config.getReportMessageConfiguration().getReportTtl());
RegistrationRecoveryPasswords registrationRecoveryPasswords = new RegistrationRecoveryPasswords(
PhoneNumberRecoveryPasswords phoneNumberRecoveryPasswords = new PhoneNumberRecoveryPasswords(
config.getDynamoDbTables().getRegistrationRecovery().getTableName(),
config.getDynamoDbTables().getRegistrationRecovery().getExpiration(),
dynamoDbClient,
@@ -717,8 +735,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
AsnInfoProvider.EMPTY,
"AsnManager");
RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager =
new RegistrationRecoveryPasswordsManager(registrationRecoveryPasswords);
PhoneNumberRecoveryPasswordsManager phoneNumberRecoveryPasswordsManager =
new PhoneNumberRecoveryPasswordsManager(phoneNumberRecoveryPasswords);
UsernameHashZkProofVerifier usernameHashZkProofVerifier = new UsernameHashZkProofVerifier();
final CarrierDataProvider carrierDataProvider =
@@ -785,9 +803,9 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
AccountsManager accountsManager = new AccountsManager(accounts, phoneNumberIdentifiers, cacheCluster,
pubsubClient, accountLockManager, keysManager, messagesManager, profilesManager,
changeNumberWaitingPeriodManager, secureStorageClient, secureValueRecovery2Client, disconnectionRequestManager,
registrationRecoveryPasswordsManager, accountLockExecutor, messagePollExecutor,
phoneNumberRecoveryPasswordsManager, accountLockExecutor, messagePollExecutor,
retryExecutor, clock, config.getLinkDeviceSecretConfiguration().secret().value());
RemoteConfigsManager remoteConfigsManager = new RemoteConfigsManager(remoteConfigs);
RemoteConfigsManager remoteConfigsManager = new RemoteConfigsManager(remoteConfigs, config.getRemoteConfigConfiguration().globalConfig());
APNSender apnSender = new APNSender(apnSenderExecutor, Clock.systemUTC(), config.getApnConfiguration());
FcmSender fcmSender = new FcmSender(fcmSenderExecutor, config.getFcmConfiguration().credentials().value());
PushNotificationScheduler pushNotificationScheduler = new PushNotificationScheduler(pushSchedulerCluster,
@@ -798,18 +816,13 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
ProvisioningManager provisioningManager = new ProvisioningManager(pubsubClient);
IssuedReceiptsManager issuedReceiptsManager = new IssuedReceiptsManager(
config.getDynamoDbTables().getIssuedReceipts().getTableName(),
config.getDynamoDbTables().getIssuedReceipts().getExpiration(),
dynamoDbClient,
config.getDynamoDbTables().getIssuedReceipts().getGenerator(),
config.getDynamoDbTables().getIssuedReceipts().getmaxIssuedReceiptsPerPaymentId());
config.getDynamoDbTables().getIssuedReceipts().getMaxReceiptsPerSubscriptionPayment());
OneTimeDonationsManager oneTimeDonationsManager = new OneTimeDonationsManager(
config.getDynamoDbTables().getOnetimeDonations().getTableName(), config.getDynamoDbTables().getOnetimeDonations().getExpiration(), dynamoDbClient);
DonationPermits donationPermits = new DonationPermits(
config.getDynamoDbTables().getDonationPermits().getTableName(), config.getDynamoDbTables().getDonationPermits().getExpiration(), dynamoDbClient);
RedeemedReceiptsManager redeemedReceiptsManager = new RedeemedReceiptsManager(clock,
config.getDynamoDbTables().getRedeemedReceipts().getTableName(),
dynamoDbClient,
config.getDynamoDbTables().getRedeemedReceipts().getExpiration());
Subscriptions subscriptions = new Subscriptions(
config.getDynamoDbTables().getSubscriptions().getTableName(), dynamoDbClient);
MessageDeliveryLoopMonitor messageDeliveryLoopMonitor =
@@ -820,7 +833,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
callQualitySurveyPubSubExecutor);
final RegistrationLockVerificationManager registrationLockVerificationManager = new RegistrationLockVerificationManager(
accountsManager, disconnectionRequestManager, svr2CredentialsGenerator, registrationRecoveryPasswordsManager,
accountsManager, disconnectionRequestManager, svr2CredentialsGenerator, phoneNumberRecoveryPasswordsManager,
pushNotificationManager, rateLimiters);
final ReportedMessageMetricsListener reportedMessageMetricsListener = new ReportedMessageMetricsListener(
@@ -978,6 +991,13 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
List.of(stripeManager, braintreeManager, googlePlayBillingManager, appleAppStoreManager),
zkReceiptOperations, issuedReceiptsManager);
final LoginPurchaseManager loginPurchaseManager = new LoginPurchaseManager(
Map.of(
PaymentProvider.APPLE_APP_STORE, appleAppStoreManager,
PaymentProvider.GOOGLE_PLAY_BILLING, googlePlayBillingManager),
issuedReceiptsManager,
zkReceiptOperations);
final List<SpamFilter> spamFilters = ServiceLoader.load(SpamFilter.class)
.stream()
.map(ServiceLoader.Provider::get)
@@ -1077,18 +1097,19 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
config.getDeliveryCertificate().embedSigner());
final PhoneVerificationTokenManager phoneVerificationTokenManager = new PhoneVerificationTokenManager(
phoneNumberIdentifiers, registrationServiceClient, registrationRecoveryPasswordsManager, registrationRecoveryChecker);
phoneNumberIdentifiers, registrationServiceClient, phoneNumberRecoveryPasswordsManager, registrationRecoveryChecker);
final ChangeNumberManager changeNumberManager = new ChangeNumberManager(messageSender, accountsManager,
phoneVerificationTokenManager, registrationLockVerificationManager, rateLimiters,
changeNumberWaitingPeriodManager, Clock.systemUTC());
final List<ServerServiceDefinition> authenticatedServices = Stream.of(
new AccountsGrpcService(accountsManager, rateLimiters, usernameHashZkProofVerifier, registrationRecoveryPasswordsManager, Clock.systemUTC(), changeNumberManager),
new AccountsGrpcService(accountsManager, rateLimiters, usernameHashZkProofVerifier,
phoneNumberRecoveryPasswordsManager, Clock.systemUTC(), changeNumberManager),
new CallingGrpcService(cloudflareTurnCredentialsManager, rateLimiters),
new CredentialsGrpcService(accountsManager, certificateGenerator, zkAuthOperations, callingGenericZkSecretParams, rateLimiters, Clock.systemUTC(), ExternalServiceDefinitions.createExternalServiceList(config, Clock.systemUTC())),
new KeysGrpcService(accountsManager, keysManager, rateLimiters),
new ProfileGrpcService(clock, accountsManager, profilesManager, dynamicConfigurationManager, config.getBadges(), profileCdnPolicyGenerator, chatGenericZkSecretParams, profileBadgeConverter, rateLimiters),
new ProfileGrpcService(clock, accountsManager, profilesManager, asnInfoProviderSupplier, dynamicConfigurationManager, config.getBadges(), profileCdnPolicyGenerator, chatGenericZkSecretParams, profileBadgeConverter, rateLimiters),
new MessagesGrpcService(accountsManager, rateLimiters, messageSender, messageByteLimitCardinalityEstimator, spamChecker, messageDispatcher, Clock.systemUTC()),
new BackupsGrpcService(accountsManager, backupAuthManager, backupMetrics),
new DevicesGrpcService(accountsManager),
@@ -1099,8 +1120,12 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new ChallengeGrpcService(accountsManager, rateLimitChallengeManager, challengeConstraintChecker),
new DonationsGrpcService(clock, zkReceiptOperations, redeemedReceiptsManager, accountsManager, config.getBadges(), ReceiptCredentialPresentation::new, donationPermitsManager, rateLimiters),
new ProductConfigurationGrpcService(config.getSubscription(), config.getOneTimeDonations(),
List.of(stripeManager, braintreeManager), profileBadgeConverter,
config.getBackupConfiguration().maxTotalMediaSize()))
config.getLoginPurchase(), List.of(stripeManager, braintreeManager),
config.getBackupConfiguration().maxTotalMediaSize()),
new RemoteConfigurationGrpcService(remoteConfigsManager, profileBadgeConverter,
config.getBadges().getBadges().stream()
.map(BadgeConfiguration::getId)
.toList()))
.map(bindableService -> ServerInterceptors.intercept(bindableService,
// Note: interceptors run in the reverse order they are added; the remote deprecation filter
// depends on the user-agent context so it has to come first here!
@@ -1117,6 +1142,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new AccountsAnonymousGrpcService(accountsManager, rateLimiters, groupSendTokenUtil),
new CallQualitySurveyGrpcService(callQualitySurveyManager, rateLimiters),
new KeysAnonymousGrpcService(accountsManager, keysManager, groupZkSecretParams, Clock.systemUTC()),
new KeyTransparencyGrpcService(rateLimiters, keyTransparencyServiceClient),
new ProfileAnonymousGrpcService(accountsManager, profilesManager, profileBadgeConverter, profileCdnPolicyGenerator, chatGenericZkSecretParams, groupZkSecretParams, rateLimiters, clock),
new MessagesAnonymousGrpcService(accountsManager, rateLimiters, messageSender, groupSendTokenUtil, messageByteLimitCardinalityEstimator, spamChecker, Clock.systemUTC()),
new BackupsAnonymousGrpcService(backupManager, backupMetrics, config.getAttachments().maxAttachmentUploadSizeInBytes(), config.getAttachments().maxMessageBackupUploadSizeInBytes()),
@@ -1232,7 +1258,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
final PersistentTimer persistentTimer = new PersistentTimer(rateLimitersCluster, clock);
final List<Object> commonControllers = Lists.newArrayList(
new AccountController(accountsManager, rateLimiters, registrationRecoveryPasswordsManager,
new AccountController(accountsManager, rateLimiters, phoneNumberRecoveryPasswordsManager,
usernameHashZkProofVerifier),
new AccountControllerV2(accountsManager, changeNumberManager),
new AttachmentControllerV4(rateLimiters, gcsAttachmentGenerator, tusAttachmentGenerator,
@@ -1245,7 +1271,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new ChallengeController(accountsManager, rateLimitChallengeManager, challengeConstraintChecker),
new DeviceController(accountsManager, rateLimiters, persistentTimer),
new DeviceCheckController(clock, accountsManager, backupAuthManager, appleDeviceCheckManager, rateLimiters,
config.getDeviceCheck().backupRedemptionLevel(),
config.getDeviceCheck().backupRedemptionDuration()),
new DirectoryV2Controller(directoryV2CredentialsGenerator),
new DonationController(clock, zkReceiptOperations, redeemedReceiptsManager, accountsManager, config.getBadges(),
@@ -1255,27 +1280,29 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new MessageController(rateLimiters, messageByteLimitCardinalityEstimator, messageSender, accountsManager,
phoneNumberIdentifiers, reportMessageManager, groupZkSecretParams, spamChecker, Clock.systemUTC()),
new PaymentsController(currencyManager, paymentsCredentialsGenerator),
new ProfileController(clock, rateLimiters, accountsManager, profilesManager, dynamicConfigurationManager,
profileBadgeConverter, config.getBadges(), profileCdnPolicyGenerator,
new ProfileController(clock, rateLimiters, accountsManager, profilesManager, asnInfoProviderSupplier,
dynamicConfigurationManager, profileBadgeConverter, config.getBadges(), profileCdnPolicyGenerator,
groupZkSecretParams, zkProfileOperations, batchIdentityCheckExecutor),
new ProvisioningController(rateLimiters, provisioningManager),
new RegistrationController(accountsManager, phoneVerificationTokenManager, registrationLockVerificationManager,
rateLimiters, registrationFraudChecker),
new RemoteConfigController(remoteConfigsManager, config.getRemoteConfigConfiguration().globalConfig()),
rateLimiters, registrationFraudChecker, ReceiptCredentialPresentation::new, zkReceiptOperations, clock, dynamicConfigurationManager),
new RemoteConfigController(remoteConfigsManager),
new SecureStorageController(storageCredentialsGenerator),
new SecureValueRecovery2Controller(svr2CredentialsGenerator, accountsManager),
new StickerController(rateLimiters, stickerPolicyGenerator, Clock.systemUTC()),
new VerificationController(registrationServiceClient, new VerificationSessionManager(verificationSessions),
pushNotificationManager, registrationCaptchaManager, registrationRecoveryPasswordsManager,
pushNotificationManager, registrationCaptchaManager, phoneNumberRecoveryPasswordsManager,
phoneNumberIdentifiers, rateLimiters, accountsManager, carrierDataProvider, registrationFraudChecker,
dynamicConfigurationManager, experimentEnrollmentManager, clock),
new SubscriptionController(clock, config.getSubscription(), config.getOneTimeDonations(),
subscriptionManager, stripeManager, braintreeManager, googlePlayBillingManager, appleAppStoreManager,
config.getLoginPurchase(), subscriptionManager, stripeManager, braintreeManager, googlePlayBillingManager,
appleAppStoreManager,
profileBadgeConverter, bankMandateTranslator, donationPermitsManager,
config.getBackupConfiguration().maxTotalMediaSize()),
new OneTimeDonationController(clock, config.getOneTimeDonations(), stripeManager, braintreeManager,
payPalDonationsTranslator, zkReceiptOperations, issuedReceiptsManager, oneTimeDonationsManager,
donationPermitsManager)
donationPermitsManager),
new LoginPurchaseController(loginPurchaseManager, dynamicConfigurationManager)
);
for (Object controller : commonControllers) {
@@ -1341,6 +1368,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new InvalidWebsocketAddressExceptionMapper(),
new DeviceLimitExceededExceptionMapper(),
new ServerRejectedExceptionMapper(),
new IllegalStateExceptionMapper(),
new ImpossiblePhoneNumberExceptionMapper(),
new NonNormalizedPhoneNumberExceptionMapper(),
new ObsoletePhoneNumberFormatExceptionMapper(),
@@ -19,7 +19,6 @@ import java.time.temporal.ChronoUnit;
import java.util.Optional;
import java.util.UUID;
import org.apache.commons.lang3.StringUtils;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
@@ -101,7 +100,7 @@ public class AccountAuthenticator implements Authenticator<BasicCredentials, Aut
if (deviceSaltedTokenHash.verify(basicCredentials.getPassword())) {
succeeded = true;
final Account authenticatedAccount = updateLastSeen(account.get(), device.get());
return Optional.of(new AuthenticatedDevice(authenticatedAccount.getIdentifier(IdentityType.ACI),
return Optional.of(new AuthenticatedDevice(authenticatedAccount.getAccountIdentifier(),
device.get().getId(),
Instant.ofEpochMilli(authenticatedAccount.getPrimaryDevice().getLastSeen())));
} else {
@@ -126,7 +125,7 @@ public class AccountAuthenticator implements Authenticator<BasicCredentials, Aut
@VisibleForTesting
public Account updateLastSeen(Account account, Device device) {
// compute a non-negative integer between 0 and 86400.
long n = Util.ensureNonNegativeLong(account.getUuid().getLeastSignificantBits());
long n = Util.ensureNonNegativeLong(account.getAccountIdentifier().getLeastSignificantBits());
final long lastSeenOffsetSeconds = n % ChronoUnit.DAYS.getDuration().toSeconds();
// produce a truncated timestamp which is either today at UTC midnight
@@ -142,7 +141,7 @@ public class AccountAuthenticator implements Authenticator<BasicCredentials, Aut
Metrics.summary(DAYS_SINCE_LAST_SEEN_DISTRIBUTION_NAME, IS_PRIMARY_DEVICE_TAG, String.valueOf(device.isPrimary()))
.record(Duration.ofMillis(todayInMillisWithOffset - device.getLastSeen()).toDays());
return accountsManager.updateDeviceLastSeen(account.getIdentifier(IdentityType.ACI), device, Util.todayInMillis(clock));
return accountsManager.updateDeviceLastSeen(account.getAccountIdentifier(), device, Util.todayInMillis(clock));
}
return account;
@@ -11,7 +11,6 @@ import java.util.concurrent.TimeUnit;
import org.signal.libsignal.protocol.ecc.ECPrivateKey;
import org.whispersystems.textsecuregcm.entities.MessageProtos.SenderCertificate;
import org.whispersystems.textsecuregcm.entities.MessageProtos.ServerCertificate;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
@@ -35,14 +34,18 @@ public class CertificateGenerator {
}
public byte[] createFor(final Account account, final byte deviceId, boolean includeE164) {
if (includeE164 && account.getNumberOptional().isEmpty()) {
throw new IllegalArgumentException();
}
SenderCertificate.Certificate.Builder builder = SenderCertificate.Certificate.newBuilder()
.setSenderDevice(Math.toIntExact(deviceId))
.setExpires(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(expiresDays))
.setIdentityKey(ByteString.copyFrom(account.getIdentityKey(IdentityType.ACI).serialize()))
.setSenderUuid(UUIDUtil.toByteString(account.getUuid()));
.setIdentityKey(ByteString.copyFrom(account.getAccountIdentityKey().serialize()))
.setSenderUuid(UUIDUtil.toByteString(account.getAccountIdentifier()));
if (includeE164) {
builder.setSenderE164(account.getNumber());
builder.setSenderE164(account.getNumberOptional().get());
}
if (embedSigner) {
@@ -7,9 +7,11 @@ package org.whispersystems.textsecuregcm.auth;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
public class ExternalServiceCredentialsSelector {
@@ -44,13 +46,13 @@ public class ExternalServiceCredentialsSelector {
* A credential is valid if it passes validation by the provided credentialsGenerator AND it is the most recent
* credential in the provided list for a username.
*
* @param tokens A list of credentials, potentially with different usernames
* @param tokens A set of credentials, potentially with different usernames
* @param credentialsGenerator To validate these credentials
* @param maxAgeSeconds The maximum allowable age of the credential
* @return A {@link CredentialInfo} for each provided token
* @return An unordered list of {@link CredentialInfo} for each provided token
*/
public static List<CredentialInfo> check(
final List<String> tokens,
final Set<String> tokens,
final ExternalServiceCredentialsGenerator credentialsGenerator,
final long maxAgeSeconds) {
@@ -22,7 +22,7 @@ import org.whispersystems.textsecuregcm.entities.RegistrationServiceSession;
import org.whispersystems.textsecuregcm.registration.RegistrationServiceClient;
import org.whispersystems.textsecuregcm.spam.RegistrationRecoveryChecker;
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
import org.whispersystems.textsecuregcm.storage.PhoneNumberRecoveryPasswordsManager;
public class PhoneVerificationTokenManager {
@@ -33,16 +33,16 @@ public class PhoneVerificationTokenManager {
private final PhoneNumberIdentifiers phoneNumberIdentifiers;
private final RegistrationServiceClient registrationServiceClient;
private final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager;
private final PhoneNumberRecoveryPasswordsManager phoneNumberRecoveryPasswordsManager;
private final RegistrationRecoveryChecker registrationRecoveryChecker;
public PhoneVerificationTokenManager(final PhoneNumberIdentifiers phoneNumberIdentifiers,
final RegistrationServiceClient registrationServiceClient,
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager,
final PhoneNumberRecoveryPasswordsManager phoneNumberRecoveryPasswordsManager,
final RegistrationRecoveryChecker registrationRecoveryChecker) {
this.phoneNumberIdentifiers = phoneNumberIdentifiers;
this.registrationServiceClient = registrationServiceClient;
this.registrationRecoveryPasswordsManager = registrationRecoveryPasswordsManager;
this.phoneNumberRecoveryPasswordsManager = phoneNumberRecoveryPasswordsManager;
this.registrationRecoveryChecker = registrationRecoveryChecker;
}
@@ -127,7 +127,7 @@ public class PhoneVerificationTokenManager {
final UUID phoneNumberIdentifier = phoneNumberIdentifiers.getPhoneNumberIdentifier(number)
.get(VERIFICATION_TIMEOUT_SECONDS, TimeUnit.SECONDS);
final boolean verified = registrationRecoveryPasswordsManager.verify(phoneNumberIdentifier, recoveryPassword);
final boolean verified = phoneNumberRecoveryPasswordsManager.verify(phoneNumberIdentifier, recoveryPassword);
if (!verified) {
throw new RecoveryPasswordVerificationFailedException();
@@ -20,7 +20,6 @@ import org.apache.commons.lang3.StringUtils;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.entities.PhoneVerificationRequest;
import org.whispersystems.textsecuregcm.entities.RegistrationLockFailure;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.push.NotPushRegisteredException;
@@ -28,7 +27,7 @@ import org.whispersystems.textsecuregcm.push.PushNotificationManager;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
import org.whispersystems.textsecuregcm.storage.PhoneNumberRecoveryPasswordsManager;
public class RegistrationLockVerificationManager {
public enum Flow {
@@ -54,20 +53,20 @@ public class RegistrationLockVerificationManager {
private final DisconnectionRequestManager disconnectionRequestManager;
private final ExternalServiceCredentialsGenerator svr2CredentialGenerator;
private final RateLimiters rateLimiters;
private final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager;
private final PhoneNumberRecoveryPasswordsManager phoneNumberRecoveryPasswordsManager;
private final PushNotificationManager pushNotificationManager;
public RegistrationLockVerificationManager(
final AccountsManager accounts,
final DisconnectionRequestManager disconnectionRequestManager,
final ExternalServiceCredentialsGenerator svr2CredentialGenerator,
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager,
final PhoneNumberRecoveryPasswordsManager phoneNumberRecoveryPasswordsManager,
final PushNotificationManager pushNotificationManager,
final RateLimiters rateLimiters) {
this.accounts = accounts;
this.disconnectionRequestManager = disconnectionRequestManager;
this.svr2CredentialGenerator = svr2CredentialGenerator;
this.registrationRecoveryPasswordsManager = registrationRecoveryPasswordsManager;
this.phoneNumberRecoveryPasswordsManager = phoneNumberRecoveryPasswordsManager;
this.pushNotificationManager = pushNotificationManager;
this.rateLimiters = rateLimiters;
}
@@ -86,6 +85,9 @@ public class RegistrationLockVerificationManager {
final PhoneVerificationRequest.VerificationType phoneVerificationType
) throws RateLimitExceededException, RegistrationLockFailureException {
final String phoneNumber = account.getNumberOptional()
.orElseThrow(() -> new IllegalArgumentException("account does not have a phone number"));
final Tags expiredTags = Tags.of(UserAgentTagUtil.getPlatformTag(userAgent),
Tag.of(REGISTRATION_LOCK_VERIFICATION_FLOW_TAG_NAME, flow.name()),
Tag.of(PHONE_VERIFICATION_TYPE_TAG_NAME, phoneVerificationType.name())
@@ -106,10 +108,9 @@ public class RegistrationLockVerificationManager {
}
if (StringUtils.isNotEmpty(clientRegistrationLock)) {
rateLimiters.getPinLimiter().validate(account.getNumber());
rateLimiters.getPinLimiter().validate(phoneNumber);
}
final String phoneNumber = account.getNumber();
final boolean registrationLockMatches = existingRegistrationLock.verify(clientRegistrationLock);
final boolean alreadyLocked = account.hasLockedCredentials();
@@ -150,11 +151,12 @@ public class RegistrationLockVerificationManager {
// This allows users to re-register via registration recovery password
// instead of always being forced to fall back to SMS verification.
if (!phoneVerificationType.equals(PhoneVerificationRequest.VerificationType.RECOVERY_PASSWORD) || clientRegistrationLock != null) {
registrationRecoveryPasswordsManager.remove(updatedAccount.getIdentifier(IdentityType.PNI));
phoneNumberRecoveryPasswordsManager.remove(updatedAccount.getPhoneNumberIdentifierOptional()
.orElseThrow(() -> new AssertionError("Account with a phone number did not have a phone number identifier")));
}
final List<Byte> deviceIds = updatedAccount.getDevices().stream().map(Device::getId).toList();
disconnectionRequestManager.requestDisconnection(updatedAccount.getUuid(), deviceIds);
disconnectionRequestManager.requestDisconnection(updatedAccount.getAccountIdentifier(), deviceIds);
try {
// Send a push notification that prompts the client to attempt login and fail due to locked credentials
@@ -176,7 +178,7 @@ public class RegistrationLockVerificationManager {
if (!existingRegistrationLock.needsFailureCredentials()) {
return null;
}
return svr2CredentialGenerator.generateForUuid(account.getUuid());
return svr2CredentialGenerator.generateForUuid(account.getAccountIdentifier());
}
}
@@ -136,11 +136,11 @@ public class BackupAuthManager {
}
if (requiresMessageRotation) {
rateLimiters.forDescriptor(RateLimiters.For.SET_BACKUP_ID).validate(account.getUuid());
rateLimiters.forDescriptor(RateLimiters.For.SET_BACKUP_ID).validate(account.getAccountIdentifier());
}
if (requiresMediaRotation && hasActiveVoucher(account)) {
rateLimiters.forDescriptor(RateLimiters.For.SET_PAID_MEDIA_BACKUP_ID).validate(account.getUuid());
rateLimiters.forDescriptor(RateLimiters.For.SET_PAID_MEDIA_BACKUP_ID).validate(account.getAccountIdentifier());
}
this.accountsManager.update(account, a ->
@@ -156,9 +156,9 @@ public class BackupAuthManager {
final boolean isPaid = hasActiveVoucher(account);
final CompletionStage<Boolean> hasSetMessagesPermits =
messagesLimiter.hasAvailablePermitsAsync(account.getUuid(), 1);
messagesLimiter.hasAvailablePermitsAsync(account.getAccountIdentifier(), 1);
final CompletionStage<Boolean> hasSetMediaPermits = isPaid
? mediaLimiter.hasAvailablePermitsAsync(account.getUuid(), 1)
? mediaLimiter.hasAvailablePermitsAsync(account.getAccountIdentifier(), 1)
: CompletableFuture.completedFuture(true);
return hasSetMessagesPermits.thenCombine(hasSetMediaPermits, (hasMessage, hasMedia) -> {
@@ -266,7 +266,7 @@ public class BackupAuthManager {
}
boolean receiptAllowed = redeemedReceiptsManager
.put(receiptSerial, receiptExpiration.getEpochSecond(), receiptLevel, account.getUuid());
.put(receiptSerial, receiptExpiration.getEpochSecond(), receiptLevel, account.getAccountIdentifier());
if (!receiptAllowed) {
throw new BackupBadReceiptException("receipt serial is already redeemed");
}
@@ -342,7 +342,7 @@ public class BackupAuthManager {
* BackupVoucher.
*/
private BackupLevel configuredBackupLevel(final Account account) {
return this.experimentEnrollmentManager.isEnrolled(account.getUuid(), BACKUP_MEDIA_EXPERIMENT_NAME)
return this.experimentEnrollmentManager.isEnrolled(account.getAccountIdentifier(), BACKUP_MEDIA_EXPERIMENT_NAME)
? BackupLevel.PAID
: BackupLevel.FREE;
}
@@ -59,6 +59,8 @@ public class BackupManager {
static final String MESSAGE_BACKUP_NAME = "messageBackup";
private static final int DEFAULT_LIST_MEDIA_LIMIT = 1000;
private static final String ZK_AUTHN_COUNTER_NAME = MetricsUtil.name(BackupManager.class, "authentication");
private static final String ZK_AUTHZ_FAILURE_COUNTER_NAME = MetricsUtil.name(BackupManager.class,
"authorizationFailure");
@@ -458,17 +460,19 @@ public class BackupManager {
*
* @param backupUser An already ZK authenticated backup user
* @param cursor A cursor returned by a previous call that can be used to resume listing
* @param limit The maximum number of list results to return
* @param limit The maximum number of list results to return, or empty to use
* {@link #DEFAULT_LIST_MEDIA_LIMIT}
* @return A {@link ListMediaResult}
* @throws BackupPermissionException if the credential does not have the correct level
*/
public ListMediaResult list(
final AuthenticatedBackupUser backupUser,
final Optional<String> cursor,
final int limit) throws BackupPermissionException {
final Optional<Integer> limit) throws BackupPermissionException {
checkBackupLevel(backupUser, BackupLevel.FREE);
final RemoteStorageManager.ListResult result =
remoteStorageManager.list(cdnMediaDirectory(backupUser), cursor, limit).toCompletableFuture().join();
final RemoteStorageManager.ListResult result = remoteStorageManager
.list(cdnMediaDirectory(backupUser), cursor, limit.orElse(DEFAULT_LIST_MEDIA_LIMIT))
.toCompletableFuture().join();
return new ListMediaResult(result
.objects()
.stream()
@@ -42,6 +42,7 @@ public class Cdn3RemoteStorageManager implements RemoteStorageManager {
private final String clientId;
private final String clientSecret;
private final Map<Integer, String> sourceSchemes;
private final Duration usageRequestTimeout;
static final String CLIENT_ID_HEADER = "CF-Access-Client-Id";
static final String CLIENT_SECRET_HEADER = "CF-Access-Client-Secret";
@@ -75,6 +76,7 @@ public class Cdn3RemoteStorageManager implements RemoteStorageManager {
.withNumClients(configuration.numHttpClients())
.build();
this.sourceSchemes = configuration.sourceSchemes();
this.usageRequestTimeout = configuration.usageRequestTimeout();
}
@Override
@@ -231,6 +233,7 @@ public class Cdn3RemoteStorageManager implements RemoteStorageManager {
HttpUtils.queryParamString(Map.of("prefix", prefix).entrySet()))))
.header(CLIENT_ID_HEADER, clientId)
.header(CLIENT_SECRET_HEADER, clientSecret)
.timeout(usageRequestTimeout)
.build();
return this.storageManagerHttpClient.sendAsync(request, HttpResponse.BodyHandlers.ofInputStream())
.thenApply(response -> {
@@ -12,6 +12,7 @@ import jakarta.validation.constraints.NotNull;
import java.util.List;
import java.util.Map;
import org.whispersystems.textsecuregcm.configuration.secrets.SecretString;
import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel;
import javax.annotation.Nullable;
/**
@@ -38,7 +39,7 @@ public record AppleAppStoreConfiguration(
@NotBlank String keyId,
@NotNull SecretString encodedKey,
@NotBlank String subscriptionGroupId,
@NotNull Map<String, Long> productIdToLevel,
@NotNull Map<String, ReceiptLevel> productIdToLevel,
@NotNull List<@NotBlank String> appleRootCerts,
@Nullable String retryConfigurationName) {
}
@@ -13,6 +13,7 @@ import com.fasterxml.jackson.annotation.Nulls;
import io.dropwizard.validation.ValidationMethod;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel;
import java.util.List;
import java.util.Map;
import java.util.Objects;
@@ -21,12 +22,12 @@ import java.util.stream.Collectors;
public class BadgesConfiguration {
private final List<BadgeConfiguration> badges;
private final Map<Long, String> receiptLevels;
private final Map<ReceiptLevel, String> receiptLevels;
@JsonCreator
public BadgesConfiguration(
@JsonProperty("badges") @JsonSetter(nulls = Nulls.AS_EMPTY) final List<BadgeConfiguration> badges,
@JsonProperty("receiptLevels") @JsonSetter(nulls = Nulls.AS_EMPTY) final Map<Long, String> receiptLevels) {
@JsonProperty("receiptLevels") @JsonSetter(nulls = Nulls.AS_EMPTY) final Map<ReceiptLevel, String> receiptLevels) {
this.badges = Objects.requireNonNull(badges);
this.receiptLevels = Objects.requireNonNull(receiptLevels);
}
@@ -39,7 +40,7 @@ public class BadgesConfiguration {
@Valid
@NotNull
public Map<Long, String> getReceiptLevels() {
public Map<ReceiptLevel, String> getReceiptLevels() {
return receiptLevels;
}
@@ -2,6 +2,7 @@ package org.whispersystems.textsecuregcm.configuration;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import java.time.Duration;
import java.util.Collections;
import java.util.Map;
import org.whispersystems.textsecuregcm.configuration.secrets.SecretString;
@@ -21,6 +22,8 @@ import javax.annotation.Nullable;
* client; if `null`, uses the global default configuration
* @param retryConfigurationName The name of a retry configuration for the storage-manager http client; if
* `null`, uses the global default configuration
* @param usageRequestTimeout The per-attempt request timeout for usage requests to the storage-manager; if
* `null`, defaults to 5 minutes
*/
public record Cdn3StorageManagerConfiguration(
@NotNull String baseUri,
@@ -29,7 +32,8 @@ public record Cdn3StorageManagerConfiguration(
@NotNull Map<Integer, String> sourceSchemes,
@NotNull Integer numHttpClients,
@Nullable String circuitBreakerConfigurationName,
@Nullable String retryConfigurationName) {
@Nullable String retryConfigurationName,
@NotNull Duration usageRequestTimeout) {
public Cdn3StorageManagerConfiguration {
if (numHttpClients == null) {
@@ -38,5 +42,8 @@ public record Cdn3StorageManagerConfiguration(
if (sourceSchemes == null) {
sourceSchemes = Collections.emptyMap();
}
if (usageRequestTimeout == null) {
usageRequestTimeout = Duration.ofMinutes(5);
}
}
}
@@ -10,6 +10,5 @@ import java.time.Duration;
* Configuration for Device Check operations
*
* @param backupRedemptionDuration How long to grant backup access for redemptions via device check
* @param backupRedemptionLevel What backup level to grant redemptions via device check
*/
public record DeviceCheckConfiguration(Duration backupRedemptionDuration, long backupRedemptionLevel) {}
public record DeviceCheckConfiguration(Duration backupRedemptionDuration) {}
@@ -9,6 +9,7 @@ import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import java.util.Map;
import org.whispersystems.textsecuregcm.configuration.secrets.SecretString;
import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel;
/**
* @param credentialsJson Service account credentials for Play Billing API
@@ -21,4 +22,4 @@ public record GooglePlayBillingConfiguration(
@NotBlank String credentialsJson,
@NotNull String packageName,
@NotBlank String applicationName,
@NotNull Map<String, Long> productIdToLevel) {}
@NotNull Map<String, ReceiptLevel> productIdToLevel) {}
@@ -7,29 +7,25 @@ package org.whispersystems.textsecuregcm.configuration;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.NotEmpty;
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
import org.whispersystems.textsecuregcm.util.EnumMapUtil;
import java.time.Duration;
import java.util.EnumMap;
import java.util.Map;
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
import org.whispersystems.textsecuregcm.util.EnumMapUtil;
public class IssuedReceiptsTableConfiguration extends DynamoDbTables.TableWithExpiration {
public class IssuedReceiptsTableConfiguration extends DynamoDbTables.Table {
private final byte[] generator;
/**
* The maximum number of issued receipts the issued receipt manager should issue for a particular itemId
*/
private final EnumMap<PaymentProvider, Integer> maxIssuedReceiptsPerPaymentId;
/// The maximum number of receipts that may be issued for a single subscription payment.
private final EnumMap<PaymentProvider, Integer> maxReceiptsPerSubscriptionPayment;
public IssuedReceiptsTableConfiguration(
@JsonProperty("tableName") final String tableName,
@JsonProperty("expiration") final Duration expiration,
@JsonProperty("generator") final byte[] generator,
@JsonProperty("maxIssuedReceiptsPerPaymentId") final Map<PaymentProvider, Integer> maxIssuedReceiptsPerPaymentId) {
super(tableName, expiration);
@JsonProperty("maxReceiptsPerSubscriptionPayment") final Map<PaymentProvider, Integer> maxReceiptsPerSubscriptionPayment) {
super(tableName);
this.generator = generator;
this.maxIssuedReceiptsPerPaymentId = EnumMapUtil.toCompleteEnumMap(PaymentProvider.class, maxIssuedReceiptsPerPaymentId);
this.maxReceiptsPerSubscriptionPayment = EnumMapUtil.toCompleteEnumMap(PaymentProvider.class, maxReceiptsPerSubscriptionPayment);
}
@NotEmpty
@@ -37,7 +33,7 @@ public class IssuedReceiptsTableConfiguration extends DynamoDbTables.TableWithEx
return generator;
}
public EnumMap<PaymentProvider, Integer> getmaxIssuedReceiptsPerPaymentId() {
return maxIssuedReceiptsPerPaymentId;
public EnumMap<PaymentProvider, Integer> getMaxReceiptsPerSubscriptionPayment() {
return maxReceiptsPerSubscriptionPayment;
}
}
@@ -0,0 +1,18 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Positive;
import java.time.Duration;
/// Configuration for one-time Signal Login purchases
///
/// @param playProductId the Google Play Billing productId clients should purchase to obtain a Signal Login
/// @param appStoreProductId the App Store productId clients should purchase to obtain a Signal Login
public record LoginPurchaseConfiguration(
@NotEmpty String playProductId,
@NotEmpty String appStoreProductId) {}
@@ -24,10 +24,9 @@ public record OneTimeDonationConfiguration(@Valid ExpiringLevelConfiguration boo
/**
* @param badge the numeric donation level ID
* @param level the badge ID associated with the level
* @param expiration the duration after which the level expires
*/
public record ExpiringLevelConfiguration(@NotEmpty String badge, @Positive long level, Duration expiration) {
public record ExpiringLevelConfiguration(@NotEmpty String badge, Duration expiration) {
}
}
@@ -35,7 +35,7 @@ public class DynamicConfiguration {
@JsonProperty
@Valid
private DynamicPaymentsConfiguration payments = new DynamicPaymentsConfiguration();
private DynamicPaymentsConfiguration payments = DynamicPaymentsConfiguration.DEFAULT;
@JsonProperty
@Valid
@@ -85,6 +85,10 @@ public class DynamicConfiguration {
@Valid
private DynamicTurnConfiguration turn = new DynamicTurnConfiguration();
@JsonProperty
@Valid
private DynamicLoginPurchaseConfiguration loginPurchase = new DynamicLoginPurchaseConfiguration(false);
public Optional<DynamicExperimentEnrollmentConfiguration> getExperimentEnrollmentConfiguration(
final String experimentName) {
return Optional.ofNullable(experiments.get(experimentName));
@@ -154,4 +158,8 @@ public class DynamicConfiguration {
public DynamicTurnConfiguration getTurnConfiguration() {
return turn;
}
public DynamicLoginPurchaseConfiguration getLoginPurchaseConfiguration() {
return loginPurchase;
}
}
@@ -0,0 +1,8 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration.dynamic;
/// @param enabled whether clients may exchange a one-time purchase for a Signal Login receipt credential
public record DynamicLoginPurchaseConfiguration(boolean enabled) {}
@@ -6,15 +6,23 @@
package org.whispersystems.textsecuregcm.configuration.dynamic;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.NotNull;
import java.util.Collections;
import java.util.List;
public class DynamicPaymentsConfiguration {
public record DynamicPaymentsConfiguration(@JsonProperty @NotNull List<String> disallowedPrefixes,
@JsonProperty @NotNull List<String> disallowedAsnRegions) {
@JsonProperty
private List<String> disallowedPrefixes = Collections.emptyList();
public static DynamicPaymentsConfiguration DEFAULT =
new DynamicPaymentsConfiguration(Collections.emptyList(), Collections.emptyList());
public List<String> getDisallowedPrefixes() {
return disallowedPrefixes;
public DynamicPaymentsConfiguration {
if (disallowedPrefixes == null) {
disallowedPrefixes = DEFAULT.disallowedPrefixes();
}
if (disallowedAsnRegions == null) {
disallowedAsnRegions = DEFAULT.disallowedAsnRegions();
}
}
}
@@ -4,12 +4,7 @@
*/
package org.whispersystems.textsecuregcm.controllers;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import io.dropwizard.auth.Auth;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Schema;
@@ -30,11 +25,13 @@ import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.Response.Status;
import java.util.Base64;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
@@ -58,20 +55,19 @@ import org.whispersystems.textsecuregcm.entities.ReserveUsernameHashResponse;
import org.whispersystems.textsecuregcm.entities.UsernameHashResponse;
import org.whispersystems.textsecuregcm.entities.UsernameLinkHandle;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.limits.RateLimitedByIp;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
import org.whispersystems.textsecuregcm.storage.PhoneNumberRecoveryPasswordsManager;
import org.whispersystems.textsecuregcm.storage.UsernameHashNotAvailableException;
import org.whispersystems.textsecuregcm.storage.UsernameReservationNotFoundException;
import org.whispersystems.textsecuregcm.util.HeaderUtils;
import org.whispersystems.textsecuregcm.util.UsernameHashZkProofVerifier;
import org.whispersystems.textsecuregcm.util.Util;
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem;
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
@Path("/v1/accounts")
@@ -81,23 +77,19 @@ public class AccountController {
public static final int USERNAME_HASH_LENGTH = 32;
public static final int MAXIMUM_USERNAME_CIPHERTEXT_LENGTH = 128;
private static final String RECOVERY_PASSWORD_SET_COUNTER_NAME =
name(AccountController.class, "recoveryPasswordSet");
private final AccountsManager accounts;
private final RateLimiters rateLimiters;
private final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager;
private final PhoneNumberRecoveryPasswordsManager phoneNumberRecoveryPasswordsManager;
private final UsernameHashZkProofVerifier usernameHashZkProofVerifier;
public AccountController(
AccountsManager accounts,
RateLimiters rateLimiters,
RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager,
PhoneNumberRecoveryPasswordsManager phoneNumberRecoveryPasswordsManager,
UsernameHashZkProofVerifier usernameHashZkProofVerifier) {
this.accounts = accounts;
this.rateLimiters = rateLimiters;
this.registrationRecoveryPasswordsManager = registrationRecoveryPasswordsManager;
this.phoneNumberRecoveryPasswordsManager = phoneNumberRecoveryPasswordsManager;
this.usernameHashZkProofVerifier = usernameHashZkProofVerifier;
}
@@ -166,8 +158,12 @@ public class AccountController {
public void setRegistrationLock(@Auth AuthenticatedDevice auth, @NotNull @Valid RegistrationLock accountLock) {
final SaltedTokenHash credentials = SaltedTokenHash.generateFor(accountLock.registrationLock());
accounts.update(auth.accountIdentifier(),
a -> a.setRegistrationLock(credentials.hash(), credentials.salt()));
try {
accounts.update(auth.accountIdentifier(),
a -> a.setRegistrationLock(credentials.hash(), credentials.salt()));
} catch (IllegalArgumentException _) {
throw new BadRequestException();
}
}
@DELETE
@@ -211,7 +207,7 @@ public class AccountController {
throw new ForbiddenException();
}
accounts.updateDevice(account.getIdentifier(IdentityType.ACI), targetDeviceId, d -> d.setName(deviceName.deviceName()));
accounts.updateDevice(account.getAccountIdentifier(), targetDeviceId, d -> d.setName(deviceName.deviceName()));
}
@PUT
@@ -220,11 +216,19 @@ public class AccountController {
@Produces(MediaType.APPLICATION_JSON)
public void setAccountAttributes(
@Auth AuthenticatedDevice auth,
@HeaderParam(HttpHeaders.USER_AGENT) String userAgent,
@HeaderParam(HeaderUtils.X_SIGNAL_AGENT) String signalAgent,
@NotNull @Valid AccountAttributes attributes) {
final Account updatedAccount = accounts.update(auth.accountIdentifier(), a -> {
final Account account = accounts.getByAccountIdentifier(auth.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
final Collection<TransactWriteItem> additionalWriteItems =
account.getPhoneNumberIdentifierOptional()
.flatMap(phoneNumberIdentifier -> attributes.recoveryPassword().map(recoveryPassword ->
List.of(phoneNumberRecoveryPasswordsManager.buildTransactWriteItemForStorePassword(phoneNumberIdentifier, recoveryPassword))))
.orElseGet(Collections::emptyList);
accounts.update(auth.accountIdentifier(), a -> {
a.getDevice(auth.deviceId()).ifPresent(d -> {
d.setFetchesMessages(attributes.getFetchesMessages());
d.setName(attributes.getName());
@@ -238,18 +242,15 @@ public class AccountController {
a.setRegistrationLockFromAttributes(attributes);
a.setUnidentifiedAccessKey(attributes.getUnidentifiedAccessKey());
a.setUnrestrictedUnidentifiedAccess(attributes.isUnrestrictedUnidentifiedAccess());
a.setDiscoverableByPhoneNumber(attributes.isDiscoverableByPhoneNumber());
});
// if registration recovery password was sent to us, store it (or refresh its expiration)
attributes.recoveryPassword().ifPresent(registrationRecoveryPassword -> {
final boolean rrpCreated = registrationRecoveryPasswordsManager
.store(updatedAccount.getIdentifier(IdentityType.PNI), registrationRecoveryPassword);
Metrics.counter(RECOVERY_PASSWORD_SET_COUNTER_NAME, Tags.of(
UserAgentTagUtil.getPlatformTag(userAgent),
Tag.of("outcome", rrpCreated ? "created" : "updated")))
.increment();
});
if (attributes.isDiscoverableByPhoneNumber() && a.getNumberOptional().isEmpty()) {
throw new BadRequestException("account does not have a phone number");
}
a.setDiscoverableByPhoneNumber(attributes.isDiscoverableByPhoneNumber());
attributes.recoveryPassword().ifPresent(a::setAccountRecoveryPassword);
}, additionalWriteItems);
}
@GET
@@ -389,7 +390,7 @@ public class AccountController {
throw new WebApplicationException(Response.status(422).build());
}
return accounts.getByUsernameHash(hash).thenApply(maybeAccount -> maybeAccount.map(Account::getUuid)
return accounts.getByUsernameHash(hash).thenApply(maybeAccount -> maybeAccount.map(Account::getAccountIdentifier)
.map(AciServiceIdentifier::new)
.map(AccountIdentifierResponse::new)
.orElseThrow(() -> new WebApplicationException(Status.NOT_FOUND)));
@@ -433,7 +434,7 @@ public class AccountController {
} else {
usernameLinkHandle = UUID.randomUUID();
}
updateUsernameLink(account.getIdentifier(IdentityType.ACI), usernameLinkHandle, encryptedUsername.usernameLinkEncryptedValue());
updateUsernameLink(account.getAccountIdentifier(), usernameLinkHandle, encryptedUsername.usernameLinkEncryptedValue());
return new UsernameLinkHandle(usernameLinkHandle);
}
@@ -155,8 +155,13 @@ public class AccountControllerV2 {
@Auth AuthenticatedDevice auth,
@NotNull @Valid PhoneNumberDiscoverabilityRequest phoneNumberDiscoverability) {
accountsManager.update(auth.accountIdentifier(), a -> a.setDiscoverableByPhoneNumber(
phoneNumberDiscoverability.discoverableByPhoneNumber()));
accountsManager.update(auth.accountIdentifier(), account -> {
if (account.getNumberOptional().isEmpty()) {
throw new BadRequestException();
}
account.setDiscoverableByPhoneNumber(phoneNumberDiscoverability.discoverableByPhoneNumber());
});
}
@GET
@@ -174,7 +179,7 @@ public class AccountControllerV2 {
return new AccountDataReportResponse(UUID.randomUUID(), Instant.now(),
new AccountDataReportResponse.AccountAndDevicesDataReport(
new AccountDataReportResponse.AccountDataReport(
account.getNumber(),
account.getNumberOptional(),
account.getBadges().stream().map(AccountDataReportResponse.BadgeDataReport::new).toList(),
account.isUnrestrictedUnidentifiedAccess(),
account.isDiscoverableByPhoneNumber()),
@@ -18,18 +18,18 @@ public class AccountIdentityResponseBuilder {
private boolean storageCapable;
private Clock clock;
public AccountIdentityResponseBuilder(Account account) {
public AccountIdentityResponseBuilder(final Account account) {
this.account = account;
this.storageCapable = account.hasCapability(DeviceCapability.STORAGE);
this.clock = Clock.systemUTC();
}
public AccountIdentityResponseBuilder storageCapable(boolean storageCapable) {
public AccountIdentityResponseBuilder storageCapable(final boolean storageCapable) {
this.storageCapable = storageCapable;
return this;
}
public AccountIdentityResponseBuilder clock(Clock clock) {
public AccountIdentityResponseBuilder clock(final Clock clock) {
this.clock = clock;
return this;
}
@@ -47,13 +47,14 @@ public class AccountIdentityResponseBuilder {
.map(bv -> new Entitlements.BackupEntitlement(bv.receiptLevel(), bv.expiration()))
.orElse(null);
return new AccountIdentityResponse(account.getUuid(),
account.getNumber(),
account.getPhoneNumberIdentifier(),
return new AccountIdentityResponse(account.getAccountIdentifier(),
account.getNumberOptional(),
account.getPhoneNumberIdentifierOptional(),
account.getUsernameHash().filter(h -> h.length > 0).orElse(null),
account.getUsernameLinkHandle(),
storageCapable,
new Entitlements(badges, backupEntitlement));
new Entitlements(badges, backupEntitlement),
account.getAuthCredentialSalt().orElse(null));
}
public static AccountIdentityResponse fromAccount(final Account account) {
@@ -975,7 +975,7 @@ public class ArchiveController {
final AuthenticatedBackupUser backupUser =
backupManager.authenticateBackupUser(presentation.presentation, signature.signature, userAgent);
final BackupManager.ListMediaResult listResult =
backupManager.list(backupUser, cursor, limit.orElse(1000));
backupManager.list(backupUser, cursor, limit);
return new ListResponse(listResult.media()
.stream().map(entry -> new StoredMediaObject(entry.cdn(), entry.key(), entry.length()))
.toList(),
@@ -26,6 +26,7 @@ import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import javax.annotation.Nonnull;
import org.signal.libsignal.protocol.ServiceId;
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
@@ -37,11 +38,9 @@ import org.whispersystems.textsecuregcm.auth.CertificateGenerator;
import org.whispersystems.textsecuregcm.auth.RedemptionRange;
import org.whispersystems.textsecuregcm.entities.DeliveryCertificate;
import org.whispersystems.textsecuregcm.entities.GroupCredentials;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
@Path("/v1/certificate")
@Tag(name = "Certificate")
public class CertificateController {
@@ -83,8 +82,11 @@ public class CertificateController {
final Account account = accountsManager.getByAccountIdentifier(auth.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
return new DeliveryCertificate(
certificateGenerator.createFor(account, auth.deviceId(), includeE164));
try {
return new DeliveryCertificate(certificateGenerator.createFor(account, auth.deviceId(), includeE164));
} catch (final IllegalArgumentException _) {
throw new BadRequestException();
}
}
@GET
@@ -110,11 +112,16 @@ public class CertificateController {
final List<GroupCredentials.GroupCredential> credentials = new ArrayList<>();
final List<GroupCredentials.CallLinkAuthCredential> callLinkAuthCredentials = new ArrayList<>();
final ServiceId.Aci aci = new ServiceId.Aci(account.getIdentifier(IdentityType.ACI));
final ServiceId.Pni pni = new ServiceId.Pni(account.getIdentifier(IdentityType.PNI));
final ServiceId.Aci aci = new ServiceId.Aci(account.getAccountIdentifier());
final Optional<ServiceId.Pni> maybePni = account.getPhoneNumberIdentifierOptional().map(ServiceId.Pni::new);
for (Instant redemption : redemptionRange) {
AuthCredentialWithPniResponse authCredentialWithPni = serverZkAuthOperations.issueAuthCredentialWithPniZkc(aci, pni, redemption);
final AuthCredentialWithPniResponse authCredentialWithPni =
maybePni.map(pni -> serverZkAuthOperations.issueAuthCredentialWithPniZkc(aci, pni, redemption))
.orElseGet(() -> serverZkAuthOperations.issueAuthCredentialZkcWithoutPni(aci,
account.getAuthCredentialSalt()
.orElseThrow(() -> new IllegalStateException("account without PNI must have auth credential salt")),
redemption));
credentials.add(new GroupCredentials.GroupCredential(
authCredentialWithPni.serialize(),
(int) redemption.getEpochSecond()));
@@ -124,6 +131,6 @@ public class CertificateController {
redemption.getEpochSecond()));
}
return new GroupCredentials(credentials, callLinkAuthCredentials, pni.getRawUUID());
return new GroupCredentials(credentials, callLinkAuthCredentials, maybePni.map(ServiceId.Pni::getRawUUID).orElse(null));
}
}
@@ -14,6 +14,7 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.ForbiddenException;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.PUT;
@@ -29,11 +30,13 @@ import java.time.Duration;
import java.util.Base64;
import java.util.Locale;
import org.glassfish.jersey.server.ManagedAsync;
import org.signal.libsignal.zkgroup.backups.BackupLevel;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.backup.BackupAuthManager;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.devicecheck.AppleDeviceCheckManager;
import org.whispersystems.textsecuregcm.storage.devicecheck.ChallengeNotFoundException;
import org.whispersystems.textsecuregcm.storage.devicecheck.DeviceCheckKeyIdNotFoundException;
@@ -59,7 +62,6 @@ public class DeviceCheckController {
private final BackupAuthManager backupAuthManager;
private final AppleDeviceCheckManager deviceCheckManager;
private final RateLimiters rateLimiters;
private final long backupRedemptionLevel;
private final Duration backupRedemptionDuration;
public DeviceCheckController(
@@ -68,13 +70,11 @@ public class DeviceCheckController {
final BackupAuthManager backupAuthManager,
final AppleDeviceCheckManager deviceCheckManager,
final RateLimiters rateLimiters,
final long backupRedemptionLevel,
final Duration backupRedemptionDuration) {
this.clock = clock;
this.accountsManager = accountsManager;
this.backupAuthManager = backupAuthManager;
this.deviceCheckManager = deviceCheckManager;
this.backupRedemptionLevel = backupRedemptionLevel;
this.backupRedemptionDuration = backupRedemptionDuration;
this.rateLimiters = rateLimiters;
}
@@ -141,6 +141,10 @@ public class DeviceCheckController {
@RequestBody(description = "The attestation data, created by [attestKey](https://developer.apple.com/documentation/devicecheck/dcappattestservice/attestkey(_:clientdatahash:completionhandler:))")
@NotNull final byte[] attestation) {
if (authenticatedDevice.deviceId() != Device.PRIMARY_ID) {
throw new ForbiddenException("Only primary devices may register attestations");
}
final Account account = accountsManager.getByAccountIdentifier(authenticatedDevice.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
@@ -252,7 +256,7 @@ public class DeviceCheckController {
switch (request.assertionRequest().action()) {
case BACKUP -> backupAuthManager.extendBackupVoucher(
account,
new Account.BackupVoucher(backupRedemptionLevel, clock.instant().plus(backupRedemptionDuration)));
new Account.BackupVoucher(BackupLevel.PAID.getValue(), clock.instant().plus(backupRedemptionDuration)));
}
}
@@ -42,11 +42,13 @@ import java.util.EnumMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.apache.commons.lang3.ObjectUtils;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.BasicAuthorizationHeader;
import org.whispersystems.textsecuregcm.auth.ChangesLinkedDevices;
@@ -72,6 +74,7 @@ import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import org.whispersystems.textsecuregcm.storage.DeviceIdentityInfo;
import org.whispersystems.textsecuregcm.storage.DeviceSpec;
import org.whispersystems.textsecuregcm.storage.LinkDeviceTokenAlreadyUsedException;
import org.whispersystems.textsecuregcm.storage.PersistentTimer;
@@ -196,7 +199,7 @@ public class DeviceController {
final Account account = accounts.getByAccountIdentifier(auth.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
rateLimiters.getAllocateDeviceLimiter().validate(account.getUuid());
rateLimiters.getAllocateDeviceLimiter().validate(account.getAccountIdentifier());
if (account.getDevices().size() >= MAX_DEVICES) {
throw new DeviceLimitExceededException(account.getDevices().size(), MAX_DEVICES);
@@ -206,7 +209,7 @@ public class DeviceController {
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
}
final String token = accounts.generateLinkDeviceToken(account.getUuid());
final String token = accounts.generateLinkDeviceToken(account.getAccountIdentifier());
return new LinkDeviceToken(token, AccountsManager.getLinkDeviceTokenIdentifier(token));
}
@@ -222,7 +225,7 @@ public class DeviceController {
""")
@ApiResponse(responseCode = "200", description = "The new device was linked to the calling account", useReturnTypeSchema = true)
@ApiResponse(responseCode = "403", description = "The given account was not found or the given verification code was incorrect")
@ApiResponse(responseCode = "409", description = "The new device is missing a capability supported by all other devices on the account")
@ApiResponse(responseCode = "409", description = "The new device is missing a capability required for the account")
@ApiResponse(responseCode = "411", description = "The given account already has its maximum number of linked devices")
@ApiResponse(responseCode = "422", description = "The request did not pass validation")
@ApiResponse(responseCode = "429", description = "Too many attempts", headers = @Header(
@@ -232,7 +235,6 @@ public class DeviceController {
@HeaderParam(HttpHeaders.USER_AGENT) @Nullable String userAgent,
@NotNull @Valid LinkDeviceRequest linkDeviceRequest)
throws RateLimitExceededException, DeviceLimitExceededException {
final Account account = accounts.checkDeviceLinkingToken(linkDeviceRequest.verificationCode())
.flatMap(accounts::getByAccountIdentifier)
.orElseThrow(ForbiddenException::new);
@@ -240,17 +242,33 @@ public class DeviceController {
final DeviceActivationRequest deviceActivationRequest = linkDeviceRequest.deviceActivationRequest();
final DeviceAttributes deviceAttributes = linkDeviceRequest.deviceAttributes();
rateLimiters.getVerifyDeviceLimiter().validate(account.getUuid());
rateLimiters.getVerifyDeviceLimiter().validate(account.getAccountIdentifier());
// Check the optional-phone-number capability before checking PNI keys, so we can give a better error code (since an
// older device will improperly supply PNI keys for a PNI-less account)
if (account.getPhoneNumberIdentifierOptional().isEmpty() &&
!linkDeviceRequest.deviceAttributes().capabilities().contains(DeviceCapability.OPTIONAL_PHONE_NUMBER)) {
throw new WebApplicationException("Missing required device capability", 409);
}
final boolean allKeysValid =
PreKeySignatureValidator.validatePreKeySignatures(account.getIdentityKey(IdentityType.ACI),
List.of(deviceActivationRequest.aciSignedPreKey(), deviceActivationRequest.aciPqLastResortPreKey()),
userAgent,
"link-device")
&& PreKeySignatureValidator.validatePreKeySignatures(account.getIdentityKey(IdentityType.PNI),
List.of(deviceActivationRequest.pniSignedPreKey(), deviceActivationRequest.pniPqLastResortPreKey()),
userAgent,
"link-device");
PreKeySignatureValidator
.validatePreKeySignatures(account.getAccountIdentityKey(),
List.of(deviceActivationRequest.aciSignedPreKey(), deviceActivationRequest.aciPqLastResortPreKey()),
userAgent,
"link-device")
&& account.getPhoneNumberIdentityKey()
.map(pniIdentityKey ->
deviceActivationRequest.pniSignedPreKey().isPresent()
&& deviceActivationRequest.pniPqLastResortPreKey().isPresent()
&& PreKeySignatureValidator.validatePreKeySignatures(
pniIdentityKey,
List.of(deviceActivationRequest.pniSignedPreKey().get(), deviceActivationRequest.pniPqLastResortPreKey().get()),
userAgent,
"link-device"))
.orElse(
deviceActivationRequest.pniSignedPreKey().isEmpty()
&& deviceActivationRequest.pniPqLastResortPreKey().isEmpty());
if (!allKeysValid) {
throw new WebApplicationException(Response.status(422).build());
@@ -279,25 +297,28 @@ public class DeviceController {
}
try {
final Pair<Account, Device> accountAndDevice = accounts.addDevice(account.getIdentifier(IdentityType.ACI),
final Pair<Account, Device> accountAndDevice = accounts.addDevice(account.getAccountIdentifier(),
new DeviceSpec(deviceAttributes.name(),
authorizationHeader.getPassword(),
signalAgent,
capabilities,
deviceAttributes.registrationId(),
deviceAttributes.phoneNumberIdentityRegistrationId(),
new DeviceIdentityInfo(
deviceAttributes.registrationId(),
deviceActivationRequest.aciSignedPreKey(),
deviceActivationRequest.aciPqLastResortPreKey()),
account.getPhoneNumberIdentityKey().map(_ ->
new DeviceIdentityInfo(
deviceAttributes.phoneNumberIdentityRegistrationId(),
deviceActivationRequest.pniSignedPreKey().get(),
deviceActivationRequest.pniPqLastResortPreKey().get())),
deviceAttributes.fetchesMessages(),
deviceActivationRequest.apnToken(),
deviceActivationRequest.gcmToken(),
deviceActivationRequest.aciSignedPreKey(),
deviceActivationRequest.pniSignedPreKey(),
deviceActivationRequest.aciPqLastResortPreKey(),
deviceActivationRequest.pniPqLastResortPreKey()),
deviceActivationRequest.gcmToken()),
linkDeviceRequest.verificationCode());
return new LinkDeviceResponse(
accountAndDevice.first().getIdentifier(IdentityType.ACI),
accountAndDevice.first().getIdentifier(IdentityType.PNI),
accountAndDevice.first().getAccountIdentifier(),
accountAndDevice.first().getPhoneNumberIdentifierOptional(),
accountAndDevice.second().getId());
} catch (final LinkDeviceTokenAlreadyUsedException e) {
throw new ForbiddenException();
@@ -41,6 +41,7 @@ import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.DonationPermitsManager;
import org.whispersystems.textsecuregcm.storage.RedeemedReceiptsManager;
import org.whispersystems.textsecuregcm.subscriptions.ReceiptCredentialPresentationFactory;
import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel;
@Path("/v1/donation")
@Tag(name = "Donations")
@@ -117,7 +118,10 @@ public class DonationController {
final ReceiptSerial receiptSerial = receiptCredentialPresentation.getReceiptSerial();
final Instant receiptExpiration = Instant.ofEpochSecond(receiptCredentialPresentation.getReceiptExpirationTime());
final long receiptLevel = receiptCredentialPresentation.getReceiptLevel();
final String badgeId = badgesConfiguration.getReceiptLevels().get(receiptLevel);
final String badgeId = ReceiptLevel
.lookupLevel(receiptLevel)
.map(badgesConfiguration.getReceiptLevels()::get)
.orElse(null);
if (badgeId == null) {
return Response.serverError()
.entity("server does not recognize the requested receipt level")
@@ -108,6 +108,7 @@ public class KeysController {
@Operation(summary = "Get prekey count",
description = "Gets the number of one-time prekeys uploaded for this device and still available")
@ApiResponse(responseCode = "200", description = "Body contains the number of available one-time prekeys for the device.", useReturnTypeSchema = true)
@ApiResponse(responseCode = "400", description = "The request was malformed or the account does not support the requested identityType")
@ApiResponse(responseCode = "401", description = "Account authentication check failed.")
public CompletableFuture<PreKeyCount> getStatus(@Auth final AuthenticatedDevice auth,
@QueryParam("identity") @DefaultValue("aci") final IdentityType identityType) {
@@ -115,12 +116,13 @@ public class KeysController {
return accounts.getByAccountIdentifierAsync(auth.accountIdentifier())
.thenCompose(maybeAccount -> {
final Account account = maybeAccount.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
final UUID identifier = getIdentifier(account, identityType);
final CompletableFuture<Integer> ecCountFuture =
keysManager.getEcCount(account.getIdentifier(identityType), auth.deviceId());
keysManager.getEcCount(identifier, auth.deviceId());
final CompletableFuture<Integer> pqCountFuture =
keysManager.getPqCount(account.getIdentifier(identityType), auth.deviceId());
keysManager.getPqCount(identifier, auth.deviceId());
return ecCountFuture.thenCombine(pqCountFuture, PreKeyCount::new);
});
@@ -131,6 +133,7 @@ public class KeysController {
@Produces(MediaType.APPLICATION_JSON)
@Operation(summary = "Upload new prekeys", description = "Upload new pre-keys for this device.")
@ApiResponse(responseCode = "200", description = "Indicates that new keys were successfully stored.")
@ApiResponse(responseCode = "400", description = "The request was malformed or the account does not support the requested identityType")
@ApiResponse(responseCode = "401", description = "Account authentication check failed.")
@ApiResponse(responseCode = "403", description = "Attempt to change identity key from a non-primary device.")
@ApiResponse(responseCode = "422", description = "Invalid request format.")
@@ -154,7 +157,7 @@ public class KeysController {
final Device device = account.getDevice(auth.deviceId())
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
final UUID identifier = account.getIdentifier(identityType);
final UUID identifier = getIdentifier(account, identityType);
checkSignedPreKeySignatures(setKeysRequest, account.getIdentityKey(identityType), userAgent);
@@ -244,6 +247,7 @@ public class KeysController {
version byte followed by 1568 bytes of key material for a total of 1569 bytes)
""")
@ApiResponse(responseCode = "200", description = "Indicates that client and server have consistent views of repeated-use keys")
@ApiResponse(responseCode = "400", description = "The request was malformed or the account does not support the requested identityType")
@ApiResponse(responseCode = "401", description = "Account authentication check failed")
@ApiResponse(responseCode = "409", description = """
Indicates that client and server have inconsistent views of repeated-use keys or one or more repeated-use keys could
@@ -258,7 +262,7 @@ public class KeysController {
.thenCompose(maybeAccount -> {
final Account account = maybeAccount.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
final UUID identifier = account.getIdentifier(checkKeysRequest.identityType());
final UUID identifier = getIdentifier(account, checkKeysRequest.identityType());
final byte deviceId = auth.deviceId();
final CompletableFuture<Optional<ECSignedPreKey>> ecSignedPreKeyFuture =
@@ -426,10 +430,20 @@ public class KeysController {
.flatMap(targetAccount::getDevice)
.map(device -> device.getRegistrationId(targetIdentifier.identityType()));
return RateLimitKeys.preKeyLimiterKey(
account.getUuid(),
account.getAccountIdentifier(),
authenticatedDevice.deviceId(),
targetIdentifier,
parsedTargetDeviceId, targetRegistrationId);
}
/// Get the identity of the requested `idenityType`, or throw a [BadRequestException] if `account` does not contain
/// that type.
private UUID getIdentifier(final Account account, final IdentityType identityType) {
return switch (identityType) {
case ACI -> account.getAccountIdentifier();
case PNI -> account.getPhoneNumberIdentifierOptional().orElseThrow(() ->
new BadRequestException("Cannot set PNI identity keys on an account without a number"));
};
}
}
@@ -0,0 +1,127 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.controllers;
import io.dropwizard.auth.Auth;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.headers.Header;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import jakarta.ws.rs.BadRequestException;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.ForbiddenException;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import java.io.IOException;
import java.util.Optional;
import org.glassfish.jersey.server.ManagedAsync;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.VerificationFailedException;
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialRequest;
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialResponse;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.mappers.SubscriptionExceptionMapper;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.subscriptions.LoginPurchaseManager;
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidArgumentsException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionNotFoundException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentRequiredException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptAlreadyRedeemedException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptRequestedForOpenPaymentException;
@Path("/v1/login-purchase")
@io.swagger.v3.oas.annotations.tags.Tag(name = "LoginPurchase")
public class LoginPurchaseController {
private final LoginPurchaseManager loginPurchaseManager;
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
public LoginPurchaseController(
final LoginPurchaseManager loginPurchaseManager,
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
this.loginPurchaseManager = loginPurchaseManager;
this.dynamicConfigurationManager = dynamicConfigurationManager;
}
public record CreateLoginReceiptCredentialRequest(
@NotNull String purchaseIdentifier,
@NotNull byte[] receiptCredentialRequest,
@NotNull PaymentProvider paymentProvider) {
}
public record CreateLoginReceiptCredentialResponse(byte[] receiptCredentialResponse) {
}
@POST
@Path("/receipt_credentials")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Operation(summary = "Create a receipt credential for a completed one-time login purchase",
description = """
Verify a completed one-time purchase with the payment provider and issue a receipt credential that can be
redeemed for a login.
This endpoint must be called on an unauthenticated connection. Retries for the same purchaseIdentifier MUST
use the same receiptCredentialRequest.
""")
@ApiResponse(responseCode = "200", description = "Successfully created receipt",
content = @Content(schema = @Schema(implementation = CreateLoginReceiptCredentialResponse.class)))
@ApiResponse(responseCode = "204", description = "The purchase is still pending with the payment provider. The client may retry later.")
@ApiResponse(responseCode = "400", description = """
Invalid request: malformed request, failed zkgroup verification, unsupported paymentProvider, the provided
purchase identifier not for a Signal Login, or login purchases are not currently enabled.
""")
@ApiResponse(responseCode = "402", description = "The purchase did not complete successfully. The body may include ChargeFailure details.",
content = @Content(schema = @Schema(
nullable = true,
implementation = SubscriptionExceptionMapper.ChargeFailureResponse.class)))
@ApiResponse(responseCode = "403", description = "The request was made on an authenticated channel")
@ApiResponse(responseCode = "404", description = "The payment provider has no purchase with the provided purchaseIdentifier")
@ApiResponse(responseCode = "409", description = "The purchase was already redeemed for a receipt credential, but with a different receipt credential request")
@ApiResponse(responseCode = "429", description = "Too many attempts", headers = @Header(
name = "Retry-After",
description = "If present, a positive integer indicating the number of seconds before a subsequent attempt could succeed"))
@ManagedAsync
public Response createLoginReceiptCredential(
@Auth final Optional<AuthenticatedDevice> authenticatedAccount,
@NotNull @Valid final CreateLoginReceiptCredentialRequest request)
throws IOException, SubscriptionPaymentRequiredException, SubscriptionInvalidArgumentsException, SubscriptionNotFoundException, RateLimitExceededException, SubscriptionReceiptAlreadyRedeemedException {
if (!dynamicConfigurationManager.getConfiguration().getLoginPurchaseConfiguration().enabled()) {
throw new BadRequestException("login purchases are not enabled");
}
if (authenticatedAccount.isPresent()) {
throw new ForbiddenException("must not use authenticated connection for login purchase operations");
}
final ReceiptCredentialRequest receiptCredentialRequest;
try {
receiptCredentialRequest = new ReceiptCredentialRequest(request.receiptCredentialRequest);
} catch (final InvalidInputException e) {
throw new BadRequestException("invalid receipt credential request", e);
}
try {
final ReceiptCredentialResponse receiptCredentialResponse = loginPurchaseManager.generateReceipt(
request.paymentProvider, request.purchaseIdentifier, receiptCredentialRequest);
return Response.ok(
new CreateLoginReceiptCredentialResponse(receiptCredentialResponse.serialize()))
.build();
} catch (SubscriptionReceiptRequestedForOpenPaymentException e) {
return Response.noContent().build();
} catch (VerificationFailedException e) {
throw new BadRequestException("receipt credential request failed verification", e);
}
}
}
@@ -263,7 +263,7 @@ public class MessageController {
final Account destination =
accountsManager.getByServiceIdentifier(destinationIdentifier).orElseThrow(NotFoundException::new);
rateLimiters.getMessagesLimiter().validate(source.accountIdentifier(), destination.getUuid());
rateLimiters.getMessagesLimiter().validate(source.accountIdentifier(), destination.getAccountIdentifier());
sendIndividualMessage(destination,
destinationIdentifier,
@@ -335,7 +335,7 @@ public class MessageController {
final Account destination = accountsManager.getByServiceIdentifier(destinationIdentifier).orElseThrow(() ->
new WebApplicationException(Response.ok(new SendMessageResponse(false)).build()));
rateLimiters.getStoriesLimiter().validate(destination.getUuid());
rateLimiters.getStoriesLimiter().validate(destination.getAccountIdentifier());
sendIndividualMessage(destination,
destinationIdentifier,
@@ -740,15 +740,17 @@ public class MessageController {
final Optional<UUID> sourceAci;
final Optional<UUID> sourcePni;
boolean sourceAccountDeleted = false;
if (source.startsWith("+")) {
sourceNumber = Optional.of(source);
final Optional<Account> maybeAccount = accountsManager.getByE164(source);
if (maybeAccount.isPresent()) {
sourceAci = maybeAccount.map(Account::getUuid);
sourcePni = maybeAccount.map(Account::getPhoneNumberIdentifier);
sourceAci = maybeAccount.map(Account::getAccountIdentifier);
sourcePni = maybeAccount.flatMap(Account::getPhoneNumberIdentifierOptional);
} else {
sourcePni = Optional.ofNullable(phoneNumberIdentifiers.getPhoneNumberIdentifier(source).join());
sourceAci = sourcePni.flatMap(accountsManager::findRecentlyDeletedAccountIdentifier);
sourceAccountDeleted = true;
}
} else {
sourceAci = Optional.of(UUID.fromString(source));
@@ -760,13 +762,14 @@ public class MessageController {
sourcePni = accountsManager.findRecentlyDeletedPhoneNumberIdentifier(sourceAci.get());
sourceNumber = sourcePni.flatMap(pni ->
Util.getCanonicalNumber(phoneNumberIdentifiers.getPhoneNumber(pni).join()));
sourceAccountDeleted = true;
} else {
sourceNumber = sourceAccount.map(Account::getNumber);
sourcePni = sourceAccount.map(Account::getPhoneNumberIdentifier);
sourceNumber = sourceAccount.flatMap(Account::getNumberOptional);
sourcePni = sourceAccount.flatMap(Account::getPhoneNumberIdentifierOptional);
}
}
UUID spamReporterUuid = auth.accountIdentifier();
final UUID spamReporterUuid = auth.accountIdentifier();
// spam report token is optional, but if provided ensure it is non-empty.
final Optional<byte[]> maybeSpamReportToken =
@@ -774,7 +777,7 @@ public class MessageController {
.flatMap(r -> Optional.ofNullable(r.token()))
.filter(t -> t.length > 0);
reportMessageManager.report(sourceNumber, sourceAci, sourcePni, messageGuid, spamReporterUuid, maybeSpamReportToken, userAgent);
reportMessageManager.report(sourceNumber, sourceAci, sourcePni, messageGuid, spamReporterUuid, maybeSpamReportToken, userAgent, sourceAccountDeleted);
return Response.status(Status.ACCEPTED)
.build();
@@ -350,8 +350,8 @@ public class OneTimeDonationController {
}
final Optional<PaymentDetails> maybePaymentDetails = (switch (request.processor) {
case STRIPE -> stripeManager.getPaymentDetails(request.paymentIntentId);
case BRAINTREE -> braintreeManager.getPaymentDetails(request.paymentIntentId);
case STRIPE -> stripeManager.claimOneTimePurchase(request.paymentIntentId);
case BRAINTREE -> braintreeManager.claimOneTimePurchase(request.paymentIntentId);
case GOOGLE_PLAY_BILLING -> throw new BadRequestException("cannot use play billing for one-time donations");
case APPLE_APP_STORE -> throw new BadRequestException("cannot use app store purchases for one-time donations");
});
@@ -383,21 +383,21 @@ public class OneTimeDonationController {
} catch (final InvalidInputException e) {
throw new BadRequestException("invalid receipt credential request", e);
}
try {
issuedReceiptsManager.recordIssuance(paymentDetails.id(), request.processor,
receiptCredentialRequest, clock.instant());
} catch (WriteConflictException _) {
throw new WebApplicationException(Response.Status.CONFLICT);
}
final Instant paidAt = oneTimeDonationsManager.getPaidAt(paymentDetails.id(), paymentDetails.created());
final Instant paidAt = oneTimeDonationsManager.getPaidAt(request.processor, paymentDetails.id(), paymentDetails.created());
final Instant expiration = paidAt
.plus(levelDetails.levelExpiration())
.truncatedTo(ChronoUnit.DAYS)
.plus(1, ChronoUnit.DAYS);
try {
issuedReceiptsManager.recordOneTimeIssuance(paymentDetails.id(), request.processor,
receiptCredentialRequest, expiration);
} catch (WriteConflictException _) {
throw new WebApplicationException(Response.Status.CONFLICT);
}
final ReceiptCredentialResponse receiptCredentialResponse;
try {
receiptCredentialResponse = zkReceiptOperations.issueReceiptCredential(
receiptCredentialRequest, expiration.getEpochSecond(), levelDetails.level());
receiptCredentialRequest, expiration.getEpochSecond(), levelDetails.level().getValue());
} catch (final VerificationFailedException e) {
throw new BadRequestException("receipt credential request failed verification", e);
}
@@ -50,6 +50,7 @@ import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.glassfish.jersey.server.ManagedAsync;
@@ -64,6 +65,7 @@ import org.signal.libsignal.zkgroup.profiles.ExpiringProfileKeyCredentialRespons
import org.signal.libsignal.zkgroup.profiles.ProfileKeyCommitment;
import org.signal.libsignal.zkgroup.profiles.ProfileKeyCredentialRequest;
import org.signal.libsignal.zkgroup.profiles.ServerZkProfileOperations;
import org.whispersystems.textsecuregcm.asn.AsnInfoProvider;
import org.whispersystems.textsecuregcm.auth.Anonymous;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.GroupSendTokenHeader;
@@ -80,6 +82,7 @@ import org.whispersystems.textsecuregcm.entities.CreateProfileRequest;
import org.whispersystems.textsecuregcm.entities.ExpiringProfileKeyCredentialProfileResponse;
import org.whispersystems.textsecuregcm.entities.ProfileAvatarUploadAttributes;
import org.whispersystems.textsecuregcm.entities.VersionedProfileResponse;
import org.whispersystems.textsecuregcm.filters.RemoteAddressFilter;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier;
@@ -108,6 +111,7 @@ public class ProfileController {
private final RateLimiters rateLimiters;
private final ProfilesManager profilesManager;
private final AccountsManager accountsManager;
private final Supplier<AsnInfoProvider> asnInfoProviderSupplier;
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
private final ProfileBadgeConverter profileBadgeConverter;
private final Map<String, BadgeConfiguration> badgeConfigurationMap;
@@ -124,25 +128,27 @@ public class ProfileController {
private static final String DUPLICATE_AUTHENTICATION_COUNTER_NAME = name(ProfileController.class, "duplicateAuthentication");
public ProfileController(
Clock clock,
RateLimiters rateLimiters,
AccountsManager accountsManager,
ProfilesManager profilesManager,
DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
ProfileBadgeConverter profileBadgeConverter,
BadgesConfiguration badgesConfiguration,
PostPolicyGenerator policyGenerator,
ServerSecretParams serverSecretParams,
ServerZkProfileOperations zkProfileOperations,
Executor batchIdentityCheckExecutor) {
final Clock clock,
final RateLimiters rateLimiters,
final AccountsManager accountsManager,
final ProfilesManager profilesManager,
final Supplier<AsnInfoProvider> asnInfoProviderSupplier,
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
final ProfileBadgeConverter profileBadgeConverter,
final BadgesConfiguration badgesConfiguration,
final PostPolicyGenerator policyGenerator,
final ServerSecretParams serverSecretParams,
final ServerZkProfileOperations zkProfileOperations,
final Executor batchIdentityCheckExecutor) {
this.clock = clock;
this.rateLimiters = rateLimiters;
this.accountsManager = accountsManager;
this.profilesManager = profilesManager;
this.asnInfoProviderSupplier = asnInfoProviderSupplier;
this.dynamicConfigurationManager = dynamicConfigurationManager;
this.profileBadgeConverter = profileBadgeConverter;
this.badgeConfigurationMap = badgesConfiguration.getBadges().stream().collect(Collectors.toMap(
BadgeConfiguration::getId, Function.identity()));
this.badgeConfigurationMap = badgesConfiguration.getBadges().stream()
.collect(Collectors.toMap(BadgeConfiguration::getId, Function.identity()));
this.serverSecretParams = serverSecretParams;
this.zkProfileOperations = zkProfileOperations;
this.policyGenerator = policyGenerator;
@@ -161,10 +167,12 @@ public class ProfileController {
description = "If the request changed the avatar, the response body contains an upload form.")))
@ApiResponse(responseCode = "400", description = "Invalid create profile request.")
@ApiResponse(responseCode = "401", description = "Account authentication check failed.")
@ApiResponse(responseCode = "403", description = "The request contained a payment address, but payments are not supported in the region of the account’s phone number.")
@ApiResponse(responseCode = "403", description = "The request contained a payment address, but payments are not supported in the region of the account’s phone number or the caller's ASN if the account does not have a phone number.")
@ApiResponse(responseCode = "412", description = "The requesting account has the profiles_v2 capability")
@ApiResponse(responseCode = "422", description = "Invalid request format")
public Response setProfile(@Auth AuthenticatedDevice auth, @NotNull @Valid CreateProfileRequest request) {
public Response setProfile(@Auth AuthenticatedDevice auth,
@NotNull @Valid CreateProfileRequest request,
@Context final ContainerRequestContext requestContext) {
final Account account = accountsManager.getByAccountIdentifier(auth.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
@@ -176,7 +184,12 @@ public class ProfileController {
final Optional<VersionedProfileV1> currentProfile =
profilesManager.getV1(auth.accountIdentifier(), request.version());
if (request.paymentAddress() != null && request.paymentAddress().length != 0 && ProfileHelper.isPaymentAddressUpdateForbidden(account, Optional.empty(), currentProfile, dynamicConfigurationManager)) {
final String remoteAddress = (String) requestContext.getProperty(RemoteAddressFilter.REMOTE_ADDRESS_ATTRIBUTE_NAME);
if (request.paymentAddress() != null &&
request.paymentAddress().length != 0 &&
ProfileHelper.isPaymentAddressUpdateForbidden(account, Optional.empty(), currentProfile, remoteAddress, asnInfoProviderSupplier.get(), dynamicConfigurationManager)) {
return Response.status(Response.Status.FORBIDDEN).build();
}
@@ -198,7 +211,7 @@ public class ProfileController {
currentAvatar.ifPresent(profilesManager::deleteAvatar);
}
accountsManager.update(account.getIdentifier(IdentityType.ACI), a -> {
accountsManager.update(account.getAccountIdentifier(), a -> {
final List<AccountBadge> updatedBadges = request.badges()
.map(badges -> ProfileHelper.mergeBadgeIdsWithExistingAccountBadges(clock, badgeConfigurationMap, badges, a.getBadges()))
@@ -245,7 +258,7 @@ public class ProfileController {
return buildVersionedProfileResponse(targetAccount,
version,
maybeRequester.map(requester -> ProfileHelper.isSelfProfileRequest(requester.getUuid(), accountIdentifier)).orElse(false),
maybeRequester.map(requester -> ProfileHelper.isSelfProfileRequest(requester.getAccountIdentifier(), accountIdentifier)).orElse(false),
false,
containerRequestContext);
}
@@ -286,7 +299,7 @@ public class ProfileController {
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED)));
final Account targetAccount = verifyPermissionToReceiveProfile(maybeRequester, accessKey, accountIdentifier, "credentialRequest", userAgent);
final boolean isSelf = maybeRequester.map(requester -> ProfileHelper.isSelfProfileRequest(requester.getUuid(), accountIdentifier)).orElse(false);
final boolean isSelf = maybeRequester.map(requester -> ProfileHelper.isSelfProfileRequest(requester.getAccountIdentifier(), accountIdentifier)).orElse(false);
return buildExpiringProfileKeyCredentialProfileResponse(targetAccount,
version,
@@ -341,7 +354,7 @@ public class ProfileController {
}
return switch (identifier.identityType()) {
case ACI -> buildBaseProfileResponseForAccountIdentity(targetAccount,
maybeRequester.map(requester -> ProfileHelper.isSelfProfileRequest(requester.getUuid(), identifier)).orElse(false),
maybeRequester.map(requester -> ProfileHelper.isSelfProfileRequest(requester.getAccountIdentifier(), identifier)).orElse(false),
containerRequestContext);
case PNI -> buildBaseProfileResponseForPhoneNumberIdentity(targetAccount);
};
@@ -426,13 +439,13 @@ public class ProfileController {
final ExpiringProfileKeyCredentialResponse expiringProfileKeyCredentialResponse;
if (account.getCurrentProfileVersion().map(v -> HexFormat.of().formatHex(v).equals(version)).orElse(false)) {
expiringProfileKeyCredentialResponse = profilesManager.getV1(account.getUuid(), version)
expiringProfileKeyCredentialResponse = profilesManager.getV1(account.getAccountIdentifier(), version)
.map(profile -> {
final ExpiringProfileKeyCredentialResponse profileKeyCredentialResponse;
try {
profileKeyCredentialResponse = ProfileHelper.getExpiringProfileKeyCredential(
new ProfileKeyCredentialRequest(HexFormat.of().parseHex(encodedCredentialRequest)),
new ProfileKeyCommitment(profile.commitment()), new ServiceId.Aci(account.getUuid()),
new ProfileKeyCommitment(profile.commitment()), new ServiceId.Aci(account.getAccountIdentifier()),
zkProfileOperations);
} catch (VerificationFailedException | InvalidInputException e) {
throw new BadRequestException(e);
@@ -455,7 +468,7 @@ public class ProfileController {
final boolean hasCredentialRequest,
final ContainerRequestContext containerRequestContext) {
final Optional<VersionedProfileV1> maybeProfile = profilesManager.getV1(account.getUuid(), version);
final Optional<VersionedProfileV1> maybeProfile = profilesManager.getV1(account.getAccountIdentifier(), version);
if (maybeProfile.isEmpty()) {
// this can happen if an account re-registers, which includes some device-transfer scenarios
@@ -498,7 +511,7 @@ public class ProfileController {
HeaderUtils.getAcceptableLanguagesForRequest(containerRequestContext),
account.getBadges(),
isSelf),
new AciServiceIdentifier(account.getUuid()));
new AciServiceIdentifier(account.getAccountIdentifier()));
}
private BaseProfileResponse buildBaseProfileResponseForPhoneNumberIdentity(final Account account) {
@@ -537,7 +550,7 @@ public class ProfileController {
}
if (maybeRequester.isPresent()) {
rateLimiters.getProfileLimiter().validate(maybeRequester.get().getUuid());
rateLimiters.getProfileLimiter().validate(maybeRequester.get().getAccountIdentifier());
}
final Optional<Account> maybeTargetAccount = accountsManager.getByServiceIdentifier(accountIdentifier);
@@ -13,6 +13,8 @@ import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.headers.Header;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
@@ -34,12 +36,16 @@ import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import java.io.IOException;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Optional;
import org.apache.commons.lang3.StringUtils;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.VerificationFailedException;
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialPresentation;
import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.auth.BasicAuthorizationHeader;
@@ -49,6 +55,7 @@ import org.whispersystems.textsecuregcm.auth.RecoveryPasswordVerificationFailedE
import org.whispersystems.textsecuregcm.auth.RegistrationLockFailureException;
import org.whispersystems.textsecuregcm.auth.RegistrationLockVerificationManager;
import org.whispersystems.textsecuregcm.auth.UnverifiedRegistrationSessionException;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.entities.AccountCreationResponse;
import org.whispersystems.textsecuregcm.entities.AccountIdentityResponse;
import org.whispersystems.textsecuregcm.entities.PhoneVerificationRequest;
@@ -61,7 +68,12 @@ import org.whispersystems.textsecuregcm.spam.RegistrationFraudChecker;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
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.subscriptions.ReceiptCredentialPresentationFactory;
import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel;
import org.whispersystems.textsecuregcm.util.HeaderUtils;
import org.whispersystems.textsecuregcm.util.Util;
@@ -84,6 +96,10 @@ public class RegistrationController {
private final RegistrationLockVerificationManager registrationLockVerificationManager;
private final RateLimiters rateLimiters;
private final RegistrationFraudChecker registrationFraudChecker;
private final ReceiptCredentialPresentationFactory receiptCredentialPresentationFactory;
private final ServerZkReceiptOperations serverZkReceiptOperations;
private final Clock clock;
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
private static final Logger logger = LoggerFactory.getLogger(RegistrationController.class);
@@ -91,13 +107,21 @@ public class RegistrationController {
final PhoneVerificationTokenManager phoneVerificationTokenManager,
final RegistrationLockVerificationManager registrationLockVerificationManager,
final RateLimiters rateLimiters,
final RegistrationFraudChecker registrationFraudChecker) {
final RegistrationFraudChecker registrationFraudChecker,
final ReceiptCredentialPresentationFactory receiptCredentialPresentationFactory,
final ServerZkReceiptOperations serverZkReceiptOperations,
final Clock clock,
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
this.accounts = accounts;
this.phoneVerificationTokenManager = phoneVerificationTokenManager;
this.registrationLockVerificationManager = registrationLockVerificationManager;
this.rateLimiters = rateLimiters;
this.registrationFraudChecker = registrationFraudChecker;
this.receiptCredentialPresentationFactory = receiptCredentialPresentationFactory;
this.serverZkReceiptOperations = serverZkReceiptOperations;
this.clock = clock;
this.dynamicConfigurationManager = dynamicConfigurationManager;
}
@POST
@@ -112,6 +136,7 @@ public class RegistrationController {
3. success \n
""")
@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 = "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")
@@ -122,6 +147,18 @@ public class RegistrationController {
description = "If present, an positive integer indicating the number of seconds before a subsequent attempt could succeed"))
@ApiResponse(responseCode = "499", description = "Client must support post-quantum ratchet")
public AccountCreationResponse register(
@Parameter(
in = ParameterIn.HEADER,
name = HttpHeaders.AUTHORIZATION,
description = """
The basic auth header. For accounts with a phone number, the username must be the e164-formatted number that is being registered.
For accounts without a phone number, the username is ignored on a fresh registration (it must be present, however, so an arbitrary
string is acceptable). For account recovery (re-registration) by ACI, it must be set to the ACI of the account being recovered.
In all cases, the password is the password to be used for primary device authentication.
""",
required = true,
schema = @Schema(type = "string")
)
@HeaderParam(HttpHeaders.AUTHORIZATION) @NotNull final BasicAuthorizationHeader authorizationHeader,
@HeaderParam(HeaderUtils.X_SIGNAL_AGENT) final String signalAgent,
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
@@ -143,6 +180,29 @@ public class RegistrationController {
throw new WebApplicationException("Missing required device capability", 499);
}
final AccountCreationResponse response;
if (registrationRequest.pniIdentityKey() != null) {
response = registerAccountWithNumber(number, password, registrationRequest, requestContext, userAgent, signalAgent);
} else {
response = registerAccountWithoutNumber(password, registrationRequest, userAgent, signalAgent);
}
return response;
}
private AccountCreationResponse registerAccountWithNumber(
final String number,
final String password,
final RegistrationRequest registrationRequest,
final ContainerRequestContext requestContext,
final String userAgent,
final String signalAgent)
throws RateLimitExceededException, InterruptedException, RegistrationLockFailureException {
if (registrationRequest.accountAttributes().getPhoneNumberIdentityRegistrationId().isEmpty()) {
throw new WebApplicationException("PNI registration ID must be provided", 422);
}
rateLimiters.getRegistrationLimiter().validate(number);
final PhoneVerificationRequest.VerificationType verificationType;
@@ -186,6 +246,7 @@ public class RegistrationController {
}
if (existingAccount.isPresent()) {
assert existingAccount.get().getNumberOptional().isPresent();
registrationLockVerificationManager.verifyRegistrationLock(existingAccount.get(),
registrationRequest.accountAttributes().getRegistrationLock(),
userAgent, RegistrationLockVerificationManager.Flow.REGISTRATION, verificationType);
@@ -193,7 +254,6 @@ public class RegistrationController {
final Account account = accounts.create(number,
registrationRequest.accountAttributes(),
existingAccount.map(Account::getBadges).orElseGet(ArrayList::new),
registrationRequest.aciIdentityKey(),
registrationRequest.pniIdentityKey(),
new DeviceSpec(
@@ -201,15 +261,18 @@ public class RegistrationController {
password,
signalAgent,
registrationRequest.accountAttributes().getCapabilities(),
registrationRequest.accountAttributes().getRegistrationId(),
registrationRequest.accountAttributes().getPhoneNumberIdentityRegistrationId(),
new DeviceIdentityInfo(
registrationRequest.accountAttributes().getRegistrationId(),
registrationRequest.deviceActivationRequest().aciSignedPreKey(),
registrationRequest.deviceActivationRequest().aciPqLastResortPreKey()),
Optional.of(new DeviceIdentityInfo(
registrationRequest.accountAttributes().getPhoneNumberIdentityRegistrationId().get(),
// We've already validated the presence of PNI keys by this point
registrationRequest.deviceActivationRequest().pniSignedPreKey().get(),
registrationRequest.deviceActivationRequest().pniPqLastResortPreKey().get())),
registrationRequest.accountAttributes().getFetchesMessages(),
registrationRequest.deviceActivationRequest().apnToken(),
registrationRequest.deviceActivationRequest().gcmToken(),
registrationRequest.deviceActivationRequest().aciSignedPreKey(),
registrationRequest.deviceActivationRequest().pniSignedPreKey(),
registrationRequest.deviceActivationRequest().aciPqLastResortPreKey(),
registrationRequest.deviceActivationRequest().pniPqLastResortPreKey()),
registrationRequest.deviceActivationRequest().gcmToken()),
userAgent);
if (verificationType == PhoneVerificationRequest.VerificationType.SESSION) {
@@ -236,4 +299,70 @@ public class RegistrationController {
return new AccountCreationResponse(identityResponse, existingAccount.isPresent());
}
private AccountCreationResponse registerAccountWithoutNumber(
final String password,
final RegistrationRequest registrationRequest,
final String userAgent,
final String signalAgent) {
if (!dynamicConfigurationManager.getConfiguration().getLoginPurchaseConfiguration().enabled()) {
throw new BadRequestException("login purchases are not enabled");
}
if (registrationRequest.accountAttributes().recoveryPassword().isEmpty()) {
throw new WebApplicationException("Account recovery password is required", 422);
}
final ReceiptCredentialPresentation receiptCredentialPresentation;
try {
receiptCredentialPresentation = receiptCredentialPresentationFactory
.build(registrationRequest.receiptCredentialPresentation());
} catch (InvalidInputException _) {
throw new BadRequestException("Invalid receipt credential presentation");
}
try {
serverZkReceiptOperations.verifyReceiptCredentialPresentation(receiptCredentialPresentation);
} catch (VerificationFailedException _) {
throw new BadRequestException("Receipt credential presentation verification failed");
}
final Instant receiptExpiration = Instant.ofEpochSecond(receiptCredentialPresentation.getReceiptExpirationTime());
if (clock.instant().isAfter(receiptExpiration)) {
throw new BadRequestException("Receipt is already expired");
}
final long receiptLevel = receiptCredentialPresentation.getReceiptLevel();
if (receiptLevel != ReceiptLevel.LOGIN.getValue()) {
throw new BadRequestException("Invalid receipt level");
}
try {
final Account account = accounts.create(
registrationRequest.accountAttributes(),
registrationRequest.aciIdentityKey(),
receiptCredentialPresentation,
new DeviceSpec(
registrationRequest.accountAttributes().getName(),
password,
signalAgent,
registrationRequest.accountAttributes().getCapabilities(),
new DeviceIdentityInfo(registrationRequest.accountAttributes().getRegistrationId(), registrationRequest.deviceActivationRequest()
.aciSignedPreKey(), registrationRequest.deviceActivationRequest().aciPqLastResortPreKey()),
Optional.empty(),
registrationRequest.accountAttributes().getFetchesMessages(),
registrationRequest.deviceActivationRequest().apnToken(),
registrationRequest.deviceActivationRequest().gcmToken()),
userAgent);
Metrics.counter(ACCOUNT_CREATED_COUNTER_NAME, Tags.of(UserAgentTagUtil.getPlatformTag(userAgent),
Tag.of(VERIFICATION_TYPE_TAG_NAME, registrationRequest.verificationType().name())))
.increment();
final AccountIdentityResponse accountIdentityResponse = new AccountIdentityResponseBuilder(account).build();
return new AccountCreationResponse(accountIdentityResponse, false);
} catch (ReceiptAlreadyRedeemedException _) {
throw new BadRequestException("Receipt already redeemed");
}
}
}
@@ -5,7 +5,6 @@
package org.whispersystems.textsecuregcm.controllers;
import com.google.common.annotations.VisibleForTesting;
import io.dropwizard.auth.Auth;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
@@ -22,45 +21,21 @@ import jakarta.ws.rs.core.EntityTag;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.HexFormat;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import org.apache.commons.lang3.tuple.Pair;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.entities.RemoteConfigurationResponse;
import org.whispersystems.textsecuregcm.storage.RemoteConfig;
import org.whispersystems.textsecuregcm.storage.RemoteConfigsManager;
import org.whispersystems.textsecuregcm.util.Conversions;
import org.whispersystems.textsecuregcm.util.Util;
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
import org.whispersystems.textsecuregcm.util.ua.UnrecognizedUserAgentException;
import org.whispersystems.textsecuregcm.util.ua.UserAgentUtil;
@Path("/v2/config")
@Tag(name = "Remote Config")
public class RemoteConfigController {
private final RemoteConfigsManager remoteConfigsManager;
private final Map<String, String> globalConfig;
private static final String GLOBAL_CONFIG_PREFIX = "global.";
private static final Set<String> PLATFORM_PREFIXES = Arrays.stream(ClientPlatform.values())
.map(p -> p.name().toLowerCase())
.collect(Collectors.toSet());
public RemoteConfigController(RemoteConfigsManager remoteConfigsManager, Map<String, String> globalConfig) {
public RemoteConfigController(RemoteConfigsManager remoteConfigsManager) {
this.remoteConfigsManager = remoteConfigsManager;
this.globalConfig = globalConfig;
}
@GET
@@ -88,69 +63,17 @@ public class RemoteConfigController {
@HeaderParam(HttpHeaders.USER_AGENT)
String userAgent
) {
final String platformPrefix = platformPrefix(userAgent);
final List<RemoteConfig> remoteConfigs = remoteConfigsManager.getAll();
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
final Map<String, String> configs = remoteConfigsManager.getConfigForAccount(auth.accountIdentifier(), userAgent);
final Map<String, String> configs = Stream.concat(
remoteConfigs.stream()
.filter(config -> {
final String firstNameComponent = config.getName().split("\\.", 2)[0];
return firstNameComponent.equals(platformPrefix) || !PLATFORM_PREFIXES.contains(firstNameComponent);
})
.map(
config -> {
final byte[] hashKey = config.getHashKey() != null
? config.getHashKey().getBytes(StandardCharsets.UTF_8)
: config.getName().getBytes(StandardCharsets.UTF_8);
boolean inBucket = isInBucket(digest, auth.accountIdentifier(), hashKey, config.getPercentage(), config.getUuids());
final String value = inBucket ? config.getValue() : config.getDefaultValue();
return Pair.of(config.getName(), value == null ? String.valueOf(inBucket) : value);
}),
globalConfig.entrySet().stream()
.map(e -> Pair.of(GLOBAL_CONFIG_PREFIX + e.getKey(), e.getValue())))
.collect(Collectors.toMap(Pair::getLeft, Pair::getRight));
final EntityTag newETag = new EntityTag(HexFormat.of().toHexDigits(configs.hashCode()));
if (newETag.equals(eTag)) {
return Response.notModified(eTag).build();
}
return Response.ok(new RemoteConfigurationResponse(configs))
.tag(newETag)
.build();
} catch (NoSuchAlgorithmException e) {
throw new AssertionError(e);
}
}
private static String platformPrefix(final String userAgent) {
try {
return UserAgentUtil.parseUserAgentString(userAgent).platform().name().toLowerCase();
} catch (UnrecognizedUserAgentException e) {
return null;
}
}
@VisibleForTesting
public static boolean isInBucket(MessageDigest digest, UUID uid, byte[] hashKey, int configPercentage,
Set<UUID> uuidsInBucket) {
if (uuidsInBucket.contains(uid)) {
return true;
final EntityTag newETag = new EntityTag(HexFormat.of().toHexDigits(configs.hashCode()));
if (newETag.equals(eTag)) {
return Response.notModified(eTag).build();
}
ByteBuffer bb = ByteBuffer.allocate(16);
bb.putLong(uid.getMostSignificantBits());
bb.putLong(uid.getLeastSignificantBits());
digest.update(bb.array());
byte[] hash = digest.digest(hashKey);
int bucket = (int) (Util.ensureNonNegativeLong(Conversions.byteArrayToLong(hash)) % 100);
return bucket < configPercentage;
return Response.ok(new RemoteConfigurationResponse(configs))
.tag(newETag)
.build();
}
}
@@ -28,6 +28,7 @@ import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
@@ -118,14 +119,14 @@ public class SecureValueRecovery2Controller {
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
@NotNull @Valid final AuthCheckRequest request) {
final List<ExternalServiceCredentialsSelector.CredentialInfo> credentials = ExternalServiceCredentialsSelector.check(
request.tokens(),
new HashSet<>(request.tokens()),
backupServiceCredentialGenerator,
MAX_AGE.getSeconds());
// the username associated with the provided number
final Optional<String> matchingUsername = accountsManager
.getByE164(request.number())
.map(Account::getUuid)
.map(Account::getAccountIdentifier)
.map(backupServiceCredentialGenerator::generateForUuid)
.map(ExternalServiceCredentials::username);
@@ -49,7 +49,6 @@ import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.Response.Status;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.math.BigDecimal;
import java.time.Clock;
import java.time.Instant;
@@ -66,6 +65,7 @@ import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialResponse;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.DonationPermitHeader;
import org.whispersystems.textsecuregcm.badges.BadgeTranslator;
import org.whispersystems.textsecuregcm.configuration.LoginPurchaseConfiguration;
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration;
import org.whispersystems.textsecuregcm.configuration.SubscriptionConfiguration;
import org.whispersystems.textsecuregcm.configuration.SubscriptionLevelConfiguration;
@@ -91,6 +91,7 @@ import org.whispersystems.textsecuregcm.subscriptions.LevelConfiguration;
import org.whispersystems.textsecuregcm.subscriptions.PaymentMethod;
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
import org.whispersystems.textsecuregcm.subscriptions.ProcessorCustomer;
import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel;
import org.whispersystems.textsecuregcm.subscriptions.StripeManager;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidArgumentsException;
@@ -106,6 +107,7 @@ public class SubscriptionController {
private final Clock clock;
private final SubscriptionConfiguration subscriptionConfiguration;
private final OneTimeDonationConfiguration oneTimeDonationConfiguration;
private final LoginPurchaseConfiguration loginPurchaseConfiguration;
private final SubscriptionManager subscriptionManager;
private final StripeManager stripeManager;
private final BraintreeManager braintreeManager;
@@ -124,6 +126,7 @@ public class SubscriptionController {
Clock clock,
SubscriptionConfiguration subscriptionConfiguration,
OneTimeDonationConfiguration oneTimeDonationConfiguration,
LoginPurchaseConfiguration loginPurchaseConfiguration,
SubscriptionManager subscriptionManager,
StripeManager stripeManager,
BraintreeManager braintreeManager,
@@ -137,6 +140,7 @@ public class SubscriptionController {
this.clock = Objects.requireNonNull(clock);
this.subscriptionConfiguration = Objects.requireNonNull(subscriptionConfiguration);
this.oneTimeDonationConfiguration = Objects.requireNonNull(oneTimeDonationConfiguration);
this.loginPurchaseConfiguration = Objects.requireNonNull(loginPurchaseConfiguration);
this.stripeManager = Objects.requireNonNull(stripeManager);
this.braintreeManager = Objects.requireNonNull(braintreeManager);
this.googlePlayBillingManager = Objects.requireNonNull(googlePlayBillingManager);
@@ -167,6 +171,8 @@ public class SubscriptionController {
buildDonationLevelsConfiguration(subscriptionConfiguration, oneTimeDonationConfiguration, badgeTranslator,
acceptableLanguages),
new BackupConfiguration(backupLevels, subscriptionConfiguration.getbackupFreeTierMediaDuration().toDays()),
new LoginConfiguration(ReceiptLevel.LOGIN.getValue(), loginPurchaseConfiguration.playProductId(),
loginPurchaseConfiguration.appStoreProductId()),
oneTimeDonationConfiguration.sepaMaximumEuros());
}
@@ -532,9 +538,20 @@ public class SubscriptionController {
Map<Long, LevelConfiguration> levels,
@Schema(description = "Backup specific configuration")
BackupConfiguration backup,
@Schema(description = "Signal Login specific configuration")
LoginConfiguration login,
@Schema(description = "The maximum value of a one-time donation SEPA transaction")
BigDecimal sepaMaximumEuros) {}
@Schema(description = "Configuration for one-time Signal Login purchases")
public record LoginConfiguration(
@Schema(description = "The receipt level associated with a Signal Login purchase")
long level,
@Schema(description = "The play billing productID associated with a Signal Login purchase")
String playProductId,
@Schema(description = "The App Store productID associated with a Signal Login purchase")
String appStoreProductId) {}
public record BackupConfiguration(
@Schema(description = "A map of numeric backup level IDs to level-specific backup configuration")
Map<String, BackupLevelConfiguration> levels,
@@ -97,7 +97,7 @@ import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
import org.whispersystems.textsecuregcm.storage.PhoneNumberRecoveryPasswordsManager;
import org.whispersystems.textsecuregcm.storage.VerificationSessionManager;
import org.whispersystems.textsecuregcm.telephony.CarrierData;
import org.whispersystems.textsecuregcm.telephony.CarrierDataException;
@@ -139,7 +139,7 @@ public class VerificationController {
private final VerificationSessionManager verificationSessionManager;
private final PushNotificationManager pushNotificationManager;
private final RegistrationCaptchaManager registrationCaptchaManager;
private final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager;
private final PhoneNumberRecoveryPasswordsManager phoneNumberRecoveryPasswordsManager;
private final PhoneNumberIdentifiers phoneNumberIdentifiers;
private final RateLimiters rateLimiters;
private final AccountsManager accountsManager;
@@ -153,7 +153,7 @@ public class VerificationController {
final VerificationSessionManager verificationSessionManager,
final PushNotificationManager pushNotificationManager,
final RegistrationCaptchaManager registrationCaptchaManager,
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager,
final PhoneNumberRecoveryPasswordsManager phoneNumberRecoveryPasswordsManager,
final PhoneNumberIdentifiers phoneNumberIdentifiers,
final RateLimiters rateLimiters,
final AccountsManager accountsManager,
@@ -166,7 +166,7 @@ public class VerificationController {
this.verificationSessionManager = verificationSessionManager;
this.pushNotificationManager = pushNotificationManager;
this.registrationCaptchaManager = registrationCaptchaManager;
this.registrationRecoveryPasswordsManager = registrationRecoveryPasswordsManager;
this.phoneNumberRecoveryPasswordsManager = phoneNumberRecoveryPasswordsManager;
this.phoneNumberIdentifiers = phoneNumberIdentifiers;
this.rateLimiters = rateLimiters;
this.accountsManager = accountsManager;
@@ -749,7 +749,10 @@ public class VerificationController {
// the RRP. It's possible the client will not actually be able to register (e.g. failed reglock challenge), and
// so we will have removed the RRP unnecessarily. The impact of this is low, since the owner of the RRP
// can always just fallback to session-based verification.
existingRRP = registrationRecoveryPasswordsManager.remove(phoneNumberIdentifiers.getPhoneNumberIdentifier(registrationServiceSession.number()).join());
//
// Note that we do not remove the recovery password from the account itself because re-creation is imminent, and
// that process will overwrite the recovery password (along with the rest of the account record).
existingRRP = phoneNumberRecoveryPasswordsManager.remove(phoneNumberIdentifiers.getPhoneNumberIdentifier(registrationServiceSession.number()).join());
}
Optional<Account> maybeExistingAccount;
@@ -824,7 +827,10 @@ public class VerificationController {
// the RRP. It's possible the client will not actually be able to register (e.g. failed reglock challenge), and
// so we will have removed the RRP unnecessarily. The impact of this is low, since the owner of the RRP
// can always just fallback to session-based verification.
registrationRecoveryPasswordsManager.remove(phoneNumberIdentifiers.getPhoneNumberIdentifier(registrationServiceSession.number()).join());
//
// Note that we do not remove the recovery password from the account itself because re-creation is imminent, and
// that process will overwrite the recovery password (along with the rest of the account record).
phoneNumberRecoveryPasswordsManager.remove(phoneNumberIdentifiers.getPhoneNumberIdentifier(registrationServiceSession.number()).join());
}
return registrationServiceSession;
@@ -52,15 +52,17 @@ public class AccountAttributes {
public AccountAttributes(
final boolean fetchesMessages,
final int registrationId,
final int phoneNumberIdentifierRegistrationId,
final Integer phoneNumberIdentifierRegistrationId,
final byte[] name,
final String registrationLock,
final boolean discoverableByPhoneNumber,
final Set<DeviceCapability> capabilities) {
final Set<DeviceCapability> capabilities,
@Nullable final byte[] recoveryPassword) {
this.deviceAttributes = new DeviceAttributes(fetchesMessages, registrationId, phoneNumberIdentifierRegistrationId, name, capabilities);
this.registrationLock = registrationLock;
this.discoverableByPhoneNumber = discoverableByPhoneNumber;
this.recoveryPassword = recoveryPassword;
}
public boolean getFetchesMessages() {
@@ -71,8 +73,8 @@ public class AccountAttributes {
return deviceAttributes.registrationId();
}
public int getPhoneNumberIdentityRegistrationId() {
return deviceAttributes.phoneNumberIdentityRegistrationId();
public Optional<Integer> getPhoneNumberIdentityRegistrationId() {
return Optional.ofNullable(deviceAttributes.phoneNumberIdentityRegistrationId());
}
public byte[] getName() {
@@ -128,6 +130,11 @@ public class AccountAttributes {
return this;
}
public AccountAttributes setDiscoverableByPhoneNumber(final boolean discoverableByPhoneNumber) {
this.discoverableByPhoneNumber = discoverableByPhoneNumber;
return this;
}
@AssertTrue
@Schema(hidden = true)
public boolean isUnrestrictedUakValid() {
@@ -13,6 +13,7 @@ import io.swagger.v3.oas.annotations.media.Schema;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import javax.annotation.Nullable;
import org.whispersystems.textsecuregcm.storage.AccountBadge;
@@ -36,21 +37,24 @@ public record AccountDataReportResponse(UUID reportId,
builder.append(String.format("""
Report ID: %s
Report timestamp: %s
""",
reportId,
reportTimestamp.truncatedTo(ChronoUnit.SECONDS)));
// account
builder.append(String.format("""
# Account
Phone number: %s
Allow sealed sender from anyone: %s
Find account by phone number: %s
""",
data.account.phoneNumber(),
data.account.allowSealedSenderFromAnyone(),
data.account.findAccountByPhoneNumber()));
builder.append("# Account\n");
data.account.phoneNumber().ifPresent(phoneNumber -> {
builder.append(String.format("""
Phone number: %s
Find account by phone number: %s
""",
phoneNumber,
data.account.findAccountByPhoneNumber()));
});
builder.append(String.format("Allow sealed sender from anyone: %s%n", data.account.allowSealedSenderFromAnyone()));
// badges
builder.append("Badges:");
@@ -93,9 +97,10 @@ public record AccountDataReportResponse(UUID reportId,
}
public record AccountDataReport(String phoneNumber, List<BadgeDataReport> badges, boolean allowSealedSenderFromAnyone,
public record AccountDataReport(Optional<String> phoneNumber,
List<BadgeDataReport> badges,
boolean allowSealedSenderFromAnyone,
boolean findAccountByPhoneNumber) {
}
public record DeviceDataReport(byte id,
@@ -8,6 +8,7 @@ package org.whispersystems.textsecuregcm.entities;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import io.swagger.v3.oas.annotations.media.Schema;
import java.util.Optional;
import java.util.UUID;
import javax.annotation.Nullable;
import org.whispersystems.textsecuregcm.util.ByteArrayBase64UrlAdapter;
@@ -16,11 +17,11 @@ public record AccountIdentityResponse(
@Schema(description = "the account identifier for this account")
UUID uuid,
@Schema(description = "the phone number associated with this account")
String number,
@Schema(description = "the phone number associated with this account; may be null if this account does not have a phone number")
Optional<String> number,
@Schema(description = "the account identifier for this account's phone-number identity")
UUID pni,
@Schema(description = "the account identifier for this account's phone-number identity; may be null if this account does not have a phone number")
Optional<UUID> pni,
@Schema(description = "a hash of this account's username, if set")
@JsonSerialize(using = ByteArrayBase64UrlAdapter.Serializing.class)
@@ -34,5 +35,8 @@ public record AccountIdentityResponse(
boolean storageCapable,
@Schema(description = "entitlements for this account and their current expirations")
Entitlements entitlements) {
Entitlements entitlements,
@Schema(description = "salt to generate PNI auth credentials for accounts without a phone number; null if this account does not have a phone number")
@Nullable byte[] authCredentialSalt) {
}
@@ -1,10 +1,8 @@
package org.whispersystems.textsecuregcm.entities;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import java.util.Optional;
public record DeviceActivationRequest(
@@ -15,12 +13,10 @@ public record DeviceActivationRequest(
""")
ECSignedPreKey aciSignedPreKey,
@NotNull
@Valid
@Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = """
A signed EC pre-key to be associated with this account's PNI.
@Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED, description = """
If the account has a phone number, a signed EC pre-key to be associated with this account's PNI.
""")
ECSignedPreKey pniSignedPreKey,
Optional<@Valid ECSignedPreKey> pniSignedPreKey,
@NotNull
@Valid
@@ -29,12 +25,10 @@ public record DeviceActivationRequest(
""")
KEMSignedPreKey aciPqLastResortPreKey,
@NotNull
@Valid
@Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = """
A signed Kyber-1024 "last resort" pre-key to be associated with this account's PNI.
@Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED, description = """
If the account has a phone number, a signed Kyber-1024 "last resort" pre-key to be associated with this account's PNI.
""")
KEMSignedPreKey pniPqLastResortPreKey,
Optional<@Valid KEMSignedPreKey> pniPqLastResortPreKey,
@Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED, description = """
An APNs token set for the account's primary device. If provided, the account's primary
@@ -13,6 +13,7 @@ import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.AssertTrue;
import jakarta.validation.constraints.Size;
import java.util.Optional;
import java.util.Set;
import javax.annotation.Nullable;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
@@ -24,16 +25,16 @@ public record DeviceAttributes(
int registrationId,
@JsonProperty("pniRegistrationId") int phoneNumberIdentityRegistrationId,
@JsonProperty("pniRegistrationId")
@Nullable
Integer phoneNumberIdentityRegistrationId,
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
@Size(max = 225)
byte[] name,
@JsonSerialize(using = DeviceCapabilityAdapter.Serializer.class)
@JsonDeserialize(using = DeviceCapabilityAdapter.Deserializer.class)
@Nullable
Set<DeviceCapability> capabilities) {
@@ -41,6 +42,7 @@ public record DeviceAttributes(
@AssertTrue
@Schema(hidden = true)
public boolean isEachRegistrationIdValid() {
return validRegistrationId(registrationId) && validRegistrationId(phoneNumberIdentityRegistrationId);
return validRegistrationId(registrationId) &&
(phoneNumberIdentityRegistrationId == null || validRegistrationId(phoneNumberIdentityRegistrationId));
}
}
@@ -33,9 +33,9 @@ public record LinkDeviceRequest(@Schema(requiredMode = Schema.RequiredMode.REQUI
public LinkDeviceRequest(@JsonProperty("verificationCode") String verificationCode,
@JsonProperty("accountAttributes") DeviceAttributes deviceAttributes,
@JsonProperty("aciSignedPreKey") @NotNull @Valid ECSignedPreKey aciSignedPreKey,
@JsonProperty("pniSignedPreKey") @NotNull @Valid ECSignedPreKey pniSignedPreKey,
@JsonProperty("pniSignedPreKey") Optional<@Valid ECSignedPreKey> pniSignedPreKey,
@JsonProperty("aciPqLastResortPreKey") @NotNull @Valid KEMSignedPreKey aciPqLastResortPreKey,
@JsonProperty("pniPqLastResortPreKey") @NotNull @Valid KEMSignedPreKey pniPqLastResortPreKey,
@JsonProperty("pniPqLastResortPreKey") Optional<@Valid KEMSignedPreKey> pniPqLastResortPreKey,
@JsonProperty("apnToken") Optional<@Valid ApnRegistrationId> apnToken,
@JsonProperty("gcmToken") Optional<@Valid GcmRegistrationId> gcmToken) {
@@ -5,7 +5,8 @@
package org.whispersystems.textsecuregcm.entities;
import java.util.Optional;
import java.util.UUID;
public record LinkDeviceResponse(UUID uuid, UUID pni, byte deviceId) {
public record LinkDeviceResponse(UUID uuid, Optional<UUID> pni, byte deviceId) {
}
@@ -10,31 +10,52 @@ import static org.apache.commons.lang3.StringUtils.isNotBlank;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.AssertTrue;
import jakarta.ws.rs.ClientErrorException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.http.HttpStatus;
public interface PhoneVerificationRequest {
enum VerificationType {
SESSION,
RECOVERY_PASSWORD
RECOVERY_PASSWORD,
RECEIPT_CREDENTIAL
}
String sessionId();
byte[] recoveryPassword();
default byte[] receiptCredentialPresentation() {
return null;
}
// for the @AssertTrue to work with bean validation, method name must follow 'isSmth()'/'getSmth()' naming convention
@AssertTrue
@Schema(hidden = true)
default boolean isValid() {
// checking that exactly one of sessionId/recoveryPassword is non-empty
return isNotBlank(sessionId()) ^ (recoveryPassword() != null && recoveryPassword().length > 0);
// exactly one of sessionId/recoveryPassword/receiptCredentialPresentation should be present
return presentVerificationTypes().size() == 1;
}
default PhoneVerificationRequest.VerificationType verificationType() {
return isNotBlank(sessionId()) ? PhoneVerificationRequest.VerificationType.SESSION
: PhoneVerificationRequest.VerificationType.RECOVERY_PASSWORD;
return presentVerificationTypes().get(0);
}
default List<VerificationType> presentVerificationTypes() {
final List<VerificationType> types = new ArrayList<>(1);
if (isNotBlank(sessionId())) {
types.add(VerificationType.SESSION);
}
if (ArrayUtils.isNotEmpty(recoveryPassword())) {
types.add(VerificationType.RECOVERY_PASSWORD);
}
if (ArrayUtils.isNotEmpty(receiptCredentialPresentation())) {
types.add(VerificationType.RECEIPT_CREDENTIAL);
}
return types;
}
default byte[] decodeSessionId() {
@@ -22,7 +22,6 @@ public abstract class PreKeySignatureValidator {
final Collection<SignedPreKey<?>> signedPreKeys,
@Nullable final String userAgent,
final String context) {
final boolean success = signedPreKeys.stream().allMatch(signedPreKey -> signedPreKey.signatureValid(identityKey));
if (!success) {
@@ -22,18 +22,31 @@ import org.whispersystems.textsecuregcm.util.IdentityKeyAdapter;
public record RegistrationRequest(@Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED, description = """
The ID of an existing verification session as it appears in a verification session
metadata object. Must be provided if `recoveryPassword` is not provided; must not be
provided if `recoveryPassword` is provided.
metadata object. Must be provided if `recoveryPassword` and `receiptCredentialPresentation`
are not provided; must not be provided if `recoveryPassword` or `receiptCredentialPresentation`
is provided.
""")
@Nullable
String sessionId,
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
@Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED, description = """
A base64-encoded registration recovery password. Must be provided if `sessionId` is
not provided; must not be provided if `sessionId` is provided
A base64-encoded registration recovery password. Must be provided if `sessionId` and
`receiptCredentialPresentation` are not provided; must not be provided if `sessionId`
or `receiptCredentialPresentation` is provided.
""")
@Nullable
byte[] recoveryPassword,
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
@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.
""")
@Nullable
byte[] receiptCredentialPresentation,
@NotNull
@Valid
@Schema(requiredMode = Schema.RequiredMode.REQUIRED)
@@ -58,13 +71,14 @@ public record RegistrationRequest(@Schema(requiredMode = Schema.RequiredMode.NOT
@JsonDeserialize(using = IdentityKeyAdapter.Deserializer.class)
IdentityKey aciIdentityKey,
@NotNull
@Valid
@Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = """
@Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED, description = """
The PNI-associated identity key for the account, encoded as a base64 string.
Must be provided for an account with a phone number.
""")
@JsonSerialize(using = IdentityKeyAdapter.Serializer.class)
@JsonDeserialize(using = IdentityKeyAdapter.Deserializer.class)
@Nullable
IdentityKey pniIdentityKey,
@NotNull
@@ -75,14 +89,18 @@ public record RegistrationRequest(@Schema(requiredMode = Schema.RequiredMode.NOT
public boolean isEverySignedKeyValid(@Nullable final String userAgent) {
if (deviceActivationRequest().aciSignedPreKey() == null ||
deviceActivationRequest().pniSignedPreKey() == null ||
deviceActivationRequest().aciPqLastResortPreKey() == null ||
deviceActivationRequest().pniPqLastResortPreKey() == null) {
deviceActivationRequest().aciPqLastResortPreKey() == null) {
return false;
}
final boolean allPniPresentOrAllAbsent = ((pniIdentityKey == null) == deviceActivationRequest().pniSignedPreKey().isEmpty())
&& ((pniIdentityKey == null) == deviceActivationRequest().pniPqLastResortPreKey().isEmpty());
if (!allPniPresentOrAllAbsent) {
return false;
}
return PreKeySignatureValidator.validatePreKeySignatures(aciIdentityKey(), List.of(deviceActivationRequest().aciSignedPreKey(), deviceActivationRequest().aciPqLastResortPreKey()), userAgent, "register")
&& PreKeySignatureValidator.validatePreKeySignatures(pniIdentityKey(), List.of(deviceActivationRequest().pniSignedPreKey(), deviceActivationRequest().pniPqLastResortPreKey()), userAgent, "register");
&& (pniIdentityKey == null || PreKeySignatureValidator.validatePreKeySignatures(pniIdentityKey(), List.of(deviceActivationRequest().pniSignedPreKey().get(), deviceActivationRequest().pniPqLastResortPreKey().get()), userAgent, "register"));
}
@VisibleForTesting
@@ -27,6 +27,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.grpc.RequestAttributesUtil;
import org.whispersystems.textsecuregcm.util.InetAddressRange;
import org.whispersystems.textsecuregcm.util.logging.ImpossibleEvents;
public class ExternalRequestFilter implements Filter, ServerInterceptor {
@@ -85,7 +86,7 @@ public class ExternalRequestFilter implements Filter, ServerInterceptor {
if (response instanceof HttpServletResponse hsr) {
hsr.setStatus(404);
} else {
logger.warn("response was an unexpected type: {}", response.getClass());
ImpossibleEvents.logImpossible(logger, "response was an unexpected type: {}", response.getClass());
}
return;
}
@@ -15,6 +15,7 @@ import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.util.HttpServletRequestUtil;
import org.whispersystems.textsecuregcm.util.logging.ImpossibleEvents;
/**
* Sets a {@link HttpServletRequest} attribute (that will also be available as a
@@ -36,7 +37,7 @@ public class RemoteAddressFilter implements Filter {
request.setAttribute(REMOTE_ADDRESS_ATTRIBUTE_NAME, remoteAddress);
} else {
logger.warn("request was of unexpected type: {}", request.getClass());
ImpossibleEvents.logImpossible(logger, "request was of unexpected type: {}", request.getClass());
}
chain.doFilter(request, response);
@@ -67,7 +67,7 @@ public class AccountsAnonymousGrpcService extends SimpleAccountsAnonymousGrpc.Ac
return accountsManager.getByUsernameHash(request.getUsernameHash().toByteArray()).join()
.map(account -> LookupUsernameHashResponse.newBuilder()
.setServiceIdentifier(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(new AciServiceIdentifier(account.getUuid())))
.setServiceIdentifier(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(new AciServiceIdentifier(account.getAccountIdentifier())))
.build())
.orElseGet(() -> LookupUsernameHashResponse.newBuilder().setNotFound(NotFound.getDefaultInstance()).build());
}
@@ -12,11 +12,12 @@ import java.security.SecureRandom;
import java.time.Clock;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HexFormat;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import java.util.function.Function;
import java.util.stream.Collectors;
@@ -62,7 +63,6 @@ import org.signal.chat.account.StaleDevices;
import org.signal.chat.account.UsernameNotAvailable;
import org.signal.chat.common.AccountIdentifiers;
import org.signal.chat.errors.FailedPrecondition;
import org.signal.chat.errors.NotFound;
import org.signal.chat.messages.SendMessageType;
import org.signal.libsignal.protocol.IdentityKey;
import org.signal.libsignal.protocol.InvalidKeyException;
@@ -73,7 +73,6 @@ import org.whispersystems.textsecuregcm.auth.InvalidRegistrationSessionException
import org.whispersystems.textsecuregcm.auth.RecoveryPasswordVerificationFailedException;
import org.whispersystems.textsecuregcm.auth.RegistrationLockFailureException;
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
import org.whispersystems.textsecuregcm.auth.UnverifiedRegistrationSessionException;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
@@ -86,7 +85,6 @@ import org.whispersystems.textsecuregcm.entities.IncomingMessage;
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.push.MessageTooLargeException;
@@ -94,13 +92,14 @@ import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.ChangeNumberManager;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
import org.whispersystems.textsecuregcm.storage.PhoneNumberRecoveryPasswordsManager;
import org.whispersystems.textsecuregcm.storage.UsernameHashNotAvailableException;
import org.whispersystems.textsecuregcm.storage.UsernameReservationNotFoundException;
import org.whispersystems.textsecuregcm.util.RegistrationIdValidator;
import org.whispersystems.textsecuregcm.util.SystemMapper;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
import org.whispersystems.textsecuregcm.util.UsernameHashZkProofVerifier;
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem;
public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
@@ -109,21 +108,21 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
private final AccountsManager accountsManager;
private final RateLimiters rateLimiters;
private final UsernameHashZkProofVerifier usernameHashZkProofVerifier;
private final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager;
private final PhoneNumberRecoveryPasswordsManager phoneNumberRecoveryPasswordsManager;
private final Clock clock;
private final ChangeNumberManager changeNumberManager;
public AccountsGrpcService(final AccountsManager accountsManager,
final RateLimiters rateLimiters,
final UsernameHashZkProofVerifier usernameHashZkProofVerifier,
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager,
final PhoneNumberRecoveryPasswordsManager phoneNumberRecoveryPasswordsManager,
final Clock clock,
final ChangeNumberManager changeNumberManager) {
this.accountsManager = accountsManager;
this.rateLimiters = rateLimiters;
this.usernameHashZkProofVerifier = usernameHashZkProofVerifier;
this.registrationRecoveryPasswordsManager = registrationRecoveryPasswordsManager;
this.phoneNumberRecoveryPasswordsManager = phoneNumberRecoveryPasswordsManager;
this.clock = clock;
this.changeNumberManager = changeNumberManager;
}
@@ -174,10 +173,14 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
final SaltedTokenHash credentials =
SaltedTokenHash.generateFor(formatRegistrationLock(request.getRegistrationLock().toByteArray()));
accountsManager.update(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier(),
account -> account.setRegistrationLock(credentials.hash(), credentials.salt()));
try {
accountsManager.update(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier(),
account -> account.setRegistrationLock(credentials.hash(), credentials.salt()));
return SetRegistrationLockResponse.getDefaultInstance();
return SetRegistrationLockResponse.getDefaultInstance();
} catch (IllegalArgumentException _) {
throw GrpcExceptions.invalidArguments(null);
}
}
@Override
@@ -235,7 +238,6 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
return ConfirmUsernameHashResponse.newBuilder()
.setConfirmedUsernameHash(ConfirmUsernameHashResponse.ConfirmedUsernameHash.newBuilder()
.setUsernameHash(ByteString.copyFrom(updatedAccount.getUsernameHash().orElseThrow()))
.setUsernameLinkHandle(UUIDUtil.toByteString(updatedAccount.getUsernameLinkHandle())))
.build();
} catch (final UsernameHashNotAvailableException e) {
@@ -277,7 +279,7 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
? account.getUsernameLinkHandle()
: UUID.randomUUID();
accountsManager.update(account.getIdentifier(IdentityType.ACI),
accountsManager.update(account.getAccountIdentifier(),
a -> a.setUsernameLinkDetails(linkHandle, request.getUsernameCiphertext().toByteArray()));
return responseBuilder.setUsernameLinkHandle(UUIDUtil.toByteString(linkHandle)).build();
@@ -314,15 +316,29 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
@Override
public SetDiscoverableByPhoneNumberResponse setDiscoverableByPhoneNumber(final SetDiscoverableByPhoneNumberRequest request) {
accountsManager.update(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier(),
account -> account.setDiscoverableByPhoneNumber(request.getDiscoverableByPhoneNumber()));
account -> {
if (account.getNumberOptional().isEmpty()) {
throw GrpcExceptions.invalidArguments("account does not have a phone number");
}
account.setDiscoverableByPhoneNumber(request.getDiscoverableByPhoneNumber());
});
return SetDiscoverableByPhoneNumberResponse.getDefaultInstance();
}
@Override
public SetRegistrationRecoveryPasswordResponse setRegistrationRecoveryPassword(final SetRegistrationRecoveryPasswordRequest request) {
registrationRecoveryPasswordsManager.store(getAuthenticatedAccount().getIdentifier(IdentityType.PNI),
request.getRegistrationRecoveryPassword().toByteArray());
final Account account = getAuthenticatedAccount();
final byte[] recoveryPassword = request.getRegistrationRecoveryPassword().toByteArray();
final Collection<TransactWriteItem> additionalWriteItems = account.getPhoneNumberIdentifierOptional()
.map(phoneNumberIdentifier ->
List.of(phoneNumberRecoveryPasswordsManager.buildTransactWriteItemForStorePassword(phoneNumberIdentifier, recoveryPassword)))
.orElseGet(Collections::emptyList);
// TODO Once we retire `AccountController`, replace this with a new `AccountsManager#setRecoveryPassword` method
accountsManager.update(account.getAccountIdentifier(), a -> a.setAccountRecoveryPassword(recoveryPassword), additionalWriteItems);
return SetRegistrationRecoveryPasswordResponse.getDefaultInstance();
}
@@ -489,7 +505,7 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
final AccountDataReportResponse report = new AccountDataReportResponse(UUID.randomUUID(), clock.instant(),
new AccountDataReportResponse.AccountAndDevicesDataReport(
new AccountDataReportResponse.AccountDataReport(
account.getNumber(),
account.getNumberOptional(),
account.getBadges().stream().map(AccountDataReportResponse.BadgeDataReport::new).toList(),
account.isUnrestrictedUnidentifiedAccess(),
account.isDiscoverableByPhoneNumber()),
@@ -520,9 +536,13 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
private static AccountIdentifiers buildAccountIdentifiers(final Account account) {
final AccountIdentifiers.Builder accountIdentifiersBuilder = AccountIdentifiers.newBuilder()
.addServiceIdentifiers(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(new AciServiceIdentifier(account.getUuid())))
.addServiceIdentifiers(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(new PniServiceIdentifier(account.getPhoneNumberIdentifier())))
.setE164(account.getNumber());
.addServiceIdentifiers(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(new AciServiceIdentifier(account.getAccountIdentifier())));
account.getPhoneNumberIdentifierOptional()
.map(phoneNumberIdentifier -> GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(new PniServiceIdentifier(phoneNumberIdentifier)))
.ifPresent(accountIdentifiersBuilder::addServiceIdentifiers);
account.getNumberOptional().ifPresent(accountIdentifiersBuilder::setE164);
account.getUsernameHash().ifPresent(usernameHash ->
accountIdentifiersBuilder.setUsernameHash(ByteString.copyFrom(usernameHash)));
@@ -265,7 +265,7 @@ public class BackupsAnonymousGrpcService extends SimpleBackupsAnonymousGrpc.Back
final BackupManager.ListMediaResult listResult = backupManager.list(
backupUser,
request.hasCursor() ? Optional.of(request.getCursor()) : Optional.empty(),
request.getLimit());
request.hasLimit() ? Optional.of(request.getLimit()) : Optional.empty());
final ListMediaResponse.ListResult.Builder builder = ListMediaResponse.ListResult.newBuilder();
for (BackupManager.StorageDescriptorWithLength sd : listResult.media()) {
builder.addPage(ListMediaResponse.ListEntry.newBuilder()
@@ -14,6 +14,7 @@ import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsSelector;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
@@ -34,15 +35,15 @@ public class CredentialsAnonymousGrpcService extends SimpleCredentialsAnonymousG
@Override
public CheckSvrCredentialsResponse checkSvrCredentials(final CheckSvrCredentialsRequest request) {
final List<String> tokens = request.getPasswordsList();
final List<String> tokens = request.getPasswordsList().stream().distinct().toList();
final List<ExternalServiceCredentialsSelector.CredentialInfo> credentials = ExternalServiceCredentialsSelector.check(
tokens,
new HashSet<>(tokens),
svrCredentialsGenerator,
MAX_SVR_PASSWORD_AGE_SECONDS);
// the username associated with the provided number
final Optional<String> maybeUsername = accountsManager.getByE164(request.getNumber())
.map(Account::getUuid)
.map(Account::getAccountIdentifier)
.map(svrCredentialsGenerator::generateForUuid)
.map(ExternalServiceCredentials::username);
@@ -10,6 +10,7 @@ import java.time.Clock;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import org.signal.chat.credentials.ExternalServiceType;
import org.signal.chat.credentials.GetCreateCallLinkCredentialsRequest;
@@ -24,6 +25,7 @@ import org.signal.chat.credentials.SimpleCredentialsGrpc;
import org.signal.libsignal.protocol.ServiceId;
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.auth.AuthCredentialWithPniResponse;
import org.signal.libsignal.zkgroup.auth.ServerZkAuthOperations;
import org.signal.libsignal.zkgroup.calllinks.CallLinkAuthCredentialResponse;
import org.signal.libsignal.zkgroup.calllinks.CreateCallLinkCredentialRequest;
@@ -34,7 +36,6 @@ import org.whispersystems.textsecuregcm.auth.RedemptionRange;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
@@ -93,12 +94,16 @@ public class CredentialsGrpcService extends SimpleCredentialsGrpc.CredentialsImp
final Account account = accountsManager.getByAccountIdentifier(authenticatedDevice.accountIdentifier())
.orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials"));
return GetDeliveryCertificateResponse.newBuilder()
.setCertificateWithE164(ByteString.copyFrom(
certificateGenerator.createFor(account, authenticatedDevice.deviceId(), true)))
final GetDeliveryCertificateResponse.Builder responseBuilder = GetDeliveryCertificateResponse.newBuilder()
.setCertificateWithoutE164(ByteString.copyFrom(
certificateGenerator.createFor(account, authenticatedDevice.deviceId(), false)))
.build();
certificateGenerator.createFor(account, authenticatedDevice.deviceId(), false)));
if (account.getNumberOptional().isPresent()) {
responseBuilder.setCertificateWithE164(ByteString.copyFrom(
certificateGenerator.createFor(account, authenticatedDevice.deviceId(), true)));
}
return responseBuilder.build();
}
@Override
@@ -117,17 +122,26 @@ public class CredentialsGrpcService extends SimpleCredentialsGrpc.CredentialsImp
accountsManager.getByAccountIdentifier(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier())
.orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials"));
final ServiceId.Aci aci = new ServiceId.Aci(account.getIdentifier(IdentityType.ACI));
final ServiceId.Pni pni = new ServiceId.Pni(account.getIdentifier(IdentityType.PNI));
final ServiceId.Aci aci = new ServiceId.Aci(account.getAccountIdentifier());
final Optional<ServiceId.Pni> maybePni = account.getPhoneNumberIdentifierOptional().map(ServiceId.Pni::new);
final GetGroupCredentialsResponse.Builder responseBuilder = GetGroupCredentialsResponse.newBuilder()
.setPni(UUIDUtil.toByteString(pni.getRawUUID()));
final GetGroupCredentialsResponse.Builder responseBuilder = GetGroupCredentialsResponse.newBuilder();
maybePni.ifPresent(pni -> responseBuilder.setPni(UUIDUtil.toByteString(pni.getRawUUID())));
for (final Instant redemption : redemptionRange) {
final AuthCredentialWithPniResponse authCredentialWithPniResponse =
maybePni.map(pni ->
serverZkAuthOperations.issueAuthCredentialWithPniZkc(aci, pni, redemption))
.orElseGet(() -> serverZkAuthOperations.issueAuthCredentialZkcWithoutPni(aci,
account.getAuthCredentialSalt()
.orElseThrow(
() -> new IllegalStateException("account without PNI must have auth credential salt")),
redemption));
responseBuilder.addGroupCredentials(GetGroupCredentialsResponse.CredentialAndRedemptionTime.newBuilder()
.setRedemptionTimeSeconds(redemption.getEpochSecond())
.setCredential(ByteString.copyFrom(
serverZkAuthOperations.issueAuthCredentialWithPniZkc(aci, pni, redemption).serialize()))
authCredentialWithPniResponse.serialize()))
.build());
responseBuilder.addCallLinkAuthCredentials(GetGroupCredentialsResponse.CredentialAndRedemptionTime.newBuilder()
@@ -20,6 +20,7 @@ public class DeviceCapabilityUtil {
case DEVICE_CAPABILITY_SPARSE_POST_QUANTUM_RATCHET -> DeviceCapability.SPARSE_POST_QUANTUM_RATCHET;
case DEVICE_CAPABILITY_PROFILES_V2 -> DeviceCapability.PROFILES_V2;
case DEVICE_CAPABILITY_USERNAME_CHANGE_SYNC_MESSAGE -> DeviceCapability.USERNAME_CHANGE_SYNC_MESSAGE;
case DEVICE_CAPABILITY_OPTIONAL_PHONE_NUMBER -> DeviceCapability.OPTIONAL_PHONE_NUMBER;
case DEVICE_CAPABILITY_UNSPECIFIED, UNRECOGNIZED ->
throw GrpcExceptions.invalidArguments("unrecognized device capability");
};
@@ -33,6 +34,7 @@ public class DeviceCapabilityUtil {
case SPARSE_POST_QUANTUM_RATCHET -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_SPARSE_POST_QUANTUM_RATCHET;
case PROFILES_V2 -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_PROFILES_V2;
case USERNAME_CHANGE_SYNC_MESSAGE -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_USERNAME_CHANGE_SYNC_MESSAGE;
case OPTIONAL_PHONE_NUMBER -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_OPTIONAL_PHONE_NUMBER;
};
}
}
@@ -29,6 +29,7 @@ import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.DonationPermitsManager;
import org.whispersystems.textsecuregcm.storage.RedeemedReceiptsManager;
import org.whispersystems.textsecuregcm.subscriptions.ReceiptCredentialPresentationFactory;
import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel;
public class DonationsGrpcService extends SimpleDonationsGrpc.DonationsImplBase {
@@ -73,7 +74,10 @@ public class DonationsGrpcService extends SimpleDonationsGrpc.DonationsImplBase
final ReceiptSerial receiptSerial = receiptCredentialPresentation.getReceiptSerial();
final Instant receiptExpiration = Instant.ofEpochSecond(receiptCredentialPresentation.getReceiptExpirationTime());
final long receiptLevel = receiptCredentialPresentation.getReceiptLevel();
final String badgeId = badgesConfiguration.getReceiptLevels().get(receiptLevel);
final String badgeId = ReceiptLevel
.lookupLevel(receiptLevel)
.map(badgesConfiguration.getReceiptLevels()::get)
.orElse(null);
if (badgeId == null) {
// Since the receipt presentation checked out, the server messed up because it doesn't recognize a receipt level it previously issued.
LOGGER.error("Server doesn't recognize previously issued receipt level; please check badgesConfiguration for issues");
@@ -15,6 +15,7 @@ import io.grpc.StatusRuntimeException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import org.whispersystems.textsecuregcm.util.logging.ImpossibleEvents;
import java.io.IOException;
import java.io.UncheckedIOException;
@@ -59,6 +60,10 @@ public class ErrorMappingInterceptor implements ServerInterceptor {
log.warn("RPC {} encountered IOException", call.getMethodDescriptor().getFullMethodName(), e);
yield GrpcExceptions.unavailable();
}
case IllegalStateException e -> {
ImpossibleEvents.logImpossible(log, e.getMessage(), e);
yield GrpcExceptions.unavailable(e.getMessage());
}
case null -> {
log.error("RPC {} finished with status UNKNOWN: {}",
call.getMethodDescriptor().getFullMethodName(), status.getDescription());
@@ -60,17 +60,21 @@ public class KeysGrpcService extends SimpleKeysGrpc.KeysImplBase {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
final Account account = getAuthenticatedAccount(authenticatedDevice.accountIdentifier());
final CompletableFuture<Integer> aciEcKeyCountFuture =
keysManager.getEcCount(account.getIdentifier(IdentityType.ACI), authenticatedDevice.deviceId());
final UUID aci = account.getAccountIdentifier();
final CompletableFuture<Integer> pniEcKeyCountFuture =
keysManager.getEcCount(account.getIdentifier(IdentityType.PNI), authenticatedDevice.deviceId());
final CompletableFuture<Integer> aciEcKeyCountFuture =
keysManager.getEcCount(aci, authenticatedDevice.deviceId());
final CompletableFuture<Integer> pniEcKeyCountFuture = account.getPhoneNumberIdentifierOptional()
.map(pni -> keysManager.getEcCount(pni, authenticatedDevice.deviceId()))
.orElseGet(() -> CompletableFuture.completedFuture(0));
final CompletableFuture<Integer> aciKemKeyCountFuture =
keysManager.getPqCount(account.getIdentifier(IdentityType.ACI), authenticatedDevice.deviceId());
keysManager.getPqCount(aci, authenticatedDevice.deviceId());
final CompletableFuture<Integer> pniKemKeyCountFuture =
keysManager.getPqCount(account.getIdentifier(IdentityType.PNI), authenticatedDevice.deviceId());
final CompletableFuture<Integer> pniKemKeyCountFuture = account.getPhoneNumberIdentifierOptional()
.map(pni -> keysManager.getPqCount(pni, authenticatedDevice.deviceId()))
.orElseGet(() -> CompletableFuture.completedFuture(0));
CompletableFuture.allOf(aciEcKeyCountFuture, pniEcKeyCountFuture, aciKemKeyCountFuture, pniKemKeyCountFuture).join();
@@ -154,11 +158,13 @@ public class KeysGrpcService extends SimpleKeysGrpc.KeysImplBase {
final Account account = getAuthenticatedAccount(authenticatedAccountUuid);
final UUID identifier = getIdentifier(account, identityType);
final List<K> preKeys = requestPreKeys.stream()
.map(requestPreKey -> extractPreKeyFunction.apply(requestPreKey, account.getIdentityKey(identityType)))
.toList();
storeKeysFunction.apply(account.getIdentifier(identityType), preKeys).join();
storeKeysFunction.apply(identifier, preKeys).join();
}
@Override
@@ -166,15 +172,10 @@ public class KeysGrpcService extends SimpleKeysGrpc.KeysImplBase {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
storeRepeatedUseKey(authenticatedDevice.accountIdentifier(),
request.getIdentityType(),
IdentityTypeUtil.fromGrpcIdentityType(request.getIdentityType()),
request.getSignedPreKey(),
(preKey, identityKey) -> KeysGrpcHelper.checkEcSignedPreKey(preKey, identityKey, INVALID_PUBLIC_KEY_EXCEPTION, INVALID_SIGNATURE_EXCEPTION),
(account, signedPreKey) -> {
final IdentityType identityType = IdentityTypeUtil.fromGrpcIdentityType(request.getIdentityType());
final UUID identifier = account.getIdentifier(identityType);
return keysManager.storeEcSignedPreKeys(identifier, authenticatedDevice.deviceId(), signedPreKey);
});
(identifier, signedPreKey) -> keysManager.storeEcSignedPreKeys(identifier, authenticatedDevice.deviceId(), signedPreKey));
return SetPreKeyResponse.getDefaultInstance();
}
@@ -184,36 +185,42 @@ public class KeysGrpcService extends SimpleKeysGrpc.KeysImplBase {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
storeRepeatedUseKey(authenticatedDevice.accountIdentifier(),
request.getIdentityType(),
IdentityTypeUtil.fromGrpcIdentityType(request.getIdentityType()),
request.getSignedPreKey(),
(preKey, identityKey) -> KeysGrpcHelper.checkKemSignedPreKey(preKey, identityKey, INVALID_PUBLIC_KEY_EXCEPTION, INVALID_SIGNATURE_EXCEPTION),
(account, lastResortKey) -> {
final UUID identifier =
account.getIdentifier(IdentityTypeUtil.fromGrpcIdentityType(request.getIdentityType()));
return keysManager.storePqLastResort(identifier, authenticatedDevice.deviceId(), lastResortKey);
});
(identifier, lastResortKey) -> keysManager.storePqLastResort(identifier, authenticatedDevice.deviceId(), lastResortKey));
return SetPreKeyResponse.getDefaultInstance();
}
private <K, R> void storeRepeatedUseKey(final UUID authenticatedAccountUuid,
final org.signal.chat.common.IdentityType identityType,
final IdentityType identityType,
final R storeKeyRequest,
final BiFunction<R, IdentityKey, K> extractKeyFunction,
final BiFunction<Account, K, CompletableFuture<Void>> storeKeyFunction) {
final BiFunction<UUID, K, CompletableFuture<Void>> storeKeyFunction) {
final Account account = getAuthenticatedAccount(authenticatedAccountUuid);
final IdentityKey identityKey = account.getIdentityKey(IdentityTypeUtil.fromGrpcIdentityType(identityType));
final UUID identifier = getIdentifier(account, identityType);
final IdentityKey identityKey = account.getIdentityKey(identityType);
final K key = extractKeyFunction.apply(storeKeyRequest, identityKey);
storeKeyFunction.apply(account, key).join();
storeKeyFunction.apply(identifier, key).join();
}
private Account getAuthenticatedAccount(final UUID authenticatedAccountId) {
return accountsManager.getByAccountIdentifier(authenticatedAccountId)
.orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials"));
}
/// Get the identity of the requested `idenityType`, or throw an invalid arguments status if `account` does not
/// contain that type.
private static UUID getIdentifier(Account account, IdentityType identityType) {
return switch (identityType) {
case ACI -> account.getAccountIdentifier();
case PNI -> account.getPhoneNumberIdentifierOptional()
.orElseThrow(() -> GrpcExceptions.invalidArguments("PNI identity type not allowed for an account without a phone number"));
};
}
}
@@ -232,8 +232,8 @@ public class MessageDispatcher {
messageMetrics.measureMessageStreamDisplaced(MessageMetrics.GRPC_CHANNEL, userAgent, false);
sink.error(GrpcExceptions.invalidCredentials("reauthentication required"));
};
disconnectionRequestManager.addListener(account.getUuid(), device.getId(), listener);
sink.onDispose(() -> disconnectionRequestManager.removeListener(account.getUuid(), device.getId(), listener));
disconnectionRequestManager.addListener(account.getAccountIdentifier(), device.getId(), listener);
sink.onDispose(() -> disconnectionRequestManager.removeListener(account.getAccountIdentifier(), device.getId(), listener));
});
}
@@ -142,7 +142,7 @@ public class MessagesGrpcService extends SimpleMessagesGrpc.MessagesImplBase {
}
final Account destination = maybeDestination.get();
rateLimiters.getMessagesLimiter().validate(authenticatedDevice.accountIdentifier(), destination.getUuid());
rateLimiters.getMessagesLimiter().validate(authenticatedDevice.accountIdentifier(), destination.getAccountIdentifier());
return sendMessage(destination,
destinationServiceIdentifier,
@@ -11,6 +11,7 @@ import org.whispersystems.textsecuregcm.subscriptions.CustomerAwareSubscriptionP
import org.whispersystems.textsecuregcm.subscriptions.PayPalDonationsTranslator;
import org.whispersystems.textsecuregcm.subscriptions.PaymentDetails;
import org.whispersystems.textsecuregcm.subscriptions.PaymentMethod;
import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionCurrencyUtil;
public class OneTimeDonationUtil {
@@ -28,7 +29,7 @@ public class OneTimeDonationUtil {
}
public record LocalizedPayPalDonationLineItem(Locale locale, String itemName){}
public record DonationLevelDetails(long level, Duration levelExpiration){}
public record DonationLevelDetails(ReceiptLevel level, Duration levelExpiration){}
public sealed interface OneTimeDonationRequestValidationResult permits OneTimeDonationRequestValidationResult.Success,
OneTimeDonationRequestValidationResult.UnsupportedCurrency,
@@ -57,8 +58,9 @@ public class OneTimeDonationUtil {
final CustomerAwareSubscriptionPaymentProcessor manager
) {
if (!(level == oneTimeDonationConfiguration.gift().level()
|| level == oneTimeDonationConfiguration.boost().level())) {
if (ReceiptLevel.lookupLevel(level)
.map(rl -> rl != ReceiptLevel.ONE_TIME_DONATION && rl != ReceiptLevel.ONE_TIME_GIFT_DONATION)
.orElse(true)) {
return new OneTimeDonationRequestValidationResult.UnsupportedLevel();
}
@@ -102,29 +104,15 @@ public class OneTimeDonationUtil {
final OneTimeDonationConfiguration oneTimeDonationConfiguration)
throws InvalidLevelException {
long level = oneTimeDonationConfiguration.boost().level();
if (paymentDetails.customMetadata() != null) {
final String levelMetadata = paymentDetails.customMetadata()
.getOrDefault("level", Long.toString(oneTimeDonationConfiguration.boost().level()));
try {
level = Long.parseLong(levelMetadata);
} catch (final NumberFormatException e) {
LOGGER.error("failed to parse level metadata ({}) on payment intent {}", levelMetadata,
paymentDetails.id(), e);
throw new InvalidLevelException("failed to parse level metadata");
final Duration levelExpiration = switch (paymentDetails.level()) {
case ONE_TIME_DONATION -> oneTimeDonationConfiguration.boost().expiration();
case ONE_TIME_GIFT_DONATION -> oneTimeDonationConfiguration.gift().expiration();
default -> {
LOGGER.error("level ({}) returned from payment intent that is unknown to the server", paymentDetails.level());
throw new InvalidLevelException("unrecognized level");
}
}
final Duration levelExpiration;
if (level == oneTimeDonationConfiguration.boost().level()) {
levelExpiration = oneTimeDonationConfiguration.boost().expiration();
} else if (level == oneTimeDonationConfiguration.gift().level()) {
levelExpiration = oneTimeDonationConfiguration.gift().expiration();
} else {
LOGGER.error("level ({}) returned from payment intent that is unknown to the server", level);
throw new InvalidLevelException("unrecognized level");
}
return new DonationLevelDetails(level, levelExpiration);
};
return new DonationLevelDetails(paymentDetails.level(), levelExpiration);
}
}
@@ -261,11 +261,11 @@ public class OneTimeDonationsGrpcService extends SimpleOneTimeDonationsGrpc.OneT
switch (request.getProcessor()) {
case PAYMENT_PROVIDER_STRIPE -> {
processor = PaymentProvider.STRIPE;
maybePaymentDetails = stripeManager.getPaymentDetails(request.getPaymentIntentId());
maybePaymentDetails = stripeManager.claimOneTimePurchase(request.getPaymentIntentId());
}
case PAYMENT_PROVIDER_BRAINTREE -> {
processor = PaymentProvider.BRAINTREE;
maybePaymentDetails = braintreeManager.getPaymentDetails(request.getPaymentIntentId());
maybePaymentDetails = braintreeManager.claimOneTimePurchase(request.getPaymentIntentId());
}
default -> throw GrpcExceptions.fieldViolation("processor", "Unsupported payment processor");
}
@@ -303,24 +303,24 @@ public class OneTimeDonationsGrpcService extends SimpleOneTimeDonationsGrpc.OneT
throw GrpcExceptions.fieldViolation("receipt_credential_request", "invalid receipt credential request");
}
try {
issuedReceiptsManager.recordIssuance(
paymentDetails.id(), processor, receiptCredentialRequest, clock.instant());
} catch (final WriteConflictException e) {
return CreateBoostReceiptCredentialsResponse.newBuilder()
.setReceiptAlreadyIssued(FailedPrecondition.getDefaultInstance()).build();
}
final Instant paidAt = oneTimeDonationsManager.getPaidAt(paymentDetails.id(), paymentDetails.created());
final Instant paidAt = oneTimeDonationsManager.getPaidAt(processor, paymentDetails.id(), paymentDetails.created());
final Instant expiration = paidAt
.plus(levelDetails.levelExpiration())
.truncatedTo(ChronoUnit.DAYS)
.plus(1, ChronoUnit.DAYS);
try {
issuedReceiptsManager.recordOneTimeIssuance(
paymentDetails.id(), processor, receiptCredentialRequest, expiration);
} catch (final WriteConflictException e) {
return CreateBoostReceiptCredentialsResponse.newBuilder()
.setReceiptAlreadyIssued(FailedPrecondition.getDefaultInstance()).build();
}
final ReceiptCredentialResponse receiptCredentialResponse;
try {
receiptCredentialResponse = zkReceiptOperations.issueReceiptCredential(
receiptCredentialRequest, expiration.getEpochSecond(), levelDetails.level());
receiptCredentialRequest, expiration.getEpochSecond(), levelDetails.level().getValue());
} catch (final VerificationFailedException e) {
throw GrpcExceptions.fieldViolation("receipt_credential_request",
"receipt credential request failed verification");
@@ -1,110 +1,47 @@
package org.whispersystems.textsecuregcm.grpc;
import com.google.protobuf.ByteString;
import com.google.protobuf.CodedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import org.signal.chat.purchase.AmountList;
import org.signal.chat.purchase.BackupConfiguration;
import org.signal.chat.purchase.BackupLevelConfiguration;
import org.signal.chat.purchase.Configuration;
import org.signal.chat.purchase.CurrencyConfiguration;
import org.signal.chat.purchase.GetConfigurationRequest;
import org.signal.chat.purchase.GetConfigurationResponse;
import org.signal.chat.purchase.LevelConfiguration;
import org.signal.chat.purchase.LoginConfiguration;
import org.signal.chat.purchase.SimpleProductConfigurationGrpc;
import org.signal.chat.purchase.TaggedConfiguration;
import org.whispersystems.textsecuregcm.badges.BadgeTranslator;
import org.whispersystems.textsecuregcm.configuration.LoginPurchaseConfiguration;
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration;
import org.whispersystems.textsecuregcm.configuration.SubscriptionConfiguration;
import org.whispersystems.textsecuregcm.entities.PurchasableBadge;
import org.whispersystems.textsecuregcm.subscriptions.CustomerAwareSubscriptionPaymentProcessor;
import org.whispersystems.textsecuregcm.subscriptions.PaymentMethod;
import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel;
public class ProductConfigurationGrpcService extends SimpleProductConfigurationGrpc.ProductConfigurationImplBase {
private final SubscriptionConfiguration subscriptionConfiguration;
private final OneTimeDonationConfiguration oneTimeDonationConfiguration;
private final BadgeTranslator badgeTranslator;
// These portions of the configuration are identical on every request
private final Map<String, CurrencyConfiguration> currencyConfigurations;
private final BackupConfiguration backupConfiguration;
// The configuration varies based on the provided Accept-Language header. Here we cache the eTag for the resolved
// language, so if the caller provides a matching etag we don't have to build the full configuration match.
private final ConcurrentHashMap<Locale, ByteString> localeToEtag = new ConcurrentHashMap<>();
private final GetConfigurationResponse configurationResponse;
public ProductConfigurationGrpcService(
final SubscriptionConfiguration subscriptionConfiguration,
final OneTimeDonationConfiguration oneTimeDonationConfiguration,
final LoginPurchaseConfiguration loginPurchaseConfiguration,
List<CustomerAwareSubscriptionPaymentProcessor> paymentProcessors,
final BadgeTranslator badgeTranslator,
final long backupMediaStorageAllowanceBytes) {
this.subscriptionConfiguration = subscriptionConfiguration;
this.oneTimeDonationConfiguration = oneTimeDonationConfiguration;
this.badgeTranslator = badgeTranslator;
this.backupConfiguration = buildBackupConfiguration(subscriptionConfiguration, backupMediaStorageAllowanceBytes);
this.currencyConfigurations =
buildCurrencyConfigurations(subscriptionConfiguration, oneTimeDonationConfiguration, paymentProcessors);
this.configurationResponse = GetConfigurationResponse.newBuilder()
.setBackup(buildBackupConfiguration(subscriptionConfiguration, backupMediaStorageAllowanceBytes))
.setSepaMaximumEuros(oneTimeDonationConfiguration.sepaMaximumEuros().toString())
.putAllCurrencies(buildCurrencyConfigurations(subscriptionConfiguration, oneTimeDonationConfiguration, paymentProcessors))
.putAllBadgeLevels(buildLevelConfigurations(subscriptionConfiguration, oneTimeDonationConfiguration))
.setLogin(buildLoginConfiguration(loginPurchaseConfiguration))
.build();
}
@Override
public GetConfigurationResponse getConfiguration(final GetConfigurationRequest request) {
final Locale locale = badgeTranslator.resolveLocale(RequestAttributesUtil.getAvailableAcceptedLocales());
final ByteString etag = localeToEtag.get(locale);
if (etag != null && etag.equals(request.getEtag())) {
return GetConfigurationResponse.newBuilder().setEtagMatched(true).build();
}
final Map<Long, LevelConfiguration> levelConfigurations = SubscriptionsUtil
.buildDonationLevelsConfiguration(subscriptionConfiguration, oneTimeDonationConfiguration, badgeTranslator,
RequestAttributesUtil.getAvailableAcceptedLocales())
.entrySet().stream().collect(Collectors.toMap(
Map.Entry::getKey,
entry -> toProtoLevelConfiguration(entry.getValue())));
final Configuration configuration = Configuration.newBuilder()
.putAllCurrencies(currencyConfigurations)
.putAllBadgeLevels(levelConfigurations)
.setBackup(backupConfiguration)
.setSepaMaximumEuros(oneTimeDonationConfiguration.sepaMaximumEuros().toString()).build();
final TaggedConfiguration taggedConfiguration = calculateEtag(configuration);
// This could race and multiple threads could decide to build-and-cache. That's fine, they should all calculate
// the same etag.
localeToEtag.put(locale, taggedConfiguration.getEtag());
return GetConfigurationResponse.newBuilder().setTaggedConfiguration(taggedConfiguration).build();
}
private static TaggedConfiguration calculateEtag(final Configuration configuration) {
final ByteArrayOutputStream baos = new ByteArrayOutputStream(configuration.getSerializedSize());
final CodedOutputStream cos = CodedOutputStream.newInstance(baos);
cos.useDeterministicSerialization();
try {
configuration.writeTo(cos);
cos.flush();
final byte[] configurationBytes = baos.toByteArray();
byte[] hash = MessageDigest.getInstance("SHA-256").digest(configurationBytes);
return TaggedConfiguration.newBuilder()
.setConfiguration(configuration)
.setEtag(ByteString.copyFrom(hash))
.build();
} catch (IOException e) {
throw new UncheckedIOException(e);
} catch (NoSuchAlgorithmException e) {
throw new AssertionError(e);
}
return this.configurationResponse;
}
private static Map<String, CurrencyConfiguration> buildCurrencyConfigurations(
@@ -119,6 +56,24 @@ public class ProductConfigurationGrpcService extends SimpleProductConfigurationG
e -> toProtoCurrencyConfiguration(e.getKey(), e.getValue())));
}
private static Map<Long, LevelConfiguration> buildLevelConfigurations(
final SubscriptionConfiguration subscriptionConfiguration,
final OneTimeDonationConfiguration oneTimeDonationConfiguration) {
final Map<Long, LevelConfiguration> donationLevels = new HashMap<>();
subscriptionConfiguration.getDonationLevels().forEach((levelId, levelConfig) -> {
donationLevels.put(levelId, LevelConfiguration.newBuilder().setBadgeId(levelConfig.badge()).build());
});
donationLevels.put(ReceiptLevel.ONE_TIME_DONATION.getValue(),
LevelConfiguration.newBuilder()
.setBadgeId(oneTimeDonationConfiguration.boost().badge())
.setBadgeDurationSeconds(oneTimeDonationConfiguration.boost().expiration().toSeconds()).build());
donationLevels.put(ReceiptLevel.ONE_TIME_GIFT_DONATION.getValue(),
LevelConfiguration.newBuilder()
.setBadgeId(oneTimeDonationConfiguration.gift().badge())
.setBadgeDurationSeconds(oneTimeDonationConfiguration.gift().expiration().toSeconds()).build());
return donationLevels;
}
private static BackupConfiguration buildBackupConfiguration(final SubscriptionConfiguration subscriptionConfiguration,
final long backupMediaStorageAllowanceBytes) {
final Map<Long, BackupLevelConfiguration> backupLevels =
@@ -135,6 +90,15 @@ public class ProductConfigurationGrpcService extends SimpleProductConfigurationG
.build();
}
private static LoginConfiguration buildLoginConfiguration(
final LoginPurchaseConfiguration loginPurchaseConfiguration) {
return LoginConfiguration.newBuilder()
.setLevel(ReceiptLevel.LOGIN.getValue())
.setPlayProductId(loginPurchaseConfiguration.playProductId())
.setAppStoreProductId(loginPurchaseConfiguration.appStoreProductId())
.build();
}
private static CurrencyConfiguration toProtoCurrencyConfiguration(
final String currency,
final org.whispersystems.textsecuregcm.subscriptions.CurrencyConfiguration config) {
@@ -153,15 +117,4 @@ public class ProductConfigurationGrpcService extends SimpleProductConfigurationG
.forEach((levelId, amount) -> builder.putBackupSubscription(levelId, amount.toString()));
return builder.build();
}
private static LevelConfiguration toProtoLevelConfiguration(
final org.whispersystems.textsecuregcm.subscriptions.LevelConfiguration levelConfiguration) {
final LevelConfiguration.Builder builder = LevelConfiguration.newBuilder();
if (levelConfiguration.badge() instanceof final PurchasableBadge purchasableBadge) {
builder.setBadgeDurationSeconds(purchasableBadge.getDuration().toSeconds());
}
return builder
.setBadge(BadgeGrpcHelper.toGrpcBadge(levelConfiguration.badge()))
.build();
}
}
@@ -13,7 +13,6 @@ import java.nio.charset.StandardCharsets;
import java.time.Clock;
import java.util.Arrays;
import java.util.HexFormat;
import java.util.List;
import java.util.Optional;
import org.bouncycastle.crypto.digests.TupleHash;
import org.signal.chat.common.S3UploadForm;
@@ -54,7 +53,7 @@ public class ProfileGrpcHelper {
final ProfileBadgeConverter profileBadgeConverter,
final byte[] requestVersion) {
final Optional<VersionedProfileV1> maybeV1Profile =
profilesManager.getV1(account.getUuid(), HexFormat.of().formatHex(requestVersion));
profilesManager.getV1(account.getAccountIdentifier(), HexFormat.of().formatHex(requestVersion));
if (maybeV1Profile.isEmpty()) {
return Optional.empty();
}
@@ -86,7 +85,7 @@ public class ProfileGrpcHelper {
final byte[] requestVersion) {
final Optional<VersionedProfile> maybeProfile = account.hasCapability(DeviceCapability.PROFILES_V2)
? profilesManager.get(account.getUuid(), requestVersion)
? profilesManager.get(account.getAccountIdentifier(), requestVersion)
: Optional.empty();
if (maybeProfile.isEmpty()) {
return Optional.empty();
@@ -131,13 +130,13 @@ public class ProfileGrpcHelper {
final Optional<VersionedProfile> versionedProfile;
if (account.hasCapability(DeviceCapability.PROFILES_V2)) {
versionedProfile = profilesManager.get(account.getUuid(), version);
versionedProfile = profilesManager.get(account.getAccountIdentifier(), version);
} else {
versionedProfile = Optional.empty();
}
return versionedProfile.map(VersionedProfile::commitment)
.or(() -> profilesManager.getV1(account.getUuid(), HexFormat.of().formatHex(version))
.or(() -> profilesManager.getV1(account.getAccountIdentifier(), HexFormat.of().formatHex(version))
.map(VersionedProfileV1::commitment))
.map(commitment -> {
@@ -145,7 +144,7 @@ public class ProfileGrpcHelper {
try {
profileKeyCredentialResponse = ProfileHelper.getExpiringProfileKeyCredential(
new ProfileKeyCredentialRequest(encodedCredentialRequest),
new ProfileKeyCommitment(commitment), new ServiceId.Aci(account.getUuid()), zkProfileOperations);
new ProfileKeyCommitment(commitment), new ServiceId.Aci(account.getAccountIdentifier()), zkProfileOperations);
} catch (VerificationFailedException | InvalidInputException e) {
throw GrpcExceptions.invalidArguments("invalid credential request");
}
@@ -16,6 +16,7 @@ import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import org.signal.chat.common.S3UploadForm;
import org.signal.chat.errors.FailedPrecondition;
@@ -37,8 +38,7 @@ import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.VerificationFailedException;
import org.signal.libsignal.zkgroup.avatars.AvatarUploadCredentialRequest;
import org.signal.libsignal.zkgroup.avatars.AvatarUploadCredentialResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.asn.AsnInfoProvider;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
import org.whispersystems.textsecuregcm.badges.ProfileBadgeConverter;
@@ -46,7 +46,6 @@ import org.whispersystems.textsecuregcm.configuration.BadgeConfiguration;
import org.whispersystems.textsecuregcm.configuration.BadgesConfiguration;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
@@ -63,11 +62,10 @@ import org.whispersystems.textsecuregcm.util.ProfileHelper;
public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
private static final Logger logger = LoggerFactory.getLogger(ProfileGrpcService.class);
private final Clock clock;
private final AccountsManager accountsManager;
private final ProfilesManager profilesManager;
private final Supplier<AsnInfoProvider> asnInfoProviderSupplier;
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
private final Map<String, BadgeConfiguration> badgeConfigurationMap;
private final PostPolicyGenerator policyGenerator;
@@ -83,6 +81,7 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
final Clock clock,
final AccountsManager accountsManager,
final ProfilesManager profilesManager,
final Supplier<AsnInfoProvider> asnInfoProviderSupplier,
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
final BadgesConfiguration badgesConfiguration,
final PostPolicyGenerator policyGenerator,
@@ -92,9 +91,10 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
this.clock = clock;
this.accountsManager = accountsManager;
this.profilesManager = profilesManager;
this.asnInfoProviderSupplier = asnInfoProviderSupplier;
this.dynamicConfigurationManager = dynamicConfigurationManager;
this.badgeConfigurationMap = badgesConfiguration.getBadges().stream().collect(Collectors.toMap(
BadgeConfiguration::getId, Function.identity()));
this.badgeConfigurationMap = badgesConfiguration.getBadges().stream()
.collect(Collectors.toMap(BadgeConfiguration::getId, Function.identity()));
this.policyGenerator = policyGenerator;
this.genericServerSecretParams = genericServerSecretParams;
this.profileBadgeConverter = profileBadgeConverter;
@@ -132,7 +132,9 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
final Optional<VersionedProfileV1> maybeV1Profile = profilesManager.getV1(
authenticatedDevice.accountIdentifier(), HexFormat.of().formatHex(version));
if (!request.getPaymentAddress().isEmpty() && ProfileHelper.isPaymentAddressUpdateForbidden(account, maybeProfile, maybeV1Profile, dynamicConfigurationManager)) {
if (!request.getPaymentAddress().isEmpty() &&
ProfileHelper.isPaymentAddressUpdateForbidden(account, maybeProfile, maybeV1Profile, RequestAttributesUtil.getRemoteAddress().getHostAddress(), asnInfoProviderSupplier.get(), dynamicConfigurationManager)) {
return SetProfileResponse.newBuilder()
.setPaymentsForbiddenInRegion(PaymentsForbiddenInRegion.getDefaultInstance())
.build();
@@ -172,7 +174,7 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
);
try {
profilesManager.set(account.getIdentifier(IdentityType.ACI), v1Profile, profile,
profilesManager.set(account.getAccountIdentifier(), v1Profile, profile,
request.getExpectedCurrentDataHash().isEmpty() ? null : request.getExpectedCurrentDataHash().toByteArray());
} catch (WriteConflictException _) {
@@ -184,7 +186,7 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
}
try {
accountsManager.updateCurrentProfileVersion(account.getIdentifier(IdentityType.ACI), version, expectedCurrentVersion, a -> {
accountsManager.updateCurrentProfileVersion(account.getAccountIdentifier(), version, expectedCurrentVersion, a -> {
final List<AccountBadge> updatedBadges = Optional.of(request.getBadgeIdsList())
.map(badges -> ProfileHelper.mergeBadgeIdsWithExistingAccountBadges(clock, badgeConfigurationMap, badges,
@@ -235,7 +237,7 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
request.getAvatarCredentialsRequest().toByteArray());
final AvatarUploadCredentialResponse credentialResponse = credentialRequest.issueCredential(
new ServiceId.Aci(account.getIdentifier(IdentityType.ACI)),
new ServiceId.Aci(account.getAccountIdentifier()),
account.getZkCredentialKey().get(),
Objects.requireNonNull(account.getZkCredentialKeyRotationId()),
clock.instant().truncatedTo(ChronoUnit.DAYS),
@@ -0,0 +1,121 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc;
import com.google.protobuf.ByteString;
import com.google.protobuf.CodedOutputStream;
import com.google.protobuf.Message;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.signal.chat.common.Badge;
import org.signal.chat.remoteconfiguration.Badges;
import org.signal.chat.remoteconfiguration.Configuration;
import org.signal.chat.remoteconfiguration.GetBadgesRequest;
import org.signal.chat.remoteconfiguration.GetBadgesResponse;
import org.signal.chat.remoteconfiguration.GetConfigurationRequest;
import org.signal.chat.remoteconfiguration.GetConfigurationResponse;
import org.signal.chat.remoteconfiguration.SimpleRemoteConfigurationGrpc;
import org.signal.chat.remoteconfiguration.TaggedBadges;
import org.signal.chat.remoteconfiguration.TaggedConfiguration;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
import org.whispersystems.textsecuregcm.badges.BadgeTranslator;
import org.whispersystems.textsecuregcm.storage.RemoteConfigsManager;
public class RemoteConfigurationGrpcService extends SimpleRemoteConfigurationGrpc.RemoteConfigurationImplBase {
private static final GetConfigurationResponse CONFIGURATION_ETAG_MATCHED =
GetConfigurationResponse.newBuilder().setEtagMatched(true).build();
private static final GetBadgesResponse BADGES_ETAG_MATCHED =
GetBadgesResponse.newBuilder().setEtagMatched(true).build();
private final RemoteConfigsManager remoteConfigsManager;
private final BadgeTranslator badgeTranslator;
private final List<String> badgeIds;
// Badge information varies based on the provided Accept-Language header. Here we cache the etag for the resolved
// language, so if the caller provides a matching etag we don't have to build the full badge response.
private final ConcurrentHashMap<Locale, ByteString> localeToBadgesEtag = new ConcurrentHashMap<>();
public RemoteConfigurationGrpcService(
final RemoteConfigsManager remoteConfigsManager,
final BadgeTranslator badgeTranslator,
final List<String> badgeIds) {
this.remoteConfigsManager = remoteConfigsManager;
this.badgeTranslator = badgeTranslator;
this.badgeIds = badgeIds;
}
@Override
public GetConfigurationResponse getConfiguration(final GetConfigurationRequest request) {
final UUID accountIdentifier = AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier();
final String userAgent = RequestAttributesUtil.getUserAgent().orElse(null);
final Map<String, String> configForAccount = remoteConfigsManager.getConfigForAccount(accountIdentifier, userAgent);
final Configuration configuration = Configuration.newBuilder()
.putAllConfiguration(configForAccount)
.build();
final ByteString etagByteString = etag(configuration);
if (etagByteString.equals(request.getEtag())) {
return CONFIGURATION_ETAG_MATCHED;
}
return GetConfigurationResponse.newBuilder()
.setTaggedConfiguration(TaggedConfiguration.newBuilder()
.setEtag(etagByteString)
.setConfiguration(configuration))
.build();
}
@Override
public GetBadgesResponse getBadges(final GetBadgesRequest request) {
final List<Locale> acceptableLanguages = RequestAttributesUtil.getAvailableAcceptedLocales();
final Locale locale = badgeTranslator.resolveLocale(acceptableLanguages);
final ByteString cachedEtag = localeToBadgesEtag.get(locale);
if (cachedEtag != null && cachedEtag.equals(request.getEtag())) {
return BADGES_ETAG_MATCHED;
}
final Map<String, Badge> badgesById = badgeIds.stream().collect(Collectors.toMap(
Function.identity(),
badgeId -> BadgeGrpcHelper.toGrpcBadge(badgeTranslator.translate(acceptableLanguages, badgeId))));
final Badges badges = Badges.newBuilder().putAllBadges(badgesById).build();
final TaggedBadges taggedBadges = TaggedBadges.newBuilder()
.setBadges(badges)
.setEtag(etag(badges))
.build();
// This could race and multiple threads could decide to build-and-cache. That's fine, they should all calculate
// the same etag.
localeToBadgesEtag.put(locale, taggedBadges.getEtag());
return GetBadgesResponse.newBuilder().setTaggedBadges(taggedBadges).build();
}
private static ByteString etag(final Message message) {
final ByteArrayOutputStream baos = new ByteArrayOutputStream(message.getSerializedSize());
final CodedOutputStream cos = CodedOutputStream.newInstance(baos);
cos.useDeterministicSerialization();
try {
message.writeTo(cos);
cos.flush();
return ByteString.copyFrom(MessageDigest.getInstance("SHA-256").digest(baos.toByteArray()));
} catch (final IOException e) {
throw new UncheckedIOException(e);
} catch (final NoSuchAlgorithmException e) {
throw new AssertionError(e);
}
}
}
@@ -31,6 +31,7 @@ import org.whispersystems.textsecuregcm.subscriptions.CustomerAwareSubscriptionP
import org.whispersystems.textsecuregcm.subscriptions.LevelConfiguration;
import org.whispersystems.textsecuregcm.subscriptions.PaymentMethod;
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel;
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
import org.whispersystems.textsecuregcm.util.ua.UnrecognizedUserAgentException;
import org.whispersystems.textsecuregcm.util.ua.UserAgentUtil;
@@ -80,8 +81,8 @@ public class SubscriptionsUtil {
final OneTimeDonationCurrencyConfiguration currencyConfig = currencyAndConfig.getValue();
final Map<Long, List<BigDecimal>> oneTimeLevelsToSuggestedAmounts = Map.of(
oneTimeDonationConfiguration.boost().level(), currencyConfig.boosts(),
oneTimeDonationConfiguration.gift().level(), List.of(currencyConfig.gift())
ReceiptLevel.ONE_TIME_DONATION.getValue(), currencyConfig.boosts(),
ReceiptLevel.ONE_TIME_GIFT_DONATION.getValue(), List.of(currencyConfig.gift())
);
final Function<Map<Long, ? extends SubscriptionLevelConfiguration>, Map<Long, BigDecimal>> extractSubscriptionAmounts = levels ->
@@ -125,7 +126,7 @@ public class SubscriptionsUtil {
final Badge boostBadge = badgeTranslator.translate(acceptableLanguages,
oneTimeDonationConfiguration.boost().badge());
donationLevels.put(oneTimeDonationConfiguration.boost().level(),
donationLevels.put(ReceiptLevel.ONE_TIME_DONATION.getValue(),
new LevelConfiguration(
// NB: the one-time badges are PurchasableBadge, which has a `duration` field
new PurchasableBadge(
@@ -133,7 +134,7 @@ public class SubscriptionsUtil {
oneTimeDonationConfiguration.boost().expiration())));
final Badge giftBadge = badgeTranslator.translate(acceptableLanguages, oneTimeDonationConfiguration.gift().badge());
donationLevels.put(oneTimeDonationConfiguration.gift().level(),
donationLevels.put(ReceiptLevel.ONE_TIME_GIFT_DONATION.getValue(),
new LevelConfiguration(
new PurchasableBadge(
giftBadge,
@@ -53,7 +53,7 @@ public class PushChallengeManager {
final boolean sent;
final String platform;
if (pushChallengeDynamoDb.add(account.getUuid(), token, CHALLENGE_TTL)) {
if (pushChallengeDynamoDb.add(account.getAccountIdentifier(), token, CHALLENGE_TTL)) {
pushNotificationManager.sendRateLimitChallengeNotification(account, HexFormat.of().formatHex(token));
sent = true;
@@ -74,7 +74,7 @@ public class PushChallengeManager {
Metrics.counter(CHALLENGE_REQUESTED_COUNTER_NAME,
PLATFORM_TAG_NAME, platform,
SOURCE_COUNTRY_TAG_NAME, Util.getCountryCode(account.getNumber()),
SOURCE_COUNTRY_TAG_NAME, Util.getCountryCode(account),
SENT_TAG_NAME, String.valueOf(sent)).increment();
}
@@ -82,7 +82,7 @@ public class PushChallengeManager {
boolean success = false;
try {
success = pushChallengeDynamoDb.remove(account.getUuid(), HexFormat.of().parseHex(challengeTokenHex));
success = pushChallengeDynamoDb.remove(account.getAccountIdentifier(), HexFormat.of().parseHex(challengeTokenHex));
} catch (final IllegalArgumentException ignored) {
}
@@ -98,7 +98,7 @@ public class PushChallengeManager {
Metrics.counter(CHALLENGE_ANSWERED_COUNTER_NAME,
PLATFORM_TAG_NAME, platform,
SOURCE_COUNTRY_TAG_NAME, Util.getCountryCode(account.getNumber()),
SOURCE_COUNTRY_TAG_NAME, Util.getCountryCode(account),
SUCCESS_TAG_NAME, String.valueOf(success)).increment();
return success;
@@ -55,12 +55,12 @@ public class RateLimitChallengeManager {
}
public boolean answerPushChallenge(final Account account, final String challenge) throws RateLimitExceededException {
rateLimiters.getPushChallengeAttemptLimiter().validate(account.getUuid());
rateLimiters.getPushChallengeAttemptLimiter().validate(account.getAccountIdentifier());
final boolean challengeSuccess = pushChallengeManager.answerChallenge(account, challenge);
if (challengeSuccess) {
rateLimiters.getPushChallengeSuccessLimiter().validate(account.getUuid());
rateLimiters.getPushChallengeSuccessLimiter().validate(account.getAccountIdentifier());
resetRateLimits(account, ChallengeType.PUSH);
}
return challengeSuccess;
@@ -73,15 +73,15 @@ public class RateLimitChallengeManager {
final Optional<Float> scoreThreshold)
throws RateLimitExceededException, IOException, InvalidCaptchaArgumentException {
rateLimiters.getCaptchaChallengeAttemptLimiter().validate(account.getUuid());
rateLimiters.getCaptchaChallengeAttemptLimiter().validate(account.getAccountIdentifier());
final AssessmentResult assessmentResult =
captchaChecker.verify(Optional.of(account.getUuid()), Action.CHALLENGE, captcha, mostRecentProxyIp, userAgent);
captchaChecker.verify(Optional.of(account.getAccountIdentifier()), Action.CHALLENGE, captcha, mostRecentProxyIp, userAgent);
final boolean challengeSuccess = assessmentResult.isValid(scoreThreshold);
final Tags tags = Tags.of(
Tag.of(SOURCE_COUNTRY_TAG_NAME, Util.getCountryCode(account.getNumber())),
Tag.of(SOURCE_COUNTRY_TAG_NAME, Util.getCountryCode(account)),
Tag.of(SUCCESS_TAG_NAME, String.valueOf(challengeSuccess)),
UserAgentTagUtil.getPlatformTag(userAgent)
);
@@ -90,13 +90,13 @@ public class RateLimitChallengeManager {
CaptchaMetrics.measureCaptchaOutcome(assessmentResult.getNormalizedIntScore(),
challengeSuccess,
Util.getRegion(account.getNumber()),
Util.getRegion(account),
// Note: currently all challenges are for message-sending, but if we add more use cases, we'll need to make the
// accept a context from callers rather than hard-coding it here
"sendMessage");
if (challengeSuccess) {
rateLimiters.getCaptchaChallengeSuccessLimiter().validate(account.getUuid());
rateLimiters.getCaptchaChallengeSuccessLimiter().validate(account.getAccountIdentifier());
resetRateLimits(account, ChallengeType.CAPTCHA);
}
return challengeSuccess;
@@ -104,10 +104,10 @@ public class RateLimitChallengeManager {
private void resetRateLimits(final Account account, final ChallengeType type) throws RateLimitExceededException {
try {
rateLimiters.getRateLimitResetLimiter().validate(account.getUuid());
rateLimiters.getRateLimitResetLimiter().validate(account.getAccountIdentifier());
} catch (final RateLimitExceededException e) {
Metrics.counter(RESET_RATE_LIMIT_EXCEEDED_COUNTER_NAME,
SOURCE_COUNTRY_TAG_NAME, Util.getCountryCode(account.getNumber())).increment();
SOURCE_COUNTRY_TAG_NAME, Util.getCountryCode(account)).increment();
throw e;
}
@@ -20,14 +20,14 @@ public class RateLimitChallengeOptionManager {
public List<RateLimitChallengeOption> getChallengeOptions(final Account account) {
final List<RateLimitChallengeOption> options = new ArrayList<>(2);
if (rateLimiters.getCaptchaChallengeAttemptLimiter().hasAvailablePermits(account.getUuid(), 1) &&
rateLimiters.getCaptchaChallengeSuccessLimiter().hasAvailablePermits(account.getUuid(), 1)) {
if (rateLimiters.getCaptchaChallengeAttemptLimiter().hasAvailablePermits(account.getAccountIdentifier(), 1) &&
rateLimiters.getCaptchaChallengeSuccessLimiter().hasAvailablePermits(account.getAccountIdentifier(), 1)) {
options.add(RateLimitChallengeOption.CAPTCHA);
}
if (rateLimiters.getPushChallengeAttemptLimiter().hasAvailablePermits(account.getUuid(), 1) &&
rateLimiters.getPushChallengeSuccessLimiter().hasAvailablePermits(account.getUuid(), 1)) {
if (rateLimiters.getPushChallengeAttemptLimiter().hasAvailablePermits(account.getAccountIdentifier(), 1) &&
rateLimiters.getPushChallengeSuccessLimiter().hasAvailablePermits(account.getAccountIdentifier(), 1)) {
options.add(RateLimitChallengeOption.PUSH_CHALLENGE);
}
@@ -0,0 +1,31 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.mappers;
import io.dropwizard.jersey.errors.ErrorMessage;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.ext.ExceptionMapper;
import jakarta.ws.rs.ext.Provider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.util.logging.ImpossibleEvents;
@Provider
public class IllegalStateExceptionMapper implements ExceptionMapper<IllegalStateException> {
private static final Logger logger = LoggerFactory.getLogger(IllegalStateExceptionMapper.class);
@Override
public Response toResponse(final IllegalStateException exception) {
ImpossibleEvents.logImpossible(logger, exception.getMessage(), exception);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity(new ErrorMessage(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
"There was an internal server error processing your request"))
.type(MediaType.APPLICATION_JSON_TYPE)
.build();
}
}
@@ -35,15 +35,19 @@ public class ReportedMessageMetricsListener implements ReportedMessageListener {
}
@Override
public void handleMessageReported(final String sourceNumber, final UUID messageGuid, final UUID reporterUuid,
final Optional<byte[]> reportSpamToken) {
public void handleMessageReported(final Optional<String> sourceNumber, final UUID messageGuid, final UUID reporterUuid,
final Optional<byte[]> reportSpamToken, final boolean sourceAccountDeleted) {
final String sourceCountryCode = Util.getCountryCode(sourceNumber);
if (sourceNumber.isEmpty() && sourceAccountDeleted) {
return;
}
final String sourceCountryCode = sourceNumber.map(Util::getCountryCode).orElse(Util.COUNTRY_CODE_NOT_APPLICABLE);
Metrics.counter(REPORTED_COUNTER_NAME, COUNTRY_CODE_TAG_NAME, sourceCountryCode).increment();
accountsManager.getByAccountIdentifier(reporterUuid).ifPresent(reporter -> {
final String destinationCountryCode = Util.getCountryCode(reporter.getNumber());
final String destinationCountryCode = Util.getCountryCode(reporter);
logger.info(Markers.appendEntries(Map.of(
"sourceCountry", sourceCountryCode,
@@ -12,8 +12,6 @@ import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tags;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.function.BiConsumer;
@@ -217,7 +215,7 @@ public class PushNotificationManager {
// Reread the account to avoid marking the caller's account as stale. The consumers of this class tend to
// promise not to modify accounts. There's no need to force the caller to be considered mutable just for
// updating an uninstalled feedback timestamp though.
accountsManager.getByAccountIdentifier(account.getUuid()).ifPresent(rereadAccount ->
accountsManager.getByAccountIdentifier(account.getAccountIdentifier()).ifPresent(rereadAccount ->
rereadAccount.getDevice(device.getId()).ifPresent(rereadDevice ->
accountsManager.updateDevice(rereadAccount.getIdentifier(IdentityType.ACI), device.getId(), d -> {
// Don't clear the token if it's already changed
@@ -350,7 +350,7 @@ public class PushNotificationScheduler implements Managed {
// the original device's id, the new device might get the old device's scheduled push, or the new device might
// delay its own push because the old device had a recent push. An extra or delayed background push is harmless,
// so this is okay.
return account.getUuid() + ":" + device.getId();
return account.getAccountIdentifier() + ":" + device.getId();
}
static Pair<UUID, Byte> decodeAciAndDeviceId(final String encoded) {
@@ -26,31 +26,32 @@ public class SchedulingUtil {
private static final String PARSED_TIMEZONE_COUNTER_NAME = MetricsUtil.name(SchedulingUtil.class, "parsedTimezone");
private static final String HAS_TIMEZONE_TAG_NAME = "hasTimezone";
/**
* Gets a present or future time at which to send a notification to a device associated with the given account. This
* is mainly intended to facilitate scheduling notifications such that they arrive during a recipient's waking hours.
* <p/>
* This method will attempt to use a timezone derived from the account's phone number to choose an appropriate time
* to send a notification. If a timezone cannot be derived from the account's phone number, then this method will
* default to the preferred time in the server's timezone.
*
* @param account the account that will receive the notification
* @param preferredTime the preferred local time (e.g. "noon") at which to deliver the notification
* @param clock a source of the current time
*
* @return the next time in the present or future at which to send a notification for the target account
*/
/// Gets a present or future time at which to send a notification to a device associated with the given account. This
/// is mainly intended to facilitate scheduling notifications such that they arrive during a recipient's waking hours.
///
/// This method will attempt to use a timezone derived from the account's phone number to choose an appropriate time
/// to send a notification. If a timezone cannot be derived from the account's phone number, or there is no phone number
/// associated with the account, then this method will default to the preferred time in the server's timezone.
///
/// @param account the account that will receive the notification
/// @param preferredTime the preferred local time (e.g. "noon") at which to deliver the notification
/// @param clock a source of the current time
///
/// @return the next time in the present or future at which to send a notification for the target account
public static Instant getNextRecommendedNotificationTime(final Account account,
final LocalTime preferredTime,
final Clock clock) {
final ZonedDateTime candidateNotificationTime = getZoneId(account.getNumber(), clock)
final ZonedDateTime candidateNotificationTime = account.getNumberOptional()
.flatMap(number -> getZoneId(number, clock))
.map(zoneId -> {
Metrics.counter(PARSED_TIMEZONE_COUNTER_NAME, HAS_TIMEZONE_TAG_NAME, String.valueOf(true)).increment();
return ZonedDateTime.now(clock.withZone(zoneId)).with(preferredTime);
})
.orElseGet(() -> {
Metrics.counter(PARSED_TIMEZONE_COUNTER_NAME, HAS_TIMEZONE_TAG_NAME, String.valueOf(false)).increment();
if (account.getNumberOptional().isPresent()) {
Metrics.counter(PARSED_TIMEZONE_COUNTER_NAME, HAS_TIMEZONE_TAG_NAME, String.valueOf(false)).increment();
}
return ZonedDateTime.now(ZoneId.systemDefault()).with(preferredTime);
});
@@ -24,9 +24,11 @@ import java.util.Base64;
import java.util.Collections;
import java.util.HexFormat;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import org.apache.commons.lang3.StringUtils;
import org.signal.libsignal.protocol.IdentityKey;
@@ -37,7 +39,9 @@ import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
import org.whispersystems.textsecuregcm.auth.StoredRegistrationLock;
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.util.ByteArrayBase64UrlAdapter;
import org.whispersystems.textsecuregcm.util.IdentityKeyAdapter;
@@ -52,9 +56,11 @@ public class Account {
private UUID uuid;
@JsonProperty("pni")
@Nullable
private UUID phoneNumberIdentifier;
@JsonProperty
@Nullable
private String number;
@JsonProperty
@@ -88,6 +94,7 @@ public class Account {
@JsonProperty("pniIdentityKey")
@JsonSerialize(using = IdentityKeyAdapter.Serializer.class)
@JsonDeserialize(using = IdentityKeyAdapter.Deserializer.class)
@Nullable
private IdentityKey phoneNumberIdentityKey;
@JsonProperty("cpv")
@@ -141,6 +148,18 @@ public class Account {
@JsonProperty("holds")
private List<UsernameHold> usernameHolds = Collections.emptyList();
@JsonProperty("arps")
@Nullable
private String accountRecoveryPasswordSalt;
@JsonProperty("arph")
@Nullable
private String accountRecoveryPasswordHash;
@JsonProperty("acs")
@Nullable
private byte[] authCredentialSalt;
@JsonIgnore
private boolean stale;
@@ -148,37 +167,72 @@ public class Account {
public record BackupVoucher(@JsonProperty("rl") long receiptLevel, @JsonProperty("e") Instant expiration) {}
/// Returns an identifier for the given identity type for this account with the assumption that all accounts have
/// identifiers for all identity types.
///
/// @param identityType the identity type for which to retrieve an account identifier
///
/// @return the identifier for the given identity type
///
/// @throws NoSuchElementException if the account does not have an identifier for the given identity type
///
/// @deprecated Different identity types have significantly differing presence and staleness requirements/guarantees
/// for their respective account identifiers. Please use [#getAccountIdentifier()] or
/// [#getPhoneNumberIdentifierOptional()] instead.
@Deprecated
public UUID getIdentifier(final IdentityType identityType) {
return switch (identityType) {
case ACI -> getUuid();
case ACI -> getAccountIdentifier();
case PNI -> getPhoneNumberIdentifier();
};
}
public UUID getUuid() {
/// Returns the core account identifier (ACI) for this account. An account's core identifier never changes.
///
/// @return the core account identifier for this account
public UUID getAccountIdentifier() {
// this is the one method that may be called on a stale account
return uuid;
}
public void setUuid(final UUID uuid) {
public void setAccountIdentifier(final UUID accountIdentifier) {
requireNotStale();
this.uuid = uuid;
this.uuid = accountIdentifier;
}
/// Returns the phone number identifier for this account.
///
/// @throws NoSuchElementException if this account does not have a phone number identifier
///
/// @return the phone number identifier for this account
///
/// @deprecated Please use [#getPhoneNumberIdentifierOptional()] (which has clearer presence semantics) instead.
@Deprecated
public UUID getPhoneNumberIdentifier() {
requireNotStale();
if (phoneNumberIdentifier == null) {
throw new NoSuchElementException();
}
return phoneNumberIdentifier;
}
/**
* Tests whether this account's account identifier or phone number identifier (depending on the given service
* identifier's identity type) matches the given service identifier.
*
* @param serviceIdentifier the identifier to test
* @return {@code true} if this account's identifier or phone number identifier matches
*/
/// Returns the phone number identifier for this account or empty if this account does not have a phone number.
///
/// @return the phone number identifier for this account or empty if this account does not have a phone number
public Optional<UUID> getPhoneNumberIdentifierOptional() {
requireNotStale();
return Optional.ofNullable(phoneNumberIdentifier);
}
/// Tests whether this account's account identifier or phone number identifier (depending on the given service
/// identifier's identity type) matches the given service identifier.
///
/// @param serviceIdentifier the identifier to test
/// @return `true` if this account's identifier or phone number identifier matches
public boolean isIdentifiedBy(final ServiceIdentifier serviceIdentifier) {
return switch (serviceIdentifier.identityType()) {
case ACI -> serviceIdentifier.uuid().equals(uuid);
@@ -186,12 +240,31 @@ public class Account {
};
}
/// Returns the E.164-formatted phone number for this account.
///
/// @return the E.164-formatted phone number for this account
///
/// @throws NoSuchElementException if this account does not have a phone number
@Deprecated
public String getNumber() {
requireNotStale();
if (number == null) {
throw new NoSuchElementException();
}
return number;
}
/// Returns the phone number for this account or empty if this account does not have a phone number.
///
/// @return the phone number for this account or empty if this account does not have a phone number
public Optional<String> getNumberOptional() {
requireNotStale();
return Optional.ofNullable(number);
}
public void setNumber(final String number, final UUID phoneNumberIdentifier) {
requireNotStale();
@@ -320,16 +393,51 @@ public class Account {
this.identityKey = identityKey;
}
/// Returns an identity key for the given identity type for this account with the assumption that all accounts have
/// identity keys for all identity types.
///
/// @param identityType the identity type for which to retrieve an identity key
///
/// @return the identity key for the given identity type
///
/// @throws NoSuchElementException if the account does not have an identifier (and therefore identity key) for the given identity type
///
/// @deprecated Different identity types have significantly differing existence requirements/guarantees
/// for their respective identity keys. Please use [#getAccountIdentityKey()] or
/// [#getPhoneNumberIdentityKey()] instead.
@Deprecated
public IdentityKey getIdentityKey(final IdentityType identityType) {
requireNotStale();
return switch (identityType) {
case ACI -> identityKey;
case PNI -> phoneNumberIdentityKey;
case PNI -> Optional.ofNullable(phoneNumberIdentityKey).orElseThrow(NoSuchElementException::new);
};
}
/// Returns an identity key for the ACI identity for this account.
public IdentityKey getAccountIdentityKey() {
requireNotStale();
return identityKey;
}
/// Returns an identity key for the phone-number identity for this account, if it has such an identity.
///
/// @return the identity key for the PNI identity for the account if it has one, or an empty `Optional` otherwise.
public Optional<IdentityKey> getPhoneNumberIdentityKey() {
requireNotStale();
return Optional.ofNullable(phoneNumberIdentityKey);
}
/// Sets the identity key for the phone-number identity of this account.
///
/// @throws IllegalStateException if the account does not have a phone number identifier.
public void setPhoneNumberIdentityKey(final IdentityKey phoneNumberIdentityKey) {
requireNotStale();
if (this.phoneNumberIdentifier == null) {
throw new IllegalStateException();
}
this.phoneNumberIdentityKey = phoneNumberIdentityKey;
}
@@ -438,6 +546,10 @@ public class Account {
public void setRegistrationLock(final String registrationLock, final String registrationLockSalt) {
requireNotStale();
if (number == null) {
throw new IllegalArgumentException("Cannot set registration lock on account with no phone number");
}
this.registrationLock = registrationLock;
this.registrationLockSalt = registrationLockSalt;
}
@@ -474,10 +586,17 @@ public class Account {
this.unrestrictedUnidentifiedAccess = unrestrictedUnidentifiedAccess;
}
/// Indicates whether this account may be discovered by its phone number via the contact discovery system (CDS).
///
/// @return `true` if this account has a phone number and has opted into discovery by phone number or `false`
/// otherwise
///
/// @see #getPhoneNumberIdentifierOptional()
/// @see #setDiscoverableByPhoneNumber(boolean)
public boolean isDiscoverableByPhoneNumber() {
requireNotStale();
return this.discoverableByPhoneNumber;
return getPhoneNumberIdentifierOptional().isPresent() && this.discoverableByPhoneNumber;
}
public void setDiscoverableByPhoneNumber(final boolean discoverableByPhoneNumber) {
@@ -528,26 +647,22 @@ public class Account {
this.backupVoucher = backupVoucher;
}
/**
* Have all this account's devices been manually locked?
*
* @see Device#hasLockedCredentials
*
* @return true if all the account's devices were locked, false otherwise.
*/
/// Have all this account's devices been manually locked?
///
/// @see Device#hasLockedCredentials
///
/// @return true if all the account's devices were locked, false otherwise.
public boolean hasLockedCredentials() {
return devices.stream().allMatch(Device::hasLockedCredentials);
}
/**
* Lock account by invalidating authentication tokens.
*
* We only want to do this in cases where there is a potential conflict between the
* phone number holder and the registration lock holder. In that case, locking the
* account will ensure that either the registration lock holder proves ownership
* of the phone number, or after 7 days the phone number holder can register a new
* account.
*/
/// Lock account by invalidating authentication tokens.
///
/// We only want to do this in cases where there is a potential conflict between the
/// phone number holder and the registration lock holder. In that case, locking the
/// account will ensure that either the registration lock holder proves ownership
/// of the phone number, or after 7 days the phone number holder can register a new
/// account.
public void lockAuthTokenHash() {
devices.forEach(Device::lockAuthTokenHash);
}
@@ -578,6 +693,37 @@ public class Account {
this.zkCredentialKeyRotationId = zkCredentialKeyRotationId;
}
public Optional<SaltedTokenHash> getAccountRecoveryPassword() {
requireNotStale();
return accountRecoveryPasswordHash != null && accountRecoveryPasswordSalt != null
? Optional.of(new SaltedTokenHash(accountRecoveryPasswordHash, accountRecoveryPasswordSalt))
: Optional.empty();
}
public void setAccountRecoveryPassword(final byte[] accountRecoveryPassword) {
requireNotStale();
setAccountRecoveryPassword(SaltedTokenHash.generateFor(HexFormat.of().formatHex(accountRecoveryPassword)));
}
public void setAccountRecoveryPassword(final SaltedTokenHash saltedAccountRecoveryPasswordHash) {
requireNotStale();
this.accountRecoveryPasswordSalt = saltedAccountRecoveryPasswordHash.salt();
this.accountRecoveryPasswordHash = saltedAccountRecoveryPasswordHash.hash();
}
public Optional<byte[]> getAuthCredentialSalt() {
requireNotStale();
return Optional.ofNullable(authCredentialSalt);
}
public void setAuthCredentialSalt(final byte[] authCredentialSalt) {
requireNotStale();
this.authCredentialSalt = authCredentialSalt;
}
public void markStale() {
stale = true;
}
@@ -32,16 +32,16 @@ class AccountChangeValidator {
public void validateChange(final Account originalAccount, final Account updatedAccount) {
if (!allowNumberChange) {
assert updatedAccount.getNumber().equals(originalAccount.getNumber());
assert updatedAccount.getNumberOptional().equals(originalAccount.getNumberOptional());
if (!updatedAccount.getNumber().equals(originalAccount.getNumber())) {
if (!updatedAccount.getNumberOptional().equals(originalAccount.getNumberOptional())) {
logger.error("Account number changed via \"normal\" update; numbers must be changed via changeNumber method",
new RuntimeException());
}
assert updatedAccount.getPhoneNumberIdentifier().equals(originalAccount.getPhoneNumberIdentifier());
assert updatedAccount.getPhoneNumberIdentifierOptional().equals(originalAccount.getPhoneNumberIdentifierOptional());
if (!updatedAccount.getPhoneNumberIdentifier().equals(originalAccount.getPhoneNumberIdentifier())) {
if (!updatedAccount.getPhoneNumberIdentifierOptional().equals(originalAccount.getPhoneNumberIdentifierOptional())) {
logger.error(
"Phone number identifier changed via \"normal\" update; PNIs must be changed via changeNumber method",
new RuntimeException());
@@ -39,22 +39,20 @@ public class AccountLockManager {
this.lockClient = lockClient;
}
/**
* Acquires a distributed, pessimistic lock for the accounts identified by the given phone number identifiers. By
* design, the accounts need not actually exist in order to acquire a lock; this allows lock acquisition for
* operations that span account lifecycle changes (like deleting an account or changing a phone number). The given
* task runs once locks for all given identifiers have been acquired, and the locks are released as soon as the task
* completes by any means.
*
* @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}
*/
/// Acquires a distributed, pessimistic lock for the accounts identified by the given phone number identifiers. By
/// design, the accounts need not actually exist in order to acquire a lock; this allows lock acquisition for
/// operations that span account lifecycle changes (like deleting an account or changing a phone number). The given
/// task runs once locks for all given identifiers have been acquired, and the locks are released as soon as the task
/// completes by any means.
///
/// @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 {
@@ -92,4 +90,29 @@ public class AccountLockManager {
}, lockAcquisitionExecutor).join();
}
}
/// Acquires a distributed, pessimistic lock for a single account that already exists. The given task
/// runs once a lock for the identifier has been acquired, and the lock is released as soon as
/// the task completes by any means.
///
/// If the account has a phone number, the lock will be based on its phone-number identifier, and
/// will therefore guard against collisions with other operations that lock the same phone number
/// identifier; if it does not, the lock will be based on its account identifier only. This is
/// safe because accounts without phone numbers can never get phone numbers and accounts with
/// them can never lose them, so we will never see two operations targeting the same account but
/// locking with different identifier types.
///
/// @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.getPhoneNumberIdentifierOptional().orElse(account.getAccountIdentifier())), task, lockAcquisitionExecutor);
}
}
@@ -26,7 +26,6 @@ import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
@@ -37,9 +36,9 @@ import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.apache.commons.lang3.StringUtils;
import org.signal.libsignal.zkgroup.backups.BackupCredentialType;
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialPresentation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.util.AsyncTimerUtil;
import org.whispersystems.textsecuregcm.util.AttributeValues;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
@@ -169,6 +168,7 @@ public class Accounts {
private final DynamoDbClient dynamoDbClient;
private final DynamoDbAsyncClient dynamoDbAsyncClient;
private final RedeemedReceiptsManager redeemedReceiptsManager;
private final String phoneNumberConstraintTableName;
private final String phoneNumberIdentifierConstraintTableName;
@@ -181,6 +181,7 @@ public class Accounts {
final Clock clock,
final DynamoDbClient dynamoDbClient,
final DynamoDbAsyncClient dynamoDbAsyncClient,
final RedeemedReceiptsManager redeemedReceiptsManager,
final String accountsTableName,
final String phoneNumberConstraintTableName,
final String phoneNumberIdentifierConstraintTableName,
@@ -191,6 +192,7 @@ public class Accounts {
this.clock = clock;
this.dynamoDbClient = dynamoDbClient;
this.dynamoDbAsyncClient = dynamoDbAsyncClient;
this.redeemedReceiptsManager = redeemedReceiptsManager;
this.phoneNumberConstraintTableName = phoneNumberConstraintTableName;
this.phoneNumberIdentifierConstraintTableName = phoneNumberIdentifierConstraintTableName;
this.accountsTableName = accountsTableName;
@@ -215,24 +217,27 @@ public class Accounts {
boolean create(final Account account, final List<TransactWriteItem> additionalWriteItems)
throws AccountAlreadyExistsException {
if (account.getNumberOptional().isEmpty() || account.getPhoneNumberIdentifierOptional().isEmpty()) {
throw new IllegalArgumentException("Phone number and phone number identifier must be set");
}
final Timer.Sample sample = Timer.start();
try {
final AttributeValue uuidAttr = AttributeValues.fromUUID(account.getUuid());
final AttributeValue numberAttr = AttributeValues.fromString(account.getNumber());
final AttributeValue pniUuidAttr = AttributeValues.fromUUID(account.getPhoneNumberIdentifier());
final AttributeValue uuidAttr = AttributeValues.fromUUID(account.getAccountIdentifier());
final AttributeValue numberAttr = AttributeValues.fromString(account.getNumberOptional().get());
final AttributeValue pniUuidAttr = AttributeValues.fromUUID(account.getPhoneNumberIdentifierOptional().get());
final TransactWriteItem phoneNumberConstraintPut = buildConstraintTablePutIfAbsent(
phoneNumberConstraintTableName, uuidAttr, ATTR_ACCOUNT_E164, numberAttr);
final TransactWriteItem phoneNumberIdentifierConstraintPut = buildConstraintTablePutIfAbsent(
phoneNumberIdentifierConstraintTableName, uuidAttr, ATTR_PNI_UUID, pniUuidAttr);
final TransactWriteItem accountPut = buildAccountPut(account, uuidAttr, numberAttr, pniUuidAttr);
final TransactWriteItem accountPut = buildAccountPut(account, uuidAttr, Optional.of(numberAttr), Optional.of(pniUuidAttr));
// Clear any "recently deleted account" record for this number since, if it existed, we've used its old ACI for
// the newly-created account.
final TransactWriteItem deletedAccountDelete = buildRemoveDeletedAccount(account.getPhoneNumberIdentifier());
final TransactWriteItem deletedAccountDelete = buildRemoveDeletedAccount(account.getPhoneNumberIdentifierOptional().get());
final Collection<TransactWriteItem> writeItems = new ArrayList<>(
List.of(phoneNumberConstraintPut, phoneNumberIdentifierConstraintPut, accountPut, deletedAccountDelete));
@@ -293,6 +298,74 @@ public class Accounts {
return true;
}
boolean create(final Account account,
final ReceiptCredentialPresentation receiptCredentialPresentation,
final byte[] accountRecoveryPasswordInRequest,
final List<TransactWriteItem> additionalWriteItems)
throws AccountAlreadyExistsException, ReceiptAlreadyRedeemedException {
final Timer.Sample sample = Timer.start();
try {
final AttributeValue uuidAttr = AttributeValues.fromUUID(account.getAccountIdentifier());
final TransactWriteItem signalLoginReceiptConstraintPut =
redeemedReceiptsManager.buildTransactWriteItemForReceipt(
receiptCredentialPresentation.getReceiptSerial(),
Instant.ofEpochSecond(receiptCredentialPresentation.getReceiptExpirationTime()),
receiptCredentialPresentation.getReceiptLevel(),
account.getAccountIdentifier());
final TransactWriteItem accountPut = buildAccountPut(account, uuidAttr, Optional.empty(), Optional.empty());
final Collection<TransactWriteItem> writeItems = new ArrayList<>(
List.of(signalLoginReceiptConstraintPut, accountPut));
writeItems.addAll(additionalWriteItems);
final TransactWriteItemsRequest request = TransactWriteItemsRequest.builder()
.transactItems(writeItems)
.build();
try {
dynamoDbClient.transactWriteItems(request);
} catch (final TransactionCanceledException e) {
final CancellationReason receiptSerialConstraintCancellationReason = e.cancellationReasons().get(0);
if (conditionalCheckFailed(receiptSerialConstraintCancellationReason)) {
final UUID existingAccountUuid = UUIDUtil.fromByteBuffer(receiptSerialConstraintCancellationReason.item()
.get(RedeemedReceiptsManager.KEY_ACCOUNT_UUID).b().asByteBuffer());
final Account existingAccount = getByAccountIdentifier(existingAccountUuid)
// 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().map(arp ->
PhoneNumberRecoveryPasswordsManager.verify(arp, accountRecoveryPasswordInRequest)).orElse(false);
if (!isRetry) {
throw new ReceiptAlreadyRedeemedException();
}
throw new AccountAlreadyExistsException(existingAccount);
}
final CancellationReason accountCancellationReason = e.cancellationReasons().get(1);
if (TRANSACTION_CONFLICT.equals(accountCancellationReason.code())) {
// this should only happen if two clients manage to make concurrent create() calls
throw new ContestedOptimisticLockException();
}
// this shouldn't happen
throw new RuntimeException("could not create account: " + extractCancellationReasonCodes(e));
}
} finally {
sample.stop(CREATE_TIMER);
}
return true;
}
/**
* Copies over any account attributes that should be preserved when a new account reclaims an account identifier.
*
@@ -303,12 +376,13 @@ public class Accounts {
final Account accountToCreate,
final Collection<TransactWriteItem> additionalWriteItems) {
if (!existingAccount.getUuid().equals(accountToCreate.getUuid()) ||
!existingAccount.getPhoneNumberIdentifier().equals(accountToCreate.getPhoneNumberIdentifier())) {
if (!existingAccount.getAccountIdentifier().equals(accountToCreate.getAccountIdentifier()) ||
existingAccount.getNumberOptional().isPresent() != accountToCreate.getNumberOptional().isPresent() ||
!existingAccount.getPhoneNumberIdentifierOptional().equals(accountToCreate.getPhoneNumberIdentifierOptional())) {
log.error("Reclaimed accounts must match. Old account {}:{}:{}, New account {}:{}:{}",
existingAccount.getUuid(), redactPhoneNumber(existingAccount.getNumber()), existingAccount.getPhoneNumberIdentifier(),
accountToCreate.getUuid(), redactPhoneNumber(accountToCreate.getNumber()), accountToCreate.getPhoneNumberIdentifier());
existingAccount.getAccountIdentifier(), existingAccount.getNumberOptional().map(Accounts::redactPhoneNumber), existingAccount.getPhoneNumberIdentifierOptional(),
accountToCreate.getAccountIdentifier(), accountToCreate.getNumberOptional().map(Accounts::redactPhoneNumber), accountToCreate.getPhoneNumberIdentifierOptional());
throw new IllegalArgumentException("reclaimed accounts must match");
}
@@ -326,6 +400,9 @@ public class Accounts {
// Carry over the existing backup voucher to the new account
accountToCreate.setBackupVoucher(existingAccount.getBackupVoucher());
// Carry over any existing badges to the new account
accountToCreate.setBadges(clock, existingAccount.getBadges());
// Carry over the existing ZK credential key to the new account
accountToCreate.setZkCredentialKey(existingAccount.getZkCredentialKey().orElse(null));
accountToCreate.setZkCredentialKeyRotationId(existingAccount.getZkCredentialKeyRotationId());
@@ -360,7 +437,7 @@ public class Accounts {
.tableName(usernamesConstraintTableName)
.item(Map.of(
UsernameTable.KEY_USERNAME_HASH, AttributeValues.fromByteArray(usernameHash),
UsernameTable.ATTR_ACCOUNT_UUID, AttributeValues.fromUUID(accountToCreate.getUuid()),
UsernameTable.ATTR_ACCOUNT_UUID, AttributeValues.fromUUID(accountToCreate.getAccountIdentifier()),
UsernameTable.ATTR_TTL, AttributeValues.fromLong(expirationTime),
UsernameTable.ATTR_CONFIRMED, AttributeValues.fromBool(false),
UsernameTable.ATTR_RECLAIMABLE, AttributeValues.fromBool(true)))
@@ -371,7 +448,7 @@ public class Accounts {
"#uuid", UsernameTable.ATTR_ACCOUNT_UUID))
.expressionAttributeValues(Map.of(
":now", AttributeValues.fromLong(clock.instant().getEpochSecond()),
":uuid", AttributeValues.fromUUID(accountToCreate.getUuid())))
":uuid", AttributeValues.fromUUID(accountToCreate.getAccountIdentifier())))
.returnValuesOnConditionCheckFailure(ReturnValuesOnConditionCheckFailure.ALL_OLD)
.build())
.build());
@@ -379,25 +456,28 @@ public class Accounts {
// Phone number canonicalization means that a user can use a different phone number in the same equivalence class
// to reclaim the account.
if (!existingAccount.getNumber().equals(accountToCreate.getNumber())) {
if (getAlternateForms(existingAccount.getNumber()).contains(accountToCreate.getNumber())) {
final AttributeValue uuidAttr = AttributeValues.fromUUID(existingAccount.getUuid());
final AttributeValue numberAttr = AttributeValues.fromString(accountToCreate.getNumber());
if (!existingAccount.getNumberOptional().equals(accountToCreate.getNumberOptional())
&& existingAccount.getNumberOptional().isPresent()
&& accountToCreate.getNumberOptional().isPresent()) {
final String existingAccountNumber = existingAccount.getNumberOptional().get();
final String accountToCreateNumber = accountToCreate.getNumberOptional().get();
if (getAlternateForms(existingAccountNumber).contains(accountToCreateNumber)) {
final AttributeValue uuidAttr = AttributeValues.fromUUID(existingAccount.getAccountIdentifier());
final AttributeValue numberAttr = AttributeValues.fromString(accountToCreateNumber);
final TransactWriteItem phoneNumberConstraintPut = buildConstraintTablePutIfAbsent(
phoneNumberConstraintTableName, uuidAttr, ATTR_ACCOUNT_E164, numberAttr);
writeItems.add(buildDelete(phoneNumberConstraintTableName, ATTR_ACCOUNT_E164, existingAccount.getNumber()));
writeItems.add(buildDelete(phoneNumberConstraintTableName, ATTR_ACCOUNT_E164, existingAccountNumber));
writeItems.add(phoneNumberConstraintPut);
} else {
log.error("Reclaiming account with a non-equivalent phone number. Old account {}:{}:{}, new account {}:{}:{}",
existingAccount.getUuid(), redactPhoneNumber(existingAccount.getNumber()), existingAccount.getPhoneNumberIdentifier(),
accountToCreate.getUuid(), redactPhoneNumber(accountToCreate.getNumber()), accountToCreate.getPhoneNumberIdentifier());
throw new IllegalArgumentException("reclaimed accounts must have equivalent phone numbers");
throw new IllegalStateException(String.format("Reclaiming account with a non-equivalent phone number. Old account %s:%s:%s, new account %s:%s:%s",
existingAccount.getAccountIdentifier(), redactPhoneNumber(existingAccountNumber), existingAccount.getPhoneNumberIdentifierOptional(),
accountToCreate.getAccountIdentifier(), redactPhoneNumber(accountToCreateNumber), accountToCreate.getPhoneNumberIdentifierOptional()));
}
}
final int updateAccountItemIndex = writeItems.size();
writeItems.add(UpdateAccountSpec.forReclaimedAccount(accountsTableName, accountToCreate, existingAccount.getNumber()).transactItem());
writeItems.add(UpdateAccountSpec.forReclaimedAccount(accountsTableName, accountToCreate, existingAccount.getNumberOptional()).transactItem());
writeItems.addAll(additionalWriteItems);
return dynamoDbAsyncClient.transactWriteItems(TransactWriteItemsRequest.builder().transactItems(writeItems).build())
@@ -410,10 +490,10 @@ public class Accounts {
if (unwrapped instanceof TransactionCanceledException te) {
if (Accounts.conditionalCheckFailed(te.cancellationReasons().get(updateAccountItemIndex))) {
final Map<String, AttributeValue> item = te.cancellationReasons().get(updateAccountItemIndex).item();
final String existingNumber = AttributeValues.getString(item, Accounts.ATTR_ACCOUNT_E164, null);
if (!existingAccount.getNumber().equals(existingNumber)) {
final Optional<String> existingNumber = Optional.ofNullable(AttributeValues.getString(item, Accounts.ATTR_ACCOUNT_E164, null));
if (!existingAccount.getNumberOptional().equals(existingNumber)) {
log.error("Failed to update account due to unexpected existing phone number. Account {}. Expected {}, got {}",
existingAccount.getUuid(), existingAccount.getNumber(), existingNumber);
existingAccount.getAccountIdentifier(), existingAccount.getNumberOptional(), existingNumber);
throw new UnexpectedExistingPhoneNumberException();
}
}
@@ -458,7 +538,7 @@ public class Accounts {
int accountUpdateIndex = -1;
try {
final List<TransactWriteItem> writeItems = new ArrayList<>();
final AttributeValue uuidAttr = AttributeValues.fromUUID(account.getUuid());
final AttributeValue uuidAttr = AttributeValues.fromUUID(account.getAccountIdentifier());
final AttributeValue numberAttr = AttributeValues.fromString(number);
final AttributeValue pniAttr = AttributeValues.fromUUID(phoneNumberIdentifier);
@@ -600,7 +680,7 @@ public class Accounts {
final long expirationTimeSeconds) throws ContestedOptimisticLockException, TtlConflictException, UsernameHashNotAvailableException {
// Use account UUID as a "reservation token" - by providing this, the client proves ownership of the hash
final UUID uuid = updatedAccount.getUuid();
final UUID uuid = updatedAccount.getAccountIdentifier();
final List<TransactWriteItem> writeItems = new ArrayList<>();
@@ -787,7 +867,7 @@ public class Accounts {
writeItems.add(TransactWriteItem.builder().put(Put.builder()
.tableName(usernamesConstraintTableName)
.item(Map.of(
UsernameTable.ATTR_ACCOUNT_UUID, AttributeValues.fromUUID(updatedAccount.getUuid()),
UsernameTable.ATTR_ACCOUNT_UUID, AttributeValues.fromUUID(updatedAccount.getAccountIdentifier()),
UsernameTable.KEY_USERNAME_HASH, AttributeValues.fromByteArray(usernameHash),
UsernameTable.ATTR_CONFIRMED, AttributeValues.fromBool(true)))
// it's not in the constraint table OR it's expired OR it was reserved by us
@@ -799,7 +879,7 @@ public class Accounts {
"#confirmed", UsernameTable.ATTR_CONFIRMED))
.expressionAttributeValues(Map.of(
":now", AttributeValues.fromLong(clock.instant().getEpochSecond()),
":aci", AttributeValues.fromUUID(updatedAccount.getUuid()),
":aci", AttributeValues.fromUUID(updatedAccount.getAccountIdentifier()),
":confirmed", AttributeValues.fromBool(false)))
.returnValuesOnConditionCheckFailure(ReturnValuesOnConditionCheckFailure.ALL_OLD)
.build())
@@ -810,11 +890,11 @@ public class Accounts {
// 2?: Add a temporary hold for the old username to stop others from claiming it
maybeOriginalUsernameHash.ifPresent(originalUsernameHash ->
writeItems.add(holdUsernameTransactItem(updatedAccount.getUuid(), originalUsernameHash, now)));
writeItems.add(holdUsernameTransactItem(updatedAccount.getAccountIdentifier(), originalUsernameHash, now)));
// 3?: Adding that hold may have caused our account to exceed our maximum holds. Release an old hold
holdToRemove.ifPresent(oldHold ->
writeItems.add(releaseHoldIfAllowedTransactItem(updatedAccount.getUuid(), oldHold, now)));
writeItems.add(releaseHoldIfAllowedTransactItem(updatedAccount.getAccountIdentifier(), oldHold, now)));
try {
dynamoDbClient.transactWriteItems(TransactWriteItemsRequest.builder().transactItems(writeItems).build());
@@ -895,10 +975,10 @@ public class Accounts {
items.add(UpdateAccountSpec.forAccount(accountsTableName, updatedAccount).transactItem());
// 1: Un-confirm our username, adding a temporary hold for the old username to stop others from claiming it
items.add(holdUsernameTransactItem(updatedAccount.getUuid(), usernameHash, now));
items.add(holdUsernameTransactItem(updatedAccount.getAccountIdentifier(), usernameHash, now));
// 2?: Adding that hold may have caused our account to exceed our maximum holds. Release an old hold
holdToRemove.ifPresent(oldHold -> items.add(releaseHoldIfAllowedTransactItem(updatedAccount.getUuid(), oldHold, now)));
holdToRemove.ifPresent(oldHold -> items.add(releaseHoldIfAllowedTransactItem(updatedAccount.getAccountIdentifier(), oldHold, now)));
try {
dynamoDbClient.transactWriteItems(TransactWriteItemsRequest.builder().transactItems(items).build());
@@ -992,26 +1072,34 @@ public class Accounts {
static UpdateAccountSpec forReclaimedAccount(
final String accountTableName,
final Account account,
final String expectedExistingE164) {
final Optional<String> maybeExpectedExistingE164) {
final UpdateAccountSpec base = forAccount(accountTableName, account);
final Map<String, String> attrNames = new HashMap<>(base.attrNames());
final Map<String, AttributeValue> attrValues = new HashMap<>(base.attrValues());
attrValues.put(":number", AttributeValues.fromString(account.getNumber()));
final UpdateExpression updateExpression = base.updateExpression();
final List<String> setClauses = new ArrayList<>(updateExpression.setClauses());
setClauses.add("#number = :number");
final MembershipExpression membershipExpression = MembershipExpression.build(getAlternateForms(expectedExistingE164));
attrValues.putAll(membershipExpression.values());
final String conditionExpression = account.getNumberOptional()
.map(number -> {
attrNames.put("#number", ATTR_ACCOUNT_E164);
attrValues.put(":number", AttributeValues.fromString(number));
setClauses.add("#number = :number");
// Defensive check: we should only update the e164 to another e164 in the same equivalence class
final String conditionExpression = base.conditionExpression() + " AND #number IN %s".formatted(membershipExpression.expression());
final MembershipExpression membershipExpression = maybeExpectedExistingE164
.map(e164 -> MembershipExpression.build(getAlternateForms(e164)))
.orElseThrow(() -> new IllegalArgumentException("E164 must be present on existing account"));
attrValues.putAll(membershipExpression.values());
// Defensive check: if an e164 exists on the account, we should only update it to another e164 in the same equivalence class
return base.conditionExpression() + " AND #number IN %s".formatted(membershipExpression.expression());
})
.orElse(base.conditionExpression());
return new UpdateAccountSpec(
base.tableName(),
base.key(),
base.attrNames(),
attrNames,
attrValues,
new UpdateExpression(setClauses, updateExpression.addClauses(), updateExpression.removeClauses()),
conditionExpression
@@ -1022,7 +1110,6 @@ public class Accounts {
final String accountTableName,
final Account account) {
final Map<String, String> attrNames = new HashMap<>(Map.of(
"#number", ATTR_ACCOUNT_E164,
"#data", ATTR_ACCOUNT_DATA,
"#cds", ATTR_CANONICALLY_DISCOVERABLE,
"#version", ATTR_VERSION));
@@ -1081,11 +1168,11 @@ public class Accounts {
return new UpdateAccountSpec(
accountTableName,
Map.of(KEY_ACCOUNT_UUID, AttributeValues.fromUUID(account.getUuid())),
Map.of(KEY_ACCOUNT_UUID, AttributeValues.fromUUID(account.getAccountIdentifier())),
attrNames,
attrValues,
new UpdateExpression(setClauses, addClauses, removeClauses),
"attribute_exists(#number) AND #version = :version");
"#version = :version");
}
}
@@ -1103,7 +1190,7 @@ public class Accounts {
} catch (final ConditionalCheckFailedException e) {
// the exception doesn't give details about which condition failed,
// but we can infer it was an optimistic locking failure if the UUID is known
if (getByAccountIdentifier(account.getUuid()).isPresent()) {
if (getByAccountIdentifier(account.getAccountIdentifier()).isPresent()) {
throw new ContestedOptimisticLockException();
} else {
throw e;
@@ -1242,7 +1329,7 @@ public class Accounts {
return TransactWriteItem.builder()
.delete(Delete.builder()
.tableName(accountsTableName)
.key(Map.of(KEY_ACCOUNT_UUID, AttributeValues.fromUUID(account.getUuid())))
.key(Map.of(KEY_ACCOUNT_UUID, AttributeValues.fromUUID(account.getAccountIdentifier())))
.conditionExpression("#version = :version")
.expressionAttributeNames(Map.of("#version", ATTR_VERSION))
.expressionAttributeValues(Map.of(":version", AttributeValues.fromInt(account.getVersion())))
@@ -1307,12 +1394,17 @@ public class Accounts {
account = maybeAccount.get();
}
final List<TransactWriteItem> transactWriteItems = new ArrayList<>(List.of(
buildConditionalDeleteAccount(account),
buildDelete(phoneNumberConstraintTableName, ATTR_ACCOUNT_E164, account.getNumber()),
buildDelete(phoneNumberIdentifierConstraintTableName, ATTR_PNI_UUID, account.getPhoneNumberIdentifier()),
buildPutDeletedAccount(uuid, account.getPhoneNumberIdentifier())
));
final List<TransactWriteItem> transactWriteItems = new ArrayList<>();
transactWriteItems.add(buildConditionalDeleteAccount(account));
account.getNumberOptional().ifPresent(e164 -> transactWriteItems.add(
buildDelete(phoneNumberConstraintTableName, ATTR_ACCOUNT_E164, e164)));
account.getPhoneNumberIdentifierOptional().ifPresent(pni -> {
transactWriteItems.add(buildDelete(phoneNumberIdentifierConstraintTableName, ATTR_PNI_UUID, pni));
transactWriteItems.add(buildPutDeletedAccount(uuid, pni));
});
account.getUsernameHash().ifPresent(usernameHash -> transactWriteItems.add(
buildDelete(usernamesConstraintTableName, UsernameTable.KEY_USERNAME_HASH, usernameHash)));
@@ -1486,13 +1578,14 @@ public class Accounts {
private TransactWriteItem buildAccountPut(
final Account account,
final AttributeValue uuidAttr,
final AttributeValue numberAttr,
final AttributeValue pniUuidAttr) {
final Optional<AttributeValue> maybeNumberAttr,
final Optional<AttributeValue> maybePniUuidAttr) {
if (maybeNumberAttr.isPresent() != maybePniUuidAttr.isPresent()) {
throw new IllegalArgumentException("Number and PNI attribute values must both be provided together or not at all");
}
final Map<String, AttributeValue> item = new HashMap<>(Map.of(
KEY_ACCOUNT_UUID, uuidAttr,
ATTR_ACCOUNT_E164, numberAttr,
ATTR_PNI_UUID, pniUuidAttr,
ATTR_ACCOUNT_DATA, accountDataAttributeValue(account),
ATTR_VERSION, AttributeValues.fromInt(account.getVersion()),
ATTR_CANONICALLY_DISCOVERABLE, AttributeValues.fromBool(account.isDiscoverableByPhoneNumber())));
@@ -1502,14 +1595,24 @@ public class Accounts {
.map(AttributeValues::fromByteArray)
.ifPresent(uak -> item.put(ATTR_UAK, uak));
return TransactWriteItem.builder()
.put(Put.builder()
.conditionExpression("attribute_not_exists(#pni) OR #pni = :pni")
.expressionAttributeNames(Map.of("#pni", ATTR_PNI_UUID))
.expressionAttributeValues(Map.of(":pni", pniUuidAttr))
final Put put = maybeNumberAttr.map(numberAttr -> {
item.put(ATTR_ACCOUNT_E164, numberAttr);
item.put(ATTR_PNI_UUID, maybePniUuidAttr.get());
return Put.builder()
.tableName(accountsTableName)
.item(item)
.conditionExpression("attribute_not_exists(#pni) OR #pni = :pni")
.expressionAttributeNames(Map.of("#pni", ATTR_PNI_UUID))
.expressionAttributeValues(Map.of(":pni", maybePniUuidAttr.get()))
.build();
})
.orElseGet(() -> Put.builder()
.tableName(accountsTableName)
.item(item)
.build())
.build());
return TransactWriteItem.builder()
.put(put)
.build();
}
@@ -1586,23 +1689,25 @@ public class Accounts {
CompletableFuture<Void> regenerateConstraints(final Account account) {
final List<CompletableFuture<?>> constraintFutures = new ArrayList<>();
constraintFutures.add(writeConstraint(phoneNumberConstraintTableName,
account.getIdentifier(IdentityType.ACI),
ATTR_ACCOUNT_E164,
AttributeValues.fromString(account.getNumber())));
account.getNumberOptional().ifPresent(phoneNumber ->
constraintFutures.add(writeConstraint(phoneNumberConstraintTableName,
account.getAccountIdentifier(),
ATTR_ACCOUNT_E164,
AttributeValues.fromString(phoneNumber))));
constraintFutures.add(writeConstraint(phoneNumberIdentifierConstraintTableName,
account.getIdentifier(IdentityType.ACI),
ATTR_PNI_UUID,
AttributeValues.fromUUID(account.getPhoneNumberIdentifier())));
account.getPhoneNumberIdentifierOptional().ifPresent(phoneNumberIdentifier ->
constraintFutures.add(writeConstraint(phoneNumberIdentifierConstraintTableName,
account.getAccountIdentifier(),
ATTR_PNI_UUID,
AttributeValues.fromUUID(phoneNumberIdentifier))));
account.getUsernameHash().ifPresent(usernameHash ->
constraintFutures.add(writeUsernameConstraint(account.getIdentifier(IdentityType.ACI),
constraintFutures.add(writeUsernameConstraint(account.getAccountIdentifier(),
usernameHash,
Optional.empty())));
account.getUsernameHolds().forEach(usernameHold ->
constraintFutures.add(writeUsernameConstraint(account.getIdentifier(IdentityType.ACI),
constraintFutures.add(writeUsernameConstraint(account.getAccountIdentifier(),
usernameHold.usernameHash(),
Optional.of(Instant.ofEpochSecond(usernameHold.expirationSecs())))));
@@ -1656,7 +1761,6 @@ public class Accounts {
@Nonnull
static Account fromItem(final Map<String, AttributeValue> item) {
if (!item.containsKey(ATTR_ACCOUNT_DATA)
|| !item.containsKey(ATTR_ACCOUNT_E164)
|| !item.containsKey(KEY_ACCOUNT_UUID)
|| !item.containsKey(ATTR_CANONICALLY_DISCOVERABLE)) {
throw new RuntimeException("item missing values");
@@ -1667,21 +1771,19 @@ public class Accounts {
final UUID accountIdentifier = UUIDUtil.fromByteBuffer(item.get(KEY_ACCOUNT_UUID).b().asByteBuffer());
final UUID phoneNumberIdentifierFromAttribute = AttributeValues.getUUID(item, ATTR_PNI_UUID, null);
if (account.getPhoneNumberIdentifier() == null || phoneNumberIdentifierFromAttribute == null ||
!Objects.equals(account.getPhoneNumberIdentifier(), phoneNumberIdentifierFromAttribute)) {
log.warn("Missing or mismatched PNIs for account {}. From JSON: {}; from attribute: {}",
accountIdentifier, account.getPhoneNumberIdentifier(), phoneNumberIdentifierFromAttribute);
if (!account.getPhoneNumberIdentifierOptional().equals(Optional.ofNullable(phoneNumberIdentifierFromAttribute))) {
log.warn("Mismatched PNIs for account {}. From JSON: {}; from attribute: {}",
accountIdentifier, account.getPhoneNumberIdentifierOptional(), phoneNumberIdentifierFromAttribute);
}
final String attributeNumber = item.get(ATTR_ACCOUNT_E164).s();
if (account.getNumber() == null || !account.getNumber().equals(attributeNumber)) {
log.error("Missing or mismatched phone numbers for account {}. From JSON: {}; from attribute: {}",
accountIdentifier, account.getNumber(), attributeNumber);
final String attributeNumber = AttributeValues.getString(item, ATTR_ACCOUNT_E164, null);
if (!account.getNumberOptional().equals(Optional.ofNullable(attributeNumber))) {
log.error("Mismatched phone numbers for account {}. From JSON: {}; from attribute: {}",
accountIdentifier, account.getNumberOptional(), attributeNumber);
}
account.setNumber(attributeNumber, phoneNumberIdentifierFromAttribute);
account.setUuid(accountIdentifier);
account.setAccountIdentifier(accountIdentifier);
account.setUsernameHash(AttributeValues.getByteArray(item, ATTR_USERNAME_HASH, null));
account.setUsernameLinkHandle(AttributeValues.getUUID(item, ATTR_USERNAME_LINK_UUID, null));
account.setVersion(Integer.parseInt(item.get(ATTR_VERSION).n()));
@@ -28,6 +28,7 @@ import java.security.InvalidKeyException;
import java.security.Key;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
@@ -36,6 +37,7 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
@@ -55,12 +57,12 @@ import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.lang3.StringUtils;
import org.signal.libsignal.protocol.IdentityKey;
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialPresentation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestManager;
@@ -87,6 +89,7 @@ import org.whispersystems.textsecuregcm.util.ResilienceUtil;
import org.whispersystems.textsecuregcm.util.SystemMapper;
import org.whispersystems.textsecuregcm.util.ThrowingConsumer;
import org.whispersystems.textsecuregcm.util.Util;
import org.whispersystems.textsecuregcm.util.logging.ImpossibleEvents;
import reactor.core.publisher.Flux;
import reactor.core.scheduler.Scheduler;
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem;
@@ -94,7 +97,6 @@ import software.amazon.awssdk.services.dynamodb.model.TransactionCanceledExcepti
public class AccountsManager extends RedisPubSubAdapter<String, String> implements Managed {
private static final Timer createTimer = Metrics.timer(name(AccountsManager.class, "create"));
private static final Timer updateTimer = Metrics.timer(name(AccountsManager.class, "update"));
private static final Timer getByNumberTimer = Metrics.timer(name(AccountsManager.class, "getByNumber"));
private static final Timer getByUsernameHashTimer = Metrics.timer(name(AccountsManager.class, "getByUsernameHash"));
@@ -113,6 +115,8 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
private static final String DELETION_REASON_TAG_NAME = "reason";
private static final String REGISTRATION_ID_BASED_TRANSFER_ARCHIVE_KEY_COUNTER_NAME =
name(AccountsManager.class, "registrationIdRedisKeyCounter");
private static final String CREATE_TIMER_NAME = name(AccountsManager.class, "create");
private static final String HAS_NUMBER_TAG_NAME = "hasNumber";
private static final String RETRY_NAME = ResilienceUtil.name(AccountsManager.class);
@@ -132,7 +136,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
private final SecureStorageClient secureStorageClient;
private final SecureValueRecoveryClient secureValueRecovery2Client;
private final DisconnectionRequestManager disconnectionRequestManager;
private final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager;
private final PhoneNumberRecoveryPasswordsManager phoneNumberRecoveryPasswordsManager;
private final Executor accountLockExecutor;
private final ScheduledExecutorService messagesPollExecutor;
private final ScheduledExecutorService retryExecutor;
@@ -181,6 +185,10 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
private static final int MAX_UPDATE_ATTEMPTS = 10;
private static final SecureRandom SECURE_RANDOM = new SecureRandom();
private static final int AUTH_CREDENTIAL_SALT_SIZE = 16;
@VisibleForTesting
static final Duration LINK_DEVICE_TOKEN_EXPIRATION_DURATION = Duration.ofMinutes(10);
@@ -214,7 +222,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
final SecureStorageClient secureStorageClient,
final SecureValueRecoveryClient secureValueRecovery2Client,
final DisconnectionRequestManager disconnectionRequestManager,
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager,
final PhoneNumberRecoveryPasswordsManager phoneNumberRecoveryPasswordsManager,
final Executor accountLockExecutor,
final ScheduledExecutorService messagesPollExecutor, final ScheduledExecutorService retryExecutor,
final Clock clock,
@@ -231,7 +239,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
this.secureStorageClient = secureStorageClient;
this.secureValueRecovery2Client = secureValueRecovery2Client;
this.disconnectionRequestManager = disconnectionRequestManager;
this.registrationRecoveryPasswordsManager = requireNonNull(registrationRecoveryPasswordsManager);
this.phoneNumberRecoveryPasswordsManager = requireNonNull(phoneNumberRecoveryPasswordsManager);
this.accountLockExecutor = accountLockExecutor;
this.messagesPollExecutor = messagesPollExecutor;
this.retryExecutor = retryExecutor;
@@ -285,20 +293,69 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
});
}
/// Create an account without a phone number.
///
/// @param accountAttributes the account-level attributes to set on the account
/// @param aciIdentityKey the ACI identity key to associate with the account
/// @param receiptCredentialPresentation the receipt credential presentation of proof of payment for a Signal Login
/// @param primaryDeviceSpec the attributes to set on the account's primary device
/// @param userAgent the user agent of the client requesting to create an account
///
/// @return the created account
public Account create(final AccountAttributes accountAttributes,
final IdentityKey aciIdentityKey,
final ReceiptCredentialPresentation receiptCredentialPresentation,
final DeviceSpec primaryDeviceSpec,
@Nullable final String userAgent) throws ReceiptAlreadyRedeemedException {
accountAttributes.recoveryPassword().filter(b -> b.length > 0)
.orElseThrow(
() -> new IllegalArgumentException("recovery password is required for accounts without phone numbers"));
// This salt is required for generating PNI-based auth credentials (e.g. group credentials) for accounts without a number
final byte[] authCredentialSalt = new byte[AUTH_CREDENTIAL_SALT_SIZE];
SECURE_RANDOM.nextBytes(authCredentialSalt);
// We ignore this property on accounts without a number anyway, but ensure that it is false for consistency
accountAttributes.setDiscoverableByPhoneNumber(false);
final Timer.Sample sample = Timer.start();
try {
return create(Optional.empty(), Optional.empty(), Optional.of(receiptCredentialPresentation), Optional.of(authCredentialSalt), accountAttributes, aciIdentityKey, Optional.empty(), primaryDeviceSpec, userAgent);
} catch (final RuntimeException e) {
logger.error("Unexpected exception while creating account", e);
throw e;
} finally {
sample.stop(Metrics.timer(CREATE_TIMER_NAME, HAS_NUMBER_TAG_NAME, "false"));
}
}
/// Create an account with a phone number.
///
/// @param number the e164-formatted phone number to set on the account
/// @param accountAttributes the account-level attributes to set on the account
/// @param aciIdentityKey the ACI identity key to associate with the account
/// @param pniIdentityKey the PNI identity key to associate with the account
/// @param primaryDeviceSpec the attributes to set on the account's primary device
/// @param userAgent the user agent of the client requesting to create an account
///
/// @return the created account
public Account create(final String number,
final AccountAttributes accountAttributes,
final List<AccountBadge> accountBadges,
final IdentityKey aciIdentityKey,
final IdentityKey pniIdentityKey,
final DeviceSpec primaryDeviceSpec,
@Nullable final String userAgent) throws InterruptedException {
@Nullable final String userAgent) {
final UUID pni = phoneNumberIdentifiers.getPhoneNumberIdentifier(number).join();
return createTimer.record(() -> {
return Metrics.timer(CREATE_TIMER_NAME, HAS_NUMBER_TAG_NAME, "true").record(() -> {
try {
return accountLockManager.withLock(Set.of(pni),
() -> create(number, pni, accountAttributes, accountBadges, aciIdentityKey, pniIdentityKey, primaryDeviceSpec, userAgent), accountLockExecutor);
() -> create(Optional.of(number), Optional.of(pni), Optional.empty(), Optional.empty(), accountAttributes, aciIdentityKey, Optional.of(pniIdentityKey), primaryDeviceSpec, userAgent), accountLockExecutor);
} catch (final ReceiptAlreadyRedeemedException e) {
throw new AssertionError("ReceiptAlreadyRedeemedException must never be thrown for accounts with numbers");
} catch (final RuntimeException e) {
logger.error("Unexpected exception while creating account", e);
throw e;
@@ -306,31 +363,41 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
});
}
private Account create(final String number,
final UUID pni,
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
private Account create(final Optional<String> maybeNumber,
final Optional<UUID> maybePni,
final Optional<ReceiptCredentialPresentation> maybeReceiptCredentialPresentation,
final Optional<byte[]> maybeAuthCredentialSalt,
final AccountAttributes accountAttributes,
final List<AccountBadge> accountBadges,
final IdentityKey aciIdentityKey,
final IdentityKey pniIdentityKey,
final Optional<IdentityKey> maybePniIdentityKey,
final DeviceSpec primaryDeviceSpec,
@Nullable final String userAgent) {
@Nullable final String userAgent) throws ReceiptAlreadyRedeemedException {
assert maybeNumber.isPresent() ^ maybeReceiptCredentialPresentation.isPresent();
final Account account = new Account();
final Optional<UUID> maybeRecentlyDeletedAccountIdentifier =
accounts.findRecentlyDeletedAccountIdentifier(pni);
maybePni.flatMap(accounts::findRecentlyDeletedAccountIdentifier);
maybeNumber.ifPresent(number -> {
account.setNumber(number, maybePni.orElseThrow(() -> new IllegalArgumentException("PNI must be provided if the account has a number")));
account.setPhoneNumberIdentityKey(maybePniIdentityKey.orElseThrow(() -> new IllegalArgumentException("PNI identity key must be provided if the account has a number")));
account.setRegistrationLockFromAttributes(accountAttributes);
});
maybeAuthCredentialSalt.ifPresent(account::setAuthCredentialSalt);
// Reuse the ACI from any recently-deleted account with this number to cover cases where somebody is
// re-registering.
account.setUuid(maybeRecentlyDeletedAccountIdentifier.orElseGet(UUID::randomUUID));
account.setNumber(number, pni);
account.setAccountIdentifier(maybeRecentlyDeletedAccountIdentifier.orElseGet(UUID::randomUUID));
account.setIdentityKey(aciIdentityKey);
account.setPhoneNumberIdentityKey(pniIdentityKey);
account.addDevice(primaryDeviceSpec.toDevice(Device.PRIMARY_ID, clock, aciIdentityKey));
account.setRegistrationLockFromAttributes(accountAttributes);
account.setUnidentifiedAccessKey(accountAttributes.getUnidentifiedAccessKey());
account.setUnrestrictedUnidentifiedAccess(accountAttributes.isUnrestrictedUnidentifiedAccess());
account.setDiscoverableByPhoneNumber(accountAttributes.isDiscoverableByPhoneNumber());
account.setBadges(clock, accountBadges);
accountAttributes.recoveryPassword().ifPresent(account::setAccountRecoveryPassword);
String accountCreationType = maybeRecentlyDeletedAccountIdentifier.isPresent() ? "recently-deleted" : "new";
@@ -347,13 +414,27 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
String previousPushTokenType = null;
try {
accounts.create(account, keysManager.buildWriteItemsForNewDevice(account.getIdentifier(IdentityType.ACI),
account.getIdentifier(IdentityType.PNI),
final List<TransactWriteItem> additionalWriteItems = new ArrayList<>(keysManager.buildWriteItemsForNewDevice(account.getAccountIdentifier(),
account.getPhoneNumberIdentifierOptional(),
Device.PRIMARY_ID,
primaryDeviceSpec.aciSignedPreKey(),
primaryDeviceSpec.pniSignedPreKey(),
primaryDeviceSpec.aciPqLastResortPreKey(),
primaryDeviceSpec.pniPqLastResortPreKey()));
primaryDeviceSpec.aciInfo().signedPreKey(),
primaryDeviceSpec.pniInfo().map(DeviceIdentityInfo::signedPreKey),
primaryDeviceSpec.aciInfo().pqLastResortPreKey(),
primaryDeviceSpec.pniInfo().map(DeviceIdentityInfo::pqLastResortPreKey)));
maybePni.ifPresent(phoneNumberIdentifier ->
accountAttributes.recoveryPassword().ifPresent(phoneNumberRecoveryPassword ->
additionalWriteItems.add(phoneNumberRecoveryPasswordsManager.buildTransactWriteItemForStorePassword(phoneNumberIdentifier, phoneNumberRecoveryPassword))));
if (maybeNumber.isPresent()) {
accounts.create(account, additionalWriteItems);
} else {
assert accountAttributes.recoveryPassword().isPresent();
accounts.create(account,
maybeReceiptCredentialPresentation.get(),
accountAttributes.recoveryPassword().get(),
additionalWriteItems);
}
} catch (final AccountAlreadyExistsException e) {
accountCreationType = "re-registration";
@@ -365,30 +446,34 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
previousPushTokenType = "none";
}
final UUID aci = e.getExistingAccount().getIdentifier(IdentityType.ACI);
account.setUuid(aci);
final UUID aci = e.getExistingAccount().getAccountIdentifier();
account.setAccountIdentifier(aci);
final List<TransactWriteItem> additionalWriteItems = Stream.concat(
keysManager.buildWriteItemsForNewDevice(account.getIdentifier(IdentityType.ACI),
account.getIdentifier(IdentityType.PNI),
Device.PRIMARY_ID,
primaryDeviceSpec.aciSignedPreKey(),
primaryDeviceSpec.pniSignedPreKey(),
primaryDeviceSpec.aciPqLastResortPreKey(),
primaryDeviceSpec.pniPqLastResortPreKey()).stream(),
e.getExistingAccount().getDevices()
.stream()
.map(Device::getId)
// No need to clear the keys for the primary device since we'll just overwrite them in the same
// transaction anyhow
.filter(existingDeviceId -> existingDeviceId != Device.PRIMARY_ID)
.flatMap(existingDeviceId ->
keysManager.buildWriteItemsForRemovedDevice(aci, pni, existingDeviceId).stream()))
.toList();
final List<TransactWriteItem> additionalWriteItems = new ArrayList<>(keysManager.buildWriteItemsForNewDevice(account.getAccountIdentifier(),
account.getPhoneNumberIdentifierOptional(),
Device.PRIMARY_ID,
primaryDeviceSpec.aciInfo().signedPreKey(),
primaryDeviceSpec.pniInfo().map(DeviceIdentityInfo::signedPreKey),
primaryDeviceSpec.aciInfo().pqLastResortPreKey(),
primaryDeviceSpec.pniInfo().map(DeviceIdentityInfo::pqLastResortPreKey)));
e.getExistingAccount().getDevices()
.stream()
.map(Device::getId)
// No need to clear the keys for the primary device since we'll just overwrite them in the same
// transaction anyhow
.filter(existingDeviceId -> existingDeviceId != Device.PRIMARY_ID)
.map(existingDeviceId ->
keysManager.buildWriteItemsForRemovedDevice(aci, account.getPhoneNumberIdentifierOptional(), existingDeviceId))
.forEach(additionalWriteItems::addAll);
maybePni.ifPresent(phoneNumberIdentifier ->
accountAttributes.recoveryPassword().ifPresent(phoneNumberRecoveryPassword ->
additionalWriteItems.add(phoneNumberRecoveryPasswordsManager.buildTransactWriteItemForStorePassword(phoneNumberIdentifier, phoneNumberRecoveryPassword))));
CompletableFuture.allOf(
keysManager.deleteSingleUsePreKeys(aci),
keysManager.deleteSingleUsePreKeys(pni),
account.getPhoneNumberIdentifierOptional().map(keysManager::deleteSingleUsePreKeys).orElse(CompletableFuture.completedFuture(null)),
messagesManager.clear(aci),
profilesManager.deleteAll(aci, false))
.thenCompose(ignored -> disconnectionRequestManager.requestDisconnection(e.getExistingAccount()))
@@ -402,7 +487,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
// We exclude the primary device's repeated-use keys from deletion because new keys were provided as
// part of the account creation process, and we don't want to delete the keys that just got added.
return CompletableFuture.allOf(keysManager.deleteSingleUsePreKeys(aci),
keysManager.deleteSingleUsePreKeys(pni),
account.getPhoneNumberIdentifierOptional().map(keysManager::deleteSingleUsePreKeys).orElse(CompletableFuture.completedFuture(null)),
messagesManager.clear(aci),
profilesManager.deleteAll(aci, false));
})
@@ -411,12 +496,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
redisSet(account);
final boolean rrpCreated = accountAttributes.recoveryPassword().map(registrationRecoveryPassword ->
registrationRecoveryPasswordsManager
.store(account.getIdentifier(IdentityType.PNI), registrationRecoveryPassword))
.orElse(false);
changeNumberWaitingPeriodManager.handleAccountCreated(account.getUuid(), clock.instant());
changeNumberWaitingPeriodManager.handleAccountCreated(account.getAccountIdentifier(), clock.instant());
Tags tags = Tags.of(UserAgentTagUtil.getPlatformTag(userAgent),
Tag.of("type", accountCreationType),
@@ -429,9 +509,6 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
if (StringUtils.isNotBlank(previousPushTokenType)) {
tags = tags.and(Tag.of("previousPushTokenType", previousPushTokenType));
}
if (accountAttributes.recoveryPassword().isPresent()) {
tags = tags.and(Tag.of("recoveryPasswordOutcome", rrpCreated ? "created" : "updated"));
}
Metrics.counter(CREATE_COUNTER_NAME, tags).increment();
return account;
}
@@ -439,11 +516,10 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
public Pair<Account, Device> addDevice(final UUID accountIdentifier, final DeviceSpec deviceSpec, final String linkDeviceToken)
throws LinkDeviceTokenAlreadyUsedException {
final UUID phoneNumberIdentifier = accounts.getByAccountIdentifier(accountIdentifier)
.map(account -> account.getIdentifier(IdentityType.PNI))
final Account account = accounts.getByAccountIdentifier(accountIdentifier)
.orElseThrow(() -> new IllegalArgumentException("Account not found: " + accountIdentifier));
return accountLockManager.withLock(Set.of(phoneNumberIdentifier),
return accountLockManager.withSingleAccountLock(account,
() -> addDevice(accountIdentifier, deviceSpec, linkDeviceToken, MAX_UPDATE_ATTEMPTS),
accountLockExecutor);
}
@@ -455,22 +531,25 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
final byte nextDeviceId = account.getNextDeviceId();
CompletableFuture.allOf(
keysManager.deleteSingleUsePreKeys(account.getUuid(), nextDeviceId),
keysManager.deleteSingleUsePreKeys(account.getPhoneNumberIdentifier(), nextDeviceId),
messagesManager.clear(account.getUuid(), nextDeviceId))
CompletableFuture
.allOf(
keysManager.deleteSingleUsePreKeys(account.getAccountIdentifier(), nextDeviceId),
account.getPhoneNumberIdentifierOptional()
.map(pni -> keysManager.deleteSingleUsePreKeys(pni, nextDeviceId))
.orElse(CompletableFuture.completedFuture(null)),
messagesManager.clear(account.getAccountIdentifier(), nextDeviceId))
.join();
account.addDevice(deviceSpec.toDevice(nextDeviceId, clock, account.getIdentityKey(IdentityType.ACI)));
account.addDevice(deviceSpec.toDevice(nextDeviceId, clock, account.getAccountIdentityKey()));
final List<TransactWriteItem> additionalWriteItems = new ArrayList<>(keysManager.buildWriteItemsForNewDevice(
account.getIdentifier(IdentityType.ACI),
account.getIdentifier(IdentityType.PNI),
account.getAccountIdentifier(),
account.getPhoneNumberIdentifierOptional(),
nextDeviceId,
deviceSpec.aciSignedPreKey(),
deviceSpec.pniSignedPreKey(),
deviceSpec.aciPqLastResortPreKey(),
deviceSpec.pniPqLastResortPreKey()));
deviceSpec.aciInfo().signedPreKey(),
deviceSpec.pniInfo().map(DeviceIdentityInfo::signedPreKey),
deviceSpec.aciInfo().pqLastResortPreKey(),
deviceSpec.pniInfo().map(DeviceIdentityInfo::pqLastResortPreKey)));
additionalWriteItems.add(accounts.buildTransactWriteItemForLinkDevice(linkDeviceToken, LINK_DEVICE_TOKEN_EXPIRATION_DURATION));
@@ -635,11 +714,10 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
}
// Always fetch a fresh, non-cached copy of the account before making modifications
final UUID phoneNumberIdentifier = accounts.getByAccountIdentifier(accountIdentifier)
.map(account -> account.getIdentifier(IdentityType.PNI))
final Account account = accounts.getByAccountIdentifier(accountIdentifier)
.orElseThrow(() -> new IllegalArgumentException("Account not found: " + accountIdentifier));
return accountLockManager.withLock(Set.of(phoneNumberIdentifier),
return accountLockManager.withSingleAccountLock(account,
() -> removeDevice(accountIdentifier, deviceId, MAX_UPDATE_ATTEMPTS),
accountLockExecutor);
}
@@ -649,18 +727,20 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
.orElseThrow(ContestedOptimisticLockException::new);
CompletableFuture.allOf(
keysManager.deleteSingleUsePreKeys(account.getUuid(), deviceId),
messagesManager.clear(account.getUuid(), deviceId))
keysManager.deleteSingleUsePreKeys(account.getAccountIdentifier(), deviceId),
account.getPhoneNumberIdentifierOptional()
.map(pni -> keysManager.deleteSingleUsePreKeys(pni, deviceId))
.orElse(CompletableFuture.completedFuture(null)),
messagesManager.clear(account.getAccountIdentifier(), deviceId))
.join();
account.removeDevice(deviceId);
final List<TransactWriteItem> additionalWriteItems = new ArrayList<>(
keysManager.buildWriteItemsForRemovedDevice(
account.getIdentifier(IdentityType.ACI),
account.getIdentifier(IdentityType.PNI),
account.getAccountIdentifier(),
account.getPhoneNumberIdentifierOptional(),
deviceId));
try {
accounts.updateTransactionally(account, additionalWriteItems);
@@ -668,8 +748,11 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
// Ensure any messages/single-use pre-keys that came in while we were working are also removed
CompletableFuture.allOf(
keysManager.deleteSingleUsePreKeys(account.getUuid(), deviceId),
messagesManager.clear(account.getUuid(), deviceId))
keysManager.deleteSingleUsePreKeys(account.getAccountIdentifier(), deviceId),
account.getPhoneNumberIdentifierOptional()
.map(pni -> keysManager.deleteSingleUsePreKeys(pni, deviceId))
.orElse(CompletableFuture.completedFuture(null)),
messagesManager.clear(account.getAccountIdentifier(), deviceId))
.join();
disconnectionRequestManager.requestDisconnection(accountIdentifier, List.of(deviceId));
@@ -695,10 +778,13 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
final Account account = accounts.getByAccountIdentifier(accountIdentifier)
.orElseThrow(() -> new IllegalArgumentException("Account not found: " + accountIdentifier));
final UUID originalPhoneNumberIdentifier = account.getPhoneNumberIdentifierOptional()
.orElseThrow(() -> new IllegalArgumentException("Cannot change phone number for accounts without phone numbers"));
final UUID targetPhoneNumberIdentifier = phoneNumberIdentifiers.getPhoneNumberIdentifier(targetNumber).join();
try {
return accountLockManager.withLock(new HashSet<>(List.of(account.getPhoneNumberIdentifier(), targetPhoneNumberIdentifier)),
return accountLockManager.withLock(new HashSet<>(List.of(originalPhoneNumberIdentifier, targetPhoneNumberIdentifier)),
() -> changeNumber(account, targetNumber, targetPhoneNumberIdentifier, pniIdentityKey, pniSignedPreKeys, pniPqLastResortPreKeys, pniRegistrationIds), accountLockExecutor);
} catch (final RuntimeException e) {
logger.error("Unexpected exception when changing phone number", e);
@@ -714,9 +800,10 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
final Map<Byte, KEMSignedPreKey> pniPqLastResortPreKeys,
final Map<Byte, Integer> pniRegistrationIds) throws MismatchedDevicesException {
validateDevices(account, pniSignedPreKeys, pniPqLastResortPreKeys, pniRegistrationIds);
final UUID originalPhoneNumberIdentifier = account.getPhoneNumberIdentifierOptional()
.orElseThrow(() -> new IllegalArgumentException("Cannot change phone number for accounts without phone numbers"));
final UUID originalPhoneNumberIdentifier = account.getPhoneNumberIdentifier();
validateDevices(account, pniSignedPreKeys, pniPqLastResortPreKeys, pniRegistrationIds);
redisDelete(account);
@@ -738,17 +825,17 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
final Optional<UUID> maybeDisplacedUuid;
if (maybeExistingAccount.isPresent()) {
if (maybeExistingAccount.get().getIdentifier(IdentityType.ACI).equals(account.getIdentifier(IdentityType.ACI))) {
if (maybeExistingAccount.get().getAccountIdentifier().equals(account.getAccountIdentifier())) {
maybeDisplacedUuid = Optional.empty();
} else {
delete(maybeExistingAccount.get());
maybeDisplacedUuid = maybeExistingAccount.map(Account::getUuid);
maybeDisplacedUuid = maybeExistingAccount.map(Account::getAccountIdentifier);
}
} else {
maybeDisplacedUuid = recentlyDeletedAci;
}
final UUID uuid = account.getUuid();
final UUID uuid = account.getAccountIdentifier();
CompletableFuture.allOf(
keysManager.deleteSingleUsePreKeys(targetPhoneNumberIdentifier),
@@ -867,7 +954,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
_ -> true,
a -> reservedUsernameHash.set(
checkAndReserveNextUsernameHash(a, new ArrayDeque<>(requestedUsernameHashes))),
() -> accounts.getByAccountIdentifier(account.getUuid()).orElseThrow(),
() -> accounts.getByAccountIdentifier(account.getAccountIdentifier()).orElseThrow(),
AccountChangeValidator.USERNAME_CHANGE_VALIDATOR);
redisDelete(updatedAccount);
@@ -926,7 +1013,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
final Account updatedAccount = updateWithRetries(
_ -> true,
a -> accounts.confirmUsernameHash(a, reservedUsernameHash, encryptedUsername),
() -> accounts.getByAccountIdentifier(account.getUuid()).orElseThrow(),
() -> accounts.getByAccountIdentifier(account.getAccountIdentifier()).orElseThrow(),
AccountChangeValidator.USERNAME_CHANGE_VALIDATOR);
redisDelete(updatedAccount);
@@ -960,6 +1047,17 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
});
}
public Account update(final UUID accountIdentifier,
final Consumer<Account> updater,
final Collection<TransactWriteItem> additionalWriteItems) {
return update(accountIdentifier, a -> {
updater.accept(a);
// assume that all updaters passed to the public method actually modify the account
return true;
}, additionalWriteItems);
}
/// Using a pessimistic lock, updates the current profile version to `newVersion` if `currentProfileVersion` matches
/// `expectedCurrentVersion`. The caller may provide a supplementary `Consumer<Account>` for additional updates
///
@@ -973,9 +1071,9 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
final Account account = accounts.getByAccountIdentifier(accountIdentifier)
.orElseThrow(() -> new IllegalArgumentException("Account not found: " + accountIdentifier));
return accountLockManager.withLock(Set.of(account.getPhoneNumberIdentifier()), () -> {
return accountLockManager.withSingleAccountLock(account, () -> {
final Account maybeUpdatedAccount = update(accountIdentifier, a -> {
if (!a.getCurrentProfileVersion().orElse(new byte[0]).equals(expectedCurrentVersion)) {
if (!Arrays.equals(a.getCurrentProfileVersion().orElse(new byte[0]), expectedCurrentVersion)) {
return false;
}
@@ -986,7 +1084,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
return true;
});
if (!maybeUpdatedAccount.getCurrentProfileVersion().map(v -> v.equals(newVersion)).orElse(false)) {
if (!maybeUpdatedAccount.getCurrentProfileVersion().map(v -> Arrays.equals(v, newVersion)).orElse(false)) {
throw new WriteConflictException();
}
@@ -1020,12 +1118,27 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
* @param accountIdentifier identifier of account to update
* @param updater must return {@code true} if the account was actually updated
*/
private Account update(UUID accountIdentifier, Function<Account, Boolean> updater) {
private Account update(final UUID accountIdentifier, final Function<Account, Boolean> updater) {
return update(accountIdentifier, updater, Collections.emptyList());
}
/**
* @param accountIdentifier identifier of account to update
* @param updater must return {@code true} if the account was actually updated
* @param additionalWriteItems additional write items to include in a transactional update
*/
private Account update(final UUID accountIdentifier,
final Function<Account, Boolean> updater,
final Collection<TransactWriteItem> additionalWriteItems) {
final ThrowingConsumer<Account, RuntimeException> persister = additionalWriteItems.isEmpty()
? accounts::update
: account -> accounts.updateTransactionally(account, additionalWriteItems);
return updateTimer.record(() -> {
final Account updatedAccount = updateWithRetries(updater,
accounts::update,
persister,
() -> accounts.getByAccountIdentifier(accountIdentifier).orElseThrow(),
AccountChangeValidator.GENERAL_CHANGE_VALIDATOR);
@@ -1181,13 +1294,13 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
final Account account = maybeAccount.get();
try {
accountLockManager.withLock(Set.of(account.getPhoneNumberIdentifier()), () -> {
accountLockManager.withSingleAccountLock(account, () -> {
delete(account);
return null;
}, accountLockExecutor);
Metrics.counter(DELETE_COUNTER_NAME,
COUNTRY_CODE_TAG_NAME, Util.getCountryCode(account.getNumber()),
COUNTRY_CODE_TAG_NAME, Util.getCountryCode(account),
DELETION_REASON_TAG_NAME, deletionReason.tagValue)
.increment();
} catch (final RuntimeException e) {
@@ -1199,26 +1312,27 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
}
private void delete(final Account account) {
final List<TransactWriteItem> additionalWriteItems = account.getDevices().stream()
final List<TransactWriteItem> additionalWriteItems = new ArrayList<>();
account.getDevices().stream()
.flatMap(device -> keysManager.buildWriteItemsForRemovedDevice(
account.getIdentifier(IdentityType.ACI),
account.getIdentifier(IdentityType.PNI),
account.getPhoneNumberIdentifierOptional(),
device.getId())
.stream())
.toList();
.forEach(additionalWriteItems::add);
account.getPhoneNumberIdentifierOptional().ifPresent(phoneNumberIdentifier ->
additionalWriteItems.add(phoneNumberRecoveryPasswordsManager.buildTransactWriteItemForRemovePassword(phoneNumberIdentifier)));
CompletableFuture.allOf(
secureStorageClient.deleteStoredData(account.getUuid()),
secureValueRecovery2Client.removeData(account.getUuid()),
keysManager.deleteSingleUsePreKeys(account.getUuid()),
keysManager.deleteSingleUsePreKeys(account.getPhoneNumberIdentifier()),
messagesManager.clear(account.getUuid()),
profilesManager.deleteAll(account.getUuid(), true))
secureStorageClient.deleteStoredData(account.getAccountIdentifier()),
secureValueRecovery2Client.removeData(account.getAccountIdentifier()),
keysManager.deleteSingleUsePreKeys(account.getAccountIdentifier()),
account.getPhoneNumberIdentifierOptional().map(keysManager::deleteSingleUsePreKeys).orElse(CompletableFuture.completedFuture(null)),
messagesManager.clear(account.getAccountIdentifier()),
profilesManager.deleteAll(account.getAccountIdentifier(), true))
.join();
registrationRecoveryPasswordsManager.remove(account.getIdentifier(IdentityType.PNI));
accounts.delete(account.getUuid(), additionalWriteItems);
accounts.delete(account.getAccountIdentifier(), additionalWriteItems);
redisDelete(account);
disconnectionRequestManager.requestDisconnection(account);
@@ -1240,9 +1354,9 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
cacheCluster.useCluster(connection -> {
final RedisAdvancedClusterCommands<String, String> commands = connection.sync();
commands.setex(getAccountMapKey(account.getPhoneNumberIdentifier().toString()), CACHE_TTL_SECONDS,
account.getUuid().toString());
commands.setex(getAccountEntityKey(account.getUuid()), CACHE_TTL_SECONDS, accountJson);
account.getPhoneNumberIdentifierOptional().ifPresent(pni ->
commands.setex(getAccountMapKey(pni.toString()), CACHE_TTL_SECONDS, account.getAccountIdentifier().toString()));
commands.setex(getAccountEntityKey(account.getAccountIdentifier()), CACHE_TTL_SECONDS, accountJson);
});
} catch (JsonProcessingException e) {
throw new IllegalStateException(e);
@@ -1260,11 +1374,11 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
}
return cacheCluster.withCluster(connection -> CompletableFuture.allOf(
connection.async().setex(
getAccountMapKey(account.getPhoneNumberIdentifier().toString()), CACHE_TTL_SECONDS,
account.getUuid().toString())
.toCompletableFuture(),
connection.async().setex(getAccountEntityKey(account.getUuid()), CACHE_TTL_SECONDS, accountJson)
account.getPhoneNumberIdentifierOptional().map(pni ->
connection.async().setex(getAccountMapKey(pni.toString()), CACHE_TTL_SECONDS, account.getAccountIdentifier().toString())
.toCompletableFuture())
.orElseGet(() -> CompletableFuture.completedFuture(null)),
connection.async().setex(getAccountEntityKey(account.getAccountIdentifier()), CACHE_TTL_SECONDS, accountJson)
.toCompletableFuture()));
}
@@ -1371,12 +1485,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
try {
if (StringUtils.isNotBlank(accountJson)) {
Account account = SystemMapper.jsonMapper().readValue(accountJson, Account.class);
account.setUuid(uuid);
if (account.getPhoneNumberIdentifier() == null) {
logger.warn("Account {} loaded from Redis is missing a PNI", uuid);
}
account.setAccountIdentifier(uuid);
return Optional.of(account);
}
@@ -1393,11 +1502,16 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
}
private void redisDelete(final Account account) {
final List<String> keysToDelete = new ArrayList<>(2);
account.getPhoneNumberIdentifierOptional()
.map(pni -> getAccountMapKey(pni.toString()))
.ifPresent(keysToDelete::add);
keysToDelete.add(getAccountEntityKey(account.getAccountIdentifier()));
ResilienceUtil.getGeneralRedisRetry(RETRY_NAME).executeRunnable(() ->
redisDeleteTimer.record(() ->
cacheCluster.useCluster(connection ->
connection.sync().del(getAccountMapKey(account.getPhoneNumberIdentifier().toString()),
getAccountEntityKey(account.getUuid())))));
connection.sync().del(keysToDelete.toArray(String[]::new)))));
}
public CompletableFuture<Optional<DeviceInfo>> waitForNewLinkedDevice(
@@ -1491,8 +1605,8 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
}
public CompletableFuture<Optional<TransferArchiveResult>> waitForTransferArchive(final Account account, final Device device, final Duration timeout) {
final DeviceIdentifier deviceIdentifier = new DeviceIdentifier(account.getIdentifier(IdentityType.ACI), device.getId(), device.getRegistrationId(IdentityType.ACI));
final String registrationIdTransferArchiveKey = getRegistrationIdTransferArchiveKey(account.getIdentifier(IdentityType.ACI), device.getId(), device.getRegistrationId(IdentityType.ACI));
final DeviceIdentifier deviceIdentifier = new DeviceIdentifier(account.getAccountIdentifier(), device.getId(), device.getRegistrationId(IdentityType.ACI));
final String registrationIdTransferArchiveKey = getRegistrationIdTransferArchiveKey(account.getAccountIdentifier(), device.getId(), device.getRegistrationId(IdentityType.ACI));
return waitForPubSubKey(waitForTransferArchiveFuturesByDeviceIdentifier,
deviceIdentifier,
@@ -1508,7 +1622,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
try {
final String transferArchiveJson = SystemMapper.jsonMapper().writeValueAsString(transferArchiveResult);
final String key = getRegistrationIdTransferArchiveKey(account.getIdentifier(IdentityType.ACI), destinationDeviceId, registrationId);
final String key = getRegistrationIdTransferArchiveKey(account.getAccountIdentifier(), destinationDeviceId, registrationId);
return ResilienceUtil.getGeneralRedisRetry(RETRY_NAME)
.executeCompletionStage(retryExecutor, () -> pubSubRedisClient.withConnection(connection -> connection.async()
@@ -1634,7 +1748,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
channel.substring(TRANSFER_ARCHIVE_KEYSPACE_PATTERN.length() - 1).split(":", 4);
if (deviceIdentifierComponents.length != 4) {
logger.error("Could not parse device identifier; unexpected component count: {}",
ImpossibleEvents.logImpossible(logger, "Could not parse device identifier; unexpected component count: {}",
deviceIdentifierComponents.length);
return;
}
@@ -1692,4 +1806,33 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
throw new AssertionError("Every implementation of the Java platform is required to support the SHA-256 MessageDigest algorithm", e);
}
}
public void migrateAccountRecoveryPassword(final Account account) {
accountLockManager.withSingleAccountLock(account, () -> {
migrateAccountRecoveryPassword(account.getAccountIdentifier(), MAX_UPDATE_ATTEMPTS);
return null;
}, accountLockExecutor);
}
private void migrateAccountRecoveryPassword(final UUID accountIdentifier, final int retries) {
try {
final Account account = accounts.getByAccountIdentifier(accountIdentifier)
.orElseThrow(ContestedOptimisticLockException::new);
account.getPhoneNumberIdentifierOptional()
.flatMap(phoneNumberRecoveryPasswordsManager::getPasswordAndWriteItemForMigration)
.ifPresent(passwordAndWriteItem -> {
account.setAccountRecoveryPassword(passwordAndWriteItem.first());
accounts.updateTransactionally(account, List.of(passwordAndWriteItem.second()));
redisDelete(account);
});
} catch (final ContestedOptimisticLockException | TransactionCanceledException e) {
if (retries > 0) {
migrateAccountRecoveryPassword(accountIdentifier, retries - 1);
}
throw e;
}
}
}
@@ -37,13 +37,13 @@ import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
import org.whispersystems.textsecuregcm.entities.PhoneVerificationRequest;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.push.MessageSender;
import org.whispersystems.textsecuregcm.push.MessageTooLargeException;
import org.whispersystems.textsecuregcm.util.Pair;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
import org.whispersystems.textsecuregcm.util.logging.ImpossibleEvents;
public class ChangeNumberManager {
@@ -101,10 +101,14 @@ public class ChangeNumberManager {
final Account account = accountAndMaybeExistingAccount.first();
// Only verify and check reglock if there's a data change to be made...
if (!account.getNumber().equals(number)) {
if (account.getNumberOptional().isEmpty()) {
throw new IllegalArgumentException("account does not have a phone number");
}
final Optional<Duration> waitingPeriodRemaining = changeNumberWaitingPeriodManager.getWaitingPeriodRemaining(account.getUuid());
// Only verify and check reglock if there's a data change to be made...
if (!account.getNumberOptional().get().equals(number)) {
final Optional<Duration> waitingPeriodRemaining = changeNumberWaitingPeriodManager.getWaitingPeriodRemaining(account.getAccountIdentifier());
if (waitingPeriodRemaining.isPresent()) {
Metrics.counter(POST_REGISTRATION_WAITING_PERIOD_NOT_MET_COUNTER_NAME).increment();
throw new RateLimitExceededException(waitingPeriodRemaining.get());
@@ -118,6 +122,7 @@ public class ChangeNumberManager {
final Optional<Account> existingAccount = accountAndMaybeExistingAccount.second();
if (existingAccount.isPresent()) {
assert existingAccount.get().getNumberOptional().isPresent();
registrationLockVerificationManager.verifyRegistrationLock(existingAccount.get(), registrationLock,
userAgent, RegistrationLockVerificationManager.Flow.CHANGE_NUMBER, verificationType);
}
@@ -129,7 +134,7 @@ public class ChangeNumberManager {
// ...but always attempt to make the change in case a client retries and needs to re-send messages
final long serverTimestamp = clock.millis();
final AciServiceIdentifier serviceIdentifier = new AciServiceIdentifier(account.getIdentifier(IdentityType.ACI));
final AciServiceIdentifier serviceIdentifier = new AciServiceIdentifier(account.getAccountIdentifier());
// Note that these for-validation envelopes do NOT have the "updated PNI" field set, and we'll need to populate that
// after actually changing the account's number.
@@ -159,13 +164,14 @@ public class ChangeNumberManager {
}
final Account updatedAccount = accountsManager.changeNumber(
account.getIdentifier(IdentityType.ACI), number, pniIdentityKey, deviceSignedPreKeys, devicePqLastResortPreKeys, pniRegistrationIds);
account.getAccountIdentifier(), number, pniIdentityKey, deviceSignedPreKeys, devicePqLastResortPreKeys, pniRegistrationIds);
if (!messagesByDeviceId.isEmpty()) {
try {
// Now that we've actually updated the account, populate the "updated PNI" field on all envelopes
messagesByDeviceId.replaceAll((_, envelope) ->
envelope.toBuilder().setUpdatedPni(UUIDUtil.toByteString(updatedAccount.getIdentifier(IdentityType.PNI)))
envelope.toBuilder().setUpdatedPni(UUIDUtil.toByteString(updatedAccount.getPhoneNumberIdentifierOptional()
.orElseThrow(() -> new AssertionError("Account does not have a PNI after changing number"))))
.build());
messageSender.sendMessages(updatedAccount,
@@ -174,9 +180,14 @@ public class ChangeNumberManager {
registrationIdsByDeviceId,
Optional.of(Device.PRIMARY_ID),
userAgent);
} catch (MismatchedDevicesException | MessageTooLargeException e) {
ImpossibleEvents.logImpossible(logger,
"Changed number but could not send device messages after preliminary validation succeeded {}",
account.getAccountIdentifier(), e);
throw e;
} catch (final RuntimeException e) {
logger.warn("Changed number but could not send all device messages for {}",
account.getIdentifier(IdentityType.ACI), e);
account.getAccountIdentifier(), e);
throw e;
}
}
@@ -9,15 +9,17 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonSetter;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.google.common.annotations.VisibleForTesting;
import java.time.Duration;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import javax.annotation.Nullable;
import com.google.common.annotations.VisibleForTesting;
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
@@ -71,7 +73,8 @@ public class Device {
private int registrationId;
@JsonProperty("pniRegistrationId")
private int phoneNumberIdentityRegistrationId;
@Nullable
private Integer phoneNumberIdentityRegistrationId;
@JsonProperty
private long lastSeen;
@@ -221,13 +224,43 @@ public class Device {
return getId() == PRIMARY_ID;
}
/// Returns the registration ID for this device associated with the given identity type.
///
/// @param identityType the type of identity for which to return the registration ID
///
/// @return the registration ID for the given identity type for the device
///
/// @throws NoSuchElementException if a PNI identity is requested for a device attached
/// to an account without a phone number identity.
///
/// @deprecated Please use [#getAccountRegistrationId()] or
/// [#getPhoneNumberIdentityRegistrationId()] instead.
@Deprecated
public int getRegistrationId(final IdentityType identityType) {
return switch (identityType) {
case ACI -> registrationId;
case PNI -> phoneNumberIdentityRegistrationId;
case ACI -> getAccountRegistrationId();
case PNI -> getPhoneNumberIdentityRegistrationId().orElseThrow(NoSuchElementException::new);
};
}
/// Returns the registration ID for this device associated with its account's account identity.
///
/// @return the registration ID for this device associated with its account's account identity.
public int getAccountRegistrationId() {
return registrationId;
}
/// Returns the registration ID for this device associated with its
/// account's phone-number identity, or an empty Optional if the account
/// does not have a phone number.
///
/// @return the registration ID for this device associated with its
/// account's phone-number identity, or an empty Optional if the account
/// does not have a phone number.
public Optional<Integer> getPhoneNumberIdentityRegistrationId() {
return Optional.ofNullable(phoneNumberIdentityRegistrationId);
}
public void setRegistrationId(int registrationId) {
this.registrationId = registrationId;
}
@@ -18,7 +18,8 @@ public enum DeviceCapability {
ATTACHMENT_BACKFILL("attachmentBackfill", AccountCapabilityMode.PRIMARY_DEVICE, AccountCapabilityVisibility.SELF, false, false),
SPARSE_POST_QUANTUM_RATCHET("spqr", AccountCapabilityMode.ALL_DEVICES, AccountCapabilityVisibility.PUBLIC, true, true),
PROFILES_V2("profiles_v2", AccountCapabilityMode.ALL_DEVICES, AccountCapabilityVisibility.SELF, false, false),
USERNAME_CHANGE_SYNC_MESSAGE("usernameChangeSyncMessage", AccountCapabilityMode.ALL_DEVICES, AccountCapabilityVisibility.SELF, true, false);
USERNAME_CHANGE_SYNC_MESSAGE("usernameChangeSyncMessage", AccountCapabilityMode.ALL_DEVICES, AccountCapabilityVisibility.SELF, true, false),
OPTIONAL_PHONE_NUMBER("optionalPhoneNumber", AccountCapabilityMode.ALL_DEVICES, AccountCapabilityVisibility.SERVER, false, false);
public static final List<DeviceCapability> PUBLIC_VISIBLE_CAPABILITIES = Arrays.stream(DeviceCapability.values())
.filter(c -> c.accountCapabilityVisibility == AccountCapabilityVisibility.PUBLIC)
Loaded 100 of 265 files, more files were not shown because too many files have changed in this diff. Show more