Compare commits

...
Author SHA1 Message Date
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
Jonathan Klabunde Tomer 98ba337787 remove primary-device requirement on three accounts grpc endpoints 2026-07-17 10:54:41 -07:00
Ameya Lokare 4410da5fb2 Use Mono.fromFuture(() ->) instead of Mono.fromFuture() to defer
evaluation
2026-07-17 10:53:44 -07:00
Ameya Lokare 607c839dda Add a utility method that returns a cancellation-safe result from
`database.runAsync`
2026-07-17 10:53:44 -07:00
Chris Eager bb3ad8d116 Add FoundationDB timeouts and retries 2026-07-17 12:47:11 -05:00
Chris Eager 2dcd43318e Update permissions in workflows/test.yml 2026-07-17 12:43:07 -05:00
Ravi Khadiwala b255c37978 Hoist user-agent tag out of publisher in copyMedia 2026-07-17 12:42:27 -05:00
Ravi Khadiwala ea411e2f1e Change ConfigureUnidentifiedAccessRequest to a oneof 2026-07-17 12:41:03 -05:00
Ravi Khadiwala 70f83326ef Make log stripping more consistent 2026-07-17 12:40:47 -05:00
Ravi Khadiwala 90a5ad589b Fix close code check in test 2026-07-15 11:35:57 -05:00
Ravi Khadiwala 749d9c4f92 Require donation permit headers 2026-07-15 11:35:46 -05:00
ravi-signal 3d45706a35 Add GetCapabilities rpcs 2026-07-15 11:35:20 -05:00
Ravi Khadiwala ed90c1c15c Drop unversioned profiles from grpc service 2026-07-14 16:06:31 -05:00
Ravi Khadiwala 5147fe57f2 Update stripe SDK to 33.1.0 2026-07-14 16:05:51 -05:00
Jon Chambers 1d366c98a9 Mirror demand signals and establish presence when mirroring reads to FoundationDB 2026-07-14 08:56:57 -07:00
Jon Chambers 8c19171284 Retire AcknowledgementMirroringMessageStream 2026-07-14 08:56:57 -07:00
Katherine 47a461ef1f Update description for status code 400 on KT endpoints 2026-07-14 11:55:43 -04:00
Jon Chambers a959656c96 Terminate the publisher if presence renewal fails 2026-07-14 11:10:51 -04:00
Jon Chambers ab08a3a0e4 Address some synchronization holes with presence renewal 2026-07-11 10:16:31 -04:00
Jon Chambers 688d3a2212 Log exceptions when fetching end-of-queue keys 2026-07-10 14:29:44 -07:00
Jon Chambers 25fdc95843 Update to the latest version of the spam filter 2026-07-10 14:13:30 -04:00
Ameya Lokare d3c93dd1a2 Port AccountControllerV2 to gRPC 2026-07-10 13:56:49 -04:00
Jonathan Klabunde Tomer 54ea7a288c test with smaller number of accounts 2026-07-10 13:56:18 -04:00
Jonathan Klabunde Tomer e2cb484743 async fetch messages in test 2026-07-10 13:56:18 -04:00
Jonathan Klabunde Tomer 45f176d5a8 re-enable FoundationDbMessageStoreTest#deleteExpiredMessages 2026-07-10 13:56:18 -04:00
Jon Chambers 450945a9cc Perform end-of-queue-key processing outside of a transaction retry loop 2026-07-10 13:55:37 -04:00
Ravi Khadiwala 253671c206 Improve assertion failure message in GracefulShutdownIntegrationTest 2026-07-10 13:54:33 -04:00
Jon Chambers cdd461b8f4 Simplify FoundationDbMessageStream construction 2026-07-10 10:47:03 -04:00
Jon Chambers d9a54a0d42 Don't parse messages inside of a retryable transaction block 2026-07-10 10:47:03 -04:00
Jon Chambers 3f3aa89b0f Retire batched acknowledgement system in favor of point deletions 2026-07-10 10:47:03 -04:00
Ravi Khadiwala 55fa60dd4e Setting apns push tokens should always update the timestamp 2026-07-10 10:46:41 -04:00
Ravi Khadiwala b539df8e48 Add some missing authentication specifiers 2026-07-10 10:46:28 -04:00
Ravi Khadiwala 0cd0716eb5 Register ProductConfigurationGrpcService in WhisperServerService 2026-07-10 10:46:28 -04:00
Jon Chambers 6386aada73 Add an "active requests" gauge for WebSocket requests 2026-07-10 10:46:16 -04:00
Jon Chambers 5c44398bb5 Add an "active requests" counter to the gRPC metrics interceptor 2026-07-10 10:46:16 -04:00
Jon Chambers 54736bb117 Update logback to 1.5.38 2026-07-10 10:46:07 -04:00
ravi-signal aed8e60789 Create a dedicated graceful shutdown test 2026-07-09 13:52:21 -05:00
Jon Chambers 5fa50e8ad7 Increment a counter for timeouts rather than logging the full exception 2026-07-09 09:49:32 -04:00
Jon Chambers fdaba751bd Update logback to 1.5.33 2026-07-09 09:48:48 -04:00
Ravi Khadiwala 0eebb58956 Remove unused badgeIdsEnabledForAll configuration 2026-07-09 09:48:18 -04:00
Ravi Khadiwala 6bb85d77a7 Add badge/backup entitlement RPC 2026-07-09 09:48:18 -04:00
Ravi Khadiwala 9e3844ee5a Add issue hook to integration test workflow 2026-07-07 12:30:08 -05:00
Jonathan Klabunde Tomer 7ee8e349e2 add command to periodically clear expired messages from foundationdb 2026-07-06 14:17:12 -04:00
Katherine 4d9e252697 Support group send endorsement authentication for versioned profile fetches on ProfileAnonymous gRPC service 2026-07-06 14:10:07 -04:00
Jon Chambers 222e5a033b Add an experiment to partially mirror reads from FoundationDB 2026-07-06 14:01:24 -04:00
Jon Chambers 8c6fbbfa65 Revert "Switch back to AcknowledgementMirroringMessageStream"
This reverts commit 5174550ef3.
2026-07-02 15:52:45 -04:00
Jon Chambers b0b2122d8c Establish presence asynchronously rather than blocking onSubscribe 2026-07-02 14:47:02 -04:00
Jon Chambers d7711e235b Revert "Simplify demand mirroring"
This reverts commit d0fcb9ab54.
2026-07-02 12:38:11 -04:00
Jon Chambers 5174550ef3 Switch back to AcknowledgementMirroringMessageStream 2026-07-02 12:09:29 -04:00
Jon Chambers d0fcb9ab54 Simplify demand mirroring 2026-07-02 12:08:21 -04:00
Jon Chambers 375150a8c3 Dispose of the mirrored FoundationDB stream when the Redis/DynamoDB stream terminates for any reason 2026-07-01 18:18:30 -04:00
Jon Chambers cb28614721 Guard against null presence values 2026-07-01 18:17:48 -04:00
Ameya Lokare f02caf78cd Make OneTimeDonationController sync 2026-07-01 18:17:16 -04:00
Jon Chambers 8fd72549fb Temporarily switch back to point deletes 2026-07-01 14:34:05 -04:00
dependabot[bot] 1e4774820f Bump actions/checkout from 6.0.3 to 7.0.0
Bumps [actions/checkout](https://github.com/actions/checkout) from 6.0.3 to 7.0.0.
- [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/df4cb1c069e1874edd31b4311f1884172cec0e10...9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-version: 7.0.0
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-07-01 14:32:54 -04:00
dependabot[bot] 48cdad7e57 Bump the minor-actions-dependencies group with 2 updates
Bumps the minor-actions-dependencies group with 2 updates: [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/setup-java` from 5.2.0 to 5.4.0
- [Release notes](https://github.com/actions/setup-java/releases)
- [Commits](https://github.com/actions/setup-java/compare/be666c2fcd27ec809703dec50e508c2fdc7f6654...1bcf9fb12cf4aa7d266a90ae39939e61372fe520)

Updates `aws-actions/configure-aws-credentials` from 6.2.0 to 6.2.1
- [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/e7f100cf4c008499ea8adda475de1042d6975c7b...254c19bd240aabef8777f48595e9d2d7b972184b)

---
updated-dependencies:
- dependency-name: actions/setup-java
  dependency-version: 5.4.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.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-actions-dependencies
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-07-01 14:16:24 -04:00
Chris Eager 392bab5b60 Consolidate and clarify ZK configuration 2026-07-01 14:14:20 -04:00
ravi-signal 6b67604fe7 Move donation/backup configuration to own service
Also, add an etag so configuration can be sent only if it changes
2026-07-01 12:19:00 -05:00
Ravi Khadiwala 67a03f81b9 Add username_link_handle to AccountIdentifiers message 2026-07-01 12:16:12 -05:00
Ravi Khadiwala 90b75cbf22 Add a test for our Any typeUrls 2026-07-01 12:15:43 -05:00
Ameya Lokare 4dede4acad Keep track of number of emitted messages so we don't fetch messages on
every onRequest()
2026-06-30 16:38:51 -07:00
Jon Chambers d225ba3618 Align FoundationDB default page size with mirroring page size 2026-06-30 17:14:06 -04:00
Jon Chambers 8790514b8a Establish presence when fetching messages from FoundationDB 2026-06-30 11:36:22 -04:00
Jon Chambers fa4d3c7ca9 Avoid automatic, unbounded requests on subscription 2026-06-30 11:36:22 -04:00
Jon Chambers 1f0b2ad92d Reapply "Mirror message reads/acknowledgements via FoundationDbMessageStream"
This reverts commit 28aefe0ebe.
2026-06-30 11:36:22 -04:00
Chris Eager feb00c6ba6 Add avatars to profiles gRPC 2026-06-29 13:15:07 -05:00
Ravi Khadiwala f588390bdb Handle ACCOUNT_NOT_FOUND errors in AppleAppStoreClient 2026-06-29 13:11:00 -05:00
Jon Chambers 355b320c92 Don't attempt to send empty message bundles when changing numbers 2026-06-26 15:51:28 -04:00
Jon Chambers 40fb9c4cee Fix a bogus assertion for "change number" message-sending 2026-06-26 15:51:28 -04:00
Ravi Khadiwala aa5ac70ad3 Select lifecycle-manager based on environment variable (like in FoundationDbClusterExtension) 2026-06-25 17:42:04 -04:00
Jon Chambers 2abf55e395 Don't trigger state transitions inside retryable transactions 2026-06-25 17:41:33 -04:00
Jon Chambers 808bb16103 Add basic read/acknowledgement counters to RedisDynamoDbMessageStream 2026-06-25 17:41:11 -04:00
Ameya Lokare 4743abcfbd Port OneTimeDonationController to gRPC 2026-06-25 17:40:49 -04:00
Katherine 1b09529ece Use V2 key transparency query RPCs 2026-06-24 15:02:34 -07:00
Chris Eager 0c3c390a0b Update Donation-Permit header parameter documentation 2026-06-24 14:51:46 -07:00
Chris Eager ca4ee141d8 Disable a flaky test 2026-06-24 13:18:07 -05:00
Jonathan Klabunde TomerandJon Chambers 671a6e1d7c address review comments
Co-authored-by: Jon Chambers <63609320+jon-signal@users.noreply.github.com>
2026-06-24 12:14:52 -05:00
Jonathan Klabunde Tomer f4e16676c9 add FoundationDbMessageStore api to clear messages before a given time 2026-06-24 12:14:52 -05:00
Chris Eager 78b3147491 Implement donation permit spending 2026-06-24 12:13:21 -05:00
Ravi Khadiwala 8b617b64f8 Add metric for requested attachment upload size 2026-06-24 12:11:57 -05:00
Jon Chambers 28aefe0ebe Revert "Mirror message reads/acknowledgements via FoundationDbMessageStream"
This reverts commit 4e52317e26.
2026-06-24 13:01:13 -04:00
Jon Chambers 4e52317e26 Mirror message reads/acknowledgements via FoundationDbMessageStream 2026-06-24 10:18:15 -04:00
Ravi Khadiwala 99465c1f41 Update to the latest version of the spam filter 2026-06-23 13:13:49 -05:00
Chris Eager 041c29bfa8 Update foundationdb to 7.3.68 2026-06-23 13:11:05 -05:00
Chris Eager 8e5ad7f52e Remove unused mocking in CredentialsGrpcServiceTest 2026-06-23 13:11:05 -05:00
Jon Chambers ca5d203f1c Make RegistrationServiceClient blocking 2026-06-23 13:09:12 -05:00
ravi-signal 9a9b15ee0a Add per-element constraint validation 2026-06-23 13:08:39 -05:00
ravi-signal 503941ec6a Add a load-shedding GOAWAY 2026-06-23 13:07:49 -05:00
Ravi Khadiwala ac720595e6 Add header to disable messages on authenticated websocket 2026-06-18 15:28:41 -05:00
Jonathan Klabunde Tomer 8deb5a803a foundationdb "versionstamp clock" 2026-06-18 13:27:59 -07:00
Jon Chambers 45f96cd702 Delete messages from FoundationDB asynchronously 2026-06-18 14:06:26 -04:00
Chris Eager 4a3275ad63 Add POST /v1/donation/permit 2026-06-18 13:06:18 -05:00
Ameya Lokare 911feceacb Handle "no sender available" error code from registration service 2026-06-18 09:03:02 -04:00
Jon Chambers fe0956c8f7 Don't add Dropwizard metrics to shared registries 2026-06-18 09:02:33 -04:00
Jon Chambers 60002a8a0f Port StickerController to gRPC 2026-06-18 08:51:00 -04:00
Ameya Lokare 1876b71d39 Port SubscriptionController to gRPC 2026-06-18 08:27:38 -04:00
Jon Chambers 3cfe8b9f6c Mirror message writes/deletions to FoundationDB 2026-06-18 08:27:03 -04:00
Jon Chambers 691a4162e1 Update to the latest version of the spam filter 2026-06-18 08:25:07 -04:00
Ravi Khadiwala 9505e7b1a1 Fix incorrect mockito matcher in BackupManagerTest 2026-06-17 12:43:34 -05:00
Jon Chambers 569f4f31e8 Update to the latest version of the spam filter 2026-06-17 08:46:11 -04:00
Ravi Khadiwala 06519ce9d1 Use uint64 for backups.proto object length 2026-06-17 08:45:43 -04:00
Jon Chambers 024fa9ce5f Move "active epoch" configuration from dynamic to static configuration 2026-06-17 08:35:07 -04:00
Jon Chambers 7c9e3d029b Remove an unused availableProcessors variable 2026-06-17 08:33:29 -04:00
Jon Chambers cc6ef53f91 Retire unused methods in MessagesManager 2026-06-17 08:33:29 -04:00
Ravi Khadiwala 4c0f454209 Add a generic STREAM_CLOSED status 2026-06-17 08:32:47 -04:00
Chris Eager 9c393972e9 Update to the latest version of the spam filter 2026-06-16 20:02:56 -05:00
Jon Chambers 31c1bb8940 Support multiple "configuration epochs" of the FoundationDB message store 2026-06-16 09:06:18 -04:00
Jon Chambers c3b2b43813 Port CallLinkController to gRPC 2026-06-16 09:02:24 -04:00
Jon Chambers 19f2574799 Update to the latest version of the spam filter 2026-06-16 09:02:03 -04:00
340 changed files with 17332 additions and 6428 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@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
- uses: actions/setup-java@be666c2fcd27ec809703dec50e508c2fdc7f6654 # v5.2.0
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
- uses: actions/setup-java@1bcf9fb12cf4aa7d266a90ae39939e61372fe520 # v5.4.0
with:
distribution: 'temurin'
java-version-file: .java-version
+12 -3
View File
@@ -17,14 +17,15 @@ jobs:
permissions:
id-token: write
contents: read
issues: write
steps:
- uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
- uses: actions/setup-java@be666c2fcd27ec809703dec50e508c2fdc7f6654 # v5.2.0
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
- uses: actions/setup-java@1bcf9fb12cf4aa7d266a90ae39939e61372fe520 # v5.4.0
with:
distribution: 'temurin'
java-version-file: .java-version
cache: 'maven'
- uses: aws-actions/configure-aws-credentials@e7f100cf4c008499ea8adda475de1042d6975c7b # v6.2.0
- uses: aws-actions/configure-aws-credentials@254c19bd240aabef8777f48595e9d2d7b972184b # v6.2.1
name: Configure AWS credentials from Test account
with:
role-to-assume: ${{ vars.AWS_ROLE }}
@@ -35,3 +36,11 @@ jobs:
echo "${INTEGRATION_TEST_CONFIG}" > integration-tests/src/main/resources/config.yml
- name: Run and verify integration tests
run: ./mvnw clean compile test-compile failsafe:integration-test failsafe:verify -P aws-sso
- name: Open an issue on failure
if: ${{ failure() && github.event_name == 'schedule' }}
env:
GH_TOKEN: ${{ github.token }}
run: |
gh issue create \
--title "Failed server integration tests ($(date +'%Y-%m-%d'))" \
--body "Workflow **${{ github.workflow }}** failed. See the run: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}"
+24 -19
View File
@@ -1,5 +1,8 @@
name: Service CI
permissions:
contents: read
on:
pull_request:
push:
@@ -9,39 +12,31 @@ on:
jobs:
build:
runs-on: ubuntu-latest
container: ubuntu:24.04
container: ubuntu:26.04
timeout-minutes: 20
services:
foundationdb0:
# Note: this should generally match the version of the FoundationDB SERVER deployed in production; it's okay if
# it's a little behind the CLIENT version.
image: foundationdb/foundationdb:7.3.62
# Note: this should generally match the version of the FoundationDB SERVER deployed in production; no need to
# bump it purely to match the CLIENT version
image: foundationdb/foundationdb:7.3.68
options: --name foundationdb0
foundationdb1:
# Note: this should generally match the version of the FoundationDB SERVER deployed in production; it's okay if
# it's a little behind the CLIENT version.
image: foundationdb/foundationdb:7.3.62
# Note: this should generally match the version of the FoundationDB SERVER deployed in production; no need to
# bump it purely to match the CLIENT version
image: foundationdb/foundationdb:7.3.68
options: --name foundationdb1
steps:
- uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
- name: Set up JDK
uses: actions/setup-java@be666c2fcd27ec809703dec50e508c2fdc7f6654 # v5.2.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@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
- 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
@@ -54,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@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
- name: Configure FoundationDB0 database
run: docker exec foundationdb0 /usr/bin/fdbcli --exec 'configure new single memory'
- name: Configure FoundationDB1 database
@@ -61,7 +66,7 @@ jobs:
- name: Download and install FoundationDB client
run: |
./mvnw -e -B -Pexclude-spam-filter clean prepare-package -DskipTests=true
cp service/target/jib-extra/usr/lib/libfdb_c.x86_64.so /usr/lib/libfdb_c.x86_64.so
cp service/target/jib-extra/usr/lib/libfdb_c.so /usr/lib/libfdb_c.x86_64.so
ldconfig
- name: Build with Maven
run: ./mvnw -e -B clean verify -DfoundationDb.serviceContainerNamePrefix=foundationdb
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
@@ -112,7 +112,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,8 +128,8 @@ public class TestUser {
return aciUuid;
}
public UUID pniUuid() {
return pniUuid;
public Optional<UUID> pniUuid() {
return Optional.ofNullable(pniUuid);
}
public AccountAttributes accountAttributes() {
@@ -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;
}
@@ -62,7 +62,7 @@ public class WebsocketClientSession implements Session.Listener.AutoDemanding {
log.info("received response message {}", response.getStatus());
final CompletableFuture<WebSocketResponseMessage> future = responseFutures.remove(response.getRequestId());
if (future == null) {
throw new IllegalArgumentException("Received response with no matching request: {}" + response.getRequestId());
throw new IllegalArgumentException("Received response with no matching request: " + response.getRequestId());
}
future.complete(response);
}
@@ -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"
+11 -13
View File
@@ -50,13 +50,12 @@
<commons-csv.version>1.14.1</commons-csv.version>
<commons-io.version>2.21.0</commons-io.version>
<dropwizard.version>5.0.1</dropwizard.version>
<!-- Note: when updating FoundationDB, also include a copy of `libfdb_c.so` from the FoundationDB release at
src/main/jib/usr/lib/libfdb_c.so. We use x86_64 builds without AVX instructions enabled (i.e. FoundationDB versions
with even-numbered patch versions). Also when updating FoundationDB, make sure to update the version of FoundationDB
used by GitHub Actions. -->
<foundationdb.version>7.3.62</foundationdb.version>
<!-- Note: We use x86_64 builds without AVX instructions enabled (i.e. FoundationDB versions with even-numbered
patch versions). Also when updating FoundationDB, make sure to update the version of FoundationDBused by GitHub
Actions. -->
<foundationdb.version>7.3.68</foundationdb.version>
<foundationdb.api-version>730</foundationdb.api-version>
<foundationdb.client-library-sha256>bfed237b787fae3cde1222676e6bfbb0d218fc27bf9e903397a7a7aa96fb2d33</foundationdb.client-library-sha256>
<foundationdb.client-library-sha256>8c96a1f7ab561cd38e16e4c269c5e50ae0fd8063854e0d72c89339a7ac1b6873</foundationdb.client-library-sha256>
<google-cloud-libraries.version>26.79.0</google-cloud-libraries.version>
<grpc.version>1.76.3</grpc.version> <!-- should be kept in sync with the value from Google libraries-bom -->
<gson.version>2.13.2</gson.version>
@@ -68,7 +67,7 @@
<junit-pioneer.version>2.3.0</junit-pioneer.version>
<jsr305.version>3.0.2</jsr305.version>
<kotlin.version>2.3.20</kotlin.version>
<logback.version>1.5.32</logback.version>
<logback.version>1.5.38</logback.version>
<logback-access-common.version>2.0.12</logback-access-common.version>
<lettuce.version>7.5.1.RELEASE</lettuce.version>
<libphonenumber.version>9.0.21</libphonenumber.version>
@@ -86,18 +85,17 @@
<semver4j.version>3.1.0</semver4j.version>
<simple-grpc.version>0.2.0</simple-grpc.version>
<slf4j.version>2.0.17</slf4j.version>
<stripe.version>31.2.0</stripe.version>
<stripe.version>33.1.0</stripe.version>
<swagger.version>2.2.46</swagger.version>
<testcontainers.version>2.0.4</testcontainers.version>
<!-- 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>
@@ -287,7 +285,7 @@
<dependency>
<groupId>org.signal</groupId>
<artifactId>libsignal-server</artifactId>
<version>0.86.6</version>
<version>0.96.2</version>
</dependency>
<dependency>
<groupId>org.signal</groupId>
+3 -2
View File
@@ -79,9 +79,8 @@ storageService.userAuthenticationTokenSharedSecret: AAAAAAAAAAAAAAAAAAAAAAAAAAAA
zkConfig-libsignal-0.42.serverSecret: ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdef
genericZkConfig.serverSecret: ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzAA==
callingZkConfig.serverSecret: ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzAA==
backupsZkConfig.serverSecret: ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzAA==
chatZkConfig.serverSecret: ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzAA==
paymentsService.userAuthenticationTokenSharedSecret: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= # base64-encoded 32-byte secret shared with MobileCoin services used to generate auth tokens for Signal users
paymentsService.fixerApiKey: unset
@@ -100,3 +99,5 @@ tlsKeyStore.password: unset
hlrLookup.apiKey: AAAAAAAAAAA
hlrLookup.apiSecret: AAAAAAAAAAA
foundationDbMessages.versionstampCipherKey.0: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=
+39 -8
View File
@@ -100,6 +100,9 @@ dynamoDbTables:
tableName: Example_DeletedAccounts
deletedAccountsLock:
tableName: Example_DeletedAccountsLock
donationPermits:
tableName: Example_DonationPermits
expiration: P7D # Duration of time until rows expire
issuedReceipts:
tableName: Example_IssuedReceipts
expiration: P30D # Duration of time until rows expire
@@ -125,6 +128,8 @@ dynamoDbTables:
expiration: P90D
phoneNumberIdentifiers:
tableName: Example_PhoneNumberIdentifiers
profileAvatars:
tableName: Example_ProfileAvatars
profiles:
tableName: Example_Profiles
profilesV2:
@@ -313,15 +318,15 @@ storageService:
AAAAAAAAAAAAAAAAAAAA
-----END CERTIFICATE-----
zkConfig:
serverPublic: ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzAB==
serverSecret: secret://zkConfig-libsignal-0.42.serverSecret
callingZkConfig:
serverSecret: secret://callingZkConfig.serverSecret
backupsZkConfig:
serverSecret: secret://backupsZkConfig.serverSecret
chatZkConfig:
serverSecret: secret://chatZkConfig.serverSecret
groupsZkConfig:
serverPublic: ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzAB==
serverSecret: secret://zkConfig-libsignal-0.42.serverSecret
dynamicConfig:
s3Region: a-region
@@ -360,8 +365,6 @@ badges:
svgs:
- light: example-light.svg
dark: example-dark.svg
badgeIdsEnabledForAll:
- TEST
receiptLevels:
'1': TEST
@@ -538,3 +541,31 @@ callQualitySurvey:
hlrLookup:
apiKey: secret://hlrLookup.apiKey
apiSecret: secret://hlrLookup.apiSecret
foundationDbMessages:
maxWatchesPerClient: 10000
transactionTimeout: PT1S
transactionRetryLimit: 3
batchPriorityTransactionTimeout: PT5S
batchPriorityTransactionRetryLimit: 10
versionstampCipherKeys:
0: secret://foundationDbMessages.versionstampCipherKey.0
currentVersionstampCipherKey: 0
clusters:
"messages-0":
clusterFileUrl: http://clusterfiles.example.com/messages-0
"messages-1":
clusterFileUrl: http://clusterfiles.example.com/messages-1
"messages-2":
clusterFileUrl: http://clusterfiles.example.com/messages-2
"messages-3":
clusterFileUrl: http://clusterfiles.example.com/messages-3
epochs:
0:
- messages-0
- messages-1
1:
- messages-0
- messages-1
- messages-2
- messages-3
+15 -2
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>
@@ -572,6 +578,12 @@
<artifactId>google-auth-library-oauth2-http</artifactId>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk18on</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.stripe</groupId>
<artifactId>stripe-java</artifactId>
@@ -617,7 +629,7 @@
<plugin>
<groupId>io.github.download-maven-plugin</groupId>
<artifactId>download-maven-plugin</artifactId>
<version>2.0.0</version>
<version>2.1.0</version>
<executions>
<execution>
@@ -632,6 +644,7 @@
<configuration>
<url>https://github.com/apple/foundationdb/releases/download/${foundationdb.version}/libfdb_c.x86_64.so</url>
<outputDirectory>${project.build.directory}/jib-extra/usr/lib</outputDirectory>
<outputFileName>libfdb_c.so</outputFileName>
<sha256>${foundationdb.client-library-sha256}</sha256>
</configuration>
</plugin>
@@ -719,7 +732,7 @@
</executions>
<configuration>
<from>
<image>eclipse-temurin@sha256:${docker.image.sha256}</image>
<image>${docker.image}</image>
<platforms>
<platform>
<architecture>amd64</architecture>
@@ -17,6 +17,7 @@ import org.whispersystems.textsecuregcm.configuration.AppleAppStoreConfiguration
import org.whispersystems.textsecuregcm.configuration.AppleDeviceCheckConfiguration;
import org.whispersystems.textsecuregcm.configuration.AttachmentsConfiguration;
import org.whispersystems.textsecuregcm.configuration.AwsCredentialsProviderFactory;
import org.whispersystems.textsecuregcm.configuration.BackupConfiguration;
import org.whispersystems.textsecuregcm.configuration.BadgesConfiguration;
import org.whispersystems.textsecuregcm.configuration.BraintreeConfiguration;
import org.whispersystems.textsecuregcm.configuration.CallQualitySurveyConfiguration;
@@ -34,6 +35,7 @@ import org.whispersystems.textsecuregcm.configuration.ExternalRequestFilterConfi
import org.whispersystems.textsecuregcm.configuration.FaultTolerantRedisClientFactory;
import org.whispersystems.textsecuregcm.configuration.FaultTolerantRedisClusterFactory;
import org.whispersystems.textsecuregcm.configuration.FcmConfiguration;
import org.whispersystems.textsecuregcm.configuration.FoundationDbMessagesConfiguration;
import org.whispersystems.textsecuregcm.configuration.GcpAttachmentsConfiguration;
import org.whispersystems.textsecuregcm.configuration.GenericZkConfig;
import org.whispersystems.textsecuregcm.configuration.GooglePlayBillingConfiguration;
@@ -66,7 +68,7 @@ import org.whispersystems.textsecuregcm.configuration.VirtualThreadConfiguration
import org.whispersystems.textsecuregcm.configuration.ZkConfig;
import org.whispersystems.websocket.configuration.WebSocketConfiguration;
/** @noinspection MismatchedQueryAndUpdateOfCollection, WeakerAccess */
// @noinspection MismatchedQueryAndUpdateOfCollection, WeakerAccess
public class WhisperServerConfiguration extends Configuration {
@NotNull
@@ -129,6 +131,11 @@ public class WhisperServerConfiguration extends Configuration {
@JsonProperty
private GcpAttachmentsConfiguration gcpAttachments;
@NotNull
@Valid
@JsonProperty
private BackupConfiguration backup = new BackupConfiguration();
@NotNull
@Valid
@JsonProperty
@@ -219,11 +226,6 @@ public class WhisperServerConfiguration extends Configuration {
@JsonProperty
private PaymentsServiceConfiguration paymentsService;
@Valid
@NotNull
@JsonProperty
private ZkConfig zkConfig;
@Valid
@NotNull
@JsonProperty
@@ -232,7 +234,12 @@ public class WhisperServerConfiguration extends Configuration {
@Valid
@NotNull
@JsonProperty
private GenericZkConfig backupsZkConfig;
private GenericZkConfig chatZkConfig;
@Valid
@NotNull
@JsonProperty
private ZkConfig groupsZkConfig;
@Valid
@NotNull
@@ -361,6 +368,11 @@ public class WhisperServerConfiguration extends Configuration {
@JsonProperty
private ChangeNumberConfiguration changeNumber = new ChangeNumberConfiguration(Duration.ofHours(1));
@Valid
@NotNull
@JsonProperty
private FoundationDbMessagesConfiguration foundationDbMessages;
public TlsKeyStoreConfiguration getTlsKeyStoreConfiguration() {
return tlsKeyStore;
}
@@ -417,6 +429,10 @@ public class WhisperServerConfiguration extends Configuration {
return gcpAttachments;
}
public BackupConfiguration getBackupConfiguration() {
return backup;
}
public FaultTolerantRedisClusterFactory getCacheClusterConfiguration() {
return cacheCluster;
}
@@ -481,16 +497,19 @@ public class WhisperServerConfiguration extends Configuration {
return paymentsService;
}
public ZkConfig getZkConfig() {
return zkConfig;
/// ZK secret limited to Chat Service
public GenericZkConfig getChatZkConfig() {
return chatZkConfig;
}
/// ZK secret shared with Calling Service
public GenericZkConfig getCallingZkConfig() {
return callingZkConfig;
}
public GenericZkConfig getBackupsZkConfig() {
return backupsZkConfig;
/// ZK secret shared with Groups Service
public ZkConfig getGroupsZkConfig() {
return groupsZkConfig;
}
public RemoteConfigConfiguration getRemoteConfigConfiguration() {
@@ -600,4 +619,8 @@ public class WhisperServerConfiguration extends Configuration {
public ChangeNumberConfiguration getChangeNumber() {
return changeNumber;
}
public FoundationDbMessagesConfiguration getFoundationDbMessagesConfiguration() {
return foundationDbMessages;
}
}
@@ -7,6 +7,8 @@ package org.whispersystems.textsecuregcm;
import static java.util.Objects.requireNonNull;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import com.apple.foundationdb.Database;
import com.apple.foundationdb.FDB;
import com.google.common.collect.Lists;
import com.webauthn4j.appattest.DeviceCheckManager;
import io.dropwizard.auth.AuthDynamicFeature;
@@ -44,6 +46,8 @@ import io.netty.resolver.dns.DnsNameResolverBuilder;
import io.netty.util.Mapping;
import jakarta.servlet.DispatcherType;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.http.HttpClient;
@@ -53,6 +57,7 @@ import java.time.Duration;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.ServiceLoader;
import java.util.Set;
@@ -63,7 +68,9 @@ import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import org.eclipse.jetty.ee10.websocket.server.config.JettyWebSocketServletContainerInitializer;
import org.eclipse.jetty.websocket.core.WebSocketExtensionRegistry;
import org.eclipse.jetty.websocket.core.server.WebSocketServerComponents;
@@ -103,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;
@@ -169,13 +177,17 @@ import org.whispersystems.textsecuregcm.grpc.MessageDispatcher;
import org.whispersystems.textsecuregcm.grpc.MessagesAnonymousGrpcService;
import org.whispersystems.textsecuregcm.grpc.MessagesGrpcService;
import org.whispersystems.textsecuregcm.grpc.MetricServerInterceptor;
import org.whispersystems.textsecuregcm.grpc.OneTimeDonationsGrpcService;
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;
import org.whispersystems.textsecuregcm.grpc.net.ManagedGrpcServer;
import org.whispersystems.textsecuregcm.grpc.net.ManagedEventLoopGroup;
import org.whispersystems.textsecuregcm.grpc.net.ManagedGrpcServer;
import org.whispersystems.textsecuregcm.grpc.net.OmnibusH2Server;
import org.whispersystems.textsecuregcm.grpc.net.OmnibusRouter;
import org.whispersystems.textsecuregcm.grpc.net.SniMapper;
@@ -194,12 +206,14 @@ 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;
import org.whispersystems.textsecuregcm.mappers.NonNormalizedPhoneNumberExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.ObsoletePhoneNumberFormatExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.RegistrationLockFailureExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.RegistrationServiceSenderExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.ServerRejectedExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.SubscriptionExceptionMapper;
@@ -226,7 +240,6 @@ import org.whispersystems.textsecuregcm.redis.ConnectionEventLogger;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
import org.whispersystems.textsecuregcm.registration.RegistrationServiceClient;
import org.whispersystems.textsecuregcm.s3.PolicySigner;
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
import org.whispersystems.textsecuregcm.s3.S3MonitoringSupplier;
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
@@ -244,7 +257,10 @@ import org.whispersystems.textsecuregcm.storage.ChangeNumberWaitingPeriodManager
import org.whispersystems.textsecuregcm.storage.ChangeNumberWaitingPeriods;
import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
import org.whispersystems.textsecuregcm.storage.ClientReleases;
import org.whispersystems.textsecuregcm.storage.DonationPermits;
import org.whispersystems.textsecuregcm.storage.DonationPermitsManager;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.storage.FoundationDbVersion;
import org.whispersystems.textsecuregcm.storage.IssuedReceiptsManager;
import org.whispersystems.textsecuregcm.storage.KeysManager;
import org.whispersystems.textsecuregcm.storage.MessagesCache;
@@ -254,6 +270,7 @@ import org.whispersystems.textsecuregcm.storage.OneTimeDonationsManager;
import org.whispersystems.textsecuregcm.storage.PagedSingleUseKEMPreKeyStore;
import org.whispersystems.textsecuregcm.storage.PersistentTimer;
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
import org.whispersystems.textsecuregcm.storage.ProfileAvatars;
import org.whispersystems.textsecuregcm.storage.Profiles;
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
import org.whispersystems.textsecuregcm.storage.ProfilesV2;
@@ -275,6 +292,8 @@ import org.whispersystems.textsecuregcm.storage.VerificationSessions;
import org.whispersystems.textsecuregcm.storage.devicecheck.AppleDeviceCheckManager;
import org.whispersystems.textsecuregcm.storage.devicecheck.AppleDeviceCheckTrustAnchor;
import org.whispersystems.textsecuregcm.storage.devicecheck.AppleDeviceChecks;
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStore;
import org.whispersystems.textsecuregcm.storage.foundationdb.VersionstampUUIDCipher;
import org.whispersystems.textsecuregcm.subscriptions.AppleAppStoreClient;
import org.whispersystems.textsecuregcm.subscriptions.AppleAppStoreManager;
import org.whispersystems.textsecuregcm.subscriptions.BankMandateTranslator;
@@ -302,6 +321,7 @@ import org.whispersystems.textsecuregcm.workers.BackupMetricsCommand;
import org.whispersystems.textsecuregcm.workers.BackupUsageRecalculationCommand;
import org.whispersystems.textsecuregcm.workers.CertificateCommand;
import org.whispersystems.textsecuregcm.workers.CheckDynamicConfigurationCommand;
import org.whispersystems.textsecuregcm.workers.ClearExpiredFoundationDbMessagesCommand;
import org.whispersystems.textsecuregcm.workers.ClearIssuedReceiptRedemptionsCommand;
import org.whispersystems.textsecuregcm.workers.CopyToS3Command;
import org.whispersystems.textsecuregcm.workers.DeleteUserCommand;
@@ -319,6 +339,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;
@@ -331,7 +352,6 @@ import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import javax.annotation.Nullable;
public class WhisperServerService extends Application<WhisperServerConfiguration> {
@@ -378,6 +398,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
bootstrap.addCommand(new NotifyIdleDevicesCommand());
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",
@@ -400,7 +422,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
@Override
public void run(WhisperServerConfiguration config, Environment environment) throws Exception {
final Clock clock = Clock.systemUTC();
final int availableProcessors = Runtime.getRuntime().availableProcessors();
final AwsCredentialsProvider awsCredentialsProvider = config.getAwsCredentialsConfiguration().build();
@@ -461,6 +482,43 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
final DynamoDbClient dynamoDbClient = config.getDynamoDbClientConfiguration()
.buildSyncClient(awsCredentialsProvider, new MicrometerAwsSdkMetricPublisher(awsSdkMetricsExecutor, "dynamoDbSync"));
final FDB fdb = FDB.selectAPIVersion(FoundationDbVersion.getFoundationDbApiVersion());
// Jetty and the FoundationDB client both register shutdown hooks to begin shutdown/cleanup operations. There isn't
// a good way to coordinate or enforce ordering between shutdown hooks, and so the two processes will race.
// Generally, FoundationDB will shut down before Jetty does, meaning we'll still be trying to serve requests that
// require talking to FoundationDB even though FoundationDB has shut down. To avoid that scenario, we disabled
// FoundationDB's shutdown hook and let the JVM terminate its (daemon) threads at exit. This isn't as graceful as
// we'd like, but is the least bad option given current constraints.
fdb.disableShutdownHook();
final Map<Integer, List<Database>> messageDatabasesByEpoch;
{
final Map<String, Database> databasesByName =
config.getFoundationDbMessagesConfiguration().clusters().entrySet().stream()
.collect(Collectors.toUnmodifiableMap(Map.Entry::getKey,
entry -> {
try {
final Database database = entry.getValue().build(fdb);
database.options().setMaxWatches(config.getFoundationDbMessagesConfiguration().maxWatchesPerClient());
database.options().setTransactionTimeout(
config.getFoundationDbMessagesConfiguration().transactionTimeout().toMillis());
database.options().setTransactionRetryLimit(
config.getFoundationDbMessagesConfiguration().transactionRetryLimit());
return database;
} catch (final IOException e) {
throw new UncheckedIOException(e);
}
}));
messageDatabasesByEpoch = config.getFoundationDbMessagesConfiguration().epochs().entrySet().stream()
.collect(Collectors.toUnmodifiableMap(Map.Entry::getKey,
entry -> entry.getValue().stream()
.map(databasesByName::get)
.toList()));
}
final AwsCredentialsProvider cdnCredentialsProvider = config.getCdnConfiguration().credentials().build();
final S3AsyncClient asyncCdnS3Client = S3AsyncClient.builder()
.credentialsProvider(cdnCredentialsProvider)
@@ -494,6 +552,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
Profiles profilesV1 = new Profiles(dynamoDbClient, dynamoDbAsyncClient,
config.getDynamoDbTables().getProfilesV1().getTableName());
ProfilesV2 profiles = new ProfilesV2(dynamoDbClient, dynamoDbAsyncClient, config.getDynamoDbTables().getProfilesV2().getTableName());
ProfileAvatars profileAvatars = new ProfileAvatars(dynamoDbClient,
config.getDynamoDbTables().getProfileAvatars().getTableName(), RemoveExpiredAccountsCommand.MAX_IDLE_DURATION, clock);
S3AsyncClient asyncKeysS3Client = S3AsyncClient.builder()
.credentialsProvider(awsCredentialsProvider)
@@ -574,6 +634,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
.threads(16).build();
final ScheduledExecutorService registrationIdentityTokenRefreshExecutor =
ScheduledExecutorServiceBuilder.of(environment, "registrationIdentityTokenRefresh").threads(1).build();
final ScheduledExecutorService presenceRenewalExecutor =
ScheduledExecutorServiceBuilder.of(environment, "presenceRenewal").threads(4).build();
Scheduler messageDeliveryScheduler = Schedulers.fromExecutorService(
ExecutorServiceBuilder.of(environment, "messageDelivery")
@@ -592,10 +654,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
.workQueue(receiptSenderQueue)
.rejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy())
.build();
ExecutorService registrationCallbackExecutor = ExecutorServiceBuilder.of(environment, "registration")
.maxThreads(2)
.minThreads(2)
.build();
ExecutorService accountLockExecutor = ExecutorServiceBuilder.of(environment, "accountLock")
.minThreads(8)
.maxThreads(8)
@@ -677,7 +735,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
retryExecutor);
RegistrationServiceClient registrationServiceClient = config.getRegistrationServiceConfiguration()
.build(environment, registrationCallbackExecutor, registrationIdentityTokenRefreshExecutor);
.build(environment, registrationIdentityTokenRefreshExecutor);
KeyTransparencyServiceClient keyTransparencyServiceClient = new KeyTransparencyServiceClient(
config.getKeyTransparencyServiceConfiguration().host(),
config.getKeyTransparencyServiceConfiguration().port(),
@@ -700,10 +758,18 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
storageServiceExecutor, retryExecutor, config.getSecureStorageServiceConfiguration());
DisconnectionRequestManager disconnectionRequestManager = new DisconnectionRequestManager(pubsubClient,
disconnectionRequestListenerExecutor, retryExecutor);
ProfilesManager profilesManager = new ProfilesManager(profilesV1, profiles, cacheCluster, retryExecutor, asyncCdnS3Client,
ProfilesManager profilesManager = new ProfilesManager(profilesV1, profiles, profileAvatars, cacheCluster, retryExecutor, asyncCdnS3Client,
config.getCdnConfiguration().bucket());
MessagesCache messagesCache = new MessagesCache(messagesCluster, messageDeliveryScheduler,
messageDeletionAsyncExecutor, retryExecutor, clock);
final FoundationDbMessageStore foundationDbMessageStore = new FoundationDbMessageStore(messageDatabasesByEpoch,
config.getFoundationDbMessagesConfiguration().activeEpoch(),
new VersionstampUUIDCipher(config.getFoundationDbMessagesConfiguration().currentVersionstampCipherKey(),
config.getFoundationDbMessagesConfiguration().versionstampCipherKeys().get(config.getFoundationDbMessagesConfiguration().currentVersionstampCipherKey()).value()),
presenceRenewalExecutor,
Clock.systemUTC(),
config.getFoundationDbMessagesConfiguration().batchPriorityTransactionTimeout(),
config.getFoundationDbMessagesConfiguration().batchPriorityTransactionRetryLimit());
ClientReleaseManager clientReleaseManager = new ClientReleaseManager(clientReleases,
recurringJobExecutor,
config.getClientReleaseConfiguration().refreshInterval(),
@@ -712,8 +778,9 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
config.getReportMessageConfiguration().getCounterTtl());
RedisMessageAvailabilityManager redisMessageAvailabilityManager =
new RedisMessageAvailabilityManager(messagesCluster, clientEventExecutor, asyncOperationQueueingExecutor);
MessagesManager messagesManager = new MessagesManager(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager,
reportMessageManager, messageDeletionAsyncExecutor, Clock.systemUTC());
MessagesManager messagesManager =
new MessagesManager(messagesDynamoDb, messagesCache, foundationDbMessageStore, redisMessageAvailabilityManager,
reportMessageManager, messageDeletionAsyncExecutor, Clock.systemUTC(), experimentEnrollmentManager);
final ChangeNumberWaitingPeriods changeNumberWaitingPeriods = new ChangeNumberWaitingPeriods(
config.getDynamoDbTables().getChangeNumberWaitingPeriods().getTableName(), dynamoDbClient);
final ChangeNumberWaitingPeriodManager changeNumberWaitingPeriodManager = new ChangeNumberWaitingPeriodManager(
@@ -725,7 +792,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
changeNumberWaitingPeriodManager, secureStorageClient, secureValueRecovery2Client, disconnectionRequestManager,
registrationRecoveryPasswordsManager, 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,
@@ -742,6 +809,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
config.getDynamoDbTables().getIssuedReceipts().getmaxIssuedReceiptsPerPaymentId());
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,
@@ -850,23 +919,28 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
config.getGcpAttachmentsConfiguration().pathPrefix(),
config.getGcpAttachmentsConfiguration().rsaSigningKey().value());
PostPolicyGenerator profileCdnPolicyGenerator = new PostPolicyGenerator(config.getCdnConfiguration().region(),
config.getCdnConfiguration().bucket(), config.getCdnConfiguration().credentials().accessKeyId().value());
PolicySigner profileCdnPolicySigner = new PolicySigner(
config.getCdnConfiguration().credentials().secretAccessKey().value(),
config.getCdnConfiguration().region());
final PostPolicyGenerator profileCdnPolicyGenerator = new PostPolicyGenerator(config.getCdnConfiguration().region(),
config.getCdnConfiguration().bucket(),
config.getCdnConfiguration().credentials().accessKeyId().value(),
config.getCdnConfiguration().credentials().secretAccessKey().value());
ServerSecretParams zkSecretParams = new ServerSecretParams(config.getZkConfig().serverSecret().value());
final PostPolicyGenerator stickerPolicyGenerator = new PostPolicyGenerator(config.getCdnConfiguration().region(),
config.getCdnConfiguration().bucket(),
config.getCdnConfiguration().credentials().accessKeyId().value(),
config.getCdnConfiguration().credentials().secretAccessKey().value());
ServerSecretParams groupZkSecretParams = new ServerSecretParams(config.getGroupsZkConfig().serverSecret().value());
GenericServerSecretParams callingGenericZkSecretParams = new GenericServerSecretParams(config.getCallingZkConfig().serverSecret().value());
GenericServerSecretParams backupsGenericZkSecretParams = new GenericServerSecretParams(config.getBackupsZkConfig().serverSecret().value());
ServerZkProfileOperations zkProfileOperations = new ServerZkProfileOperations(zkSecretParams);
ServerZkAuthOperations zkAuthOperations = new ServerZkAuthOperations(zkSecretParams);
ServerZkReceiptOperations zkReceiptOperations = new ServerZkReceiptOperations(zkSecretParams);
GenericServerSecretParams chatGenericZkSecretParams = new GenericServerSecretParams(config.getChatZkConfig().serverSecret().value());
ServerZkProfileOperations zkProfileOperations = new ServerZkProfileOperations(groupZkSecretParams);
ServerZkAuthOperations zkAuthOperations = new ServerZkAuthOperations(groupZkSecretParams);
// ZK receipts are not actually shared with ZK groups, but use the same extensible parameters object for legacy reasons
ServerZkReceiptOperations zkReceiptOperations = new ServerZkReceiptOperations(groupZkSecretParams);
TusAttachmentGenerator tusAttachmentGenerator = new TusAttachmentGenerator(config.getTus());
Cdn3BackupCredentialGenerator cdn3BackupCredentialGenerator = new Cdn3BackupCredentialGenerator(config.getTus());
BackupAuthManager backupAuthManager = new BackupAuthManager(experimentEnrollmentManager, rateLimiters,
accountsManager, zkReceiptOperations, redeemedReceiptsManager, backupsGenericZkSecretParams, clock);
accountsManager, zkReceiptOperations, redeemedReceiptsManager, chatGenericZkSecretParams, clock);
BackupsDb backupsDb = new BackupsDb(
dynamoDbAsyncClient,
config.getDynamoDbTables().getBackups().getTableName(),
@@ -877,7 +951,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
config.getCdn3StorageManagerConfiguration());
BackupManager backupManager = new BackupManager(
backupsDb,
backupsGenericZkSecretParams,
chatGenericZkSecretParams,
rateLimiters,
tusAttachmentGenerator,
cdn3BackupCredentialGenerator,
@@ -885,7 +959,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
svrbCredentialsGenerator,
secureValueRecoveryBClient,
clock,
dynamicConfigurationManager);
config.getBackupConfiguration());
final BackupMetrics backupMetrics = new BackupMetrics();
final AppleDeviceChecks appleDeviceChecks = new AppleDeviceChecks(
@@ -902,6 +976,13 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
config.getAppleDeviceCheck().teamId(),
config.getAppleDeviceCheck().bundleId());
final DonationPermitsManager donationPermitsManager = new DonationPermitsManager(donationPermits, groupZkSecretParams,
clock);
final SubscriptionManager subscriptionManager = new SubscriptionManager(subscriptions,
List.of(stripeManager, braintreeManager, googlePlayBillingManager, appleAppStoreManager),
zkReceiptOperations, issuedReceiptsManager);
final List<SpamFilter> spamFilters = ServiceLoader.load(SpamFilter.class)
.stream()
.map(ServiceLoader.Provider::get)
@@ -988,7 +1069,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
config.getExternalRequestFilterConfiguration().grpcMethods());
final RequireAuthenticationInterceptor requireAuthenticationInterceptor = new RequireAuthenticationInterceptor(accountAuthenticator);
final ProhibitAuthenticationInterceptor prohibitAuthenticationInterceptor = new ProhibitAuthenticationInterceptor();
final GroupSendTokenUtil groupSendTokenUtil = new GroupSendTokenUtil(zkSecretParams, Clock.systemUTC());
final GroupSendTokenUtil groupSendTokenUtil = new GroupSendTokenUtil(groupZkSecretParams, Clock.systemUTC());
final MessageMetrics messageMetrics = new MessageMetrics();
final MessageDispatcher messageDispatcher = new MessageDispatcher(receiptSender, messagesManager, messageMetrics,
pushNotificationManager, pushNotificationScheduler, messageDeliveryLoopMonitor, disconnectionRequestManager,
@@ -1000,20 +1081,34 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
config.getDeliveryCertificate().expiresDays(),
config.getDeliveryCertificate().embedSigner());
final PhoneVerificationTokenManager phoneVerificationTokenManager = new PhoneVerificationTokenManager(
phoneNumberIdentifiers, registrationServiceClient, registrationRecoveryPasswordsManager, 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),
new AccountsGrpcService(accountsManager, rateLimiters, usernameHashZkProofVerifier, registrationRecoveryPasswordsManager, 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, profileCdnPolicySigner, profileBadgeConverter, rateLimiters),
new ProfileGrpcService(clock, accountsManager, profilesManager, 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),
new AttachmentsGrpcService(experimentEnrollmentManager, rateLimiters,
gcsAttachmentGenerator, tusAttachmentGenerator, config.getAttachments().maxAttachmentUploadSizeInBytes()),
new AttachmentsGrpcService(experimentEnrollmentManager, rateLimiters, gcsAttachmentGenerator,
tusAttachmentGenerator, stickerPolicyGenerator,
config.getAttachments().maxAttachmentUploadSizeInBytes(), Clock.systemUTC()),
new PaymentsGrpcService(currencyManager),
new ChallengeGrpcService(accountsManager, rateLimitChallengeManager, challengeConstraintChecker),
new DonationsGrpcService(clock, zkReceiptOperations, redeemedReceiptsManager, accountsManager, config.getBadges(), ReceiptCredentialPresentation::new))
new DonationsGrpcService(clock, zkReceiptOperations, redeemedReceiptsManager, accountsManager, config.getBadges(), ReceiptCredentialPresentation::new, donationPermitsManager, rateLimiters),
new ProductConfigurationGrpcService(config.getSubscription(), config.getOneTimeDonations(),
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!
@@ -1027,13 +1122,18 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
requireAuthenticationInterceptor))
.toList();
final List<ServerServiceDefinition> unauthenticatedServices = Stream.of(
new AccountsAnonymousGrpcService(accountsManager, rateLimiters),
new AccountsAnonymousGrpcService(accountsManager, rateLimiters, groupSendTokenUtil),
new CallQualitySurveyGrpcService(callQualitySurveyManager, rateLimiters),
new KeysAnonymousGrpcService(accountsManager, keysManager, zkSecretParams, Clock.systemUTC()),
new ProfileAnonymousGrpcService(accountsManager, profilesManager, profileBadgeConverter, zkSecretParams),
new KeysAnonymousGrpcService(accountsManager, keysManager, groupZkSecretParams, Clock.systemUTC()),
new ProfileAnonymousGrpcService(accountsManager, profilesManager, profileBadgeConverter, profileCdnPolicyGenerator, chatGenericZkSecretParams, groupZkSecretParams, rateLimiters, clock),
new MessagesAnonymousGrpcService(accountsManager, rateLimiters, messageSender, groupSendTokenUtil, messageByteLimitCardinalityEstimator, spamChecker, Clock.systemUTC()),
new BackupsAnonymousGrpcService(backupManager, backupMetrics, config.getAttachments().maxAttachmentUploadSizeInBytes(), config.getAttachments().maxMessageBackupUploadSizeInBytes()),
new CredentialsAnonymousGrpcService(accountsManager, ExternalServiceDefinitions.SVR.generatorFactory().apply(config, Clock.systemUTC())))
new CredentialsAnonymousGrpcService(accountsManager, ExternalServiceDefinitions.SVR.generatorFactory().apply(config, Clock.systemUTC())),
new SubscriptionsGrpcService(clock, config.getSubscription(), subscriptionManager, donationPermitsManager,
stripeManager, braintreeManager, googlePlayBillingManager, appleAppStoreManager, bankMandateTranslator),
new OneTimeDonationsGrpcService(config.getOneTimeDonations(), stripeManager, braintreeManager,
payPalDonationsTranslator, oneTimeDonationsManager, issuedReceiptsManager,
zkReceiptOperations, clock, rateLimiters, donationPermitsManager))
.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!
@@ -1074,6 +1174,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
omnibusNioEventLoopGroup.getEventLoopGroup(),
omnibusLocalEventLoopGroup.getEventLoopGroup(),
new InetSocketAddress(config.getGrpc().bindAddress(), config.getGrpc().port()), omnibusRouter,
() -> dynamicConfigurationManager.getConfiguration().getOmnibus(),
config.getGrpc().idleTimeout());
environment.lifecycle().manage(omnibusLocalEventLoopGroup);
@@ -1138,13 +1239,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
final PersistentTimer persistentTimer = new PersistentTimer(rateLimitersCluster, clock);
final PhoneVerificationTokenManager phoneVerificationTokenManager = new PhoneVerificationTokenManager(
phoneNumberIdentifiers, registrationServiceClient, registrationRecoveryPasswordsManager, registrationRecoveryChecker);
final ChangeNumberManager changeNumberManager = new ChangeNumberManager(messageSender, accountsManager,
phoneVerificationTokenManager, registrationLockVerificationManager, rateLimiters,
changeNumberWaitingPeriodManager, Clock.systemUTC());
final List<Object> commonControllers = Lists.newArrayList(
new AccountController(accountsManager, rateLimiters, registrationRecoveryPasswordsManager,
usernameHashZkProofVerifier),
@@ -1163,39 +1257,34 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
config.getDeviceCheck().backupRedemptionDuration()),
new DirectoryV2Controller(directoryV2CredentialsGenerator),
new DonationController(clock, zkReceiptOperations, redeemedReceiptsManager, accountsManager, config.getBadges(),
ReceiptCredentialPresentation::new),
new KeysController(rateLimiters, keysManager, accountsManager, zkSecretParams, Clock.systemUTC()),
ReceiptCredentialPresentation::new, donationPermitsManager, rateLimiters),
new KeysController(rateLimiters, keysManager, accountsManager, groupZkSecretParams, Clock.systemUTC()),
new KeyTransparencyController(keyTransparencyServiceClient),
new MessageController(rateLimiters, messageByteLimitCardinalityEstimator, messageSender, accountsManager,
phoneNumberIdentifiers, reportMessageManager, zkSecretParams, spamChecker, Clock.systemUTC()),
phoneNumberIdentifiers, reportMessageManager, groupZkSecretParams, spamChecker, Clock.systemUTC()),
new PaymentsController(currencyManager, paymentsCredentialsGenerator),
new ProfileController(clock, rateLimiters, accountsManager, profilesManager, dynamicConfigurationManager,
profileBadgeConverter, config.getBadges(), profileCdnPolicyGenerator, profileCdnPolicySigner,
zkSecretParams, zkProfileOperations, batchIdentityCheckExecutor),
profileBadgeConverter, config.getBadges(), profileCdnPolicyGenerator,
groupZkSecretParams, zkProfileOperations, batchIdentityCheckExecutor),
new ProvisioningController(rateLimiters, provisioningManager),
new RegistrationController(accountsManager, phoneVerificationTokenManager, registrationLockVerificationManager,
rateLimiters, registrationFraudChecker),
new RemoteConfigController(remoteConfigsManager, config.getRemoteConfigConfiguration().globalConfig()),
new RemoteConfigController(remoteConfigsManager),
new SecureStorageController(storageCredentialsGenerator),
new SecureValueRecovery2Controller(svr2CredentialsGenerator, accountsManager),
new StickerController(rateLimiters, config.getCdnConfiguration().credentials().accessKeyId().value(),
config.getCdnConfiguration().credentials().secretAccessKey().value(), config.getCdnConfiguration().region(),
config.getCdnConfiguration().bucket()),
new StickerController(rateLimiters, stickerPolicyGenerator, Clock.systemUTC()),
new VerificationController(registrationServiceClient, new VerificationSessionManager(verificationSessions),
pushNotificationManager, registrationCaptchaManager, registrationRecoveryPasswordsManager,
phoneNumberIdentifiers, rateLimiters, accountsManager, carrierDataProvider, registrationFraudChecker,
dynamicConfigurationManager, experimentEnrollmentManager, clock)
dynamicConfigurationManager, experimentEnrollmentManager, clock),
new SubscriptionController(clock, config.getSubscription(), config.getOneTimeDonations(),
subscriptionManager, stripeManager, braintreeManager, googlePlayBillingManager, appleAppStoreManager,
profileBadgeConverter, bankMandateTranslator, donationPermitsManager,
config.getBackupConfiguration().maxTotalMediaSize()),
new OneTimeDonationController(clock, config.getOneTimeDonations(), stripeManager, braintreeManager,
payPalDonationsTranslator, zkReceiptOperations, issuedReceiptsManager, oneTimeDonationsManager,
donationPermitsManager)
);
if (config.getSubscription() != null && config.getOneTimeDonations() != null) {
SubscriptionManager subscriptionManager = new SubscriptionManager(subscriptions,
List.of(stripeManager, braintreeManager, googlePlayBillingManager, appleAppStoreManager),
zkReceiptOperations, issuedReceiptsManager);
commonControllers.add(new SubscriptionController(clock, config.getSubscription(), config.getOneTimeDonations(),
subscriptionManager, stripeManager, braintreeManager, googlePlayBillingManager, appleAppStoreManager,
profileBadgeConverter, bankMandateTranslator, dynamicConfigurationManager));
commonControllers.add(new OneTimeDonationController(clock, config.getOneTimeDonations(), stripeManager, braintreeManager,
payPalDonationsTranslator, zkReceiptOperations, issuedReceiptsManager, oneTimeDonationsManager));
}
for (Object controller : commonControllers) {
environment.jersey().register(controller);
@@ -1260,13 +1349,15 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new InvalidWebsocketAddressExceptionMapper(),
new DeviceLimitExceededExceptionMapper(),
new ServerRejectedExceptionMapper(),
new IllegalStateExceptionMapper(),
new ImpossiblePhoneNumberExceptionMapper(),
new NonNormalizedPhoneNumberExceptionMapper(),
new ObsoletePhoneNumberFormatExceptionMapper(),
new RegistrationServiceSenderExceptionMapper(),
new SubscriptionExceptionMapper(),
new BackupExceptionMapper(),
new JsonMappingExceptionMapper()
new JsonMappingExceptionMapper(),
new RegistrationLockFailureExceptionMapper()
).forEach(exceptionMapper -> {
environment.jersey().register(exceptionMapper);
webSocketEnvironment.jersey().register(exceptionMapper);
@@ -1310,7 +1401,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
}
}
public static void main(String[] args) throws Exception {
static void main(String[] args) throws Exception {
new WhisperServerService().run(args);
}
}
@@ -126,7 +126,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
@@ -35,14 +35,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()));
.setSenderUuid(UUIDUtil.toByteString(account.getAccountIdentifier()));
if (includeE164) {
builder.setSenderE164(account.getNumber());
builder.setSenderE164(account.getNumberOptional().get());
}
if (embedSigner) {
@@ -0,0 +1,24 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.auth;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.core.Response;
import java.util.Base64;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.donation.DonationPermit;
public record DonationPermitHeader(DonationPermit permit) {
public static DonationPermitHeader valueOf(String header) {
try {
return new DonationPermitHeader(new DonationPermit(Base64.getDecoder().decode(header)));
} catch (InvalidInputException | IllegalArgumentException e) {
// Base64 throws IllegalArgumentException; DonationPermit ctor throws InvalidInputException
throw new WebApplicationException(e, Response.Status.UNAUTHORIZED);
}
}
}
@@ -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) {
@@ -0,0 +1,10 @@
package org.whispersystems.textsecuregcm.auth;
import org.whispersystems.textsecuregcm.util.NoStackTraceException;
public class InvalidRegistrationSessionException extends NoStackTraceException {
public InvalidRegistrationSessionException(final String message) {
super(message);
}
}
@@ -7,19 +7,14 @@ package org.whispersystems.textsecuregcm.auth;
import io.grpc.Status;
import io.grpc.StatusRuntimeException;
import jakarta.ws.rs.BadRequestException;
import jakarta.ws.rs.ForbiddenException;
import jakarta.ws.rs.NotAuthorizedException;
import jakarta.ws.rs.ServerErrorException;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.core.Response;
import java.io.IOException;
import java.security.MessageDigest;
import java.time.Duration;
import java.util.UUID;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.entities.PhoneVerificationRequest;
@@ -28,7 +23,6 @@ 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 javax.annotation.Nullable;
public class PhoneVerificationTokenManager {
@@ -56,23 +50,27 @@ public class PhoneVerificationTokenManager {
* Checks if a {@link PhoneVerificationRequest} has a token that verifies the caller has confirmed access to the e164
* number
*
* @param requestContext the container request context
* @param number the e164 presented for verification
* @param sessionId a verification session ID; exactly one of {@code sessionId} or {@code recoveryPassword} must be
* non-null
* @param recoveryPassword a registration recovery password; exactly one of {@code sessionId} or
* {@code recoveryPassword} must be non-null
* @return if verification was successful, returns the verification type
* @throws BadRequestException if the number does not match the sessionId’s number, or the remote service rejects
* @throws InvalidRegistrationSessionException if the number does not match the sessionId’s number, or the remote service rejects
* the session ID as invalid
* @throws NotAuthorizedException if the session is not verified
* @throws ForbiddenException if the recovery password is not valid
* @throws UnverifiedRegistrationSessionException if the session is not verified
* @throws RecoveryPasswordVerificationFailedException if the recovery password is not valid
* @throws InterruptedException if verification did not complete before a timeout
* @throws IOException if there was an error talking to registration service
*/
public PhoneVerificationRequest.VerificationType verify(final ContainerRequestContext requestContext,
public PhoneVerificationRequest.VerificationType verify(
final String number,
@Nullable final String userAgent,
@Nullable final String acceptLanguage,
@Nullable final String mostRecentProxy,
@Nullable final byte[] sessionId,
@Nullable final byte[] recoveryPassword) throws InterruptedException {
@Nullable final byte[] recoveryPassword)
throws InterruptedException, UnverifiedRegistrationSessionException, InvalidRegistrationSessionException, IOException, RecoveryPasswordVerificationFailedException {
if ((sessionId == null) == (recoveryPassword == null)) {
throw new IllegalArgumentException("Exactly one of session ID or recovery password must non-null");
@@ -84,49 +82,45 @@ public class PhoneVerificationTokenManager {
switch (verificationType) {
case SESSION -> verifyBySessionId(number, sessionId);
case RECOVERY_PASSWORD -> verifyByRecoveryPassword(requestContext, number, recoveryPassword);
case RECOVERY_PASSWORD -> verifyByRecoveryPassword(number, userAgent, acceptLanguage, mostRecentProxy, recoveryPassword);
}
return verificationType;
}
private void verifyBySessionId(final String number, final byte[] sessionId) throws InterruptedException {
private void verifyBySessionId(final String number, final byte[] sessionId)
throws UnverifiedRegistrationSessionException, InvalidRegistrationSessionException, IOException {
try {
final RegistrationServiceSession session = registrationServiceClient
.getSession(sessionId, REGISTRATION_RPC_TIMEOUT)
.get(VERIFICATION_TIMEOUT_SECONDS, TimeUnit.SECONDS)
.orElseThrow(() -> new NotAuthorizedException("session not verified"));
.orElseThrow(UnverifiedRegistrationSessionException::new);
if (!MessageDigest.isEqual(number.getBytes(), session.number().getBytes())) {
throw new BadRequestException("number does not match session");
throw new InvalidRegistrationSessionException("number does not match session");
}
if (!session.verified()) {
throw new NotAuthorizedException("session not verified");
throw new UnverifiedRegistrationSessionException();
}
} catch (final ExecutionException e) {
if (e.getCause() instanceof StatusRuntimeException grpcRuntimeException) {
if (grpcRuntimeException.getStatus().getCode() == Status.Code.INVALID_ARGUMENT) {
throw new BadRequestException();
}
} catch (final StatusRuntimeException e) {
if (e.getStatus().getCode() == Status.Code.INVALID_ARGUMENT) {
throw new InvalidRegistrationSessionException(e.getMessage());
}
logger.error("Registration service failure", e);
throw new ServerErrorException(Response.Status.SERVICE_UNAVAILABLE);
} catch (final CancellationException | TimeoutException e) {
logger.error("Registration service failure", e);
throw new ServerErrorException(Response.Status.SERVICE_UNAVAILABLE);
throw new IOException("Registration service failure", e);
}
}
private void verifyByRecoveryPassword(final ContainerRequestContext requestContext,
private void verifyByRecoveryPassword(
final String number,
final byte[] recoveryPassword) throws InterruptedException {
@Nullable final String userAgent,
@Nullable final String acceptLanguage,
@Nullable final String mostRecentProxy,
final byte[] recoveryPassword)
throws InterruptedException, IOException, RecoveryPasswordVerificationFailedException {
if (!registrationRecoveryChecker.checkRegistrationRecoveryAttempt(requestContext, number)) {
throw new ForbiddenException("recoveryPassword couldn't be verified");
if (!registrationRecoveryChecker.checkRegistrationRecoveryAttempt(number, userAgent, acceptLanguage, mostRecentProxy)) {
throw new RecoveryPasswordVerificationFailedException();
}
try {
@@ -136,10 +130,10 @@ public class PhoneVerificationTokenManager {
final boolean verified = registrationRecoveryPasswordsManager.verify(phoneNumberIdentifier, recoveryPassword);
if (!verified) {
throw new ForbiddenException("recoveryPassword couldn't be verified");
throw new RecoveryPasswordVerificationFailedException();
}
} catch (final ExecutionException | TimeoutException e) {
throw new ServerErrorException(Response.Status.SERVICE_UNAVAILABLE);
throw new IOException("registration service unavailable", e);
}
}
}
@@ -0,0 +1,6 @@
package org.whispersystems.textsecuregcm.auth;
import org.whispersystems.textsecuregcm.util.NoStackTraceException;
public class RecoveryPasswordVerificationFailedException extends NoStackTraceException {
}
@@ -0,0 +1,18 @@
package org.whispersystems.textsecuregcm.auth;
import org.whispersystems.textsecuregcm.entities.RegistrationLockFailure;
import org.whispersystems.textsecuregcm.util.NoStackTraceException;
public class RegistrationLockFailureException extends NoStackTraceException {
private final RegistrationLockFailure failure;
public RegistrationLockFailureException(final RegistrationLockFailure failure) {
super();
this.failure = failure;
}
public RegistrationLockFailure getFailure() {
return failure;
}
}
@@ -12,8 +12,6 @@ import io.micrometer.core.instrument.DistributionSummary;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.core.Response;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
@@ -80,13 +78,13 @@ public class RegistrationLockVerificationManager {
* @param account
* @param clientRegistrationLock
* @throws RateLimitExceededException
* @throws WebApplicationException
* @throws RegistrationLockFailureException
*/
public void verifyRegistrationLock(final Account account, @Nullable final String clientRegistrationLock,
final String userAgent,
@Nullable final String userAgent,
final Flow flow,
final PhoneVerificationRequest.VerificationType phoneVerificationType
) throws RateLimitExceededException, WebApplicationException {
) throws RateLimitExceededException, RegistrationLockFailureException {
final Tags expiredTags = Tags.of(UserAgentTagUtil.getPlatformTag(userAgent),
Tag.of(REGISTRATION_LOCK_VERIFICATION_FLOW_TAG_NAME, flow.name()),
@@ -156,7 +154,7 @@ public class RegistrationLockVerificationManager {
}
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
@@ -165,11 +163,10 @@ public class RegistrationLockVerificationManager {
Metrics.counter(CHALLENGED_DEVICE_NOT_PUSH_REGISTERED_COUNTER_NAME).increment();
}
throw new WebApplicationException(Response.status(FAILURE_HTTP_STATUS)
.entity(new RegistrationLockFailure(
throw new RegistrationLockFailureException(
new RegistrationLockFailure(
existingRegistrationLock.getTimeRemaining().toMillis(),
svr2FailureCredentials(existingRegistrationLock, updatedAccount)))
.build());
svr2FailureCredentials(existingRegistrationLock, updatedAccount)));
}
rateLimiters.getPinLimiter().clear(phoneNumber);
@@ -179,7 +176,7 @@ public class RegistrationLockVerificationManager {
if (!existingRegistrationLock.needsFailureCredentials()) {
return null;
}
return svr2CredentialGenerator.generateForUuid(account.getUuid());
return svr2CredentialGenerator.generateForUuid(account.getAccountIdentifier());
}
}
@@ -0,0 +1,6 @@
package org.whispersystems.textsecuregcm.auth;
import org.whispersystems.textsecuregcm.util.NoStackTraceException;
public class UnverifiedRegistrationSessionException extends NoStackTraceException {
}
@@ -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;
}
@@ -23,6 +23,7 @@ import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.function.Function;
import javax.annotation.Nullable;
import org.apache.commons.lang3.StringUtils;
import org.signal.libsignal.protocol.ecc.ECKeyPair;
import org.signal.libsignal.protocol.ecc.ECPublicKey;
@@ -34,19 +35,17 @@ import org.signal.libsignal.zkgroup.backups.BackupLevel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.attachments.AttachmentGenerator;
import org.whispersystems.textsecuregcm.attachments.AttachmentUtil;
import org.whispersystems.textsecuregcm.attachments.TusAttachmentGenerator;
import org.whispersystems.textsecuregcm.auth.AuthenticatedBackupUser;
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicBackupConfiguration;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.configuration.BackupConfiguration;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecoveryClient;
import org.whispersystems.textsecuregcm.attachments.AttachmentUtil;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import org.whispersystems.textsecuregcm.util.Pair;
import org.whispersystems.textsecuregcm.util.ua.UnrecognizedUserAgentException;
@@ -55,7 +54,6 @@ import org.whispersystems.textsecuregcm.util.ua.UserAgentUtil;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Scheduler;
import javax.annotation.Nullable;
public class BackupManager {
@@ -89,7 +87,7 @@ public class BackupManager {
private final ExternalServiceCredentialsGenerator secureValueRecoveryBCredentialsGenerator;
private final SecureValueRecoveryClient secureValueRecoveryBClient;
private final Clock clock;
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
private final BackupConfiguration backupConfiguration;
public BackupManager(
final BackupsDb backupsDb,
@@ -101,7 +99,7 @@ public class BackupManager {
final ExternalServiceCredentialsGenerator secureValueRecoveryBCredentialsGenerator,
final SecureValueRecoveryClient secureValueRecoveryBClient,
final Clock clock,
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
final BackupConfiguration backupConfiguration) {
this.backupsDb = backupsDb;
this.serverSecretParams = serverSecretParams;
this.rateLimiters = rateLimiters;
@@ -111,7 +109,7 @@ public class BackupManager {
this.secureValueRecoveryBClient = secureValueRecoveryBClient;
this.clock = clock;
this.secureValueRecoveryBCredentialsGenerator = secureValueRecoveryBCredentialsGenerator;
this.dynamicConfigurationManager = dynamicConfigurationManager;
this.backupConfiguration = backupConfiguration;
}
@@ -196,8 +194,7 @@ public class BackupManager {
// update message backup TTL
final StoredBackupAttributes storedBackupAttributes = backupsDb.ttlRefresh(backupUser).join();
if (backupUser.credentialType() == BackupCredentialType.MEDIA) {
final long maxTotalMediaSize =
dynamicConfigurationManager.getConfiguration().getBackupConfiguration().maxTotalMediaSize();
final long maxTotalMediaSize = backupConfiguration.maxTotalMediaSize();
// Report that the backup is out of quota if it is within 100MiB of the limit
final boolean quotaExhausted = storedBackupAttributes.bytesUsed() >=
@@ -258,8 +255,6 @@ public class BackupManager {
*/
public Flux<CopyResult> copyToBackup(final CopyQuota copyQuota) {
final AuthenticatedBackupUser backupUser = copyQuota.backupUser();
final DynamicBackupConfiguration backupConfiguration =
dynamicConfigurationManager.getConfiguration().getBackupConfiguration();
return Flux.concat(
@@ -347,8 +342,6 @@ public class BackupManager {
}
final long totalBytesAdded = toCopy.stream().mapToLong(CopyParameters::destinationObjectSize).sum();
final DynamicBackupConfiguration backupConfiguration =
dynamicConfigurationManager.getConfiguration().getBackupConfiguration();
final Duration maxQuotaStaleness = backupConfiguration.maxQuotaStaleness();
final long maxTotalMediaSize = backupConfiguration.maxTotalMediaSize();
@@ -491,8 +484,7 @@ public class BackupManager {
public void deleteEntireBackup(final AuthenticatedBackupUser backupUser) throws BackupPermissionException {
checkBackupLevel(backupUser, BackupLevel.FREE);
final int deletionConcurrency =
dynamicConfigurationManager.getConfiguration().getBackupConfiguration().deletionConcurrency();
final int deletionConcurrency = backupConfiguration.deletionConcurrency();
// Clients only include SVRB data with their messages backup-id
if (backupUser.credentialType() == BackupCredentialType.MESSAGES) {
@@ -523,8 +515,6 @@ public class BackupManager {
if (storageDescriptors.stream().anyMatch(sd -> sd.cdn() != remoteStorageManager.cdnNumber())) {
return Flux.error(new BackupInvalidArgumentException("unsupported media cdn provided"));
}
final DynamicBackupConfiguration backupConfiguration =
dynamicConfigurationManager.getConfiguration().getBackupConfiguration();
return Flux.usingWhen(
@@ -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
@@ -86,7 +88,7 @@ public class Cdn3RemoteStorageManager implements RemoteStorageManager {
public CompletionStage<Void> copy(
final int sourceCdn,
final String sourceKey,
final int expectedSourceLength,
final long expectedSourceLength,
final MediaEncryptionParameters encryptionParameters,
final String destinationKey) {
final String sourceScheme = this.sourceSchemes.get(sourceCdn);
@@ -132,10 +134,10 @@ public class Cdn3RemoteStorageManager implements RemoteStorageManager {
*/
record Cdn3CopyRequest(
String encryptionKey, String hmacKey,
SourceDescriptor source, int expectedSourceLength,
SourceDescriptor source, long expectedSourceLength,
String dst) {
Cdn3CopyRequest(MediaEncryptionParameters parameters, SourceDescriptor source, int expectedSourceLength,
Cdn3CopyRequest(MediaEncryptionParameters parameters, SourceDescriptor source, long expectedSourceLength,
String dst) {
this(Base64.getEncoder().encodeToString(parameters.aesEncryptionKey().getEncoded()),
Base64.getEncoder().encodeToString(parameters.hmacSHA256Key().getEncoded()),
@@ -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 -> {
@@ -18,7 +18,7 @@ import com.google.common.annotations.VisibleForTesting;
public record CopyParameters(
int sourceCdn,
String sourceKey,
int sourceLength,
long sourceLength,
MediaEncryptionParameters encryptionParameters,
byte[] destinationMediaId) {
@@ -35,16 +35,17 @@ public record CopyParameters(
///
/// @return the size, in bytes, of the ciphertext of a media object with the given `inputSize`
@VisibleForTesting
static long destinationObjectSize(final int inputSize) {
static long destinationObjectSize(final long inputSize) {
if (inputSize < 0) {
throw new IllegalArgumentException("Size must be non-negative, but was " + inputSize);
}
// AES-256 has 16-byte block size, and always adds a block if the plaintext is a multiple of the block size
final long numBlocks = ((long) inputSize + 16) / 16;
final long numBlocks = Math.addExact(inputSize, 16L) / 16;
final long cipherTextLength = Math.multiplyExact(numBlocks, 16);
// 16-byte IV will be generated and prepended to the ciphertext
// 16-byte IV will be generated and prepended to the ciphertext.
// IV + AES-256 encrypted data + HmacSHA256
return 16 + (numBlocks * 16) + 32;
return Math.addExact(cipherTextLength, 16L + 32);
}
}
@@ -35,7 +35,7 @@ public interface RemoteStorageManager {
CompletionStage<Void> copy(
int sourceCdn,
String sourceKey,
int expectedSourceLength,
long expectedSourceLength,
MediaEncryptionParameters encryptionParameters,
String dstKey);
@@ -10,5 +10,8 @@ import java.util.Locale;
import org.whispersystems.textsecuregcm.entities.Badge;
public interface BadgeTranslator {
Locale resolveLocale(List<Locale> acceptableLanguages);
Badge translate(List<Locale> acceptableLanguages, String badgeId);
}
@@ -7,7 +7,6 @@ package org.whispersystems.textsecuregcm.badges;
import com.google.common.annotations.VisibleForTesting;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
@@ -31,7 +30,6 @@ public class ConfiguredProfileBadgeConverter implements ProfileBadgeConverter, B
private final Clock clock;
private final Map<String, BadgeConfiguration> knownBadges;
private final List<String> badgeIdsEnabledForAll;
private final HeaderControlledResourceBundleLookup headerControlledResourceBundleLookup;
public ConfiguredProfileBadgeConverter(
@@ -41,10 +39,14 @@ public class ConfiguredProfileBadgeConverter implements ProfileBadgeConverter, B
this.clock = clock;
this.knownBadges = badgesConfiguration.getBadges().stream()
.collect(Collectors.toMap(BadgeConfiguration::getId, Function.identity()));
this.badgeIdsEnabledForAll = badgesConfiguration.getBadgeIdsEnabledForAll();
this.headerControlledResourceBundleLookup = headerControlledResourceBundleLookup;
}
@Override
public Locale resolveLocale(final List<Locale> acceptableLanguages) {
return headerControlledResourceBundleLookup.getResourceBundle(BASE_NAME, acceptableLanguages).getLocale();
}
@Override
public Badge translate(final List<Locale> acceptableLanguages, final String badgeId) {
final ResourceBundle resourceBundle = headerControlledResourceBundleLookup.getResourceBundle(BASE_NAME,
@@ -63,12 +65,27 @@ public class ConfiguredProfileBadgeConverter implements ProfileBadgeConverter, B
false);
}
@Override
public List<String> visibleBadgeIds(final List<AccountBadge> accountBadges) {
if (accountBadges.isEmpty()) {
return List.of();
}
final Instant now = clock.instant();
return accountBadges.stream()
.filter(accountBadge -> accountBadge.visible()
&& now.isBefore(accountBadge.expiration())
&& knownBadges.containsKey(accountBadge.id()))
.map(AccountBadge::id)
.toList();
}
@Override
public List<Badge> convert(
final List<Locale> acceptableLanguages,
final List<AccountBadge> accountBadges,
final boolean isSelf) {
if (accountBadges.isEmpty() && badgeIdsEnabledForAll.isEmpty()) {
if (accountBadges.isEmpty()) {
return List.of();
}
@@ -94,20 +111,6 @@ public class ConfiguredProfileBadgeConverter implements ProfileBadgeConverter, B
accountBadge.visible());
})
.collect(Collectors.toCollection(ArrayList::new));
badges.addAll(badgeIdsEnabledForAll.stream().filter(knownBadges::containsKey).map(id -> {
BadgeConfiguration configuration = knownBadges.get(id);
return newBadge(
isSelf,
id,
configuration.getCategory(),
resourceBundle.getString(id + "_name"),
resourceBundle.getString(id + "_description"),
configuration.getSprites(),
configuration.getSvg(),
configuration.getSvgs(),
now.plus(Duration.ofDays(1)),
true);
}).collect(Collectors.toList()));
return badges;
}
@@ -12,6 +12,12 @@ import org.whispersystems.textsecuregcm.storage.AccountBadge;
public interface ProfileBadgeConverter {
/// Determine displayable badge ids for an account's badges
///
/// @param badges The full list of badges on an account
/// @return The list of badge-ids that should appear on this account's profile to other users
List<String> visibleBadgeIds(final List<AccountBadge> badges);
/**
* Converts the {@link AccountBadge}s for an account into the objects
* that can be returned on a profile fetch.
@@ -100,7 +100,7 @@ public class CaptchaChecker {
final Set<String> allowedSiteKeys = client.validSiteKeys(parsedAction);
if (!allowedSiteKeys.contains(siteKey)) {
logger.debug("invalid site-key {}, action={}, token={}", siteKey, action, token);
logger.debug("invalid site-key {}, action={}", siteKey, action);
Metrics.counter(INVALID_SITEKEY_COUNTER_NAME, "action", action).increment();
throw new InvalidCaptchaArgumentException("invalid captcha site-key");
}
@@ -3,7 +3,7 @@
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration.dynamic;
package org.whispersystems.textsecuregcm.configuration;
import io.dropwizard.util.DataSize;
import jakarta.validation.constraints.NotNull;
@@ -17,14 +17,14 @@ import java.time.Duration;
* @param maxQuotaStaleness The maximum age of a quota estimate that can be used to enforce a quota limit
* @param maxTotalMediaSize The number of media bytes a paid-tier user may store
*/
public record DynamicBackupConfiguration(
public record BackupConfiguration(
@NotNull Integer deletionConcurrency,
@NotNull Integer copyConcurrency,
@NotNull Integer usageCheckpointCount,
@NotNull Duration maxQuotaStaleness,
@NotNull Long maxTotalMediaSize) {
public DynamicBackupConfiguration {
public BackupConfiguration {
if (deletionConcurrency == null) {
deletionConcurrency = 10;
}
@@ -42,7 +42,7 @@ public record DynamicBackupConfiguration(
}
}
public DynamicBackupConfiguration() {
public BackupConfiguration() {
this(null, null, null, null, null);
}
}
@@ -21,16 +21,13 @@ import java.util.stream.Collectors;
public class BadgesConfiguration {
private final List<BadgeConfiguration> badges;
private final List<String> badgeIdsEnabledForAll;
private final Map<Long, String> receiptLevels;
@JsonCreator
public BadgesConfiguration(
@JsonProperty("badges") @JsonSetter(nulls = Nulls.AS_EMPTY) final List<BadgeConfiguration> badges,
@JsonProperty("badgeIdsEnabledForAll") @JsonSetter(nulls = Nulls.AS_EMPTY) final List<String> badgeIdsEnabledForAll,
@JsonProperty("receiptLevels") @JsonSetter(nulls = Nulls.AS_EMPTY) final Map<Long, String> receiptLevels) {
this.badges = Objects.requireNonNull(badges);
this.badgeIdsEnabledForAll = Objects.requireNonNull(badgeIdsEnabledForAll);
this.receiptLevels = Objects.requireNonNull(receiptLevels);
}
@@ -40,12 +37,6 @@ public class BadgesConfiguration {
return badges;
}
@Valid
@NotNull
public List<String> getBadgeIdsEnabledForAll() {
return badgeIdsEnabledForAll;
}
@Valid
@NotNull
public Map<Long, String> getReceiptLevels() {
@@ -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);
}
}
}
@@ -55,6 +55,7 @@ public class DynamoDbTables {
private final Table clientReleases;
private final Table deletedAccounts;
private final Table deletedAccountsLock;
private final TableWithExpiration donationPermits;
private final IssuedReceiptsTableConfiguration issuedReceipts;
private final Table ecKeys;
private final Table ecSignedPreKeys;
@@ -63,6 +64,7 @@ public class DynamoDbTables {
private final TableWithExpiration messages;
private final TableWithExpiration onetimeDonations;
private final Table phoneNumberIdentifiers;
private final Table profileAvatars;
private final Table profiles;
private final Table profilesV2;
private final Table pushChallenge;
@@ -84,6 +86,7 @@ public class DynamoDbTables {
@JsonProperty("clientReleases") final Table clientReleases,
@JsonProperty("deletedAccounts") final Table deletedAccounts,
@JsonProperty("deletedAccountsLock") final Table deletedAccountsLock,
@JsonProperty("donationPermits") final TableWithExpiration donationPermits,
@JsonProperty("issuedReceipts") final IssuedReceiptsTableConfiguration issuedReceipts,
@JsonProperty("ecKeys") final Table ecKeys,
@JsonProperty("ecSignedPreKeys") final Table ecSignedPreKeys,
@@ -92,6 +95,7 @@ public class DynamoDbTables {
@JsonProperty("messages") final TableWithExpiration messages,
@JsonProperty("onetimeDonations") final TableWithExpiration onetimeDonations,
@JsonProperty("phoneNumberIdentifiers") final Table phoneNumberIdentifiers,
@JsonProperty("profileAvatars") final Table profileAvatars,
@JsonProperty("profiles") final Table profiles,
@JsonProperty("profilesV2") final Table profilesV2,
@JsonProperty("pushChallenge") final Table pushChallenge,
@@ -112,6 +116,7 @@ public class DynamoDbTables {
this.clientReleases = clientReleases;
this.deletedAccounts = deletedAccounts;
this.deletedAccountsLock = deletedAccountsLock;
this.donationPermits = donationPermits;
this.issuedReceipts = issuedReceipts;
this.ecKeys = ecKeys;
this.ecSignedPreKeys = ecSignedPreKeys;
@@ -120,6 +125,7 @@ public class DynamoDbTables {
this.messages = messages;
this.onetimeDonations = onetimeDonations;
this.phoneNumberIdentifiers = phoneNumberIdentifiers;
this.profileAvatars = profileAvatars;
this.profiles = profiles;
this.profilesV2 = profilesV2;
this.pushChallenge = pushChallenge;
@@ -181,6 +187,12 @@ public class DynamoDbTables {
return deletedAccountsLock;
}
@NotNull
@Valid
public TableWithExpiration getDonationPermits() {
return donationPermits;
}
@NotNull
@Valid
public IssuedReceiptsTableConfiguration getIssuedReceipts() {
@@ -229,6 +241,12 @@ public class DynamoDbTables {
return phoneNumberIdentifiers;
}
@NotNull
@Valid
public Table getProfileAvatars() {
return profileAvatars;
}
@NotNull
@Valid
public Table getProfilesV1() {
@@ -0,0 +1,65 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration;
import com.apple.foundationdb.Database;
import com.apple.foundationdb.FDB;
import com.fasterxml.jackson.annotation.JsonTypeName;
import jakarta.validation.constraints.NotBlank;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
@JsonTypeName("default")
public record FoundationDbClusterConfiguration(@NotBlank String clusterFileUrl) implements FoundationDbDatabaseFactory {
@Override
public Database build(final FDB fdb) throws IOException {
final URI clusterFileUri = URI.create(clusterFileUrl());
final File clusterFile = switch (clusterFileUri.getScheme()) {
case "file" -> new File(clusterFileUri);
case "http", "https" -> {
try (final HttpClient clusterFileClient = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_1_1)
.connectTimeout(Duration.ofSeconds(10))
.build()) {
final HttpResponse<String> response = clusterFileClient.send(HttpRequest.newBuilder()
.uri(URI.create(clusterFileUrl()))
.timeout(Duration.ofSeconds(10))
.GET()
.build(), HttpResponse.BodyHandlers.ofString());
if (response.statusCode() != 200) {
throw new IOException("Could not load cluster file (status " + response.statusCode() + ")");
}
final File tempClusterFile = File.createTempFile("fdb.cluster-", "");
tempClusterFile.deleteOnExit();
try (final FileWriter fileWriter = new FileWriter(tempClusterFile)) {
fileWriter.write(response.body());
}
yield tempClusterFile;
} catch (final InterruptedException e) {
throw new IOException("Interrupted while waiting for cluster file response", e);
}
}
default -> throw new IllegalArgumentException("Unrecognized cluster file URI scheme: " + clusterFileUri.getScheme());
};
return fdb.open(clusterFile.getAbsolutePath());
}
}
@@ -0,0 +1,18 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration;
import com.apple.foundationdb.Database;
import com.apple.foundationdb.FDB;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import io.dropwizard.jackson.Discoverable;
import java.io.IOException;
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type", defaultImpl = FoundationDbClusterConfiguration.class)
public interface FoundationDbDatabaseFactory extends Discoverable {
Database build(final FDB fdb) throws IOException;
}
@@ -0,0 +1,75 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration;
import jakarta.validation.Valid;
import jakarta.validation.constraints.AssertTrue;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.PositiveOrZero;
import jakarta.validation.constraints.Size;
import java.time.Duration;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import org.whispersystems.textsecuregcm.configuration.secrets.SecretBytes;
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStore;
/// @param transactionTimeout the time limit for a transaction, which may [contain multiple tries](https://forums.foundationdb.org/t/defaults-for-transaction-timeouts-and-retries/315/2).
/// Note that this is independent of the FoundationDB server’s transaction hard limit of 5 seconds.
/// @param transactionRetryLimit the maximum number of retries permitted _within_ a transaction
/// @param batchPriorityTransactionTimeout the maximum time for a batch priority transaction. Should be greater than or equal to {@link transactionTimeout}
/// @param batchPriorityTransactionRetryLimit the maximum number of retries permitted _within_ a batch priority transaction
public record FoundationDbMessagesConfiguration(@NotEmpty Map<String, @Valid FoundationDbDatabaseFactory> clusters,
@NotEmpty Map<@PositiveOrZero @Max(FoundationDbMessageStore.MAX_EPOCHS - 1) Integer, @Size(min = 1, max = FoundationDbMessageStore.MAX_SHARDS - 1) List<String>> epochs,
@PositiveOrZero @Max(FoundationDbMessageStore.MAX_EPOCHS - 1) int activeEpoch,
@NotEmpty Map<@PositiveOrZero @Max(63) Integer, SecretBytes> versionstampCipherKeys,
@PositiveOrZero @Max(63) int currentVersionstampCipherKey,
@PositiveOrZero @Max(1_000_000) long maxWatchesPerClient,
@NotNull Duration transactionTimeout,
@PositiveOrZero long transactionRetryLimit,
@NotNull Duration batchPriorityTransactionTimeout,
@PositiveOrZero long batchPriorityTransactionRetryLimit) {
public static final long DEFAULT_MAX_WATCHES_PER_CLIENT = 10_000;
public static final Duration DEFAULT_TRANSACTION_TIMEOUT = Duration.ofSeconds(1);
public static final long DEFAULT_TRANSACTION_RETRY_LIMIT = 3;
@AssertTrue
boolean isEveryEpochClusterConfigured() {
for (final List<String> clustersInEpoch : epochs().values()) {
for (final String cluster : clustersInEpoch) {
if (!clusters.containsKey(cluster)) {
return false;
}
}
}
return true;
}
@AssertTrue
boolean isEveryEpochFreeOfDuplicates() {
for (final List<String> clustersInEpoch : epochs().values()) {
if (new HashSet<>(clustersInEpoch).size() != clustersInEpoch.size()) {
return false;
}
}
return true;
}
@AssertTrue
boolean isActiveEpochConfigured() {
return epochs().containsKey(activeEpoch());
}
@AssertTrue
boolean isCurrentVersionstampCipherKeyConfigured() {
return versionstampCipherKeys().containsKey(currentVersionstampCipherKey());
}
}
@@ -15,6 +15,5 @@ import java.util.concurrent.ScheduledExecutorService;
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type", defaultImpl = RegistrationServiceConfiguration.class)
public interface RegistrationServiceClientFactory extends Discoverable {
RegistrationServiceClient build(Environment environment, Executor callbackExecutor,
ScheduledExecutorService identityRefreshExecutor);
RegistrationServiceClient build(Environment environment, ScheduledExecutorService identityRefreshExecutor);
}
@@ -5,7 +5,6 @@ import io.dropwizard.core.setup.Environment;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import java.io.IOException;
import java.util.concurrent.Executor;
import java.util.concurrent.ScheduledExecutorService;
import org.whispersystems.textsecuregcm.configuration.secrets.SecretBytes;
import org.whispersystems.textsecuregcm.registration.IdentityTokenCallCredentials;
@@ -21,16 +20,16 @@ public record RegistrationServiceConfiguration(@NotBlank String host,
RegistrationServiceClientFactory {
@Override
public RegistrationServiceClient build(final Environment environment, final Executor callbackExecutor,
public RegistrationServiceClient build(final Environment environment,
final ScheduledExecutorService identityRefreshExecutor) {
try {
final IdentityTokenCallCredentials callCredentials = IdentityTokenCallCredentials.fromCredentialConfig(
credentialConfigurationJson, identityTokenAudience, identityRefreshExecutor);
environment.lifecycle().manage(callCredentials);
return new RegistrationServiceClient(host, port, callCredentials, registrationCaCertificate, collationKeySalt.value(),
identityRefreshExecutor);
return new RegistrationServiceClient(host, port, callCredentials, registrationCaCertificate, collationKeySalt.value());
} catch (IOException e) {
throw new RuntimeException(e);
}
@@ -7,6 +7,7 @@ package org.whispersystems.textsecuregcm.configuration.dynamic;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.Valid;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
@@ -68,10 +69,6 @@ public class DynamicConfiguration {
@Valid
DynamicRestDeprecationConfiguration restDeprecation = new DynamicRestDeprecationConfiguration(Map.of());
@JsonProperty
@Valid
private DynamicBackupConfiguration backup = new DynamicBackupConfiguration();
@JsonProperty
@Valid
private DynamicCarrierDataLookupConfiguration carrierDataLookup = new DynamicCarrierDataLookupConfiguration();
@@ -80,6 +77,10 @@ public class DynamicConfiguration {
@Valid
private DynamicGrpcAllowListConfiguration grpcAllowList = new DynamicGrpcAllowListConfiguration();
@JsonProperty
@Valid
private DynamicOmnibusConfiguration omnibus = new DynamicOmnibusConfiguration(BigDecimal.ZERO);
@JsonProperty
@Valid
private DynamicTurnConfiguration turn = new DynamicTurnConfiguration();
@@ -138,10 +139,6 @@ public class DynamicConfiguration {
return restDeprecation;
}
public DynamicBackupConfiguration getBackupConfiguration() {
return backup;
}
public DynamicCarrierDataLookupConfiguration getCarrierDataLookupConfiguration() {
return carrierDataLookup;
}
@@ -150,6 +147,10 @@ public class DynamicConfiguration {
return grpcAllowList;
}
public DynamicOmnibusConfiguration getOmnibus() {
return omnibus;
}
public DynamicTurnConfiguration getTurnConfiguration() {
return turn;
}
@@ -0,0 +1,13 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration.dynamic;
import jakarta.validation.constraints.DecimalMax;
import jakarta.validation.constraints.DecimalMin;
import java.math.BigDecimal;
/// @param rejectConnectionRatio The proportion of connection attempts that should be immediately closed with a GOAWAY
public record DynamicOmnibusConfiguration(@DecimalMin("0.0") @DecimalMax("1.0") BigDecimal rejectConnectionRatio) {
}
@@ -389,7 +389,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)));
@@ -19,6 +19,7 @@ import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.ForbiddenException;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.HeaderParam;
import jakarta.ws.rs.NotAuthorizedException;
import jakarta.ws.rs.PUT;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
@@ -28,11 +29,16 @@ import jakarta.ws.rs.container.ContainerRequestContext;
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.Instant;
import java.util.UUID;
import org.apache.commons.lang3.StringUtils;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.ChangesPhoneNumber;
import org.whispersystems.textsecuregcm.auth.InvalidRegistrationSessionException;
import org.whispersystems.textsecuregcm.auth.RecoveryPasswordVerificationFailedException;
import org.whispersystems.textsecuregcm.auth.RegistrationLockFailureException;
import org.whispersystems.textsecuregcm.auth.UnverifiedRegistrationSessionException;
import org.whispersystems.textsecuregcm.entities.AccountDataReportResponse;
import org.whispersystems.textsecuregcm.entities.AccountIdentityResponse;
import org.whispersystems.textsecuregcm.entities.ChangeNumberRequest;
@@ -40,6 +46,7 @@ import org.whispersystems.textsecuregcm.entities.MismatchedDevicesResponse;
import org.whispersystems.textsecuregcm.entities.PhoneNumberDiscoverabilityRequest;
import org.whispersystems.textsecuregcm.entities.RegistrationLockFailure;
import org.whispersystems.textsecuregcm.entities.StaleDevicesResponse;
import org.whispersystems.textsecuregcm.filters.RemoteAddressFilter;
import org.whispersystems.textsecuregcm.push.MessageTooLargeException;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
@@ -80,7 +87,8 @@ public class AccountControllerV2 {
public AccountIdentityResponse changeNumber(@Auth final AuthenticatedDevice authenticatedDevice,
@NotNull @Valid final ChangeNumberRequest request,
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgentString,
@Context final ContainerRequestContext requestContext) throws RateLimitExceededException, InterruptedException {
@Context final ContainerRequestContext requestContext)
throws RateLimitExceededException, InterruptedException, RegistrationLockFailureException {
if (authenticatedDevice.deviceId() != Device.PRIMARY_ID) {
throw new ForbiddenException();
@@ -102,7 +110,9 @@ public class AccountControllerV2 {
request.devicePniPqLastResortPrekeys(),
request.deviceMessages(),
request.pniRegistrationIds(),
requestContext);
userAgentString,
requestContext.getHeaderString(HttpHeaders.ACCEPT_LANGUAGE),
(String) requestContext.getProperty(RemoteAddressFilter.REMOTE_ADDRESS_ATTRIBUTE_NAME));
return AccountIdentityResponseBuilder.fromAccount(updatedAccount);
} catch (final MismatchedDevicesException e) {
@@ -124,6 +134,14 @@ public class AccountControllerV2 {
throw new WebApplicationException(Response.Status.REQUEST_ENTITY_TOO_LARGE);
} catch (final MessageDeliveryNotAllowedException e) {
throw new ServiceUnavailableException();
} catch (final UnverifiedRegistrationSessionException e) {
throw new NotAuthorizedException("registration session is unverified");
} catch (final InvalidRegistrationSessionException e) {
throw new BadRequestException(e.getMessage());
} catch (final IOException e) {
throw new ServiceUnavailableException(e.getMessage());
} catch (final RecoveryPasswordVerificationFailedException e) {
throw new ForbiddenException("recovery password could not be verified");
}
}
@@ -156,7 +174,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,9 +47,9 @@ 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,
@@ -5,16 +5,21 @@
package org.whispersystems.textsecuregcm.controllers;
import com.google.common.net.HttpHeaders;
import io.dropwizard.auth.Auth;
import io.micrometer.core.instrument.DistributionSummary;
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.headers.Header;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Positive;
import jakarta.ws.rs.ClientErrorException;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.HeaderParam;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.QueryParam;
@@ -24,6 +29,7 @@ import java.security.SecureRandom;
import java.util.Map;
import java.util.Optional;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.whispersystems.textsecuregcm.attachments.AttachmentGenerator;
import org.whispersystems.textsecuregcm.attachments.AttachmentUtil;
import org.whispersystems.textsecuregcm.attachments.GcsAttachmentGenerator;
@@ -33,6 +39,8 @@ import org.whispersystems.textsecuregcm.entities.AttachmentDescriptorV3;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.limits.RateLimiter;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
/**
@@ -40,7 +48,7 @@ import org.whispersystems.textsecuregcm.limits.RateLimiters;
* (message attachments) to a remote storage location. The location may be selected by the server at runtime.
*/
@Path("/v4/attachments")
@Tag(name = "Attachments")
@io.swagger.v3.oas.annotations.tags.Tag(name = "Attachments")
public class AttachmentControllerV4 {
private final ExperimentEnrollmentManager experimentEnrollmentManager;
@@ -50,6 +58,9 @@ public class AttachmentControllerV4 {
private final Map<Integer, AttachmentGenerator> attachmentGenerators;
private static final String ATTACHMENT_SIZE_NAME =
MetricsUtil.name(AttachmentControllerV4.class, "attachmentSize");
@Nonnull
private final SecureRandom secureRandom;
@@ -91,7 +102,8 @@ public class AttachmentControllerV4 {
public AttachmentDescriptorV3 getAttachmentUploadForm(
@Auth AuthenticatedDevice auth,
@Parameter(description = "The size of the attachment to upload in bytes")
@QueryParam("uploadLength") final @Valid Optional<@Positive Long> maybeUploadLength)
@QueryParam("uploadLength") final @Valid Optional<@Positive Long> maybeUploadLength,
@HeaderParam(HttpHeaders.USER_AGENT) @Nullable final String userAgent)
throws RateLimitExceededException {
final long uploadLength = maybeUploadLength.orElse(maxUploadLength);
@@ -111,6 +123,12 @@ public class AttachmentControllerV4 {
}
}
DistributionSummary.builder(ATTACHMENT_SIZE_NAME)
.tags(Tags.of(UserAgentTagUtil.getPlatformTag(userAgent),
Tag.of("uploadLengthSupplied", Boolean.toString(maybeUploadLength.isPresent()))))
.register(Metrics.globalRegistry)
.record(uploadLength);
final String key = AttachmentUtil.generateAttachmentKey(secureRandom);
final boolean useCdn3 = this.experimentEnrollmentManager.isEnrolled(auth.accountIdentifier(), AttachmentUtil.CDN3_EXPERIMENT_NAME);
int cdn = useCdn3 ? 3 : 2;
@@ -41,7 +41,6 @@ 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
@@ -196,7 +196,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 +206,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));
}
@@ -240,7 +240,7 @@ public class DeviceController {
final DeviceActivationRequest deviceActivationRequest = linkDeviceRequest.deviceActivationRequest();
final DeviceAttributes deviceAttributes = linkDeviceRequest.deviceAttributes();
rateLimiters.getVerifyDeviceLimiter().validate(account.getUuid());
rateLimiters.getVerifyDeviceLimiter().validate(account.getAccountIdentifier());
final boolean allKeysValid =
PreKeySignatureValidator.validatePreKeySignatures(account.getIdentityKey(IdentityType.ACI),
@@ -11,6 +11,7 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import jakarta.ws.rs.BadRequestException;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
@@ -21,18 +22,23 @@ import jakarta.ws.rs.core.Response.Status;
import java.time.Clock;
import java.time.Instant;
import java.util.Objects;
import javax.annotation.Nonnull;
import org.glassfish.jersey.server.ManagedAsync;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.VerificationFailedException;
import org.signal.libsignal.zkgroup.donation.DonationPermitRequest;
import org.signal.libsignal.zkgroup.donation.DonationPermitResponse;
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialPresentation;
import org.signal.libsignal.zkgroup.receipts.ReceiptSerial;
import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.configuration.BadgesConfiguration;
import org.whispersystems.textsecuregcm.entities.CreateDonationPermitResponse;
import org.whispersystems.textsecuregcm.entities.CreateDonationPermitsRequest;
import org.whispersystems.textsecuregcm.entities.RedeemReceiptRequest;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.storage.AccountBadge;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.DonationPermitsManager;
import org.whispersystems.textsecuregcm.storage.RedeemedReceiptsManager;
import org.whispersystems.textsecuregcm.subscriptions.ReceiptCredentialPresentationFactory;
@@ -46,20 +52,26 @@ public class DonationController {
private final AccountsManager accountsManager;
private final BadgesConfiguration badgesConfiguration;
private final ReceiptCredentialPresentationFactory receiptCredentialPresentationFactory;
private final DonationPermitsManager donationPermitsManager;
private final RateLimiters rateLimiters;
public DonationController(
@Nonnull final Clock clock,
@Nonnull final ServerZkReceiptOperations serverZkReceiptOperations,
@Nonnull final RedeemedReceiptsManager redeemedReceiptsManager,
@Nonnull final AccountsManager accountsManager,
@Nonnull final BadgesConfiguration badgesConfiguration,
@Nonnull final ReceiptCredentialPresentationFactory receiptCredentialPresentationFactory) {
final Clock clock,
final ServerZkReceiptOperations serverZkReceiptOperations,
final RedeemedReceiptsManager redeemedReceiptsManager,
final AccountsManager accountsManager,
final BadgesConfiguration badgesConfiguration,
final ReceiptCredentialPresentationFactory receiptCredentialPresentationFactory,
final DonationPermitsManager donationPermitsManager,
final RateLimiters rateLimiters) {
this.clock = Objects.requireNonNull(clock);
this.serverZkReceiptOperations = Objects.requireNonNull(serverZkReceiptOperations);
this.redeemedReceiptsManager = Objects.requireNonNull(redeemedReceiptsManager);
this.accountsManager = Objects.requireNonNull(accountsManager);
this.badgesConfiguration = Objects.requireNonNull(badgesConfiguration);
this.receiptCredentialPresentationFactory = Objects.requireNonNull(receiptCredentialPresentationFactory);
this.donationPermitsManager = Objects.requireNonNull(donationPermitsManager);
this.rateLimiters = Objects.requireNonNull(rateLimiters);
}
@POST
@@ -131,4 +143,34 @@ public class DonationController {
return Response.ok().build();
}
@POST
@Path("/permit")
@Produces({MediaType.APPLICATION_JSON})
@Operation(
summary = "Generate permits for anonymous donation endpoints",
description = """
Generate a set of anonymous, single-use, permits for use with /v1/subscription endpoints.
""")
@ApiResponse(responseCode = "200", description = "`JSON` with generated credentials", useReturnTypeSchema = true)
@ApiResponse(responseCode = "400", description = "Invalid credential request")
@ApiResponse(responseCode = "401", description = "Account authentication check failed")
@ApiResponse(responseCode = "422", description = "Invalid request format")
@ApiResponse(responseCode = "429", description = "Rate-limited; reduce requested permit count and/or try again after the prescribed delay")
public CreateDonationPermitResponse createPermits(@Auth final AuthenticatedDevice auth,
@NotNull @Valid final CreateDonationPermitsRequest request) throws RateLimitExceededException {
final DonationPermitRequest permitRequest;
try {
permitRequest = new DonationPermitRequest(request.permitRequest());
} catch (InvalidInputException e) {
throw new BadRequestException();
}
rateLimiters.getCreateDonationPermitLimiter().validate(auth.accountIdentifier(), permitRequest.getPermitCount());
final DonationPermitResponse permitResponse = donationPermitsManager.issue(permitRequest);
return new CreateDonationPermitResponse(permitResponse.serialize());
}
}
@@ -33,6 +33,8 @@ import org.glassfish.jersey.server.ManagedAsync;
import org.signal.keytransparency.client.AciMonitorRequest;
import org.signal.keytransparency.client.E164MonitorRequest;
import org.signal.keytransparency.client.E164SearchRequest;
import org.signal.keytransparency.client.MonitorResponseV2;
import org.signal.keytransparency.client.SearchResponseV2;
import org.signal.keytransparency.client.UsernameHashMonitorRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -73,7 +75,7 @@ public class KeyTransparencyController {
"""
)
@ApiResponse(responseCode = "200", description = "The ACI was found and its mapped value matched the provided ACI identity key", useReturnTypeSchema = true)
@ApiResponse(responseCode = "400", description = "Invalid request. See response for any available details.")
@ApiResponse(responseCode = "400", description = "Request was authenticated but endpoint requires unauthenticated access.")
@ApiResponse(responseCode = "403", description = """
The ACI was found but its mapped value did not match the provided ACI identity key
or the ACI was not found in the log.
@@ -101,15 +103,23 @@ public class KeyTransparencyController {
.build()
));
return new KeyTransparencySearchResponse(
keyTransparencyServiceClient.search(
ByteString.copyFrom(request.aci().toCompactByteArray()),
ByteString.copyFrom(request.aciIdentityKey().serialize()),
request.usernameHash().map(ByteString::copyFrom),
maybeE164SearchRequest,
request.lastTreeHeadSize(),
request.distinguishedTreeHeadSize())
.toByteArray());
final SearchResponseV2 searchResponse = keyTransparencyServiceClient.search(
ByteString.copyFrom(request.aci().toCompactByteArray()),
ByteString.copyFrom(request.aciIdentityKey().serialize()),
request.usernameHash().map(ByteString::copyFrom),
maybeE164SearchRequest,
request.lastTreeHeadSize(),
request.distinguishedTreeHeadSize());
if (searchResponse.hasPermissionDenied()) {
throw new StatusRuntimeException(Status.PERMISSION_DENIED);
}
if (!searchResponse.hasSearchResponse()) {
throw new StatusRuntimeException(Status.UNAVAILABLE.withDescription("Missing search response"));
}
return new KeyTransparencySearchResponse(searchResponse.getSearchResponse().toByteArray());
} catch (final StatusRuntimeException exception) {
handleKeyTransparencyServiceError(exception);
}
@@ -125,7 +135,7 @@ public class KeyTransparencyController {
"""
)
@ApiResponse(responseCode = "200", description = "All identifiers exist in the log", useReturnTypeSchema = true)
@ApiResponse(responseCode = "400", description = "Invalid request. See response for any available details.")
@ApiResponse(responseCode = "400", description = "Request was authenticated but endpoint requires unauthenticated access.")
@ApiResponse(responseCode = "403", description = "One or more of the provided commitment indexes did not match")
@ApiResponse(responseCode = "404", description = "At least one identifier was not found")
@ApiResponse(responseCode = "429", description = "Rate-limited")
@@ -163,13 +173,22 @@ public class KeyTransparencyController {
.setCommitmentIndex(ByteString.copyFrom(e164.commitmentIndex()))
.build());
return new KeyTransparencyMonitorResponse(keyTransparencyServiceClient.monitor(
final MonitorResponseV2 monitorResponse = keyTransparencyServiceClient.monitor(
aciMonitorRequest,
usernameHashMonitorRequest,
e164MonitorRequest,
request.lastNonDistinguishedTreeHeadSize(),
request.lastDistinguishedTreeHeadSize())
.toByteArray());
request.lastDistinguishedTreeHeadSize());
if (monitorResponse.hasPermissionDenied()) {
throw new StatusRuntimeException(Status.PERMISSION_DENIED);
}
if (!monitorResponse.hasMonitorResponse()) {
throw new StatusRuntimeException(Status.UNAVAILABLE.withDescription("Missing monitor response"));
}
return new KeyTransparencyMonitorResponse(monitorResponse.getMonitorResponse().toByteArray());
} catch (final StatusRuntimeException exception) {
handleKeyTransparencyServiceError(exception);
}
@@ -186,7 +205,7 @@ public class KeyTransparencyController {
"""
)
@ApiResponse(responseCode = "200", description = "The `distinguished` search key exists in the log", useReturnTypeSchema = true)
@ApiResponse(responseCode = "400", description = "Invalid request. See response for any available details.")
@ApiResponse(responseCode = "400", description = "Request was authenticated but endpoint requires unauthenticated access.")
@ApiResponse(responseCode = "422", description = "Invalid request format")
@ApiResponse(responseCode = "429", description = "Rate-limited")
@GET
@@ -426,7 +426,7 @@ public class KeysController {
.flatMap(targetAccount::getDevice)
.map(device -> device.getRegistrationId(targetIdentifier.identityType()));
return RateLimitKeys.preKeyLimiterKey(
account.getUuid(),
account.getAccountIdentifier(),
authenticatedDevice.deviceId(),
targetIdentifier,
parsedTargetDeviceId, targetRegistrationId);
@@ -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,
@@ -744,7 +744,7 @@ public class MessageController {
sourceNumber = Optional.of(source);
final Optional<Account> maybeAccount = accountsManager.getByE164(source);
if (maybeAccount.isPresent()) {
sourceAci = maybeAccount.map(Account::getUuid);
sourceAci = maybeAccount.map(Account::getAccountIdentifier);
sourcePni = maybeAccount.map(Account::getPhoneNumberIdentifier);
} else {
sourcePni = Optional.ofNullable(phoneNumberIdentifiers.getPhoneNumberIdentifier(source).join());
@@ -4,13 +4,17 @@
*/
package org.whispersystems.textsecuregcm.controllers;
import static org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil.getClientPlatform;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.google.common.net.HttpHeaders;
import com.stripe.model.PaymentIntent;
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.StringToClassMapItem;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
@@ -31,19 +35,18 @@ import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
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;
@@ -52,10 +55,14 @@ import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.DonationPermitHeader;
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration;
import org.whispersystems.textsecuregcm.grpc.OneTimeDonationUtil;
import org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil;
import org.whispersystems.textsecuregcm.limits.RateLimitedByIp;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.storage.DonationPermitsManager;
import org.whispersystems.textsecuregcm.storage.IssuedReceiptsManager;
import org.whispersystems.textsecuregcm.storage.OneTimeDonationsManager;
import org.whispersystems.textsecuregcm.storage.WriteConflictException;
@@ -68,13 +75,10 @@ import org.whispersystems.textsecuregcm.subscriptions.PaymentMethod;
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
import org.whispersystems.textsecuregcm.subscriptions.PaymentStatus;
import org.whispersystems.textsecuregcm.subscriptions.StripeManager;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionCurrencyUtil;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidAmountException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorException;
import org.whispersystems.textsecuregcm.util.ExactlySize;
import org.whispersystems.textsecuregcm.util.HeaderUtils;
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
import org.whispersystems.textsecuregcm.util.ua.UnrecognizedUserAgentException;
import org.whispersystems.textsecuregcm.util.ua.UserAgentUtil;
/**
* Endpoints for making one-time donation payments (boost and gift)
@@ -89,8 +93,6 @@ public class OneTimeDonationController {
private static final Logger logger = LoggerFactory.getLogger(OneTimeDonationController.class);
private static final String EURO_CURRENCY_CODE = "EUR";
private final Clock clock;
private final OneTimeDonationConfiguration oneTimeDonationConfiguration;
private final StripeManager stripeManager;
@@ -99,16 +101,18 @@ public class OneTimeDonationController {
private final ServerZkReceiptOperations zkReceiptOperations;
private final IssuedReceiptsManager issuedReceiptsManager;
private final OneTimeDonationsManager oneTimeDonationsManager;
private final DonationPermitsManager donationPermitsManager;
public OneTimeDonationController(
@Nonnull Clock clock,
@Nonnull OneTimeDonationConfiguration oneTimeDonationConfiguration,
@Nonnull StripeManager stripeManager,
@Nonnull BraintreeManager braintreeManager,
@Nonnull PayPalDonationsTranslator payPalDonationsTranslator,
@Nonnull ServerZkReceiptOperations zkReceiptOperations,
@Nonnull IssuedReceiptsManager issuedReceiptsManager,
@Nonnull OneTimeDonationsManager oneTimeDonationsManager) {
final Clock clock,
final OneTimeDonationConfiguration oneTimeDonationConfiguration,
final StripeManager stripeManager,
final BraintreeManager braintreeManager,
final PayPalDonationsTranslator payPalDonationsTranslator,
final ServerZkReceiptOperations zkReceiptOperations,
final IssuedReceiptsManager issuedReceiptsManager,
final OneTimeDonationsManager oneTimeDonationsManager,
final DonationPermitsManager donationPermitsManager) {
this.clock = Objects.requireNonNull(clock);
this.oneTimeDonationConfiguration = Objects.requireNonNull(oneTimeDonationConfiguration);
this.stripeManager = Objects.requireNonNull(stripeManager);
@@ -117,6 +121,7 @@ public class OneTimeDonationController {
this.zkReceiptOperations = Objects.requireNonNull(zkReceiptOperations);
this.issuedReceiptsManager = Objects.requireNonNull(issuedReceiptsManager);
this.oneTimeDonationsManager = Objects.requireNonNull(oneTimeDonationsManager);
this.donationPermitsManager = Objects.requireNonNull(donationPermitsManager);
}
public static class CreateBoostRequest {
@@ -147,10 +152,10 @@ public class OneTimeDonationController {
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Operation(summary = "Create a Stripe payment intent", description = """
Create a Stripe PaymentIntent and return a client secret that can be used to complete the payment.
Once the payment is complete, the paymentIntentId can be used at /v1/subscriptions/receipt_credentials
""")
Create a Stripe PaymentIntent and return a client secret that can be used to complete the payment.
Once the payment is complete, the paymentIntentId can be used at /v1/subscriptions/receipt_credentials
""")
@ApiResponse(responseCode = "200", description = "Payment Intent created", content = @Content(schema = @Schema(implementation = CreateBoostResponse.class)))
@ApiResponse(responseCode = "403", description = "The request was made on an authenticated channel")
@ApiResponse(responseCode = "400", description = """
@@ -164,65 +169,72 @@ public class OneTimeDonationController {
properties = {
@StringToClassMapItem(key = "error", value = String.class)
})))
@ApiResponse(responseCode = "401", description = "Donation permit was invalid or already spent")
@RateLimitedByIp(RateLimiters.For.ONE_TIME_DONATION)
public CompletableFuture<Response> createBoostPaymentIntent(
@Auth Optional<AuthenticatedDevice> authenticatedAccount,
@NotNull @Valid CreateBoostRequest request,
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent) {
@ManagedAsync
public CreateBoostResponse createBoostPaymentIntent(
@Auth final Optional<AuthenticatedDevice> authenticatedAccount,
@Parameter(description = "A base64-encoded donation permit retrieved from POST /v1/donation/permit")
@HeaderParam(HeaderUtils.DONATION_PERMIT) final Optional<DonationPermitHeader> donationPermitHeader,
@NotNull @Valid final CreateBoostRequest request,
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent) throws SubscriptionInvalidAmountException {
if (authenticatedAccount.isPresent()) {
throw new ForbiddenException("must not use authenticated connection for one-time donation operations");
}
return CompletableFuture.runAsync(() ->
validateRequestCurrencyAmount(request, BigDecimal.valueOf(request.amount), stripeManager))
.thenCompose(_ -> stripeManager.createPaymentIntent(request.currency, request.amount, request.level,
getClientPlatform(userAgent)))
.thenApply(paymentIntent -> Response.ok(new CreateBoostResponse(paymentIntent.getClientSecret())).build());
SubscriptionsUtil.recordDonationPermitPresent(donationPermitHeader.isPresent(), "boostCreate", userAgent);
final boolean spendSuccessful = donationPermitHeader.map(
permitHeader -> {
try {
return SubscriptionsUtil.verifyAndSpendDonationPermit(permitHeader.permit(), donationPermitsManager, clock);
} catch (final VerificationFailedException e) {
return false;
}
})
.orElse(false);
if (!spendSuccessful) {
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
}
validateRequestCurrencyAmount(request, BigDecimal.valueOf(request.amount), stripeManager);
final PaymentIntent paymentIntent = stripeManager.createPaymentIntent(request.currency, request.amount,
request.level,
getClientPlatform(userAgent));
return new CreateBoostResponse(paymentIntent.getClientSecret());
}
/**
* Validates that the request level is valid, the currency is supported by the {@code manager} and {@code request.paymentMethod},
* and that the amount meets minimum and maximum constraints.
* Validates that the request level is valid, the currency is supported by the {@code manager} and
* {@code request.paymentMethod}, and that the amount meets minimum and maximum constraints.
*
* @throws BadRequestException indicates validation failed. Inspect {@code response.error} for details
*/
private void validateRequestCurrencyAmount(final CreateBoostRequest request, final BigDecimal amount,
final CustomerAwareSubscriptionPaymentProcessor manager) {
if (!(request.level == oneTimeDonationConfiguration.gift().level()
|| request.level == oneTimeDonationConfiguration.boost().level())) {
final Map<String, String> errorBody = switch (OneTimeDonationUtil.validateOneTimeDonationRequest(request.currency,
amount, request.level, request.paymentMethod, oneTimeDonationConfiguration, manager)) {
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.UnsupportedLevel _ ->
Map.of("error", "invalid_level");
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.UnsupportedCurrency _ ->
Map.of("error", "unsupported_currency");
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.AmountBelowMinimum(final BigDecimal min) ->
Map.of("error", "amount_below_currency_minimum",
"minimum", min.toString());
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.AmountAboveSepaLimit(final BigDecimal max) ->
Map.of("error", "amount_above_sepa_limit",
"maximum", max.toString());
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.Success _ -> Collections.emptyMap();
};
if (!errorBody.isEmpty()) {
throw new BadRequestException(
Response.status(Response.Status.BAD_REQUEST).entity(Map.of("error", "invalid_level")).build());
Response.status(Response.Status.BAD_REQUEST).entity(errorBody).build());
}
if (!manager.getSupportedCurrenciesForPaymentMethod(request.paymentMethod)
.contains(request.currency.toLowerCase(Locale.ROOT))) {
throw new BadRequestException(Response.status(Response.Status.BAD_REQUEST)
.entity(Map.of("error", "unsupported_currency")).build());
}
final BigDecimal minCurrencyAmountMajorUnits = oneTimeDonationConfiguration.currencies()
.get(request.currency.toLowerCase(Locale.ROOT)).minimum();
final BigDecimal minCurrencyAmountMinorUnits = SubscriptionCurrencyUtil.convertConfiguredAmountToApiAmount(
request.currency,
minCurrencyAmountMajorUnits);
if (minCurrencyAmountMinorUnits.compareTo(amount) > 0) {
throw new BadRequestException(Response.status(Response.Status.BAD_REQUEST)
.entity(Map.of(
"error", "amount_below_currency_minimum",
"minimum", minCurrencyAmountMajorUnits.toString())).build());
}
if (request.paymentMethod == PaymentMethod.SEPA_DEBIT &&
amount.compareTo(SubscriptionCurrencyUtil.convertConfiguredAmountToApiAmount(
EURO_CURRENCY_CODE,
oneTimeDonationConfiguration.sepaMaximumEuros())) > 0) {
throw new BadRequestException(Response.status(Response.Status.BAD_REQUEST)
.entity(Map.of(
"error", "amount_above_sepa_limit",
"maximum", oneTimeDonationConfiguration.sepaMaximumEuros().toString())).build());
}
}
public static class CreatePayPalBoostRequest extends CreateBoostRequest {
@@ -237,44 +249,32 @@ public class OneTimeDonationController {
}
}
record CreatePayPalBoostResponse(String approvalUrl, String paymentId) {}
public record CreatePayPalBoostResponse(String approvalUrl, String paymentId) {}
@POST
@Path("/paypal/create")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public CompletableFuture<Response> createPayPalBoost(
@Auth Optional<AuthenticatedDevice> authenticatedAccount,
@NotNull @Valid CreatePayPalBoostRequest request,
@Context ContainerRequestContext containerRequestContext) {
@ManagedAsync
public CreatePayPalBoostResponse createPayPalBoost(
@Auth final Optional<AuthenticatedDevice> authenticatedAccount,
@NotNull @Valid final CreatePayPalBoostRequest request,
@Context final ContainerRequestContext containerRequestContext) throws IOException {
if (authenticatedAccount.isPresent()) {
throw new ForbiddenException("must not use authenticated connection for one-time donation operations");
}
return CompletableFuture.runAsync(() ->
validateRequestCurrencyAmount(request, BigDecimal.valueOf(request.amount), braintreeManager))
.thenCompose(_ -> {
final List<Locale> acceptableLanguages =
HeaderUtils.getAcceptableLanguagesForRequest(containerRequestContext);
// These two localizations are a best-effort, and it's possible that the first `locale` and the localized line
// item name will not match. We could try to align with the locales PayPal documents <https://developer.paypal.com/reference/locale-codes/#supported-locale-codes>
// but that's a moving target, and we can hopefully have one of them be better for the user by selecting
// independently.
final Locale locale = acceptableLanguages.stream()
.filter(l -> !"*".equals(l.getLanguage()))
.findFirst()
.orElse(Locale.US);
final String localizedLineItemName = payPalDonationsTranslator.translate(acceptableLanguages,
PayPalDonationsTranslator.ONE_TIME_DONATION_LINE_ITEM_KEY);
return braintreeManager.createOneTimePayment(request.currency.toUpperCase(Locale.ROOT), request.amount,
locale.toLanguageTag(),
request.returnUrl, request.cancelUrl, localizedLineItemName);
})
.thenApply(approvalDetails -> Response.ok(
new CreatePayPalBoostResponse(approvalDetails.approvalUrl(), approvalDetails.paymentId())).build());
validateRequestCurrencyAmount(request, BigDecimal.valueOf(request.amount), braintreeManager);
final List<Locale> acceptableLanguages =
HeaderUtils.getAcceptableLanguagesForRequest(containerRequestContext);
final OneTimeDonationUtil.LocalizedPayPalDonationLineItem localizedLineItem = OneTimeDonationUtil.localizePayPalDonationLineItem(
payPalDonationsTranslator, acceptableLanguages);
final BraintreeManager.PayPalOneTimePaymentApprovalDetails approvalDetails =
braintreeManager.createOneTimePayment(request.currency.toUpperCase(Locale.ROOT), request.amount,
localizedLineItem.locale().toLanguageTag(),
request.returnUrl, request.cancelUrl, localizedLineItem.itemName());
return new CreatePayPalBoostResponse(approvalDetails.approvalUrl(), approvalDetails.paymentId());
}
public static class ConfirmPayPalBoostRequest extends CreateBoostRequest {
@@ -291,30 +291,28 @@ public class OneTimeDonationController {
}
}
record ConfirmPayPalBoostResponse(String paymentId) {}
public record ConfirmPayPalBoostResponse(String paymentId) {}
@POST
@Path("/paypal/confirm")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public CompletableFuture<Response> confirmPayPalBoost(
@Auth Optional<AuthenticatedDevice> authenticatedAccount,
@NotNull @Valid ConfirmPayPalBoostRequest request,
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent) {
@ManagedAsync
public ConfirmPayPalBoostResponse confirmPayPalBoost(
@Auth final Optional<AuthenticatedDevice> authenticatedAccount,
@NotNull @Valid final ConfirmPayPalBoostRequest request,
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent) throws SubscriptionProcessorException, IOException {
if (authenticatedAccount.isPresent()) {
throw new ForbiddenException("must not use authenticated connection for one-time donation operations");
}
return CompletableFuture.runAsync(() ->
validateRequestCurrencyAmount(request, BigDecimal.valueOf(request.amount), braintreeManager))
.thenCompose(_ -> braintreeManager.captureOneTimePayment(request.payerId, request.paymentId,
request.paymentToken, request.currency, request.amount, request.level, getClientPlatform(userAgent)))
.thenApply(chargeSuccessDetails -> {
oneTimeDonationsManager.putPaidAt(chargeSuccessDetails.paymentId(), Instant.now());
return Response.ok(
new ConfirmPayPalBoostResponse(chargeSuccessDetails.paymentId())).build();
});
validateRequestCurrencyAmount(request, BigDecimal.valueOf(request.amount), braintreeManager);
final BraintreeManager.PayPalChargeSuccessDetails chargeSuccessDetails = braintreeManager.captureOneTimePayment(
request.payerId, request.paymentId,
request.paymentToken, request.currency, request.amount, request.level, getClientPlatform(userAgent));
oneTimeDonationsManager.putPaidAt(chargeSuccessDetails.paymentId(), Instant.now());
return new ConfirmPayPalBoostResponse(chargeSuccessDetails.paymentId());
}
public static class CreateBoostReceiptCredentialsRequest {
@@ -341,98 +339,76 @@ public class OneTimeDonationController {
@Path("/receipt_credentials")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public CompletableFuture<Response> createBoostReceiptCredentials(
@Auth Optional<AuthenticatedDevice> authenticatedAccount,
@ManagedAsync
public Response createBoostReceiptCredentials(
@Auth final Optional<AuthenticatedDevice> authenticatedAccount,
@NotNull @Valid final CreateBoostReceiptCredentialsRequest request,
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent) {
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent) throws IOException {
if (authenticatedAccount.isPresent()) {
throw new ForbiddenException("must not use authenticated connection for one-time donation operations");
}
final CompletableFuture<PaymentDetails> paymentDetailsFut = switch (request.processor) {
final Optional<PaymentDetails> maybePaymentDetails = (switch (request.processor) {
case STRIPE -> stripeManager.getPaymentDetails(request.paymentIntentId);
case BRAINTREE -> braintreeManager.getPaymentDetails(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");
};
return paymentDetailsFut.thenApply(paymentDetails -> {
if (paymentDetails == null) {
throw new WebApplicationException(Response.Status.NOT_FOUND);
} else if (paymentDetails.status() == PaymentStatus.PROCESSING) {
return Response.noContent().build();
} else if (paymentDetails.status() != PaymentStatus.SUCCEEDED) {
throw new WebApplicationException(Response.status(Response.Status.PAYMENT_REQUIRED)
.entity(new CreateBoostReceiptCredentialsErrorResponse(paymentDetails.chargeFailure())).build());
}
// The payment was successful, try to issue the receipt credential
long level = oneTimeDonationConfiguration.boost().level();
if (paymentDetails.customMetadata() != null) {
String levelMetadata = paymentDetails.customMetadata()
.getOrDefault("level", Long.toString(oneTimeDonationConfiguration.boost().level()));
try {
level = Long.parseLong(levelMetadata);
} catch (NumberFormatException e) {
logger.error("failed to parse level metadata ({}) on payment intent {}", levelMetadata,
paymentDetails.id(), e);
throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
}
}
Duration levelExpiration;
if (oneTimeDonationConfiguration.boost().level() == level) {
levelExpiration = oneTimeDonationConfiguration.boost().expiration();
} else if (oneTimeDonationConfiguration.gift().level() == level) {
levelExpiration = oneTimeDonationConfiguration.gift().expiration();
} else {
logger.error("level ({}) returned from payment intent that is unknown to the server", level);
throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
}
ReceiptCredentialRequest receiptCredentialRequest;
try {
receiptCredentialRequest = new ReceiptCredentialRequest(request.receiptCredentialRequest);
} catch (InvalidInputException e) {
throw new BadRequestException("invalid receipt credential request", e);
}
final long finalLevel = level;
try {
issuedReceiptsManager.recordIssuance(paymentDetails.id(), request.processor,
receiptCredentialRequest, clock.instant());
} catch (final WriteConflictException _) {
throw new WebApplicationException(Response.Status.CONFLICT);
}
final Instant paidAt = oneTimeDonationsManager.getPaidAt(paymentDetails.id(), paymentDetails.created());
final Instant expiration = paidAt
.plus(levelExpiration)
.truncatedTo(ChronoUnit.DAYS)
.plus(1, ChronoUnit.DAYS);
final ReceiptCredentialResponse receiptCredentialResponse;
try {
receiptCredentialResponse = zkReceiptOperations.issueReceiptCredential(
receiptCredentialRequest, expiration.getEpochSecond(), finalLevel);
} catch (final VerificationFailedException e) {
throw new BadRequestException("receipt credential request failed verification", e);
}
Metrics.counter(SubscriptionController.RECEIPT_ISSUED_COUNTER_NAME,
Tags.of(
Tag.of(SubscriptionController.PROCESSOR_TAG_NAME, request.processor.toString()),
Tag.of(SubscriptionController.TYPE_TAG_NAME, "boost"),
UserAgentTagUtil.getPlatformTag(userAgent)))
.increment();
return Response.ok(
new CreateBoostReceiptCredentialsSuccessResponse(receiptCredentialResponse.serialize()))
.build();
});
}
@Nullable
private static ClientPlatform getClientPlatform(@Nullable final String userAgentString) {
try {
return UserAgentUtil.parseUserAgentString(userAgentString).platform();
} catch (final UnrecognizedUserAgentException e) {
return null;
if (maybePaymentDetails.isEmpty()) {
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
final PaymentDetails paymentDetails = maybePaymentDetails.get();
if (paymentDetails.status() == PaymentStatus.PROCESSING) {
return Response.noContent().build();
}
if (paymentDetails.status() != PaymentStatus.SUCCEEDED) {
throw new WebApplicationException(Response.status(Response.Status.PAYMENT_REQUIRED)
.entity(new CreateBoostReceiptCredentialsErrorResponse(paymentDetails.chargeFailure())).build());
}
// The payment was successful, try to issue the receipt credential
final OneTimeDonationUtil.DonationLevelDetails levelDetails;
try {
levelDetails = OneTimeDonationUtil.getLevelDetails(paymentDetails, oneTimeDonationConfiguration);
} catch (OneTimeDonationUtil.InvalidLevelException _) {
throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
}
final ReceiptCredentialRequest receiptCredentialRequest;
try {
receiptCredentialRequest = new ReceiptCredentialRequest(request.receiptCredentialRequest);
} 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 expiration = paidAt
.plus(levelDetails.levelExpiration())
.truncatedTo(ChronoUnit.DAYS)
.plus(1, ChronoUnit.DAYS);
final ReceiptCredentialResponse receiptCredentialResponse;
try {
receiptCredentialResponse = zkReceiptOperations.issueReceiptCredential(
receiptCredentialRequest, expiration.getEpochSecond(), levelDetails.level());
} catch (final VerificationFailedException e) {
throw new BadRequestException("receipt credential request failed verification", e);
}
Metrics.counter(SubscriptionController.RECEIPT_ISSUED_COUNTER_NAME,
Tags.of(
Tag.of(SubscriptionController.PROCESSOR_TAG_NAME, request.processor.toString()),
Tag.of(SubscriptionController.TYPE_TAG_NAME, "boost"),
UserAgentTagUtil.getPlatformTag(userAgent)))
.increment();
return Response.ok(
new CreateBoostReceiptCredentialsSuccessResponse(receiptCredentialResponse.serialize()))
.build();
}
}
@@ -39,7 +39,6 @@ import jakarta.ws.rs.core.Response;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Clock;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
@@ -88,7 +87,6 @@ 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.s3.PolicySigner;
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountBadge;
@@ -114,7 +112,6 @@ public class ProfileController {
private final ProfileBadgeConverter profileBadgeConverter;
private final Map<String, BadgeConfiguration> badgeConfigurationMap;
private final PolicySigner policySigner;
private final PostPolicyGenerator policyGenerator;
private final ServerSecretParams serverSecretParams;
private final ServerZkProfileOperations zkProfileOperations;
@@ -135,7 +132,6 @@ public class ProfileController {
ProfileBadgeConverter profileBadgeConverter,
BadgesConfiguration badgesConfiguration,
PostPolicyGenerator policyGenerator,
PolicySigner policySigner,
ServerSecretParams serverSecretParams,
ServerZkProfileOperations zkProfileOperations,
Executor batchIdentityCheckExecutor) {
@@ -150,7 +146,6 @@ public class ProfileController {
this.serverSecretParams = serverSecretParams;
this.zkProfileOperations = zkProfileOperations;
this.policyGenerator = policyGenerator;
this.policySigner = policySigner;
this.batchIdentityCheckExecutor = Preconditions.checkNotNull(batchIdentityCheckExecutor);
}
@@ -250,7 +245,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);
}
@@ -291,7 +286,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,
@@ -346,7 +341,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);
};
@@ -431,13 +426,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);
@@ -460,7 +455,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
@@ -503,7 +498,7 @@ public class ProfileController {
HeaderUtils.getAcceptableLanguagesForRequest(containerRequestContext),
account.getBadges(),
isSelf),
new AciServiceIdentifier(account.getUuid()));
new AciServiceIdentifier(account.getAccountIdentifier()));
}
private BaseProfileResponse buildBaseProfileResponseForPhoneNumberIdentity(final Account account) {
@@ -542,7 +537,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);
@@ -553,20 +548,18 @@ public class ProfileController {
return maybeTargetAccount.get();
}
private ProfileAvatarUploadAttributes generateAvatarUploadForm(
final String objectName) {
ZonedDateTime now = ZonedDateTime.now(clock);
Pair<String, String> policy = policyGenerator.createFor(now, objectName, ProfileHelper.MAX_PROFILE_AVATAR_SIZE_BYTES);
String signature = policySigner.getSignature(now, policy.second());
private ProfileAvatarUploadAttributes generateAvatarUploadForm(final String objectName) {
final PostPolicyGenerator.SignedPostPolicy signedPostPolicy =
policyGenerator.createFor(objectName, ProfileHelper.MAX_PROFILE_AVATAR_SIZE_BYTES, clock.instant());
return new ProfileAvatarUploadAttributes(objectName, policy.first(),
"private", "AWS4-HMAC-SHA256",
now.format(PostPolicyGenerator.AWS_DATE_TIME), policy.second(), signature);
return new ProfileAvatarUploadAttributes(objectName, signedPostPolicy.credential(),
PostPolicyGenerator.ACL, PostPolicyGenerator.ALGORITHM,
signedPostPolicy.formattedTimestamp(), signedPostPolicy.encodedPolicy(), signedPostPolicy.signature());
}
private static Map<String, Boolean> getAccountCapabilities(final Account account) {
return Arrays.stream(DeviceCapability.values())
.filter(DeviceCapability::includeInProfile)
.filter(DeviceCapability::includeInLegacyProfile)
.collect(Collectors.toMap(DeviceCapability::getName, account::hasCapability));
}
}
@@ -19,16 +19,21 @@ 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.HeaderParam;
import jakarta.ws.rs.NotAuthorizedException;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.ServiceUnavailableException;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.container.ContainerRequestContext;
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.Duration;
import java.time.Instant;
import java.util.ArrayList;
@@ -38,13 +43,18 @@ import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.auth.BasicAuthorizationHeader;
import org.whispersystems.textsecuregcm.auth.InvalidRegistrationSessionException;
import org.whispersystems.textsecuregcm.auth.PhoneVerificationTokenManager;
import org.whispersystems.textsecuregcm.auth.RecoveryPasswordVerificationFailedException;
import org.whispersystems.textsecuregcm.auth.RegistrationLockFailureException;
import org.whispersystems.textsecuregcm.auth.RegistrationLockVerificationManager;
import org.whispersystems.textsecuregcm.auth.UnverifiedRegistrationSessionException;
import org.whispersystems.textsecuregcm.entities.AccountCreationResponse;
import org.whispersystems.textsecuregcm.entities.AccountIdentityResponse;
import org.whispersystems.textsecuregcm.entities.PhoneVerificationRequest;
import org.whispersystems.textsecuregcm.entities.RegistrationLockFailure;
import org.whispersystems.textsecuregcm.entities.RegistrationRequest;
import org.whispersystems.textsecuregcm.filters.RemoteAddressFilter;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.spam.RegistrationFraudChecker;
@@ -116,7 +126,8 @@ public class RegistrationController {
@HeaderParam(HeaderUtils.X_SIGNAL_AGENT) final String signalAgent,
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
@NotNull @Valid final RegistrationRequest registrationRequest,
@Context final ContainerRequestContext requestContext) throws RateLimitExceededException, InterruptedException {
@Context final ContainerRequestContext requestContext)
throws RateLimitExceededException, InterruptedException, RegistrationLockFailureException {
final String number = authorizationHeader.getUsername();
final String password = authorizationHeader.getPassword();
@@ -134,11 +145,24 @@ public class RegistrationController {
rateLimiters.getRegistrationLimiter().validate(number);
final PhoneVerificationRequest.VerificationType verificationType =
phoneVerificationTokenManager.verify(requestContext,
number,
StringUtils.isNotBlank(registrationRequest.sessionId()) ? registrationRequest.decodeSessionId() : null,
registrationRequest.recoveryPassword());
final PhoneVerificationRequest.VerificationType verificationType;
try {
verificationType = phoneVerificationTokenManager.verify(
number,
requestContext.getHeaderString(HttpHeaders.USER_AGENT),
requestContext.getHeaderString(HttpHeaders.ACCEPT_LANGUAGE),
(String) requestContext.getProperty(RemoteAddressFilter.REMOTE_ADDRESS_ATTRIBUTE_NAME),
StringUtils.isNotBlank(registrationRequest.sessionId()) ? registrationRequest.decodeSessionId() : null,
registrationRequest.recoveryPassword());
} catch (final UnverifiedRegistrationSessionException e) {
throw new NotAuthorizedException("registration session is unverified");
} catch (final InvalidRegistrationSessionException e) {
throw new BadRequestException(e.getMessage());
} catch (final IOException e) {
throw new ServiceUnavailableException(e.getMessage());
} catch (final RecoveryPasswordVerificationFailedException e) {
throw new ForbiddenException("recovery password could not be verified");
}
// There can be at most one existing account for a set of numbers in the same equivalence class, so it's sufficient
// to find the first one.
@@ -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);
@@ -6,6 +6,7 @@
package org.whispersystems.textsecuregcm.controllers;
import io.dropwizard.auth.Auth;
import io.dropwizard.util.DataSize;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
@@ -15,8 +16,8 @@ import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import java.security.SecureRandom;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.Clock;
import java.time.Instant;
import java.util.HexFormat;
import java.util.LinkedList;
import java.util.List;
@@ -24,23 +25,25 @@ import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.entities.StickerPackFormUploadAttributes;
import org.whispersystems.textsecuregcm.entities.StickerPackFormUploadAttributes.StickerPackFormUploadItem;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.s3.PolicySigner;
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
import org.whispersystems.textsecuregcm.util.Constants;
import org.whispersystems.textsecuregcm.util.Pair;
@Path("/v1/sticker")
@Tag(name = "Stickers")
public class StickerController {
private final RateLimiters rateLimiters;
private final PolicySigner policySigner;
private final PostPolicyGenerator policyGenerator;
private final Clock clock;
public StickerController(RateLimiters rateLimiters, String accessKey, String accessSecret, String region, String bucket) {
public static final int MAXIMUM_STICKER_SIZE_BYTES = (int) DataSize.kibibytes(300 + 1).toBytes(); // add 1 kiB for encryption overhead
public static final int MAXIMUM_STICKER_MANIFEST_SIZE_BYTES = (int) DataSize.kibibytes(10).toBytes();
public StickerController(final RateLimiters rateLimiters,
final PostPolicyGenerator postPolicyGenerator,
final Clock clock) {
this.rateLimiters = rateLimiters;
this.policySigner = new PolicySigner(accessSecret, region);
this.policyGenerator = new PostPolicyGenerator(region, bucket, accessKey);
this.policyGenerator = postPolicyGenerator;
this.clock = clock;
}
@GET
@@ -51,33 +54,32 @@ public class StickerController {
throws RateLimitExceededException {
rateLimiters.getStickerPackLimiter().validate(auth.accountIdentifier());
ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC);
String packId = generatePackId();
String packLocation = "stickers/" + packId;
String manifestKey = packLocation + "/manifest.proto";
Pair<String, String> manifestPolicy = policyGenerator.createFor(now, manifestKey,
Constants.MAXIMUM_STICKER_MANIFEST_SIZE_BYTES);
String manifestSignature = policySigner.getSignature(now, manifestPolicy.second());
StickerPackFormUploadItem manifest = new StickerPackFormUploadItem(-1, manifestKey, manifestPolicy.first(),
"private", "AWS4-HMAC-SHA256",
now.format(PostPolicyGenerator.AWS_DATE_TIME), manifestPolicy.second(), manifestSignature);
final Instant currentTime = clock.instant();
final String packId = generatePackId();
final String packLocation = "stickers/" + packId;
final String manifestKey = packLocation + "/manifest.proto";
final PostPolicyGenerator.SignedPostPolicy manifestPolicy =
policyGenerator.createFor(manifestKey, MAXIMUM_STICKER_MANIFEST_SIZE_BYTES, currentTime);
List<StickerPackFormUploadItem> stickers = new LinkedList<>();
final StickerPackFormUploadItem manifest = new StickerPackFormUploadItem(-1, manifestKey, manifestPolicy.credential(),
PostPolicyGenerator.ACL, PostPolicyGenerator.ALGORITHM,
manifestPolicy.formattedTimestamp(), manifestPolicy.encodedPolicy(), manifestPolicy.signature());
final List<StickerPackFormUploadItem> stickers = new LinkedList<>();
for (int i = 0; i < stickerCount; i++) {
String stickerKey = packLocation + "/full/" + i;
Pair<String, String> stickerPolicy = policyGenerator.createFor(now, stickerKey,
Constants.MAXIMUM_STICKER_SIZE_BYTES);
String stickerSignature = policySigner.getSignature(now, stickerPolicy.second());
stickers.add(new StickerPackFormUploadItem(i, stickerKey, stickerPolicy.first(), "private", "AWS4-HMAC-SHA256",
now.format(PostPolicyGenerator.AWS_DATE_TIME), stickerPolicy.second(), stickerSignature));
final String stickerKey = packLocation + "/full/" + i;
final PostPolicyGenerator.SignedPostPolicy stickerPolicy =
policyGenerator.createFor(stickerKey, MAXIMUM_STICKER_SIZE_BYTES, currentTime);
stickers.add(new StickerPackFormUploadItem(i, stickerKey, stickerPolicy.credential(), PostPolicyGenerator.ACL, PostPolicyGenerator.ALGORITHM,
manifestPolicy.formattedTimestamp(), stickerPolicy.encodedPolicy(), stickerPolicy.signature()));
}
return new StickerPackFormUploadAttributes(packId, manifest, stickers);
}
private String generatePackId() {
byte[] object = new byte[16];
final byte[] object = new byte[16];
new SecureRandom().nextBytes(object);
return HexFormat.of().formatHex(object);
@@ -5,6 +5,11 @@
package org.whispersystems.textsecuregcm.controllers;
import static org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil.buildCurrencyConfiguration;
import static org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil.buildDonationLevelsConfiguration;
import static org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil.getClientPlatform;
import static org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil.getPayPalLocale;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.google.common.annotations.VisibleForTesting;
@@ -15,6 +20,7 @@ import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import io.swagger.v3.oas.annotations.ExternalDocumentation;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.headers.Header;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
@@ -36,44 +42,40 @@ import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.core.Context;
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;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.glassfish.jersey.server.ManagedAsync;
import org.signal.libsignal.zkgroup.VerificationFailedException;
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.OneTimeDonationConfiguration;
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationCurrencyConfiguration;
import org.whispersystems.textsecuregcm.configuration.SubscriptionConfiguration;
import org.whispersystems.textsecuregcm.configuration.SubscriptionLevelConfiguration;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.entities.Badge;
import org.whispersystems.textsecuregcm.entities.PurchasableBadge;
import org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil;
import org.whispersystems.textsecuregcm.limits.RateLimitedByIp;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.mappers.SubscriptionExceptionMapper;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.storage.PaymentTime;
import org.whispersystems.textsecuregcm.storage.DonationPermitsManager;
import org.whispersystems.textsecuregcm.storage.SubscriberCredentials;
import org.whispersystems.textsecuregcm.storage.SubscriptionManager;
import org.whispersystems.textsecuregcm.storage.Subscriptions;
@@ -82,8 +84,10 @@ import org.whispersystems.textsecuregcm.subscriptions.BankMandateTranslator;
import org.whispersystems.textsecuregcm.subscriptions.BankTransferType;
import org.whispersystems.textsecuregcm.subscriptions.BraintreeManager;
import org.whispersystems.textsecuregcm.subscriptions.ChargeFailure;
import org.whispersystems.textsecuregcm.subscriptions.CurrencyConfiguration;
import org.whispersystems.textsecuregcm.subscriptions.CustomerAwareSubscriptionPaymentProcessor;
import org.whispersystems.textsecuregcm.subscriptions.GooglePlayBillingManager;
import org.whispersystems.textsecuregcm.subscriptions.LevelConfiguration;
import org.whispersystems.textsecuregcm.subscriptions.PaymentMethod;
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
import org.whispersystems.textsecuregcm.subscriptions.ProcessorCustomer;
@@ -94,9 +98,6 @@ import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidLevelEx
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentRequiresActionException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptRequestedForOpenPaymentException;
import org.whispersystems.textsecuregcm.util.HeaderUtils;
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
import org.whispersystems.textsecuregcm.util.ua.UnrecognizedUserAgentException;
import org.whispersystems.textsecuregcm.util.ua.UserAgentUtil;
@Path("/v1/subscription")
@io.swagger.v3.oas.annotations.tags.Tag(name = "Subscriptions")
@@ -112,24 +113,26 @@ public class SubscriptionController {
private final AppleAppStoreManager appleAppStoreManager;
private final BadgeTranslator badgeTranslator;
private final BankMandateTranslator bankMandateTranslator;
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
private final DonationPermitsManager donationPermitsManager;
private final long backupMediaStorageAllowanceBytes;
static final String RECEIPT_ISSUED_COUNTER_NAME = MetricsUtil.name(SubscriptionController.class, "receiptIssued");
static final String PROCESSOR_TAG_NAME = "processor";
static final String TYPE_TAG_NAME = "type";
private static final String SUBSCRIPTION_TYPE_TAG_NAME = "subscriptionType";
public SubscriptionController(
@Nonnull Clock clock,
@Nonnull SubscriptionConfiguration subscriptionConfiguration,
@Nonnull OneTimeDonationConfiguration oneTimeDonationConfiguration,
@Nonnull SubscriptionManager subscriptionManager,
@Nonnull StripeManager stripeManager,
@Nonnull BraintreeManager braintreeManager,
@Nonnull GooglePlayBillingManager googlePlayBillingManager,
@Nonnull AppleAppStoreManager appleAppStoreManager,
@Nonnull BadgeTranslator badgeTranslator,
@Nonnull BankMandateTranslator bankMandateTranslator,
@NotNull DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
Clock clock,
SubscriptionConfiguration subscriptionConfiguration,
OneTimeDonationConfiguration oneTimeDonationConfiguration,
SubscriptionManager subscriptionManager,
StripeManager stripeManager,
BraintreeManager braintreeManager,
GooglePlayBillingManager googlePlayBillingManager,
AppleAppStoreManager appleAppStoreManager,
BadgeTranslator badgeTranslator,
BankMandateTranslator bankMandateTranslator,
DonationPermitsManager donationPermitsManager,
long backupMediaStorageAllowanceBytes) {
this.subscriptionManager = subscriptionManager;
this.clock = Objects.requireNonNull(clock);
this.subscriptionConfiguration = Objects.requireNonNull(subscriptionConfiguration);
@@ -140,91 +143,29 @@ public class SubscriptionController {
this.appleAppStoreManager = appleAppStoreManager;
this.badgeTranslator = Objects.requireNonNull(badgeTranslator);
this.bankMandateTranslator = Objects.requireNonNull(bankMandateTranslator);
this.dynamicConfigurationManager = dynamicConfigurationManager;
this.donationPermitsManager = donationPermitsManager;
this.backupMediaStorageAllowanceBytes = backupMediaStorageAllowanceBytes;
}
private Map<String, CurrencyConfiguration> buildCurrencyConfiguration() {
final List<CustomerAwareSubscriptionPaymentProcessor> subscriptionPaymentProcessors = List.of(stripeManager, braintreeManager);
return oneTimeDonationConfiguration.currencies()
.entrySet().stream()
.collect(Collectors.toMap(Entry::getKey, currencyAndConfig -> {
final String currency = currencyAndConfig.getKey();
final OneTimeDonationCurrencyConfiguration currencyConfig = currencyAndConfig.getValue();
final Map<String, List<BigDecimal>> oneTimeLevelsToSuggestedAmounts = Map.of(
String.valueOf(oneTimeDonationConfiguration.boost().level()), currencyConfig.boosts(),
String.valueOf(oneTimeDonationConfiguration.gift().level()), List.of(currencyConfig.gift())
);
final Function<Map<Long, ? extends SubscriptionLevelConfiguration>, Map<String, BigDecimal>> extractSubscriptionAmounts = levels ->
levels.entrySet().stream()
.filter(levelIdAndConfig -> levelIdAndConfig.getValue().prices().containsKey(currency))
.collect(Collectors.toMap(
levelIdAndConfig -> String.valueOf(levelIdAndConfig.getKey()),
levelIdAndConfig -> levelIdAndConfig.getValue().prices().get(currency).amount()));
final List<String> supportedPaymentMethods = Arrays.stream(PaymentMethod.values())
.filter(paymentMethod -> subscriptionPaymentProcessors.stream()
.anyMatch(manager -> manager.supportsPaymentMethod(paymentMethod)
&& manager.getSupportedCurrenciesForPaymentMethod(paymentMethod).contains(currency)))
.map(PaymentMethod::name)
.collect(Collectors.toList());
if (supportedPaymentMethods.isEmpty()) {
throw new RuntimeException("Configuration has currency with no processor support: " + currency);
}
return new CurrencyConfiguration(
currencyConfig.minimum(),
oneTimeLevelsToSuggestedAmounts,
extractSubscriptionAmounts.apply(subscriptionConfiguration.getDonationLevels()),
extractSubscriptionAmounts.apply(subscriptionConfiguration.getBackupLevels()),
supportedPaymentMethods);
}));
}
@VisibleForTesting
GetSubscriptionConfigurationResponse buildGetSubscriptionConfigurationResponse(
final List<Locale> acceptableLanguages) {
final Map<String, LevelConfiguration> donationLevels = new HashMap<>();
subscriptionConfiguration.getDonationLevels().forEach((levelId, levelConfig) -> {
final LevelConfiguration levelConfiguration = new LevelConfiguration(
"" /* deprecated and unused */,
badgeTranslator.translate(acceptableLanguages, levelConfig.badge()));
donationLevels.put(String.valueOf(levelId), levelConfiguration);
});
final Badge boostBadge = badgeTranslator.translate(acceptableLanguages,
oneTimeDonationConfiguration.boost().badge());
donationLevels.put(String.valueOf(oneTimeDonationConfiguration.boost().level()),
new LevelConfiguration(
"" /* deprecated and unused */,
// NB: the one-time badges are PurchasableBadge, which has a `duration` field
new PurchasableBadge(
boostBadge,
oneTimeDonationConfiguration.boost().expiration())));
final Badge giftBadge = badgeTranslator.translate(acceptableLanguages, oneTimeDonationConfiguration.gift().badge());
donationLevels.put(String.valueOf(oneTimeDonationConfiguration.gift().level()),
new LevelConfiguration(
"" /* deprecated and unused */,
new PurchasableBadge(
giftBadge,
oneTimeDonationConfiguration.gift().expiration())));
final long maxTotalBackupMediaBytes =
dynamicConfigurationManager.getConfiguration().getBackupConfiguration().maxTotalMediaSize();
final Map<String, BackupLevelConfiguration> backupLevels = subscriptionConfiguration.getBackupLevels()
.entrySet().stream()
.collect(Collectors.toMap(
e -> String.valueOf(e.getKey()),
e -> new BackupLevelConfiguration(
maxTotalBackupMediaBytes,
backupMediaStorageAllowanceBytes,
e.getValue().playProductId(),
e.getValue().mediaTtl().toDays())));
return new GetSubscriptionConfigurationResponse(buildCurrencyConfiguration(), donationLevels,
return new GetSubscriptionConfigurationResponse(
buildCurrencyConfiguration(List.of(stripeManager, braintreeManager), oneTimeDonationConfiguration,
subscriptionConfiguration),
buildDonationLevelsConfiguration(subscriptionConfiguration, oneTimeDonationConfiguration, badgeTranslator,
acceptableLanguages),
new BackupConfiguration(backupLevels, subscriptionConfiguration.getbackupFreeTierMediaDuration().toDays()),
oneTimeDonationConfiguration.sepaMaximumEuros());
}
@@ -267,15 +208,35 @@ public class SubscriptionController {
period of time will result in the subscription being canceled.
""")
@ApiResponse(responseCode = "200", description = "The subscriber was successfully created or refreshed")
@ApiResponse(responseCode = "401", description = "Donation permit was invalid or already spent")
@ApiResponse(responseCode = "403", description = "subscriberId authentication failure OR account authentication is present")
@ApiResponse(responseCode = "404", description = "subscriberId is malformed")
@ManagedAsync
public Response updateSubscriber(
@Auth Optional<AuthenticatedDevice> authenticatedAccount,
@Parameter(description="A base64-encoded donation permit retrieved from POST /v1/donation/permit. Not required if the subscriber already exists.")
@HeaderParam(HeaderUtils.DONATION_PERMIT)
final Optional<DonationPermitHeader> donationPermitHeader,
@HeaderParam(HttpHeaders.USER_AGENT) @Nullable final String userAgent,
@PathParam("subscriberId") String subscriberId) throws SubscriptionException {
SubscriberCredentials subscriberCredentials =
SubscriberCredentials.process(authenticatedAccount, subscriberId, clock);
subscriptionManager.updateSubscriber(subscriberCredentials);
SubscriptionsUtil.recordDonationPermitPresent(donationPermitHeader.isPresent(), "putSubscriber", userAgent);
final boolean creationPermitted = donationPermitHeader.map(
permitHeader -> {
try {
return SubscriptionsUtil.verifyAndSpendDonationPermit(permitHeader.permit(), donationPermitsManager, clock);
} catch (VerificationFailedException e) {
return false;
}
})
.orElse(false);
subscriptionManager.updateSubscriber(subscriberCredentials, creationPermitted);
return Response.ok().build();
}
@@ -287,10 +248,25 @@ public class SubscriptionController {
@Path("/{subscriberId}/create_payment_method")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Operation(summary = "Create a payment method", description = """
Creates a payment method setup token with the payment processor and returns a client secret that can be used to
complete the payment method setup.
""")
@ApiResponse(responseCode = "200", description = "The payment method was created", content = @Content(schema = @Schema(implementation = CreatePaymentMethodResponse.class)))
@ApiResponse(responseCode = "400", description = "The requested payment method type is not supported by this endpoint")
@ApiResponse(responseCode = "401", description = "Donation permit was invalid or already spent")
@ApiResponse(responseCode = "403", description = "subscriberId authentication failure OR account authentication is present")
@ApiResponse(responseCode = "404", description = "subscriberId is malformed OR the subscriber does not exist")
@ApiResponse(responseCode = "409", description = "The subscriber is already associated with a different payment processor")
@ManagedAsync
@RateLimitedByIp(RateLimiters.For.ADD_SUBSCRIPTION_PAYMENT_METHOD)
public CreatePaymentMethodResponse createPaymentMethod(
@Auth Optional<AuthenticatedDevice> authenticatedAccount,
@Parameter(description="A base64-encoded donation permit retrieved from POST /v1/donation/permit")
@HeaderParam(HeaderUtils.DONATION_PERMIT)
final Optional<DonationPermitHeader> donationPermitHeader,
@PathParam("subscriberId") String subscriberId,
@QueryParam("type") @DefaultValue("CARD") PaymentMethod paymentMethodType,
@HeaderParam(HttpHeaders.USER_AGENT) @Nullable final String userAgentString) throws SubscriptionException {
@@ -308,6 +284,21 @@ public class SubscriptionController {
case UNKNOWN -> throw new BadRequestException("Invalid payment method");
};
SubscriptionsUtil.recordDonationPermitPresent(donationPermitHeader.isPresent(), "createPaymentMethod", userAgentString);
final boolean spendSuccessful = donationPermitHeader.map(
permitHeader -> {
try {
return SubscriptionsUtil.verifyAndSpendDonationPermit(permitHeader.permit(), donationPermitsManager, clock);
} catch (VerificationFailedException e) {
return false;
}
})
.orElse(false);
if (!spendSuccessful) {
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
}
final String token = subscriptionManager.addPaymentMethodToCustomer(
subscriberCredentials,
customerAwareSubscriptionPaymentProcessor,
@@ -332,23 +323,19 @@ public class SubscriptionController {
@PathParam("subscriberId") String subscriberId,
@NotNull @Valid CreatePayPalBillingAgreementRequest request,
@Context ContainerRequestContext containerRequestContext,
@HeaderParam(HttpHeaders.USER_AGENT) @Nullable final String userAgentString) throws SubscriptionException {
@HeaderParam(HttpHeaders.USER_AGENT) @Nullable final String userAgentString)
throws SubscriptionException, IOException {
final SubscriberCredentials subscriberCredentials =
SubscriberCredentials.process(authenticatedAccount, subscriberId, clock);
final Locale locale = HeaderUtils.getAcceptableLanguagesForRequest(containerRequestContext).stream()
.filter(l -> !"*".equals(l.getLanguage()))
.findFirst()
.orElse(Locale.US);
final Locale locale = getPayPalLocale(HeaderUtils.getAcceptableLanguagesForRequest(containerRequestContext));
final BraintreeManager.PayPalBillingAgreementApprovalDetails billingAgreementApprovalDetails = subscriptionManager.addPaymentMethodToCustomer(
subscriberCredentials,
braintreeManager,
getClientPlatform(userAgentString),
(mgr, customerId) ->
mgr.createPayPalBillingAgreement(request.returnUrl, request.cancelUrl, locale.toLanguageTag()))
.join();
return new CreatePayPalBillingAgreementResponse(
(mgr, _) -> mgr.createPayPalBillingAgreement(request.returnUrl, request.cancelUrl, locale.toLanguageTag()));
return new CreatePayPalBillingAgreementResponse(
billingAgreementApprovalDetails.approvalUrl(),
billingAgreementApprovalDetails.billingAgreementToken());
}
@@ -370,7 +357,7 @@ public class SubscriptionController {
@Auth Optional<AuthenticatedDevice> authenticatedAccount,
@PathParam("subscriberId") String subscriberId,
@PathParam("processor") PaymentProvider processor,
@PathParam("paymentMethodToken") @NotEmpty String paymentMethodToken) throws SubscriptionException {
@PathParam("paymentMethodToken") @NotEmpty String paymentMethodToken) throws SubscriptionException, IOException {
SubscriberCredentials subscriberCredentials =
SubscriberCredentials.process(authenticatedAccount, subscriberId, clock);
@@ -542,33 +529,12 @@ public class SubscriptionController {
@Schema(description = "A map of lower-cased ISO 3 currency codes to minimums and level-specific scalar amounts")
Map<String, CurrencyConfiguration> currencies,
@Schema(description = "A map of numeric donation level IDs to level-specific badge configuration")
Map<String, LevelConfiguration> levels,
Map<Long, LevelConfiguration> levels,
@Schema(description = "Backup specific configuration")
BackupConfiguration backup,
@Schema(description = "The maximum value of a one-time donation SEPA transaction")
BigDecimal sepaMaximumEuros) {}
@Schema(description = "Configuration for a currency - use to present appropriate client interfaces")
public record CurrencyConfiguration(
@Schema(description = "The minimum amount that may be submitted for a one-time donation in the currency")
BigDecimal minimum,
@Schema(description = "A map of numeric one-time donation level IDs to the list of default amounts to be presented")
Map<String, List<BigDecimal>> oneTime,
@Schema(description = "A map of numeric subscription level IDs to the amount charged for that level")
Map<String, BigDecimal> subscription,
@Schema(description = "A map of numeric backup level IDs to the amount charged for that level")
Map<String, BigDecimal> backupSubscription,
@Schema(description = "The payment methods that support the given currency")
List<String> supportedPaymentMethods) {}
@Schema(description = "Configuration for a donation level - use to present appropriate client interfaces")
public record LevelConfiguration(
@Deprecated(forRemoval = true) // may be removed after 2025-01-28
@Schema(description = "The localized name for the level")
String name,
@Schema(description = "The displayable badge associated with the level")
Badge badge) {}
public record BackupConfiguration(
@Schema(description = "A map of numeric backup level IDs to level-specific backup configuration")
Map<String, BackupLevelConfiguration> levels,
@@ -768,7 +734,8 @@ public class SubscriptionController {
SubscriberCredentials subscriberCredentials = SubscriberCredentials.process(authenticatedAccount, subscriberId, clock);
try {
final SubscriptionManager.ReceiptResult receiptCredential = subscriptionManager.createReceiptCredentials(
subscriberCredentials, request, this::receiptExpirationWithGracePeriod);
subscriberCredentials, request.receiptCredentialRequest(),
r -> SubscriptionsUtil.receiptExpirationWithGracePeriod(subscriptionConfiguration, r));
final ReceiptCredentialResponse receiptCredentialResponse = receiptCredential.receiptCredentialResponse();
final CustomerAwareSubscriptionPaymentProcessor.ReceiptItem receipt = receiptCredential.receiptItem();
@@ -794,18 +761,18 @@ public class SubscriptionController {
public Response setDefaultPaymentMethodForIdeal(
@Auth Optional<AuthenticatedDevice> authenticatedAccount,
@PathParam("subscriberId") String subscriberId,
@PathParam("setupIntentId") @NotEmpty String setupIntentId) throws SubscriptionException {
@PathParam("setupIntentId") @NotEmpty String setupIntentId) throws SubscriptionException, IOException {
SubscriberCredentials subscriberCredentials =
SubscriberCredentials.process(authenticatedAccount, subscriberId, clock);
final String generatedSepaId = stripeManager.getGeneratedSepaIdFromSetupIntent(setupIntentId).join();
final String generatedSepaId = stripeManager.getGeneratedSepaIdFromSetupIntent(setupIntentId);
setDefaultPaymentMethod(stripeManager, generatedSepaId, subscriberCredentials);
return Response.ok().build();
}
private void setDefaultPaymentMethod(final CustomerAwareSubscriptionPaymentProcessor manager,
final String paymentMethodId,
final SubscriberCredentials requestData) throws SubscriptionException {
final SubscriberCredentials requestData) throws SubscriptionException, IOException {
try {
final Subscriptions.Record record = subscriptionManager.getSubscriber(requestData);
@@ -816,26 +783,13 @@ public class SubscriptionController {
manager
.setDefaultPaymentMethodForCustomer(processorCustomer.customerId(), paymentMethodId, record.subscriptionId);
} catch (SubscriptionInvalidArgumentsException e) {
} catch (final SubscriptionInvalidArgumentsException e) {
// Here, invalid arguments must mean that the client has made requests out of order, and needs to finish
// setting up the paymentMethod first
throw new ClientErrorException(Status.CONFLICT);
}
}
private Instant receiptExpirationWithGracePeriod(CustomerAwareSubscriptionPaymentProcessor.ReceiptItem receiptItem) {
final PaymentTime paymentTime = receiptItem.paymentTime();
return switch (subscriptionConfiguration.getSubscriptionLevel(receiptItem.level()).type()) {
case DONATION -> paymentTime.receiptExpiration(
subscriptionConfiguration.getBadgeExpiration(),
subscriptionConfiguration.getBadgeGracePeriod());
case BACKUP -> paymentTime.receiptExpiration(
subscriptionConfiguration.getBackupExpiration(),
subscriptionConfiguration.getBackupGracePeriod());
};
}
private String getSubscriptionTemplateId(long level, String currency, PaymentProvider processor) {
final SubscriptionLevelConfiguration config = subscriptionConfiguration.getSubscriptionLevel(level);
if (config == null) {
@@ -854,13 +808,4 @@ public class SubscriptionController {
SetSubscriptionLevelErrorResponse.Error.Type.UNSUPPORTED_CURRENCY, null))))
.build()));
}
@Nullable
private static ClientPlatform getClientPlatform(@Nullable final String userAgentString) {
try {
return UserAgentUtil.parseUserAgentString(userAgentString).platform();
} catch (final UnrecognizedUserAgentException e) {
return null;
}
}
}
@@ -59,8 +59,6 @@ import java.util.HexFormat;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletionException;
import org.apache.commons.lang3.Strings;
import org.apache.http.HttpStatus;
import org.slf4j.Logger;
@@ -91,7 +89,6 @@ import org.whispersystems.textsecuregcm.registration.MessageTransport;
import org.whispersystems.textsecuregcm.registration.RegistrationFraudException;
import org.whispersystems.textsecuregcm.registration.RegistrationServiceClient;
import org.whispersystems.textsecuregcm.registration.RegistrationServiceException;
import org.whispersystems.textsecuregcm.registration.RegistrationServiceSenderException;
import org.whispersystems.textsecuregcm.registration.TransportNotAllowedException;
import org.whispersystems.textsecuregcm.registration.VerificationSession;
import org.whispersystems.textsecuregcm.spam.RegistrationFraudChecker;
@@ -105,7 +102,6 @@ import org.whispersystems.textsecuregcm.storage.VerificationSessionManager;
import org.whispersystems.textsecuregcm.telephony.CarrierData;
import org.whispersystems.textsecuregcm.telephony.CarrierDataException;
import org.whispersystems.textsecuregcm.telephony.CarrierDataProvider;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import org.whispersystems.textsecuregcm.util.ObsoletePhoneNumberFormatException;
import org.whispersystems.textsecuregcm.util.Pair;
import org.whispersystems.textsecuregcm.util.Util;
@@ -225,27 +221,13 @@ public class VerificationController {
maybeCarrierData = Optional.empty();
}
final RegistrationServiceSession registrationServiceSession;
try {
final String sourceHost = (String) requestContext.getProperty(RemoteAddressFilter.REMOTE_ADDRESS_ATTRIBUTE_NAME);
registrationServiceSession = registrationServiceClient.createRegistrationSession(phoneNumber,
sourceHost,
accountsManager.getByE164(request.number()).isPresent(),
maybeCarrierData.flatMap(CarrierData::mcc).orElse(null),
maybeCarrierData.flatMap(CarrierData::mnc).orElse(null),
REGISTRATION_RPC_TIMEOUT).join();
} catch (final CancellationException e) {
throw new ServerErrorException("registration service unavailable", Response.Status.SERVICE_UNAVAILABLE);
} catch (final CompletionException e) {
if (ExceptionUtils.unwrap(e) instanceof RateLimitExceededException re) {
throw re;
}
throw new ServerErrorException(Response.Status.INTERNAL_SERVER_ERROR, e);
}
final RegistrationServiceSession registrationServiceSession =
registrationServiceClient.createRegistrationSession(phoneNumber,
(String) requestContext.getProperty(RemoteAddressFilter.REMOTE_ADDRESS_ATTRIBUTE_NAME),
accountsManager.getByE164(request.number()).isPresent(),
maybeCarrierData.flatMap(CarrierData::mcc).orElse(null),
maybeCarrierData.flatMap(CarrierData::mnc).orElse(null),
REGISTRATION_RPC_TIMEOUT);
VerificationSession verificationSession = new VerificationSession(registrationServiceSession.encodedSessionId(),
null,
@@ -654,59 +636,44 @@ public class VerificationController {
clientType,
acceptLanguage.orElse(null),
senderOverride,
REGISTRATION_RPC_TIMEOUT).join();
REGISTRATION_RPC_TIMEOUT);
} catch (final VerificationSessionRateLimitExceededException e) {
throw new ClientErrorException(buildResponseForRateLimitExceeded(verificationSession,
e.getRegistrationSession(),
e.getRetryDuration()));
} catch (final RegistrationServiceException registrationServiceException) {
throw registrationServiceException.getRegistrationSession()
.map(s -> buildResponse(s, verificationSession))
.map(verificationSessionResponse -> {
final Response response = registrationServiceException instanceof TransportNotAllowedException
? Response.status(418).entity(verificationSessionResponse).build()
: Response.status(Response.Status.CONFLICT).entity(verificationSessionResponse).build();
accountsManager.getByE164(registrationServiceSession.number())
.filter(existingAccount ->
experimentEnrollmentManager.isEnrolled(existingAccount.getIdentifier(IdentityType.ACI), VERIFICATION_CODE_PUSH_NOTIFICATION_EXPERIMENT_NAME))
.ifPresent(existingAccount -> {
try {
pushNotificationManager.sendVerificationCodeRequestedNotifications(existingAccount, clock.instant());
} catch (final NotPushRegisteredException _) {
}
});
} catch (final CancellationException e) {
throw new ServerErrorException("registration service unavailable", Response.Status.SERVICE_UNAVAILABLE);
} catch (final CompletionException e) {
final Throwable unwrappedException = ExceptionUtils.unwrap(e);
switch (unwrappedException) {
case RateLimitExceededException rateLimitExceededException -> {
if (rateLimitExceededException instanceof VerificationSessionRateLimitExceededException ve) {
final Response response = buildResponseForRateLimitExceeded(verificationSession,
ve.getRegistrationSession(),
ve.getRetryDuration());
throw new ClientErrorException(response);
}
throw new RateLimitExceededException(rateLimitExceededException.getRetryDuration().orElse(null));
}
case RegistrationServiceException registrationServiceException ->
throw registrationServiceException.getRegistrationSession()
.map(s -> buildResponse(s, verificationSession))
.map(verificationSessionResponse -> {
final Response response = registrationServiceException instanceof TransportNotAllowedException
? Response.status(418).entity(verificationSessionResponse).build()
: Response.status(Response.Status.CONFLICT).entity(verificationSessionResponse).build();
return new ClientErrorException(response);
})
.orElseGet(NotFoundException::new);
case RegistrationFraudException _ -> {
if (dynamicConfigurationManager.getConfiguration().getRegistrationConfiguration()
.squashDeclinedAttemptErrors()) {
return buildResponse(registrationServiceSession, verificationSession);
} else {
throw unwrappedException.getCause();
}
}
case RegistrationServiceSenderException _ -> throw unwrappedException;
case null, default -> {
logger.error("Registration service failure", unwrappedException);
throw new ServerErrorException(Response.Status.INTERNAL_SERVER_ERROR);
}
return new ClientErrorException(response);
})
.orElseGet(NotFoundException::new);
} catch (final RegistrationFraudException e) {
if (dynamicConfigurationManager.getConfiguration().getRegistrationConfiguration()
.squashDeclinedAttemptErrors()) {
return buildResponse(registrationServiceSession, verificationSession);
} else {
throw e.getCause();
}
} catch (final RuntimeException e) {
logger.error("Registration service failure", e);
throw new ServerErrorException(Response.Status.INTERNAL_SERVER_ERROR);
}
accountsManager.getByE164(registrationServiceSession.number())
.filter(existingAccount ->
experimentEnrollmentManager.isEnrolled(existingAccount.getIdentifier(IdentityType.ACI), VERIFICATION_CODE_PUSH_NOTIFICATION_EXPERIMENT_NAME))
.ifPresent(existingAccount -> {
try {
pushNotificationManager.sendVerificationCodeRequestedNotifications(existingAccount, clock.instant());
} catch (final NotPushRegisteredException _) {
}
});
Metrics.counter(CODE_REQUESTED_COUNTER_NAME, Tags.of(
UserAgentTagUtil.getPlatformTag(userAgent),
Tag.of(COUNTRY_CODE_TAG_NAME, Util.getCountryCode(registrationServiceSession.number())),
@@ -746,8 +713,7 @@ public class VerificationController {
schema = @Schema(implementation = Integer.class)))
public VerificationSessionResponse verifyCode(@PathParam("sessionId") final String encodedSessionId,
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
@NotNull @Valid final SubmitVerificationCodeRequest submitVerificationCodeRequest)
throws RateLimitExceededException {
@NotNull @Valid final SubmitVerificationCodeRequest submitVerificationCodeRequest) {
final RegistrationServiceSession registrationServiceSession = retrieveRegistrationServiceSession(encodedSessionId);
final VerificationSession verificationSession = retrieveVerificationSession(registrationServiceSession);
@@ -764,35 +730,17 @@ public class VerificationController {
try {
resultSession = registrationServiceClient.checkVerificationCode(registrationServiceSession.id(),
submitVerificationCodeRequest.code(),
REGISTRATION_RPC_TIMEOUT)
.join();
} catch (final CancellationException e) {
logger.warn("Unexpected cancellation from registration service", e);
throw new ServerErrorException(Response.Status.SERVICE_UNAVAILABLE);
} catch (final CompletionException e) {
final Throwable unwrappedException = ExceptionUtils.unwrap(e);
if (unwrappedException instanceof RateLimitExceededException rateLimitExceededException) {
if (rateLimitExceededException instanceof VerificationSessionRateLimitExceededException ve) {
final Response response = buildResponseForRateLimitExceeded(verificationSession, ve.getRegistrationSession(),
ve.getRetryDuration());
throw new ClientErrorException(response);
}
throw new RateLimitExceededException(rateLimitExceededException.getRetryDuration().orElse(null));
} else if (unwrappedException instanceof RegistrationServiceException registrationServiceException) {
throw registrationServiceException.getRegistrationSession()
.map(s -> buildResponse(s, verificationSession))
.map(verificationSessionResponse -> new ClientErrorException(
Response.status(Response.Status.CONFLICT).entity(verificationSessionResponse).build()))
.orElseGet(NotFoundException::new);
} else {
logger.error("Registration service failure", unwrappedException);
throw new ServerErrorException(Response.Status.INTERNAL_SERVER_ERROR);
}
REGISTRATION_RPC_TIMEOUT);
} catch (final VerificationSessionRateLimitExceededException e) {
throw new ClientErrorException(buildResponseForRateLimitExceeded(verificationSession,
e.getRegistrationSession(),
e.getRetryDuration()));
} catch (final RegistrationServiceException e) {
throw e.getRegistrationSession()
.map(s -> buildResponse(s, verificationSession))
.map(verificationSessionResponse -> new ClientErrorException(
Response.status(Response.Status.CONFLICT).entity(verificationSessionResponse).build()))
.orElseGet(NotFoundException::new);
}
boolean existingRRP = false;
@@ -868,9 +816,8 @@ public class VerificationController {
}
try {
final RegistrationServiceSession registrationServiceSession = registrationServiceClient.getSession(sessionId,
REGISTRATION_RPC_TIMEOUT).join()
.orElseThrow(NotFoundException::new);
final RegistrationServiceSession registrationServiceSession =
registrationServiceClient.getSession(sessionId, REGISTRATION_RPC_TIMEOUT).orElseThrow(NotFoundException::new);
if (registrationServiceSession.verified()) {
// Since there is a valid verification session we invalidate the other possible verification mechanism,
@@ -882,14 +829,16 @@ public class VerificationController {
return registrationServiceSession;
} catch (final CompletionException | CancellationException e) {
final Throwable unwrapped = ExceptionUtils.unwrap(e);
if (unwrapped instanceof StatusRuntimeException grpcRuntimeException) {
if (grpcRuntimeException.getStatus().getCode() == Status.Code.INVALID_ARGUMENT) {
throw new BadRequestException();
}
} catch (final StatusRuntimeException e) {
if (e.getStatus().getCode() == Status.Code.INVALID_ARGUMENT) {
throw new BadRequestException();
}
logger.error("Registration service failure", e);
throw new ServerErrorException(Response.Status.SERVICE_UNAVAILABLE, e);
} catch (final WebApplicationException e) {
throw e;
} catch (final RuntimeException e) {
logger.error("Registration service failure", e);
throw new ServerErrorException(Response.Status.SERVICE_UNAVAILABLE, e);
}
@@ -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;
@@ -28,7 +29,7 @@ public record AccountDataReportResponse(UUID reportId,
@JsonProperty
@Schema(description = "A plaintext representation of the data report")
String text() {
public String text() {
final StringBuilder builder = new StringBuilder();
@@ -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)
@@ -0,0 +1,20 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.entities;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
public record CreateDonationPermitResponse(
@Schema(description = "A serialized DonationPermitResponse")
@NotEmpty
@NotNull
@Valid
byte[] permitResponse) {
}
@@ -0,0 +1,18 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.entities;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
public record CreateDonationPermitsRequest(
@Schema(description = "A serialized DonationPermitRequest")
@NotEmpty
@NotNull
byte[] permitRequest) {
}
@@ -11,7 +11,7 @@ import io.swagger.v3.oas.annotations.media.Schema;
import org.whispersystems.textsecuregcm.registration.VerificationSession;
public record VerificationSessionResponse(
@Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = "A URL-safe ID for the session")
@Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = "A URL-safe base64-encoded ID for the session")
String id,
@Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED, description = "Duration in seconds after which next SMS can be requested for this session")
@@ -71,6 +71,10 @@ public class Experiment {
this.experimentNullMismatchTimer = experimentNullMismatchTimer;
}
public <T> void compareResult(final T expected, final T experimentResult) {
recordResult(expected, experimentResult, Timer.start());
}
public <T> void compareMonoResult(final T expected, final Mono<T> experimentMono) {
final Timer.Sample sample = Timer.start();
@@ -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);
@@ -6,31 +6,43 @@
package org.whispersystems.textsecuregcm.grpc;
import com.google.protobuf.ByteString;
import java.util.Optional;
import java.util.UUID;
import org.signal.chat.account.Capabilities;
import org.signal.chat.account.CheckAccountExistenceRequest;
import org.signal.chat.account.CheckAccountExistenceResponse;
import org.signal.chat.account.GetCapabilitiesAnonymousRequest;
import org.signal.chat.account.GetCapabilitiesAnonymousResponse;
import org.signal.chat.account.LookupUsernameHashRequest;
import org.signal.chat.account.LookupUsernameHashResponse;
import org.signal.chat.account.LookupUsernameLinkRequest;
import org.signal.chat.account.LookupUsernameLinkResponse;
import org.signal.chat.account.SimpleAccountsAnonymousGrpc;
import org.signal.chat.errors.FailedUnidentifiedAuthorization;
import org.signal.chat.errors.NotFound;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
public class AccountsAnonymousGrpcService extends SimpleAccountsAnonymousGrpc.AccountsAnonymousImplBase {
private final AccountsManager accountsManager;
private final RateLimiters rateLimiters;
private final GroupSendTokenUtil groupSendTokenUtil;
public AccountsAnonymousGrpcService(final AccountsManager accountsManager, final RateLimiters rateLimiters) {
public AccountsAnonymousGrpcService(
final AccountsManager accountsManager,
final RateLimiters rateLimiters,
final GroupSendTokenUtil groupSendTokenUtil) {
this.accountsManager = accountsManager;
this.rateLimiters = rateLimiters;
this.groupSendTokenUtil = groupSendTokenUtil;
}
@Override
@@ -55,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());
}
@@ -80,4 +92,40 @@ public class AccountsAnonymousGrpcService extends SimpleAccountsAnonymousGrpc.Ac
.build())
.orElseGet(() -> LookupUsernameLinkResponse.newBuilder().setNotFound(NotFound.getDefaultInstance()).build());
}
@Override
public GetCapabilitiesAnonymousResponse getCapabilities(GetCapabilitiesAnonymousRequest request) {
final ServiceIdentifier targetIdentifier =
GrpcServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getAccountIdentifier());
final Optional<Account> targetAccount = accountsManager.getByServiceIdentifier(targetIdentifier);
final boolean authorized = switch (request.getAuthenticationCase()) {
case GROUP_SEND_TOKEN -> groupSendTokenUtil.checkGroupSendToken(request.getGroupSendToken(), targetIdentifier);
case UNIDENTIFIED_ACCESS_KEY -> targetAccount
.map(a -> UnidentifiedAccessUtil.checkUnidentifiedAccess(a, request.getUnidentifiedAccessKey().toByteArray()))
.orElse(false);
default -> throw GrpcExceptions.invalidArguments("invalid authentication");
};
if (!authorized) {
return GetCapabilitiesAnonymousResponse.newBuilder()
.setFailedUnidentifiedAuthorization(FailedUnidentifiedAuthorization.getDefaultInstance())
.build();
}
return targetAccount.map(target -> {
final Capabilities.Builder builder = Capabilities.newBuilder();
for (DeviceCapability capability : DeviceCapability.PUBLIC_VISIBLE_CAPABILITIES) {
if (target.hasCapability(capability)) {
builder.addCapabilities(DeviceCapabilityUtil.toGrpcDeviceCapability(capability));
}
}
return GetCapabilitiesAnonymousResponse.newBuilder().setCapabilities(builder.build()).build();
})
.orElseGet(() -> GetCapabilitiesAnonymousResponse.newBuilder()
.setNotFound(NotFound.getDefaultInstance())
.build());
}
}
@@ -6,13 +6,22 @@
package org.whispersystems.textsecuregcm.grpc;
import com.google.protobuf.ByteString;
import io.grpc.StatusRuntimeException;
import java.io.IOException;
import java.security.SecureRandom;
import java.time.Clock;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HexFormat;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.signal.chat.account.Capabilities;
import org.signal.chat.account.ChangeNumberRequest;
import org.signal.chat.account.ChangeNumberResponse;
import org.signal.chat.account.ClearRegistrationLockRequest;
import org.signal.chat.account.ClearRegistrationLockResponse;
import org.signal.chat.account.ConfigureUnidentifiedAccessRequest;
@@ -25,8 +34,16 @@ import org.signal.chat.account.DeleteUsernameHashRequest;
import org.signal.chat.account.DeleteUsernameHashResponse;
import org.signal.chat.account.DeleteUsernameLinkRequest;
import org.signal.chat.account.DeleteUsernameLinkResponse;
import org.signal.chat.account.ExternalServiceCredentials;
import org.signal.chat.account.GetAccountDataReportRequest;
import org.signal.chat.account.GetAccountDataReportResponse;
import org.signal.chat.account.GetAccountIdentityRequest;
import org.signal.chat.account.GetAccountIdentityResponse;
import org.signal.chat.account.GetCapabilitiesRequest;
import org.signal.chat.account.GetCapabilitiesResponse;
import org.signal.chat.account.GetEntitlementsRequest;
import org.signal.chat.account.GetEntitlementsResponse;
import org.signal.chat.account.RegistrationLockFailure;
import org.signal.chat.account.ReserveUsernameHashRequest;
import org.signal.chat.account.ReserveUsernameHashResponse;
import org.signal.chat.account.SetDiscoverableByPhoneNumberRequest;
@@ -40,25 +57,45 @@ import org.signal.chat.account.SetUsernameLinkResponse;
import org.signal.chat.account.SetZkCredentialKeyRequest;
import org.signal.chat.account.SetZkCredentialKeyResponse;
import org.signal.chat.account.SimpleAccountsGrpc;
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.messages.SendMessageType;
import org.signal.libsignal.protocol.IdentityKey;
import org.signal.libsignal.protocol.InvalidKeyException;
import org.signal.libsignal.usernames.BaseUsernameException;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.ZkCredentialPublicKey;
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;
import org.whispersystems.textsecuregcm.controllers.AccountController;
import org.whispersystems.textsecuregcm.controllers.MessageDeliveryNotAllowedException;
import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.entities.AccountDataReportResponse;
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
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;
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.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;
@@ -70,38 +107,60 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
private final RateLimiters rateLimiters;
private final UsernameHashZkProofVerifier usernameHashZkProofVerifier;
private final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager;
private final Clock clock;
private final ChangeNumberManager changeNumberManager;
public AccountsGrpcService(final AccountsManager accountsManager,
final RateLimiters rateLimiters,
final UsernameHashZkProofVerifier usernameHashZkProofVerifier,
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager) {
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager,
final Clock clock,
final ChangeNumberManager changeNumberManager) {
this.accountsManager = accountsManager;
this.rateLimiters = rateLimiters;
this.usernameHashZkProofVerifier = usernameHashZkProofVerifier;
this.registrationRecoveryPasswordsManager = registrationRecoveryPasswordsManager;
this.clock = clock;
this.changeNumberManager = changeNumberManager;
}
@Override
public GetAccountIdentityResponse getAccountIdentity(final GetAccountIdentityRequest request) {
final Account account = getAuthenticatedAccount();
final AccountIdentifiers.Builder accountIdentifiersBuilder = AccountIdentifiers.newBuilder()
.addServiceIdentifiers(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(new AciServiceIdentifier(account.getUuid())))
.addServiceIdentifiers(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(new PniServiceIdentifier(account.getPhoneNumberIdentifier())))
.setE164(account.getNumber());
account.getUsernameHash().ifPresent(usernameHash ->
accountIdentifiersBuilder.setUsernameHash(ByteString.copyFrom(usernameHash)));
return GetAccountIdentityResponse.newBuilder()
.setAccountIdentifiers(accountIdentifiersBuilder)
.setAccountIdentifiers(buildAccountIdentifiers(getAuthenticatedAccount()))
.build();
}
@Override
public GetEntitlementsResponse getEntitlements(final GetEntitlementsRequest request) {
final Account account = getAuthenticatedAccount();
final GetEntitlementsResponse.Builder builder = GetEntitlementsResponse.newBuilder();
final Instant now = clock.instant();
final Account.BackupVoucher backupVoucher = account.getBackupVoucher();
if (backupVoucher != null && backupVoucher.expiration().isAfter(now)) {
builder.setBackup(GetEntitlementsResponse.BackupEntitlement.newBuilder()
.setExpirationEpochSeconds(backupVoucher.expiration().getEpochSecond())
.setLevel(backupVoucher.receiptLevel()));
}
builder.addAllBadges(account.getBadges().stream()
.filter(badge -> badge.expiration().isAfter(now))
.map(badge -> GetEntitlementsResponse.BadgeEntitlement.newBuilder()
.setBadgeId(badge.id())
.setExpirationEpochSeconds(badge.expiration().getEpochSecond())
.setVisible(badge.visible())
.build())
.toList());
return builder.build();
}
@Override
public DeleteAccountResponse deleteAccount(final DeleteAccountRequest request) {
accountsManager.delete(AuthenticationUtil.requireAuthenticatedPrimaryDevice().accountIdentifier(),
accountsManager.delete(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier(),
AccountsManager.DeletionReason.USER_REQUEST);
return DeleteAccountResponse.getDefaultInstance();
@@ -109,12 +168,10 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
@Override
public SetRegistrationLockResponse setRegistrationLock(final SetRegistrationLockRequest request) {
// In the previous REST-based API, clients would send hex strings directly. For backward compatibility, we
// convert the registration lock secret to a lowercase hex string before turning it into a salted hash.
final SaltedTokenHash credentials =
SaltedTokenHash.generateFor(HexFormat.of().withLowerCase().formatHex(request.getRegistrationLock().toByteArray()));
SaltedTokenHash.generateFor(formatRegistrationLock(request.getRegistrationLock().toByteArray()));
accountsManager.update(AuthenticationUtil.requireAuthenticatedPrimaryDevice().accountIdentifier(),
accountsManager.update(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier(),
account -> account.setRegistrationLock(credentials.hash(), credentials.salt()));
return SetRegistrationLockResponse.getDefaultInstance();
@@ -122,7 +179,7 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
@Override
public ClearRegistrationLockResponse clearRegistrationLock(final ClearRegistrationLockRequest request) {
accountsManager.update(AuthenticationUtil.requireAuthenticatedPrimaryDevice().accountIdentifier(),
accountsManager.update(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier(),
account -> account.setRegistrationLock(null, null));
return ClearRegistrationLockResponse.getDefaultInstance();
@@ -136,11 +193,6 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
final List<byte[]> usernameHashes = new ArrayList<>(request.getUsernameHashesCount());
for (final ByteString usernameHash : request.getUsernameHashesList()) {
if (usernameHash.size() != AccountController.USERNAME_HASH_LENGTH) {
throw GrpcExceptions.fieldViolation("username_hashes",
String.format("Username hash length must be %d bytes, but was actually %d",
AccountController.USERNAME_HASH_LENGTH, usernameHash.size()));
}
usernameHashes.add(usernameHash.toByteArray());
}
@@ -180,7 +232,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) {
@@ -242,15 +293,15 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
@Override
public ConfigureUnidentifiedAccessResponse configureUnidentifiedAccess(final ConfigureUnidentifiedAccessRequest request) {
if (!request.getAllowUnrestrictedUnidentifiedAccess() && request.getUnidentifiedAccessKey().size() != UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH) {
throw GrpcExceptions.fieldViolation("unidentified_access_key",
String.format("Unidentified access key must be %d bytes, but was actually %d",
UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH, request.getUnidentifiedAccessKey().size()));
if (request.getConfigurationCase() == ConfigureUnidentifiedAccessRequest.ConfigurationCase.CONFIGURATION_NOT_SET) {
throw GrpcExceptions.fieldViolation("configuration", "a configuration case must be set");
}
accountsManager.update(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier(), account -> {
account.setUnrestrictedUnidentifiedAccess(request.getAllowUnrestrictedUnidentifiedAccess());
account.setUnidentifiedAccessKey(request.getAllowUnrestrictedUnidentifiedAccess() ? null : request.getUnidentifiedAccessKey().toByteArray());
account.setUnidentifiedAccessKey(request.hasUnidentifiedAccessKey()
? request.getUnidentifiedAccessKey().toByteArray()
: null);
account.setUnrestrictedUnidentifiedAccess(request.hasAllowUnrestrictedUnidentifiedAccess());
});
return ConfigureUnidentifiedAccessResponse.getDefaultInstance();
@@ -277,9 +328,14 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
final Account authenticatedAccount = getAuthenticatedAccount();
final byte[] zkCredentialKey = request.getPublicKey().toByteArray();
final ZkCredentialPublicKey zkCredentialKey;
try {
zkCredentialKey = new ZkCredentialPublicKey(request.getPublicKey().toByteArray());
} catch (InvalidInputException _) {
throw GrpcExceptions.invalidArguments("invalid public key bytes");
}
if (Arrays.equals(authenticatedAccount.getZkCredentialKey(), zkCredentialKey)) {
if (authenticatedAccount.getZkCredentialKey().map(zkCredentialKey::equals).orElse(false)) {
return SetZkCredentialKeyResponse.newBuilder()
.setRotationId(Objects.requireNonNull(authenticatedAccount.getZkCredentialKeyRotationId()))
.build();
@@ -300,6 +356,194 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
.build();
}
@Override
public ChangeNumberResponse changeNumber(final ChangeNumberRequest request)
throws RateLimitExceededException, InterruptedException {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedPrimaryDevice();
final IdentityKey pniIdentityKey;
try {
pniIdentityKey = new IdentityKey(request.getPniIdentityKey().toByteArray());
} catch (final InvalidKeyException e) {
throw GrpcExceptions.fieldViolation("pni_identity_key", "invalid identity key");
}
final Map<Byte, ECSignedPreKey> devicePniSignedPreKeys = transformDeviceMap(request.getDevicePniSignedPreKeysMap(),
key -> KeysGrpcHelper.checkEcSignedPreKey(key, pniIdentityKey,
invalidPublicKeyException("device_pni_signed_pre_keys"),
invalidSignatureException("device_pni_signed_pre_keys")));
final Map<Byte, KEMSignedPreKey> devicePniPqLastResortPreKeys = transformDeviceMap(request.getDevicePniPqLastResortPreKeysMap(),
key -> KeysGrpcHelper.checkKemSignedPreKey(key, pniIdentityKey,
invalidPublicKeyException("device_pni_pq_last_resort_pre_keys"),
invalidSignatureException("device_pni_pq_last_resort_pre_keys")));
final Map<Byte, Integer> pniRegistrationIds = transformDeviceMap(request.getPniRegistrationIdsMap(), Function.identity());
if (!pniRegistrationIds.values().stream().allMatch(RegistrationIdValidator::validRegistrationId)) {
throw GrpcExceptions.fieldViolation("pni_registration_ids", "invalid registration id");
}
final List<IncomingMessage> deviceMessages = request.getDeviceMessages().getMessagesMap()
.entrySet()
.stream()
.map(entry -> new IncomingMessage(
getEnvelopeType(entry.getValue().getType()).getNumber(),
(byte) (int) entry.getKey(),
entry.getValue().getRegistrationId(),
entry.getValue().getPayload().toByteArray()))
.toList();
final byte[] sessionId = request.getVerificationCase() == ChangeNumberRequest.VerificationCase.SESSION_ID
? request.getSessionId().toByteArray()
: null;
final byte[] recoveryPassword =
request.getVerificationCase() == ChangeNumberRequest.VerificationCase.RECOVERY_PASSWORD
? request.getRecoveryPassword().toByteArray()
: null;
final String registrationLock = request.getRegistrationLock().isEmpty() ? null :
formatRegistrationLock(request.getRegistrationLock().toByteArray());
try {
final Account updatedAccount = changeNumberManager.changeNumber(
authenticatedDevice.accountIdentifier(),
sessionId,
recoveryPassword,
registrationLock,
request.getNumber(),
pniIdentityKey,
devicePniSignedPreKeys,
devicePniPqLastResortPreKeys,
deviceMessages,
pniRegistrationIds,
RequestAttributesUtil.getUserAgent().orElse(null),
RequestAttributesUtil.getAcceptLanguageRaw(),
RequestAttributesUtil.getRemoteAddress().getHostAddress());
return ChangeNumberResponse.newBuilder()
.setAccountIdentifiers(buildAccountIdentifiers(updatedAccount))
.build();
} catch (final MismatchedDevicesException e) {
if (!e.getMismatchedDevices().staleDeviceIds().isEmpty()) {
return ChangeNumberResponse.newBuilder()
.setStaleDevices(StaleDevices.newBuilder()
.addAllStaleDevices(e.getMismatchedDevices().staleDeviceIds().stream().map(Byte::intValue).toList()))
.build();
}
return ChangeNumberResponse.newBuilder()
.setMismatchedDevices(MessagesGrpcHelper.buildMismatchedDevices(
new AciServiceIdentifier(authenticatedDevice.accountIdentifier()), e.getMismatchedDevices()))
.build();
} catch (final MessageTooLargeException e) {
return ChangeNumberResponse.newBuilder()
.setMessageTooLarge(FailedPrecondition.newBuilder()
.setDescription("one or more device messages was too large"))
.build();
} catch (final MessageDeliveryNotAllowedException e) {
throw GrpcExceptions.unavailable();
} catch (final IllegalArgumentException e) {
throw GrpcExceptions.invalidArguments(e.getMessage());
} catch (final RegistrationLockFailureException e) {
final RegistrationLockFailure.Builder failureBuilder = RegistrationLockFailure.newBuilder()
.setTimeRemainingMillis(e.getFailure().timeRemaining());
if (e.getFailure().svr2Credentials() != null) {
failureBuilder.setSvr2Credentials(ExternalServiceCredentials.newBuilder()
.setUsername(e.getFailure().svr2Credentials().username())
.setPassword(e.getFailure().svr2Credentials().password()));
}
return ChangeNumberResponse.newBuilder()
.setRegistrationLockFailure(failureBuilder)
.build();
} catch (final UnverifiedRegistrationSessionException e) {
return ChangeNumberResponse.newBuilder()
.setUnverifiedRegistrationSession(FailedPrecondition.getDefaultInstance())
.build();
} catch (final InvalidRegistrationSessionException e) {
return ChangeNumberResponse.newBuilder()
.setInvalidRegistrationSession(FailedPrecondition.newBuilder().setDescription(e.getMessage()))
.build();
} catch (final IOException e) {
throw GrpcExceptions.unavailable(e.getMessage());
} catch (final RecoveryPasswordVerificationFailedException e) {
return ChangeNumberResponse.newBuilder()
.setRecoveryPasswordVerificationFailed(FailedPrecondition.getDefaultInstance())
.build();
}
}
@Override
public GetAccountDataReportResponse getAccountDataReport(final GetAccountDataReportRequest request)
throws IOException {
final Account account = getAuthenticatedAccount();
final AccountDataReportResponse report = new AccountDataReportResponse(UUID.randomUUID(), clock.instant(),
new AccountDataReportResponse.AccountAndDevicesDataReport(
new AccountDataReportResponse.AccountDataReport(
account.getNumberOptional(),
account.getBadges().stream().map(AccountDataReportResponse.BadgeDataReport::new).toList(),
account.isUnrestrictedUnidentifiedAccess(),
account.isDiscoverableByPhoneNumber()),
account.getDevices().stream().map(device ->
new AccountDataReportResponse.DeviceDataReport(
device.getId(),
Instant.ofEpochMilli(device.getLastSeen()),
Instant.ofEpochMilli(device.getCreated()),
device.getUserAgent())).toList()));
return GetAccountDataReportResponse.newBuilder()
.setJson(SystemMapper.jsonMapper().writeValueAsString(report))
.setText(report.text())
.build();
}
@Override
public GetCapabilitiesResponse getCapabilities(GetCapabilitiesRequest request) {
final Account account = getAuthenticatedAccount();
final Capabilities.Builder builder = Capabilities.newBuilder();
for (DeviceCapability capability : DeviceCapability.SELF_VISIBLE_CAPABILITIES) {
if (account.hasCapability(capability)) {
builder.addCapabilities(DeviceCapabilityUtil.toGrpcDeviceCapability(capability));
}
}
return GetCapabilitiesResponse.newBuilder().setCapabilities(builder.build()).build();
}
private static AccountIdentifiers buildAccountIdentifiers(final Account account) {
final AccountIdentifiers.Builder accountIdentifiersBuilder = AccountIdentifiers.newBuilder()
.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)));
if (account.getUsernameLinkHandle() != null) {
accountIdentifiersBuilder.setUsernameLinkHandle(UUIDUtil.toByteString(account.getUsernameLinkHandle()));
}
return accountIdentifiersBuilder.build();
}
private static MessageProtos.Envelope.Type getEnvelopeType(final SendMessageType type) {
return switch (type) {
case DOUBLE_RATCHET -> MessageProtos.Envelope.Type.CIPHERTEXT;
case PREKEY_MESSAGE -> MessageProtos.Envelope.Type.PREKEY_BUNDLE;
case PLAINTEXT_CONTENT -> MessageProtos.Envelope.Type.PLAINTEXT_CONTENT;
case UNIDENTIFIED_SENDER -> throw GrpcExceptions.invalidArguments("illegal envelope type for change-number sync messages");
case UNSPECIFIED, UNRECOGNIZED -> throw GrpcExceptions.invalidArguments("unrecognized envelope type");
};
}
private Account getAuthenticatedAccount() {
return getAuthenticatedAccount(AuthenticationUtil.requireAuthenticatedDevice());
}
@@ -308,4 +552,25 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
return accountsManager.getByAccountIdentifier(authenticatedDevice.accountIdentifier())
.orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials"));
}
private static String formatRegistrationLock(final byte[] registrationLock) {
// In the previous REST-based API, clients would send hex strings directly. For backward compatibility, we
// convert the registration lock secret to a lowercase hex string before turning it into a salted hash.
return HexFormat.of().withLowerCase().formatHex(registrationLock);
}
private static StatusRuntimeException invalidPublicKeyException(final String fieldName) {
return GrpcExceptions.fieldViolation(fieldName, "invalid public key");
}
private static StatusRuntimeException invalidSignatureException(final String fieldName) {
return GrpcExceptions.fieldViolation(fieldName, "pre-key signature did not match PNI identity key");
}
private static <T, U> Map<Byte, U> transformDeviceMap(final Map<Integer, T> byDeviceId, final Function<T, U> f) {
return byDeviceId.entrySet()
.stream()
.collect(Collectors.<Map.Entry<Integer, T>, Byte, U>toMap(entry -> entry.getKey().byteValue(),
entry -> f.apply(entry.getValue())));
}
}
@@ -6,10 +6,21 @@
package org.whispersystems.textsecuregcm.grpc;
import java.security.SecureRandom;
import java.time.Clock;
import java.time.Instant;
import java.util.HexFormat;
import java.util.Map;
import java.util.stream.IntStream;
import io.micrometer.core.instrument.DistributionSummary;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import org.signal.chat.attachments.GetStickerUploadFormRequest;
import org.signal.chat.attachments.GetStickerUploadFormResponse;
import org.signal.chat.attachments.GetUploadFormRequest;
import org.signal.chat.attachments.GetUploadFormResponse;
import org.signal.chat.attachments.SimpleAttachmentsGrpc;
import org.signal.chat.common.S3UploadForm;
import org.signal.chat.common.UploadForm;
import org.signal.chat.errors.FailedPrecondition;
import org.whispersystems.textsecuregcm.attachments.AttachmentGenerator;
@@ -18,30 +29,51 @@ import org.whispersystems.textsecuregcm.attachments.GcsAttachmentGenerator;
import org.whispersystems.textsecuregcm.attachments.TusAttachmentGenerator;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
import org.whispersystems.textsecuregcm.controllers.AttachmentControllerV4;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.controllers.StickerController;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.limits.RateLimiter;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
public class AttachmentsGrpcService extends SimpleAttachmentsGrpc.AttachmentsImplBase {
private final ExperimentEnrollmentManager experimentEnrollmentManager;
private final RateLimiter countRateLimiter;
private final RateLimiter bytesRateLimiter;
private final RateLimiter stickerPackLimiter;
private final long maxUploadLength;
private final Map<Integer, AttachmentGenerator> attachmentGenerators;
private final PostPolicyGenerator stickerPolicyGenerator;
private final Clock clock;
private final SecureRandom secureRandom;
private static final S3UploadForm PROTOTYPE_STICKER_UPLOAD_FORM = S3UploadForm.newBuilder()
.setAcl(PostPolicyGenerator.ACL)
.setAlgorithm(PostPolicyGenerator.ALGORITHM)
.build();
private static final String ATTACHMENT_SIZE_NAME =
MetricsUtil.name(AttachmentsGrpcService.class, "attachmentSize");
public AttachmentsGrpcService(
final ExperimentEnrollmentManager experimentEnrollmentManager,
final RateLimiters rateLimiters,
final GcsAttachmentGenerator gcsAttachmentGenerator,
final TusAttachmentGenerator tusAttachmentGenerator,
final long maxUploadLength) {
final PostPolicyGenerator stickerPolicyGenerator,
final long maxUploadLength,
final Clock clock) {
this.experimentEnrollmentManager = experimentEnrollmentManager;
this.countRateLimiter = rateLimiters.getAttachmentLimiter();
this.bytesRateLimiter = rateLimiters.getAttachmentBytesLimiter();
this.stickerPackLimiter = rateLimiters.getStickerPackLimiter();
this.stickerPolicyGenerator = stickerPolicyGenerator;
this.maxUploadLength = maxUploadLength;
this.clock = clock;
this.secureRandom = new SecureRandom();
this.attachmentGenerators = Map.of(
2, gcsAttachmentGenerator,
@@ -67,6 +99,11 @@ public class AttachmentsGrpcService extends SimpleAttachmentsGrpc.AttachmentsImp
throw e;
}
DistributionSummary.builder(ATTACHMENT_SIZE_NAME)
.tags(Tags.of(UserAgentTagUtil.getPlatformTag(RequestAttributesUtil.getUserAgent().orElse(null))))
.register(Metrics.globalRegistry)
.record(request.getUploadLength());
final String key = AttachmentUtil.generateAttachmentKey(secureRandom);
final boolean useCdn3 = this.experimentEnrollmentManager.isEnrolled(auth.accountIdentifier(),
AttachmentUtil.CDN3_EXPERIMENT_NAME);
@@ -80,4 +117,59 @@ public class AttachmentsGrpcService extends SimpleAttachmentsGrpc.AttachmentsImp
.setSignedUploadLocation(descriptor.signedUploadLocation()))
.build();
}
@Override
public GetStickerUploadFormResponse getStickerUploadForm(final GetStickerUploadFormRequest request)
throws RateLimitExceededException {
stickerPackLimiter.validate(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier());
final Instant currentTime = clock.instant();
final String packId;
{
final byte[] packIdBytes = new byte[16];
secureRandom.nextBytes(packIdBytes);
packId = HexFormat.of().formatHex(packIdBytes);
}
final String packLocation = "stickers/" + packId;
final GetStickerUploadFormResponse.Builder responseBuilder = GetStickerUploadFormResponse.newBuilder()
.setPackId(packId);
{
final String manifestKey = packLocation + "/manifest.proto";
final PostPolicyGenerator.SignedPostPolicy manifestPolicy =
stickerPolicyGenerator.createFor(manifestKey, StickerController.MAXIMUM_STICKER_MANIFEST_SIZE_BYTES, currentTime);
responseBuilder
.setManifestUploadForm(PROTOTYPE_STICKER_UPLOAD_FORM.toBuilder()
.setKey(manifestKey)
.setCredential(manifestPolicy.credential())
.setDate(manifestPolicy.formattedTimestamp())
.setPolicy(manifestPolicy.encodedPolicy())
.setSignature(manifestPolicy.signature())
.build());
}
IntStream.range(0, request.getStickerCount())
.mapToObj(i -> {
final String stickerKey = packLocation + "/full/" + i;
final PostPolicyGenerator.SignedPostPolicy stickerPolicy =
stickerPolicyGenerator.createFor(stickerKey, StickerController.MAXIMUM_STICKER_SIZE_BYTES, currentTime);
return PROTOTYPE_STICKER_UPLOAD_FORM.toBuilder()
.setKey(stickerKey)
.setCredential(stickerPolicy.credential())
.setDate(stickerPolicy.formattedTimestamp())
.setPolicy(stickerPolicy.encodedPolicy())
.setSignature(stickerPolicy.signature())
.build();
})
.forEach(responseBuilder::addStickerUploadForms);
return responseBuilder.build();
}
}
@@ -8,6 +8,8 @@ import com.google.protobuf.ByteString;
import com.google.protobuf.Empty;
import java.util.Optional;
import java.util.concurrent.Flow;
import io.micrometer.core.instrument.Tag;
import org.signal.chat.backup.BackupStreamClosed;
import org.signal.chat.backup.CopyMediaRequest;
import org.signal.chat.backup.CopyMediaResponse;
import org.signal.chat.backup.DeleteAllRequest;
@@ -223,20 +225,21 @@ public class BackupsAnonymousGrpcService extends SimpleBackupsAnonymousGrpc.Back
copyQuota = backupManager.getCopyQuota(backupUser,
request.getItemsList().stream().map(item -> new CopyParameters(
item.getSourceAttachmentCdn(), item.getSourceKey(),
// uint32 in proto, make sure it fits in a signed int
fromUnsignedExact(item.getObjectLength()),
item.getObjectLength(),
new MediaEncryptionParameters(item.getEncryptionKey().toByteArray(), item.getHmacKey().toByteArray()),
item.getMediaId().toByteArray())).toList(), maxAttachmentSize);
} catch (BackupFailedZkAuthenticationException e) {
return JdkFlowAdapter.publisherToFlowPublisher(Mono.just(CopyMediaResponse
.newBuilder()
.setFailedAuthentication(FailedZkAuthentication.newBuilder().setDescription(e.getMessage()))
.build()));
return JdkFlowAdapter.publisherToFlowPublisher(
Mono.error(GrpcExceptions.streamClosed(BackupStreamClosed.newBuilder()
.setFailedAuthentication(FailedZkAuthentication.newBuilder()
.setDescription(e.getMessage())
.build())
.build())));
}
final Tag platformTag = UserAgentTagUtil.getPlatformTag(RequestAttributesUtil.getUserAgent().orElse(null));
return JdkFlowAdapter.publisherToFlowPublisher(backupManager.copyToBackup(copyQuota)
.doOnNext(result -> backupMetrics.updateCopyCounter(
result,
UserAgentTagUtil.getPlatformTag(RequestAttributesUtil.getUserAgent().orElse(null))))
.doOnNext(result -> backupMetrics.updateCopyCounter(result, platformTag))
.map(copyResult -> {
CopyMediaResponse.Builder builder = CopyMediaResponse
.newBuilder()
@@ -308,10 +311,12 @@ public class BackupsAnonymousGrpcService extends SimpleBackupsAnonymousGrpc.Back
.map(item -> new BackupManager.StorageDescriptor(item.getCdn(), item.getMediaId().toByteArray()))
.toList());
} catch (BackupFailedZkAuthenticationException e) {
return JdkFlowAdapter.publisherToFlowPublisher(Mono.just(DeleteMediaResponse
.newBuilder()
.setFailedAuthentication(FailedZkAuthentication.newBuilder().setDescription(e.getMessage()))
.build()));
return JdkFlowAdapter.publisherToFlowPublisher(
Mono.error(GrpcExceptions.streamClosed(BackupStreamClosed.newBuilder()
.setFailedAuthentication(FailedZkAuthentication.newBuilder()
.setDescription(e.getMessage())
.build())
.build())));
}
return JdkFlowAdapter.publisherToFlowPublisher(deleteItems
.map(storageDescriptor -> DeleteMediaResponse.newBuilder()
@@ -346,17 +351,6 @@ public class BackupsAnonymousGrpcService extends SimpleBackupsAnonymousGrpc.Back
}
}
/**
* Convert an int from a proto uint32 to a signed positive integer, throwing if the value exceeds
* {@link Integer#MAX_VALUE}. To convert to a long, see {@link Integer#toUnsignedLong(int)}
*/
private static int fromUnsignedExact(final int i) {
if (i < 0) {
throw GrpcExceptions.invalidArguments("integer length too large");
}
return i;
}
private interface Deserializer<T> {
T deserialize(byte[] bytes) throws InvalidInputException, InvalidKeyException;
@@ -0,0 +1,32 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc;
import org.signal.chat.common.Badge;
import org.signal.chat.common.BadgeSvg;
public class BadgeGrpcHelper {
public static Badge toGrpcBadge(final org.whispersystems.textsecuregcm.entities.Badge badge) {
final Badge.Builder builder = Badge.newBuilder()
.setId(badge.getId())
.setCategory(badge.getCategory())
.setName(badge.getName())
.setDescription(badge.getDescription())
.addAllSprites6(badge.getSprites6())
.setSvg(badge.getSvg());
badge.getSvgs().stream()
.map(badgeSvg -> BadgeSvg.newBuilder()
.setDark(badgeSvg.getDark())
.setLight(badgeSvg.getLight())
.build())
.forEach(builder::addSvgs);
return builder.build();
}
}
@@ -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);
@@ -8,8 +8,12 @@ package org.whispersystems.textsecuregcm.grpc;
import com.google.protobuf.ByteString;
import java.time.Clock;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Map;
import java.util.UUID;
import org.signal.chat.credentials.ExternalServiceType;
import org.signal.chat.credentials.GetCreateCallLinkCredentialsRequest;
import org.signal.chat.credentials.GetCreateCallLinkCredentialsResponse;
import org.signal.chat.credentials.GetDeliveryCertificateRequest;
import org.signal.chat.credentials.GetDeliveryCertificateResponse;
import org.signal.chat.credentials.GetExternalServiceCredentialsRequest;
@@ -19,8 +23,10 @@ import org.signal.chat.credentials.GetGroupCredentialsResponse;
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.ServerZkAuthOperations;
import org.signal.libsignal.zkgroup.calllinks.CallLinkAuthCredentialResponse;
import org.signal.libsignal.zkgroup.calllinks.CreateCallLinkCredentialRequest;
import org.whispersystems.textsecuregcm.auth.CertificateGenerator;
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
@@ -87,12 +93,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
@@ -133,4 +143,30 @@ public class CredentialsGrpcService extends SimpleCredentialsGrpc.CredentialsImp
return responseBuilder.build();
}
@Override
public GetCreateCallLinkCredentialsResponse getCreateCallLinkCredentials(final GetCreateCallLinkCredentialsRequest request)
throws RateLimitExceededException {
final UUID accountIdentifier = AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier();
rateLimiters.getCreateCallLinkLimiter().validate(accountIdentifier);
final Instant truncatedDayTimestamp = clock.instant().truncatedTo(ChronoUnit.DAYS);
try {
final CreateCallLinkCredentialRequest createCallLinkCredentialRequest =
new CreateCallLinkCredentialRequest(request.getCredentialRequest().toByteArray());
return GetCreateCallLinkCredentialsResponse.newBuilder()
.setRedemptionTimeSeconds(truncatedDayTimestamp.getEpochSecond())
.setCredential(ByteString.copyFrom(createCallLinkCredentialRequest.issueCredential(
new ServiceId.Aci(accountIdentifier),
truncatedDayTimestamp,
serverSecretParams)
.serialize()))
.build();
} catch (final InvalidInputException e) {
throw GrpcExceptions.invalidArguments("Invalid 'create call link credential' request");
}
}
}
@@ -138,7 +138,9 @@ public class DevicesGrpcService extends SimpleDevicesGrpc.DevicesImplBase {
final Device device = account.getDevice(authenticatedDevice.deviceId())
.orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials"));
if (!Objects.equals(device.getApnId(), apnsToken) || !Objects.equals(device.getGcmId(), fcmToken)) {
// Unlike FCM tokens, we need current "last updated" timestamps for APNs tokens and so update device records
// unconditionally if it's an APNS request
if (request.hasApnsTokenRequest() || !Objects.equals(device.getGcmId(), fcmToken)) {
accountsManager.updateDevice(account.getIdentifier(IdentityType.ACI), authenticatedDevice.deviceId(), d -> {
d.setApnId(apnsToken);
d.setGcmId(fcmToken);
@@ -1,8 +1,11 @@
package org.whispersystems.textsecuregcm.grpc;
import com.google.protobuf.ByteString;
import com.google.protobuf.Empty;
import java.time.Clock;
import java.time.Instant;
import org.signal.chat.donations.CreateDonationPermitRequest;
import org.signal.chat.donations.CreateDonationPermitResponse;
import org.signal.chat.donations.RedeemReceiptRequest;
import org.signal.chat.donations.RedeemReceiptResponse;
import org.signal.chat.donations.SimpleDonationsGrpc;
@@ -10,6 +13,8 @@ import org.signal.chat.errors.FailedPrecondition;
import org.signal.chat.errors.FailedZkAuthentication;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.VerificationFailedException;
import org.signal.libsignal.zkgroup.donation.DonationPermitRequest;
import org.signal.libsignal.zkgroup.donation.DonationPermitResponse;
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialPresentation;
import org.signal.libsignal.zkgroup.receipts.ReceiptSerial;
import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations;
@@ -18,8 +23,10 @@ import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
import org.whispersystems.textsecuregcm.configuration.BadgesConfiguration;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.storage.AccountBadge;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.DonationPermitsManager;
import org.whispersystems.textsecuregcm.storage.RedeemedReceiptsManager;
import org.whispersystems.textsecuregcm.subscriptions.ReceiptCredentialPresentationFactory;
@@ -31,6 +38,8 @@ public class DonationsGrpcService extends SimpleDonationsGrpc.DonationsImplBase
private final AccountsManager accountsManager;
private final BadgesConfiguration badgesConfiguration;
private final ReceiptCredentialPresentationFactory receiptCredentialPresentationFactory;
private final DonationPermitsManager donationPermitsManager;
private final RateLimiters rateLimiters;
private static final Logger LOGGER = LoggerFactory.getLogger(DonationsGrpcService.class);
@@ -40,7 +49,9 @@ public class DonationsGrpcService extends SimpleDonationsGrpc.DonationsImplBase
final RedeemedReceiptsManager redeemedReceiptsManager,
final AccountsManager accountsManager,
final BadgesConfiguration badgesConfiguration,
final ReceiptCredentialPresentationFactory receiptCredentialPresentationFactory) {
final ReceiptCredentialPresentationFactory receiptCredentialPresentationFactory,
final DonationPermitsManager donationPermitsManager,
final RateLimiters rateLimiters) {
this.clock = clock;
this.serverZkReceiptOperations = serverZkReceiptOperations;
@@ -48,6 +59,8 @@ public class DonationsGrpcService extends SimpleDonationsGrpc.DonationsImplBase
this.accountsManager = accountsManager;
this.badgesConfiguration = badgesConfiguration;
this.receiptCredentialPresentationFactory = receiptCredentialPresentationFactory;
this.donationPermitsManager = donationPermitsManager;
this.rateLimiters = rateLimiters;
}
@Override
@@ -101,4 +114,23 @@ public class DonationsGrpcService extends SimpleDonationsGrpc.DonationsImplBase
.build();
}
}
@Override
public CreateDonationPermitResponse createDonationPermit(final CreateDonationPermitRequest request) throws Exception {
final DonationPermitRequest permitRequest;
try {
permitRequest = new DonationPermitRequest(request.getDonationPermitRequest().toByteArray());
} catch (InvalidInputException e) {
throw GrpcExceptions.invalidArguments("invalid permit request");
}
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
rateLimiters.getCreateDonationPermitLimiter().validate(authenticatedDevice.accountIdentifier(), permitRequest.getPermitCount());
final DonationPermitResponse permitResponse = donationPermitsManager.issue(permitRequest);
return CreateDonationPermitResponse.newBuilder()
.setDonationPermitResponse(ByteString.copyFrom(permitResponse.serialize()))
.build();
}
}
@@ -39,7 +39,7 @@ public class ErrorConformanceInterceptor implements ServerInterceptor {
}
switch (status.getCode()) {
case UNAUTHENTICATED, UNAVAILABLE, INVALID_ARGUMENT, RESOURCE_EXHAUSTED -> {
case UNAUTHENTICATED, UNAVAILABLE, INVALID_ARGUMENT, RESOURCE_EXHAUSTED, ABORTED -> {
}
default -> {
log.error("Intercepted call {} returned illegal application status {}: {}",
@@ -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());
@@ -39,6 +39,11 @@ public class GrpcExceptions {
.setReason("BAD_AUTHENTICATION")
.build());
private static final Any ERROR_INFO_STREAM_CLOSED = Any.pack(ErrorInfo.newBuilder()
.setDomain(DOMAIN)
.setReason("STREAM_CLOSED")
.build());
private static final com.google.rpc.Status UPGRADE_REQUIRED = com.google.rpc.Status.newBuilder()
.setCode(Status.Code.INVALID_ARGUMENT.value())
.setMessage("Upgrade required")
@@ -144,6 +149,20 @@ public class GrpcExceptions {
return StatusProto.toStatusRuntimeException(builder.build());
}
/// The server terminated the stream non-successfully for a reason specific to the RPC. The server must provide
/// additional information about the stream closure reason via the `streamClosedMessage`.
///
/// @param streamClosedMessage The additional domain-specific proto message that indicates the closure reason
/// @return A [StatusRuntimeException] encoding the error
public static <T extends com.google.protobuf.Message> StatusRuntimeException streamClosed(
final T streamClosedMessage) {
return StatusProto.toStatusRuntimeException(com.google.rpc.Status.newBuilder()
.setCode(Status.Code.ABORTED.value())
.addDetails(ERROR_INFO_STREAM_CLOSED)
.addDetails(Any.pack(streamClosedMessage))
.build());
}
public static StatusRuntimeException unavailable() {
return unavailable(null);
}
@@ -15,8 +15,10 @@ import org.signal.keytransparency.client.E164MonitorRequest;
import org.signal.keytransparency.client.E164SearchRequest;
import org.signal.keytransparency.client.MonitorRequest;
import org.signal.keytransparency.client.MonitorResponse;
import org.signal.keytransparency.client.MonitorResponseV2;
import org.signal.keytransparency.client.SearchRequest;
import org.signal.keytransparency.client.SearchResponse;
import org.signal.keytransparency.client.SearchResponseV2;
import org.signal.keytransparency.client.SimpleKeyTransparencyQueryServiceGrpc;
import org.signal.keytransparency.client.UsernameHashMonitorRequest;
import org.whispersystems.textsecuregcm.controllers.AccountController;
@@ -39,102 +41,51 @@ public class KeyTransparencyGrpcService extends
}
@Override
public SearchResponse search(final SearchRequest request) throws RateLimitExceededException {
public SearchResponseV2 searchV2(final SearchRequest request) throws RateLimitExceededException {
rateLimiters.getKeyTransparencySearchLimiter().validate(RequestAttributesUtil.getRemoteAddress().getHostAddress());
return client.search(validateSearchRequest(request));
}
@Override
public MonitorResponse monitor(final MonitorRequest request) throws RateLimitExceededException {
public MonitorResponseV2 monitorV2(final MonitorRequest request) throws RateLimitExceededException {
rateLimiters.getKeyTransparencyMonitorLimiter().validate(RequestAttributesUtil.getRemoteAddress().getHostAddress());
return client.monitor(validateMonitorRequest(request));
}
@Override
public DistinguishedResponse distinguished(final DistinguishedRequest request) throws RateLimitExceededException {
public DistinguishedResponse distinguishedV2(final DistinguishedRequest request) throws RateLimitExceededException {
rateLimiters.getKeyTransparencyDistinguishedLimiter().validate(RequestAttributesUtil.getRemoteAddress().getHostAddress());
// A client's very first distinguished request will not have a "last" parameter
if (request.hasLast() && request.getLast() <= 0) {
throw Status.INVALID_ARGUMENT.withDescription("Last tree head size must be positive").asRuntimeException();
}
return client.distinguished(request);
}
private SearchRequest validateSearchRequest(final SearchRequest request) {
validateAci(request.getAci().toByteArray());
if (request.hasE164SearchRequest()) {
final E164SearchRequest e164SearchRequest = request.getE164SearchRequest();
if (e164SearchRequest.getUnidentifiedAccessKey().isEmpty() != e164SearchRequest.getE164().isEmpty()) {
throw Status.INVALID_ARGUMENT.withDescription("Unidentified access key and E164 must be provided together or not at all").asRuntimeException();
throw GrpcExceptions.fieldViolation("e164_search_request", "Unidentified access key and E164 must be provided together or not at all");
}
}
if (!request.getConsistency().hasDistinguished()) {
throw Status.INVALID_ARGUMENT.withDescription("Must provide distinguished tree head size").asRuntimeException();
}
validateConsistencyParameters(request.getConsistency());
return request;
}
private void validateAci(final byte[] aci) {
try {
AciServiceIdentifier.fromBytes(aci);
} catch (IllegalArgumentException e) {
throw GrpcExceptions.fieldViolation("aci", "Invalid ACI");
}
}
private MonitorRequest validateMonitorRequest(final MonitorRequest request) {
final AciMonitorRequest aciMonitorRequest = request.getAci();
validateAci(request.getAci().getAci().toByteArray());
try {
AciServiceIdentifier.fromBytes(aciMonitorRequest.getAci().toByteArray());
} catch (IllegalArgumentException e) {
throw Status.INVALID_ARGUMENT.withDescription("Invalid ACI").asRuntimeException();
}
if (aciMonitorRequest.getEntryPosition() <= 0) {
throw Status.INVALID_ARGUMENT.withDescription("Aci entry position must be positive").asRuntimeException();
}
if (aciMonitorRequest.getCommitmentIndex().size() != COMMITMENT_INDEX_LENGTH) {
throw Status.INVALID_ARGUMENT.withDescription("Aci commitment index must be 32 bytes").asRuntimeException();
if (!request.getConsistency().hasLast()) {
throw GrpcExceptions.fieldViolation("consistency_last", "Must provide distinguished and last tree head sizes");
}
if (request.hasUsernameHash()) {
final UsernameHashMonitorRequest usernameHashMonitorRequest = request.getUsernameHash();
if (usernameHashMonitorRequest.getUsernameHash().isEmpty()) {
throw Status.INVALID_ARGUMENT.withDescription("Username hash cannot be empty").asRuntimeException();
}
if (usernameHashMonitorRequest.getUsernameHash().size() != AccountController.USERNAME_HASH_LENGTH) {
throw Status.INVALID_ARGUMENT.withDescription("Invalid username hash length").asRuntimeException();
}
if (usernameHashMonitorRequest.getEntryPosition() <= 0) {
throw Status.INVALID_ARGUMENT.withDescription("Username hash entry position must be positive").asRuntimeException();
}
if (usernameHashMonitorRequest.getCommitmentIndex().size() != COMMITMENT_INDEX_LENGTH) {
throw Status.INVALID_ARGUMENT.withDescription("Username hash commitment index must be 32 bytes").asRuntimeException();
}
}
if (request.hasE164()) {
final E164MonitorRequest e164MonitorRequest = request.getE164();
if (e164MonitorRequest.getE164().isEmpty()) {
throw Status.INVALID_ARGUMENT.withDescription("E164 cannot be empty").asRuntimeException();
}
if (e164MonitorRequest.getEntryPosition() <= 0) {
throw Status.INVALID_ARGUMENT.withDescription("E164 entry position must be positive").asRuntimeException();
}
if (e164MonitorRequest.getCommitmentIndex().size() != COMMITMENT_INDEX_LENGTH) {
throw Status.INVALID_ARGUMENT.withDescription("E164 commitment index must be 32 bytes").asRuntimeException();
}
}
if (!request.getConsistency().hasDistinguished() || !request.getConsistency().hasLast()) {
throw Status.INVALID_ARGUMENT.withDescription("Must provide distinguished and last tree head sizes").asRuntimeException();
}
validateConsistencyParameters(request.getConsistency());
return request;
}
private static void validateConsistencyParameters(final ConsistencyParameters consistency) {
if (consistency.getDistinguished() <= 0) {
throw Status.INVALID_ARGUMENT.withDescription("Distinguished tree head size must be positive").asRuntimeException();
}
if (consistency.hasLast() && consistency.getLast() <= 0) {
throw Status.INVALID_ARGUMENT.withDescription("Last tree head size must be positive").asRuntimeException();
}
}
}
@@ -6,19 +6,31 @@
package org.whispersystems.textsecuregcm.grpc;
import com.google.protobuf.ByteString;
import java.util.Arrays;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import io.grpc.StatusRuntimeException;
import org.signal.chat.common.EcPreKey;
import org.signal.chat.common.EcSignedPreKey;
import org.signal.chat.common.KemSignedPreKey;
import org.signal.chat.keys.AccountPreKeyBundles;
import org.signal.chat.keys.DevicePreKeyBundle;
import org.signal.libsignal.protocol.IdentityKey;
import org.signal.libsignal.protocol.InvalidKeyException;
import org.signal.libsignal.protocol.ecc.ECPublicKey;
import org.signal.libsignal.protocol.kem.KEMPublicKey;
import org.whispersystems.textsecuregcm.entities.ECPreKey;
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessChecksum;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import org.whispersystems.textsecuregcm.storage.KeyIdUtil;
import org.whispersystems.textsecuregcm.storage.KeysManager;
@@ -63,7 +75,16 @@ class KeysGrpcHelper {
}
final AccountPreKeyBundles.Builder preKeyBundlesBuilder = AccountPreKeyBundles.newBuilder()
.setIdentityKey(ByteString.copyFrom(targetAccount.getIdentityKey(targetServiceIdentifier.identityType()).serialize()));
.setIdentityKey(ByteString.copyFrom(targetAccount.getIdentityKey(targetServiceIdentifier.identityType()).serialize()))
.setUnrestrictedUnidentifiedAccess(targetServiceIdentifier.identityType() == IdentityType.ACI && targetAccount.isUnrestrictedUnidentifiedAccess());
// Set the UAK hash if the account has a UAK and we're targeting an ACI. PNIs don't allow unidentified access.
targetAccount
.getUnidentifiedAccessKey()
.filter(_ -> targetServiceIdentifier.identityType() == IdentityType.ACI)
.map(UnidentifiedAccessChecksum::generateFor)
.map(ByteString::copyFrom)
.ifPresent(preKeyBundlesBuilder::setUnidentifiedAccessKeyFingerprint);
preKeysByDeviceId.forEach((deviceId, devicePreKeys) -> {
final Device device = targetAccount.getDevice(deviceId).orElseThrow();
@@ -89,4 +110,46 @@ class KeysGrpcHelper {
return Optional.of(preKeyBundlesBuilder.build());
}
public static ECPreKey checkEcPreKey(final EcPreKey preKey, final StatusRuntimeException invalidPublicKeyException) {
try {
return new ECPreKey(preKey.getKeyId(), new ECPublicKey(preKey.getPublicKey().toByteArray()));
} catch (final InvalidKeyException e) {
throw invalidPublicKeyException;
}
}
public static ECSignedPreKey checkEcSignedPreKey(final EcSignedPreKey preKey, final IdentityKey identityKey,
final StatusRuntimeException invalidPublicKeyException, final StatusRuntimeException invalidSignatureException) {
try {
final ECSignedPreKey ecSignedPreKey = new ECSignedPreKey(preKey.getKeyId(),
new ECPublicKey(preKey.getPublicKey().toByteArray()),
preKey.getSignature().toByteArray());
if (ecSignedPreKey.signatureValid(identityKey)) {
return ecSignedPreKey;
} else {
throw invalidSignatureException;
}
} catch (final InvalidKeyException e) {
throw invalidPublicKeyException;
}
}
public static KEMSignedPreKey checkKemSignedPreKey(final KemSignedPreKey preKey, final IdentityKey identityKey,
final StatusRuntimeException invalidPublicKeyException, final StatusRuntimeException invalidSignatureException) {
try {
final KEMSignedPreKey kemSignedPreKey = new KEMSignedPreKey(preKey.getKeyId(),
new KEMPublicKey(preKey.getPublicKey().toByteArray()),
preKey.getSignature().toByteArray());
if (kemSignedPreKey.signatureValid(identityKey)) {
return kemSignedPreKey;
} else {
throw invalidSignatureException;
}
} catch (final InvalidKeyException e) {
throw invalidPublicKeyException;
}
}
}
@@ -11,9 +11,6 @@ import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.function.BiFunction;
import org.signal.chat.common.EcPreKey;
import org.signal.chat.common.EcSignedPreKey;
import org.signal.chat.common.KemSignedPreKey;
import org.signal.chat.errors.NotFound;
import org.signal.chat.keys.GetPreKeyCountRequest;
import org.signal.chat.keys.GetPreKeyCountResponse;
@@ -26,16 +23,10 @@ import org.signal.chat.keys.SetOneTimeKemSignedPreKeysRequest;
import org.signal.chat.keys.SetPreKeyResponse;
import org.signal.chat.keys.SimpleKeysGrpc;
import org.signal.libsignal.protocol.IdentityKey;
import org.signal.libsignal.protocol.InvalidKeyException;
import org.signal.libsignal.protocol.ecc.ECPublicKey;
import org.signal.libsignal.protocol.kem.KEMPublicKey;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.controllers.RateLimitKeys;
import org.whispersystems.textsecuregcm.entities.ECPreKey;
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
@@ -136,7 +127,7 @@ public class KeysGrpcService extends SimpleKeysGrpc.KeysImplBase {
storeOneTimePreKeys(authenticatedDevice.accountIdentifier(),
request.getPreKeysList(),
IdentityTypeUtil.fromGrpcIdentityType(request.getIdentityType()),
(requestPreKey, _) -> checkEcPreKey(requestPreKey),
(requestPreKey, _) -> KeysGrpcHelper.checkEcPreKey(requestPreKey, INVALID_PUBLIC_KEY_EXCEPTION),
(identifier, preKeys) -> keysManager.storeEcOneTimePreKeys(identifier, authenticatedDevice.deviceId(), preKeys));
return SetPreKeyResponse.getDefaultInstance();
@@ -149,7 +140,7 @@ public class KeysGrpcService extends SimpleKeysGrpc.KeysImplBase {
storeOneTimePreKeys(authenticatedDevice.accountIdentifier(),
request.getPreKeysList(),
IdentityTypeUtil.fromGrpcIdentityType(request.getIdentityType()),
KeysGrpcService::checkKemSignedPreKey,
(preKey, identityKey) -> KeysGrpcHelper.checkKemSignedPreKey(preKey, identityKey, INVALID_PUBLIC_KEY_EXCEPTION, INVALID_SIGNATURE_EXCEPTION),
(identifier, preKeys) -> keysManager.storeKemOneTimePreKeys(identifier, authenticatedDevice.deviceId(), preKeys));
return SetPreKeyResponse.getDefaultInstance();
@@ -177,7 +168,7 @@ public class KeysGrpcService extends SimpleKeysGrpc.KeysImplBase {
storeRepeatedUseKey(authenticatedDevice.accountIdentifier(),
request.getIdentityType(),
request.getSignedPreKey(),
KeysGrpcService::checkEcSignedPreKey,
(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);
@@ -195,7 +186,7 @@ public class KeysGrpcService extends SimpleKeysGrpc.KeysImplBase {
storeRepeatedUseKey(authenticatedDevice.accountIdentifier(),
request.getIdentityType(),
request.getSignedPreKey(),
KeysGrpcService::checkKemSignedPreKey,
(preKey, identityKey) -> KeysGrpcHelper.checkKemSignedPreKey(preKey, identityKey, INVALID_PUBLIC_KEY_EXCEPTION, INVALID_SIGNATURE_EXCEPTION),
(account, lastResortKey) -> {
final UUID identifier =
account.getIdentifier(IdentityTypeUtil.fromGrpcIdentityType(request.getIdentityType()));
@@ -220,45 +211,6 @@ public class KeysGrpcService extends SimpleKeysGrpc.KeysImplBase {
storeKeyFunction.apply(account, key).join();
}
private static ECPreKey checkEcPreKey(final EcPreKey preKey) {
try {
return new ECPreKey(preKey.getKeyId(), new ECPublicKey(preKey.getPublicKey().toByteArray()));
} catch (final InvalidKeyException e) {
throw INVALID_PUBLIC_KEY_EXCEPTION;
}
}
private static ECSignedPreKey checkEcSignedPreKey(final EcSignedPreKey preKey, final IdentityKey identityKey) {
try {
final ECSignedPreKey ecSignedPreKey = new ECSignedPreKey(preKey.getKeyId(),
new ECPublicKey(preKey.getPublicKey().toByteArray()),
preKey.getSignature().toByteArray());
if (ecSignedPreKey.signatureValid(identityKey)) {
return ecSignedPreKey;
} else {
throw INVALID_SIGNATURE_EXCEPTION;
}
} catch (final InvalidKeyException e) {
throw INVALID_PUBLIC_KEY_EXCEPTION;
}
}
private static KEMSignedPreKey checkKemSignedPreKey(final KemSignedPreKey preKey, final IdentityKey identityKey) {
try {
final KEMSignedPreKey kemSignedPreKey = new KEMSignedPreKey(preKey.getKeyId(),
new KEMPublicKey(preKey.getPublicKey().toByteArray()),
preKey.getSignature().toByteArray());
if (kemSignedPreKey.signatureValid(identityKey)) {
return kemSignedPreKey;
} else {
throw INVALID_SIGNATURE_EXCEPTION;
}
} catch (final InvalidKeyException e) {
throw INVALID_PUBLIC_KEY_EXCEPTION;
}
}
private Account getAuthenticatedAccount(final UUID authenticatedAccountId) {
return accountsManager.getByAccountIdentifier(authenticatedAccountId)
@@ -6,11 +6,13 @@ package org.whispersystems.textsecuregcm.grpc;
import com.google.common.annotations.VisibleForTesting;
import com.google.protobuf.Empty;
import io.grpc.StatusRuntimeException;
import io.micrometer.core.instrument.Metrics;
import java.time.Duration;
import java.util.UUID;
import javax.annotation.Nullable;
import org.signal.chat.messages.GetMessagesResponse;
import org.signal.chat.messages.GetMessagesStreamClosed;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestListener;
@@ -54,14 +56,10 @@ public class MessageDispatcher {
public static final GetMessagesResponse QUEUE_EMPTY_RESPONSE =
GetMessagesResponse.newBuilder().setQueueEmpty(Empty.getDefaultInstance()).build();
private static final GetMessagesResponse CONFLICTING_STREAM_RESPONSE = GetMessagesResponse.newBuilder()
.setTerminated(GetMessagesResponse.Terminated.newBuilder()
.setConflictingStream(Empty.getDefaultInstance()))
.build();
private static final GetMessagesResponse REAUTHENTICATION_REQUIRED_RESPONSE = GetMessagesResponse.newBuilder()
.setTerminated(GetMessagesResponse.Terminated.newBuilder()
.setReauthenticationRequired(Empty.getDefaultInstance()))
.build();
private static final StatusRuntimeException CONFLICTING_STREAM_EXCEPTION =
GrpcExceptions.streamClosed(GetMessagesStreamClosed.newBuilder()
.setConflictingStream(Empty.getDefaultInstance())
.build());
private static final String SEND_MESSAGES_FLUX_NAME = MetricsUtil.name(MessageDispatcher.class, "sendMessages");
@@ -99,8 +97,8 @@ public class MessageDispatcher {
/// terminates for any reason. The error from the client will be propagated to the returned flux. The stream may also
/// terminate with any other error encountered retrieving messages or processing acknowledgements.
///
/// The returned flux will emit a [GetMessagesResponse.Terminated] and then complete if
/// - A disconnection request (typically indicating a change in authorization credentials) is received.
/// The returned flux will error with a [GrpcExceptions#streamClosed] non-ok status exception if:
/// - A disconnection request (typically indicating a change in authorization credentials) is received
/// - A client requests messages for the same account/device while this stream is still active
///
/// When the stream terminates for any reason and the client has messages remaining in their queue, a push
@@ -167,7 +165,11 @@ public class MessageDispatcher {
pendingAcknowledgementTracker.markEndOfQueue();
yield Mono.empty();
}
}, MAX_UNACKED_MESSAGES);
}, MAX_UNACKED_MESSAGES)
.onErrorMap(ConflictingMessageConsumerException.class, _ -> {
messageMetrics.measureMessageStreamDisplaced(MessageMetrics.GRPC_CHANNEL, userAgent, true);
return CONFLICTING_STREAM_EXCEPTION;
});
// Only emit envelopes when the permit flux emits a value. Initially it is seeded MAX_UNACKED_MESSAGES permits,
// after that a permit is emitted every time we receive an ack.
@@ -204,18 +206,8 @@ public class MessageDispatcher {
ackCompletions,
// Emits a queue empty once all messages prior to the queueEmpty signal have been acked
pendingAcknowledgementTracker.queueDrained(),
// Emit a Terminated response if we receive a disconnection request
disconnectionSignal(account, device))
.onErrorResume(ConflictingMessageConsumerException.class, _ -> Mono.just(CONFLICTING_STREAM_RESPONSE))
.takeUntil(response -> switch (response.getResponseCase()) {
case ENVELOPE, QUEUE_EMPTY -> false;
case TERMINATED -> {
messageMetrics.measureMessageStreamDisplaced(MessageMetrics.GRPC_CHANNEL, userAgent,
response.getTerminated().hasConflictingStream());
yield true;
}
case RESPONSE_NOT_SET -> throw new IllegalStateException("tried to return an invalid GetMessagesResponse");
})
// Emit an invalid credentials error if we receive a disconnection request
disconnectionSignal(account, device, userAgent))
.doFinally(_ -> maybeSchedulePush(account, device));
}
@@ -232,13 +224,16 @@ public class MessageDispatcher {
/// Watch for a disconnection signal from the [DisconnectionRequestManager]
///
/// @return Mono that completes with a [org.signal.chat.messages.GetMessagesResponse.Terminated] response if the
/// @return Mono that completes with an `InvalidCredentials` status if the
/// device receives a disconnection request
private Mono<GetMessagesResponse> disconnectionSignal(final Account account, final Device device) {
private Mono<GetMessagesResponse> disconnectionSignal(final Account account, final Device device, final UserAgent userAgent) {
return Mono.create(sink -> {
final DisconnectionRequestListener listener = () -> sink.success(REAUTHENTICATION_REQUIRED_RESPONSE);
disconnectionRequestManager.addListener(account.getUuid(), device.getId(), listener);
sink.onDispose(() -> disconnectionRequestManager.removeListener(account.getUuid(), device.getId(), listener));
final DisconnectionRequestListener listener = () -> {
messageMetrics.measureMessageStreamDisplaced(MessageMetrics.GRPC_CHANNEL, userAgent, false);
sink.error(GrpcExceptions.invalidCredentials("reauthentication required"));
};
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,
@@ -30,6 +30,7 @@ import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.LongAdder;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -65,12 +66,19 @@ public class MetricServerInterceptor implements ServerInterceptor {
@VisibleForTesting
static final String DURATION_TIMER_NAME = MetricsUtil.name(MetricServerInterceptor.class, "processingDuration");
private static final String ACTIVE_REQUESTS_GAUGE_NAME =
MetricsUtil.name(MetricServerInterceptor.class, "activeRequests");
private final MeterRegistry meterRegistry;
private final ClientReleaseManager clientReleaseManager;
private final LongAdder activeRequests;
public MetricServerInterceptor(final MeterRegistry meterRegistry, final ClientReleaseManager clientReleaseManager) {
this.meterRegistry = meterRegistry;
this.clientReleaseManager = clientReleaseManager;
this.activeRequests = meterRegistry.gauge(ACTIVE_REQUESTS_GAUGE_NAME, new LongAdder());
}
@Override
@@ -194,6 +202,8 @@ public class MetricServerInterceptor implements ServerInterceptor {
this.requestBytesCounter = meterRegistry.counter(REQUEST_BYTES_COUNTER_NAME, tags);
this.responseTimer = meterRegistry.timer(DURATION_TIMER_NAME, tags);
this.sample = Timer.start(meterRegistry);
activeRequests.increment();
}
@Override
@@ -210,12 +220,14 @@ public class MetricServerInterceptor implements ServerInterceptor {
@Override
public void onComplete() {
this.sample.stop(responseTimer);
activeRequests.decrement();
super.onComplete();
}
@Override
public void onCancel() {
this.sample.stop(responseTimer);
activeRequests.decrement();
super.onCancel();
}
}
@@ -0,0 +1,130 @@
package org.whispersystems.textsecuregcm.grpc;
import java.math.BigDecimal;
import java.time.Duration;
import java.util.List;
import java.util.Locale;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration;
import org.whispersystems.textsecuregcm.subscriptions.CustomerAwareSubscriptionPaymentProcessor;
import org.whispersystems.textsecuregcm.subscriptions.PayPalDonationsTranslator;
import org.whispersystems.textsecuregcm.subscriptions.PaymentDetails;
import org.whispersystems.textsecuregcm.subscriptions.PaymentMethod;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionCurrencyUtil;
public class OneTimeDonationUtil {
private static final String EURO_CURRENCY_CODE = "EUR";
private static final Logger LOGGER = LoggerFactory.getLogger(OneTimeDonationUtil.class);
/// Thrown if a one time donation level cannot be parsed or if it is not found in configuration
public static class InvalidLevelException extends Exception {
public InvalidLevelException(final String message) {
super(message);
}
}
public record LocalizedPayPalDonationLineItem(Locale locale, String itemName){}
public record DonationLevelDetails(long level, Duration levelExpiration){}
public sealed interface OneTimeDonationRequestValidationResult permits OneTimeDonationRequestValidationResult.Success,
OneTimeDonationRequestValidationResult.UnsupportedCurrency,
OneTimeDonationRequestValidationResult.UnsupportedLevel,
OneTimeDonationRequestValidationResult.AmountBelowMinimum,
OneTimeDonationRequestValidationResult.AmountAboveSepaLimit {
record Success() implements OneTimeDonationRequestValidationResult {}
record UnsupportedCurrency() implements OneTimeDonationRequestValidationResult {}
record UnsupportedLevel() implements OneTimeDonationRequestValidationResult {}
record AmountBelowMinimum(BigDecimal minimum) implements OneTimeDonationRequestValidationResult {}
record AmountAboveSepaLimit(BigDecimal maximum) implements OneTimeDonationRequestValidationResult {}
}
public static OneTimeDonationRequestValidationResult validateOneTimeDonationRequest(
final String currency,
final BigDecimal amount,
final long level,
final PaymentMethod paymentMethod,
final OneTimeDonationConfiguration oneTimeDonationConfiguration,
final CustomerAwareSubscriptionPaymentProcessor manager
) {
if (!(level == oneTimeDonationConfiguration.gift().level()
|| level == oneTimeDonationConfiguration.boost().level())) {
return new OneTimeDonationRequestValidationResult.UnsupportedLevel();
}
if (!manager.getSupportedCurrenciesForPaymentMethod(paymentMethod)
.contains(currency.toLowerCase(Locale.ROOT))) {
return new OneTimeDonationRequestValidationResult.UnsupportedCurrency();
}
final BigDecimal minCurrencyAmountMajorUnits = oneTimeDonationConfiguration.currencies()
.get(currency.toLowerCase(Locale.ROOT)).minimum();
final BigDecimal minCurrencyAmountMinorUnits = SubscriptionCurrencyUtil.convertConfiguredAmountToApiAmount(
currency,
minCurrencyAmountMajorUnits);
if (minCurrencyAmountMinorUnits.compareTo(amount) > 0) {
return new OneTimeDonationRequestValidationResult.AmountBelowMinimum(minCurrencyAmountMajorUnits);
}
if (paymentMethod == PaymentMethod.SEPA_DEBIT &&
amount.compareTo(SubscriptionCurrencyUtil.convertConfiguredAmountToApiAmount(
EURO_CURRENCY_CODE,
oneTimeDonationConfiguration.sepaMaximumEuros())) > 0) {
return new OneTimeDonationRequestValidationResult.AmountAboveSepaLimit(
oneTimeDonationConfiguration.sepaMaximumEuros());
}
return new OneTimeDonationRequestValidationResult.Success();
}
public static LocalizedPayPalDonationLineItem localizePayPalDonationLineItem(
final PayPalDonationsTranslator payPalDonationsTranslator, final List<Locale> acceptableLocales) {
// These two localizations are a best-effort, and it's possible that the first `locale` and the localized line
// item name will not match. We could try to align with the locales PayPal documents <https://developer.paypal.com/reference/locale-codes/#supported-locale-codes>
// but that's a moving target, and we can hopefully have one of them be better for the user by selecting
// independently.
final Locale locale = SubscriptionsUtil.getPayPalLocale(acceptableLocales);
final String localizedLineItemName = payPalDonationsTranslator.translate(acceptableLocales,
org.whispersystems.textsecuregcm.subscriptions.PayPalDonationsTranslator.ONE_TIME_DONATION_LINE_ITEM_KEY);
return new LocalizedPayPalDonationLineItem(locale, localizedLineItemName);
}
public static DonationLevelDetails getLevelDetails(final PaymentDetails paymentDetails,
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;
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);
}
}
@@ -0,0 +1,343 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc;
import static org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil.getClientPlatform;
import static org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil.toChargeFailure;
import com.google.protobuf.ByteString;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.Clock;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import org.signal.chat.errors.FailedPrecondition;
import org.signal.chat.errors.FailedZkAuthentication;
import org.signal.chat.errors.NotFound;
import org.signal.chat.purchase.AmountAboveSepaLimitError;
import org.signal.chat.purchase.AmountBelowMinimumError;
import org.signal.chat.purchase.ConfirmPayPalBoostRequest;
import org.signal.chat.purchase.ConfirmPayPalBoostResponse;
import org.signal.chat.purchase.CreateBoostReceiptCredentialsRequest;
import org.signal.chat.purchase.CreateBoostReceiptCredentialsResponse;
import org.signal.chat.purchase.CreateBoostRequest;
import org.signal.chat.purchase.CreateBoostResponse;
import org.signal.chat.purchase.CreatePayPalBoostRequest;
import org.signal.chat.purchase.CreatePayPalBoostResponse;
import org.signal.chat.purchase.SimpleOneTimeDonationsGrpc;
import org.signal.chat.purchase.PaymentRequired;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.VerificationFailedException;
import org.signal.libsignal.zkgroup.donation.DonationPermit;
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialRequest;
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialResponse;
import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations;
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.storage.DonationPermitsManager;
import org.whispersystems.textsecuregcm.storage.IssuedReceiptsManager;
import org.whispersystems.textsecuregcm.storage.OneTimeDonationsManager;
import org.whispersystems.textsecuregcm.storage.WriteConflictException;
import org.whispersystems.textsecuregcm.subscriptions.BraintreeManager;
import org.whispersystems.textsecuregcm.subscriptions.PayPalDonationsTranslator;
import org.whispersystems.textsecuregcm.subscriptions.PaymentDetails;
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
import org.whispersystems.textsecuregcm.subscriptions.PaymentStatus;
import org.whispersystems.textsecuregcm.subscriptions.StripeManager;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidAmountException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorException;
public class OneTimeDonationsGrpcService extends SimpleOneTimeDonationsGrpc.OneTimeDonationsImplBase {
private final OneTimeDonationConfiguration oneTimeDonationConfiguration;
private final StripeManager stripeManager;
private final BraintreeManager braintreeManager;
private final PayPalDonationsTranslator payPalDonationsTranslator;
private final OneTimeDonationsManager oneTimeDonationsManager;
private final IssuedReceiptsManager issuedReceiptsManager;
private final ServerZkReceiptOperations zkReceiptOperations;
private final Clock clock;
private final RateLimiters rateLimiters;
private final DonationPermitsManager donationPermitsManager;
public OneTimeDonationsGrpcService(
final OneTimeDonationConfiguration oneTimeDonationConfiguration,
final StripeManager stripeManager,
final BraintreeManager braintreeManager,
final PayPalDonationsTranslator payPalDonationsTranslator,
final OneTimeDonationsManager oneTimeDonationsManager,
final IssuedReceiptsManager issuedReceiptsManager,
final ServerZkReceiptOperations zkReceiptOperations,
final Clock clock,
final RateLimiters rateLimiters,
final DonationPermitsManager donationPermitsManager) {
this.oneTimeDonationConfiguration = oneTimeDonationConfiguration;
this.stripeManager = stripeManager;
this.braintreeManager = braintreeManager;
this.payPalDonationsTranslator = payPalDonationsTranslator;
this.oneTimeDonationsManager = oneTimeDonationsManager;
this.issuedReceiptsManager = issuedReceiptsManager;
this.zkReceiptOperations = zkReceiptOperations;
this.clock = clock;
this.rateLimiters = rateLimiters;
this.donationPermitsManager = donationPermitsManager;
}
@Override
public CreateBoostResponse createBoost(final CreateBoostRequest request)
throws RateLimitExceededException {
RateLimitUtil.rateLimitByRemoteAddress(rateLimiters.forDescriptor(RateLimiters.For.ONE_TIME_DONATION));
try {
final DonationPermit donationPermit = new DonationPermit(request.getDonationPermit().toByteArray());
if (!donationPermitsManager.spend(donationPermit)) {
return CreateBoostResponse.newBuilder()
.setPermitRejected(FailedZkAuthentication.newBuilder()
.setDescription("donation permit rejected")
.build())
.build();
}
} catch (InvalidInputException | VerificationFailedException _) {
return CreateBoostResponse.newBuilder()
.setPermitRejected(FailedZkAuthentication.newBuilder()
.setDescription("donation permit rejected")
.build())
.build();
}
final org.whispersystems.textsecuregcm.subscriptions.PaymentMethod paymentMethod =
switch (request.getPaymentMethod()) {
case PAYMENT_METHOD_CARD -> org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.CARD;
case PAYMENT_METHOD_SEPA_DEBIT -> org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.SEPA_DEBIT;
case PAYMENT_METHOD_IDEAL -> org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.IDEAL;
default -> throw GrpcExceptions.fieldViolation("payment_method", "Unsupported payment method");
};
final OneTimeDonationUtil.OneTimeDonationRequestValidationResult validationResult =
OneTimeDonationUtil.validateOneTimeDonationRequest(
request.getCurrency(),
BigDecimal.valueOf(request.getAmount()),
request.getLevel(),
paymentMethod,
oneTimeDonationConfiguration,
stripeManager);
return switch (validationResult) {
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.UnsupportedLevel _ ->
CreateBoostResponse.newBuilder()
.setUnsupportedLevel(FailedPrecondition.getDefaultInstance()).build();
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.UnsupportedCurrency _ ->
CreateBoostResponse.newBuilder()
.setUnsupportedCurrency(FailedPrecondition.getDefaultInstance()).build();
case final OneTimeDonationUtil.OneTimeDonationRequestValidationResult.AmountBelowMinimum r ->
CreateBoostResponse.newBuilder()
.setAmountBelowMinimum(AmountBelowMinimumError.newBuilder()
.setMinimum(r.minimum().toString()).build()).build();
case final OneTimeDonationUtil.OneTimeDonationRequestValidationResult.AmountAboveSepaLimit r ->
CreateBoostResponse.newBuilder()
.setAmountAboveSepaLimit(AmountAboveSepaLimitError.newBuilder()
.setMaximum(r.maximum().toString()).build()).build();
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.Success _ -> {
try {
final com.stripe.model.PaymentIntent paymentIntent = stripeManager.createPaymentIntent(
request.getCurrency(), request.getAmount(), request.getLevel(),
getClientPlatform(RequestAttributesUtil.getUserAgent().orElse(null)));
yield CreateBoostResponse.newBuilder().setClientSecret(paymentIntent.getClientSecret()).build();
} catch (final SubscriptionInvalidAmountException e) {
yield CreateBoostResponse.newBuilder()
.setInvalidAmount(FailedPrecondition.newBuilder()
.setDescription(e.getErrorCode()).build())
.build();
}
}
};
}
@Override
public CreatePayPalBoostResponse createPayPalBoost(final CreatePayPalBoostRequest request) throws IOException {
final OneTimeDonationUtil.OneTimeDonationRequestValidationResult validationResult =
OneTimeDonationUtil.validateOneTimeDonationRequest(
request.getCurrency(),
BigDecimal.valueOf(request.getAmount()),
request.getLevel(),
org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.PAYPAL,
oneTimeDonationConfiguration,
braintreeManager);
return switch (validationResult) {
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.UnsupportedLevel _ ->
CreatePayPalBoostResponse.newBuilder()
.setUnsupportedLevel(FailedPrecondition.getDefaultInstance()).build();
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.UnsupportedCurrency _ ->
CreatePayPalBoostResponse.newBuilder()
.setUnsupportedCurrency(FailedPrecondition.getDefaultInstance()).build();
case final OneTimeDonationUtil.OneTimeDonationRequestValidationResult.AmountBelowMinimum r ->
CreatePayPalBoostResponse.newBuilder()
.setAmountBelowMinimum(AmountBelowMinimumError.newBuilder()
.setMinimum(r.minimum().toString()).build()).build();
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.AmountAboveSepaLimit _ ->
throw new IllegalStateException("SEPA limit should not trigger for PayPal");
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.Success _ -> {
final List<Locale> acceptableLocales = RequestAttributesUtil.getAvailableAcceptedLocales();
final OneTimeDonationUtil.LocalizedPayPalDonationLineItem localizedLineItem = OneTimeDonationUtil.localizePayPalDonationLineItem(
payPalDonationsTranslator, acceptableLocales);
final BraintreeManager.PayPalOneTimePaymentApprovalDetails approvalDetails =
braintreeManager.createOneTimePayment(
request.getCurrency().toUpperCase(Locale.ROOT), request.getAmount(),
localizedLineItem.locale().toLanguageTag(), request.getReturnUrl(), request.getCancelUrl(),
localizedLineItem.itemName());
yield CreatePayPalBoostResponse.newBuilder()
.setResult(CreatePayPalBoostResponse.CreatePayPalBoostResult.newBuilder()
.setApprovalUrl(approvalDetails.approvalUrl())
.setPaymentId(approvalDetails.paymentId()).build()).build();
}
};
}
@Override
public ConfirmPayPalBoostResponse confirmPayPalBoost(final ConfirmPayPalBoostRequest request)
throws RateLimitExceededException, IOException {
RateLimitUtil.rateLimitByRemoteAddress(rateLimiters.forDescriptor(RateLimiters.For.ONE_TIME_DONATION));
final OneTimeDonationUtil.OneTimeDonationRequestValidationResult validationResult =
OneTimeDonationUtil.validateOneTimeDonationRequest(
request.getCurrency(),
BigDecimal.valueOf(request.getAmount()),
request.getLevel(),
org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.PAYPAL,
oneTimeDonationConfiguration,
braintreeManager);
return switch (validationResult) {
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.UnsupportedLevel _ ->
ConfirmPayPalBoostResponse.newBuilder()
.setUnsupportedLevel(FailedPrecondition.getDefaultInstance()).build();
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.UnsupportedCurrency _ ->
ConfirmPayPalBoostResponse.newBuilder()
.setUnsupportedCurrency(FailedPrecondition.getDefaultInstance()).build();
case final OneTimeDonationUtil.OneTimeDonationRequestValidationResult.AmountBelowMinimum r ->
ConfirmPayPalBoostResponse.newBuilder()
.setAmountBelowMinimum(AmountBelowMinimumError.newBuilder()
.setMinimum(r.minimum().toString()).build()).build();
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.AmountAboveSepaLimit _ ->
throw new IllegalStateException("SEPA limit should not trigger for PayPal");
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.Success _ -> {
final BraintreeManager.PayPalChargeSuccessDetails chargeSuccessDetails;
try {
chargeSuccessDetails = braintreeManager.captureOneTimePayment(
request.getPayerId(), request.getPaymentId(), request.getPaymentToken(),
request.getCurrency(), request.getAmount(), request.getLevel(),
SubscriptionsUtil.getClientPlatform(RequestAttributesUtil.getUserAgent().orElse(null)));
oneTimeDonationsManager.putPaidAt(chargeSuccessDetails.paymentId(), clock.instant());
yield ConfirmPayPalBoostResponse.newBuilder()
.setResult(ConfirmPayPalBoostResponse.ConfirmPayPalBoostResult.newBuilder()
.setPaymentId(chargeSuccessDetails.paymentId()).build()).build();
} catch (final SubscriptionProcessorException e) {
yield ConfirmPayPalBoostResponse.newBuilder()
.setChargeFailure(SubscriptionsUtil.toChargeFailure(e.getProcessor(), e.getChargeFailure()))
.build();
}
}
};
}
@Override
public CreateBoostReceiptCredentialsResponse createBoostReceiptCredentials(
final CreateBoostReceiptCredentialsRequest request) throws IOException {
final PaymentProvider processor;
final Optional<PaymentDetails> maybePaymentDetails;
switch (request.getProcessor()) {
case PAYMENT_PROVIDER_STRIPE -> {
processor = PaymentProvider.STRIPE;
maybePaymentDetails = stripeManager.getPaymentDetails(request.getPaymentIntentId());
}
case PAYMENT_PROVIDER_BRAINTREE -> {
processor = PaymentProvider.BRAINTREE;
maybePaymentDetails = braintreeManager.getPaymentDetails(request.getPaymentIntentId());
}
default -> throw GrpcExceptions.fieldViolation("processor", "Unsupported payment processor");
}
if (maybePaymentDetails.isEmpty()) {
return CreateBoostReceiptCredentialsResponse.newBuilder()
.setPaymentNotFound(NotFound.getDefaultInstance()).build();
}
final PaymentDetails paymentDetails = maybePaymentDetails.get();
if (paymentDetails.status() == PaymentStatus.PROCESSING) {
return CreateBoostReceiptCredentialsResponse.newBuilder()
.setPaymentStillProcessing(FailedPrecondition.getDefaultInstance()).build();
}
if (paymentDetails.status() != PaymentStatus.SUCCEEDED) {
final PaymentRequired.Builder paymentRequiredBuilder = PaymentRequired.newBuilder();
if (paymentDetails.chargeFailure() != null) {
paymentRequiredBuilder.setChargeFailure(toChargeFailure(processor, paymentDetails.chargeFailure()));
}
return CreateBoostReceiptCredentialsResponse.newBuilder()
.setPaymentRequired(paymentRequiredBuilder).build();
}
final OneTimeDonationUtil.DonationLevelDetails levelDetails;
try {
levelDetails = OneTimeDonationUtil.getLevelDetails(paymentDetails, oneTimeDonationConfiguration);
} catch (final OneTimeDonationUtil.InvalidLevelException e) {
throw GrpcExceptions.unavailable(e.getMessage());
}
final ReceiptCredentialRequest receiptCredentialRequest;
try {
receiptCredentialRequest = new ReceiptCredentialRequest(
request.getReceiptCredentialRequest().toByteArray());
} catch (final InvalidInputException e) {
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 expiration = paidAt
.plus(levelDetails.levelExpiration())
.truncatedTo(ChronoUnit.DAYS)
.plus(1, ChronoUnit.DAYS);
final ReceiptCredentialResponse receiptCredentialResponse;
try {
receiptCredentialResponse = zkReceiptOperations.issueReceiptCredential(
receiptCredentialRequest, expiration.getEpochSecond(), levelDetails.level());
} catch (final VerificationFailedException e) {
throw GrpcExceptions.fieldViolation("receipt_credential_request",
"receipt credential request failed verification");
}
Metrics.counter(SubscriptionsGrpcService.RECEIPT_ISSUED_COUNTER_NAME,
Tags.of(
Tag.of(SubscriptionsGrpcService.PROCESSOR_TAG_NAME, processor.toString()),
Tag.of(SubscriptionsGrpcService.TYPE_TAG_NAME, "boost"),
UserAgentTagUtil.getPlatformTag(RequestAttributesUtil.getUserAgent().orElse(null))))
.increment();
return CreateBoostReceiptCredentialsResponse.newBuilder()
.setResult(CreateBoostReceiptCredentialsResponse.CreateBoostReceiptCredentialsResult.newBuilder()
.setReceiptCredentialResponse(ByteString.copyFrom(receiptCredentialResponse.serialize()))
.build())
.build();
}
}
@@ -0,0 +1,106 @@
package org.whispersystems.textsecuregcm.grpc;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
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.CurrencyConfiguration;
import org.signal.chat.purchase.GetConfigurationRequest;
import org.signal.chat.purchase.GetConfigurationResponse;
import org.signal.chat.purchase.LevelConfiguration;
import org.signal.chat.purchase.SimpleProductConfigurationGrpc;
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration;
import org.whispersystems.textsecuregcm.configuration.SubscriptionConfiguration;
import org.whispersystems.textsecuregcm.subscriptions.CustomerAwareSubscriptionPaymentProcessor;
import org.whispersystems.textsecuregcm.subscriptions.PaymentMethod;
public class ProductConfigurationGrpcService extends SimpleProductConfigurationGrpc.ProductConfigurationImplBase {
private final GetConfigurationResponse configurationResponse;
public ProductConfigurationGrpcService(
final SubscriptionConfiguration subscriptionConfiguration,
final OneTimeDonationConfiguration oneTimeDonationConfiguration,
List<CustomerAwareSubscriptionPaymentProcessor> paymentProcessors,
final long backupMediaStorageAllowanceBytes) {
this.configurationResponse = GetConfigurationResponse.newBuilder()
.setBackup(buildBackupConfiguration(subscriptionConfiguration, backupMediaStorageAllowanceBytes))
.setSepaMaximumEuros(oneTimeDonationConfiguration.sepaMaximumEuros().toString())
.putAllCurrencies(buildCurrencyConfigurations(subscriptionConfiguration, oneTimeDonationConfiguration, paymentProcessors))
.putAllBadgeLevels(buildLevelConfigurations(subscriptionConfiguration, oneTimeDonationConfiguration))
.build();
}
@Override
public GetConfigurationResponse getConfiguration(final GetConfigurationRequest request) {
return this.configurationResponse;
}
private static Map<String, CurrencyConfiguration> buildCurrencyConfigurations(
final SubscriptionConfiguration subscriptionConfiguration,
final OneTimeDonationConfiguration oneTimeDonationConfiguration,
List<CustomerAwareSubscriptionPaymentProcessor> paymentProcessors) {
return SubscriptionsUtil
.buildCurrencyConfiguration(paymentProcessors, oneTimeDonationConfiguration, subscriptionConfiguration)
.entrySet().stream()
.collect(Collectors.toMap(
Map.Entry::getKey,
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(oneTimeDonationConfiguration.boost().level(),
LevelConfiguration.newBuilder()
.setBadgeId(oneTimeDonationConfiguration.boost().badge())
.setBadgeDurationSeconds(oneTimeDonationConfiguration.boost().expiration().toSeconds()).build());
donationLevels.put(oneTimeDonationConfiguration.gift().level(),
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 =
subscriptionConfiguration.getBackupLevels().entrySet().stream().collect(Collectors.toMap(
Map.Entry::getKey,
e -> BackupLevelConfiguration.newBuilder()
.setStorageAllowanceBytes(backupMediaStorageAllowanceBytes)
.setPlayProductId(e.getValue().playProductId())
.setMediaTtlDays(e.getValue().mediaTtl().toDays())
.build()));
return BackupConfiguration.newBuilder()
.putAllLevels(backupLevels)
.setFreeTierMediaDays(subscriptionConfiguration.getbackupFreeTierMediaDuration().toDays())
.build();
}
private static CurrencyConfiguration toProtoCurrencyConfiguration(
final String currency,
final org.whispersystems.textsecuregcm.subscriptions.CurrencyConfiguration config) {
final CurrencyConfiguration.Builder builder = CurrencyConfiguration.newBuilder()
.setMinimum(config.minimum().toString())
.addAllSupportedPaymentMethods(config.supportedPaymentMethods().stream()
.map(PaymentMethod::toProtoPaymentMethod)
.toList());
config.oneTime().forEach((levelId, amounts) ->
builder.putOneTime(levelId, AmountList.newBuilder()
.addAllAmounts(amounts.stream().map(BigDecimal::toString).toList())
.build()));
config.subscription()
.forEach((levelId, amount) -> builder.putSubscription(levelId, amount.toString()));
config.backupSubscription()
.forEach((levelId, amount) -> builder.putBackupSubscription(levelId, amount.toString()));
return builder.build();
}
}
@@ -5,70 +5,101 @@
package org.whispersystems.textsecuregcm.grpc;
import java.time.Clock;
import java.util.Optional;
import com.google.common.annotations.VisibleForTesting;
import com.google.protobuf.Empty;
import java.time.Clock;
import java.util.Base64;
import java.util.Optional;
import org.signal.chat.errors.FailedUnidentifiedAuthorization;
import org.signal.chat.errors.FailedZkAuthentication;
import org.signal.chat.errors.NotFound;
import org.signal.chat.profile.CredentialType;
import org.signal.chat.profile.DeleteAvatarRequest;
import org.signal.chat.profile.DeleteAvatarResponse;
import org.signal.chat.profile.ExtendAvatarTTLRequest;
import org.signal.chat.profile.ExtendAvatarTTLResponse;
import org.signal.chat.profile.GetAvatarUploadFormRequest;
import org.signal.chat.profile.GetAvatarUploadFormResponse;
import org.signal.chat.profile.GetExpiringProfileKeyCredentialAnonymousRequest;
import org.signal.chat.profile.GetExpiringProfileKeyCredentialAnonymousResponse;
import org.signal.chat.profile.GetUnversionedProfileAnonymousRequest;
import org.signal.chat.profile.GetUnversionedProfileAnonymousResponse;
import org.signal.chat.profile.GetVersionedProfileAnonymousRequest;
import org.signal.chat.profile.GetVersionedProfileAnonymousResponse;
import org.signal.chat.profile.GetProfileAnonymousRequest;
import org.signal.chat.profile.GetProfileAnonymousResponse;
import org.signal.chat.profile.SimpleProfileAnonymousGrpc;
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.ServerSecretParams;
import org.signal.libsignal.zkgroup.VerificationFailedException;
import org.signal.libsignal.zkgroup.avatars.AvatarUploadCredentialPresentation;
import org.signal.libsignal.zkgroup.profiles.ServerZkProfileOperations;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
import org.whispersystems.textsecuregcm.badges.ProfileBadgeConverter;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
import org.whispersystems.textsecuregcm.util.ProfileHelper;
public class ProfileAnonymousGrpcService extends SimpleProfileAnonymousGrpc.ProfileAnonymousImplBase {
private final AccountsManager accountsManager;
private final ProfilesManager profilesManager;
private final ProfileBadgeConverter profileBadgeConverter;
private final ServerZkProfileOperations zkProfileOperations;
private final GenericServerSecretParams genericServerSecretParams;
private final GroupSendTokenUtil groupSendTokenUtil;
private final PostPolicyGenerator policyGenerator;
private final RateLimiters rateLimiters;
private final Clock clock;
public ProfileAnonymousGrpcService(
final AccountsManager accountsManager,
final ProfilesManager profilesManager,
final ProfileBadgeConverter profileBadgeConverter,
final ServerSecretParams serverSecretParams) {
final PostPolicyGenerator policyGenerator,
final GenericServerSecretParams genericServerSecretParams,
final ServerSecretParams serverSecretParams,
final RateLimiters rateLimiters,
final Clock clock) {
this(accountsManager,
profilesManager,
profileBadgeConverter,
policyGenerator,
genericServerSecretParams,
rateLimiters,
clock,
new ServerZkProfileOperations(serverSecretParams),
new GroupSendTokenUtil(serverSecretParams, Clock.systemUTC()));
new GroupSendTokenUtil(serverSecretParams, clock));
}
@VisibleForTesting
ProfileAnonymousGrpcService(final AccountsManager accountsManager,
final ProfilesManager profilesManager,
final ProfileBadgeConverter profileBadgeConverter,
final PostPolicyGenerator policyGenerator,
final GenericServerSecretParams genericServerSecretParams,
final RateLimiters rateLimiters,
final Clock clock,
final ServerZkProfileOperations zkProfileOperations,
final GroupSendTokenUtil groupSendTokenUtil) {
this.accountsManager = accountsManager;
this.profilesManager = profilesManager;
this.profileBadgeConverter = profileBadgeConverter;
this.policyGenerator = policyGenerator;
this.genericServerSecretParams = genericServerSecretParams;
this.rateLimiters = rateLimiters;
this.clock = clock;
this.zkProfileOperations = zkProfileOperations;
this.groupSendTokenUtil = groupSendTokenUtil;
}
@Override
public GetUnversionedProfileAnonymousResponse getUnversionedProfile(final GetUnversionedProfileAnonymousRequest request) {
final ServiceIdentifier targetIdentifier =
GrpcServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getRequest().getServiceIdentifier());
// Callers must be authenticated to request unversioned profiles by PNI
if (targetIdentifier.identityType() == IdentityType.PNI) {
throw GrpcExceptions.invalidArguments("aci service identifier type required");
}
public GetProfileAnonymousResponse getProfile(final GetProfileAnonymousRequest request) {
final ServiceIdentifier targetIdentifier = GrpcServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getRequest().getAccountIdentifier());
final Optional<Account> targetAccount = accountsManager.getByServiceIdentifier(targetIdentifier);
@@ -81,43 +112,25 @@ public class ProfileAnonymousGrpcService extends SimpleProfileAnonymousGrpc.Prof
};
if (!authorized) {
return GetUnversionedProfileAnonymousResponse.newBuilder()
return GetProfileAnonymousResponse.newBuilder()
.setFailedUnidentifiedAuthorization(FailedUnidentifiedAuthorization.getDefaultInstance())
.build();
}
final byte[] version = request.getRequest().getVersion().toByteArray();
return targetAccount.map(account ->
GetUnversionedProfileAnonymousResponse.newBuilder()
.setResult(ProfileGrpcHelper.buildUnversionedProfileResult(targetIdentifier,
null,
account,
profileBadgeConverter))
.build())
.orElseGet(() -> GetUnversionedProfileAnonymousResponse.newBuilder()
.setNotFound(NotFound.getDefaultInstance())
.build());
}
return targetAccount.flatMap(account -> ProfileGrpcHelper
.getProfile(account, profilesManager, profileBadgeConverter, version)
@Override
public GetVersionedProfileAnonymousResponse getVersionedProfile(final GetVersionedProfileAnonymousRequest request) {
final ServiceIdentifier targetIdentifier = GrpcServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getRequest().getAccountIdentifier());
// If the etag matches, drop the result
.map(profileResult -> request.getRequest().getEtag().equals(profileResult.getEtag())
? GetProfileAnonymousResponse.newBuilder().setEtagMatched(true).build()
: GetProfileAnonymousResponse.newBuilder().setProfile(profileResult).build())
final Optional<Account> targetAccount = getTargetAccountAndValidateUnidentifiedAccess(targetIdentifier, request.getUnidentifiedAccessKey().toByteArray());
return targetAccount.flatMap(account ->
ProfileGrpcHelper.getVersionedProfile(account,
profilesManager,
request.getRequest().getVersion().toByteArray(),
request.getRequest().getDataEtag().toByteArray(),
request.getRequest().getPaymentAddressEtag().toByteArray()))
.map(result ->
GetVersionedProfileAnonymousResponse.newBuilder()
.setResult(result)
.build())
.orElseGet(() ->
GetVersionedProfileAnonymousResponse.newBuilder()
.setNotFound(NotFound.getDefaultInstance())
.build());
// If we didn't find a v2 profile, try a v1 profile
.or(() -> ProfileGrpcHelper
.getProfileV1(account, profilesManager, profileBadgeConverter, version)
.map(v1Result -> GetProfileAnonymousResponse.newBuilder().setProfileV1(v1Result).build())))
.orElseGet(() -> GetProfileAnonymousResponse.newBuilder().setNotFound(NotFound.getDefaultInstance()).build());
}
@Override
@@ -152,4 +165,92 @@ public class ProfileAnonymousGrpcService extends SimpleProfileAnonymousGrpc.Prof
return accountsManager.getByServiceIdentifier(targetIdentifier)
.filter(targetAccount -> UnidentifiedAccessUtil.checkUnidentifiedAccess(targetAccount, unidentifiedAccessKey));
}
@Override
public GetAvatarUploadFormResponse getAvatarUploadForm(final GetAvatarUploadFormRequest request) throws RateLimitExceededException {
final AvatarUploadCredentialPresentation presentation;
try {
presentation = new AvatarUploadCredentialPresentation(
request.getAvatarCredentialsPresentation().toByteArray());
presentation.verify(clock.instant(), this.genericServerSecretParams);
} catch (InvalidInputException _) {
throw GrpcExceptions.invalidArguments("invalid credential presentation");
} catch (VerificationFailedException _) {
return GetAvatarUploadFormResponse.newBuilder()
.setInvalidCredentialsPresentation(FailedZkAuthentication.getDefaultInstance())
.build();
}
final byte[] identity = presentation.getCommitment();
rateLimiters.getProfileAvatarBytesLimiter().validate(Base64.getEncoder().encodeToString(identity), request.getUploadLength());
final String avatar = ProfileHelper.generateAvatarObjectName();
profilesManager.setAvatarForIdentity(identity, avatar);
return GetAvatarUploadFormResponse.newBuilder()
.setAvatarUploadForm(ProfileGrpcHelper.generateAvatarUploadForm(avatar, request.getUploadLength(), policyGenerator, clock))
.build();
}
@Override
public ExtendAvatarTTLResponse extendAvatarTTL(final ExtendAvatarTTLRequest request) {
final AvatarUploadCredentialPresentation presentation;
try {
presentation = new AvatarUploadCredentialPresentation(
request.getAvatarCredentialsPresentation().toByteArray());
} catch (InvalidInputException _) {
throw GrpcExceptions.invalidArguments("invalid credential presentation");
}
try {
presentation.verify(clock.instant(), this.genericServerSecretParams);
} catch (VerificationFailedException _) {
return ExtendAvatarTTLResponse.newBuilder()
.setInvalidCredentialsPresentation(FailedZkAuthentication.getDefaultInstance())
.build();
}
final byte[] identity = presentation.getCommitment();
return profilesManager.extendAvatarTtlForIdentity(identity)
.map(extendedPath -> ExtendAvatarTTLResponse.newBuilder()
.setPath(extendedPath)
.build())
.orElseGet(() -> ExtendAvatarTTLResponse.newBuilder()
.setNotFound(NotFound.getDefaultInstance())
.build());
}
@Override
public DeleteAvatarResponse deleteAvatar(final DeleteAvatarRequest request) {
final AvatarUploadCredentialPresentation presentation;
try {
presentation = new AvatarUploadCredentialPresentation(
request.getAvatarCredentialsPresentation().toByteArray());
} catch (InvalidInputException _) {
throw GrpcExceptions.invalidArguments("invalid credential presentation");
}
try {
presentation.verify(clock.instant(), this.genericServerSecretParams);
} catch (VerificationFailedException _) {
return DeleteAvatarResponse.newBuilder()
.setInvalidCredentialsPresentation(FailedZkAuthentication.getDefaultInstance())
.build();
}
final byte[] identity = presentation.getCommitment();
profilesManager.deleteAvatarForIdentity(identity);
return DeleteAvatarResponse.newBuilder().setSuccess(Empty.getDefaultInstance()).build();
}
}
@@ -7,21 +7,20 @@ package org.whispersystems.textsecuregcm.grpc;
import com.google.common.annotations.VisibleForTesting;
import com.google.protobuf.ByteString;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
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 java.util.UUID;
import org.signal.chat.profile.Badge;
import org.signal.chat.profile.BadgeSvg;
import org.signal.chat.profile.DataEtag;
import org.bouncycastle.crypto.digests.TupleHash;
import org.signal.chat.common.S3UploadForm;
import org.signal.chat.profile.GetExpiringProfileKeyCredentialResult;
import org.signal.chat.profile.GetUnversionedProfileResult;
import org.signal.chat.profile.GetVersionedProfileResult;
import org.signal.chat.profile.GetVersionedProfileV1Response;
import org.signal.chat.profile.ProfileResult;
import org.signal.chat.profile.ProfileResultOrBuilder;
import org.signal.chat.profile.LegacyProfileResult;
import org.signal.chat.profile.AccountInfo;
import org.signal.libsignal.protocol.ServiceId;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.VerificationFailedException;
@@ -31,7 +30,8 @@ import org.signal.libsignal.zkgroup.profiles.ProfileKeyCredentialRequest;
import org.signal.libsignal.zkgroup.profiles.ServerZkProfileOperations;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessChecksum;
import org.whispersystems.textsecuregcm.badges.ProfileBadgeConverter;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
@@ -40,149 +40,85 @@ import org.whispersystems.textsecuregcm.storage.VersionedProfileV1;
import org.whispersystems.textsecuregcm.util.ProfileHelper;
public class ProfileGrpcHelper {
static Optional<GetVersionedProfileResult> getVersionedProfile(final Account account,
private static final byte[] ETAG_DOMAIN = "ProfileETag/v1".getBytes(StandardCharsets.UTF_8);
private static final int ETAG_LENGTH = 10;
private static final S3UploadForm PROTOTYPE_AVATAR_UPLOAD_FORM = S3UploadForm.newBuilder()
.setAcl(PostPolicyGenerator.ACL)
.setAlgorithm(PostPolicyGenerator.ALGORITHM)
.build();
static Optional<LegacyProfileResult> getProfileV1(final Account account,
final ProfilesManager profilesManager,
final byte[] requestVersion,
final byte[] requestDataEtag,
final byte[] requestPaymentAddressEtag) {
final Optional<VersionedProfile> profile;
if (account.hasCapability(DeviceCapability.PROFILES_V2)) {
profile = profilesManager.get(account.getUuid(), requestVersion);
} else {
profile = Optional.empty();
}
final Optional<VersionedProfileV1> v1Profile;
if (profile.isEmpty()) {
v1Profile = profilesManager.getV1(account.getUuid(), HexFormat.of().formatHex(requestVersion));
} else {
v1Profile = Optional.empty();
}
if (profile.isEmpty() && v1Profile.isEmpty()) {
final ProfileBadgeConverter profileBadgeConverter,
final byte[] requestVersion) {
final Optional<VersionedProfileV1> maybeV1Profile =
profilesManager.getV1(account.getAccountIdentifier(), HexFormat.of().formatHex(requestVersion));
if (maybeV1Profile.isEmpty()) {
return Optional.empty();
}
final VersionedProfileV1 v1Profile = maybeV1Profile.get();
final GetVersionedProfileResult.Builder responseBuilder = GetVersionedProfileResult.newBuilder();
final LegacyProfileResult.Builder builder = LegacyProfileResult.newBuilder()
.setAccountInfo(buildAccountInfo(profileBadgeConverter, account))
.setName(ByteString.copyFrom(v1Profile.name()))
.setAbout(ByteString.copyFrom(v1Profile.about()))
.setAboutEmoji(ByteString.copyFrom(v1Profile.aboutEmoji()))
.setPhoneNumberSharing(ByteString.copyFrom(v1Profile.phoneNumberSharing()));
profile.ifPresent(p -> {
if (requestDataEtag.length > 0 && Arrays.equals(requestDataEtag, p.dataHash())) {
responseBuilder.setDataEtagMatched(true);
} else {
responseBuilder.setDataEtag(DataEtag.newBuilder()
.setData(ByteString.copyFrom(p.data()))
.setEtagSha256(ByteString.copyFrom(p.dataHash()))
.build());
}
});
v1Profile.ifPresent(p -> {
final GetVersionedProfileV1Response.Builder v1ResponseBuilder = GetVersionedProfileV1Response.newBuilder();
v1ResponseBuilder
.setName(ByteString.copyFrom(p.name()))
.setAbout(ByteString.copyFrom(p.about()))
.setAboutEmoji(ByteString.copyFrom(p.aboutEmoji()))
.setPhoneNumberSharing(ByteString.copyFrom(p.phoneNumberSharing()));
if (p.avatar() != null) {
v1ResponseBuilder.setAvatar(p.avatar());
}
responseBuilder.setV1Response(v1ResponseBuilder);
});
// Include payment address if the version matches the latest version on Account or the latest version on Account
// is empty
if (account.getCurrentProfileVersion().map(v -> Arrays.equals(v, requestVersion)).orElse(true)) {
final Optional<byte []> paymentAddress = profile.map(VersionedProfile::paymentAddress).or(() -> v1Profile.map(VersionedProfileV1::paymentAddress));
if (paymentAddress.isPresent()) {
final boolean paymentAddressETagMatches = requestPaymentAddressEtag.length > 0 &&
profile.map(VersionedProfile::paymentAddressHash)
.map(h -> Arrays.equals(requestPaymentAddressEtag, h))
.orElse(false);
if (paymentAddressETagMatches) {
responseBuilder.setPaymentAddressEtagMatched(true);
} else {
responseBuilder.setPaymentAddressDataEtag(DataEtag.newBuilder()
.setData(ByteString.copyFrom(paymentAddress.get()))
.setEtagSha256(ByteString.copyFrom(
profile.map(VersionedProfile::paymentAddressHash).orElseGet(() -> hash(paymentAddress.get()))))
.build());
}
}
if (v1Profile.avatar() != null) {
builder.setAvatar(v1Profile.avatar());
}
return Optional.of(responseBuilder.build());
}
@VisibleForTesting
static List<Badge> buildBadges(final List<org.whispersystems.textsecuregcm.entities.Badge> badges) {
final ArrayList<Badge> grpcBadges = new ArrayList<>();
for (final org.whispersystems.textsecuregcm.entities.Badge badge : badges) {
grpcBadges.add(Badge.newBuilder()
.setId(badge.getId())
.setCategory(badge.getCategory())
.setName(badge.getName())
.setDescription(badge.getDescription())
.addAllSprites6(badge.getSprites6())
.setSvg(badge.getSvg())
.addAllSvgs(buildBadgeSvgs(badge.getSvgs()))
.build());
}
return grpcBadges;
}
@VisibleForTesting
static List<org.signal.chat.common.DeviceCapability> buildAccountCapabilities(final Account account) {
return Arrays.stream(DeviceCapability.values())
.filter(DeviceCapability::includeInProfile)
.filter(account::hasCapability)
.map(DeviceCapabilityUtil::toGrpcDeviceCapability)
.toList();
}
private static List<BadgeSvg> buildBadgeSvgs(final List<org.whispersystems.textsecuregcm.entities.BadgeSvg> badgeSvgs) {
ArrayList<BadgeSvg> grpcBadgeSvgs = new ArrayList<>();
for (final org.whispersystems.textsecuregcm.entities.BadgeSvg badgeSvg : badgeSvgs) {
grpcBadgeSvgs.add(BadgeSvg.newBuilder()
.setDark(badgeSvg.getDark())
.setLight(badgeSvg.getLight())
.build());
}
return grpcBadgeSvgs;
}
static GetUnversionedProfileResult buildUnversionedProfileResult(
final ServiceIdentifier targetIdentifier,
final UUID requesterUuid,
final Account targetAccount,
final ProfileBadgeConverter profileBadgeConverter) {
final GetUnversionedProfileResult.Builder resultBuilder = GetUnversionedProfileResult.newBuilder()
.setIdentityKey(ByteString.copyFrom(targetAccount.getIdentityKey(targetIdentifier.identityType()).serialize()))
.addAllCapabilities(buildAccountCapabilities(targetAccount));
switch (targetIdentifier.identityType()) {
case ACI -> {
resultBuilder.setUnrestrictedUnidentifiedAccess(targetAccount.isUnrestrictedUnidentifiedAccess())
.addAllBadges(
buildBadges(profileBadgeConverter.convert(RequestAttributesUtil.getAvailableAcceptedLocales(),
targetAccount.getBadges(),
ProfileHelper.isSelfProfileRequest(requesterUuid, targetIdentifier))));
targetAccount.getUnidentifiedAccessKey()
.map(UnidentifiedAccessChecksum::generateFor)
.map(ByteString::copyFrom)
.ifPresent(resultBuilder::setUnidentifiedAccess);
}
case PNI -> resultBuilder.setUnrestrictedUnidentifiedAccess(false);
// If present, include the payment address if the version matches the latest version on Account or the latest
// version on Account is empty
if (v1Profile.paymentAddress() != null && account.getCurrentProfileVersion().map(v -> Arrays.equals(v, requestVersion)).orElse(true)) {
builder.setPaymentAddress(ByteString.copyFrom(v1Profile.paymentAddress()));
}
return resultBuilder.build();
return Optional.of(builder.build());
}
static Optional<ProfileResult> getProfile(final Account account,
final ProfilesManager profilesManager,
final ProfileBadgeConverter profileBadgeConverter,
final byte[] requestVersion) {
final Optional<VersionedProfile> maybeProfile = account.hasCapability(DeviceCapability.PROFILES_V2)
? profilesManager.get(account.getAccountIdentifier(), requestVersion)
: Optional.empty();
if (maybeProfile.isEmpty()) {
return Optional.empty();
}
final VersionedProfile profile = maybeProfile.get();
final ProfileResult.Builder builder = ProfileResult.newBuilder()
.setData(ByteString.copyFrom(profile.data()))
.setAccountInfo(buildAccountInfo(profileBadgeConverter, account));
// If present, include the payment address if the version matches the latest version on Account or the latest
// version on Account is empty
if (profile.paymentAddress() != null && account.getCurrentProfileVersion().map(v -> Arrays.equals(v, requestVersion)).orElse(true)) {
builder.setPaymentAddress(ByteString.copyFrom(profile.paymentAddress()));
}
builder.setEtag(ByteString.copyFrom(etag(builder)));
return Optional.of(builder.build());
}
private static AccountInfo buildAccountInfo(final ProfileBadgeConverter profileBadgeConverter,
final Account account) {
final AccountInfo.Builder accountInfoBuilder = AccountInfo.newBuilder()
.addAllBadgeIds(profileBadgeConverter.visibleBadgeIds(account.getBadges()))
.setIdentityKey(ByteString.copyFrom(account.getIdentityKey(IdentityType.ACI).serialize()))
.setUnrestrictedUnidentifiedAccess(account.isUnrestrictedUnidentifiedAccess());
account.getUnidentifiedAccessKey()
.map(UnidentifiedAccessChecksum::generateFor)
.map(ByteString::copyFrom)
.ifPresent(accountInfoBuilder::setUnidentifiedAccessKeyFingerprint);
return accountInfoBuilder.build();
}
static Optional<GetExpiringProfileKeyCredentialResult> getExpiringProfileKeyCredentialResult(
@@ -194,19 +130,21 @@ 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)).map(VersionedProfileV1::commitment))
.or(() -> profilesManager.getV1(account.getAccountIdentifier(), HexFormat.of().formatHex(version))
.map(VersionedProfileV1::commitment))
.map(commitment -> {
final ExpiringProfileKeyCredentialResponse profileKeyCredentialResponse;
try {
profileKeyCredentialResponse = ProfileHelper.getExpiringProfileKeyCredential(new ProfileKeyCredentialRequest(encodedCredentialRequest),
new ProfileKeyCommitment(commitment), new ServiceId.Aci(account.getUuid()), zkProfileOperations);
profileKeyCredentialResponse = ProfileHelper.getExpiringProfileKeyCredential(
new ProfileKeyCredentialRequest(encodedCredentialRequest),
new ProfileKeyCommitment(commitment), new ServiceId.Aci(account.getAccountIdentifier()), zkProfileOperations);
} catch (VerificationFailedException | InvalidInputException e) {
throw GrpcExceptions.invalidArguments("invalid credential request");
}
@@ -217,19 +155,51 @@ public class ProfileGrpcHelper {
});
}
/**
* Computes the SHA-256 hash of the given data.
* <p>
* Only needed during the v1 -> v2 migration. See also: VersionedProfile#hash(byte[])
*/
public static S3UploadForm generateAvatarUploadForm(final String objectName, final int uploadLength,
final PostPolicyGenerator policyGenerator, final Clock clock) {
final PostPolicyGenerator.SignedPostPolicy policy =
policyGenerator.createFor(objectName, uploadLength, clock.instant());
return PROTOTYPE_AVATAR_UPLOAD_FORM.toBuilder()
.setKey(objectName)
.setCredential(policy.credential())
.setDate(policy.formattedTimestamp())
.setPolicy(policy.encodedPolicy())
.setSignature(policy.signature())
.build();
}
/// Compute the etag of a [ProfileResult]
///
/// @implNote This uses the NIST-SP 800-185 TupleHash to provide a cryptographic hash over variable length fields.
/// Clients must be able to reproduce the same etag from the data, so hash must be stable.
@VisibleForTesting
public static byte[] hash(final byte[] data) {
final MessageDigest sha256;
try {
sha256 = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
throw new AssertionError(e);
}
return sha256.digest(data);
static byte[] etag(final ProfileResultOrBuilder profile) {
final TupleHash h = new TupleHash(256, ETAG_DOMAIN, ETAG_LENGTH * Byte.SIZE);
final AccountInfo accountInfo = profile.getAccountInfo();
addByteArray(h, profile.getData().toByteArray());
addByteArray(h, profile.getPaymentAddress().toByteArray());
addByteArray(h, accountInfo.getIdentityKey().toByteArray());
addByteArray(h, accountInfo.getUnidentifiedAccessKeyFingerprint().toByteArray());
h.update(accountInfo.getUnrestrictedUnidentifiedAccess() ? (byte) 1 : (byte) 0);
addInt(h, accountInfo.getBadgeIdsCount());
accountInfo.getBadgeIdsList().asByteStringList().stream()
.map(ByteString::toByteArray)
.sorted(Arrays::compareUnsigned)
.forEach(badgeId -> addByteArray(h, badgeId));
final byte[] out = new byte[ETAG_LENGTH];
h.doFinal(out, 0);
return out;
}
private static void addByteArray(final TupleHash hash, final byte[] bytes) {
hash.update(bytes, 0, bytes.length);
}
private static void addInt(final TupleHash hash, final int v) {
addByteArray(hash, ByteBuffer.allocate(Integer.BYTES).order(ByteOrder.BIG_ENDIAN).putInt(v).array());
}
}
@@ -7,29 +7,38 @@ package org.whispersystems.textsecuregcm.grpc;
import com.google.protobuf.ByteString;
import java.time.Clock;
import java.time.ZonedDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
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;
import org.signal.chat.common.S3UploadForm;
import org.signal.chat.errors.FailedPrecondition;
import org.signal.chat.errors.NotFound;
import org.signal.chat.profile.GetUnversionedProfileRequest;
import org.signal.chat.profile.GetUnversionedProfileResponse;
import org.signal.chat.profile.GetVersionedProfileRequest;
import org.signal.chat.profile.GetVersionedProfileResponse;
import org.signal.chat.profile.GetAvatarCredentialsRequest;
import org.signal.chat.profile.GetAvatarCredentialsResponse;
import org.signal.chat.profile.GetProfileRequest;
import org.signal.chat.profile.GetProfileResponse;
import org.signal.chat.profile.PaymentsForbiddenInRegion;
import org.signal.chat.profile.ProfileAvatarUploadAttributes;
import org.signal.chat.profile.ProfilesV2CapabilityRequired;
import org.signal.chat.profile.SetProfileRequest;
import org.signal.chat.profile.SetProfileResponse;
import org.signal.chat.profile.SetProfileResult;
import org.signal.chat.profile.SetProfileV1Request.AvatarChange;
import org.signal.chat.profile.SimpleProfileGrpc;
import org.signal.libsignal.protocol.ServiceId;
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
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.auth.grpc.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
import org.whispersystems.textsecuregcm.badges.ProfileBadgeConverter;
@@ -40,7 +49,6 @@ 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.PolicySigner;
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountBadge;
@@ -51,24 +59,25 @@ import org.whispersystems.textsecuregcm.storage.ProfilesManager;
import org.whispersystems.textsecuregcm.storage.VersionedProfile;
import org.whispersystems.textsecuregcm.storage.VersionedProfileV1;
import org.whispersystems.textsecuregcm.storage.WriteConflictException;
import org.whispersystems.textsecuregcm.util.Pair;
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 DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
private final Map<String, BadgeConfiguration> badgeConfigurationMap;
private final PostPolicyGenerator policyGenerator;
private final PolicySigner policySigner;
private final GenericServerSecretParams genericServerSecretParams;
private final ProfileBadgeConverter profileBadgeConverter;
private final RateLimiters rateLimiters;
private record AvatarData(Optional<String> currentAvatar,
Optional<String> finalAvatar,
Optional<ProfileAvatarUploadAttributes> uploadAttributes) {}
Optional<S3UploadForm> uploadAttributes) {}
public ProfileGrpcService(
final Clock clock,
@@ -77,7 +86,7 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
final BadgesConfiguration badgesConfiguration,
final PostPolicyGenerator policyGenerator,
final PolicySigner policySigner,
final GenericServerSecretParams genericServerSecretParams,
final ProfileBadgeConverter profileBadgeConverter,
final RateLimiters rateLimiters) {
this.clock = clock;
@@ -87,7 +96,7 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
this.badgeConfigurationMap = badgesConfiguration.getBadges().stream().collect(Collectors.toMap(
BadgeConfiguration::getId, Function.identity()));
this.policyGenerator = policyGenerator;
this.policySigner = policySigner;
this.genericServerSecretParams = genericServerSecretParams;
this.profileBadgeConverter = profileBadgeConverter;
this.rateLimiters = rateLimiters;
}
@@ -138,7 +147,7 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
case AVATAR_CHANGE_UPDATE -> {
final String updateAvatarObjectName = ProfileHelper.generateAvatarObjectName();
yield new AvatarData(currentAvatar, Optional.of(updateAvatarObjectName),
Optional.of(generateAvatarUploadForm(updateAvatarObjectName)));
Optional.of(ProfileGrpcHelper.generateAvatarUploadForm(updateAvatarObjectName, ProfileHelper.MAX_PROFILE_AVATAR_SIZE_BYTES, policyGenerator, clock)));
}
};
@@ -208,44 +217,60 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
}
@Override
public GetUnversionedProfileResponse getUnversionedProfile(final GetUnversionedProfileRequest request) throws RateLimitExceededException {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
final ServiceIdentifier targetIdentifier =
GrpcServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getServiceIdentifier());
final Optional<Account> maybeAccount = validateRateLimitAndGetAccount(authenticatedDevice.accountIdentifier(), targetIdentifier);
public GetAvatarCredentialsResponse getAvatarCredentials(final GetAvatarCredentialsRequest request) {
return maybeAccount.map(account -> GetUnversionedProfileResponse.newBuilder()
.setResult(ProfileGrpcHelper.buildUnversionedProfileResult(targetIdentifier,
authenticatedDevice.accountIdentifier(),
account,
profileBadgeConverter))
.build()).orElseGet(() -> GetUnversionedProfileResponse.newBuilder()
.setNotFound(NotFound.getDefaultInstance())
.build());
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
final Account account = accountsManager.getByAccountIdentifier(authenticatedDevice.accountIdentifier())
.orElseThrow(() -> GrpcExceptions.invalidCredentials("account not found"));
if (account.getZkCredentialKey().isEmpty()) {
return GetAvatarCredentialsResponse.newBuilder()
.setMissingZkCredentialKey(FailedPrecondition.newBuilder().setDescription("account requires ZK credential key"))
.build();
}
try {
final AvatarUploadCredentialRequest credentialRequest = new AvatarUploadCredentialRequest(
request.getAvatarCredentialsRequest().toByteArray());
final AvatarUploadCredentialResponse credentialResponse = credentialRequest.issueCredential(
new ServiceId.Aci(account.getIdentifier(IdentityType.ACI)),
account.getZkCredentialKey().get(),
Objects.requireNonNull(account.getZkCredentialKeyRotationId()),
clock.instant().truncatedTo(ChronoUnit.DAYS),
this.genericServerSecretParams);
return GetAvatarCredentialsResponse.newBuilder()
.setAvatarCredentials(ByteString.copyFrom(credentialResponse.serialize()))
.build();
} catch (InvalidInputException | VerificationFailedException _) {
throw GrpcExceptions.invalidArguments("invalid credential request");
}
}
@Override
public GetVersionedProfileResponse getVersionedProfile(final GetVersionedProfileRequest request) throws RateLimitExceededException {
public GetProfileResponse getProfile(final GetProfileRequest request) throws RateLimitExceededException {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
final ServiceIdentifier targetIdentifier =
GrpcServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getAccountIdentifier());
final byte[] version = request.getVersion().toByteArray();
final Optional<Account> maybeAccount =
validateRateLimitAndGetAccount(authenticatedDevice.accountIdentifier(), targetIdentifier);
final Optional<Account> maybeAccount = validateRateLimitAndGetAccount(authenticatedDevice.accountIdentifier(), targetIdentifier);
return maybeAccount.flatMap(account -> ProfileGrpcHelper
.getProfile(account, profilesManager, profileBadgeConverter, version)
return maybeAccount.map(account ->
ProfileGrpcHelper.getVersionedProfile(account, profilesManager,
request.getVersion().toByteArray(),
request.getDataEtag().toByteArray(),
request.getPaymentAddressEtag().toByteArray())
.map(result ->
GetVersionedProfileResponse.newBuilder()
.setResult(result)
.build())
.orElseGet(() -> GetVersionedProfileResponse.newBuilder()
.setNotFound(NotFound.getDefaultInstance())
.build())).orElseGet(() -> GetVersionedProfileResponse.newBuilder()
.setNotFound(NotFound.getDefaultInstance())
.build());
// If the etag matches, drop the result
.map(profileResult -> request.getEtag().equals(profileResult.getEtag())
? GetProfileResponse.newBuilder().setEtagMatched(true).build()
: GetProfileResponse.newBuilder().setProfile(profileResult).build())
// If we didn't find a v2 profile, try a v1 profile
.or(() -> ProfileGrpcHelper
.getProfileV1(account, profilesManager, profileBadgeConverter, version)
.map(v1Result -> GetProfileResponse.newBuilder().setLegacyProfile(v1Result).build())))
.orElseGet(() -> GetProfileResponse.newBuilder().setNotFound(NotFound.getDefaultInstance()).build());
}
private Optional<Account> validateRateLimitAndGetAccount(final UUID requesterUuid,
@@ -265,20 +290,4 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
throw GrpcExceptions.invalidArguments("Request must include commitment during migration");
}
}
private ProfileAvatarUploadAttributes generateAvatarUploadForm(final String objectName) {
final ZonedDateTime now = ZonedDateTime.now(clock);
final Pair<String, String> policy = policyGenerator.createFor(now, objectName, ProfileHelper.MAX_PROFILE_AVATAR_SIZE_BYTES);
final String signature = policySigner.getSignature(now, policy.second());
return ProfileAvatarUploadAttributes.newBuilder()
.setPath(objectName)
.setCredential(policy.first())
.setAcl("private")
.setAlgorithm("AWS4-HMAC-SHA256")
.setDate(now.format(PostPolicyGenerator.AWS_DATE_TIME))
.setPolicy(policy.second())
.setSignature(ByteString.copyFrom(signature.getBytes()))
.build();
}
}
@@ -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);
}
}
}
@@ -0,0 +1,521 @@
package org.whispersystems.textsecuregcm.grpc;
import static org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil.getClientPlatform;
import static org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil.getPayPalLocale;
import com.google.protobuf.ByteString;
import com.google.protobuf.Empty;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.time.Clock;
import java.util.Locale;
import java.util.Optional;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import org.signal.chat.errors.FailedPrecondition;
import org.signal.chat.errors.FailedUnidentifiedAuthorization;
import org.signal.chat.errors.FailedZkAuthentication;
import org.signal.chat.errors.NotFound;
import org.signal.chat.purchase.CreatePayPalPaymentMethodRequest;
import org.signal.chat.purchase.CreatePayPalPaymentMethodResponse;
import org.signal.chat.purchase.CreatePaymentMethodRequest;
import org.signal.chat.purchase.CreatePaymentMethodResponse;
import org.signal.chat.purchase.DeleteSubscriberRequest;
import org.signal.chat.purchase.DeleteSubscriberResponse;
import org.signal.chat.purchase.GetBankMandateRequest;
import org.signal.chat.purchase.GetBankMandateResponse;
import org.signal.chat.purchase.GetReceiptCredentialsRequest;
import org.signal.chat.purchase.GetReceiptCredentialsResponse;
import org.signal.chat.purchase.GetSubscriptionInformationRequest;
import org.signal.chat.purchase.GetSubscriptionInformationResponse;
import org.signal.chat.purchase.PaymentRequired;
import org.signal.chat.purchase.SetDefaultPaymentMethodRequest;
import org.signal.chat.purchase.SetDefaultPaymentMethodResponse;
import org.signal.chat.purchase.SetIapSubscriptionRequest;
import org.signal.chat.purchase.SetIapSubscriptionResponse;
import org.signal.chat.purchase.SetSubscriptionLevelRequest;
import org.signal.chat.purchase.SetSubscriptionLevelResponse;
import org.signal.chat.purchase.SimpleSubscriptionsGrpc;
import org.signal.chat.purchase.UpdateSubscriberRequest;
import org.signal.chat.purchase.UpdateSubscriberResponse;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.VerificationFailedException;
import org.signal.libsignal.zkgroup.donation.DonationPermit;
import org.whispersystems.textsecuregcm.configuration.SubscriptionConfiguration;
import org.whispersystems.textsecuregcm.configuration.SubscriptionLevelConfiguration;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.storage.DonationPermitsManager;
import org.whispersystems.textsecuregcm.storage.SubscriberCredentials;
import org.whispersystems.textsecuregcm.storage.SubscriptionManager;
import org.whispersystems.textsecuregcm.storage.Subscriptions;
import org.whispersystems.textsecuregcm.subscriptions.AppleAppStoreManager;
import org.whispersystems.textsecuregcm.subscriptions.BankMandateTranslator;
import org.whispersystems.textsecuregcm.subscriptions.BankTransferType;
import org.whispersystems.textsecuregcm.subscriptions.BraintreeManager;
import org.whispersystems.textsecuregcm.subscriptions.CustomerAwareSubscriptionPaymentProcessor;
import org.whispersystems.textsecuregcm.subscriptions.GooglePlayBillingManager;
import org.whispersystems.textsecuregcm.subscriptions.ProcessorCustomer;
import org.whispersystems.textsecuregcm.subscriptions.StripeManager;
import org.whispersystems.textsecuregcm.subscriptions.SubscriberIdCreationNotPermittedException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionChargeFailurePaymentRequiredException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionForbiddenException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInformation;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidArgumentsException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidIdempotencyKeyException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidLevelException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionNotFoundException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentRequiredException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentRequiresActionException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorConflictException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptAlreadyRedeemedException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptRequestedForOpenPaymentException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionStatus;
public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.SubscriptionsImplBase {
private final Clock clock;
private final SubscriptionConfiguration subscriptionConfiguration;
private final SubscriptionManager subscriptionManager;
private final DonationPermitsManager donationPermitsManager;
private final StripeManager stripeManager;
private final BraintreeManager braintreeManager;
private final GooglePlayBillingManager googlePlayBillingManager;
private final AppleAppStoreManager appleAppStoreManager;
private final BankMandateTranslator bankMandateTranslator;
static final String RECEIPT_ISSUED_COUNTER_NAME = MetricsUtil.name(SubscriptionsGrpcService.class, "receiptIssued");
static final String PROCESSOR_TAG_NAME = "processor";
static final String TYPE_TAG_NAME = "type";
private static final String SUBSCRIPTION_TYPE_TAG_NAME = "subscriptionType";
public SubscriptionsGrpcService(final Clock clock,
final SubscriptionConfiguration subscriptionConfiguration,
final SubscriptionManager subscriptionManager,
final DonationPermitsManager donationPermitsManager,
final StripeManager stripeManager,
final BraintreeManager braintreeManager,
final GooglePlayBillingManager googlePlayBillingManager,
final AppleAppStoreManager appleAppStoreManager,
final BankMandateTranslator bankMandateTranslator) {
this.clock = clock;
this.subscriptionConfiguration = subscriptionConfiguration;
this.subscriptionManager = subscriptionManager;
this.donationPermitsManager = donationPermitsManager;
this.stripeManager = stripeManager;
this.braintreeManager = braintreeManager;
this.googlePlayBillingManager = googlePlayBillingManager;
this.appleAppStoreManager = appleAppStoreManager;
this.bankMandateTranslator = bankMandateTranslator;
}
@Override
public UpdateSubscriberResponse updateSubscriber(final UpdateSubscriberRequest request) {
try {
final SubscriberCredentials subscriberCredentials = SubscriberCredentials.process(
request.getSubscriberId().toByteArray(), clock);
final boolean creationPermitted;
try {
if (request.getDonationPermit().isEmpty()) {
creationPermitted = false;
} else {
final DonationPermit permit = new DonationPermit(request.getDonationPermit().toByteArray());
creationPermitted = SubscriptionsUtil.verifyAndSpendDonationPermit(permit, donationPermitsManager, clock);
}
} catch (final InvalidInputException _) {
throw GrpcExceptions.invalidArguments("invalid donation permit");
} catch (final VerificationFailedException _) {
return UpdateSubscriberResponse.newBuilder()
.setPermitRejected(FailedZkAuthentication.newBuilder()
.setDescription("donation permit failed verification")
.build())
.build();
}
subscriptionManager.updateSubscriber(subscriberCredentials, creationPermitted);
return UpdateSubscriberResponse.newBuilder().setSuccess(Empty.getDefaultInstance()).build();
} catch (final SubscriptionForbiddenException e) {
return UpdateSubscriberResponse.newBuilder().setSubscriberIdMismatch(
FailedUnidentifiedAuthorization.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
} catch (SubscriberIdCreationNotPermittedException _) {
if (request.getDonationPermit().isEmpty()) {
throw GrpcExceptions.invalidArguments("donation permit is required to create a subscriber ID");
}
return UpdateSubscriberResponse.newBuilder()
.setPermitRejected(FailedZkAuthentication.newBuilder()
.setDescription("donation permit was not valid")
.build())
.build();
}
}
@Override
public DeleteSubscriberResponse deleteSubscriber(final DeleteSubscriberRequest request)
throws RateLimitExceededException {
try {
final SubscriberCredentials subscriberCredentials = SubscriberCredentials.process(
request.getSubscriberId().toByteArray(), clock);
subscriptionManager.deleteSubscriber(subscriberCredentials);
return DeleteSubscriberResponse.newBuilder().setSuccess(Empty.getDefaultInstance()).build();
} catch (final SubscriptionNotFoundException e) {
return DeleteSubscriberResponse.newBuilder().setSubscriberNotFound(NotFound.newBuilder().build()).build();
} catch (final SubscriptionInvalidArgumentsException e) {
return DeleteSubscriberResponse.newBuilder().setCannotCancelSubscription(
FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
}
}
@Override
public CreatePaymentMethodResponse createPaymentMethod(final CreatePaymentMethodRequest request) {
final SubscriberCredentials subscriberCredentials = SubscriberCredentials.process(
request.getSubscriberId().toByteArray(), clock);
final CustomerAwareSubscriptionPaymentProcessor customerAwareSubscriptionPaymentProcessor = switch (request.getPaymentMethod()) {
case PAYMENT_METHOD_CARD, PAYMENT_METHOD_SEPA_DEBIT, PAYMENT_METHOD_IDEAL -> stripeManager;
default -> throw GrpcExceptions.fieldViolation("payment_method", "Unsupported payment method");
};
try {
final DonationPermit permit = new DonationPermit(request.getDonationPermit().toByteArray());
if (!SubscriptionsUtil.verifyAndSpendDonationPermit(permit, donationPermitsManager, clock)) {
return CreatePaymentMethodResponse.newBuilder()
.setPermitRejected(FailedZkAuthentication.getDefaultInstance())
.build();
}
} catch (final InvalidInputException _) {
throw GrpcExceptions.invalidArguments("invalid donation permit");
} catch (final VerificationFailedException _) {
return CreatePaymentMethodResponse.newBuilder()
.setPermitRejected(FailedZkAuthentication.getDefaultInstance())
.build();
}
try {
final String token = subscriptionManager.addPaymentMethodToCustomer(subscriberCredentials,
customerAwareSubscriptionPaymentProcessor,
getClientPlatform(RequestAttributesUtil.getUserAgent().orElse(null)),
CustomerAwareSubscriptionPaymentProcessor::createPaymentMethodSetupToken);
return CreatePaymentMethodResponse.newBuilder().setResult(
CreatePaymentMethodResponse.CreatePaymentMethodResult.newBuilder().setClientSecret(token)
.setPaymentProvider(customerAwareSubscriptionPaymentProcessor.getProvider().toProto()).build()).build();
} catch (final SubscriptionNotFoundException e) {
return CreatePaymentMethodResponse.newBuilder().setSubscriberNotFound(NotFound.newBuilder()).build();
} catch (final SubscriptionForbiddenException e) {
return CreatePaymentMethodResponse.newBuilder().setSubscriberIdMismatch(
FailedUnidentifiedAuthorization.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
} catch (final SubscriptionProcessorConflictException e) {
return CreatePaymentMethodResponse.newBuilder().setSubscriptionProcessorConflict(
FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
}
}
@Override
public CreatePayPalPaymentMethodResponse createPayPalPaymentMethod(final CreatePayPalPaymentMethodRequest request)
throws IOException {
final SubscriberCredentials subscriberCredentials = SubscriberCredentials.process(
request.getSubscriberId().toByteArray(), clock);
final Locale locale = getPayPalLocale(RequestAttributesUtil.getAvailableAcceptedLocales());
try {
final BraintreeManager.PayPalBillingAgreementApprovalDetails details = subscriptionManager.addPaymentMethodToCustomer(
subscriberCredentials, braintreeManager, getClientPlatform(RequestAttributesUtil.getUserAgent().orElse(null)),
(mgr, _) -> mgr.createPayPalBillingAgreement(request.getReturnUrl(), request.getCancelUrl(),
locale.toLanguageTag()));
return CreatePayPalPaymentMethodResponse.newBuilder().setResult(
CreatePayPalPaymentMethodResponse.CreatePayPalPaymentMethodResult.newBuilder()
.setApprovalUrl(details.approvalUrl()).setToken(details.billingAgreementToken()).build()).build();
} catch (final SubscriptionNotFoundException e) {
return CreatePayPalPaymentMethodResponse.newBuilder().setSubscriberNotFound(NotFound.newBuilder().build())
.build();
} catch (final SubscriptionForbiddenException e) {
return CreatePayPalPaymentMethodResponse.newBuilder().setSubscriberIdMismatch(
FailedUnidentifiedAuthorization.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
} catch (final SubscriptionProcessorConflictException e) {
return CreatePayPalPaymentMethodResponse.newBuilder().setSubscriptionProcessorConflict(
FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
}
}
@Override
public SetDefaultPaymentMethodResponse setDefaultPaymentMethod(final SetDefaultPaymentMethodRequest request)
throws IOException {
try {
final SubscriberCredentials subscriberCredentials = SubscriberCredentials.process(
request.getSubscriberId().toByteArray(), clock);
final CustomerAwareSubscriptionPaymentProcessor manager;
final String paymentMethodId = switch (request.getRequestCase()) {
case STRIPE -> {
manager = stripeManager;
yield request.getStripe().getPaymentMethodToken();
}
case BRAINTREE -> {
manager = braintreeManager;
yield request.getBraintree().getPaymentMethodToken();
}
case SEPA -> {
manager = stripeManager;
yield stripeManager.getGeneratedSepaIdFromSetupIntent(request.getSepa().getSetupIntentId());
}
default -> throw GrpcExceptions.fieldViolation("request", "No payment method specified");
};
final Subscriptions.Record record = subscriptionManager.getSubscriber(subscriberCredentials);
return record.getProcessorCustomer().map(
processorCustomer -> setDefaultPaymentMethodForCustomer(manager, processorCustomer, paymentMethodId,
record.subscriptionId)).orElseGet(() ->
// a missing customer ID indicates the client made requests out of order,
// and needs to call create_payment_method to create a customer for the given payment method
SetDefaultPaymentMethodResponse.newBuilder().setPaymentMethodNotSetUp(FailedPrecondition.newBuilder().build())
.build());
} catch (final SubscriptionNotFoundException e) {
return SetDefaultPaymentMethodResponse.newBuilder().setSubscriberNotFound(NotFound.newBuilder().build()).build();
} catch (final SubscriptionForbiddenException e) {
return SetDefaultPaymentMethodResponse.newBuilder().setSubscriberIdMismatch(
FailedUnidentifiedAuthorization.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
} catch (final SubscriptionProcessorConflictException e) {
return SetDefaultPaymentMethodResponse.newBuilder()
.setSubscriptionProcessorConflict(
FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
}
}
private static SetDefaultPaymentMethodResponse setDefaultPaymentMethodForCustomer(
final CustomerAwareSubscriptionPaymentProcessor processor, final ProcessorCustomer processorCustomer,
final String paymentMethodId, final String subscriptionId) {
try {
processor.setDefaultPaymentMethodForCustomer(processorCustomer.customerId(), paymentMethodId, subscriptionId);
return SetDefaultPaymentMethodResponse.newBuilder().setSuccess(Empty.getDefaultInstance()).build();
} catch (final SubscriptionInvalidArgumentsException e) {
// Here, invalid arguments must mean that the client has made requests out of order, and needs to finish
// setting up the paymentMethod first
return SetDefaultPaymentMethodResponse.newBuilder()
.setPaymentMethodNotSetUp(FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build())
.build();
} catch (final IOException e) {
throw new UncheckedIOException(e);
}
}
@Override
public SetSubscriptionLevelResponse setSubscriptionLevel(final SetSubscriptionLevelRequest request) {
final SubscriberCredentials subscriberCredentials = SubscriberCredentials.process(
request.getSubscriberId().toByteArray(), clock);
try {
final Subscriptions.Record record = subscriptionManager.getSubscriber(subscriberCredentials);
return record.getProcessorCustomer().map(
processorCustomer -> setSubscriptionLevelForCustomer(processorCustomer, subscriberCredentials, record,
request)).orElseGet(() -> SetSubscriptionLevelResponse.newBuilder()
.setPaymentMethodNotSetUp(FailedPrecondition.newBuilder().build()).build());
} catch (final SubscriptionNotFoundException e) {
return SetSubscriptionLevelResponse.newBuilder().setSubscriberNotFound(NotFound.newBuilder().build()).build();
} catch (final SubscriptionForbiddenException e) {
return SetSubscriptionLevelResponse.newBuilder().setSubscriberIdMismatch(
FailedUnidentifiedAuthorization.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
}
}
private SetSubscriptionLevelResponse setSubscriptionLevelForCustomer(final ProcessorCustomer processorCustomer,
final SubscriberCredentials subscriberCredentials, final Subscriptions.Record subscriptionRecord,
final SetSubscriptionLevelRequest request) {
final SubscriptionLevelConfiguration config = subscriptionConfiguration.getSubscriptionLevel(request.getLevel());
if (config == null) {
return SetSubscriptionLevelResponse.newBuilder().setUnsupportedLevel(FailedPrecondition.newBuilder().build())
.build();
}
final Optional<String> templateId = Optional.ofNullable(
config.prices().get(request.getCurrency().toLowerCase(Locale.ROOT)))
.map(priceConfiguration -> priceConfiguration.processorIds().get(processorCustomer.processor()));
if (templateId.isEmpty()) {
return SetSubscriptionLevelResponse.newBuilder().setUnsupportedCurrency(FailedPrecondition.newBuilder().build())
.build();
}
final CustomerAwareSubscriptionPaymentProcessor manager;
switch (processorCustomer.processor()) {
case STRIPE -> manager = stripeManager;
case BRAINTREE -> manager = braintreeManager;
default -> {
return SetSubscriptionLevelResponse.newBuilder().setUnsupportedOperation(FailedPrecondition.newBuilder()
.setDescription(
"Operation cannot be performed with the '" + processorCustomer.processor() + "' payment provider")
.build()).build();
}
}
try {
subscriptionManager.updateSubscriptionLevelForCustomer(subscriberCredentials, subscriptionRecord, manager,
request.getLevel(), request.getCurrency(), request.getIdempotencyKey(), templateId.get(),
(l1, l2) -> SubscriptionsUtil.subscriptionsAreSameType(subscriptionConfiguration, l1, l2));
return SetSubscriptionLevelResponse.newBuilder().setSuccess(
SetSubscriptionLevelResponse.SetSubscriptionLevelResult.newBuilder().setLevel(request.getLevel()).build())
.build();
} catch (final SubscriptionInvalidIdempotencyKeyException e) {
return SetSubscriptionLevelResponse.newBuilder()
.setInvalidIdempotencyKey(FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build())
.build();
} catch (final SubscriptionProcessorException e) {
return SetSubscriptionLevelResponse.newBuilder()
.setChargeFailure(SubscriptionsUtil.toChargeFailure(e.getProcessor(), e.getChargeFailure())).build();
} catch (final SubscriptionPaymentRequiresActionException e) {
return SetSubscriptionLevelResponse.newBuilder().setPaymentRequiresAction(FailedPrecondition.newBuilder().build())
.build();
} catch (final SubscriptionInvalidLevelException e) {
return SetSubscriptionLevelResponse.newBuilder()
.setInvalidLevelTransition(FailedPrecondition.newBuilder().build()).build();
} catch (final SubscriptionProcessorConflictException e) {
return SetSubscriptionLevelResponse.newBuilder().setSubscriptionProcessorConflict(
FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
}
}
@Override
public SetIapSubscriptionResponse setIapSubscription(final SetIapSubscriptionRequest request)
throws RateLimitExceededException {
final SubscriberCredentials subscriberCredentials = SubscriberCredentials.process(
request.getSubscriberId().toByteArray(), clock);
try {
final long level = switch (request.getRequestCase()) {
case APP_STORE -> subscriptionManager.updateAppStoreTransactionId(subscriberCredentials, appleAppStoreManager,
request.getAppStore().getOriginalTransactionId());
case PLAY_BILLING ->
subscriptionManager.updatePlayBillingPurchaseToken(subscriberCredentials, googlePlayBillingManager,
request.getPlayBilling().getPurchaseToken());
default -> throw GrpcExceptions.fieldViolation("request", "must set request type");
};
return SetIapSubscriptionResponse.newBuilder()
.setSuccess(SetIapSubscriptionResponse.SetIapSubscriptionResult.newBuilder().setLevel(level).build()).build();
} catch (final SubscriptionNotFoundException e) {
return SetIapSubscriptionResponse.newBuilder().setSubscriberNotFound(NotFound.newBuilder().build()).build();
} catch (final SubscriptionForbiddenException e) {
return SetIapSubscriptionResponse.newBuilder().setSubscriberIdMismatch(
FailedUnidentifiedAuthorization.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
} catch (final SubscriptionProcessorConflictException e) {
return SetIapSubscriptionResponse.newBuilder().setSubscriptionProcessorConflict(
FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
} catch (final SubscriptionPaymentRequiredException e) {
return SetIapSubscriptionResponse.newBuilder().setPaymentRequired(FailedPrecondition.newBuilder().build())
.build();
} catch (final SubscriptionInvalidArgumentsException e) {
return SetIapSubscriptionResponse.newBuilder()
.setInvalidTransaction(FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build())
.build();
}
}
@Override
public GetSubscriptionInformationResponse getSubscriptionInformation(final GetSubscriptionInformationRequest request)
throws RateLimitExceededException {
final SubscriberCredentials subscriberCredentials = SubscriberCredentials.process(
request.getSubscriberId().toByteArray(), clock);
try {
return subscriptionManager.getSubscriptionInformation(subscriberCredentials)
.map(SubscriptionsGrpcService::buildSubscriptionInformationResponse).orElseGet(
() -> GetSubscriptionInformationResponse.newBuilder().setNoSubscription(Empty.getDefaultInstance())
.build());
} catch (final SubscriptionNotFoundException e) {
return GetSubscriptionInformationResponse.newBuilder().setSubscriberNotFound(NotFound.newBuilder().build())
.build();
} catch (final SubscriptionForbiddenException e) {
return GetSubscriptionInformationResponse.newBuilder().setSubscriberIdMismatch(
FailedUnidentifiedAuthorization.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
}
}
private static GetSubscriptionInformationResponse buildSubscriptionInformationResponse(
final SubscriptionInformation info) {
final GetSubscriptionInformationResponse.Subscription.Builder subscription = GetSubscriptionInformationResponse.Subscription.newBuilder()
.setLevel(info.level()).setEndOfCurrentPeriod(info.endOfCurrentPeriod().getEpochSecond())
.setActive(info.active()).setCancelAtPeriodEnd(info.cancelAtPeriodEnd()).setCurrency(info.price().currency())
.setAmount(info.price().amount().longValue()).setStatus(toProtoSubscriptionStatus(info.status()))
.setProcessor(info.paymentProvider().toProto()).setPaymentMethod(info.paymentMethod().toProtoPaymentMethod())
.setPaymentProcessing(info.paymentProcessing());
if (info.billingCycleAnchor() != null) {
subscription.setBillingCycleAnchor(info.billingCycleAnchor().getEpochSecond());
}
if (info.chargeFailure() != null) {
subscription.setChargeFailure(SubscriptionsUtil.toChargeFailure(info.paymentProvider(), info.chargeFailure()));
}
return GetSubscriptionInformationResponse.newBuilder().setSuccess(subscription.build()).build();
}
@Override
public GetReceiptCredentialsResponse getReceiptCredentials(final GetReceiptCredentialsRequest request)
throws RateLimitExceededException {
final SubscriberCredentials subscriberCredentials = SubscriberCredentials.process(
request.getSubscriberId().toByteArray(), clock);
try {
final SubscriptionManager.ReceiptResult result = subscriptionManager.createReceiptCredentials(
subscriberCredentials, request.getReceiptCredentialRequest().toByteArray(),
r -> SubscriptionsUtil.receiptExpirationWithGracePeriod(subscriptionConfiguration, r));
Metrics.counter(RECEIPT_ISSUED_COUNTER_NAME,
Tags.of(
Tag.of(PROCESSOR_TAG_NAME, result.paymentProvider().toString()),
Tag.of(TYPE_TAG_NAME, "subscription"),
Tag.of(SUBSCRIPTION_TYPE_TAG_NAME,
subscriptionConfiguration.getSubscriptionLevel(result.receiptItem().level()).type().name()
.toLowerCase(Locale.ROOT)),
UserAgentTagUtil.getPlatformTag(RequestAttributesUtil.getUserAgent().orElse(null))))
.increment();
return GetReceiptCredentialsResponse.newBuilder().setSuccess(
GetReceiptCredentialsResponse.GetReceiptCredentialsResult.newBuilder()
.setReceiptCredentialResponse(ByteString.copyFrom(result.receiptCredentialResponse().serialize()))
.build()).build();
} catch (final SubscriptionReceiptRequestedForOpenPaymentException e) {
return GetReceiptCredentialsResponse.newBuilder().setNoPaidInvoice(FailedPrecondition.newBuilder().build())
.build();
} catch (final SubscriptionChargeFailurePaymentRequiredException e) {
return GetReceiptCredentialsResponse.newBuilder().setPaymentRequired(
PaymentRequired.newBuilder()
.setChargeFailure(SubscriptionsUtil.toChargeFailure(e.getProcessor(), e.getChargeFailure())).build()).build();
} catch (final SubscriptionPaymentRequiredException e) {
return GetReceiptCredentialsResponse.newBuilder()
.setPaymentRequired(PaymentRequired.newBuilder().build()).build();
} catch (final SubscriptionInvalidArgumentsException e) {
throw GrpcExceptions.invalidArguments(e.errorDetail().orElse(""));
} catch (final SubscriptionReceiptAlreadyRedeemedException e) {
return GetReceiptCredentialsResponse.newBuilder().setAlreadyRedeemed(FailedPrecondition.newBuilder().build())
.build();
} catch (final SubscriptionNotFoundException e) {
return GetReceiptCredentialsResponse.newBuilder().setSubscriberNotFound(NotFound.newBuilder().build()).build();
} catch (final SubscriptionForbiddenException e) {
return GetReceiptCredentialsResponse.newBuilder().setSubscriberIdMismatch(
FailedUnidentifiedAuthorization.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
}
}
private static org.signal.chat.purchase.SubscriptionStatus toProtoSubscriptionStatus(
final SubscriptionStatus status) {
return switch (status) {
case ACTIVE -> org.signal.chat.purchase.SubscriptionStatus.SUBSCRIPTION_STATUS_ACTIVE;
case INCOMPLETE -> org.signal.chat.purchase.SubscriptionStatus.SUBSCRIPTION_STATUS_INCOMPLETE;
case PAST_DUE -> org.signal.chat.purchase.SubscriptionStatus.SUBSCRIPTION_STATUS_PAST_DUE;
case CANCELED -> org.signal.chat.purchase.SubscriptionStatus.SUBSCRIPTION_STATUS_CANCELED;
case UNPAID -> org.signal.chat.purchase.SubscriptionStatus.SUBSCRIPTION_STATUS_UNPAID;
case UNKNOWN -> org.signal.chat.purchase.SubscriptionStatus.SUBSCRIPTION_STATUS_UNKNOWN;
};
}
@Override
public GetBankMandateResponse getBankMandate(final GetBankMandateRequest request) {
final BankTransferType bankTransferType = switch (request.getBankTransferType()) {
case BANK_TRANSFER_TYPE_SEPA_DEBIT -> BankTransferType.SEPA_DEBIT;
default -> throw GrpcExceptions.fieldViolation("bank_transfer_type", "Unsupported bank transfer type");
};
final String mandate = bankMandateTranslator.translate(RequestAttributesUtil.getAvailableAcceptedLocales(),
bankTransferType);
return GetBankMandateResponse.newBuilder().setMandate(mandate).build();
}
}
@@ -0,0 +1,187 @@
package org.whispersystems.textsecuregcm.grpc;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tags;
import java.math.BigDecimal;
import java.time.Clock;
import java.time.Instant;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.signal.libsignal.zkgroup.VerificationFailedException;
import org.signal.libsignal.zkgroup.donation.DonationPermit;
import org.whispersystems.textsecuregcm.badges.BadgeTranslator;
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration;
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationCurrencyConfiguration;
import org.whispersystems.textsecuregcm.configuration.SubscriptionConfiguration;
import org.whispersystems.textsecuregcm.configuration.SubscriptionLevelConfiguration;
import org.whispersystems.textsecuregcm.entities.Badge;
import org.whispersystems.textsecuregcm.entities.PurchasableBadge;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.storage.DonationPermitsManager;
import org.whispersystems.textsecuregcm.subscriptions.ChargeFailure;
import org.whispersystems.textsecuregcm.subscriptions.CurrencyConfiguration;
import org.whispersystems.textsecuregcm.subscriptions.CustomerAwareSubscriptionPaymentProcessor;
import org.whispersystems.textsecuregcm.subscriptions.LevelConfiguration;
import org.whispersystems.textsecuregcm.subscriptions.PaymentMethod;
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
import org.whispersystems.textsecuregcm.util.ua.UnrecognizedUserAgentException;
import org.whispersystems.textsecuregcm.util.ua.UserAgentUtil;
public class SubscriptionsUtil {
private static final String DONATION_PERMIT_PRESENT_COUNTER_NAME = MetricsUtil.name(SubscriptionsUtil.class,
"donationPermitPresent");
private static final String DONATION_PERMIT_SPEND_COUNTER_NAME = MetricsUtil.name(SubscriptionsUtil.class,
"donationPermitSpend");
@Nullable
public static ClientPlatform getClientPlatform(@Nullable final String userAgentString) {
try {
return UserAgentUtil.parseUserAgentString(userAgentString).platform();
} catch (final UnrecognizedUserAgentException e) {
return null;
}
}
public static boolean subscriptionsAreSameType(final SubscriptionConfiguration subscriptionConfiguration, final long level1, final long level2) {
return subscriptionConfiguration.getSubscriptionLevel(level1).type()
== subscriptionConfiguration.getSubscriptionLevel(level2).type();
}
public static Instant receiptExpirationWithGracePeriod(
final SubscriptionConfiguration subscriptionConfiguration,
final CustomerAwareSubscriptionPaymentProcessor.ReceiptItem receiptItem) {
return switch (subscriptionConfiguration.getSubscriptionLevel(receiptItem.level()).type()) {
case DONATION -> receiptItem.paymentTime().receiptExpiration(
subscriptionConfiguration.getBadgeExpiration(),
subscriptionConfiguration.getBadgeGracePeriod());
case BACKUP -> receiptItem.paymentTime().receiptExpiration(
subscriptionConfiguration.getBackupExpiration(),
subscriptionConfiguration.getBackupGracePeriod());
};
}
public static Map<String, CurrencyConfiguration> buildCurrencyConfiguration(final List<CustomerAwareSubscriptionPaymentProcessor> subscriptionPaymentProcessors,
final OneTimeDonationConfiguration oneTimeDonationConfiguration,
final SubscriptionConfiguration subscriptionConfiguration) {
return oneTimeDonationConfiguration.currencies()
.entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey, currencyAndConfig -> {
final String currency = currencyAndConfig.getKey();
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())
);
final Function<Map<Long, ? extends SubscriptionLevelConfiguration>, Map<Long, BigDecimal>> extractSubscriptionAmounts = levels ->
levels.entrySet().stream()
.filter(levelIdAndConfig -> levelIdAndConfig.getValue().prices().containsKey(currency))
.collect(Collectors.toMap(
Map.Entry::getKey,
levelIdAndConfig -> levelIdAndConfig.getValue().prices().get(currency).amount()));
final List<PaymentMethod> supportedPaymentMethods = Arrays.stream(PaymentMethod.values())
.filter(paymentMethod -> subscriptionPaymentProcessors.stream()
.anyMatch(manager -> manager.supportsPaymentMethod(paymentMethod)
&& manager.getSupportedCurrenciesForPaymentMethod(paymentMethod).contains(currency)))
.collect(Collectors.toList());
if (supportedPaymentMethods.isEmpty()) {
throw new RuntimeException("Configuration has currency with no processor support: " + currency);
}
return new CurrencyConfiguration(
currencyConfig.minimum(),
oneTimeLevelsToSuggestedAmounts,
extractSubscriptionAmounts.apply(subscriptionConfiguration.getDonationLevels()),
extractSubscriptionAmounts.apply(subscriptionConfiguration.getBackupLevels()),
supportedPaymentMethods);
}));
}
public static Map<Long, LevelConfiguration> buildDonationLevelsConfiguration(
final SubscriptionConfiguration subscriptionConfiguration,
final OneTimeDonationConfiguration oneTimeDonationConfiguration,
final BadgeTranslator badgeTranslator,
final List<Locale> acceptableLanguages) {
final Map<Long, LevelConfiguration> donationLevels = new HashMap<>();
subscriptionConfiguration.getDonationLevels().forEach((levelId, levelConfig) -> {
final LevelConfiguration levelConfiguration = new LevelConfiguration(
badgeTranslator.translate(acceptableLanguages, levelConfig.badge()));
donationLevels.put(levelId, levelConfiguration);
});
final Badge boostBadge = badgeTranslator.translate(acceptableLanguages,
oneTimeDonationConfiguration.boost().badge());
donationLevels.put(oneTimeDonationConfiguration.boost().level(),
new LevelConfiguration(
// NB: the one-time badges are PurchasableBadge, which has a `duration` field
new PurchasableBadge(
boostBadge,
oneTimeDonationConfiguration.boost().expiration())));
final Badge giftBadge = badgeTranslator.translate(acceptableLanguages, oneTimeDonationConfiguration.gift().badge());
donationLevels.put(oneTimeDonationConfiguration.gift().level(),
new LevelConfiguration(
new PurchasableBadge(
giftBadge,
oneTimeDonationConfiguration.gift().expiration())));
return donationLevels;
}
/// Verifies the permit and spends it
///
/// @return `true` if the spend was accepted, otherwise `false`
/// @throws VerificationFailedException if the permit is invalid
public static boolean verifyAndSpendDonationPermit(final DonationPermit permit, final DonationPermitsManager donationPermitsManager, final Clock clock) throws VerificationFailedException {
final boolean spent = donationPermitsManager.spend(permit);
Metrics.counter(DONATION_PERMIT_SPEND_COUNTER_NAME, "outcome", spent ? "success" : "failure").increment();
return spent;
}
public static void recordDonationPermitPresent(final boolean present, final String context, final String userAgent) {
Metrics.counter(DONATION_PERMIT_PRESENT_COUNTER_NAME,
Tags.of("present", String.valueOf(present),
"context", context)
.and(UserAgentTagUtil.getPlatformTag(userAgent)))
.increment();
}
public static org.signal.chat.purchase.ChargeFailure toChargeFailure(final PaymentProvider processor,
final ChargeFailure chargeFailure) {
final org.signal.chat.purchase.ChargeFailure.Builder builder = org.signal.chat.purchase.ChargeFailure.newBuilder()
.setProcessor(processor.toProto()).setCode(chargeFailure.code()).setMessage(chargeFailure.message());
if (chargeFailure.outcomeNetworkStatus() != null) {
builder.setOutcomeNetworkStatus(chargeFailure.outcomeNetworkStatus());
}
if (chargeFailure.outcomeReason() != null) {
builder.setOutcomeReason(chargeFailure.outcomeReason());
}
if (chargeFailure.outcomeType() != null) {
builder.setOutcomeType(chargeFailure.outcomeType());
}
return builder.build();
}
public static Locale getPayPalLocale(final List<Locale> acceptableLocales) {
return acceptableLocales.stream()
.filter(l -> !"*".equals(l.getLanguage()))
.findFirst()
.orElse(Locale.US);
}
}
Loaded 100 of 340 files, more files were not shown because too many files have changed in this diff. Show more