Compare commits

...
Author SHA1 Message Date
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
82 changed files with 2555 additions and 1727 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 }}"
+2 -2
View File
@@ -25,9 +25,9 @@ jobs:
options: --name foundationdb1
steps:
- uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
- name: Set up JDK
uses: actions/setup-java@be666c2fcd27ec809703dec50e508c2fdc7f6654 # v5.2.0
uses: actions/setup-java@1bcf9fb12cf4aa7d266a90ae39939e61372fe520 # v5.4.0
with:
distribution: 'temurin'
java-version-file: .java-version
+1 -1
View File
@@ -67,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>
+1 -3
View File
@@ -79,10 +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==
profileAvatarsZkConfig.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
+5 -10
View File
@@ -318,18 +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
profileAvatarsZkConfig:
serverSecret: secret://profileAvatarsZkConfig.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
@@ -368,8 +365,6 @@ badges:
svgs:
- light: example-light.svg
dark: example-dark.svg
badgeIdsEnabledForAll:
- TEST
receiptLevels:
'1': TEST
@@ -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;
@@ -67,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
@@ -130,6 +131,11 @@ public class WhisperServerConfiguration extends Configuration {
@JsonProperty
private GcpAttachmentsConfiguration gcpAttachments;
@NotNull
@Valid
@JsonProperty
private BackupConfiguration backup = new BackupConfiguration();
@NotNull
@Valid
@JsonProperty
@@ -220,11 +226,6 @@ public class WhisperServerConfiguration extends Configuration {
@JsonProperty
private PaymentsServiceConfiguration paymentsService;
@Valid
@NotNull
@JsonProperty
private ZkConfig zkConfig;
@Valid
@NotNull
@JsonProperty
@@ -233,12 +234,12 @@ public class WhisperServerConfiguration extends Configuration {
@Valid
@NotNull
@JsonProperty
private GenericZkConfig backupsZkConfig;
private GenericZkConfig chatZkConfig;
@Valid
@NotNull
@JsonProperty
private GenericZkConfig profileAvatarsZkConfig;
private ZkConfig groupsZkConfig;
@Valid
@NotNull
@@ -428,6 +429,10 @@ public class WhisperServerConfiguration extends Configuration {
return gcpAttachments;
}
public BackupConfiguration getBackupConfiguration() {
return backup;
}
public FaultTolerantRedisClusterFactory getCacheClusterConfiguration() {
return cacheCluster;
}
@@ -492,20 +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;
}
public GenericZkConfig getProfileAvatarsZkConfig() {
return profileAvatarsZkConfig;
/// ZK secret shared with Groups Service
public ZkConfig getGroupsZkConfig() {
return groupsZkConfig;
}
public RemoteConfigConfiguration getRemoteConfigConfiguration() {
@@ -178,6 +178,7 @@ 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.RequestAttributesInterceptor;
@@ -316,6 +317,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;
@@ -391,6 +393,7 @@ 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 ProcessScheduledJobsServiceCommand("process-idle-device-notification-jobs",
"Processes scheduled jobs to send notifications to idle devices",
@@ -914,18 +917,18 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
config.getCdnConfiguration().credentials().accessKeyId().value(),
config.getCdnConfiguration().credentials().secretAccessKey().value());
ServerSecretParams zkSecretParams = new ServerSecretParams(config.getZkConfig().serverSecret().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());
GenericServerSecretParams profileAvatarsGenericZkSecretParams = new GenericServerSecretParams(config.getProfileAvatarsZkConfig().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(),
@@ -936,7 +939,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
config.getCdn3StorageManagerConfiguration());
BackupManager backupManager = new BackupManager(
backupsDb,
backupsGenericZkSecretParams,
chatGenericZkSecretParams,
rateLimiters,
tusAttachmentGenerator,
cdn3BackupCredentialGenerator,
@@ -944,7 +947,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
svrbCredentialsGenerator,
secureValueRecoveryBClient,
clock,
dynamicConfigurationManager);
config.getBackupConfiguration());
final BackupMetrics backupMetrics = new BackupMetrics();
final AppleDeviceChecks appleDeviceChecks = new AppleDeviceChecks(
@@ -961,7 +964,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
config.getAppleDeviceCheck().teamId(),
config.getAppleDeviceCheck().bundleId());
final DonationPermitsManager donationPermitsManager = new DonationPermitsManager(donationPermits, zkSecretParams,
final DonationPermitsManager donationPermitsManager = new DonationPermitsManager(donationPermits, groupZkSecretParams,
clock);
final SubscriptionManager subscriptionManager = new SubscriptionManager(subscriptions,
@@ -1054,7 +1057,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,
@@ -1067,11 +1070,11 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
config.getDeliveryCertificate().embedSigner());
final List<ServerServiceDefinition> authenticatedServices = Stream.of(
new AccountsGrpcService(accountsManager, rateLimiters, usernameHashZkProofVerifier, registrationRecoveryPasswordsManager),
new AccountsGrpcService(accountsManager, rateLimiters, usernameHashZkProofVerifier, registrationRecoveryPasswordsManager, Clock.systemUTC()),
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, profileAvatarsGenericZkSecretParams, 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),
@@ -1080,7 +1083,10 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
config.getAttachments().maxAttachmentUploadSizeInBytes(), Clock.systemUTC()),
new PaymentsGrpcService(currencyManager),
new ChallengeGrpcService(accountsManager, rateLimitChallengeManager, challengeConstraintChecker),
new DonationsGrpcService(clock, zkReceiptOperations, redeemedReceiptsManager, accountsManager, config.getBadges(), ReceiptCredentialPresentation::new, donationPermitsManager, rateLimiters))
new DonationsGrpcService(clock, zkReceiptOperations, redeemedReceiptsManager, accountsManager, config.getBadges(), ReceiptCredentialPresentation::new, donationPermitsManager, rateLimiters),
new ProductConfigurationGrpcService(config.getSubscription(), config.getOneTimeDonations(),
List.of(stripeManager, braintreeManager), profileBadgeConverter,
config.getBackupConfiguration().maxTotalMediaSize()))
.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!
@@ -1096,14 +1102,13 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
final List<ServerServiceDefinition> unauthenticatedServices = Stream.of(
new AccountsAnonymousGrpcService(accountsManager, rateLimiters),
new CallQualitySurveyGrpcService(callQualitySurveyManager, rateLimiters),
new KeysAnonymousGrpcService(accountsManager, keysManager, zkSecretParams, Clock.systemUTC()),
new ProfileAnonymousGrpcService(accountsManager, profilesManager, profileBadgeConverter, profileCdnPolicyGenerator, profileAvatarsGenericZkSecretParams, zkSecretParams, rateLimiters, clock),
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 SubscriptionsGrpcService(clock, config.getSubscription(), config.getOneTimeDonations(), subscriptionManager,
donationPermitsManager, stripeManager, braintreeManager, googlePlayBillingManager, appleAppStoreManager,
profileBadgeConverter, bankMandateTranslator, dynamicConfigurationManager),
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))
@@ -1238,14 +1243,14 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new DirectoryV2Controller(directoryV2CredentialsGenerator),
new DonationController(clock, zkReceiptOperations, redeemedReceiptsManager, accountsManager, config.getBadges(),
ReceiptCredentialPresentation::new, donationPermitsManager, rateLimiters),
new KeysController(rateLimiters, keysManager, accountsManager, zkSecretParams, Clock.systemUTC()),
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,
zkSecretParams, zkProfileOperations, batchIdentityCheckExecutor),
groupZkSecretParams, zkProfileOperations, batchIdentityCheckExecutor),
new ProvisioningController(rateLimiters, provisioningManager),
new RegistrationController(accountsManager, phoneVerificationTokenManager, registrationLockVerificationManager,
rateLimiters, registrationFraudChecker),
@@ -1259,7 +1264,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
dynamicConfigurationManager, experimentEnrollmentManager, clock),
new SubscriptionController(clock, config.getSubscription(), config.getOneTimeDonations(),
subscriptionManager, stripeManager, braintreeManager, googlePlayBillingManager, appleAppStoreManager,
profileBadgeConverter, bankMandateTranslator, donationPermitsManager, dynamicConfigurationManager),
profileBadgeConverter, bankMandateTranslator, donationPermitsManager,
config.getBackupConfiguration().maxTotalMediaSize()),
new OneTimeDonationController(clock, config.getOneTimeDonations(), stripeManager, braintreeManager,
payPalDonationsTranslator, zkReceiptOperations, issuedReceiptsManager, oneTimeDonationsManager,
donationPermitsManager)
@@ -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(
@@ -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,
@@ -68,7 +70,7 @@ public class ConfiguredProfileBadgeConverter implements ProfileBadgeConverter, B
final List<Locale> acceptableLanguages,
final List<AccountBadge> accountBadges,
final boolean isSelf) {
if (accountBadges.isEmpty() && badgeIdsEnabledForAll.isEmpty()) {
if (accountBadges.isEmpty()) {
return List.of();
}
@@ -94,20 +96,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;
}
@@ -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() {
@@ -69,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();
@@ -143,10 +139,6 @@ public class DynamicConfiguration {
return restDeprecation;
}
public DynamicBackupConfiguration getBackupConfiguration() {
return backup;
}
public DynamicCarrierDataLookupConfiguration getCarrierDataLookupConfiguration() {
return carrierDataLookup;
}
@@ -8,6 +8,7 @@ import static org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil.getClientP
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;
@@ -34,9 +35,9 @@ 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;
@@ -45,7 +46,7 @@ import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
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;
@@ -74,6 +75,8 @@ 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.SubscriptionInvalidAmountException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorException;
import org.whispersystems.textsecuregcm.util.ExactlySize;
import org.whispersystems.textsecuregcm.util.HeaderUtils;
@@ -168,14 +171,15 @@ public class OneTimeDonationController {
})))
@ApiResponse(responseCode = "401", description = "Donation permit was invalid or already spent")
@RateLimitedByIp(RateLimiters.For.ONE_TIME_DONATION)
public CompletableFuture<Response> createBoostPaymentIntent(
@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) {
@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");
@@ -195,11 +199,11 @@ public class OneTimeDonationController {
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
}
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());
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());
}
/**
@@ -245,34 +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(
@ManagedAsync
public CreatePayPalBoostResponse createPayPalBoost(
@Auth final Optional<AuthenticatedDevice> authenticatedAccount,
@NotNull @Valid final CreatePayPalBoostRequest request,
@Context final ContainerRequestContext containerRequestContext) {
@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);
final OneTimeDonationUtil.LocalizedPayPalDonationLineItem localizedLineItem = OneTimeDonationUtil.localizePayPalDonationLineItem(
payPalDonationsTranslator, acceptableLanguages);
return braintreeManager.createOneTimePayment(request.currency.toUpperCase(Locale.ROOT), request.amount,
localizedLineItem.locale().toLanguageTag(),
request.returnUrl, request.cancelUrl, localizedLineItem.itemName());
})
.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 {
@@ -289,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(
@ManagedAsync
public ConfirmPayPalBoostResponse confirmPayPalBoost(
@Auth final Optional<AuthenticatedDevice> authenticatedAccount,
@NotNull @Valid final ConfirmPayPalBoostRequest request,
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent) {
@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 {
@@ -339,77 +339,76 @@ public class OneTimeDonationController {
@Path("/receipt_credentials")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public CompletableFuture<Response> createBoostReceiptCredentials(
@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<Optional<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(maybePaymentDetails -> {
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();
});
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();
}
}
@@ -48,6 +48,8 @@ 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;
@@ -67,7 +69,6 @@ import org.whispersystems.textsecuregcm.badges.BadgeTranslator;
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration;
import org.whispersystems.textsecuregcm.configuration.SubscriptionConfiguration;
import org.whispersystems.textsecuregcm.configuration.SubscriptionLevelConfiguration;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil;
import org.whispersystems.textsecuregcm.limits.RateLimitedByIp;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
@@ -75,7 +76,6 @@ import org.whispersystems.textsecuregcm.mappers.SubscriptionExceptionMapper;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.storage.DonationPermitsManager;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.storage.SubscriberCredentials;
import org.whispersystems.textsecuregcm.storage.SubscriptionManager;
import org.whispersystems.textsecuregcm.storage.Subscriptions;
@@ -114,7 +114,7 @@ public class SubscriptionController {
private final BadgeTranslator badgeTranslator;
private final BankMandateTranslator bankMandateTranslator;
private final DonationPermitsManager donationPermitsManager;
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
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";
@@ -132,7 +132,7 @@ public class SubscriptionController {
BadgeTranslator badgeTranslator,
BankMandateTranslator bankMandateTranslator,
DonationPermitsManager donationPermitsManager,
DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
long backupMediaStorageAllowanceBytes) {
this.subscriptionManager = subscriptionManager;
this.clock = Objects.requireNonNull(clock);
this.subscriptionConfiguration = Objects.requireNonNull(subscriptionConfiguration);
@@ -144,7 +144,7 @@ public class SubscriptionController {
this.badgeTranslator = Objects.requireNonNull(badgeTranslator);
this.bankMandateTranslator = Objects.requireNonNull(bankMandateTranslator);
this.donationPermitsManager = donationPermitsManager;
this.dynamicConfigurationManager = Objects.requireNonNull(dynamicConfigurationManager);
this.backupMediaStorageAllowanceBytes = backupMediaStorageAllowanceBytes;
}
@@ -152,14 +152,12 @@ public class SubscriptionController {
GetSubscriptionConfigurationResponse buildGetSubscriptionConfigurationResponse(
final List<Locale> acceptableLanguages) {
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())));
@@ -315,7 +313,8 @@ 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);
@@ -325,10 +324,8 @@ public class SubscriptionController {
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());
}
@@ -350,7 +347,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);
@@ -754,18 +751,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);
@@ -776,7 +773,7 @@ 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);
@@ -7,6 +7,8 @@ package org.whispersystems.textsecuregcm.grpc;
import com.google.protobuf.ByteString;
import java.security.SecureRandom;
import java.time.Clock;
import java.time.Instant;
import java.util.ArrayList;
import java.util.HexFormat;
import java.util.List;
@@ -26,6 +28,8 @@ import org.signal.chat.account.DeleteUsernameLinkRequest;
import org.signal.chat.account.DeleteUsernameLinkResponse;
import org.signal.chat.account.GetAccountIdentityRequest;
import org.signal.chat.account.GetAccountIdentityResponse;
import org.signal.chat.account.GetEntitlementsRequest;
import org.signal.chat.account.GetEntitlementsResponse;
import org.signal.chat.account.ReserveUsernameHashRequest;
import org.signal.chat.account.ReserveUsernameHashResponse;
import org.signal.chat.account.SetDiscoverableByPhoneNumberRequest;
@@ -70,16 +74,19 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
private final RateLimiters rateLimiters;
private final UsernameHashZkProofVerifier usernameHashZkProofVerifier;
private final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager;
private final Clock clock;
public AccountsGrpcService(final AccountsManager accountsManager,
final RateLimiters rateLimiters,
final UsernameHashZkProofVerifier usernameHashZkProofVerifier,
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager) {
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager,
final Clock clock) {
this.accountsManager = accountsManager;
this.rateLimiters = rateLimiters;
this.usernameHashZkProofVerifier = usernameHashZkProofVerifier;
this.registrationRecoveryPasswordsManager = registrationRecoveryPasswordsManager;
this.clock = clock;
}
@Override
@@ -94,11 +101,41 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
account.getUsernameHash().ifPresent(usernameHash ->
accountIdentifiersBuilder.setUsernameHash(ByteString.copyFrom(usernameHash)));
if (account.getUsernameLinkHandle() != null) {
accountIdentifiersBuilder.setUsernameLinkHandle(UUIDUtil.toByteString(account.getUsernameLinkHandle()));
}
return GetAccountIdentityResponse.newBuilder()
.setAccountIdentifiers(accountIdentifiersBuilder)
.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(),
@@ -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();
}
}
@@ -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);
@@ -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();
}
}
@@ -8,6 +8,7 @@ import static org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil.getClientP
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;
@@ -21,18 +22,18 @@ 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.one_time_donations.AmountAboveSepaLimitError;
import org.signal.chat.one_time_donations.AmountBelowMinimumError;
import org.signal.chat.one_time_donations.ConfirmPayPalBoostRequest;
import org.signal.chat.one_time_donations.ConfirmPayPalBoostResponse;
import org.signal.chat.one_time_donations.CreateBoostReceiptCredentialsRequest;
import org.signal.chat.one_time_donations.CreateBoostReceiptCredentialsResponse;
import org.signal.chat.one_time_donations.CreateBoostRequest;
import org.signal.chat.one_time_donations.CreateBoostResponse;
import org.signal.chat.one_time_donations.CreatePayPalBoostRequest;
import org.signal.chat.one_time_donations.CreatePayPalBoostResponse;
import org.signal.chat.one_time_donations.SimpleOneTimeDonationsGrpc;
import org.signal.chat.subscriptions.PaymentRequired;
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;
@@ -53,6 +54,8 @@ 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 {
@@ -91,7 +94,8 @@ public class OneTimeDonationsGrpcService extends SimpleOneTimeDonationsGrpc.OneT
}
@Override
public CreateBoostResponse createBoost(final CreateBoostRequest request) throws RateLimitExceededException {
public CreateBoostResponse createBoost(final CreateBoostRequest request)
throws RateLimitExceededException {
RateLimitUtil.rateLimitByRemoteAddress(rateLimiters.forDescriptor(RateLimiters.For.ONE_TIME_DONATION));
try {
@@ -144,16 +148,23 @@ public class OneTimeDonationsGrpcService extends SimpleOneTimeDonationsGrpc.OneT
.setAmountAboveSepaLimit(AmountAboveSepaLimitError.newBuilder()
.setMaximum(r.maximum().toString()).build()).build();
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.Success _ -> {
final com.stripe.model.PaymentIntent paymentIntent = stripeManager.createPaymentIntent(
request.getCurrency(), request.getAmount(), request.getLevel(),
getClientPlatform(RequestAttributesUtil.getUserAgent().orElse(null))).join();
yield CreateBoostResponse.newBuilder().setClientSecret(paymentIntent.getClientSecret()).build();
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) {
public CreatePayPalBoostResponse createPayPalBoost(final CreatePayPalBoostRequest request) throws IOException {
final OneTimeDonationUtil.OneTimeDonationRequestValidationResult validationResult =
OneTimeDonationUtil.validateOneTimeDonationRequest(
@@ -185,7 +196,7 @@ public class OneTimeDonationsGrpcService extends SimpleOneTimeDonationsGrpc.OneT
braintreeManager.createOneTimePayment(
request.getCurrency().toUpperCase(Locale.ROOT), request.getAmount(),
localizedLineItem.locale().toLanguageTag(), request.getReturnUrl(), request.getCancelUrl(),
localizedLineItem.itemName()).join();
localizedLineItem.itemName());
yield CreatePayPalBoostResponse.newBuilder()
.setResult(CreatePayPalBoostResponse.CreatePayPalBoostResult.newBuilder()
.setApprovalUrl(approvalDetails.approvalUrl())
@@ -196,7 +207,7 @@ public class OneTimeDonationsGrpcService extends SimpleOneTimeDonationsGrpc.OneT
@Override
public ConfirmPayPalBoostResponse confirmPayPalBoost(final ConfirmPayPalBoostRequest request)
throws RateLimitExceededException {
throws RateLimitExceededException, IOException {
RateLimitUtil.rateLimitByRemoteAddress(rateLimiters.forDescriptor(RateLimiters.For.ONE_TIME_DONATION));
final OneTimeDonationUtil.OneTimeDonationRequestValidationResult validationResult =
@@ -222,33 +233,39 @@ public class OneTimeDonationsGrpcService extends SimpleOneTimeDonationsGrpc.OneT
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.AmountAboveSepaLimit _ ->
throw new IllegalStateException("SEPA limit should not trigger for PayPal");
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.Success _ -> {
final BraintreeManager.PayPalChargeSuccessDetails chargeSuccessDetails =
braintreeManager.captureOneTimePayment(
request.getPayerId(), request.getPaymentId(), request.getPaymentToken(),
request.getCurrency(), request.getAmount(), request.getLevel(),
getClientPlatform(RequestAttributesUtil.getUserAgent().orElse(null))).join();
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) {
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()).join();
maybePaymentDetails = stripeManager.getPaymentDetails(request.getPaymentIntentId());
}
case PAYMENT_PROVIDER_BRAINTREE -> {
processor = PaymentProvider.BRAINTREE;
maybePaymentDetails = braintreeManager.getPaymentDetails(request.getPaymentIntentId()).join();
maybePaymentDetails = braintreeManager.getPaymentDetails(request.getPaymentIntentId());
}
default -> throw GrpcExceptions.fieldViolation("processor", "Unsupported payment processor");
}
@@ -0,0 +1,167 @@
package org.whispersystems.textsecuregcm.grpc;
import com.google.protobuf.ByteString;
import com.google.protobuf.CodedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import org.signal.chat.purchase.AmountList;
import org.signal.chat.purchase.BackupConfiguration;
import org.signal.chat.purchase.BackupLevelConfiguration;
import org.signal.chat.purchase.Configuration;
import org.signal.chat.purchase.CurrencyConfiguration;
import org.signal.chat.purchase.GetConfigurationRequest;
import org.signal.chat.purchase.GetConfigurationResponse;
import org.signal.chat.purchase.LevelConfiguration;
import org.signal.chat.purchase.SimpleProductConfigurationGrpc;
import org.signal.chat.purchase.TaggedConfiguration;
import org.whispersystems.textsecuregcm.badges.BadgeTranslator;
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration;
import org.whispersystems.textsecuregcm.configuration.SubscriptionConfiguration;
import org.whispersystems.textsecuregcm.entities.PurchasableBadge;
import org.whispersystems.textsecuregcm.subscriptions.CustomerAwareSubscriptionPaymentProcessor;
import org.whispersystems.textsecuregcm.subscriptions.PaymentMethod;
public class ProductConfigurationGrpcService extends SimpleProductConfigurationGrpc.ProductConfigurationImplBase {
private final SubscriptionConfiguration subscriptionConfiguration;
private final OneTimeDonationConfiguration oneTimeDonationConfiguration;
private final BadgeTranslator badgeTranslator;
// These portions of the configuration are identical on every request
private final Map<String, CurrencyConfiguration> currencyConfigurations;
private final BackupConfiguration backupConfiguration;
// The configuration varies based on the provided Accept-Language header. Here we cache the eTag for the resolved
// language, so if the caller provides a matching etag we don't have to build the full configuration match.
private final ConcurrentHashMap<Locale, ByteString> localeToEtag = new ConcurrentHashMap<>();
public ProductConfigurationGrpcService(
final SubscriptionConfiguration subscriptionConfiguration,
final OneTimeDonationConfiguration oneTimeDonationConfiguration,
List<CustomerAwareSubscriptionPaymentProcessor> paymentProcessors,
final BadgeTranslator badgeTranslator,
final long backupMediaStorageAllowanceBytes) {
this.subscriptionConfiguration = subscriptionConfiguration;
this.oneTimeDonationConfiguration = oneTimeDonationConfiguration;
this.badgeTranslator = badgeTranslator;
this.backupConfiguration = buildBackupConfiguration(subscriptionConfiguration, backupMediaStorageAllowanceBytes);
this.currencyConfigurations =
buildCurrencyConfigurations(subscriptionConfiguration, oneTimeDonationConfiguration, paymentProcessors);
}
@Override
public GetConfigurationResponse getConfiguration(final GetConfigurationRequest request) {
final Locale locale = badgeTranslator.resolveLocale(RequestAttributesUtil.getAvailableAcceptedLocales());
final ByteString etag = localeToEtag.get(locale);
if (etag != null && etag.equals(request.getEtag())) {
return GetConfigurationResponse.newBuilder().setEtagMatched(true).build();
}
final Map<Long, LevelConfiguration> levelConfigurations = SubscriptionsUtil
.buildDonationLevelsConfiguration(subscriptionConfiguration, oneTimeDonationConfiguration, badgeTranslator,
RequestAttributesUtil.getAvailableAcceptedLocales())
.entrySet().stream().collect(Collectors.toMap(
Map.Entry::getKey,
entry -> toProtoLevelConfiguration(entry.getValue())));
final Configuration configuration = Configuration.newBuilder()
.putAllCurrencies(currencyConfigurations)
.putAllBadgeLevels(levelConfigurations)
.setBackup(backupConfiguration)
.setSepaMaximumEuros(oneTimeDonationConfiguration.sepaMaximumEuros().toString()).build();
final TaggedConfiguration taggedConfiguration = calculateEtag(configuration);
// This could race and multiple threads could decide to build-and-cache. That's fine, they should all calculate
// the same etag.
localeToEtag.put(locale, taggedConfiguration.getEtag());
return GetConfigurationResponse.newBuilder().setTaggedConfiguration(taggedConfiguration).build();
}
private static TaggedConfiguration calculateEtag(final Configuration configuration) {
final ByteArrayOutputStream baos = new ByteArrayOutputStream(configuration.getSerializedSize());
final CodedOutputStream cos = CodedOutputStream.newInstance(baos);
cos.useDeterministicSerialization();
try {
configuration.writeTo(cos);
cos.flush();
final byte[] configurationBytes = baos.toByteArray();
byte[] hash = MessageDigest.getInstance("SHA-256").digest(configurationBytes);
return TaggedConfiguration.newBuilder()
.setConfiguration(configuration)
.setEtag(ByteString.copyFrom(hash))
.build();
} catch (IOException e) {
throw new UncheckedIOException(e);
} catch (NoSuchAlgorithmException e) {
throw new AssertionError(e);
}
}
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 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();
}
private static LevelConfiguration toProtoLevelConfiguration(
final org.whispersystems.textsecuregcm.subscriptions.LevelConfiguration levelConfiguration) {
final LevelConfiguration.Builder builder = LevelConfiguration.newBuilder();
if (levelConfiguration.badge() instanceof final PurchasableBadge purchasableBadge) {
builder.setBadgeDurationSeconds(purchasableBadge.getDuration().toSeconds());
}
return builder
.setBadge(BadgeGrpcHelper.toGrpcBadge(levelConfiguration.badge()))
.build();
}
}
@@ -129,7 +129,6 @@ public class ProfileAnonymousGrpcService extends SimpleProfileAnonymousGrpc.Prof
return targetAccount.map(account ->
GetUnversionedProfileAnonymousResponse.newBuilder()
.setResult(ProfileGrpcHelper.buildUnversionedProfileResult(targetIdentifier,
null,
account,
profileBadgeConverter))
.build())
@@ -142,7 +141,21 @@ public class ProfileAnonymousGrpcService extends SimpleProfileAnonymousGrpc.Prof
public GetVersionedProfileAnonymousResponse getVersionedProfile(final GetVersionedProfileAnonymousRequest request) {
final ServiceIdentifier targetIdentifier = GrpcServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getRequest().getAccountIdentifier());
final Optional<Account> targetAccount = getTargetAccountAndValidateUnidentifiedAccess(targetIdentifier, request.getUnidentifiedAccessKey().toByteArray());
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 GetVersionedProfileAnonymousResponse.newBuilder()
.setFailedUnidentifiedAuthorization(FailedUnidentifiedAuthorization.getDefaultInstance())
.build();
}
return targetAccount.flatMap(account ->
ProfileGrpcHelper.getVersionedProfile(account,
@@ -10,14 +10,11 @@ import com.google.protobuf.ByteString;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Clock;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HexFormat;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import java.util.UUID;
import org.signal.chat.common.Badge;
import org.signal.chat.common.BadgeSvg;
import org.signal.chat.common.S3UploadForm;
import org.signal.chat.profile.DataEtag;
import org.signal.chat.profile.GetExpiringProfileKeyCredentialResult;
@@ -33,6 +30,7 @@ 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.entities.Badge;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
import org.whispersystems.textsecuregcm.storage.Account;
@@ -129,23 +127,6 @@ public class ProfileGrpcHelper {
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())
@@ -155,20 +136,8 @@ public class ProfileGrpcHelper {
.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()
@@ -177,11 +146,13 @@ public class ProfileGrpcHelper {
switch (targetIdentifier.identityType()) {
case ACI -> {
resultBuilder.setUnrestrictedUnidentifiedAccess(targetAccount.isUnrestrictedUnidentifiedAccess())
.addAllBadges(
buildBadges(profileBadgeConverter.convert(RequestAttributesUtil.getAvailableAcceptedLocales(),
targetAccount.getBadges(),
ProfileHelper.isSelfProfileRequest(requesterUuid, targetIdentifier))));
final List<Locale> acceptedLocales = RequestAttributesUtil.getAvailableAcceptedLocales();
final List<Badge> badges =
profileBadgeConverter.convert(acceptedLocales, targetAccount.getBadges(), false);
resultBuilder
.setUnrestrictedUnidentifiedAccess(targetAccount.isUnrestrictedUnidentifiedAccess())
.addAllBadges(badges.stream().map(BadgeGrpcHelper::toGrpcBadge).toList());
targetAccount.getUnidentifiedAccessKey()
.map(UnidentifiedAccessChecksum::generateFor)
@@ -260,7 +260,6 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
return maybeAccount.map(account -> GetUnversionedProfileResponse.newBuilder()
.setResult(ProfileGrpcHelper.buildUnversionedProfileResult(targetIdentifier,
authenticatedDevice.accountIdentifier(),
account,
profileBadgeConverter))
.build()).orElseGet(() -> GetUnversionedProfileResponse.newBuilder()
@@ -5,13 +5,11 @@ import static org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil.getPayPalL
import com.google.protobuf.ByteString;
import com.google.protobuf.Empty;
import java.math.BigDecimal;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.time.Clock;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
@@ -19,46 +17,37 @@ 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.subscriptions.CreatePayPalPaymentMethodRequest;
import org.signal.chat.subscriptions.CreatePayPalPaymentMethodResponse;
import org.signal.chat.subscriptions.CreatePaymentMethodRequest;
import org.signal.chat.subscriptions.CreatePaymentMethodResponse;
import org.signal.chat.subscriptions.DeleteSubscriberRequest;
import org.signal.chat.subscriptions.DeleteSubscriberResponse;
import org.signal.chat.subscriptions.GetBankMandateRequest;
import org.signal.chat.subscriptions.GetBankMandateResponse;
import org.signal.chat.subscriptions.GetConfigurationRequest;
import org.signal.chat.subscriptions.GetConfigurationResponse;
import org.signal.chat.subscriptions.GetReceiptCredentialsRequest;
import org.signal.chat.subscriptions.GetReceiptCredentialsResponse;
import org.signal.chat.subscriptions.GetSubscriptionInformationRequest;
import org.signal.chat.subscriptions.GetSubscriptionInformationResponse;
import org.signal.chat.subscriptions.PaymentMethod;
import org.signal.chat.subscriptions.PaymentRequired;
import org.signal.chat.subscriptions.SetDefaultPaymentMethodRequest;
import org.signal.chat.subscriptions.SetDefaultPaymentMethodResponse;
import org.signal.chat.subscriptions.SetIapSubscriptionRequest;
import org.signal.chat.subscriptions.SetIapSubscriptionResponse;
import org.signal.chat.subscriptions.SetSubscriptionLevelRequest;
import org.signal.chat.subscriptions.SetSubscriptionLevelResponse;
import org.signal.chat.subscriptions.SimpleSubscriptionsGrpc;
import org.signal.chat.subscriptions.UpdateSubscriberRequest;
import org.signal.chat.subscriptions.UpdateSubscriberResponse;
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.badges.BadgeTranslator;
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration;
import org.whispersystems.textsecuregcm.configuration.SubscriptionConfiguration;
import org.whispersystems.textsecuregcm.configuration.SubscriptionLevelConfiguration;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
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.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.storage.SubscriberCredentials;
import org.whispersystems.textsecuregcm.storage.SubscriptionManager;
import org.whispersystems.textsecuregcm.storage.Subscriptions;
@@ -66,7 +55,6 @@ 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.CurrencyConfiguration;
import org.whispersystems.textsecuregcm.subscriptions.CustomerAwareSubscriptionPaymentProcessor;
import org.whispersystems.textsecuregcm.subscriptions.GooglePlayBillingManager;
import org.whispersystems.textsecuregcm.subscriptions.ProcessorCustomer;
@@ -91,41 +79,37 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
private final Clock clock;
private final SubscriptionConfiguration subscriptionConfiguration;
private final OneTimeDonationConfiguration oneTimeDonationConfiguration;
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 BadgeTranslator badgeTranslator;
private final BankMandateTranslator bankMandateTranslator;
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
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 OneTimeDonationConfiguration oneTimeDonationConfiguration, final SubscriptionManager subscriptionManager,
final DonationPermitsManager donationPermitsManager, final StripeManager stripeManager,
final BraintreeManager braintreeManager, final GooglePlayBillingManager googlePlayBillingManager,
final AppleAppStoreManager appleAppStoreManager, final BadgeTranslator badgeTranslator,
final BankMandateTranslator bankMandateTranslator,
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
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.oneTimeDonationConfiguration = oneTimeDonationConfiguration;
this.subscriptionManager = subscriptionManager;
this.donationPermitsManager = donationPermitsManager;
this.stripeManager = stripeManager;
this.braintreeManager = braintreeManager;
this.googlePlayBillingManager = googlePlayBillingManager;
this.appleAppStoreManager = appleAppStoreManager;
this.badgeTranslator = badgeTranslator;
this.bankMandateTranslator = bankMandateTranslator;
this.dynamicConfigurationManager = dynamicConfigurationManager;
}
@Override
@@ -234,7 +218,8 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
}
@Override
public CreatePayPalPaymentMethodResponse createPayPalPaymentMethod(final CreatePayPalPaymentMethodRequest request) {
public CreatePayPalPaymentMethodResponse createPayPalPaymentMethod(final CreatePayPalPaymentMethodRequest request)
throws IOException {
final SubscriberCredentials subscriberCredentials = SubscriberCredentials.process(
request.getSubscriberId().toByteArray(), clock);
final Locale locale = getPayPalLocale(RequestAttributesUtil.getAvailableAcceptedLocales());
@@ -242,7 +227,7 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
final BraintreeManager.PayPalBillingAgreementApprovalDetails details = subscriptionManager.addPaymentMethodToCustomer(
subscriberCredentials, braintreeManager, getClientPlatform(RequestAttributesUtil.getUserAgent().orElse(null)),
(mgr, _) -> mgr.createPayPalBillingAgreement(request.getReturnUrl(), request.getCancelUrl(),
locale.toLanguageTag())).join();
locale.toLanguageTag()));
return CreatePayPalPaymentMethodResponse.newBuilder().setResult(
CreatePayPalPaymentMethodResponse.CreatePayPalPaymentMethodResult.newBuilder()
.setApprovalUrl(details.approvalUrl()).setToken(details.billingAgreementToken()).build()).build();
@@ -259,27 +244,28 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
}
@Override
public SetDefaultPaymentMethodResponse setDefaultPaymentMethod(final SetDefaultPaymentMethodRequest request) {
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()).join();
}
default -> throw GrpcExceptions.fieldViolation("request", "No payment method specified");
};
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,
@@ -293,6 +279,10 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
} 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();
}
}
@@ -308,6 +298,8 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
return SetDefaultPaymentMethodResponse.newBuilder()
.setPaymentMethodNotSetUp(FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build())
.build();
} catch (final IOException e) {
throw new UncheckedIOException(e);
}
}
@@ -446,7 +438,7 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
.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(toProtoPaymentMethod(info.paymentMethod()))
.setProcessor(info.paymentProvider().toProto()).setPaymentMethod(info.paymentMethod().toProtoPaymentMethod())
.setPaymentProcessing(info.paymentProcessing());
if (info.billingCycleAnchor() != null) {
subscription.setBillingCycleAnchor(info.billingCycleAnchor().getEpochSecond());
@@ -503,99 +495,18 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
}
}
private static org.signal.chat.subscriptions.SubscriptionStatus toProtoSubscriptionStatus(
private static org.signal.chat.purchase.SubscriptionStatus toProtoSubscriptionStatus(
final SubscriptionStatus status) {
return switch (status) {
case ACTIVE -> org.signal.chat.subscriptions.SubscriptionStatus.SUBSCRIPTION_STATUS_ACTIVE;
case INCOMPLETE -> org.signal.chat.subscriptions.SubscriptionStatus.SUBSCRIPTION_STATUS_INCOMPLETE;
case PAST_DUE -> org.signal.chat.subscriptions.SubscriptionStatus.SUBSCRIPTION_STATUS_PAST_DUE;
case CANCELED -> org.signal.chat.subscriptions.SubscriptionStatus.SUBSCRIPTION_STATUS_CANCELED;
case UNPAID -> org.signal.chat.subscriptions.SubscriptionStatus.SUBSCRIPTION_STATUS_UNPAID;
case UNKNOWN -> org.signal.chat.subscriptions.SubscriptionStatus.SUBSCRIPTION_STATUS_UNKNOWN;
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;
};
}
private static PaymentMethod toProtoPaymentMethod(
final org.whispersystems.textsecuregcm.subscriptions.PaymentMethod paymentMethod) {
if (paymentMethod == null) {
return PaymentMethod.PAYMENT_METHOD_UNKNOWN;
}
return switch (paymentMethod) {
case CARD -> PaymentMethod.PAYMENT_METHOD_CARD;
case SEPA_DEBIT -> PaymentMethod.PAYMENT_METHOD_SEPA_DEBIT;
case IDEAL -> PaymentMethod.PAYMENT_METHOD_IDEAL;
case PAYPAL -> PaymentMethod.PAYMENT_METHOD_PAYPAL;
case GOOGLE_PLAY_BILLING -> PaymentMethod.PAYMENT_METHOD_GOOGLE_PLAY_BILLING;
case APPLE_APP_STORE -> PaymentMethod.PAYMENT_METHOD_APPLE_APP_STORE;
case UNKNOWN -> PaymentMethod.PAYMENT_METHOD_UNKNOWN;
};
}
@Override
public GetConfigurationResponse getConfiguration(final GetConfigurationRequest request) {
final long maxBackupBytes = dynamicConfigurationManager.getConfiguration().getBackupConfiguration()
.maxTotalMediaSize();
final Map<Long, GetConfigurationResponse.BackupLevelConfiguration> backupLevels = subscriptionConfiguration.getBackupLevels()
.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey,
e -> GetConfigurationResponse.BackupLevelConfiguration.newBuilder().setStorageAllowanceBytes(maxBackupBytes)
.setPlayProductId(e.getValue().playProductId()).setMediaTtlDays(e.getValue().mediaTtl().toDays())
.build()));
return GetConfigurationResponse.newBuilder().putAllCurrencies(buildCurrencyConfigurations())
.putAllLevels(buildLevelConfigurations()).setBackup(
GetConfigurationResponse.BackupConfiguration.newBuilder().putAllLevels(backupLevels)
.setFreeTierMediaDays(subscriptionConfiguration.getbackupFreeTierMediaDuration().toDays()).build())
.setSepaMaximumEuros(oneTimeDonationConfiguration.sepaMaximumEuros().toString()).build();
}
private Map<String, GetConfigurationResponse.CurrencyConfiguration> buildCurrencyConfigurations() {
return SubscriptionsUtil.buildCurrencyConfiguration(List.of(stripeManager, braintreeManager),
oneTimeDonationConfiguration, subscriptionConfiguration).entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey, e -> toProtoCurrencyConfiguration(e.getKey(), e.getValue())));
}
private Map<Long, GetConfigurationResponse.LevelConfiguration> buildLevelConfigurations() {
return SubscriptionsUtil.buildDonationLevelsConfiguration(subscriptionConfiguration, oneTimeDonationConfiguration,
badgeTranslator, RequestAttributesUtil.getAvailableAcceptedLocales()).entrySet().stream().collect(
Collectors.toMap(Map.Entry::getKey, entry -> GetConfigurationResponse.LevelConfiguration.newBuilder()
.setBadge(toProtoBadge(entry.getValue().badge())).build()));
}
private static GetConfigurationResponse.CurrencyConfiguration toProtoCurrencyConfiguration(final String currency,
final CurrencyConfiguration config) {
final GetConfigurationResponse.CurrencyConfiguration.Builder builder = GetConfigurationResponse.CurrencyConfiguration.newBuilder()
.setMinimum(config.minimum().toString())
.addAllSupportedPaymentMethods(
config.supportedPaymentMethods().stream().map(SubscriptionsGrpcService::toProtoPaymentMethod).toList());
config.oneTime().forEach((levelId, amounts) -> builder.putOneTime(levelId,
GetConfigurationResponse.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();
}
private static GetConfigurationResponse.Badge toProtoBadge(final Badge badge) {
final org.signal.chat.common.Badge commonBadge = org.signal.chat.common.Badge.newBuilder().setId(badge.getId())
.setCategory(badge.getCategory()).setName(badge.getName()).setDescription(badge.getDescription())
.addAllSprites6(badge.getSprites6()).setSvg(badge.getSvg()).addAllSvgs(badge.getSvgs().stream()
.map(s -> org.signal.chat.common.BadgeSvg.newBuilder().setLight(s.getLight()).setDark(s.getDark()).build())
.toList()).build();
final GetConfigurationResponse.Badge.Builder builder = GetConfigurationResponse.Badge.newBuilder()
.setBadge(commonBadge);
if (badge instanceof final PurchasableBadge purchasableBadge) {
builder.setDurationSeconds(purchasableBadge.getDuration().toSeconds());
}
return builder.build();
}
@Override
public GetBankMandateResponse getBankMandate(final GetBankMandateRequest request) {
final BankTransferType bankTransferType = switch (request.getBankTransferType()) {
@@ -162,9 +162,9 @@ public class SubscriptionsUtil {
.increment();
}
public static org.signal.chat.subscriptions.ChargeFailure toChargeFailure(final PaymentProvider processor,
public static org.signal.chat.purchase.ChargeFailure toChargeFailure(final PaymentProvider processor,
final ChargeFailure chargeFailure) {
final org.signal.chat.subscriptions.ChargeFailure.Builder builder = org.signal.chat.subscriptions.ChargeFailure.newBuilder()
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());
@@ -16,6 +16,7 @@ import io.micrometer.core.instrument.Tags;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.LongAdder;
import javax.annotation.Nullable;
import org.glassfish.jersey.server.ContainerResponse;
import org.glassfish.jersey.server.monitoring.RequestEvent;
@@ -44,6 +45,8 @@ public class MetricsRequestEventListener implements RequestEventListener {
public static final String RESPONSE_BYTES_COUNTER_NAME = name(MetricsRequestEventListener.class, "responseBytes");
public static final String REQUEST_BYTES_COUNTER_NAME = name(MetricsRequestEventListener.class, "requestBytes");
private static final String ACTIVE_REQUESTS_GAUGE_NAME = name(MetricsRequestEventListener.class, "activeRequests");
@VisibleForTesting
static final String PATH_TAG = "path";
@@ -65,6 +68,8 @@ public class MetricsRequestEventListener implements RequestEventListener {
private final TrafficSource trafficSource;
private final MeterRegistry meterRegistry;
private final LongAdder activeRequests;
public MetricsRequestEventListener(final TrafficSource trafficSource, final ClientReleaseManager clientReleaseManager) {
this(trafficSource, Metrics.globalRegistry, clientReleaseManager);
@@ -81,10 +86,20 @@ public class MetricsRequestEventListener implements RequestEventListener {
this.trafficSource = trafficSource;
this.meterRegistry = meterRegistry;
this.clientReleaseManager = clientReleaseManager;
this.activeRequests = meterRegistry.gauge(ACTIVE_REQUESTS_GAUGE_NAME, new LongAdder());
}
@Override
public void onEvent(final RequestEvent event) {
if (event.getType() == RequestEvent.Type.RESOURCE_METHOD_START) {
activeRequests.increment();
}
if (event.getType() == RequestEvent.Type.RESOURCE_METHOD_FINISHED) {
activeRequests.decrement();
}
if (event.getType() == RequestEvent.Type.FINISHED) {
if (!event.getUriInfo().getMatchedTemplates().isEmpty()) {
@Nullable final UserAgent userAgent;
@@ -114,7 +114,7 @@ public class AcknowledgementMirroringMessageStream implements MessageStream {
JdkFlowAdapter.flowPublisherToFlux(redisDynamoDbMessageStream.getMessages())
// Mirror demand and termination signals to the FoundationDB message stream
.doOnNext(subscriber::handleRedisDynamoDbMessageStreamEntry)
.doOnComplete(subscriber::dispose));
.doFinally(_ -> subscriber.dispose()));
}
@Override
@@ -38,7 +38,6 @@ import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager;
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStore;
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStream;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
import reactor.core.observability.micrometer.Micrometer;
import reactor.core.publisher.Flux;
@@ -62,12 +61,18 @@ public class MessagesManager {
private static final String PRESENCE_MATCH_COUNTER_NAME =
MetricsUtil.name(MessagesManager.class, "presenceMatch");
private static final Counter INSERT_TIMEOUT_COUNTER =
Metrics.counter(name(MessagesManager.class, "insertTimeout"));
@VisibleForTesting
static final String MIRROR_INSERTS_EXPERIMENT_NAME = "foundationDbMirrorInserts";
@VisibleForTesting
static final String MIRROR_DELETIONS_EXPERIMENT_NAME = "foundationDbMirrorDeletions";
@VisibleForTesting
static final String MIRROR_READS_EXPERIMENT_NAME = "foundationDbMirrorReads";
private static final long FOUNDATIONDB_INSERT_TIMEOUT_MILLIS = Duration.ofSeconds(2).toMillis();
private final MessagesDynamoDb messagesDynamoDb;
@@ -130,10 +135,14 @@ public class MessagesManager {
foundationDbMessageStore.insert(new AciServiceIdentifier(accountIdentifier), minimizedMessagesByDeviceId)
.orTimeout(FOUNDATIONDB_INSERT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)
.exceptionally(e -> {
logger.warn("Failed to insert {} message(s) for {} into FoundationDB",
minimizedMessagesByDeviceId.size(),
accountIdentifier,
e);
if (e instanceof TimeoutException) {
INSERT_TIMEOUT_COUNTER.increment();
} else {
logger.warn("Failed to insert {} message(s) for {} into FoundationDB",
minimizedMessagesByDeviceId.size(),
accountIdentifier,
e);
}
return Collections.emptyMap();
});
@@ -284,11 +293,12 @@ public class MessagesManager {
new RedisDynamoDbMessageStream(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager,
destinationUuid, destinationDevice);
return experimentEnrollmentManager.isEnrolled(destinationUuid, MIRROR_DELETIONS_EXPERIMENT_NAME)
? new AcknowledgementMirroringMessageStream(
return new MirroringMessageStream(
redisDynamoDbMessageStream,
foundationDbMessageStore.getMessages(new AciServiceIdentifier(destinationUuid), destinationDevice.getId()))
: redisDynamoDbMessageStream;
foundationDbMessageStore.getMessages(new AciServiceIdentifier(destinationUuid), destinationDevice.getId()),
experimentEnrollmentManager,
destinationUuid,
destinationDevice.getId());
}
Publisher<Envelope> getMessagesForDevice(final UUID destinationUuid, final Device destinationDevice) {
@@ -387,4 +397,29 @@ public class MessagesManager {
final SealedSenderMultiRecipientMessage sealedSenderMultiRecipientMessage) {
return messagesCache.insertSharedMultiRecipientMessagePayload(sealedSenderMultiRecipientMessage);
}
/// Record versionstamps for the current time in the FoundationDB database(s).
public void recordFoundationDbVersionstamps() {
foundationDbMessageStore.recordVersionstamps();
}
/// Clean up expired entries in the FoundationDB versionstamp clock.
///
/// @param oldestRetainedEntryTimestamp the earliest time for which we still want to be able to obtain a versionstamp
public void expireOldFoundationDbVersionstamps(final Instant oldestRetainedEntryTimestamp) {
foundationDbMessageStore.expireOldVersionstamps(oldestRetainedEntryTimestamp);
}
/// Delete messages in FoundationDB for the given devices that were inserted before the given
/// time. (Expiration of messages from Redis and Dynamo is handled automatically and do not
/// require any interaction with this class.)
///
/// @param accountDeviceIdentifiers a map from ACI to the list of device IDs for which expired messages should be
/// trimmed.
///
/// @param cutoffTime the expiration threshold. Messages inserted before this time may be deleted; messages inserted
/// after it will not be.
public void deleteFoundationDbMessagesBefore(final Map<AciServiceIdentifier, List<Byte>> accountDeviceIdentifiers, final Instant cutoffTime) {
foundationDbMessageStore.deleteMessagesBefore(accountDeviceIdentifiers, cutoffTime);
}
}
@@ -0,0 +1,84 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Flow;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStream;
import reactor.adapter.JdkFlowAdapter;
import reactor.core.Disposable;
/// A temporary message stream that can mirror message acknowledgements (deletion requests) to FoundationDB
public class MirroringMessageStream implements MessageStream {
private final RedisDynamoDbMessageStream redisDynamoDbMessageStream;
private final FoundationDbMessageStream foundationDbMessageStream;
private final ExperimentEnrollmentManager experimentEnrollmentManager;
private final AciServiceIdentifier accountIdentifier;
private final byte deviceId;
private static final Logger logger = LoggerFactory.getLogger(MirroringMessageStream.class);
public MirroringMessageStream(final RedisDynamoDbMessageStream redisDynamoDbMessageStream,
final FoundationDbMessageStream foundationDbMessageStream,
final ExperimentEnrollmentManager experimentEnrollmentManager,
final UUID accountIdentifier,
final byte deviceId) {
this.redisDynamoDbMessageStream = redisDynamoDbMessageStream;
this.foundationDbMessageStream = foundationDbMessageStream;
this.experimentEnrollmentManager = experimentEnrollmentManager;
this.accountIdentifier = new AciServiceIdentifier(accountIdentifier);
this.deviceId = deviceId;
}
@Override
public Flow.Publisher<MessageStreamEntry> getMessages() {
if (experimentEnrollmentManager.isEnrolled(accountIdentifier.uuid(), MessagesManager.MIRROR_READS_EXPERIMENT_NAME)) {
final Disposable foundationDbDisposable =
foundationDbMessageStream.getFiniteMessageStream()
.limitRate(100)
.subscribe();
return JdkFlowAdapter.publisherToFlowPublisher(
JdkFlowAdapter.flowPublisherToFlux(redisDynamoDbMessageStream.getMessages())
.doFinally(_ -> {
try {
foundationDbDisposable.dispose();
} catch (final Exception _) {
}
}));
}
return redisDynamoDbMessageStream.getMessages();
}
@Override
public CompletableFuture<Void> acknowledgeMessage(final UUID messageGuid, final long serverTimestamp) {
// All messages stored in FoundationDB use version 8 UUIDs; if a message has a version 4 UUID, then it only exists
// in Redis/DynamoDB
if (messageGuid.version() == 8 &&
experimentEnrollmentManager.isEnrolled(accountIdentifier.uuid(), MessagesManager.MIRROR_DELETIONS_EXPERIMENT_NAME)) {
foundationDbMessageStream.acknowledgeMessage(messageGuid, serverTimestamp)
.whenComplete((_, throwable) -> {
if (throwable != null) {
logger.warn("Failed to delete message {}/{}/{} from FoundationDb", accountIdentifier.uuid(), deviceId,
messageGuid, throwable);
}
});
}
return redisDynamoDbMessageStream.acknowledgeMessage(messageGuid, serverTimestamp);
}
}
@@ -41,6 +41,7 @@ import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorConfl
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptAlreadyRedeemedException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptRequestedForOpenPaymentException;
import org.whispersystems.textsecuregcm.util.ThrowingBiFunction;
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
/**
@@ -244,6 +245,7 @@ public class SubscriptionManager {
* @param <T> A payment processor that has a notion of server-managed customers
* @param <R> The return type of the paymentSetupFunction, which should be used by a client
* to configure the newly created payment method
* @param <E> An exception thrown by the paymentSetupFunction
* @return The return value of the paymentSetupFunction
* @throws SubscriptionForbiddenException if the subscriber credentials were incorrect
* @throws SubscriptionNotFoundException if the subscriber did not exist or did not have a subscription
@@ -251,12 +253,12 @@ public class SubscriptionManager {
* @throws SubscriptionProcessorConflictException if the new payment processor does not match the existing processor associated with
* the subscriberId
*/
public <T extends CustomerAwareSubscriptionPaymentProcessor, R> R addPaymentMethodToCustomer(
public <T extends CustomerAwareSubscriptionPaymentProcessor, R, E extends Exception> R addPaymentMethodToCustomer(
final SubscriberCredentials subscriberCredentials,
final T subscriptionPaymentProcessor,
final ClientPlatform clientPlatform,
final BiFunction<T, String, R> paymentSetupFunction)
throws SubscriptionForbiddenException, SubscriptionNotFoundException, SubscriptionProcessorConflictException {
final ThrowingBiFunction<T, String, R, E> paymentSetupFunction)
throws SubscriptionForbiddenException, SubscriptionNotFoundException, SubscriptionProcessorConflictException, E {
Subscriptions.Record record = this.getSubscriber(subscriberCredentials);
if (record.getProcessorCustomer().isEmpty()) {
@@ -1,113 +0,0 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage.foundationdb;
import com.apple.foundationdb.tuple.Versionstamp;
import com.google.common.annotations.VisibleForTesting;
import org.whispersystems.textsecuregcm.util.Pair;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.NavigableMap;
import java.util.TreeMap;
/// An acknowledged message buffer keeps track of messages that have been sent, whether they have been acknowledged by
/// the recipient, and whether those acknowledgements have been flushed to the underlying data store. It also batches
/// acknowledgements into contiguous ranges in the interest of efficiency.
class AcknowledgedMessageBuffer {
/// The maximum number of unacknowledged messages we will send before closing the stream with an error
private final int maxUnacknowledgedMessages;
/// Map of versionstamp -> acknowledged? to keep track of acknowledged versionstamp ranges to clear
private final NavigableMap<Versionstamp, Boolean> sentVersionstamps = new TreeMap<>();
private int unacknowledgedMessages = 0;
AcknowledgedMessageBuffer(final int maxUnacknowledgedMessages) {
this.maxUnacknowledgedMessages = maxUnacknowledgedMessages;
}
public synchronized void addUnacknowledgedMessage(final Versionstamp versionstamp) throws TooManyUnacknowledgedMessagesException {
if (++unacknowledgedMessages > maxUnacknowledgedMessages) {
throw new TooManyUnacknowledgedMessagesException();
}
sentVersionstamps.put(versionstamp, false);
}
public synchronized void acknowledgeMessage(final Versionstamp versionstamp) {
// If we don't know about this versionstamp, or it's already acknowledged, there's nothing to do
if (!sentVersionstamps.containsKey(versionstamp) || sentVersionstamps.get(versionstamp)) {
return;
}
unacknowledgedMessages--;
sentVersionstamps.put(versionstamp, true);
}
@VisibleForTesting
int getUnacknowledgedMessageCount() {
return unacknowledgedMessages;
}
/// Computes a list of acknowledged contiguous versionstamp ranges that can be cleared from the database and removes
/// them from ths unacknowledged mesage buffer.
///
/// @return a list of acknowledged contiguous versionstamp ranges that can be cleared from the database.
public synchronized List<Pair<Versionstamp, Versionstamp>> takeFlushableRanges() {
final List<Pair<Versionstamp, Versionstamp>> flushableRanges = computeFlushableRanges();
flushableRanges.forEach(range -> sentVersionstamps.subMap(range.first(), true, range.second(), true).clear());
return flushableRanges;
}
/// Computes a list of acknowledged contiguous versionstamp ranges that can be cleared from the database.
///
/// @return a list of acknowledged contiguous versionstamp ranges that can be cleared from the database.
@VisibleForTesting
synchronized List<Pair<Versionstamp, Versionstamp>> computeFlushableRanges() {
final List<Pair<Versionstamp, Versionstamp>> flushableRanges = new ArrayList<>();
Versionstamp startInclusive = null;
Versionstamp endInclusive = null;
for (final Map.Entry<Versionstamp, Boolean> entry : sentVersionstamps.entrySet()) {
if (entry.getValue()) {
// Message is acknowledged, so we can either start tracking a new range if we aren't already, or extend our
// current range
if (startInclusive == null) {
startInclusive = entry.getKey();
}
endInclusive = entry.getKey();
} else {
// Message is un-acknowledged, which means either it is a "range-breaker" or we never started tracking an
// acknowledged range. Mark the currently tracked range flushable, if it exists.
if (startInclusive != null) {
assert endInclusive != null;
flushableRanges.add(new Pair<>(startInclusive, endInclusive));
startInclusive = null;
}
}
}
if (startInclusive != null) {
assert endInclusive != null;
flushableRanges.add(new Pair<>(startInclusive, endInclusive));
}
return flushableRanges;
}
/// Acknowledges a stale ephemeral message for cleanup from FoundationDB.
/// Ephemeral messages are only delivered when the recipient has an active message stream, so any ephemeral message
/// read from the finite publisher is stale by definition and can be immediately acknowledged and discarded.
///
/// @param versionstamp The versionstamp to acknowledge
public synchronized void acknowledgeStaleEphemeralMessage(final Versionstamp versionstamp) {
sentVersionstamps.put(versionstamp, true);
}
}
@@ -10,9 +10,9 @@ import com.google.protobuf.InvalidProtocolBufferException;
import java.io.UncheckedIOException;
import java.time.Clock;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
@@ -20,15 +20,13 @@ import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Supplier;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.util.Pair;
import reactor.core.publisher.Flux;
import reactor.core.publisher.FluxSink;
import reactor.core.publisher.Mono;
/// Publishes a message stream from a device queue in FoundationDB. Capable of publishing both a finite stream for
/// catching up to end-of-queue,and an infinite stream for live updates.
@@ -60,10 +58,6 @@ class FoundationDbMessagePublisher {
/// Listener to watch for state machine transitions; used for testing.
private final BiConsumer<State, State> stateChangeListener;
/// A supplier that returns a function to execute before we begin fetching a page; it is passed the transaction that
/// is started for the page fetch operations.
private final Supplier<Consumer<Transaction>> beforePageFetch;
/// Whether the publisher is finite or infinite.
private final boolean terminateOnQueueEmpty;
@@ -131,8 +125,7 @@ class FoundationDbMessagePublisher {
@Nullable final byte[] presenceKey,
@Nullable final ScheduledExecutorService presenceRenewalExecutorService,
@Nullable final byte[] messagesAvailableWatchKey,
@Nullable final BiConsumer<State, State> stateChangeListener,
final Supplier<Consumer<Transaction>> beforePageFetch) {
@Nullable final BiConsumer<State, State> stateChangeListener) {
this.database = database;
this.clock = clock;
@@ -143,37 +136,37 @@ class FoundationDbMessagePublisher {
this.messagesAvailableWatchKey = messagesAvailableWatchKey;
this.terminateOnQueueEmpty = messagesAvailableWatchKey == null;
this.stateChangeListener = stateChangeListener != null ? stateChangeListener : (_, _) -> {};
this.beforePageFetch = beforePageFetch;
if (!terminateOnQueueEmpty) {
Objects.requireNonNull(presenceKey);
Objects.requireNonNull(presenceRenewalExecutorService);
}
this.messagePublisher = Flux.<FoundationDbMessageStreamEntry.Message>create(emitter -> {
this.emitter = emitter;
emitter.onRequest(n -> {
final long totalRequestedCount = totalRequested.addAndGet(n);
if (totalRequestedCount > totalEmitted.get()) {
transitionStateOnEvent(Event.DEMAND_REQUESTED);
}
});
emitter.onDispose(this::onDispose);
}).doOnSubscribe(_ -> {
if (!terminateOnQueueEmpty) {
// Establish presence immediately and block until we do. We must establish presence for watches to work as
// expected. If we fail to establish presence, then this non-terminating stream will never learn about new
// messages. If establishing presence throws an exception, then the whole publisher will terminate with that
// exception.
database.run(transaction -> {
setPresence(transaction);
return null;
});
// Refresh presence at regular intervals
startPresenceRenewal(presenceRenewalExecutorService);
}
});
this.messagePublisher = Mono.fromFuture(() -> {
if (!terminateOnQueueEmpty) {
// Establish presence before attempting to fetch messages. We must establish presence for watches to work as
// expected. If we fail to establish presence, then this non-terminating stream will never learn about new
// messages. If establishing presence throws an exception, then the whole publisher will terminate with that
// exception.
return database.runAsync(transaction -> {
setPresence(transaction);
return CompletableFuture.completedFuture(null);
})
.thenRun(() -> startPresenceRenewal(presenceRenewalExecutorService));
} else {
return CompletableFuture.completedFuture(null);
}
})
.thenMany(Flux.create(emitter -> {
this.emitter = emitter;
emitter.onRequest(n -> {
final long totalRequestedCount = totalRequested.addAndGet(n);
if (totalRequestedCount > totalEmitted.get()) {
transitionStateOnEvent(Event.DEMAND_REQUESTED);
}
});
emitter.onDispose(this::onDispose);
}));
}
/// Creates a [FoundationDbMessagePublisher] that publishes a stream of messages in a queue that terminates when it
@@ -185,8 +178,7 @@ class FoundationDbMessagePublisher {
final Clock clock,
final KeySelector beginKeyInclusive,
final KeySelector endKeyExclusive,
final int maxMessagesPerScan,
final Supplier<Consumer<Transaction>> beforePageFetch) {
final int maxMessagesPerScan) {
return new FoundationDbMessagePublisher(database,
clock,
@@ -196,8 +188,7 @@ class FoundationDbMessagePublisher {
null,
null,
null,
null,
beforePageFetch);
null);
}
/// Creates a [FoundationDbMessagePublisher] that publishes a non-terminating stream of messages from a device queue.
@@ -211,8 +202,7 @@ class FoundationDbMessagePublisher {
final int maxMessagesPerScan,
final byte[] presenceKey,
final ScheduledExecutorService presenceRenewalExecutorService,
final byte[] messagesAvailableWatchKey,
final Supplier<Consumer<Transaction>> beforePageFetch) {
final byte[] messagesAvailableWatchKey) {
return new FoundationDbMessagePublisher(database,
clock,
@@ -222,8 +212,7 @@ class FoundationDbMessagePublisher {
presenceKey,
presenceRenewalExecutorService,
messagesAvailableWatchKey,
null,
beforePageFetch);
null);
}
private synchronized void setState(final State newState, final Event event) {
@@ -312,70 +301,43 @@ class FoundationDbMessagePublisher {
/// Fetch messages using a range query limiting batch size to [#maxMessagesPerScan]. If the query returns fewer than
/// [#maxMessagesPerScan], emit [Event#FETCHED_ALL_AVAILABLE_MESSAGES]. In the case of an infinite publisher, also set
/// a watch for new messages. Execute the function supplied by [#beforePageFetch] in the context of the transaction.
/// Additionally, the cursor is updated so that we begin fetching from the right key on
/// subsequent scans
/// a watch for new messages. Additionally, the cursor is updated so that we begin fetching from the right key on
/// subsequent scans.
///
/// @return a future of a list of [FoundationDbMessageStreamEntry.Message] with a max size of [#maxMessagesPerScan]
private CompletableFuture<List<FoundationDbMessageStreamEntry.Message>> getMessagesBatch() {
final Consumer<Transaction> doBeforePageFetch = beforePageFetch.get();
return database.runAsync(transaction ->
transaction.getRange(beginKeyCursor, endKeyExclusive, maxMessagesPerScan, false, StreamingMode.EXACT).asList()
.thenApply(keyValues -> {
if (keyValues.size() < maxMessagesPerScan && !terminateOnQueueEmpty) {
setWatch(transaction);
}
return database.runAsync(transaction -> {
doBeforePageFetch.accept(transaction);
return getItemsInRange(transaction, beginKeyCursor, endKeyExclusive, maxMessagesPerScan)
.thenApply(lastKeyReadAndItems -> {
if (lastKeyReadAndItems.second().size() < maxMessagesPerScan && !terminateOnQueueEmpty) {
setWatch(transaction);
}
return lastKeyReadAndItems;
});
})
// Defer any state mutations until after the transaction has been committed. The transaction block can
// fail/retry, and we don't want to trigger spurious state transitions when that happens.
.thenApply(lastKeyReadAndItems -> {
// Set our beginning key to just past the last key read so that we're ready for our next fetch
lastKeyReadAndItems.first()
.ifPresent(lastKeyRead -> beginKeyCursor = KeySelector.firstGreaterThan(lastKeyRead));
if (lastKeyReadAndItems.second().size() < maxMessagesPerScan) {
return keyValues;
}))
.thenApply(keyValues -> {
if (keyValues.size() < maxMessagesPerScan) {
transitionStateOnEvent(Event.FETCHED_ALL_AVAILABLE_MESSAGES);
}
return lastKeyReadAndItems.second();
});
}
if (keyValues.isEmpty()) {
return Collections.emptyList();
}
/// Fetch messages in the range between `begin` and `end` limited to a batch size of `maxMessagesPerSccan`
///
/// @param transaction the FoundationDB transaction in which to perform the read query
/// @param beginInclusive the range start key (inclusive)
/// @param endExclusive the range end key (exclusive)
/// @param maxMessagesPerScan maximum number of messages to return in the fetch query
/// @return the last key read (if there were non-zero number of messages read) and the list of messages read
private CompletableFuture<Pair<Optional<byte[]>, List<FoundationDbMessageStreamEntry.Message>>> getItemsInRange(
final Transaction transaction,
final KeySelector beginInclusive,
final KeySelector endExclusive,
final int maxMessagesPerScan) {
return transaction.getRange(beginInclusive, endExclusive, maxMessagesPerScan, false, StreamingMode.EXACT).asList()
.thenApply(keyValues -> {
final Optional<byte[]> lastKeyRead = keyValues.isEmpty()
? Optional.empty()
: Optional.of(keyValues.getLast().getKey());
final List<FoundationDbMessageStreamEntry.Message> messages = keyValues.stream()
beginKeyCursor = KeySelector.firstGreaterThan(keyValues.getLast().getKey());
return keyValues.stream()
.map(keyValue -> {
final Versionstamp versionstamp = FoundationDbMessageStore.getVersionstamp(keyValue.getKey());
try {
return new FoundationDbMessageStreamEntry.Message(versionstamp, MessageProtos.Envelope.parseFrom(keyValue.getValue()));
return new FoundationDbMessageStreamEntry.Message(versionstamp,
MessageProtos.Envelope.parseFrom(keyValue.getValue()));
} catch (final InvalidProtocolBufferException e) {
throw new UncheckedIOException(e);
}
})
.toList();
return new Pair<>(lastKeyRead, messages);
});
}
@@ -463,6 +425,10 @@ class FoundationDbMessagePublisher {
if (!terminateOnQueueEmpty) {
database.runAsync(transaction -> transaction.get(presenceKey).thenAccept(presenceValue -> {
if (presenceValue == null) {
return;
}
final byte[] presenceServerId = FoundationDbMessageStore.getPresenceServerId(presenceValue);
final int presenceStreamId = FoundationDbMessageStore.getPresenceStreamId(presenceValue);
@@ -84,6 +84,12 @@ public class FoundationDbMessageStore {
private static final Timer INSERT_MESSAGE_BATCH_TIMER =
Metrics.timer(MetricsUtil.name(FoundationDbMessageStore.class, "insertMessageBatchTimer"));
private static final Counter DELETE_MESSAGE_COUNTER =
Metrics.counter(MetricsUtil.name(FoundationDbMessageStore.class, "deleteMessage"));
private static final Timer DELETE_MESSAGE_TIMER =
Metrics.timer(MetricsUtil.name(FoundationDbMessageStore.class, "deleteMessageTimer"));
/// Result of inserting a message for a particular device
///
/// @param versionstamp the versionstamp of the transaction in which this device's message was inserted, empty
@@ -343,6 +349,25 @@ public class FoundationDbMessageStore {
});
}
CompletableFuture<Void> delete(final AciServiceIdentifier aci, final byte deviceId, final UUID messageGuid) {
return delete(aci, deviceId, versionstampUUIDCipher.decryptVersionstamp(messageGuid, aci.uuid(), deviceId));
}
CompletableFuture<Void> delete(final AciServiceIdentifier aci, final byte deviceId, final Versionstamp versionstamp) {
final Timer.Sample sample = Timer.start();
final byte[] messageKey = getDeviceQueueSubspace(aci, deviceId).pack(Tuple.from(versionstamp));
return databasesByEpoch[getConfigurationEpoch(versionstamp)][getShardId(versionstamp)].runAsync(transaction -> {
transaction.clear(messageKey);
return CompletableFuture.completedFuture(null);
})
.thenRun(() -> {
sample.stop(DELETE_MESSAGE_TIMER);
DELETE_MESSAGE_COUNTER.increment();
});
}
public void clearAll(final AciServiceIdentifier aci) {
doForAllDatabasesWithMessages(aci, database -> database.run(transaction -> {
transaction.clear(getAccountSubspace(aci).range());
@@ -366,15 +391,13 @@ public class FoundationDbMessageStore {
}
public FoundationDbMessageStream getMessages(final AciServiceIdentifier aci, final byte deviceId) {
return getMessages(aci, deviceId, FoundationDbMessageStream.DEFAULT_MAX_MESSAGES_PER_SCAN,
FoundationDbMessageStream.DEFAULT_MAX_UNACKNOWLEDGED_MESSAGES, Util.NOOP);
return getMessages(aci, deviceId, FoundationDbMessageStream.DEFAULT_MAX_MESSAGES_PER_SCAN, Util.NOOP);
}
@VisibleForTesting
FoundationDbMessageStream getMessages(final AciServiceIdentifier aci,
final byte deviceId,
final int maxMessagesPerScan,
final int maxUnacknowledgedMessages,
final Runnable doAfterCleanup) {
// For each configured database epoch, which database held (or holds) the messages for this ACI/device pair?
@@ -384,13 +407,12 @@ public class FoundationDbMessageStore {
databasesForQueueByEpoch[epoch] = getShardForAci(aci, epoch);
}
return new FoundationDbMessageStream(getDeviceQueueSubspace(aci, deviceId),
getPresenceKey(aci, deviceId),
getMessagesAvailableWatchKey(aci),
return new FoundationDbMessageStream(this,
aci,
deviceId,
databasesForQueueByEpoch,
new MessageGuidCodec(aci.uuid(), deviceId, versionstampUUIDCipher),
maxMessagesPerScan,
maxUnacknowledgedMessages,
doAfterCleanup,
presenceRenewalExecutorService,
clock);
@@ -403,6 +425,15 @@ public class FoundationDbMessageStore {
}
}
/// Remove any entries from each database's versionstamp-clock namespace that are strictly older than the given timestamp.
///
/// @param oldestRetainedEntryTimestamp the earliest time for which we still want to be able to obtain a versionstamp
public void expireOldVersionstamps(final Instant oldestRetainedEntryTimestamp) {
for (VersionstampClock versionstampClock : versionstampClocks.values()) {
versionstampClock.clearExpiredEntries(oldestRetainedEntryTimestamp);
}
}
/// Delete messages for the given devices that were inserted before the given time.
///
/// This issues one range delete for every account/device pair in the map for each actual underlying FoundationDB
@@ -420,7 +451,6 @@ public class FoundationDbMessageStore {
/// @param cutoffTime the expiration threshold. Messages inserted before this time may be deleted; messages inserted
/// after it will not be. Deletion depends on the underlying [versionstamp clocks][VersionstampClock] being kept up to
/// date.
@VisibleForTesting
public void deleteMessagesBefore(final Map<AciServiceIdentifier, List<Byte>> accountDeviceIdentifiers, final Instant cutoffTime) {
final Map<Database, List<Subspace>> queueSubspacesToTrimByDatabase = new IdentityHashMap<>();
@@ -5,33 +5,23 @@ import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import com.apple.foundationdb.Database;
import com.apple.foundationdb.KeySelector;
import com.apple.foundationdb.StreamingMode;
import com.apple.foundationdb.Transaction;
import com.apple.foundationdb.subspace.Subspace;
import com.apple.foundationdb.tuple.ByteArrayUtil;
import com.apple.foundationdb.tuple.Tuple;
import com.apple.foundationdb.tuple.Versionstamp;
import com.google.common.annotations.VisibleForTesting;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Metrics;
import java.time.Clock;
import java.util.Arrays;
import java.util.Comparator;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Flow;
import java.util.concurrent.ScheduledExecutorService;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.storage.MessageStream;
import org.whispersystems.textsecuregcm.storage.MessageStreamEntry;
import org.whispersystems.textsecuregcm.util.Pair;
import reactor.adapter.JdkFlowAdapter;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@@ -42,6 +32,10 @@ import reactor.util.function.Tuples;
/// A [MessageStream] implementation that fetches messages from FoundationDB
public class FoundationDbMessageStream implements MessageStream {
private final FoundationDbMessageStore foundationDbMessageStore;
private final AciServiceIdentifier aciServiceIdentifier;
private final byte deviceId;
private final Subspace deviceQueueSubspace;
private final byte[] presenceKey;
private final byte[] messagesAvailableWatchKey;
@@ -54,8 +48,6 @@ public class FoundationDbMessageStream implements MessageStream {
private final ScheduledExecutorService presenceRenewalExecutorService;
private final Clock clock;
private final Map<Database, AcknowledgedMessageBuffer> acknowledgedMessageBuffersByDatabase;
private final Counter messageReadCounter =
Metrics.counter(name(FoundationDbMessageStream.class, "messagesRead"));
@@ -66,27 +58,25 @@ public class FoundationDbMessageStream implements MessageStream {
Metrics.counter(name(FoundationDbMessageStream.class, "staleEphemeralMessages"));
static final int DEFAULT_MAX_MESSAGES_PER_SCAN = 100;
@VisibleForTesting
static final int DEFAULT_MAX_UNACKNOWLEDGED_MESSAGES = 16_384;
private static final Comparator<FoundationDbMessageStreamEntry.Message> STREAM_ENTRY_TIMESTAMP_COMPARATOR =
Comparator.comparingLong(streamEntry -> streamEntry.partialEnvelope().getServerTimestamp());
private static final Logger LOGGER = LoggerFactory.getLogger(FoundationDbMessageStream.class);
FoundationDbMessageStream(final Subspace deviceQueueSubspace,
final byte[] presenceKey,
final byte[] messagesAvailableWatchKey,
FoundationDbMessageStream(final FoundationDbMessageStore foundationDbMessageStore,
final AciServiceIdentifier aciServiceIdentifier,
final byte deviceId,
final Database[] databasesByEpoch,
final MessageGuidCodec messageGuidCodec,
final int maxMessagesPerScan,
final int maxUnacknowledgedMessages,
final Runnable doAfterCleanup,
final ScheduledExecutorService presenceRenewalExecutorService,
final Clock clock) {
this.deviceQueueSubspace = deviceQueueSubspace;
this.presenceKey = presenceKey;
this.messagesAvailableWatchKey = messagesAvailableWatchKey;
this.foundationDbMessageStore = foundationDbMessageStore;
this.aciServiceIdentifier = aciServiceIdentifier;
this.deviceId = deviceId;
this.deviceQueueSubspace = FoundationDbMessageStore.getDeviceQueueSubspace(aciServiceIdentifier, deviceId);
this.presenceKey = FoundationDbMessageStore.getPresenceKey(aciServiceIdentifier, deviceId);
this.messagesAvailableWatchKey = FoundationDbMessageStore.getMessagesAvailableWatchKey(aciServiceIdentifier);
this.databasesByEpoch = databasesByEpoch;
this.messageGuidCodec = messageGuidCodec;
this.maxMessagesPerScan = maxMessagesPerScan;
@@ -94,19 +84,6 @@ public class FoundationDbMessageStream implements MessageStream {
this.doAfterCleanup = doAfterCleanup;
this.presenceRenewalExecutorService = presenceRenewalExecutorService;
this.clock = clock;
// Not all epochs may be in use (this is true most of the time) and if we DO have multiple epochs in play, it's
// possible/likely that a given queue will be on the same shard in multiple epochs. We only want acknowledgement
// buffer per distinct shard, so find the distinct shards for this queue and create a buffer for each.
this.acknowledgedMessageBuffersByDatabase = Arrays.stream(databasesByEpoch)
.filter(Objects::nonNull)
.distinct()
.collect(Collectors.toMap(database -> database,
_ -> new AcknowledgedMessageBuffer(maxUnacknowledgedMessages),
(_, _) -> {
throw new AssertionError("Duplicate database in distinct stream");
},
IdentityHashMap::new));
}
@Override
@@ -114,6 +91,42 @@ public class FoundationDbMessageStream implements MessageStream {
return this.messageStreamPublisher;
}
public Flux<MessageStreamEntry> getFiniteMessageStream() {
// This may seem like an odd construction since it looks like we could also just do `Flux#fromArray`, but
// `Flux#fromArray` cannot handle `null` elements
final List<Database> databases = Arrays.stream(databasesByEpoch).filter(Objects::nonNull).distinct().toList();
return Flux.fromIterable(databases)
.flatMap(database -> Mono.fromFuture(getEndOfQueueKeyExclusive(database))
.map(maybeEndOfQueueKeyExclusive -> Tuples.of(database, maybeEndOfQueueKeyExclusive)))
.collectMap(Tuple2::getT1, Tuple2::getT2)
.flatMapMany(endOfQueueKeysByDatabase -> {
@SuppressWarnings("unchecked") final Flux<FoundationDbMessageStreamEntry.Message>[] finitePublishers =
endOfQueueKeysByDatabase.entrySet().stream()
.map(entry -> {
final Database database = entry.getKey();
final Optional<KeySelector> maybeEndOfQueueKeyExclusive = entry.getValue();
return maybeEndOfQueueKeyExclusive
.map(endOfQueueKeyExclusive -> FoundationDbMessagePublisher.createFinitePublisher(
database,
clock,
KeySelector.firstGreaterOrEqual(deviceQueueSubspace.range().begin),
endOfQueueKeyExclusive,
maxMessagesPerScan)
.getMessages())
.orElseGet(Flux::empty);
})
.toArray(Flux[]::new);
return Flux.concat(
Flux.mergeComparing(maxMessagesPerScan, STREAM_ENTRY_TIMESTAMP_COMPARATOR, finitePublishers)
.doOnNext(_ -> messageReadCounter.increment()),
Mono.just(new FoundationDbMessageStreamEntry.QueueEmpty()))
.map(fdbMessageStreamEntry -> fdbMessageStreamEntry.toMessageStreamEntry(messageGuidCodec));
});
}
/// Create a message publisher
///
/// @return a Flux of {@link MessageStreamEntry} fetched from FoundationDB
@@ -121,25 +134,13 @@ public class FoundationDbMessageStream implements MessageStream {
/// first to keep track of versionstamps sent to the client.
private Flux<MessageStreamEntry> createMessagePublisher() {
return createFoundationDbMessagePublisher()
.<FoundationDbMessageStreamEntry>handle((messageStreamEntry, sink) -> {
if (messageStreamEntry instanceof final FoundationDbMessageStreamEntry.Message message) {
try {
getAcknowledgedMessageBuffer(message.versionstamp()).addUnacknowledgedMessage(message.versionstamp());
} catch (final TooManyUnacknowledgedMessagesException e) {
sink.error(e);
return;
}
}
sink.next(messageStreamEntry);
})
.map(fdbMessageStreamEntry -> fdbMessageStreamEntry.toMessageStreamEntry(messageGuidCodec))
.doOnNext(messageStreamEntry -> {
if (messageStreamEntry instanceof MessageStreamEntry.Envelope) {
messageReadCounter.increment();
}
})
.doFinally(_ -> flushAllAcknowledgedMessages().thenRun(doAfterCleanup));
.doFinally(_ -> doAfterCleanup.run());
}
/// Create a message publisher that fetches messages from FoundationDB
@@ -176,14 +177,16 @@ public class FoundationDbMessageStream implements MessageStream {
clock,
KeySelector.firstGreaterOrEqual(deviceQueueSubspace.range().begin),
endOfQueueKeyExclusive,
maxMessagesPerScan,
() -> this.clearAcknowledgedMessages(database))
maxMessagesPerScan)
.getMessages())
.orElseGet(Flux::empty)
.handle((fdbMessageStreamEntry, sink) -> {
final MessageProtos.Envelope partialEnvelope = fdbMessageStreamEntry.partialEnvelope();
// Ephemeral messages from the finite stream are considered stale and automatically discarded
if (fdbMessageStreamEntry.partialEnvelope().getEphemeral()) {
acknowledgedMessageBuffersByDatabase.get(database).acknowledgeStaleEphemeralMessage(fdbMessageStreamEntry.versionstamp());
if (partialEnvelope.getEphemeral()) {
foundationDbMessageStore.delete(aciServiceIdentifier, deviceId, fdbMessageStreamEntry.versionstamp());
staleEphemeralMessagesCounter.increment();
return;
}
@@ -209,8 +212,7 @@ public class FoundationDbMessageStream implements MessageStream {
maxMessagesPerScan,
presenceKey,
presenceRenewalExecutorService,
messagesAvailableWatchKey,
() -> clearAcknowledgedMessages(database)).getMessages();
messagesAvailableWatchKey).getMessages();
})
.toArray(Flux[]::new);
@@ -249,61 +251,8 @@ public class FoundationDbMessageStream implements MessageStream {
@Override
public CompletableFuture<Void> acknowledgeMessage(final UUID messageGuid, final long serverTimestamp) {
final Versionstamp versionstamp = messageGuidCodec.decodeMessageGuid(messageGuid);
getAcknowledgedMessageBuffer(versionstamp).acknowledgeMessage(versionstamp);
messageAcknowledgedCounter.increment();
return CompletableFuture.completedFuture(null);
}
/// Clear the versionstamp range (startInclusive, endInclusive) in a single FoundationDB operation.
///
/// @param transaction The FoundationDB transaction in which to perform the range clear
/// @param startInclusive The starting versionstamp of the range to be cleared (inclusive)
/// @param endInclusive The ending versionstamp of the range to be cleared (inclusive)
private void clearRange(final Transaction transaction, final Versionstamp startInclusive, final Versionstamp endInclusive) {
final byte[] startKeyInclusive = deviceQueueSubspace.pack(Tuple.from(startInclusive));
final byte[] endKeyExclusive = ByteArrayUtil.keyAfter(deviceQueueSubspace.pack(Tuple.from(endInclusive)));
transaction.clear(startKeyInclusive, endKeyExclusive);
}
/// Clear all outstanding acknowledged messages. Called when the stream ends
private CompletableFuture<Void> flushAllAcknowledgedMessages() {
return CompletableFuture.allOf(Arrays.stream(databasesByEpoch)
.filter(Objects::nonNull)
.distinct()
.map(database -> {
final Consumer<Transaction> clearAllAcknowlegedMessagedConsumer = clearAcknowledgedMessages(database);
return database.runAsync(transaction -> {
clearAllAcknowlegedMessagedConsumer.accept(transaction);
return CompletableFuture.completedFuture((Void) null);
})
.whenComplete((_, throwable) -> {
if (throwable != null) {
LOGGER.warn("Failed to clear acknowledged messages", throwable);
}
});
})
.toArray(CompletableFuture[]::new));
}
private AcknowledgedMessageBuffer getAcknowledgedMessageBuffer(final Versionstamp versionstamp) {
final int epoch = FoundationDbMessageStore.getConfigurationEpoch(versionstamp);
final Database database = databasesByEpoch[epoch];
if (database == null) {
throw new IllegalStateException("Read message for unrecognized epoch");
}
return acknowledgedMessageBuffersByDatabase.get(database);
}
private synchronized Consumer<Transaction> clearAcknowledgedMessages(final Database database) {
final List<Pair<Versionstamp, Versionstamp>> flushableRanges =
acknowledgedMessageBuffersByDatabase.get(database).takeFlushableRanges();
return transaction -> flushableRanges.forEach(range -> clearRange(transaction, range.first(), range.second()));
return foundationDbMessageStore.delete(aciServiceIdentifier, deviceId, messageGuid);
}
}
@@ -36,7 +36,7 @@ import com.braintree.graphql.clientoperation.CreatePayPalOneTimePaymentMutation;
import com.braintree.graphql.clientoperation.TokenizePayPalBillingAgreementMutation;
import com.braintree.graphql.clientoperation.TokenizePayPalOneTimePaymentMutation;
import com.braintree.graphql.clientoperation.VaultPaymentMethodMutation;
import jakarta.ws.rs.ServiceUnavailableException;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URI;
import java.net.URISyntaxException;
@@ -44,7 +44,6 @@ import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Base64;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import okio.Buffer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -69,7 +68,7 @@ class BraintreeGraphqlClient {
this.httpClient = httpClient;
try {
this.graphqlUri = new URI(graphqlUri);
} catch (URISyntaxException e) {
} catch (final URISyntaxException e) {
throw new IllegalArgumentException("Invalid URI", e);
}
// “public”/“private” key is a bit of a misnomer, but we follow the upstream nomenclature
@@ -77,36 +76,32 @@ class BraintreeGraphqlClient {
this.authorizationHeader = "Basic " + Base64.getEncoder().encodeToString((publicKey + ":" + privateKey).getBytes());
}
CompletableFuture<CreatePayPalOneTimePaymentMutation.CreatePayPalOneTimePayment> createPayPalOneTimePayment(
CreatePayPalOneTimePaymentMutation.CreatePayPalOneTimePayment createPayPalOneTimePayment(
final BigDecimal amount, final String currency, final String returnUrl,
final String cancelUrl, final String locale, final String localizedLineItemName) {
final String cancelUrl, final String locale, final String localizedLineItemName) throws IOException {
final CreatePayPalOneTimePaymentInput input = buildCreatePayPalOneTimePaymentInput(amount, currency, returnUrl,
cancelUrl, locale, localizedLineItemName);
final CreatePayPalOneTimePaymentMutation mutation = new CreatePayPalOneTimePaymentMutation(input);
final HttpRequest request = buildRequest(mutation);
return httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(httpResponse ->
{
// IntelliJ users: type parameters error “no instance of type variable exists so that Data conforms to Data”
// is not accurate; this might be fixed in Kotlin 1.8: https://youtrack.jetbrains.com/issue/KTIJ-21905/
final ApolloResponse<CreatePayPalOneTimePaymentMutation.Data> apolloResponse =
extractApolloResponse(httpResponse, mutation);
final CreatePayPalOneTimePaymentMutation.Data data = assertSuccessAndExtractDataFromApolloResponse(apolloResponse);
if (data.createPayPalOneTimePayment == null) {
logger.warn(
"createPayPalOneTimePayment requestId={} currency={} amount={} did not have any errors but data was null. response={}",
apolloResponse.extensions.getOrDefault("requestId", "<No-Request-Id>"),
currency, amount, httpResponse.body());
throw new ServiceUnavailableException();
}
return data.createPayPalOneTimePayment;
});
final HttpResponse<String> httpResponse = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
final ApolloResponse<CreatePayPalOneTimePaymentMutation.Data> apolloResponse =
extractApolloResponse(httpResponse, mutation);
final CreatePayPalOneTimePaymentMutation.Data data = assertSuccessAndExtractDataFromApolloResponse(apolloResponse);
if (data.createPayPalOneTimePayment == null) {
logger.warn(
"createPayPalOneTimePayment requestId={} currency={} amount={} did not have any errors but data was null. response={}",
apolloResponse.extensions.getOrDefault("requestId", "<No-Request-Id>"),
currency, amount, httpResponse.body());
throw new IOException();
}
return data.createPayPalOneTimePayment;
}
private static CreatePayPalOneTimePaymentInput buildCreatePayPalOneTimePaymentInput(BigDecimal amount,
String currency, String returnUrl, String cancelUrl, String locale, String localizedLineItemName) {
private static CreatePayPalOneTimePaymentInput buildCreatePayPalOneTimePaymentInput(final BigDecimal amount,
final String currency, final String returnUrl, final String cancelUrl, final String locale, final String localizedLineItemName) {
// Note locale and localizedLineItemName are a best-effort, and it's possible that they will not match.
// We could try to align with the locales PayPal documents <https://developer.paypal.com/reference/locale-codes/#supported-locale-codes>
@@ -148,8 +143,8 @@ class BraintreeGraphqlClient {
);
}
CompletableFuture<TokenizePayPalOneTimePaymentMutation.TokenizePayPalOneTimePayment> tokenizePayPalOneTimePayment(
final String payerId, final String paymentId, final String paymentToken) {
TokenizePayPalOneTimePaymentMutation.TokenizePayPalOneTimePayment tokenizePayPalOneTimePayment(
final String payerId, final String paymentId, final String paymentToken) throws IOException {
final TokenizePayPalOneTimePaymentInput input = new TokenizePayPalOneTimePaymentInput(
Optional.absent(),
@@ -159,18 +154,15 @@ class BraintreeGraphqlClient {
final TokenizePayPalOneTimePaymentMutation mutation = new TokenizePayPalOneTimePaymentMutation(input);
final HttpRequest request = buildRequest(mutation);
final HttpResponse<String> httpResponse = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
return httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(httpResponse -> {
// IntelliJ users: type parameters error “no instance of type variable exists so that Data conforms to Data”
// is not accurate; this might be fixed in Kotlin 1.8: https://youtrack.jetbrains.com/issue/KTIJ-21905/
final TokenizePayPalOneTimePaymentMutation.Data data = assertSuccessAndExtractData(httpResponse, mutation);
return data.tokenizePayPalOneTimePayment;
});
final TokenizePayPalOneTimePaymentMutation.Data data = assertSuccessAndExtractData(httpResponse, mutation);
return data.tokenizePayPalOneTimePayment;
}
CompletableFuture<ChargePayPalOneTimePaymentMutation.ChargePaymentMethod> chargeOneTimePayment(
final String paymentMethodId, final BigDecimal amount, final String merchantAccount, final long level) {
ChargePayPalOneTimePaymentMutation.ChargePaymentMethod chargeOneTimePayment(
final String paymentMethodId, final BigDecimal amount, final String merchantAccount, final long level)
throws IOException {
final List<CustomFieldInput> customFields = List.of(
new CustomFieldInput("level", Optional.present(Long.toString(level))));
@@ -180,18 +172,14 @@ class BraintreeGraphqlClient {
final ChargePayPalOneTimePaymentMutation mutation = new ChargePayPalOneTimePaymentMutation(input);
final HttpRequest request = buildRequest(mutation);
return httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(httpResponse -> {
// IntelliJ users: type parameters error “no instance of type variable exists so that Data conforms to Data”
// is not accurate; this might be fixed in Kotlin 1.8: https://youtrack.jetbrains.com/issue/KTIJ-21905/
final ChargePayPalOneTimePaymentMutation.Data data = assertSuccessAndExtractData(httpResponse,
mutation);
return data.chargePaymentMethod;
});
final HttpResponse<String> httpResponse = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
final ChargePayPalOneTimePaymentMutation.Data data = assertSuccessAndExtractData(httpResponse,
mutation);
return data.chargePaymentMethod;
}
private static ChargePaymentMethodInput buildChargePaymentMethodInput(String paymentMethodId, BigDecimal amount,
String merchantAccount, List<CustomFieldInput> customFields) {
private static ChargePaymentMethodInput buildChargePaymentMethodInput(final String paymentMethodId, final BigDecimal amount,
final String merchantAccount, final List<CustomFieldInput> customFields) {
return new ChargePaymentMethodInput(
Optional.absent(),
@@ -221,25 +209,21 @@ class BraintreeGraphqlClient {
);
}
public CompletableFuture<CreatePayPalBillingAgreementMutation.CreatePayPalBillingAgreement> createPayPalBillingAgreement(
final String returnUrl, final String cancelUrl, final String locale) {
public CreatePayPalBillingAgreementMutation.CreatePayPalBillingAgreement createPayPalBillingAgreement(
final String returnUrl, final String cancelUrl, final String locale) throws IOException {
final CreatePayPalBillingAgreementInput input = buildCreatePayPalBillingAgreementInput(returnUrl, cancelUrl,
locale);
final CreatePayPalBillingAgreementMutation mutation = new CreatePayPalBillingAgreementMutation(input);
final HttpRequest request = buildRequest(mutation);
return httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(httpResponse -> {
// IntelliJ users: type parameters error “no instance of type variable exists so that Data conforms to Data”
// is not accurate; this might be fixed in Kotlin 1.8: https://youtrack.jetbrains.com/issue/KTIJ-21905/
final CreatePayPalBillingAgreementMutation.Data data = assertSuccessAndExtractData(httpResponse, mutation);
return data.createPayPalBillingAgreement;
});
final HttpResponse<String> httpResponse = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
final CreatePayPalBillingAgreementMutation.Data data = assertSuccessAndExtractData(httpResponse, mutation);
return data.createPayPalBillingAgreement;
}
private static CreatePayPalBillingAgreementInput buildCreatePayPalBillingAgreementInput(String returnUrl,
String cancelUrl, String locale) {
private static CreatePayPalBillingAgreementInput buildCreatePayPalBillingAgreementInput(final String returnUrl,
final String cancelUrl, final String locale) {
return new CreatePayPalBillingAgreementInput(
Optional.absent(),
@@ -263,8 +247,8 @@ class BraintreeGraphqlClient {
);
}
public CompletableFuture<TokenizePayPalBillingAgreementMutation.TokenizePayPalBillingAgreement> tokenizePayPalBillingAgreement(
final String billingAgreementToken) {
public TokenizePayPalBillingAgreementMutation.TokenizePayPalBillingAgreement tokenizePayPalBillingAgreement(
final String billingAgreementToken) throws IOException {
final TokenizePayPalBillingAgreementInput input = new TokenizePayPalBillingAgreementInput(
Optional.absent(),
@@ -272,32 +256,24 @@ class BraintreeGraphqlClient {
final TokenizePayPalBillingAgreementMutation mutation = new TokenizePayPalBillingAgreementMutation(input);
final HttpRequest request = buildRequest(mutation);
return httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(httpResponse -> {
// IntelliJ users: type parameters error “no instance of type variable exists so that Data conforms to Data”
// is not accurate; this might be fixed in Kotlin 1.8: https://youtrack.jetbrains.com/issue/KTIJ-21905/
final TokenizePayPalBillingAgreementMutation.Data data = assertSuccessAndExtractData(httpResponse, mutation);
return data.tokenizePayPalBillingAgreement;
});
final HttpResponse<String> httpResponse = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
final TokenizePayPalBillingAgreementMutation.Data data = assertSuccessAndExtractData(httpResponse, mutation);
return data.tokenizePayPalBillingAgreement;
}
public CompletableFuture<VaultPaymentMethodMutation.VaultPaymentMethod> vaultPaymentMethod(final String customerId,
final String paymentMethodId) {
public VaultPaymentMethodMutation.VaultPaymentMethod vaultPaymentMethod(final String customerId,
final String paymentMethodId) throws IOException {
final VaultPaymentMethodInput input = buildVaultPaymentMethodInput(customerId, paymentMethodId);
final VaultPaymentMethodMutation mutation = new VaultPaymentMethodMutation(input);
final HttpRequest request = buildRequest(mutation);
return httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(httpResponse -> {
// IntelliJ users: type parameters error “no instance of type variable exists so that Data conforms to Data”
// is not accurate; this might be fixed in Kotlin 1.8: https://youtrack.jetbrains.com/issue/KTIJ-21905/
final VaultPaymentMethodMutation.Data data = assertSuccessAndExtractData(httpResponse, mutation);
return data.vaultPaymentMethod;
});
final HttpResponse<String> httpResponse = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
final VaultPaymentMethodMutation.Data data = assertSuccessAndExtractData(httpResponse, mutation);
return data.vaultPaymentMethod;
}
private static VaultPaymentMethodInput buildVaultPaymentMethodInput(String customerId, String paymentMethodId) {
private static VaultPaymentMethodInput buildVaultPaymentMethodInput(final String customerId, final String paymentMethodId) {
return new VaultPaymentMethodInput(
Optional.absent(),
paymentMethodId,
@@ -311,26 +287,28 @@ class BraintreeGraphqlClient {
/**
* Verifies that the HTTP response has a {@code 200} status code and the GraphQL response has no errors, otherwise
* throws a {@link ServiceUnavailableException}.
* throws a {@link IOException}.
*/
private static <T extends Operation<U>, U extends Operation.Data> U assertSuccessAndExtractData(
HttpResponse<String> httpResponse, T operation) {
final HttpResponse<String> httpResponse, final T operation) throws IOException {
return assertSuccessAndExtractDataFromApolloResponse(extractApolloResponse(httpResponse, operation));
}
private static <T extends Operation<U>, U extends Operation.Data> ApolloResponse<U> extractApolloResponse(
HttpResponse<String> httpResponse, T operation) {
final HttpResponse<String> httpResponse, final T operation) throws IOException {
if (httpResponse.statusCode() != 200) {
logger.warn("Received HTTP response status {} ({})", httpResponse.statusCode(),
httpResponse.headers().firstValue("paypal-debug-id").orElse("<debug id absent>"));
throw new ServiceUnavailableException();
throw new IOException();
}
return Operations.parseJsonResponse(operation, httpResponse.body());
}
private static <T extends Operation<U>, U extends Operation.Data> U assertSuccessAndExtractDataFromApolloResponse(final ApolloResponse<U> response) {
private static <T extends Operation<U>, U extends Operation.Data> U assertSuccessAndExtractDataFromApolloResponse(
final ApolloResponse<U> response)
throws IOException {
if (response.hasErrors() || response.data == null) {
//noinspection ConstantConditions
response.errors.forEach(
@@ -342,7 +320,7 @@ class BraintreeGraphqlClient {
response.operation.name(), error.getMessage(), legacyCode);
});
throw new ServiceUnavailableException();
throw new IOException();
}
return response.data;
@@ -5,7 +5,11 @@
package org.whispersystems.textsecuregcm.subscriptions;
import com.braintree.graphql.clientoperation.ChargePayPalOneTimePaymentMutation;
import com.braintree.graphql.clientoperation.CreatePayPalBillingAgreementMutation;
import com.braintree.graphql.clientoperation.CreatePayPalOneTimePaymentMutation;
import com.braintree.graphql.clientoperation.TokenizePayPalBillingAgreementMutation;
import com.braintree.graphql.clientoperation.TokenizePayPalOneTimePaymentMutation;
import com.braintree.graphql.clientoperation.VaultPaymentMethodMutation;
import com.braintreegateway.BraintreeGateway;
import com.braintreegateway.ClientTokenRequest;
@@ -36,7 +40,6 @@ import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import javax.annotation.Nullable;
import org.slf4j.Logger;
@@ -45,7 +48,6 @@ import org.whispersystems.textsecuregcm.currency.CurrencyConversionManager;
import org.whispersystems.textsecuregcm.http.FaultTolerantHttpClient;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.storage.PaymentTime;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import org.whispersystems.textsecuregcm.util.ExecutorUtil;
import org.whispersystems.textsecuregcm.util.GoogleApiUtil;
import org.whispersystems.textsecuregcm.util.SystemMapper;
@@ -128,92 +130,88 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
return paymentMethod == PaymentMethod.PAYPAL;
}
public CompletableFuture<Optional<PaymentDetails>> getPaymentDetails(final String paymentId) {
return CompletableFuture.supplyAsync(() -> {
try {
final Transaction transaction = braintreeGateway.transaction().find(paymentId);
ChargeFailure chargeFailure = null;
if (!getPaymentStatus(transaction.getStatus()).equals(PaymentStatus.SUCCEEDED)) {
chargeFailure = createChargeFailure(transaction);
}
return Optional.of(new PaymentDetails(transaction.getGraphQLId(),
transaction.getCustomFields(),
getPaymentStatus(transaction.getStatus()),
transaction.getCreatedAt().toInstant(),
chargeFailure));
} catch (final NotFoundException e) {
return Optional.empty();
public Optional<PaymentDetails> getPaymentDetails(final String paymentId) {
try {
final Transaction transaction = braintreeGateway.transaction().find(paymentId);
ChargeFailure chargeFailure = null;
if (!getPaymentStatus(transaction.getStatus()).equals(PaymentStatus.SUCCEEDED)) {
chargeFailure = createChargeFailure(transaction);
}
}, executor);
return Optional.of(new PaymentDetails(transaction.getGraphQLId(),
transaction.getCustomFields(),
getPaymentStatus(transaction.getStatus()),
transaction.getCreatedAt().toInstant(),
chargeFailure));
} catch (final NotFoundException e) {
return Optional.empty();
}
}
public CompletableFuture<PayPalOneTimePaymentApprovalDetails> createOneTimePayment(String currency, long amount,
String locale, String returnUrl, String cancelUrl, String localizedLineItemname) {
return braintreeGraphqlClient.createPayPalOneTimePayment(convertApiAmountToBraintreeAmount(currency, amount),
currency.toUpperCase(Locale.ROOT), returnUrl,
cancelUrl, locale, localizedLineItemname)
.thenApply(result -> new PayPalOneTimePaymentApprovalDetails((String) result.approvalUrl, result.paymentId));
public PayPalOneTimePaymentApprovalDetails createOneTimePayment(final String currency, final long amount,
final String locale, final String returnUrl, final String cancelUrl, final String localizedLineItemName) throws IOException {
final CreatePayPalOneTimePaymentMutation.CreatePayPalOneTimePayment result = braintreeGraphqlClient.createPayPalOneTimePayment(
convertApiAmountToBraintreeAmount(currency, amount),
currency.toUpperCase(Locale.ROOT), returnUrl,
cancelUrl, locale, localizedLineItemName);
return new PayPalOneTimePaymentApprovalDetails((String) result.approvalUrl, result.paymentId);
}
public CompletableFuture<PayPalChargeSuccessDetails> captureOneTimePayment(String payerId, String paymentId,
String paymentToken, String currency, long amount, long level, @Nullable ClientPlatform clientPlatform) {
return braintreeGraphqlClient.tokenizePayPalOneTimePayment(payerId, paymentId, paymentToken)
.thenCompose(response -> braintreeGraphqlClient.chargeOneTimePayment(
response.paymentMethod.id,
convertApiAmountToBraintreeAmount(currency, amount),
currenciesToMerchantAccounts.get(currency.toLowerCase(Locale.ROOT)),
level)
.thenComposeAsync(chargeResponse -> {
public PayPalChargeSuccessDetails captureOneTimePayment(final String payerId, final String paymentId,
final String paymentToken, final String currency, final long amount, final long level, @Nullable final ClientPlatform clientPlatform)
throws SubscriptionProcessorException, IOException {
final TokenizePayPalOneTimePaymentMutation.TokenizePayPalOneTimePayment response = braintreeGraphqlClient.tokenizePayPalOneTimePayment(
payerId, paymentId, paymentToken);
final ChargePayPalOneTimePaymentMutation.ChargePaymentMethod chargeResponse = braintreeGraphqlClient.chargeOneTimePayment(
response.paymentMethod.id,
convertApiAmountToBraintreeAmount(currency, amount),
currenciesToMerchantAccounts.get(currency.toLowerCase(Locale.ROOT)),
level);
final PaymentStatus paymentStatus = getPaymentStatus(chargeResponse.transaction.status);
if (paymentStatus == PaymentStatus.SUCCEEDED || paymentStatus == PaymentStatus.PROCESSING) {
publishDonationEvent(amount, currency, Instant.now(), clientPlatform);
return CompletableFuture.completedFuture(new PayPalChargeSuccessDetails(chargeResponse.transaction.id));
}
final PaymentStatus paymentStatus = getPaymentStatus(chargeResponse.transaction.status);
if (paymentStatus == PaymentStatus.SUCCEEDED || paymentStatus == PaymentStatus.PROCESSING) {
publishDonationEvent(amount, currency, Instant.now(), clientPlatform);
return new PayPalChargeSuccessDetails(chargeResponse.transaction.id);
}
// the GraphQL/Apollo interfaces are a tad unwieldy for this type of status checking
final Transaction unsuccessfulTx = braintreeGateway.transaction().find(chargeResponse.transaction.id);
// the GraphQL/Apollo interfaces are a tad unwieldy for this type of status checking
final Transaction unsuccessfulTx = braintreeGateway.transaction().find(chargeResponse.transaction.id);
if (PAYPAL_PAYMENT_ALREADY_COMPLETED_PROCESSOR_CODE.equals(unsuccessfulTx.getProcessorResponseCode())
|| Transaction.GatewayRejectionReason.DUPLICATE.equals(unsuccessfulTx.getGatewayRejectionReason())) {
// the payment has already been charged - maybe a previous call timed out or was interrupted -
// in any case, check for a successful transaction with the paymentId
final ResourceCollection<Transaction> search = braintreeGateway.transaction()
.search(new TransactionSearchRequest()
.paypalPaymentId().is(paymentId)
.status().in(
Transaction.Status.SETTLED,
Transaction.Status.SETTLING,
Transaction.Status.SUBMITTED_FOR_SETTLEMENT,
Transaction.Status.SETTLEMENT_PENDING
)
);
if (PAYPAL_PAYMENT_ALREADY_COMPLETED_PROCESSOR_CODE.equals(unsuccessfulTx.getProcessorResponseCode())
|| Transaction.GatewayRejectionReason.DUPLICATE.equals(unsuccessfulTx.getGatewayRejectionReason())) {
// the payment has already been charged - maybe a previous call timed out or was interrupted -
// in any case, check for a successful transaction with the paymentId
final ResourceCollection<Transaction> search = braintreeGateway.transaction()
.search(new TransactionSearchRequest()
.paypalPaymentId().is(paymentId)
.status().in(
Transaction.Status.SETTLED,
Transaction.Status.SETTLING,
Transaction.Status.SUBMITTED_FOR_SETTLEMENT,
Transaction.Status.SETTLEMENT_PENDING
)
);
if (search.getMaximumSize() == 0) {
return CompletableFuture.failedFuture(ExceptionUtils.wrap(new IOException()));
}
if (search.getMaximumSize() == 0) {
throw new IOException();
}
final Transaction successfulTx = search.getFirst();
final Transaction successfulTx = search.getFirst();
publishDonationEvent(amount, currency, successfulTx.getCreatedAt().toInstant(), clientPlatform);
publishDonationEvent(amount, currency, successfulTx.getCreatedAt().toInstant(), clientPlatform);
return CompletableFuture.completedFuture(
new PayPalChargeSuccessDetails(successfulTx.getGraphQLId()));
}
return new PayPalChargeSuccessDetails(successfulTx.getGraphQLId());
}
return switch (unsuccessfulTx.getProcessorResponseCode()) {
case GENERIC_DECLINED_PROCESSOR_CODE, PAYPAL_FUNDING_INSTRUMENT_DECLINED_PROCESSOR_CODE ->
CompletableFuture.failedFuture(
new SubscriptionProcessorException(getProvider(), createChargeFailure(unsuccessfulTx)));
switch (unsuccessfulTx.getProcessorResponseCode()) {
case GENERIC_DECLINED_PROCESSOR_CODE, PAYPAL_FUNDING_INSTRUMENT_DECLINED_PROCESSOR_CODE ->
throw new SubscriptionProcessorException(getProvider(), createChargeFailure(unsuccessfulTx));
default -> {
logger.info("PayPal charge unexpectedly failed: {}", unsuccessfulTx.getProcessorResponseCode());
yield CompletableFuture.failedFuture(ExceptionUtils.wrap(new IOException()));
}
};
}, executor));
default -> {
logger.info("PayPal charge unexpectedly failed: {}", unsuccessfulTx.getProcessorResponseCode());
throw new IOException();
}
}
}
private void publishDonationEvent(final long amount,
@@ -264,7 +262,7 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
return amount.multiply(ONE_MILLION).longValueExact();
}
private static PaymentStatus getPaymentStatus(Transaction.Status status) {
private static PaymentStatus getPaymentStatus(final Transaction.Status status) {
return switch (status) {
case SETTLEMENT_CONFIRMED, SETTLING, SUBMITTED_FOR_SETTLEMENT, SETTLED -> PaymentStatus.SUCCEEDED;
case AUTHORIZATION_EXPIRED, GATEWAY_REJECTED, PROCESSOR_DECLINED, SETTLEMENT_DECLINED, VOIDED, FAILED ->
@@ -273,9 +271,9 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
};
}
private static PaymentStatus getPaymentStatus(com.braintree.graphql.client.type.PaymentStatus status) {
private static PaymentStatus getPaymentStatus(final com.braintree.graphql.client.type.PaymentStatus status) {
try {
Transaction.Status transactionStatus = Transaction.Status.valueOf(status.rawValue);
final Transaction.Status transactionStatus = Transaction.Status.valueOf(status.rawValue);
return getPaymentStatus(transactionStatus);
} catch (final Exception e) {
@@ -283,7 +281,8 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
}
}
private static SubscriptionStatus getSubscriptionStatus(final Subscription.Status status, final boolean latestTransactionFailed) {
private static SubscriptionStatus getSubscriptionStatus(final Subscription.Status status,
final boolean latestTransactionFailed) {
return switch (status) {
// Stripe returns a PAST_DUE status if the subscription's most recent payment failed.
// This check ensures that Braintree is consistent with Stripe.
@@ -316,7 +315,7 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
@Override
public ProcessorCustomer createCustomer(final byte[] subscriberUser, @Nullable final ClientPlatform clientPlatform) {
CustomerRequest request = new CustomerRequest()
final CustomerRequest request = new CustomerRequest()
.customField("subscriber_user", HexFormat.of().formatHex(subscriberUser));
if (clientPlatform != null) {
@@ -332,19 +331,19 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
@Override
public String createPaymentMethodSetupToken(final String customerId) {
ClientTokenRequest request = new ClientTokenRequest().customerId(customerId);
final ClientTokenRequest request = new ClientTokenRequest().customerId(customerId);
return braintreeGateway.clientToken().generate(request);
}
@Override
public void setDefaultPaymentMethodForCustomer(String customerId, String billingAgreementToken,
@Nullable String currentSubscriptionId) {
public void setDefaultPaymentMethodForCustomer(final String customerId, final String billingAgreementToken,
@Nullable final String currentSubscriptionId) throws IOException {
final Optional<String> maybeSubscriptionId = Optional.ofNullable(currentSubscriptionId);
final TokenizePayPalBillingAgreementMutation.TokenizePayPalBillingAgreement tokenizePayPalBillingAgreement =
braintreeGraphqlClient.tokenizePayPalBillingAgreement(billingAgreementToken).join();
braintreeGraphqlClient.tokenizePayPalBillingAgreement(billingAgreementToken);
final VaultPaymentMethodMutation.VaultPaymentMethod vaultPaymentMethod =
braintreeGraphqlClient.vaultPaymentMethod(customerId, tokenizePayPalBillingAgreement.paymentMethod.id).join();
braintreeGraphqlClient.vaultPaymentMethod(customerId, tokenizePayPalBillingAgreement.paymentMethod.id);
final Result<Customer> result = braintreeGateway.customer()
.update(customerId, new CustomerRequest().defaultPaymentMethodToken(vaultPaymentMethod.paymentMethod.id));
maybeSubscriptionId.ifPresent(subscriptionId ->
@@ -353,13 +352,13 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
}
@Override
public Object getSubscription(String subscriptionId) {
public Object getSubscription(final String subscriptionId) {
return braintreeGateway.subscription().find(subscriptionId);
}
@Override
public SubscriptionId createSubscription(String customerId, String planId, long level,
long lastSubscriptionCreatedAt)
public SubscriptionId createSubscription(final String customerId, final String planId, final long level,
final long lastSubscriptionCreatedAt)
throws SubscriptionProcessorConflictException, SubscriptionProcessorException {
final com.braintreegateway.PaymentMethod paymentMethod = getDefaultPaymentMethod(customerId);
@@ -406,14 +405,15 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
return new SubscriptionId(result.getTarget().getId());
}
private com.braintreegateway.PaymentMethod getDefaultPaymentMethod(String customerId) {
private com.braintreegateway.PaymentMethod getDefaultPaymentMethod(final String customerId) {
return braintreeGateway.customer().find(customerId).getDefaultPaymentMethod();
}
@Override
public CustomerAwareSubscriptionPaymentProcessor.SubscriptionId updateSubscription(Object subscriptionObj, String planId, long level,
String idempotencyKey) throws SubscriptionProcessorConflictException, SubscriptionProcessorException {
public CustomerAwareSubscriptionPaymentProcessor.SubscriptionId updateSubscription(final Object subscriptionObj,
final String planId, final long level,
final String idempotencyKey) throws SubscriptionProcessorConflictException, SubscriptionProcessorException {
if (!(subscriptionObj instanceof final Subscription subscription)) {
throw new IllegalArgumentException("invalid subscription object: " + subscriptionObj.getClass().getName());
@@ -425,7 +425,7 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
endSubscription(subscription);
final Transaction transaction = getLatestTransactionForSubscription(subscription)
.orElseThrow(() -> ExceptionUtils.wrap(new SubscriptionProcessorConflictException()));
.orElseThrow(SubscriptionProcessorConflictException::new);
final Customer customer = transaction.getCustomer();
@@ -434,13 +434,13 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
}
@Override
public LevelAndCurrency getLevelAndCurrencyForSubscription(Object subscriptionObj) {
public LevelAndCurrency getLevelAndCurrencyForSubscription(final Object subscriptionObj) {
final Subscription subscription = getSubscription(subscriptionObj);
final Plan plan = findPlan(subscription.getPlanId());
return new LevelAndCurrency(getLevelForPlan(plan), plan.getCurrencyIsoCode().toLowerCase(Locale.ROOT));
}
private Plan findPlan(String planId) {
private Plan findPlan(final String planId) {
return braintreeGateway.plan().find(planId);
}
@@ -449,7 +449,7 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
try {
metadata = SystemMapper.jsonMapper().readValue(plan.getDescription(), BraintreePlanMetadata.class);
} catch (JsonProcessingException e) {
} catch (final JsonProcessingException e) {
throw new RuntimeException(e);
}
@@ -458,7 +458,7 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
@Override
public SubscriptionInformation getSubscriptionInformation(final String subscriptionId) {
final Subscription subscription = getSubscription(getSubscription(subscriptionId));
final Subscription subscription = getSubscription(getSubscription(subscriptionId));
final Plan plan = braintreeGateway.plan().find(subscription.getPlanId());
final long level = getLevelForPlan(plan);
@@ -500,11 +500,12 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
return new TransactionInfo(paymentMethod, paymentProcessing, false, null);
}
private PaymentMethod getPaymentMethodFromTransaction(Transaction transaction) {
private PaymentMethod getPaymentMethodFromTransaction(final Transaction transaction) {
if (transaction.getPayPalDetails() != null) {
return PaymentMethod.PAYPAL;
}
logger.error("Unexpected payment method from Braintree: {}, transaction id {}", transaction.getPaymentInstrumentType(), transaction.getId());
logger.error("Unexpected payment method from Braintree: {}, transaction id {}",
transaction.getPaymentInstrumentType(), transaction.getId());
return PaymentMethod.UNKNOWN;
}
@@ -512,7 +513,7 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
return status == Transaction.Status.SETTLEMENT_PENDING;
}
private ChargeFailure createChargeFailure(Transaction transaction) {
private ChargeFailure createChargeFailure(final Transaction transaction) {
final String code;
final String message;
@@ -539,7 +540,7 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
}
@Override
public void cancelAllActiveSubscriptions(String customerId) {
public void cancelAllActiveSubscriptions(final String customerId) {
final Customer customer = braintreeGateway.customer().find(customerId);
ExecutorUtil.runAll(executor, Optional.ofNullable(customer.getDefaultPaymentMethod())
.stream()
@@ -548,7 +549,7 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
.toList());
}
private void endSubscription(Subscription subscription) {
private void endSubscription(final Subscription subscription) {
final boolean latestTransactionFailed = getLatestTransactionForSubscription(subscription)
.map(this::getTransactionInfo)
.map(TransactionInfo::transactionFailed)
@@ -563,20 +564,20 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
}
}
private void cancelSubscriptionAtEndOfCurrentPeriod(Subscription subscription) {
private void cancelSubscriptionAtEndOfCurrentPeriod(final Subscription subscription) {
braintreeGateway
.subscription()
.update(subscription.getId(),
new SubscriptionRequest().numberOfBillingCycles(subscription.getCurrentBillingCycle()));
}
private void cancelSubscriptionImmediately(Subscription subscription) {
private void cancelSubscriptionImmediately(final Subscription subscription) {
braintreeGateway.subscription().cancel(subscription.getId());
}
@Override
public ReceiptItem getReceiptItem(String subscriptionId)
public ReceiptItem getReceiptItem(final String subscriptionId)
throws SubscriptionReceiptRequestedForOpenPaymentException, SubscriptionChargeFailurePaymentRequiredException {
final Subscription subscription = getSubscription(getSubscription(subscriptionId));
final Transaction transaction = getLatestTransactionForSubscription(subscription)
@@ -597,31 +598,31 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
try {
metadata = SystemMapper.jsonMapper().readValue(plan.getDescription(), BraintreePlanMetadata.class);
} catch (JsonProcessingException e) {
} catch (final JsonProcessingException e) {
throw new RuntimeException(e);
}
return new ReceiptItem(transaction.getId(), PaymentTime.periodStart(paidAt), metadata.level());
}
private static Subscription getSubscription(Object subscriptionObj) {
private static Subscription getSubscription(final Object subscriptionObj) {
if (!(subscriptionObj instanceof final Subscription subscription)) {
throw new IllegalArgumentException("Invalid subscription object: " + subscriptionObj.getClass().getName());
}
return subscription;
}
private Optional<Transaction> getLatestTransactionForSubscription(Subscription subscription) {
private Optional<Transaction> getLatestTransactionForSubscription(final Subscription subscription) {
return subscription.getTransactions().stream()
.max(Comparator.comparing(Transaction::getCreatedAt));
.max(Comparator.comparing(Transaction::getCreatedAt));
}
public CompletableFuture<PayPalBillingAgreementApprovalDetails> createPayPalBillingAgreement(final String returnUrl,
final String cancelUrl, final String locale) {
return braintreeGraphqlClient.createPayPalBillingAgreement(returnUrl, cancelUrl, locale)
.thenApply(response ->
new PayPalBillingAgreementApprovalDetails((String) response.approvalUrl, response.billingAgreementToken)
);
public PayPalBillingAgreementApprovalDetails createPayPalBillingAgreement(final String returnUrl,
final String cancelUrl, final String locale)
throws IOException {
final CreatePayPalBillingAgreementMutation.CreatePayPalBillingAgreement response = braintreeGraphqlClient.createPayPalBillingAgreement(
returnUrl, cancelUrl, locale);
return new PayPalBillingAgreementApprovalDetails((String) response.approvalUrl, response.billingAgreementToken);
}
public record PayPalBillingAgreementApprovalDetails(String approvalUrl, String billingAgreementToken) {
@@ -5,6 +5,7 @@
package org.whispersystems.textsecuregcm.subscriptions;
import java.io.IOException;
import java.util.Set;
import javax.annotation.Nullable;
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
@@ -41,10 +42,11 @@ public interface CustomerAwareSubscriptionPaymentProcessor extends SubscriptionP
* {@link #createPaymentMethodSetupToken}
* @param currentSubscriptionId (nullable) an active subscription ID, in case it needs an explicit update
* @throws SubscriptionInvalidArgumentsException If the paymentMethodToken is invalid or the payment method has not
* finished being set up
* finished being set up
* @throws IOException If there was an error talking to the external payment provider
*/
void setDefaultPaymentMethodForCustomer(String customerId, String paymentMethodToken,
@Nullable String currentSubscriptionId) throws SubscriptionInvalidArgumentsException;
@Nullable String currentSubscriptionId) throws SubscriptionInvalidArgumentsException, IOException;
Object getSubscription(String subscriptionId);
@@ -24,5 +24,18 @@ public enum PaymentMethod {
*/
IDEAL,
GOOGLE_PLAY_BILLING,
APPLE_APP_STORE
APPLE_APP_STORE;
public org.signal.chat.purchase.PaymentMethod toProtoPaymentMethod() {
return switch (this) {
case CARD -> org.signal.chat.purchase.PaymentMethod.PAYMENT_METHOD_CARD;
case SEPA_DEBIT -> org.signal.chat.purchase.PaymentMethod.PAYMENT_METHOD_SEPA_DEBIT;
case IDEAL -> org.signal.chat.purchase.PaymentMethod.PAYMENT_METHOD_IDEAL;
case PAYPAL -> org.signal.chat.purchase.PaymentMethod.PAYMENT_METHOD_PAYPAL;
case GOOGLE_PLAY_BILLING -> org.signal.chat.purchase.PaymentMethod.PAYMENT_METHOD_GOOGLE_PLAY_BILLING;
case APPLE_APP_STORE -> org.signal.chat.purchase.PaymentMethod.PAYMENT_METHOD_APPLE_APP_STORE;
case UNKNOWN -> org.signal.chat.purchase.PaymentMethod.PAYMENT_METHOD_UNKNOWN;
};
}
}
@@ -48,12 +48,12 @@ public enum PaymentProvider {
return id;
}
public org.signal.chat.subscriptions.PaymentProvider toProto() {
public org.signal.chat.purchase.PaymentProvider toProto() {
return switch (this) {
case STRIPE -> org.signal.chat.subscriptions.PaymentProvider.PAYMENT_PROVIDER_STRIPE;
case BRAINTREE -> org.signal.chat.subscriptions.PaymentProvider.PAYMENT_PROVIDER_BRAINTREE;
case GOOGLE_PLAY_BILLING -> org.signal.chat.subscriptions.PaymentProvider.PAYMENT_PROVIDER_GOOGLE_PLAY_BILLING;
case APPLE_APP_STORE -> org.signal.chat.subscriptions.PaymentProvider.PAYMENT_PROVIDER_APPLE_APP_STORE;
case STRIPE -> org.signal.chat.purchase.PaymentProvider.PAYMENT_PROVIDER_STRIPE;
case BRAINTREE -> org.signal.chat.purchase.PaymentProvider.PAYMENT_PROVIDER_BRAINTREE;
case GOOGLE_PLAY_BILLING -> org.signal.chat.purchase.PaymentProvider.PAYMENT_PROVIDER_GOOGLE_PLAY_BILLING;
case APPLE_APP_STORE -> org.signal.chat.purchase.PaymentProvider.PAYMENT_PROVIDER_APPLE_APP_STORE;
};
}
}
@@ -62,11 +62,8 @@ import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.Executor;
import java.util.function.Consumer;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
@@ -76,11 +73,11 @@ import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.WhisperServerVersion;
import org.whispersystems.textsecuregcm.storage.PaymentTime;
import org.whispersystems.textsecuregcm.util.Conversions;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import org.whispersystems.textsecuregcm.util.ExecutorUtil;
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor {
private static final Logger logger = LoggerFactory.getLogger(StripeManager.class);
private static final String METADATA_KEY_LEVEL = "level";
private static final String METADATA_KEY_CLIENT_PLATFORM = "clientPlatform";
@@ -93,11 +90,11 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
@VisibleForTesting
StripeManager(
@Nonnull StripeClient stripeClient,
@Nonnull Executor executor,
@Nonnull byte[] idempotencyKeyGenerator,
@Nonnull String boostDescription,
@Nonnull Map<PaymentMethod, Set<String>> supportedCurrenciesByPaymentMethod) {
final StripeClient stripeClient,
final Executor executor,
final byte[] idempotencyKeyGenerator,
final String boostDescription,
final Map<PaymentMethod, Set<String>> supportedCurrenciesByPaymentMethod) {
Stripe.setAppInfo("Signal-Server", WhisperServerVersion.getServerVersion());
this.stripeClient = Objects.requireNonNull(stripeClient);
@@ -109,13 +106,15 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
this.boostDescription = Objects.requireNonNull(boostDescription);
this.supportedCurrenciesByPaymentMethod = supportedCurrenciesByPaymentMethod;
}
public StripeManager(
@Nonnull String apiKey,
@Nonnull Executor executor,
@Nonnull byte[] idempotencyKeyGenerator,
@Nonnull String boostDescription,
@Nonnull Map<PaymentMethod, Set<String>> supportedCurrenciesByPaymentMethod) {
this(new StripeClient(apiKey), executor, idempotencyKeyGenerator, boostDescription, supportedCurrenciesByPaymentMethod);
final String apiKey,
final Executor executor,
final byte[] idempotencyKeyGenerator,
final String boostDescription,
final Map<PaymentMethod, Set<String>> supportedCurrenciesByPaymentMethod) {
this(new StripeClient(apiKey), executor, idempotencyKeyGenerator, boostDescription,
supportedCurrenciesByPaymentMethod);
if (StringUtils.isEmpty(apiKey)) {
throw new IllegalArgumentException("apiKey cannot be empty");
@@ -128,7 +127,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
}
@Override
public boolean supportsPaymentMethod(PaymentMethod paymentMethod) {
public boolean supportsPaymentMethod(final PaymentMethod paymentMethod) {
return paymentMethod == PaymentMethod.CARD
|| paymentMethod == PaymentMethod.SEPA_DEBIT
|| paymentMethod == PaymentMethod.IDEAL;
@@ -138,7 +137,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
return commonOptions(null);
}
private RequestOptions commonOptions(@Nullable String idempotencyKey) {
private RequestOptions commonOptions(@Nullable final String idempotencyKey) {
return RequestOptions.builder()
.setIdempotencyKey(idempotencyKey)
.build();
@@ -157,46 +156,46 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
final Customer customer = stripeClient.v1().customers()
.create(builder.build(), commonOptions(generateIdempotencyKeyForSubscriberUser(subscriberUser)));
return new ProcessorCustomer(customer.getId(), getProvider());
} catch (StripeException e) {
} catch (final StripeException e) {
throw new UncheckedIOException(new IOException(e));
}
}
public Customer getCustomer(String customerId) {
CustomerRetrieveParams params = CustomerRetrieveParams.builder().build();
public Customer getCustomer(final String customerId) {
final CustomerRetrieveParams params = CustomerRetrieveParams.builder().build();
try {
return stripeClient.v1().customers().retrieve(customerId, params, commonOptions());
} catch (StripeException e) {
} catch (final StripeException e) {
throw new UncheckedIOException(new IOException(e));
}
}
@Override
public void setDefaultPaymentMethodForCustomer(String customerId, String paymentMethodId,
@Nullable String currentSubscriptionId) throws SubscriptionInvalidArgumentsException {
CustomerUpdateParams params = CustomerUpdateParams.builder()
.setInvoiceSettings(InvoiceSettings.builder()
.setDefaultPaymentMethod(paymentMethodId)
.build())
.build();
try {
stripeClient.v1().customers().update(customerId, params, commonOptions());
} catch (InvalidRequestException e) {
// Could happen if the paymentMethodId was bunk or the client didn't actually finish setting it up
throw new SubscriptionInvalidArgumentsException(e.getMessage());
} catch (StripeException e) {
throw new UncheckedIOException(new IOException(e));
}
public void setDefaultPaymentMethodForCustomer(final String customerId, final String paymentMethodId,
@Nullable final String currentSubscriptionId) throws SubscriptionInvalidArgumentsException {
final CustomerUpdateParams params = CustomerUpdateParams.builder()
.setInvoiceSettings(InvoiceSettings.builder()
.setDefaultPaymentMethod(paymentMethodId)
.build())
.build();
try {
stripeClient.v1().customers().update(customerId, params, commonOptions());
} catch (final InvalidRequestException e) {
// Could happen if the paymentMethodId was bunk or the client didn't actually finish setting it up
throw new SubscriptionInvalidArgumentsException(e.getMessage());
} catch (final StripeException e) {
throw new UncheckedIOException(new IOException(e));
}
}
@Override
public String createPaymentMethodSetupToken(String customerId) {
SetupIntentCreateParams params = SetupIntentCreateParams.builder()
public String createPaymentMethodSetupToken(final String customerId) {
final SetupIntentCreateParams params = SetupIntentCreateParams.builder()
.setCustomer(customerId)
.build();
try {
return stripeClient.v1().setupIntents().create(params, commonOptions()).getClientSecret();
} catch (StripeException e) {
} catch (final StripeException e) {
throw new UncheckedIOException(new IOException(e));
}
}
@@ -207,70 +206,65 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
}
/**
* Creates a payment intent. May throw a {@link SubscriptionInvalidAmountException} if stripe rejects the
* attempt if the amount is too large or too small
* Creates a payment intent. May throw a {@link SubscriptionInvalidAmountException} if stripe rejects the attempt if
* the amount is too large or too small
*/
public CompletableFuture<PaymentIntent> createPaymentIntent(final String currency,
public PaymentIntent createPaymentIntent(final String currency,
final long amount,
final long level,
@Nullable final ClientPlatform clientPlatform) {
@Nullable final ClientPlatform clientPlatform) throws SubscriptionInvalidAmountException {
return CompletableFuture.supplyAsync(() -> {
final PaymentIntentCreateParams.Builder builder = PaymentIntentCreateParams.builder()
.setAmount(amount)
.setCurrency(currency.toLowerCase(Locale.ROOT))
.setDescription(boostDescription)
.setCaptureMethod(PaymentIntentCreateParams.CaptureMethod.AUTOMATIC)
.putMetadata("level", Long.toString(level));
final PaymentIntentCreateParams.Builder builder = PaymentIntentCreateParams.builder()
.setAmount(amount)
.setCurrency(currency.toLowerCase(Locale.ROOT))
.setDescription(boostDescription)
.setCaptureMethod(PaymentIntentCreateParams.CaptureMethod.AUTOMATIC)
.putMetadata("level", Long.toString(level));
if (clientPlatform != null) {
builder.putMetadata(METADATA_KEY_CLIENT_PLATFORM, clientPlatform.name().toLowerCase());
if (clientPlatform != null) {
builder.putMetadata(METADATA_KEY_CLIENT_PLATFORM, clientPlatform.name().toLowerCase());
}
try {
return stripeClient.v1().paymentIntents().create(builder.build(), commonOptions());
} catch (final StripeException e) {
final String errorCode = e.getCode() == null
? "unknown"
: e.getCode().toLowerCase(Locale.ROOT);
switch (errorCode) {
case "amount_too_small", "amount_too_large" -> throw new SubscriptionInvalidAmountException(errorCode);
default -> throw new RuntimeException(e);
}
try {
return stripeClient.v1().paymentIntents().create(builder.build(), commonOptions());
} catch (StripeException e) {
final String errorCode = e.getCode() == null
? "unknown"
: e.getCode().toLowerCase(Locale.ROOT);
switch (errorCode) {
case "amount_too_small","amount_too_large" ->
throw ExceptionUtils.wrap(new SubscriptionInvalidAmountException(errorCode));
default -> throw new CompletionException(e);
}
}
}, executor);
}
}
public CompletableFuture<Optional<PaymentDetails>> getPaymentDetails(final String paymentIntentId) {
return CompletableFuture.supplyAsync(() -> {
try {
final PaymentIntent paymentIntent = getPaymentIntent(paymentIntentId);
public Optional<PaymentDetails> getPaymentDetails(final String paymentIntentId) throws IOException {
try {
final PaymentIntent paymentIntent = getPaymentIntent(paymentIntentId);
ChargeFailure chargeFailure = null;
if (paymentIntent.getLatestChargeObject() != null) {
final Charge charge = paymentIntent.getLatestChargeObject();
if (charge.getFailureCode() != null || charge.getFailureMessage() != null) {
chargeFailure = createChargeFailure(charge);
}
}
return Optional.of(new PaymentDetails(paymentIntent.getId(),
paymentIntent.getMetadata() == null ? Collections.emptyMap() : paymentIntent.getMetadata(),
getPaymentStatusForStatus(paymentIntent.getStatus()),
Instant.ofEpochSecond(paymentIntent.getCreated()),
chargeFailure));
} catch (StripeException e) {
if (e.getStatusCode() == 404) {
return Optional.empty();
} else {
throw new CompletionException(e);
ChargeFailure chargeFailure = null;
if (paymentIntent.getLatestChargeObject() != null) {
final Charge charge = paymentIntent.getLatestChargeObject();
if (charge.getFailureCode() != null || charge.getFailureMessage() != null) {
chargeFailure = createChargeFailure(charge);
}
}
}, executor);
return Optional.of(new PaymentDetails(paymentIntent.getId(),
paymentIntent.getMetadata() == null ? Collections.emptyMap() : paymentIntent.getMetadata(),
getPaymentStatusForStatus(paymentIntent.getStatus()),
Instant.ofEpochSecond(paymentIntent.getCreated()),
chargeFailure));
} catch (final StripeException e) {
if (e.getStatusCode() == 404) {
return Optional.empty();
} else {
throw new IOException(e);
}
}
}
private static PaymentStatus getPaymentStatusForStatus(String status) {
private static PaymentStatus getPaymentStatusForStatus(final String status) {
return switch (status.toLowerCase(Locale.ROOT)) {
case "processing" -> PaymentStatus.PROCESSING;
case "succeeded" -> PaymentStatus.SUCCEEDED;
@@ -283,13 +277,13 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
}
@Override
public SubscriptionId createSubscription(String customerId, String priceId, long level,
long lastSubscriptionCreatedAt)
public SubscriptionId createSubscription(final String customerId, final String priceId, final long level,
final long lastSubscriptionCreatedAt)
throws SubscriptionProcessorException, SubscriptionInvalidIdempotencyKeyException,
SubscriptionPaymentRequiresActionException {
// this relies on Stripe's idempotency key to avoid creating more than one subscription if the client
// retries this request
SubscriptionCreateParams params = SubscriptionCreateParams.builder()
final SubscriptionCreateParams params = SubscriptionCreateParams.builder()
.setCustomer(customerId)
.setOffSession(true)
.setPaymentBehavior(SubscriptionCreateParams.PaymentBehavior.ERROR_IF_INCOMPLETE)
@@ -307,11 +301,11 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
params,
commonOptions(generateIdempotencyKeyForCreateSubscription(customerId, lastSubscriptionCreatedAt)));
return new SubscriptionId(subscription.getId());
} catch (IdempotencyException e) {
} catch (final IdempotencyException e) {
throw new SubscriptionInvalidIdempotencyKeyException(e.getStripeError().getMessage());
} catch (CardException e) {
} catch (final CardException e) {
throw new SubscriptionProcessorException(getProvider(), createChargeFailureFromCardException(e));
} catch (StripeException e) {
} catch (final StripeException e) {
if ("subscription_payment_intent_requires_action".equals(e.getCode())) {
throw new SubscriptionPaymentRequiresActionException();
}
@@ -320,7 +314,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
}
@Override
public SubscriptionId updateSubscription(Object subscriptionObj, String priceId, long level, String idempotencyKey)
public SubscriptionId updateSubscription(final Object subscriptionObj, final String priceId, final long level, final String idempotencyKey)
throws SubscriptionInvalidIdempotencyKeyException, SubscriptionPaymentRequiresActionException,
SubscriptionProcessorException {
@@ -332,7 +326,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
return createSubscription(subscription.getCustomer(), priceId, level, subscription.getCreated());
}
List<SubscriptionUpdateParams.Item> items = new ArrayList<>();
final List<SubscriptionUpdateParams.Item> items = new ArrayList<>();
try {
final StripeCollection<SubscriptionItem> subscriptionItems = stripeClient.v1().subscriptionItems()
.list(SubscriptionItemListParams.builder().setSubscription(subscription.getId()).build(),
@@ -346,7 +340,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
items.add(SubscriptionUpdateParams.Item.builder()
.setPrice(priceId)
.build());
SubscriptionUpdateParams params = SubscriptionUpdateParams.builder()
final SubscriptionUpdateParams params = SubscriptionUpdateParams.builder()
.putMetadata(METADATA_KEY_LEVEL, Long.toString(level))
// since badge redemption is untrackable by design and unrevokable, subscription changes must be immediate and
@@ -360,56 +354,57 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
final Subscription subscription1 = stripeClient.v1().subscriptions().update(subscription.getId(), params,
commonOptions(generateIdempotencyKeyForSubscriptionUpdate(subscription.getCustomer(), idempotencyKey)));
return new SubscriptionId(subscription1.getId());
} catch (IdempotencyException e) {
} catch (final IdempotencyException e) {
throw new SubscriptionInvalidIdempotencyKeyException(e.getStripeError().getMessage());
} catch (CardException e) {
} catch (final CardException e) {
throw new SubscriptionProcessorException(getProvider(), createChargeFailureFromCardException(e));
} catch (StripeException e) {
} catch (final StripeException e) {
throw new UncheckedIOException(new IOException(e));
}
}
/// Retrieves the subscription object with `latest_invoice.payments` expanded
@Override
public Object getSubscription(String subscriptionId) {
SubscriptionRetrieveParams params = SubscriptionRetrieveParams.builder()
public Object getSubscription(final String subscriptionId) {
final SubscriptionRetrieveParams params = SubscriptionRetrieveParams.builder()
.addExpand("latest_invoice.payments")
.build();
try {
return stripeClient.v1().subscriptions().retrieve(subscriptionId, params, commonOptions());
} catch (StripeException e) {
} catch (final StripeException e) {
throw new UncheckedIOException(new IOException(e));
}
}
/// Retrieves the payment intent object with `latest_charge` expanded
public PaymentIntent getPaymentIntent(String paymentIntentId) throws StripeException {
PaymentIntentRetrieveParams params = PaymentIntentRetrieveParams.builder()
public PaymentIntent getPaymentIntent(final String paymentIntentId) throws StripeException {
final PaymentIntentRetrieveParams params = PaymentIntentRetrieveParams.builder()
.addExpand("latest_charge")
.build();
return stripeClient.v1().paymentIntents().retrieve(paymentIntentId, params, commonOptions());
}
public Charge getCharge(String chargeId) {
ChargeRetrieveParams params = ChargeRetrieveParams.builder()
public Charge getCharge(final String chargeId) {
final ChargeRetrieveParams params = ChargeRetrieveParams.builder()
.build();
try {
return stripeClient.v1().charges().retrieve(chargeId, params, commonOptions());
} catch (StripeException e) {
} catch (final StripeException e) {
throw new UncheckedIOException(new IOException(e));
}
}
@Override
public void cancelAllActiveSubscriptions(String customerId) {
public void cancelAllActiveSubscriptions(final String customerId) {
final Customer customer = getCustomer(customerId);
if (customer == null) {
throw new UncheckedIOException(new IOException("no customer record found for id " + customerId));
}
if (StringUtils.isBlank(customer.getId()) || (!customer.getId().equals(customerId))) {
logger.error("customer ID returned by Stripe ({}) did not match query ({})", customerId, customer.getSubscriptions());
throw new UncheckedIOException(new IOException("unexpected customer ID returned by Stripe"));
}
if (customer == null) {
throw new UncheckedIOException(new IOException("no customer record found for id " + customerId));
}
if (StringUtils.isBlank(customer.getId()) || (!customer.getId().equals(customerId))) {
logger.error("customer ID returned by Stripe ({}) did not match query ({})", customerId,
customer.getSubscriptions());
throw new UncheckedIOException(new IOException("unexpected customer ID returned by Stripe"));
}
final Collection<Subscription> subscriptions = listNonCanceledSubscriptions(customer);
if (subscriptions.stream()
@@ -423,20 +418,20 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
.toList());
}
public Collection<Subscription> listNonCanceledSubscriptions(Customer customer) {
SubscriptionListParams params = SubscriptionListParams.builder()
public Collection<Subscription> listNonCanceledSubscriptions(final Customer customer) {
final SubscriptionListParams params = SubscriptionListParams.builder()
.setCustomer(customer.getId())
.build();
try {
return Lists.newArrayList(
stripeClient.v1().subscriptions().list(params, commonOptions()).autoPagingIterable());
} catch (StripeException e) {
} catch (final StripeException e) {
throw new UncheckedIOException(new IOException(e));
}
}
@VisibleForTesting
void endSubscription(Subscription subscription) {
void endSubscription(final Subscription subscription) {
final SubscriptionStatus status = SubscriptionStatus.forApiValue(subscription.getStatus());
switch (status) {
@@ -459,30 +454,30 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
cancelSubscriptionAtEndOfCurrentPeriod(subscription);
}
}
};
}
}
private void cancelSubscriptionImmediately(Subscription subscription) {
SubscriptionCancelParams params = SubscriptionCancelParams.builder().build();
private void cancelSubscriptionImmediately(final Subscription subscription) {
final SubscriptionCancelParams params = SubscriptionCancelParams.builder().build();
try {
stripeClient.v1().subscriptions().cancel(subscription.getId(), params, commonOptions());
} catch (StripeException e) {
} catch (final StripeException e) {
throw new UncheckedIOException(new IOException(e));
}
}
private void cancelSubscriptionAtEndOfCurrentPeriod(Subscription subscription) {
SubscriptionUpdateParams params = SubscriptionUpdateParams.builder()
private void cancelSubscriptionAtEndOfCurrentPeriod(final Subscription subscription) {
final SubscriptionUpdateParams params = SubscriptionUpdateParams.builder()
.setCancelAtPeriodEnd(true)
.build();
try {
stripeClient.v1().subscriptions().update(subscription.getId(), params, commonOptions());
} catch (StripeException e) {
} catch (final StripeException e) {
throw new UncheckedIOException(new IOException(e));
}
}
public Collection<SubscriptionItem> getItemsForSubscription(Subscription subscription) {
public Collection<SubscriptionItem> getItemsForSubscription(final Subscription subscription) {
try {
final StripeCollection<SubscriptionItem> subscriptionItems = stripeClient.v1().subscriptionItems().list(
SubscriptionItemListParams.builder().setSubscription(subscription.getId()).build(), commonOptions());
@@ -493,7 +488,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
}
}
public Price getPriceForSubscription(Subscription subscription) {
public Price getPriceForSubscription(final Subscription subscription) {
final Collection<SubscriptionItem> subscriptionItems = getItemsForSubscription(subscription);
if (subscriptionItems.isEmpty()) {
throw new IllegalStateException("no items found in subscription " + subscription.getId());
@@ -505,12 +500,12 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
}
}
private Product getProductForSubscription(Subscription subscription) {
private Product getProductForSubscription(final Subscription subscription) {
return getProductForPrice(getPriceForSubscription(subscription).getId());
}
@Override
public LevelAndCurrency getLevelAndCurrencyForSubscription(Object subscriptionObj) {
public LevelAndCurrency getLevelAndCurrencyForSubscription(final Object subscriptionObj) {
final Subscription subscription = getSubscription(subscriptionObj);
final Product product = getProductForSubscription(subscription);
@@ -519,25 +514,25 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
subscription.getCurrency().toLowerCase(Locale.ROOT));
}
public long getLevelForPrice(Price price) {
public long getLevelForPrice(final Price price) {
return getLevelForProduct(getProductForPrice(price.getId()));
}
public Product getProductForPrice(String priceId) {
PriceRetrieveParams params = PriceRetrieveParams.builder().addExpand("product").build();
public Product getProductForPrice(final String priceId) {
final PriceRetrieveParams params = PriceRetrieveParams.builder().addExpand("product").build();
try {
return stripeClient.v1().prices().retrieve(priceId, params, commonOptions()).getProductObject();
} catch (StripeException e) {
} catch (final StripeException e) {
throw new UncheckedIOException(new IOException(e));
}
}
public long getLevelForProduct(Product product) {
public long getLevelForProduct(final Product product) {
return Long.parseLong(product.getMetadata().get(METADATA_KEY_LEVEL));
}
private static ChargeFailure createChargeFailure(final Charge charge) {
Charge.Outcome outcome = charge.getOutcome();
final Charge.Outcome outcome = charge.getOutcome();
return new ChargeFailure(
charge.getFailureCode(),
charge.getFailureMessage(),
@@ -546,7 +541,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
outcome != null ? outcome.getType() : null);
}
private static ChargeFailure createChargeFailureFromCardException(CardException e) {
private static ChargeFailure createChargeFailureFromCardException(final CardException e) {
return new ChargeFailure(
StringUtils.defaultIfBlank(e.getDeclineCode(), e.getCode()),
e.getStripeError().getMessage(),
@@ -583,7 +578,8 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
if (charge.getPaymentMethodDetails() != null
&& charge.getPaymentMethodDetails().getType() != null) {
paymentMethod = getPaymentMethodFromStripeString(charge.getPaymentMethodDetails().getType(), invoice.getId());
paymentMethod = getPaymentMethodFromStripeString(charge.getPaymentMethodDetails().getType(),
invoice.getId());
}
}
}
@@ -604,7 +600,8 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
);
}
private static PaymentMethod getPaymentMethodFromStripeString(final String paymentMethodString, final String invoiceId) {
private static PaymentMethod getPaymentMethodFromStripeString(final String paymentMethodString,
final String invoiceId) {
return switch (paymentMethodString) {
case "sepa_debit" -> PaymentMethod.SEPA_DEBIT;
case "card" -> PaymentMethod.CARD;
@@ -615,7 +612,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
};
}
private Subscription getSubscription(Object subscriptionObj) {
private Subscription getSubscription(final Object subscriptionObj) {
if (!(subscriptionObj instanceof final Subscription subscription)) {
throw new IllegalArgumentException("invalid subscription object: " + subscriptionObj.getClass().getName());
}
@@ -624,18 +621,19 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
}
@Override
public ReceiptItem getReceiptItem(String subscriptionId)
public ReceiptItem getReceiptItem(final String subscriptionId)
throws SubscriptionPaymentRequiredException, SubscriptionReceiptRequestedForOpenPaymentException {
final Invoice invoice = getSubscription(getSubscription(subscriptionId)).getLatestInvoiceObject();
return convertInvoiceToReceipt(invoice, subscriptionId);
}
private ReceiptItem convertInvoiceToReceipt(Invoice latestSubscriptionInvoice, String subscriptionId)
private ReceiptItem convertInvoiceToReceipt(final Invoice latestSubscriptionInvoice, final String subscriptionId)
throws SubscriptionReceiptRequestedForOpenPaymentException, SubscriptionPaymentRequiredException {
if (latestSubscriptionInvoice == null) {
throw new SubscriptionReceiptRequestedForOpenPaymentException();
}
if ("open".equalsIgnoreCase(latestSubscriptionInvoice.getStatus()) || "draft".equalsIgnoreCase(latestSubscriptionInvoice.getStatus())) {
if ("open".equalsIgnoreCase(latestSubscriptionInvoice.getStatus()) || "draft".equalsIgnoreCase(
latestSubscriptionInvoice.getStatus())) {
throw new SubscriptionReceiptRequestedForOpenPaymentException();
}
if (!"paid".equalsIgnoreCase(latestSubscriptionInvoice.getStatus())) {
@@ -660,7 +658,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
}
final Collection<InvoiceLineItem> invoiceLineItems = getInvoiceLineItemsForInvoice(latestSubscriptionInvoice);
Collection<InvoiceLineItem> subscriptionLineItems = invoiceLineItems.stream()
final Collection<InvoiceLineItem> subscriptionLineItems = invoiceLineItems.stream()
.filter(invoiceLineItem -> "subscription_item_details".equalsIgnoreCase(invoiceLineItem.getParent().getType()))
.toList();
if (subscriptionLineItems.isEmpty()) {
@@ -673,11 +671,11 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
+ "; invoiceId=" + latestSubscriptionInvoice.getId() + "; count=" + subscriptionLineItems.size());
}
InvoiceLineItem subscriptionLineItem = subscriptionLineItems.stream().findAny().get();
final InvoiceLineItem subscriptionLineItem = subscriptionLineItems.stream().findAny().get();
return getReceiptForSubscription(subscriptionLineItem, latestSubscriptionInvoice);
}
private ReceiptItem getReceiptForSubscription(InvoiceLineItem subscriptionLineItem, Invoice invoice) {
private ReceiptItem getReceiptForSubscription(final InvoiceLineItem subscriptionLineItem, final Invoice invoice) {
final Instant paidAt;
if (invoice.getStatusTransitions().getPaidAt() != null) {
paidAt = Instant.ofEpochSecond(invoice.getStatusTransitions().getPaidAt());
@@ -693,7 +691,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
getLevelForProduct(product));
}
public Collection<InvoiceLineItem> getInvoiceLineItemsForInvoice(Invoice invoice) {
public Collection<InvoiceLineItem> getInvoiceLineItemsForInvoice(final Invoice invoice) {
try {
final StripeCollection<InvoiceLineItem> lineItems = stripeClient.v1().invoices().lineItems()
.list(invoice.getId(), commonOptions());
@@ -703,31 +701,31 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
}
}
public CompletableFuture<String> getGeneratedSepaIdFromSetupIntent(String setupIntentId) {
return CompletableFuture.supplyAsync(() -> {
SetupIntentRetrieveParams params = SetupIntentRetrieveParams.builder()
.addExpand("latest_attempt")
.build();
try {
final SetupIntent setupIntent = stripeClient.v1().setupIntents().retrieve(setupIntentId, params, commonOptions());
if (setupIntent.getLatestAttemptObject() == null
|| setupIntent.getLatestAttemptObject().getPaymentMethodDetails() == null
|| setupIntent.getLatestAttemptObject().getPaymentMethodDetails().getIdeal() == null
|| setupIntent.getLatestAttemptObject().getPaymentMethodDetails().getIdeal().getGeneratedSepaDebit() == null) {
// This usually indicates that the client has made requests out of order, either by not confirming
// the SetupIntent or not having the user authorize the transaction.
logger.debug("setupIntent {} missing expected fields", setupIntentId);
throw ExceptionUtils.wrap(new SubscriptionProcessorConflictException());
}
return setupIntent.getLatestAttemptObject().getPaymentMethodDetails().getIdeal().getGeneratedSepaDebit();
} catch (StripeException e) {
if (e.getStatusCode() == 404) {
throw ExceptionUtils.wrap(new SubscriptionNotFoundException());
}
logger.error("unexpected error from Stripe when retrieving setupIntent {}", setupIntentId, e);
throw ExceptionUtils.wrap(e);
public String getGeneratedSepaIdFromSetupIntent(final String setupIntentId)
throws SubscriptionNotFoundException, SubscriptionProcessorConflictException, IOException {
final SetupIntentRetrieveParams params = SetupIntentRetrieveParams.builder()
.addExpand("latest_attempt")
.build();
try {
final SetupIntent setupIntent = stripeClient.v1().setupIntents().retrieve(setupIntentId, params, commonOptions());
if (setupIntent.getLatestAttemptObject() == null
|| setupIntent.getLatestAttemptObject().getPaymentMethodDetails() == null
|| setupIntent.getLatestAttemptObject().getPaymentMethodDetails().getIdeal() == null
|| setupIntent.getLatestAttemptObject().getPaymentMethodDetails().getIdeal().getGeneratedSepaDebit()
== null) {
// This usually indicates that the client has made requests out of order, either by not confirming
// the SetupIntent or not having the user authorize the transaction.
logger.debug("setupIntent {} missing expected fields", setupIntentId);
throw new SubscriptionProcessorConflictException();
}
}, executor);
return setupIntent.getLatestAttemptObject().getPaymentMethodDetails().getIdeal().getGeneratedSepaDebit();
} catch (final StripeException e) {
if (e.getStatusCode() == 404) {
throw new SubscriptionNotFoundException();
}
logger.error("unexpected error from Stripe when retrieving setupIntent {}", setupIntentId, e);
throw new IOException(e);
}
}
private Optional<InvoicePayment> getMostRecentInvoicePayment(final Invoice invoice) {
@@ -757,32 +755,32 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
* it is intentionally sending a repeat of the update to level 2 request because user is changing again, so in this
* case we derive idempotency from the client.
*/
private String generateIdempotencyKeyForSubscriptionUpdate(String customerId, String idempotencyKey) {
private String generateIdempotencyKeyForSubscriptionUpdate(final String customerId, final String idempotencyKey) {
return generateIdempotencyKey("subscriptionUpdate", mac -> {
mac.update(customerId.getBytes(StandardCharsets.UTF_8));
mac.update(idempotencyKey.getBytes(StandardCharsets.UTF_8));
});
}
private String generateIdempotencyKeyForSubscriberUser(byte[] subscriberUser) {
private String generateIdempotencyKeyForSubscriberUser(final byte[] subscriberUser) {
return generateIdempotencyKey("subscriberUser", mac -> mac.update(subscriberUser));
}
private String generateIdempotencyKeyForCreateSubscription(String customerId, long lastSubscriptionCreatedAt) {
private String generateIdempotencyKeyForCreateSubscription(final String customerId, final long lastSubscriptionCreatedAt) {
return generateIdempotencyKey("customerId", mac -> {
mac.update(customerId.getBytes(StandardCharsets.UTF_8));
mac.update(Conversions.longToByteArray(lastSubscriptionCreatedAt));
});
}
private String generateIdempotencyKey(String type, Consumer<Mac> byteConsumer) {
private String generateIdempotencyKey(final String type, final Consumer<Mac> byteConsumer) {
try {
Mac mac = Mac.getInstance("HmacSHA256");
final Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(idempotencyKeyGenerator, "HmacSHA256"));
mac.update(type.getBytes(StandardCharsets.UTF_8));
byteConsumer.accept(mac);
return Base64.getUrlEncoder().encodeToString(mac.doFinal());
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
} catch (final NoSuchAlgorithmException | InvalidKeyException e) {
throw new AssertionError(e);
}
}
@@ -0,0 +1,20 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.util;
/// Represents an operation that two argument and returns a result, but may throw a checked exception. Unlike most other
/// functional interfaces, `ThrowingBiFunction` is expected to operate via side-effects.
@FunctionalInterface
public interface ThrowingBiFunction<T, U, R, E extends Exception> {
/// Performs this operation on the given arguments and returns a result.
///
/// @param t the first input argument
/// @param u the second input argument
/// @return the result of applying the function
/// @throws E at the implementation's discretion
R apply(T t, U u) throws E;
}
@@ -0,0 +1,112 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.workers;
import com.google.common.annotations.VisibleForTesting;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.stream.Collectors;
import net.sourceforge.argparse4j.inf.Subparser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.MessagesManager;
import reactor.core.publisher.Flux;
public class ClearExpiredFoundationDbMessagesCommand extends AbstractSinglePassCrawlAccountsCommand {
private final Clock clock;
@VisibleForTesting
static final String DRY_RUN_ARGUMENT = "dry-run";
@VisibleForTesting
static final String BATCH_SIZE_ARGUMENT = "batch-size";
@VisibleForTesting
static final String MESSAGE_TTL_DAYS_ARGUMENT = "message-ttl-days";
@VisibleForTesting
static final String VERSIONSTAMP_TTL_DAYS_ARGUMENT = "versionstamp-ttl-days";
@VisibleForTesting
static final Duration TIMESTAMP_RETENTION_PERIOD = Duration.ofDays(60);
private static final Logger log = LoggerFactory.getLogger(ClearExpiredFoundationDbMessagesCommand.class);
public ClearExpiredFoundationDbMessagesCommand(final Clock clock) {
super("clear-expired-foundationdb-messages", "Removes expired messages from FoundationDB");
this.clock = clock;
}
@Override
public void configure(final Subparser subparser) {
super.configure(subparser);
subparser.addArgument("--dry-run")
.type(Boolean.class)
.dest(DRY_RUN_ARGUMENT)
.required(false)
.setDefault(true)
.help("If true, don't actually delete any messages (but do still make entries in the versionstamp clock)");
subparser.addArgument("--batch-size")
.type(Integer.class)
.dest(BATCH_SIZE_ARGUMENT)
.required(false)
.setDefault(10000)
.help("Maximum number of queues to trim in a single transaction");
subparser.addArgument("--message-ttl-days")
.type(Integer.class)
.dest(MESSAGE_TTL_DAYS_ARGUMENT)
.required(true)
.help("Desired message TTL in days");
subparser.addArgument("--versionstamp-ttl-days")
.type(Integer.class)
.dest(VERSIONSTAMP_TTL_DAYS_ARGUMENT)
.required(false)
.setDefault(180)
.help("Desired versionstamp-clock TTL in days");
}
@Override
protected void crawlAccounts(final Flux<Account> accounts) {
final MessagesManager messagesManager = getCommandDependencies().messagesManager();
// Record the current versionstamp/time pair for the benefit of future runs. Because this job runs regularly, it has
// the dual role of clearing messages and keeping the versionstamp/time mappings populated.
messagesManager.recordFoundationDbVersionstamps();
final int batchSize = getNamespace().getInt(BATCH_SIZE_ARGUMENT);
final boolean dryRun = getNamespace().getBoolean(DRY_RUN_ARGUMENT);
final int messageTtlDays = getNamespace().getInt(MESSAGE_TTL_DAYS_ARGUMENT);
final int versionstampTtlDays = getNamespace().getInt(VERSIONSTAMP_TTL_DAYS_ARGUMENT);
final Instant oldestMessageTime = clock.instant().minus(Duration.ofDays(messageTtlDays));
final Instant oldestVersionstampTime = clock.instant().minus(Duration.ofDays(versionstampTtlDays));
accounts
.buffer(batchSize)
.map(batch -> batch.stream().collect(
Collectors.toMap(
account -> new AciServiceIdentifier(account.getIdentifier(IdentityType.ACI)),
account -> account.getDevices().stream().map(Device::getId).toList())))
.doOnNext(
dryRun ? _ -> {}
: deviceIdsByAccountIdentifier -> messagesManager.deleteFoundationDbMessagesBefore(deviceIdsByAccountIdentifier, oldestMessageTime))
.then()
.block();
messagesManager.expireOldFoundationDbVersionstamps(oldestVersionstampTime);
}
}
@@ -351,7 +351,7 @@ public record CommandDependencies(
final GenericServerSecretParams backupsGenericZkSecretParams;
try {
backupsGenericZkSecretParams =
new GenericServerSecretParams(configuration.getBackupsZkConfig().serverSecret().value());
new GenericServerSecretParams(configuration.getChatZkConfig().serverSecret().value());
} catch (InvalidInputException e) {
throw new IllegalArgumentException(e);
}
@@ -368,7 +368,7 @@ public record CommandDependencies(
secureValueRecoveryBCredentialsGenerator,
secureValueRecoveryBClient,
clock,
dynamicConfigurationManager);
configuration.getBackupConfiguration());
final IssuedReceiptsManager issuedReceiptsManager = new IssuedReceiptsManager(
configuration.getDynamoDbTables().getIssuedReceipts().getTableName(),
@@ -377,7 +377,7 @@ public record CommandDependencies(
configuration.getDynamoDbTables().getIssuedReceipts().getGenerator(),
configuration.getDynamoDbTables().getIssuedReceipts().getmaxIssuedReceiptsPerPaymentId());
final ServerSecretParams zkSecretParams = new ServerSecretParams(configuration.getZkConfig().serverSecret().value());
final ServerSecretParams zkSecretParams = new ServerSecretParams(configuration.getGroupsZkConfig().serverSecret().value());
final ServerZkReceiptOperations zkReceiptOperations = new ServerZkReceiptOperations(zkSecretParams);
GooglePlayBillingManager googlePlayBillingManager = new GooglePlayBillingManager(
new ByteArrayInputStream(configuration.getGooglePlayBilling().credentialsJson().getBytes(StandardCharsets.UTF_8)),
@@ -11,9 +11,14 @@ import "org/signal/chat/tag.proto";
// Provides methods for working with Signal accounts.
service Accounts {
option (require.auth) = AUTH_ONLY_AUTHENTICATED;
// Returns basic identifiers for the authenticated account.
rpc GetAccountIdentity(GetAccountIdentityRequest) returns (GetAccountIdentityResponse) {}
// Returns entitlements for the authenticated account.
rpc GetEntitlements(GetEntitlementsRequest) returns (GetEntitlementsResponse) {}
// Deletes the authenticated account, purging all associated data in the
// process.
rpc DeleteAccount(DeleteAccountRequest) returns (DeleteAccountResponse) {}
@@ -65,6 +70,8 @@ service Accounts {
// Provides methods for looking up Signal accounts. Callers must not provide
// identifying credentials when calling methods in this service.
service AccountsAnonymous {
option (require.auth) = AUTH_ONLY_ANONYMOUS;
// Checks whether an account with the given service identifier exists.
rpc CheckAccountExistence(CheckAccountExistenceRequest) returns (CheckAccountExistenceResponse) {}
@@ -84,6 +91,35 @@ message GetAccountIdentityResponse {
common.AccountIdentifiers account_identifiers = 1;
}
message GetEntitlementsRequest {
}
message GetEntitlementsResponse {
message BadgeEntitlement {
// The id of the badge the account is entitled. Metadata to display for
// badges may be obtained by cross-referencing badge ids with
// ProductConfiguration.GetConfiguration.
string badge_id = 1;
// When the badge expires, in number of seconds since epoch
uint64 expiration_epoch_seconds = 2;
// Whether the badge is currently configured to be visible
bool visible = 3;
}
message BackupEntitlement {
// The backup level of the account
uint64 level = 1;
// When the backup entitlement expires, in number of seconds since epoch
uint64 expiration_epoch_seconds = 2;
}
// Active badges added via Donations.redeemReceipt
repeated BadgeEntitlement badges = 1;
// If present, the backup level set via Backups.redeemReceipt
BackupEntitlement backup = 2;
}
message DeleteAccountRequest {
}
@@ -9,8 +9,11 @@ option java_multiple_files = true;
package org.signal.chat.calling.quality;
import "org/signal/chat/require.proto";
// Provides methods for submitting call quality surveys
service CallQuality {
option (require.auth) = AUTH_ONLY_ANONYMOUS;
// Submits a call quality survey response.
rpc SubmitCallQualitySurvey(SubmitCallQualitySurveyRequest) returns (SubmitCallQualitySurveyResponse) {}
@@ -9,9 +9,12 @@ option java_multiple_files = true;
package org.signal.chat.calling;
import "org/signal/chat/require.proto";
// Provides methods for getting credentials and relay options for one-on-one
// calls.
service Calling {
option (require.auth) = AUTH_ONLY_AUTHENTICATED;
// Retrieves TURN credentials and relay options for one-on-one calls.
rpc GetCallingRelays(GetCallingRelaysRequest) returns (GetCallingRelaysResponse) {}
@@ -30,11 +30,15 @@ message AccountIdentifiers {
repeated ServiceIdentifier service_identifiers = 1;
// The phone number associated with the identified account.
string e164 = 2;
string e164 = 2 [(org.signal.chat.require.e164) = true];
// The username hash (if any) associated with the identified account. May be
// empty if no username is associated with the identified account.
bytes username_hash = 3;
bytes username_hash = 3 [(org.signal.chat.require.exactlySize) = 0, (org.signal.chat.require.exactlySize) = 32];
// The username link handle UUID associated with the identified account.
// May be empty if no username is associated with the identified account.
bytes username_link_handle = 4 [(org.signal.chat.require.exactlySize) = 0, (org.signal.chat.require.exactlySize) = 16];
}
message EcPreKey {
@@ -15,6 +15,7 @@ package org.signal.chat.credentials;
// authenticated user to authenticate in another service or context without
// revealing their identity.
service Credentials {
option (require.auth) = AUTH_ONLY_AUTHENTICATED;
// Generates and returns an external service credentials for the caller.
rpc GetExternalServiceCredentials(GetExternalServiceCredentialsRequest)
@@ -40,6 +41,7 @@ service Credentials {
// revealing an association between the credentials and the caller's identity to
// the server.
service CredentialsAnonymous {
option (require.auth) = AUTH_ONLY_ANONYMOUS;
// Given a list of secure value recovery (SVR) service credentials and a phone
// number, checks and returns which of the provided credentials were generated
@@ -18,6 +18,8 @@ import "org/signal/chat/tag.proto";
// Provides methods for working with devices attached to a Signal account.
service Devices {
option (require.auth) = AUTH_ONLY_AUTHENTICATED;
// Returns a list of devices associated with the caller's account.
rpc GetDevices(GetDevicesRequest) returns (GetDevicesResponse) {}
@@ -18,6 +18,7 @@ import "org/signal/chat/tag.proto";
// Provides methods for working with pre-keys.
service Keys {
option (require.auth) = AUTH_ONLY_AUTHENTICATED;
// Retrieves an approximate count of the number of the various kinds of
// pre-keys stored for the authenticated device.
@@ -57,6 +58,7 @@ service Keys {
// Provides methods for working with pre-keys using "unidentified access"
// credentials.
service KeysAnonymous {
option (require.auth) = AUTH_ONLY_ANONYMOUS;
// Retrieves a set of pre-keys for establishing a session with the targeted
// device or devices. Callers must not submit any self-identifying credentials
@@ -7,7 +7,7 @@ syntax = "proto3";
option java_multiple_files = true;
package org.signal.chat.one_time_donations;
package org.signal.chat.purchase;
import "org/signal/chat/require.proto";
import "org/signal/chat/errors.proto";
@@ -16,9 +16,7 @@ import "org/signal/chat/subscriptions.proto";
// Service for making one-time donation payments (boost and gift)
//
// Note that these are siblings of the RPCs in the Subscriptions service. One-time payments do
// not require the subscription management methods in that service, though the configuration at
// Subscriptions.GetConfiguration is shared between subscription and one-time payments.
// Configuration for one-time donations can be found in ProductConfiguration.
service OneTimeDonations {
option (require.auth) = AUTH_ONLY_ANONYMOUS;
@@ -59,7 +57,7 @@ message CreateBoostRequest {
// The level for the boost payment
uint64 level = 3 [(require.range).min = 1];
// The payment method
subscriptions.PaymentMethod payment_method = 4 [(require.specified) = true];
PaymentMethod payment_method = 4 [(require.specified) = true];
// A donation permit retrieved from Donations.createDonationPermit
bytes donation_permit = 5 [(require.nonEmpty) = true];
}
@@ -78,6 +76,8 @@ message CreateBoostResponse {
errors.FailedPrecondition unsupported_level = 5 [(tag.reason) = "unsupported_level"];
// Donation permit was invalid or already spent
errors.FailedZkAuthentication permit_rejected = 6 [(tag.reason) = "permit_rejected"];
// The amount in the specified currency is not supported by the payment provider
errors.FailedPrecondition invalid_amount = 7 [(tag.reason) = "invalid_amount"];
}
}
@@ -137,6 +137,8 @@ message ConfirmPayPalBoostResponse {
errors.FailedPrecondition unsupported_currency = 3 [(tag.reason) = "unsupported_currency"];
// The requested level is not a valid one-time donation level
errors.FailedPrecondition unsupported_level = 4 [(tag.reason) = "unsupported_level"];
// The payment failed; see charge failure details
ChargeFailure charge_failure = 5 [(tag.reason) = "charge_failure"];
}
}
@@ -146,7 +148,7 @@ message CreateBoostReceiptCredentialsRequest {
// ZK blind-signature receipt credential request bytes
bytes receipt_credential_request = 2 [(require.nonEmpty) = true];
// The processor that handled the payment
subscriptions.PaymentProvider processor = 3 [(require.specified) = true];
PaymentProvider processor = 3 [(require.specified) = true];
}
message CreateBoostReceiptCredentialsResponse {
@@ -158,7 +160,7 @@ message CreateBoostReceiptCredentialsResponse {
// Payment is still processing; client should retry
errors.FailedPrecondition payment_still_processing = 2 [(tag.reason) = "payment_still_processing"];
// Payment failed
subscriptions.PaymentRequired payment_required = 3 [(tag.reason) = "payment_required"];
PaymentRequired payment_required = 3 [(tag.reason) = "payment_required"];
// Payment intent not found
errors.NotFound payment_not_found = 4 [(tag.reason) = "payment_not_found"];
// A receipt credential was already issued for this payment
@@ -9,9 +9,13 @@ option java_multiple_files = true;
package org.signal.chat.payments;
import "org/signal/chat/require.proto";
// Provides methods for working with payments.
service Payments {
option (require.auth) = AUTH_ONLY_AUTHENTICATED;
rpc GetCurrencyConversions(GetCurrencyConversionsRequest) returns (GetCurrencyConversionsResponse) {}
}
@@ -0,0 +1,109 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
syntax = "proto3";
option java_multiple_files = true;
package org.signal.chat.purchase;
import "org/signal/chat/common.proto";
import "org/signal/chat/require.proto";
import "org/signal/chat/tag.proto";
import "org/signal/chat/subscriptions.proto";
// Retrieve product metadata for one-time donations, subscriptions, and backups
service ProductConfiguration {
option (require.auth) = AUTH_ONLY_AUTHENTICATED;
// Returns all configuration for badges, donation subscriptions, backup subscriptions, and one-time donation (
// "boost" and "gift") minimum and suggested amounts.
//
// Product descriptions may contain localized strings. Callers should set
// their language preferences via an "Accept-Language" header on the request
// https://datatracker.ietf.org/doc/html/rfc3282#section-3
rpc GetConfiguration(GetConfigurationRequest) returns (GetConfigurationResponse) {}
}
message GetConfigurationRequest {
// If present, the etag from a prior GetConfigurationResponse. If the
// provided etag matches the current configuration etag, the server may elide
// the configuration response.
bytes etag = 1;
}
message GetConfigurationResponse {
oneof response {
// The full configuration and corresponding ETag.
TaggedConfiguration tagged_configuration = 1;
// The etag in the request matched the current configuration ETag
bool etag_matched = 2 [(tag.reason) = "etag_match"];
}
}
message AmountList {
// NOTE: this is a string instead of a numeric type because it is intended
// for display purposes only
repeated string amounts = 1;
}
message CurrencyConfiguration {
// Minimum one-time donation
// NOTE: this is a string instead of a numeric type because it is intended
// for display purposes only
string minimum = 1;
// Map of one-time donation level IDs to suggested amounts
map<uint64, AmountList> one_time = 2;
// Map of subscription level IDs to the amount charged
map<uint64, string> subscription = 3;
// Map of backup subscription level IDs to the amount charged
map<uint64, string> backup_subscription = 4;
repeated PaymentMethod supported_payment_methods = 5;
}
message LevelConfiguration {
common.Badge badge = 1;
// The duration for which a badge is valid. Present only for
// one-time (boost, gift) badges
optional uint64 badge_duration_seconds = 2;
}
// Configuration for a backup level - use to present appropriate client interfaces
message BackupLevelConfiguration {
// The amount of media storage in bytes that a paying subscriber may store
uint64 storage_allowance_bytes = 1;
// The play billing productID associated with this backup level
string play_product_id = 2;
// The duration, in days, for which your backed up media is retained on the server after you stop refreshing with a paid credential
uint64 media_ttl_days = 3;
}
message BackupConfiguration {
// A map of numeric backup level IDs to level-specific backup configuration
map<uint64, BackupLevelConfiguration> levels = 1;
// The number of days of media a free tier backup user gets
uint64 free_tier_media_days = 2;
}
message Configuration {
// Map of lower-cased ISO 3 currency codes to currency-specific configuration
map<string, CurrencyConfiguration> currencies = 1;
// Map of numeric donation level IDs to level-specific badge configuration
map<uint64, LevelConfiguration> badge_levels = 2;
// Configuration for backup subscription options
BackupConfiguration backup = 3;
// Maximum value of a one-time SEPA donation
string sepa_maximum_euros = 4;
}
message TaggedConfiguration {
Configuration configuration = 1;
// An entity tag for `configuration`. This may be used in subsequent
// requests for the configuration version to optimize bandwidth.
bytes etag = 2;
}
@@ -18,6 +18,8 @@ import "org/signal/chat/tag.proto";
// Provides methods for working with profiles and profile-related data.
service Profile {
option (require.auth) = AUTH_ONLY_AUTHENTICATED;
// Sets profile data and, if needed, returns credentials used by clients to upload a v1 avatar.
rpc SetProfile(SetProfileRequest) returns (SetProfileResponse) {}
@@ -42,6 +44,8 @@ service Profile {
// without an unidentified access key should use the equivalent, authenticated
// methods in `Profile` instead.
service ProfileAnonymous {
option (require.auth) = AUTH_ONLY_ANONYMOUS;
// Retrieves versioned profile data.
rpc GetVersionedProfile(GetVersionedProfileAnonymousRequest) returns (GetVersionedProfileAnonymousResponse) {}
// Retrieves unversioned profile data.
@@ -193,8 +197,14 @@ message GetVersionedProfileRequest {
message GetVersionedProfileAnonymousRequest {
// Contains the data necessary to request a versioned profile.
GetVersionedProfileRequest request = 1 [(require.present) = true];
// The unidentified access key for the targeted account.
bytes unidentified_access_key = 2 [(require.exactlySize) = 16];
oneof authentication {
// The unidentified access key for the targeted account.
bytes unidentified_access_key = 2 [(require.exactlySize) = 16];
// A group send endorsement token for the targeted account.
bytes group_send_token = 3 [(require.nonEmpty) = true];
}
}
message DataEtag {
@@ -286,13 +296,16 @@ message GetUnversionedProfileAnonymousRequest {
message GetUnversionedProfileResult {
// The identity key of the targeted account/identity type.
bytes identity_key = 1;
// A checksum of the unidentified access key for the targeted account.
// A checksum of the unidentified access key for the targeted account. Absent
// if the request was for a PNI.
bytes unidentified_access = 2;
// Whether the account has enabled sealed sender from anyone.
// Whether the account has enabled sealed sender from anyone. Always false
// if the request was for a PNI.
bool unrestricted_unidentified_access = 3;
// A list of capabilities enabled on the account.
repeated common.DeviceCapability capabilities = 4;
// A list of badges associated with the account.
// A list of badges associated with the account. Absent if the request was for
// a PNI.
repeated common.Badge badges = 5;
}
@@ -7,7 +7,7 @@ syntax = "proto3";
option java_multiple_files = true;
package org.signal.chat.subscriptions;
package org.signal.chat.purchase;
import "google/protobuf/empty.proto";
import "org/signal/chat/common.proto";
@@ -15,6 +15,9 @@ import "org/signal/chat/require.proto";
import "org/signal/chat/errors.proto";
import "org/signal/chat/tag.proto";
// Service for creating donation subscriptions
//
// Configuration for subscription levels can be found in ProductConfiguration.
service Subscriptions {
option (require.auth) = AUTH_ONLY_ANONYMOUS;
// Creates a subscriber record if it does not exist, otherwise refreshes its last access time.
@@ -99,10 +102,6 @@ service Subscriptions {
// associated with the old purchaseToken will be cancelled.
rpc SetIapSubscription(SetIapSubscriptionRequest) returns (SetIapSubscriptionResponse) {}
// Returns all configuration for badges, donation subscriptions, backup subscriptions, and one-time donation (
// "boost" and "gift") minimum and suggested amounts.
rpc GetConfiguration(GetConfigurationRequest) returns (GetConfigurationResponse) {}
// Returns a localized bank mandate for the specified bank transfer type
rpc GetBankMandate(GetBankMandateRequest) returns (GetBankMandateResponse) {}
}
@@ -252,6 +251,8 @@ message SetDefaultPaymentMethodResponse {
// subscriberId authentication failure
errors.FailedUnidentifiedAuthorization subscriber_id_mismatch = 3 [(tag.reason) = "subscriber_id_mismatch"];
errors.FailedPrecondition payment_method_not_set_up = 4 [(tag.reason) = "payment_method_not_set_up"];
// Payment processor does not match existing processor associated with the subscription
errors.FailedPrecondition subscription_processor_conflict = 5 [(tag.reason) = "subscription_processor_conflict"];
}
}
@@ -426,65 +427,6 @@ message GetSubscriptionInformationResponse {
}
}
message GetConfigurationRequest {}
message GetConfigurationResponse {
message Badge {
common.Badge badge = 1;
// Present only for one-time (purchasable) badges
optional uint64 duration_seconds = 2;
}
message AmountList {
// NOTE: this is a string instead of a numeric type because it is intended
// for display purposes only
repeated string amounts = 1;
}
message CurrencyConfiguration {
// Minimum one-time donation
// NOTE: this is a string instead of a numeric type because it is intended
// for display purposes only
string minimum = 1;
// Map of one-time donation level IDs to suggested amounts
map<uint64, AmountList> one_time = 2;
// Map of subscription level IDs to the amount charged
map<uint64, string> subscription = 3;
// Map of backup subscription level IDs to the amount charged
map<uint64, string> backup_subscription = 4;
repeated PaymentMethod supported_payment_methods = 5;
}
message LevelConfiguration {
Badge badge = 1;
}
// Configuration for a backup level - use to present appropriate client interfaces
message BackupLevelConfiguration {
// The amount of media storage in bytes that a paying subscriber may store
uint64 storage_allowance_bytes = 1;
// The play billing productID associated with this backup level
string play_product_id = 2;
// The duration, in days, for which your backed up media is retained on the server after you stop refreshing with a paid credential
uint64 media_ttl_days = 3;
}
message BackupConfiguration {
// A map of numeric backup level IDs to level-specific backup configuration
map<uint64, BackupLevelConfiguration> levels = 1;
// The number of days of media a free tier backup user gets
uint64 free_tier_media_days = 2;
}
// Map of lower-cased ISO 3 currency codes to currency-specific configuration
map<string, CurrencyConfiguration> currencies = 1;
// Map of numeric donation level IDs to level-specific badge configuration
map<uint64, LevelConfiguration> levels = 2;
BackupConfiguration backup = 3;
// Maximum value of a one-time SEPA donation
string sepa_maximum_euros = 4;
}
enum BankTransferType {
BANK_TRANSFER_TYPE_UNKNOWN = 0;
BANK_TRANSFER_TYPE_SEPA_DEBIT = 1;
@@ -0,0 +1,147 @@
package org.whispersystems.textsecuregcm;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.whispersystems.textsecuregcm.filters.RemoteAddressFilter.REMOTE_ADDRESS_ATTRIBUTE_NAME;
import io.dropwizard.core.Application;
import io.dropwizard.core.Configuration;
import io.dropwizard.core.server.DefaultServerFactory;
import io.dropwizard.core.setup.Environment;
import io.dropwizard.http2.Http2CConnectorFactory;
import io.dropwizard.jetty.HttpConnectorFactory;
import io.dropwizard.testing.DropwizardTestSupport;
import java.net.URI;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.ee10.websocket.server.config.JettyWebSocketServletContainerInitializer;
import org.eclipse.jetty.http2.client.HTTP2Client;
import org.eclipse.jetty.http2.client.transport.HttpClientTransportOverHTTP2;
import org.eclipse.jetty.io.ClientConnector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.util.component.Graceful;
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.StatusCode;
import org.eclipse.jetty.websocket.client.WebSocketClient;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Timeout;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.filters.PriorityFilter;
import org.whispersystems.textsecuregcm.filters.RemoteAddressFilter;
import org.whispersystems.textsecuregcm.tests.util.TestWebsocketListener;
import org.whispersystems.websocket.WebSocketResourceProviderFactory;
import org.whispersystems.websocket.configuration.WebSocketConfiguration;
import org.whispersystems.websocket.setup.WebSocketEnvironment;
@Timeout(value = 10, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
public class GracefulShutdownIntegrationTest {
private WebSocketClient webSocketClient;
private WebSocketClient h2WebSocketClient;
@BeforeEach
void setUp() throws Exception {
webSocketClient = new WebSocketClient();
webSocketClient.start();
final ClientConnector clientConnector = new ClientConnector();
final HTTP2Client http2Client = new HTTP2Client(clientConnector);
h2WebSocketClient = new WebSocketClient(new HttpClient(new HttpClientTransportOverHTTP2(http2Client)));
h2WebSocketClient.start();
}
@AfterEach
void tearDown() throws Exception {
webSocketClient.stop();
h2WebSocketClient.stop();
}
private DropwizardTestSupport<Configuration> configureApplication() {
final Http2CConnectorFactory applicationConnector = new Http2CConnectorFactory();
applicationConnector.setPort(0);
final HttpConnectorFactory adminConnector = new HttpConnectorFactory();
adminConnector.setPort(0);
final DefaultServerFactory serverFactory = new DefaultServerFactory();
serverFactory.setApplicationConnectors(List.of(applicationConnector));
serverFactory.setAdminConnectors(List.of(adminConnector));
final Configuration configuration = new Configuration();
configuration.setServerFactory(serverFactory);
return new DropwizardTestSupport<>(TestApplication.class, configuration);
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void jettyClosesOpenWebsocketSessions(final boolean useH2) throws Exception {
final DropwizardTestSupport<Configuration> support = configureApplication();
support.before();
try {
final Server server = support.getEnvironment().getApplicationContext().getServer();
final TestWebsocketListener listener = new TestWebsocketListener();
final Session session = (useH2 ? h2WebSocketClient : webSocketClient)
.connect(listener, URI.create("ws://localhost:%d/websocket".formatted(support.getLocalPort())))
.join();
assertTrue(session.isOpen(), "session should be open before shutdown");
// Open websockets should be closed by org.eclipse.jetty.websocket.common.SessionTracker
// during the container Lifecycle stopping phase
final CompletableFuture<Integer> closeObserved = listener.closeFuture();
// Keep the jetty graceful-shutdown window open until the client has observed the close
server.addBean(new Graceful() {
@Override
public CompletableFuture<Void> shutdown() {
return closeObserved.thenApply(_ -> null);
}
@Override
public boolean isShutdown() {
return closeObserved.isDone();
}
});
server.setStopTimeout(TimeUnit.SECONDS.toMillis(10));
server.stop();
final int shutdownCode = closeObserved.get(1, TimeUnit.SECONDS);
// In h2, when jetty shuts down a websocket with abnormal status code (e.g. 1001) it also cancels the underlying
// H2 stream. It's possible that the stream cancellation makes it to the wire before the close frame which will
// be parsed as a 1006, so we accept both . In practice, a 1001 vs an RST_STREAM shouldn't make a difference to a
// client. We just care that jetty is attempting to shut down all websockets during graceful shutdowns.
assertTrue(shutdownCode == StatusCode.SHUTDOWN || (shutdownCode == StatusCode.NO_CODE && useH2));
} finally {
support.after();
}
}
public static class TestApplication extends Application<Configuration> {
@Override
public void run(final Configuration configuration, final Environment environment) throws Exception {
final WebSocketEnvironment<AuthenticatedDevice> webSocketEnvironment =
new WebSocketEnvironment<>(environment, new WebSocketConfiguration());
webSocketEnvironment.jersey().register(new RemoteAddressFilter());
webSocketEnvironment.setAuthenticator(upgradeRequest -> Optional.of(mock(AuthenticatedDevice.class)));
webSocketEnvironment.setConnectListener(context -> {});
final WebSocketResourceProviderFactory<AuthenticatedDevice> webSocketServlet =
new WebSocketResourceProviderFactory<>(webSocketEnvironment, AuthenticatedDevice.class,
REMOTE_ADDRESS_ATTRIBUTE_NAME);
JettyWebSocketServletContainerInitializer.configure(environment.getApplicationContext(),
(servletContext, container) -> {
container.addMapping("/websocket", webSocketServlet);
PriorityFilter.ensureFilter(servletContext, new RemoteAddressFilter());
});
}
}
}
@@ -132,15 +132,6 @@ class WhisperServerServiceTest {
final TestWebsocketListener testWebsocketListener = new TestWebsocketListener();
EXTENSION.getTestSupport().getEnvironment().getApplicationContext().getServer()
.addEventListener(new LifeCycle.Listener() {
@Override
public void lifeCycleStopped(final LifeCycle event) {
// closed by org.eclipse.jetty.websocket.common.SessionTracker during the container Lifecycle stopping phase
assertEquals(StatusCode.SHUTDOWN, testWebsocketListener.closeFuture().getNow(-1));
}
});
// Session is Closeable, but we intentionally keep it open so that we can confirm the container Lifecycle behavior
final Session session = (useH2 ? h2WebSocketClient : webSocketClient).connect(testWebsocketListener,
URI.create(String.format("ws://localhost:%d/v1/websocket/", EXTENSION.getLocalPort())))
@@ -72,14 +72,12 @@ 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.BackupConfiguration;
import org.whispersystems.textsecuregcm.configuration.SecureValueRecoveryConfiguration;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicBackupConfiguration;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.limits.RateLimiter;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecoveryClient;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.storage.DynamoDbExtension;
import org.whispersystems.textsecuregcm.storage.DynamoDbExtensionSchema;
import org.whispersystems.textsecuregcm.util.AttributeValues;
@@ -114,7 +112,7 @@ public class BackupManagerTest {
private final RemoteStorageManager remoteStorageManager = mock(RemoteStorageManager.class);
private final byte[] backupKey = TestRandomUtil.nextBytes(32);
private final UUID aci = UUID.randomUUID();
private final DynamicBackupConfiguration backupConfiguration = new DynamicBackupConfiguration(
private final BackupConfiguration backupConfiguration = new BackupConfiguration(
3, 4, 5, Duration.ofSeconds(30), MAX_TOTAL_MEDIA_BYTES);
@@ -146,11 +144,6 @@ public class BackupManagerTest {
DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(),
DynamoDbExtensionSchema.Tables.BACKUPS.tableName(),
testClock);
@SuppressWarnings("unchecked") final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager =
mock(DynamicConfigurationManager.class);
final DynamicConfiguration dynamicConfiguration = mock(DynamicConfiguration.class);
when(dynamicConfiguration.getBackupConfiguration()).thenReturn(backupConfiguration);
when(dynamicConfigurationManager.getConfiguration()).thenReturn(dynamicConfiguration);
this.backupManager = new BackupManager(
backupsDb,
@@ -162,7 +155,7 @@ public class BackupManagerTest {
svrbCredentialGenerator,
svrbClient,
testClock,
dynamicConfigurationManager);
backupConfiguration);
}
@ParameterizedTest
@@ -83,7 +83,7 @@ public class ConfiguredProfileBadgeConverterTest {
return objects;
}
};
return new BadgesConfiguration(badges, List.of(), Map.of());
return new BadgesConfiguration(badges, Map.of());
}
private BadgeConfiguration getBadge(BadgesConfiguration badgesConfiguration, int i) {
@@ -75,7 +75,6 @@ class DonationControllerTest {
List.of(new BadgeSvg("sl", "sd"), new BadgeSvg("ml", "md"), new BadgeSvg("ll", "ld"))),
new BadgeConfiguration("TEST3", "testing", List.of("l", "m", "h", "x", "xx", "xxx"), "SVG",
List.of(new BadgeSvg("sl", "sd"), new BadgeSvg("ml", "md"), new BadgeSvg("ll", "ld")))),
List.of("TEST"),
Map.of(1L, "TEST1", 2L, "TEST2", 3L, "TEST3"));
}
@@ -20,6 +20,7 @@ import io.dropwizard.testing.junit5.DropwizardExtensionsSupport;
import io.dropwizard.testing.junit5.ResourceExtension;
import jakarta.ws.rs.client.Entity;
import jakarta.ws.rs.core.Response;
import java.io.IOException;
import java.time.Instant;
import java.util.Base64;
import java.util.Collections;
@@ -55,6 +56,7 @@ import org.whispersystems.textsecuregcm.subscriptions.PaymentDetails;
import org.whispersystems.textsecuregcm.subscriptions.PaymentMethod;
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
import org.whispersystems.textsecuregcm.subscriptions.PaymentStatus;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidAmountException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorException;
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
import org.whispersystems.textsecuregcm.util.HeaderUtils;
@@ -179,13 +181,13 @@ class OneTimeDonationControllerTest extends AbstractV1SubscriptionControllerTest
@ParameterizedTest
@ValueSource(booleans = {true, false})
void testCreateBoostPaymentIntent(final boolean donationPermitSpendOk) {
void testCreateBoostPaymentIntent(final boolean donationPermitSpendOk) throws SubscriptionInvalidAmountException {
when(DONATION_PERMITS.spend(any(byte[].class), any(Instant.class))).thenReturn(donationPermitSpendOk);
when(STRIPE_MANAGER.getSupportedCurrenciesForPaymentMethod(PaymentMethod.CARD))
.thenReturn(Set.of("usd", "jpy", "bif", "eur"));
when(STRIPE_MANAGER.createPaymentIntent(anyString(), anyLong(), anyLong(), any()))
.thenReturn(CompletableFuture.completedFuture(PAYMENT_INTENT));
.thenReturn(PAYMENT_INTENT);
String clientSecret = "some_client_secret";
when(PAYMENT_INTENT.getClientSecret()).thenReturn(clientSecret);
@@ -202,13 +204,13 @@ class OneTimeDonationControllerTest extends AbstractV1SubscriptionControllerTest
}
@Test
void testCreateBoostPayPal() {
void testCreateBoostPayPal() throws IOException {
final BraintreeManager.PayPalOneTimePaymentApprovalDetails payPalOneTimePaymentApprovalDetails = mock(
BraintreeManager.PayPalOneTimePaymentApprovalDetails.class);
when(BRAINTREE_MANAGER.getSupportedCurrenciesForPaymentMethod(PaymentMethod.PAYPAL))
.thenReturn(Set.of("usd", "jpy", "bif", "eur"));
when(BRAINTREE_MANAGER.createOneTimePayment(anyString(), anyLong(), anyString(), anyString(), anyString(), anyString()))
.thenReturn(CompletableFuture.completedFuture(payPalOneTimePaymentApprovalDetails));
.thenReturn(payPalOneTimePaymentApprovalDetails);
when(payPalOneTimePaymentApprovalDetails.approvalUrl()).thenReturn("approvalUrl");
when(payPalOneTimePaymentApprovalDetails.paymentId()).thenReturn("someId");
@@ -239,14 +241,15 @@ class OneTimeDonationControllerTest extends AbstractV1SubscriptionControllerTest
@ParameterizedTest
@MethodSource
void createBoostReceiptPaymentRequired(final ChargeFailure chargeFailure, boolean expectChargeFailure) {
when(STRIPE_MANAGER.getPaymentDetails(any())).thenReturn(CompletableFuture.completedFuture(Optional.of(new PaymentDetails(
void createBoostReceiptPaymentRequired(final ChargeFailure chargeFailure, boolean expectChargeFailure)
throws IOException {
when(STRIPE_MANAGER.getPaymentDetails(any())).thenReturn(Optional.of(new PaymentDetails(
"id",
Collections.emptyMap(),
PaymentStatus.FAILED,
Instant.now(),
chargeFailure))
));
);
try (Response response = RESOURCE_EXTENSION.target("/v1/subscription/boost/receipt_credentials")
.request()
.post(Entity.json("""
@@ -281,13 +284,13 @@ class OneTimeDonationControllerTest extends AbstractV1SubscriptionControllerTest
}
@Test
void confirmPaypalBoostProcessorError() {
void confirmPaypalBoostProcessorError() throws SubscriptionProcessorException, IOException {
when(BRAINTREE_MANAGER.getSupportedCurrenciesForPaymentMethod(PaymentMethod.PAYPAL))
.thenReturn(Set.of("usd", "jpy", "bif", "eur"));
when(BRAINTREE_MANAGER.captureOneTimePayment(anyString(), anyString(), anyString(), anyString(), anyLong(),
anyLong(), any()))
.thenReturn(CompletableFuture.failedFuture(new SubscriptionProcessorException(PaymentProvider.BRAINTREE,
new ChargeFailure("2046", "Declined", null, null, null))));
.thenThrow(new SubscriptionProcessorException(PaymentProvider.BRAINTREE,
new ChargeFailure("2046", "Declined", null, null, null)));
try (Response response = RESOURCE_EXTENSION.target("/v1/subscription/boost/paypal/confirm")
.request()
@@ -323,12 +326,12 @@ class OneTimeDonationControllerTest extends AbstractV1SubscriptionControllerTest
ServerSecretParams.generate().getPublicParams()).createReceiptCredentialRequestContext(
new ReceiptSerial(new byte[ReceiptSerial.SIZE])).getRequest();
when(STRIPE_MANAGER.getPaymentDetails(any())).thenReturn(CompletableFuture.completedFuture(Optional.of(new PaymentDetails(
when(STRIPE_MANAGER.getPaymentDetails(any())).thenReturn(Optional.of(new PaymentDetails(
"id",
Collections.emptyMap(),
PaymentStatus.SUCCEEDED,
Instant.now(),
null))));
null)));
doThrow(WriteConflictException.class).when(ISSUED_RECEIPTS_MANAGER).recordIssuance(any(), any(), any(), any());
try (Response response = RESOURCE_EXTENSION.target("/v1/subscription/boost/receipt_credentials")
@@ -168,7 +168,7 @@ class ProfileControllerTest {
new BadgeConfiguration("TEST1", "testing", List.of("l", "m", "h", "x", "xx", "xxx"), "SVG", List.of(new BadgeSvg("sl", "sd"), new BadgeSvg("ml", "md"), new BadgeSvg("ll", "ld"))),
new BadgeConfiguration("TEST2", "testing", List.of("l", "m", "h", "x", "xx", "xxx"), "SVG", List.of(new BadgeSvg("sl", "sd"), new BadgeSvg("ml", "md"), new BadgeSvg("ll", "ld"))),
new BadgeConfiguration("TEST3", "testing", List.of("l", "m", "h", "x", "xx", "xxx"), "SVG", List.of(new BadgeSvg("sl", "sd"), new BadgeSvg("ml", "md"), new BadgeSvg("ll", "ld")))
), List.of("TEST1"), Map.of(1L, "TEST1", 2L, "TEST2", 3L, "TEST3")),
), Map.of(1L, "TEST1", 2L, "TEST2", 3L, "TEST3")),
postPolicyGenerator,
serverSecretParams,
zkProfileOperations,
@@ -61,15 +61,12 @@ import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.badges.BadgeTranslator;
import org.whispersystems.textsecuregcm.configuration.SubscriptionConfiguration;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicBackupConfiguration;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.controllers.SubscriptionController.GetBankMandateResponse;
import org.whispersystems.textsecuregcm.controllers.SubscriptionController.GetSubscriptionConfigurationResponse;
import org.whispersystems.textsecuregcm.entities.Badge;
import org.whispersystems.textsecuregcm.entities.BadgeSvg;
import org.whispersystems.textsecuregcm.mappers.CompletionExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.SubscriptionExceptionMapper;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.storage.PaymentTime;
import org.whispersystems.textsecuregcm.storage.SubscriptionManager;
import org.whispersystems.textsecuregcm.storage.Subscriptions;
@@ -112,12 +109,11 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest {
private static final ServerZkReceiptOperations ZK_OPS = mock(ServerZkReceiptOperations.class);
private static final BadgeTranslator BADGE_TRANSLATOR = mock(BadgeTranslator.class);
private static final BankMandateTranslator BANK_MANDATE_TRANSLATOR = mock(BankMandateTranslator.class);
private static final DynamicConfigurationManager<DynamicConfiguration> DYNAMIC_CONFIGURATION_MANAGER = mock(DynamicConfigurationManager.class);
private final static SubscriptionController SUBSCRIPTION_CONTROLLER = new SubscriptionController(CLOCK,
SUBSCRIPTION_CONFIG, ONETIME_CONFIG,
new SubscriptionManager(SUBSCRIPTIONS, List.of(STRIPE_MANAGER, BRAINTREE_MANAGER, PLAY_MANAGER, APPSTORE_MANAGER),
ZK_OPS, ISSUED_RECEIPTS_MANAGER), STRIPE_MANAGER, BRAINTREE_MANAGER, PLAY_MANAGER, APPSTORE_MANAGER,
BADGE_TRANSLATOR, BANK_MANDATE_TRANSLATOR, DONATION_PERMITS_MANAGER, DYNAMIC_CONFIGURATION_MANAGER);
BADGE_TRANSLATOR, BANK_MANDATE_TRANSLATOR, DONATION_PERMITS_MANAGER, MAX_TOTAL_BACKUP_MEDIA_BYTES);
private static final ResourceExtension RESOURCE_EXTENSION = ResourceExtension.builder()
.addProperty(ServerProperties.UNWRAP_COMPLETION_STAGE_IN_WRITER_ENABLE, Boolean.TRUE)
.addProvider(AuthHelper.getAuthFilter())
@@ -139,10 +135,6 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest {
when(STRIPE_MANAGER.getProvider()).thenReturn(PaymentProvider.STRIPE);
when(BRAINTREE_MANAGER.getProvider()).thenReturn(PaymentProvider.BRAINTREE);
final DynamicConfiguration dynamicConfiguration = mock(DynamicConfiguration.class);
when(dynamicConfiguration.getBackupConfiguration())
.thenReturn(new DynamicBackupConfiguration(null, null, null, null, MAX_TOTAL_BACKUP_MEDIA_BYTES));
when(DYNAMIC_CONFIGURATION_MANAGER.getConfiguration()).thenReturn(dynamicConfiguration);
List.of(STRIPE_MANAGER, BRAINTREE_MANAGER)
.forEach(manager -> when(manager.supportsPaymentMethod(any()))
@@ -5,6 +5,7 @@
package org.whispersystems.textsecuregcm.grpc;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -21,6 +22,7 @@ import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.protobuf.ByteString;
import io.grpc.Status;
import java.time.Duration;
import java.time.Instant;
import java.util.HexFormat;
import java.util.List;
import java.util.Optional;
@@ -46,6 +48,8 @@ import org.signal.chat.account.DeleteUsernameHashRequest;
import org.signal.chat.account.DeleteUsernameLinkRequest;
import org.signal.chat.account.GetAccountIdentityRequest;
import org.signal.chat.account.GetAccountIdentityResponse;
import org.signal.chat.account.GetEntitlementsRequest;
import org.signal.chat.account.GetEntitlementsResponse;
import org.signal.chat.account.ReserveUsernameHashRequest;
import org.signal.chat.account.ReserveUsernameHashResponse;
import org.signal.chat.account.SetDiscoverableByPhoneNumberRequest;
@@ -73,12 +77,14 @@ import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier;
import org.whispersystems.textsecuregcm.limits.RateLimiter;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountBadge;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
import org.whispersystems.textsecuregcm.storage.UsernameHashNotAvailableException;
import org.whispersystems.textsecuregcm.storage.UsernameReservationNotFoundException;
import org.whispersystems.textsecuregcm.tests.util.AccountsHelper;
import org.whispersystems.textsecuregcm.util.TestClock;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
import org.whispersystems.textsecuregcm.util.UsernameHashZkProofVerifier;
@@ -97,6 +103,8 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
@Mock
private RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager;
private final TestClock testClock = TestClock.pinned(Instant.now());
@Override
protected AccountsGrpcService createServiceBeforeEachTest() {
AccountsHelper.setupMockUpdate(accountsManager);
@@ -111,7 +119,8 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
return new AccountsGrpcService(accountsManager,
rateLimiters,
usernameHashZkProofVerifier,
registrationRecoveryPasswordsManager);
registrationRecoveryPasswordsManager,
testClock);
}
@Test
@@ -121,12 +130,14 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
PhoneNumberUtil.getInstance().getExampleNumber("US"), PhoneNumberUtil.PhoneNumberFormat.E164);
final byte[] usernameHash = TestRandomUtil.nextBytes(32);
final UUID usernameLinkHandle = UUID.randomUUID();
final Account account = mock(Account.class);
when(account.getUuid()).thenReturn(AUTHENTICATED_ACI);
when(account.getPhoneNumberIdentifier()).thenReturn(phoneNumberIdentifier);
when(account.getNumber()).thenReturn(e164);
when(account.getUsernameHash()).thenReturn(Optional.of(usernameHash));
when(account.getUsernameLinkHandle()).thenReturn(usernameLinkHandle);
when(accountsManager.getByAccountIdentifier(AUTHENTICATED_ACI))
.thenReturn(Optional.of(account));
@@ -137,6 +148,7 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
.addServiceIdentifiers(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(new PniServiceIdentifier(phoneNumberIdentifier)))
.setE164(e164)
.setUsernameHash(ByteString.copyFrom(usernameHash))
.setUsernameLinkHandle(UUIDUtil.toByteString(usernameLinkHandle))
.build())
.build();
@@ -762,4 +774,41 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
verify(accountsManager, never()).update(any(UUID.class), any());
verify(account, never()).setZkCredentialKey(any());
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void getEntitlements(final boolean expired) {
final Account account = mock(Account.class);
final Instant expiration = expired
? testClock.instant().minus(Duration.ofDays(1))
: testClock.instant().plus(Duration.ofMillis(1));
final AccountBadge badge1 = new AccountBadge("badge1", expiration, true);
final AccountBadge badge2 = new AccountBadge("badge2", expiration, true);
when(account.getBackupVoucher()).thenReturn(new Account.BackupVoucher(100, expiration));
when(account.getBadges()).thenReturn(List.of(badge1, badge2));
when(account.getUuid()).thenReturn(AUTHENTICATED_ACI);
when(accountsManager.getByAccountIdentifier(AUTHENTICATED_ACI)).thenReturn(Optional.of(account));
final GetEntitlementsResponse entitlements = authenticatedServiceStub()
.getEntitlements(GetEntitlementsRequest.newBuilder().build());
if (expired) {
assertThat(entitlements.getBadgesCount()).isEqualTo(0);
assertThat(entitlements.hasBackup()).isFalse();
} else {
assertThat(entitlements.getBadges(0)).isEqualTo(toBadgeEntitlement(badge1));
assertThat(entitlements.getBadges(1)).isEqualTo(toBadgeEntitlement(badge2));
assertThat(entitlements.getBackup().getLevel()).isEqualTo(100);
assertThat(entitlements.getBackup().getExpirationEpochSeconds()).isEqualTo(expiration.getEpochSecond());
}
}
private static GetEntitlementsResponse.BadgeEntitlement toBadgeEntitlement(AccountBadge badge) {
return GetEntitlementsResponse.BadgeEntitlement.newBuilder()
.setExpirationEpochSeconds(badge.expiration().getEpochSecond())
.setBadgeId(badge.id())
.setVisible(badge.visible())
.build();
}
}
@@ -11,6 +11,7 @@ import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyByte;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.whispersystems.textsecuregcm.grpc.GrpcTestUtils.assertStatusException;
@@ -334,7 +335,9 @@ class DevicesGrpcServiceTest extends SimpleBaseGrpcTest<DevicesGrpcService, Devi
final SetPushTokenResponse ignored = authenticatedServiceStub().setPushToken(request);
verify(accountsManager, never()).updateDevice(any(), anyByte(), any());
// Update push token even if it matches the stored value for apns (to update the timestamp)
verify(accountsManager, apnsToken == null ? never() : times(1))
.updateDevice(any(), anyByte(), any());
}
private static Stream<Arguments> setPushTokenUnchanged() {
@@ -0,0 +1,39 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.google.protobuf.Any;
import com.google.rpc.ErrorInfo;
import io.grpc.StatusRuntimeException;
import io.grpc.protobuf.StatusProto;
import java.util.List;
import java.util.UUID;
import org.junit.jupiter.api.Test;
import org.signal.chat.common.IdentityType;
import org.signal.chat.common.ServiceIdentifier;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
class GrpcExceptionsTest {
@Test
void streamClosed() {
final ServiceIdentifier message = ServiceIdentifier.newBuilder().setIdentityType(IdentityType.IDENTITY_TYPE_ACI)
.setUuid(UUIDUtil.toByteString(UUID.randomUUID()))
.build();
final StatusRuntimeException statusRuntimeException = GrpcExceptions.streamClosed(message);
final com.google.rpc.Status status = StatusProto.fromThrowable(statusRuntimeException);
final List<Any> details = status.getDetailsList();
assertEquals(2, details.size());
assertEquals(1, details.stream().filter(any -> any.is(ErrorInfo.class)).count());
final Any packed = details.stream().filter(any -> any.is(ServiceIdentifier.class)).findFirst().orElseThrow();
assertEquals("type.googleapis.com/org.signal.chat.common.ServiceIdentifier", packed.getTypeUrl(), """
The generated typeUrl for a packed Any message has changed. gRPC clients may rely on stable typeUrls
scheme to distinguish `details` in error metadata
""");
}
}
@@ -18,30 +18,30 @@ import com.google.common.net.InetAddresses;
import com.google.protobuf.ByteString;
import com.stripe.model.PaymentIntent;
import jakarta.annotation.Nullable;
import java.io.IOException;
import java.time.Instant;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.mockito.Mock;
import org.signal.chat.one_time_donations.ConfirmPayPalBoostRequest;
import org.signal.chat.one_time_donations.ConfirmPayPalBoostResponse;
import org.signal.chat.one_time_donations.CreateBoostReceiptCredentialsRequest;
import org.signal.chat.one_time_donations.CreateBoostReceiptCredentialsResponse;
import org.signal.chat.one_time_donations.CreateBoostRequest;
import org.signal.chat.one_time_donations.CreateBoostResponse;
import org.signal.chat.one_time_donations.CreatePayPalBoostRequest;
import org.signal.chat.one_time_donations.CreatePayPalBoostResponse;
import org.signal.chat.one_time_donations.OneTimeDonationsGrpc;
import org.signal.chat.subscriptions.PaymentMethod;
import org.signal.chat.subscriptions.PaymentProvider;
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.OneTimeDonationsGrpc;
import org.signal.chat.purchase.PaymentMethod;
import org.signal.chat.purchase.PaymentProvider;
import org.signal.libsignal.zkgroup.ServerSecretParams;
import org.signal.libsignal.zkgroup.VerificationFailedException;
import org.signal.libsignal.zkgroup.donation.DonationPermit;
@@ -66,6 +66,8 @@ import org.whispersystems.textsecuregcm.subscriptions.PayPalDonationsTranslator;
import org.whispersystems.textsecuregcm.subscriptions.PaymentDetails;
import org.whispersystems.textsecuregcm.subscriptions.PaymentStatus;
import org.whispersystems.textsecuregcm.subscriptions.StripeManager;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidAmountException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorException;
import org.whispersystems.textsecuregcm.tests.util.SubscriptionConfigTestHelper;
import org.whispersystems.textsecuregcm.util.TestClock;
@@ -135,14 +137,14 @@ public class OneTimeDonationsGrpcServiceTest extends
}
@Test
void createBoost() {
void createBoost() throws SubscriptionInvalidAmountException {
final PaymentIntent paymentIntent = mock(PaymentIntent.class);
when(paymentIntent.getClientSecret()).thenReturn("test-client-secret");
when(stripeManager.getSupportedCurrenciesForPaymentMethod(
org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.CARD))
.thenReturn(Set.of("usd"));
when(stripeManager.createPaymentIntent(any(), anyLong(), anyLong(), any()))
.thenReturn(CompletableFuture.completedFuture(paymentIntent));
.thenReturn(paymentIntent);
final CreateBoostResponse response = unauthenticatedServiceStub().createBoost(
CreateBoostRequest.newBuilder()
@@ -212,7 +214,7 @@ public class OneTimeDonationsGrpcServiceTest extends
}
@Test
void createPayPalBoost() {
void createPayPalBoost() throws IOException {
final BraintreeManager.PayPalOneTimePaymentApprovalDetails approvalDetails =
mock(BraintreeManager.PayPalOneTimePaymentApprovalDetails.class);
when(approvalDetails.approvalUrl()).thenReturn("test-approval-url");
@@ -224,7 +226,7 @@ public class OneTimeDonationsGrpcServiceTest extends
.thenReturn("Donation to Signal Technology Foundation");
when(braintreeManager.createOneTimePayment(anyString(), anyLong(), anyString(), anyString(), anyString(),
anyString()))
.thenReturn(CompletableFuture.completedFuture(approvalDetails));
.thenReturn(approvalDetails);
final CreatePayPalBoostResponse response = unauthenticatedServiceStub().createPayPalBoost(
CreatePayPalBoostRequest.newBuilder()
@@ -241,14 +243,14 @@ public class OneTimeDonationsGrpcServiceTest extends
}
@Test
void confirmPayPalBoost() {
void confirmPayPalBoost() throws SubscriptionProcessorException, IOException {
when(braintreeManager.getSupportedCurrenciesForPaymentMethod(
org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.PAYPAL))
.thenReturn(Set.of("usd"));
when(braintreeManager.captureOneTimePayment(anyString(), anyString(), anyString(), anyString(), anyLong(),
anyLong(), any()))
.thenReturn(CompletableFuture.completedFuture(
new BraintreeManager.PayPalChargeSuccessDetails("test-id")));
.thenReturn(
new BraintreeManager.PayPalChargeSuccessDetails("test-id"));
final ConfirmPayPalBoostResponse response = unauthenticatedServiceStub().confirmPayPalBoost(
ConfirmPayPalBoostRequest.newBuilder()
@@ -268,10 +270,10 @@ public class OneTimeDonationsGrpcServiceTest extends
@MethodSource
void createBoostReceiptCredentialsPaymentRequired(
@Nullable final ChargeFailure chargeFailure,
final boolean expectChargeFailure) {
when(stripeManager.getPaymentDetails(any())).thenReturn(CompletableFuture.completedFuture(
final boolean expectChargeFailure) throws IOException {
when(stripeManager.getPaymentDetails(any())).thenReturn(
Optional.of(new PaymentDetails("id", Collections.emptyMap(), PaymentStatus.FAILED,
clock.instant(), chargeFailure))));
clock.instant(), chargeFailure)));
final CreateBoostReceiptCredentialsResponse response =
unauthenticatedServiceStub().createBoostReceiptCredentials(
@@ -303,9 +305,9 @@ public class OneTimeDonationsGrpcServiceTest extends
ServerSecretParams.generate().getPublicParams()).createReceiptCredentialRequestContext(
new ReceiptSerial(new byte[ReceiptSerial.SIZE])).getRequest();
when(stripeManager.getPaymentDetails(any())).thenReturn(CompletableFuture.completedFuture(
when(stripeManager.getPaymentDetails(any())).thenReturn(
Optional.of(new PaymentDetails("id", Collections.emptyMap(), PaymentStatus.SUCCEEDED,
clock.instant(), null))));
clock.instant(), null)));
doThrow(WriteConflictException.class).when(issuedReceiptsManager)
.recordIssuance(any(), any(), any(), any());
@@ -0,0 +1,220 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.google.common.net.InetAddresses;
import com.google.protobuf.ByteString;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.signal.chat.purchase.BackupLevelConfiguration;
import org.signal.chat.purchase.Configuration;
import org.signal.chat.purchase.CurrencyConfiguration;
import org.signal.chat.purchase.GetConfigurationRequest;
import org.signal.chat.purchase.GetConfigurationResponse;
import org.signal.chat.purchase.PaymentMethod;
import org.signal.chat.purchase.ProductConfigurationGrpc;
import org.whispersystems.textsecuregcm.badges.BadgeTranslator;
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration;
import org.whispersystems.textsecuregcm.configuration.SubscriptionConfiguration;
import org.whispersystems.textsecuregcm.entities.Badge;
import org.whispersystems.textsecuregcm.entities.BadgeSvg;
import org.whispersystems.textsecuregcm.subscriptions.BraintreeManager;
import org.whispersystems.textsecuregcm.subscriptions.StripeManager;
import org.whispersystems.textsecuregcm.tests.util.SubscriptionConfigTestHelper;
public class ProductConfigurationGrpcServiceTest extends
SimpleBaseGrpcTest<ProductConfigurationGrpcService, ProductConfigurationGrpc.ProductConfigurationBlockingStub> {
private final SubscriptionConfiguration subscriptionConfiguration =
SubscriptionConfigTestHelper.getSubscriptionConfig();
private final OneTimeDonationConfiguration oneTimeDonationConfiguration =
SubscriptionConfigTestHelper.getOneTimeConfig();
@Mock
private StripeManager stripeManager;
@Mock
private BraintreeManager braintreeManager;
@Mock
private BadgeTranslator badgeTranslator;
@Override
protected ProductConfigurationGrpcService createServiceBeforeEachTest() {
getMockRequestAttributesInterceptor().setRequestAttributes(
new RequestAttributes(InetAddresses.forString("127.0.0.1"), null, "en-us"));
when(stripeManager.supportsPaymentMethod(any())).thenCallRealMethod();
when(stripeManager.getSupportedCurrenciesForPaymentMethod(
org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.CARD))
.thenReturn(Set.of("usd", "jpy", "bif", "eur"));
when(stripeManager.getSupportedCurrenciesForPaymentMethod(
org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.SEPA_DEBIT))
.thenReturn(Set.of("eur"));
when(stripeManager.getSupportedCurrenciesForPaymentMethod(
org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.IDEAL))
.thenReturn(Set.of("eur"));
when(braintreeManager.supportsPaymentMethod(any())).thenCallRealMethod();
when(braintreeManager.getSupportedCurrenciesForPaymentMethod(
org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.PAYPAL))
.thenReturn(Set.of("usd", "jpy"));
when(badgeTranslator.translate(any(), eq("B1"))).thenReturn(new Badge("B1", "cat1", "name1", "desc1",
List.of("l", "m", "h", "x", "xx", "xxx"), "SVG", List.of(new BadgeSvg("sl", "sd"))));
when(badgeTranslator.translate(any(), eq("B2"))).thenReturn(new Badge("B2", "cat2", "name2", "desc2",
List.of("l", "m", "h", "x", "xx", "xxx"), "SVG", List.of(new BadgeSvg("sl", "sd"))));
when(badgeTranslator.translate(any(), eq("B3"))).thenReturn(new Badge("B3", "cat3", "name3", "desc3",
List.of("l", "m", "h", "x", "xx", "xxx"), "SVG", List.of(new BadgeSvg("sl", "sd"))));
when(badgeTranslator.translate(any(), eq("BOOST"))).thenReturn(new Badge("BOOST", "boost1", "boost1", "boost1",
List.of("l", "m", "h", "x", "xx", "xxx"), "SVG", List.of(new BadgeSvg("sl", "sd"))));
when(badgeTranslator.translate(any(), eq("GIFT"))).thenReturn(new Badge("GIFT", "gift1", "gift1", "gift1",
List.of("l", "m", "h", "x", "xx", "xxx"), "SVG", List.of(new BadgeSvg("sl", "sd"))));
when(badgeTranslator.resolveLocale(any())).thenReturn(Locale.US);
return new ProductConfigurationGrpcService(subscriptionConfiguration, oneTimeDonationConfiguration,
List.of(stripeManager, braintreeManager), badgeTranslator, 1234L);
}
private void checkConfiguration(final Configuration configuration) {
assertEquals("10000", configuration.getSepaMaximumEuros());
assertEquals(30L, configuration.getBackup().getFreeTierMediaDays());
final BackupLevelConfiguration backupLevel =
configuration.getBackup().getLevelsOrThrow(201L);
assertEquals(1234L, backupLevel.getStorageAllowanceBytes());
assertEquals("testPlayProductId", backupLevel.getPlayProductId());
assertEquals(40L, backupLevel.getMediaTtlDays());
final CurrencyConfiguration usd = configuration.getCurrenciesOrThrow("usd");
assertEquals("2.50", usd.getMinimum());
assertEquals(List.of(PaymentMethod.PAYMENT_METHOD_CARD, PaymentMethod.PAYMENT_METHOD_PAYPAL),
usd.getSupportedPaymentMethodsList());
assertEquals(List.of("5.50", "6", "7", "8", "9", "10"), usd.getOneTimeOrThrow(1L).getAmountsList());
assertEquals(List.of("20"), usd.getOneTimeOrThrow(100L).getAmountsList());
assertEquals(Map.of(5L, "5", 15L, "15", 35L, "35"), usd.getSubscriptionMap());
assertEquals(Map.of(201L, "5"), usd.getBackupSubscriptionMap());
final CurrencyConfiguration jpy = configuration.getCurrenciesOrThrow("jpy");
assertEquals("250", jpy.getMinimum());
assertEquals(List.of(PaymentMethod.PAYMENT_METHOD_CARD, PaymentMethod.PAYMENT_METHOD_PAYPAL),
jpy.getSupportedPaymentMethodsList());
assertEquals(List.of("550", "600", "700", "800", "900", "1000"), jpy.getOneTimeOrThrow(1L).getAmountsList());
assertEquals(List.of("2000"), jpy.getOneTimeOrThrow(100L).getAmountsList());
assertEquals(Map.of(5L, "500", 15L, "1500", 35L, "3500"), jpy.getSubscriptionMap());
assertEquals(Map.of(201L, "500"), jpy.getBackupSubscriptionMap());
final CurrencyConfiguration bif = configuration.getCurrenciesOrThrow("bif");
assertEquals("2500", bif.getMinimum());
assertEquals(List.of(PaymentMethod.PAYMENT_METHOD_CARD), bif.getSupportedPaymentMethodsList());
assertEquals(List.of("5500", "6000", "7000", "8000", "9000", "10000"), bif.getOneTimeOrThrow(1L).getAmountsList());
assertEquals(List.of("20000"), bif.getOneTimeOrThrow(100L).getAmountsList());
assertEquals(Map.of(5L, "5000", 15L, "15000", 35L, "35000"), bif.getSubscriptionMap());
assertEquals(Map.of(201L, "5000"), bif.getBackupSubscriptionMap());
final CurrencyConfiguration eur = configuration.getCurrenciesOrThrow("eur");
assertEquals("3", eur.getMinimum());
assertEquals(
List.of(PaymentMethod.PAYMENT_METHOD_CARD, PaymentMethod.PAYMENT_METHOD_SEPA_DEBIT,
PaymentMethod.PAYMENT_METHOD_IDEAL),
eur.getSupportedPaymentMethodsList());
assertEquals(List.of("5", "10", "20", "30", "50", "100"), eur.getOneTimeOrThrow(1L).getAmountsList());
assertEquals(List.of("5"), eur.getOneTimeOrThrow(100L).getAmountsList());
assertEquals(Map.of(5L, "5", 15L, "15", 35L, "35"), eur.getSubscriptionMap());
assertEquals(Map.of(201L, "5"), eur.getBackupSubscriptionMap());
assertEquals("B1", configuration.getBadgeLevelsOrThrow(5L).getBadge().getId());
assertEquals(0L, configuration.getBadgeLevelsOrThrow(5L).getBadgeDurationSeconds());
assertEquals("B2", configuration.getBadgeLevelsOrThrow(15L).getBadge().getId());
assertEquals("B3", configuration.getBadgeLevelsOrThrow(35L).getBadge().getId());
assertEquals("BOOST", configuration.getBadgeLevelsOrThrow(1L).getBadge().getId());
assertTrue(configuration.getBadgeLevelsOrThrow(1L).getBadgeDurationSeconds() > 0);
assertEquals("GIFT", configuration.getBadgeLevelsOrThrow(100L).getBadge().getId());
assertTrue(configuration.getBadgeLevelsOrThrow(100L).getBadgeDurationSeconds() > 0);
}
@Test
void getConfigurationNoEtag() {
final GetConfigurationResponse response = unauthenticatedServiceStub()
.getConfiguration(GetConfigurationRequest.newBuilder().build());
assertFalse(response.hasEtagMatched());
checkConfiguration(response.getTaggedConfiguration().getConfiguration());
}
@Test
void getConfigurationWrongEtag() {
final GetConfigurationResponse response = unauthenticatedServiceStub()
.getConfiguration(GetConfigurationRequest.newBuilder().setEtag(ByteString.copyFrom(new byte[32])).build());
assertFalse(response.hasEtagMatched());
checkConfiguration(response.getTaggedConfiguration().getConfiguration());
}
@Test
void getConfigurationCorrectEtag() {
final GetConfigurationResponse response = unauthenticatedServiceStub()
.getConfiguration(GetConfigurationRequest.newBuilder().build());
final ByteString etag = response.getTaggedConfiguration().getEtag();
final GetConfigurationResponse withCorrectEtag = unauthenticatedServiceStub()
.getConfiguration(GetConfigurationRequest.newBuilder().setEtag(etag).build());
assertTrue(withCorrectEtag.hasEtagMatched());
assertTrue(withCorrectEtag.getEtagMatched());
assertFalse(withCorrectEtag.hasTaggedConfiguration());
}
@Test
void getConfigurationComputesOnce() {
final RequestAttributes frAttributes =
new RequestAttributes(InetAddresses.forString("127.0.0.1"), null, "fr-fr");
final List<Locale> frLocales = List.of(Locale.FRANCE);
final RequestAttributes caAttributes =
new RequestAttributes(InetAddresses.forString("127.0.0.1"), null, "en-ca");
final List<Locale> caLocales = List.of(Locale.CANADA);
when(badgeTranslator.resolveLocale(frLocales)).thenReturn(Locale.FRANCE);
when(badgeTranslator.resolveLocale(caLocales)).thenReturn(Locale.CANADA);
// return slightly different values based on the language so the two configurations have different etags
when(badgeTranslator.translate(eq(frLocales), eq("B1")))
.thenReturn(new Badge("B1", "cat1", "name1", "desc1", List.of("l", "m", "h", "x", "xx", "xxx"), "SVG", List.of(new BadgeSvg("sl", "sd"))));
when(badgeTranslator.translate(eq(caLocales), eq("B1")))
.thenReturn(new Badge("B1", "dog1", "name1", "desc1", List.of("l", "m", "h", "x", "xx", "xxx"), "SVG", List.of(new BadgeSvg("sl", "sd"))));
getMockRequestAttributesInterceptor().setRequestAttributes(caAttributes);
final GetConfigurationResponse caResponse =
unauthenticatedServiceStub().getConfiguration(GetConfigurationRequest.newBuilder().build());
final GetConfigurationResponse caResponseCached = unauthenticatedServiceStub()
.getConfiguration(GetConfigurationRequest.newBuilder()
.setEtag(caResponse.getTaggedConfiguration().getEtag())
.build());
assertTrue(caResponseCached.hasEtagMatched());
verify(badgeTranslator, times(1)).translate(any(), eq("B1"));
getMockRequestAttributesInterceptor().setRequestAttributes(frAttributes);
final GetConfigurationResponse frResponse =
unauthenticatedServiceStub().getConfiguration(GetConfigurationRequest.newBuilder().build());
assertFalse(frResponse.hasEtagMatched());
verify(badgeTranslator, times(2)).translate(any(), eq("B1"));
}
}
@@ -10,6 +10,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.params.provider.EnumSource.Mode.EXCLUDE;
import static org.mockito.AdditionalMatchers.aryEq;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
@@ -49,8 +50,10 @@ import javax.annotation.Nullable;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.EnumSource;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.junitpioneer.jupiter.cartesian.CartesianTest;
import org.mockito.Mock;
import org.signal.chat.common.IdentityType;
import org.signal.chat.common.ServiceIdentifier;
@@ -216,7 +219,7 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
.setUnidentifiedAccess(ByteString.copyFrom(unidentifiedAccessChecksum))
.setUnrestrictedUnidentifiedAccess(false)
.addCapabilities(org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_SPARSE_POST_QUANTUM_RATCHET)
.addAllBadges(ProfileGrpcHelper.buildBadges(badges))
.addAllBadges(badges.stream().map(BadgeGrpcHelper::toGrpcBadge).toList())
.build()
)
.build();
@@ -270,7 +273,7 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
.setIdentityKey(ByteString.copyFrom(identityKey.serialize()))
.setUnrestrictedUnidentifiedAccess(false)
.addAllCapabilities(ProfileGrpcHelper.buildAccountCapabilities(account))
.addAllBadges(ProfileGrpcHelper.buildBadges(badges))
.addAllBadges(badges.stream().map(BadgeGrpcHelper::toGrpcBadge).toList())
.build();
verify(accountsManager).getByServiceIdentifier(serviceIdentifier);
@@ -399,7 +402,9 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
@MethodSource
void getVersionedProfile(final byte[] requestVersion,
@Nullable final byte[] accountVersion,
final boolean expectResponseHasPaymentAddress) {
final boolean expectResponseHasPaymentAddress,
final GetVersionedProfileAnonymousRequest.AuthenticationCase authenticationCase) throws Exception {
final AciServiceIdentifier serviceIdentifier = new AciServiceIdentifier(UUID.randomUUID());
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
final byte[] name = TestRandomUtil.nextBytes(81);
@@ -418,18 +423,23 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
when(accountsManager.getByServiceIdentifier(any())).thenReturn(Optional.of(account));
when(profilesManager.getV1(any(), any())).thenReturn(profile);
final GetVersionedProfileAnonymousRequest request = GetVersionedProfileAnonymousRequest.newBuilder()
.setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey))
final GetVersionedProfileAnonymousRequest.Builder requestBuilder = GetVersionedProfileAnonymousRequest.newBuilder()
.setRequest(GetVersionedProfileRequest.newBuilder()
.setAccountIdentifier(ServiceIdentifier.newBuilder()
.setIdentityType(IdentityType.IDENTITY_TYPE_ACI)
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(UUID.randomUUID())))
.build())
.setAccountIdentifier(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(serviceIdentifier))
.setVersion(ByteString.copyFrom(requestVersion))
.build())
.build();
.build());
final GetVersionedProfileAnonymousResponse response = unauthenticatedServiceStub().getVersionedProfile(request);
switch (authenticationCase) {
case GROUP_SEND_TOKEN -> {
final Instant expiration = Instant.now().plus(Duration.ofDays(1)).truncatedTo(ChronoUnit.DAYS);
final byte[] token = AuthHelper.validGroupSendToken(SERVER_SECRET_PARAMS, List.of(serviceIdentifier), expiration);
requestBuilder.setGroupSendToken(ByteString.copyFrom(token));
}
case UNIDENTIFIED_ACCESS_KEY -> requestBuilder.setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey));
}
final GetVersionedProfileAnonymousResponse response = unauthenticatedServiceStub().getVersionedProfile(
requestBuilder.build());
final GetVersionedProfileResult.Builder expectedResultBuilder = GetVersionedProfileResult.newBuilder()
.setV1Response(GetVersionedProfileV1Response.newBuilder()
@@ -454,14 +464,22 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
final byte[] version1 = TestRandomUtil.nextBytes(32);
final byte[] version2 = TestRandomUtil.nextBytes(32);
return List.of(
Arguments.argumentSet("current profile version matches", version1, version1, true),
Arguments.argumentSet("current profile version absent",version1, null, true),
Arguments.argumentSet("current profile version mismatch",version1, version2, false)
Arguments.argumentSet("current profile version matches, unidentified access key auth", version1, version1, true,
GetVersionedProfileAnonymousRequest.AuthenticationCase.UNIDENTIFIED_ACCESS_KEY),
Arguments.argumentSet("current profile version absent, unidentified access key auth",version1, null, true,
GetVersionedProfileAnonymousRequest.AuthenticationCase.UNIDENTIFIED_ACCESS_KEY),
Arguments.argumentSet("current profile version mismatch, unidentified access key auth",version1, version2, false,
GetVersionedProfileAnonymousRequest.AuthenticationCase.UNIDENTIFIED_ACCESS_KEY),
Arguments.argumentSet("current profile version matches, group send endorsement auth", version1, version1, true,
GetVersionedProfileAnonymousRequest.AuthenticationCase.GROUP_SEND_TOKEN)
);
}
@Test
void getVersionedProfileV2() {
@ParameterizedTest
@EnumSource(mode = EXCLUDE, names = "AUTHENTICATION_NOT_SET")
void getVersionedProfileV2(
final GetVersionedProfileAnonymousRequest.AuthenticationCase authenticationCase) throws Exception {
final AciServiceIdentifier serviceIdentifier = new AciServiceIdentifier(UUID.randomUUID());
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
final byte[] data = TestRandomUtil.nextBytes(128);
final byte[] paymentAddress = TestRandomUtil.nextBytes(582);
@@ -477,18 +495,22 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
when(profilesManager.get(any(), any())).thenReturn(Optional.of(v2Profile));
when(profilesManager.getV1(any(), any())).thenReturn(Optional.empty());
final GetVersionedProfileAnonymousRequest request = GetVersionedProfileAnonymousRequest.newBuilder()
.setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey))
final GetVersionedProfileAnonymousRequest.Builder requestBuilder = GetVersionedProfileAnonymousRequest.newBuilder()
.setRequest(GetVersionedProfileRequest.newBuilder()
.setAccountIdentifier(ServiceIdentifier.newBuilder()
.setIdentityType(IdentityType.IDENTITY_TYPE_ACI)
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(UUID.randomUUID())))
.build())
.setAccountIdentifier(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(serviceIdentifier))
.setVersion(ByteString.copyFrom(version))
.build())
.build();
.build());
final GetVersionedProfileAnonymousResponse response = unauthenticatedServiceStub().getVersionedProfile(request);
switch (authenticationCase) {
case GROUP_SEND_TOKEN -> {
final Instant expiration = Instant.now().plus(Duration.ofDays(1)).truncatedTo(ChronoUnit.DAYS);
final byte[] token = AuthHelper.validGroupSendToken(SERVER_SECRET_PARAMS, List.of(serviceIdentifier), expiration);
requestBuilder.setGroupSendToken(ByteString.copyFrom(token));
}
case UNIDENTIFIED_ACCESS_KEY -> requestBuilder.setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey));
}
final GetVersionedProfileAnonymousResponse response = unauthenticatedServiceStub().getVersionedProfile(requestBuilder.build());
assertTrue(response.hasResult());
final GetVersionedProfileResult result = response.getResult();
@@ -576,44 +598,38 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
}
@ParameterizedTest
@MethodSource
void getVersionedProfileUnauthenticated(final boolean missingUnidentifiedAccessKey, final boolean accountNotFound) {
@EnumSource(mode = EXCLUDE, names = "AUTHENTICATION_NOT_SET")
void getVersionedProfileAccountNotFound(
final GetVersionedProfileAnonymousRequest.AuthenticationCase authenticationCase
) throws Exception {
final AciServiceIdentifier serviceIdentifier = new AciServiceIdentifier(UUID.randomUUID());
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
when(account.isUnrestrictedUnidentifiedAccess()).thenReturn(false);
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
when(accountsManager.getByServiceIdentifier(any())).thenReturn(
accountNotFound ? Optional.empty() : Optional.of(account));
when(accountsManager.getByServiceIdentifier(any())).thenReturn(Optional.empty());
final GetVersionedProfileAnonymousRequest.Builder requestBuilder = GetVersionedProfileAnonymousRequest.newBuilder()
.setRequest(GetVersionedProfileRequest.newBuilder()
.setAccountIdentifier(ServiceIdentifier.newBuilder()
.setIdentityType(IdentityType.IDENTITY_TYPE_ACI)
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(UUID.randomUUID())))
.build())
.setAccountIdentifier(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(serviceIdentifier))
.setVersion(ByteString.copyFrom(TestRandomUtil.nextBytes(32)))
.build());
if (missingUnidentifiedAccessKey) {
assertStatusException(Status.INVALID_ARGUMENT,
() -> unauthenticatedServiceStub().getVersionedProfile(requestBuilder.build()));
} else {
requestBuilder.setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey));
final GetVersionedProfileAnonymousResponse response = unauthenticatedServiceStub().getVersionedProfile(
requestBuilder.build());
assertEquals(accountNotFound, response.hasNotFound());
assertNotEquals(accountNotFound, response.hasFailedUnidentifiedAuthorization());
switch (authenticationCase) {
case GROUP_SEND_TOKEN -> {
final Instant expiration = Instant.now().plus(Duration.ofDays(1)).truncatedTo(ChronoUnit.DAYS);
final byte[] token = AuthHelper.validGroupSendToken(SERVER_SECRET_PARAMS, List.of(serviceIdentifier), expiration);
requestBuilder.setGroupSendToken(ByteString.copyFrom(token));
}
case UNIDENTIFIED_ACCESS_KEY -> requestBuilder.setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey));
}
final GetVersionedProfileAnonymousResponse response = unauthenticatedServiceStub().getVersionedProfile(requestBuilder.build());
}
private static Stream<Arguments> getVersionedProfileUnauthenticated() {
return Stream.of(
Arguments.of(true, false),
Arguments.of(false, true)
);
switch (authenticationCase) {
case GROUP_SEND_TOKEN -> assertTrue(response.hasNotFound());
case UNIDENTIFIED_ACCESS_KEY, AUTHENTICATION_NOT_SET -> assertTrue(response.hasFailedUnidentifiedAuthorization());
}
}
@Test
@@ -631,9 +647,81 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
.build())
.build();
//noinspection ThrowableNotThrown
assertStatusException(Status.INVALID_ARGUMENT, () -> unauthenticatedServiceStub().getVersionedProfile(request));
}
@Test
void getVersionedProfileNoAuth() {
final GetVersionedProfileAnonymousRequest request = GetVersionedProfileAnonymousRequest.newBuilder()
.setRequest(GetVersionedProfileRequest.newBuilder()
.setAccountIdentifier(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(new AciServiceIdentifier(UUID.randomUUID()))))
.build();
//noinspection ThrowableNotThrown
assertStatusException(Status.INVALID_ARGUMENT, () -> unauthenticatedServiceStub().getVersionedProfile(request));
}
@Test
void getVersionedProfileIncorrectUnidentifiedAccessKey() {
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
when(account.isUnrestrictedUnidentifiedAccess()).thenReturn(false);
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
when(accountsManager.getByServiceIdentifier(any())).thenReturn(Optional.of(account));
final GetVersionedProfileAnonymousRequest request = GetVersionedProfileAnonymousRequest.newBuilder()
.setUnidentifiedAccessKey(ByteString.copyFrom(new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH]))
.setRequest(GetVersionedProfileRequest.newBuilder()
.setAccountIdentifier(ServiceIdentifier.newBuilder()
.setIdentityType(IdentityType.IDENTITY_TYPE_ACI)
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(UUID.randomUUID())))
.build())
.setVersion(ByteString.copyFrom(TestRandomUtil.nextBytes(32)))
.build())
.build();
final GetVersionedProfileAnonymousResponse response = unauthenticatedServiceStub().getVersionedProfile(request);
assertTrue(response.hasFailedUnidentifiedAuthorization());
}
@ParameterizedTest
@MethodSource
void getVersionedProfileFailingGroupSendEndorsement(final boolean expired, final boolean wrongIdentifier) throws Exception {
final AciServiceIdentifier serviceIdentifier = new AciServiceIdentifier(UUID.randomUUID());
final AciServiceIdentifier wrongServiceIdentifier = new AciServiceIdentifier(UUID.randomUUID());
when(accountsManager.getByServiceIdentifier(serviceIdentifier))
.thenReturn(Optional.of(mock(Account.class)));
final Instant expiration = expired ? Instant.now().truncatedTo(ChronoUnit.DAYS) : Instant.now().plus(Duration.ofDays(1)).truncatedTo(ChronoUnit.DAYS);
final byte[] token = AuthHelper.validGroupSendToken(SERVER_SECRET_PARAMS,
List.of(wrongIdentifier ? wrongServiceIdentifier : serviceIdentifier), expiration);
final GetVersionedProfileAnonymousRequest request = GetVersionedProfileAnonymousRequest.newBuilder()
.setGroupSendToken(ByteString.copyFrom(token))
.setRequest(GetVersionedProfileRequest.newBuilder()
.setAccountIdentifier(
GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(serviceIdentifier))
.setVersion(ByteString.copyFrom(TestRandomUtil.nextBytes(32)))
.build())
.build();
final GetVersionedProfileAnonymousResponse response = unauthenticatedServiceStub().getVersionedProfile(request);
assertTrue(response.hasFailedUnidentifiedAuthorization());
}
private static List<Arguments> getVersionedProfileFailingGroupSendEndorsement() {
return List.of(
Arguments.of(true, true),
Arguments.of(true, false),
Arguments.of(false, true)
);
}
@Test
void getExpiringProfileKeyCredential() throws Exception {
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
@@ -174,7 +174,6 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
new BadgeSvg("ll", "ld")
)
)),
List.of("TEST1"),
Map.of(1L, "TEST1", 2L, "TEST2", 3L, "TEST3")
);
final RateLimiters rateLimiters = mock(RateLimiters.class);
@@ -655,7 +654,7 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
.setIdentityKey(ByteString.copyFrom(identityKey.serialize()))
.setUnidentifiedAccess(ByteString.copyFrom(unidentifiedAccessChecksum))
.setUnrestrictedUnidentifiedAccess(true)
.addAllBadges(ProfileGrpcHelper.buildBadges(badges))
.addAllBadges(badges.stream().map(BadgeGrpcHelper::toGrpcBadge).toList())
.build();
final GetUnversionedProfileResult expectedResponse;
@@ -19,12 +19,12 @@ import static org.mockito.Mockito.when;
import com.google.common.net.InetAddresses;
import com.google.protobuf.ByteString;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.Duration;
import java.time.Instant;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
@@ -35,30 +35,28 @@ import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.EnumSource;
import org.junit.jupiter.params.provider.MethodSource;
import org.mockito.Mock;
import org.signal.chat.subscriptions.CreatePayPalPaymentMethodRequest;
import org.signal.chat.subscriptions.CreatePayPalPaymentMethodResponse;
import org.signal.chat.subscriptions.CreatePaymentMethodRequest;
import org.signal.chat.subscriptions.CreatePaymentMethodResponse;
import org.signal.chat.subscriptions.DeleteSubscriberRequest;
import org.signal.chat.subscriptions.DeleteSubscriberResponse;
import org.signal.chat.subscriptions.GetBankMandateRequest;
import org.signal.chat.subscriptions.GetBankMandateResponse;
import org.signal.chat.subscriptions.GetConfigurationRequest;
import org.signal.chat.subscriptions.GetConfigurationResponse;
import org.signal.chat.subscriptions.GetReceiptCredentialsRequest;
import org.signal.chat.subscriptions.GetReceiptCredentialsResponse;
import org.signal.chat.subscriptions.GetSubscriptionInformationRequest;
import org.signal.chat.subscriptions.GetSubscriptionInformationResponse;
import org.signal.chat.subscriptions.PaymentMethod;
import org.signal.chat.subscriptions.SetDefaultPaymentMethodRequest;
import org.signal.chat.subscriptions.SetDefaultPaymentMethodResponse;
import org.signal.chat.subscriptions.SetIapSubscriptionRequest;
import org.signal.chat.subscriptions.SetIapSubscriptionResponse;
import org.signal.chat.subscriptions.SetSubscriptionLevelRequest;
import org.signal.chat.subscriptions.SetSubscriptionLevelResponse;
import org.signal.chat.subscriptions.SubscriptionsGrpc;
import org.signal.chat.subscriptions.UpdateSubscriberRequest;
import org.signal.chat.subscriptions.UpdateSubscriberResponse;
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.PaymentMethod;
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.SubscriptionsGrpc;
import org.signal.chat.purchase.UpdateSubscriberRequest;
import org.signal.chat.purchase.UpdateSubscriberResponse;
import org.signal.libsignal.zkgroup.ServerSecretParams;
import org.signal.libsignal.zkgroup.VerificationFailedException;
import org.signal.libsignal.zkgroup.donation.DonationPermit;
@@ -66,17 +64,10 @@ import org.signal.libsignal.zkgroup.donation.DonationPermitRequest;
import org.signal.libsignal.zkgroup.donation.DonationPermitRequestContext;
import org.signal.libsignal.zkgroup.donation.DonationPermitResponse;
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialResponse;
import org.whispersystems.textsecuregcm.badges.BadgeTranslator;
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration;
import org.whispersystems.textsecuregcm.configuration.SubscriptionConfiguration;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicBackupConfiguration;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.entities.Badge;
import org.whispersystems.textsecuregcm.entities.BadgeSvg;
import org.whispersystems.textsecuregcm.storage.DonationPermits;
import org.whispersystems.textsecuregcm.storage.DonationPermitsManager;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.storage.SubscriptionManager;
import org.whispersystems.textsecuregcm.storage.Subscriptions;
import org.whispersystems.textsecuregcm.subscriptions.AppleAppStoreManager;
@@ -118,9 +109,6 @@ public class SubscriptionsGrpcServiceTest extends
private final SubscriptionConfiguration subscriptionConfiguration =
SubscriptionConfigTestHelper.getSubscriptionConfig();
private final OneTimeDonationConfiguration oneTimeDonationConfiguration =
SubscriptionConfigTestHelper.getOneTimeConfig();
@Mock
private DonationPermits donationPermits;
@@ -142,15 +130,9 @@ public class SubscriptionsGrpcServiceTest extends
@Mock
private AppleAppStoreManager appleAppStoreManager;
@Mock
private BadgeTranslator badgeTranslator;
@Mock
private BankMandateTranslator bankMandateTranslator;
@Mock
private DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
private static final ByteString SUBSCRIBER_ID = ByteString.copyFrom(TestRandomUtil.nextBytes(32));
private static final long LEVEL = 5L;
private static final String CURRENCY = "usd";
@@ -167,9 +149,8 @@ public class SubscriptionsGrpcServiceTest extends
when(donationPermits.spend(any(byte[].class), any(Instant.class)))
.thenAnswer(answer -> spent.add(new String(answer.getArgument(0, byte[].class))));
return new SubscriptionsGrpcService(clock, subscriptionConfiguration, oneTimeDonationConfiguration,
subscriptionManager, donationPermitsManager, stripeManager, braintreeManager, googlePlayBillingManager,
appleAppStoreManager, badgeTranslator, bankMandateTranslator, dynamicConfigurationManager);
return new SubscriptionsGrpcService(clock, subscriptionConfiguration, subscriptionManager, donationPermitsManager,
stripeManager, braintreeManager, googlePlayBillingManager, appleAppStoreManager, bankMandateTranslator);
}
@Test
@@ -267,7 +248,7 @@ public class SubscriptionsGrpcServiceTest extends
final CreatePaymentMethodResponse response = unauthenticatedServiceStub().createPaymentMethod(builder.build());
assertEquals(CreatePaymentMethodResponse.ResponseCase.RESULT, response.getResponseCase());
// Currently, only stripe is chosen as the payment provider for all supported payment methods
assertEquals(org.signal.chat.subscriptions.PaymentProvider.PAYMENT_PROVIDER_STRIPE,
assertEquals(org.signal.chat.purchase.PaymentProvider.PAYMENT_PROVIDER_STRIPE,
response.getResult().getPaymentProvider());
assertEquals("test-client-secret", response.getResult().getClientSecret());
}
@@ -330,7 +311,7 @@ public class SubscriptionsGrpcServiceTest extends
final BraintreeManager.PayPalBillingAgreementApprovalDetails details =
new BraintreeManager.PayPalBillingAgreementApprovalDetails("https://fake-approval", "test-billing-token");
when(subscriptionManager.addPaymentMethodToCustomer(any(), any(), any(), any()))
.thenReturn(CompletableFuture.completedFuture(details));
.thenReturn(details);
final CreatePayPalPaymentMethodResponse response = unauthenticatedServiceStub().createPayPalPaymentMethod(
CreatePayPalPaymentMethodRequest.newBuilder()
.setSubscriberId(SUBSCRIBER_ID)
@@ -360,7 +341,7 @@ public class SubscriptionsGrpcServiceTest extends
@ParameterizedTest
@EnumSource(value = SetDefaultPaymentMethodRequest.RequestCase.class, names = {"STRIPE", "BRAINTREE", "SEPA"})
void setDefaultPaymentMethod(final SetDefaultPaymentMethodRequest.RequestCase requestCase)
throws SubscriptionNotFoundException, SubscriptionForbiddenException {
throws SubscriptionNotFoundException, SubscriptionForbiddenException, IOException, SubscriptionProcessorConflictException {
final PaymentProvider provider = requestCase == SetDefaultPaymentMethodRequest.RequestCase.BRAINTREE
? PaymentProvider.BRAINTREE : PaymentProvider.STRIPE;
final Subscriptions.Record record = mock(Subscriptions.Record.class);
@@ -368,7 +349,7 @@ public class SubscriptionsGrpcServiceTest extends
when(subscriptionManager.getSubscriber(any())).thenReturn(record);
if (requestCase == SetDefaultPaymentMethodRequest.RequestCase.SEPA) {
when(stripeManager.getGeneratedSepaIdFromSetupIntent(any()))
.thenReturn(CompletableFuture.completedFuture("sepa-id"));
.thenReturn("sepa-id");
}
final SetDefaultPaymentMethodRequest.Builder builder = SetDefaultPaymentMethodRequest.newBuilder()
.setSubscriberId(SUBSCRIBER_ID);
@@ -540,7 +521,7 @@ public class SubscriptionsGrpcServiceTest extends
.setLevel(LEVEL).setCurrency(CURRENCY).setIdempotencyKey("test-idempotency-key")
.build());
assertEquals(SetSubscriptionLevelResponse.ResponseCase.CHARGE_FAILURE, response.getResponseCase());
assertEquals(org.signal.chat.subscriptions.PaymentProvider.PAYMENT_PROVIDER_STRIPE,
assertEquals(org.signal.chat.purchase.PaymentProvider.PAYMENT_PROVIDER_STRIPE,
response.getChargeFailure().getProcessor());
assertEquals("card_declined", response.getChargeFailure().getCode());
assertEquals("Insufficient funds", response.getChargeFailure().getMessage());
@@ -573,7 +554,7 @@ public class SubscriptionsGrpcServiceTest extends
assertEquals(1000L, response.getSuccess().getEndOfCurrentPeriod());
assertTrue(response.getSuccess().getActive());
assertFalse(response.getSuccess().getCancelAtPeriodEnd());
assertEquals(org.signal.chat.subscriptions.PaymentProvider.PAYMENT_PROVIDER_STRIPE,
assertEquals(org.signal.chat.purchase.PaymentProvider.PAYMENT_PROVIDER_STRIPE,
response.getSuccess().getProcessor());
assertEquals(PaymentMethod.PAYMENT_METHOD_CARD, response.getSuccess().getPaymentMethod());
}
@@ -640,7 +621,7 @@ public class SubscriptionsGrpcServiceTest extends
.setReceiptCredentialRequest(ByteString.copyFrom(TestRandomUtil.nextBytes(97)))
.build());
assertEquals(GetReceiptCredentialsResponse.ResponseCase.PAYMENT_REQUIRED, response.getResponseCase());
assertEquals(org.signal.chat.subscriptions.PaymentProvider.PAYMENT_PROVIDER_STRIPE,
assertEquals(org.signal.chat.purchase.PaymentProvider.PAYMENT_PROVIDER_STRIPE,
response.getPaymentRequired().getChargeFailure().getProcessor());
assertEquals("card_declined", response.getPaymentRequired().getChargeFailure().getCode());
}
@@ -703,104 +684,12 @@ public class SubscriptionsGrpcServiceTest extends
assertEquals(expectedCase, response.getResponseCase());
}
@Test
void getConfiguration() {
final DynamicConfiguration dynamicConfiguration = mock(DynamicConfiguration.class);
when(dynamicConfigurationManager.getConfiguration()).thenReturn(dynamicConfiguration);
when(dynamicConfiguration.getBackupConfiguration())
.thenReturn(new DynamicBackupConfiguration(null, null, null, null, 1234L));
when(stripeManager.supportsPaymentMethod(any())).thenCallRealMethod();
when(stripeManager.getSupportedCurrenciesForPaymentMethod(
org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.CARD))
.thenReturn(Set.of("usd", "jpy", "bif", "eur"));
when(stripeManager.getSupportedCurrenciesForPaymentMethod(
org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.SEPA_DEBIT))
.thenReturn(Set.of("eur"));
when(stripeManager.getSupportedCurrenciesForPaymentMethod(
org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.IDEAL))
.thenReturn(Set.of("eur"));
when(braintreeManager.supportsPaymentMethod(any())).thenCallRealMethod();
when(braintreeManager.getSupportedCurrenciesForPaymentMethod(
org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.PAYPAL))
.thenReturn(Set.of("usd", "jpy"));
when(badgeTranslator.translate(any(), eq("B1"))).thenReturn(new Badge("B1", "cat1", "name1", "desc1",
List.of("l", "m", "h", "x", "xx", "xxx"), "SVG", List.of(new BadgeSvg("sl", "sd"))));
when(badgeTranslator.translate(any(), eq("B2"))).thenReturn(new Badge("B2", "cat2", "name2", "desc2",
List.of("l", "m", "h", "x", "xx", "xxx"), "SVG", List.of(new BadgeSvg("sl", "sd"))));
when(badgeTranslator.translate(any(), eq("B3"))).thenReturn(new Badge("B3", "cat3", "name3", "desc3",
List.of("l", "m", "h", "x", "xx", "xxx"), "SVG", List.of(new BadgeSvg("sl", "sd"))));
when(badgeTranslator.translate(any(), eq("BOOST"))).thenReturn(new Badge("BOOST", "boost1", "boost1", "boost1",
List.of("l", "m", "h", "x", "xx", "xxx"), "SVG", List.of(new BadgeSvg("sl", "sd"))));
when(badgeTranslator.translate(any(), eq("GIFT"))).thenReturn(new Badge("GIFT", "gift1", "gift1", "gift1",
List.of("l", "m", "h", "x", "xx", "xxx"), "SVG", List.of(new BadgeSvg("sl", "sd"))));
final GetConfigurationResponse response = unauthenticatedServiceStub()
.getConfiguration(GetConfigurationRequest.newBuilder().build());
assertEquals("10000", response.getSepaMaximumEuros());
assertEquals(30L, response.getBackup().getFreeTierMediaDays());
final GetConfigurationResponse.BackupLevelConfiguration backupLevel =
response.getBackup().getLevelsOrThrow(201L);
assertEquals(1234L, backupLevel.getStorageAllowanceBytes());
assertEquals("testPlayProductId", backupLevel.getPlayProductId());
assertEquals(40L, backupLevel.getMediaTtlDays());
final GetConfigurationResponse.CurrencyConfiguration usd = response.getCurrenciesOrThrow("usd");
assertEquals("2.50", usd.getMinimum());
assertEquals(List.of(PaymentMethod.PAYMENT_METHOD_CARD, PaymentMethod.PAYMENT_METHOD_PAYPAL),
usd.getSupportedPaymentMethodsList());
assertEquals(List.of("5.50", "6", "7", "8", "9", "10"), usd.getOneTimeOrThrow(1L).getAmountsList());
assertEquals(List.of("20"), usd.getOneTimeOrThrow(100L).getAmountsList());
assertEquals(Map.of(5L, "5", 15L, "15", 35L, "35"), usd.getSubscriptionMap());
assertEquals(Map.of(201L, "5"), usd.getBackupSubscriptionMap());
final GetConfigurationResponse.CurrencyConfiguration jpy = response.getCurrenciesOrThrow("jpy");
assertEquals("250", jpy.getMinimum());
assertEquals(List.of(PaymentMethod.PAYMENT_METHOD_CARD, PaymentMethod.PAYMENT_METHOD_PAYPAL),
jpy.getSupportedPaymentMethodsList());
assertEquals(List.of("550", "600", "700", "800", "900", "1000"), jpy.getOneTimeOrThrow(1L).getAmountsList());
assertEquals(List.of("2000"), jpy.getOneTimeOrThrow(100L).getAmountsList());
assertEquals(Map.of(5L, "500", 15L, "1500", 35L, "3500"), jpy.getSubscriptionMap());
assertEquals(Map.of(201L, "500"), jpy.getBackupSubscriptionMap());
final GetConfigurationResponse.CurrencyConfiguration bif = response.getCurrenciesOrThrow("bif");
assertEquals("2500", bif.getMinimum());
assertEquals(List.of(PaymentMethod.PAYMENT_METHOD_CARD), bif.getSupportedPaymentMethodsList());
assertEquals(List.of("5500", "6000", "7000", "8000", "9000", "10000"), bif.getOneTimeOrThrow(1L).getAmountsList());
assertEquals(List.of("20000"), bif.getOneTimeOrThrow(100L).getAmountsList());
assertEquals(Map.of(5L, "5000", 15L, "15000", 35L, "35000"), bif.getSubscriptionMap());
assertEquals(Map.of(201L, "5000"), bif.getBackupSubscriptionMap());
final GetConfigurationResponse.CurrencyConfiguration eur = response.getCurrenciesOrThrow("eur");
assertEquals("3", eur.getMinimum());
assertEquals(
List.of(PaymentMethod.PAYMENT_METHOD_CARD, PaymentMethod.PAYMENT_METHOD_SEPA_DEBIT,
PaymentMethod.PAYMENT_METHOD_IDEAL),
eur.getSupportedPaymentMethodsList());
assertEquals(List.of("5", "10", "20", "30", "50", "100"), eur.getOneTimeOrThrow(1L).getAmountsList());
assertEquals(List.of("5"), eur.getOneTimeOrThrow(100L).getAmountsList());
assertEquals(Map.of(5L, "5", 15L, "15", 35L, "35"), eur.getSubscriptionMap());
assertEquals(Map.of(201L, "5"), eur.getBackupSubscriptionMap());
assertEquals("B1", response.getLevelsOrThrow(5L).getBadge().getBadge().getId());
assertEquals(0L, response.getLevelsOrThrow(5L).getBadge().getDurationSeconds());
assertEquals("B2", response.getLevelsOrThrow(15L).getBadge().getBadge().getId());
assertEquals("B3", response.getLevelsOrThrow(35L).getBadge().getBadge().getId());
assertEquals("BOOST", response.getLevelsOrThrow(1L).getBadge().getBadge().getId());
assertTrue(response.getLevelsOrThrow(1L).getBadge().getDurationSeconds() > 0);
assertEquals("GIFT", response.getLevelsOrThrow(100L).getBadge().getBadge().getId());
assertTrue(response.getLevelsOrThrow(100L).getBadge().getDurationSeconds() > 0);
}
@Test
void getBankMandate() {
when(bankMandateTranslator.translate(any(), eq(BankTransferType.SEPA_DEBIT))).thenReturn("test-mandate");
final GetBankMandateResponse response = unauthenticatedServiceStub().getBankMandate(
GetBankMandateRequest.newBuilder()
.setBankTransferType(org.signal.chat.subscriptions.BankTransferType.BANK_TRANSFER_TYPE_SEPA_DEBIT)
.setBankTransferType(org.signal.chat.purchase.BankTransferType.BANK_TRANSFER_TYPE_SEPA_DEBIT)
.build());
assertEquals("test-mandate", response.getMandate());
}
@@ -8,6 +8,7 @@ package org.whispersystems.textsecuregcm.metrics;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
@@ -77,6 +78,8 @@ class MetricsRequestEventListenerTest {
@BeforeEach
void setup() {
meterRegistry = mock(MeterRegistry.class);
when(meterRegistry.gauge(anyString(), any(Number.class))).thenAnswer(invocation -> invocation.getArgument(1));
counter = mock(Counter.class);
responseBytesCounter = mock(Counter.class);
requestBytesCounter = mock(Counter.class);
@@ -0,0 +1,74 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.List;
import java.util.UUID;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStream;
class MirroringMessageStreamTest {
private FoundationDbMessageStream foundationDbMessageStream;
private ExperimentEnrollmentManager experimentEnrollmentManager;
private MirroringMessageStream mirroringMessageStream;
private static final AciServiceIdentifier ACCOUNT_IDENTIFIER = new AciServiceIdentifier(UUID.randomUUID());
private static final byte DEVICE_ID = Device.PRIMARY_ID;
@BeforeEach
void setUp() {
foundationDbMessageStream = mock(FoundationDbMessageStream.class);
experimentEnrollmentManager = mock(ExperimentEnrollmentManager.class);
mirroringMessageStream = new MirroringMessageStream(
mock(RedisDynamoDbMessageStream.class),
foundationDbMessageStream,
experimentEnrollmentManager,
ACCOUNT_IDENTIFIER.uuid(),
DEVICE_ID);
}
@ParameterizedTest
@MethodSource
void acknowledgeMessage(final boolean enrolled, final UUID messageGuid, final boolean expectFoundationDbDeletion) {
when(experimentEnrollmentManager.isEnrolled(any(UUID.class), eq(MessagesManager.MIRROR_DELETIONS_EXPERIMENT_NAME)))
.thenReturn(enrolled);
final long serverTimestamp = System.currentTimeMillis();
mirroringMessageStream.acknowledgeMessage(messageGuid, serverTimestamp);
if (expectFoundationDbDeletion) {
verify(foundationDbMessageStream).acknowledgeMessage(messageGuid, serverTimestamp);
} else {
verify(foundationDbMessageStream, never()).acknowledgeMessage(any(), anyLong());
}
}
private static List<Arguments> acknowledgeMessage() {
return List.of(
Arguments.argumentSet("Not enrolled, v4 UUID", false, UUID.randomUUID(), false),
Arguments.argumentSet("Not enrolled, v8 UUID", false, MessageGuidUtil.generateRandomV8UUID(), false),
Arguments.argumentSet("Enrolled, v4 UUID", true, UUID.randomUUID(), false),
Arguments.argumentSet("Enrolled, v8 UUID", true, MessageGuidUtil.generateRandomV8UUID(), true)
);
}
}
@@ -1,95 +0,0 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage.foundationdb;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.apple.foundationdb.tuple.Versionstamp;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Collections;
import java.util.List;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.whispersystems.textsecuregcm.util.Pair;
class AcknowledgedMessageBufferTest {
@ParameterizedTest
@MethodSource
void computeFlushableRanges(final List<Integer> versionstampsSent,
final List<Integer> versionstampsAcknowledged,
final List<Pair<Integer, Integer>> expectedRanges) {
final AcknowledgedMessageBuffer acknowledgedMessageBuffer =
new AcknowledgedMessageBuffer(FoundationDbMessageStream.DEFAULT_MAX_UNACKNOWLEDGED_MESSAGES);
versionstampsSent.forEach(versionstamp -> assertDoesNotThrow(() ->
acknowledgedMessageBuffer.addUnacknowledgedMessage(versionstampFromInt(versionstamp))));
versionstampsAcknowledged.forEach(versionstamp ->
acknowledgedMessageBuffer.acknowledgeMessage(versionstampFromInt(versionstamp)));
final List<Pair<Versionstamp, Versionstamp>> flushableRanges = acknowledgedMessageBuffer.computeFlushableRanges();
assertEquals(expectedRanges
.stream()
.map(range -> new Pair<>(versionstampFromInt(range.first()), versionstampFromInt(range.second())))
.toList(),
flushableRanges);
}
@Test
void takeFlushableRanges() {
final AcknowledgedMessageBuffer acknowledgedMessageBuffer =
new AcknowledgedMessageBuffer(FoundationDbMessageStream.DEFAULT_MAX_UNACKNOWLEDGED_MESSAGES);
IntStream.range(0, 10)
.mapToObj(AcknowledgedMessageBufferTest::versionstampFromInt)
.forEach(versionstamp -> assertDoesNotThrow(
() -> acknowledgedMessageBuffer.addUnacknowledgedMessage(versionstamp)));
assertEquals(10, acknowledgedMessageBuffer.getUnacknowledgedMessageCount());
IntStream.range(2, 8)
.mapToObj(AcknowledgedMessageBufferTest::versionstampFromInt)
.forEach(acknowledgedMessageBuffer::acknowledgeMessage);
assertEquals(List.of(new Pair<>(versionstampFromInt(2), versionstampFromInt(7))),
acknowledgedMessageBuffer.takeFlushableRanges());
assertEquals(4, acknowledgedMessageBuffer.getUnacknowledgedMessageCount());
}
static Stream<Arguments> computeFlushableRanges() {
return Stream.of(
Arguments.argumentSet("Single acknowledged message range", List.of(1, 2, 3), List.of(1),
List.of(new Pair<>(1, 1))),
Arguments.argumentSet("No acknowledged messages", List.of(1, 2, 3), Collections.emptyList(),
Collections.emptyList()),
Arguments.argumentSet("Fully acknowledged message range", List.of(1, 2, 3, 4),
List.of(1, 2, 3, 4), List.of(new Pair<>(1, 4))),
Arguments.argumentSet("Not all messages acknowledged", List.of(1, 2, 3, 4),
List.of(1, 2, 3), List.of(new Pair<>(1, 3))),
Arguments.argumentSet("Out-of-order acknowledged ranges", List.of(1, 2, 3, 4, 5, 6, 7, 8),
List.of(1, 3, 4, 5, 7, 8), List.of(new Pair<>(1, 1), new Pair<>(3, 5), new Pair<>(7, 8))),
Arguments.argumentSet("Out-of-order acknowledged single messages", List.of(1, 2, 3, 4, 5, 6, 7, 8),
List.of(1, 3, 5), List.of(new Pair<>(1, 1), new Pair<>(3, 3), new Pair<>(5, 5)))
);
}
private static Versionstamp versionstampFromInt(final int version) {
final ByteBuffer buf = ByteBuffer.allocate(10).order(ByteOrder.BIG_ENDIAN);
buf.putLong(version); // 8 bytes: transaction version
buf.putShort((short) 2); // 2 bytes: batch order within transaction
return Versionstamp.complete(buf.array());
}
}
@@ -35,9 +35,7 @@ import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
@@ -66,8 +64,6 @@ class FoundationDbMessagePublisherTest {
private static final byte[] MESSAGES_AVAILABLE_WATCH_KEY =
FoundationDbMessageStore.getMessagesAvailableWatchKey(SERVICE_IDENTIFIER);
private static final Supplier<Consumer<Transaction>> NOOP_ON_PAGE_FETCH = () -> _ -> {};
private static final Clock CLOCK = Clock.systemUTC();
private static final int STREAM_ID = ThreadLocalRandom.current().nextInt();
@@ -131,8 +127,7 @@ class FoundationDbMessagePublisherTest {
null,
null,
null,
(_, newState) -> stateTransitions.add(newState),
NOOP_ON_PAGE_FETCH
(_, newState) -> stateTransitions.add(newState)
);
StepVerifier.create(finitePublisher.getMessages())
@@ -219,8 +214,7 @@ class FoundationDbMessagePublisherTest {
watchFuture2.complete(null);
}
}
},
NOOP_ON_PAGE_FETCH
}
);
StepVerifier.create(infinitePublisher.getMessages())
@@ -302,8 +296,7 @@ class FoundationDbMessagePublisherTest {
.count() == 1) {
watchFuture1.complete(null);
}
},
NOOP_ON_PAGE_FETCH
}
);
StepVerifier.create(infinitePublisher.getMessages())
@@ -338,8 +331,7 @@ class FoundationDbMessagePublisherTest {
100,
FoundationDbMessageStore.getPresenceKey(SERVICE_IDENTIFIER, Device.PRIMARY_ID),
presenceRenewalExecutorService,
MESSAGES_AVAILABLE_WATCH_KEY,
() -> _ -> {});
MESSAGES_AVAILABLE_WATCH_KEY);
final MessageProtos.Envelope message = FoundationDbMessageStoreTest.generateRandomMessage(false);
final Transaction transaction = mock(Transaction.class);
final KeyValue keyValue = mockKeyValue((byte) 5, message);
@@ -399,8 +391,7 @@ class FoundationDbMessagePublisherTest {
FoundationDbMessageStore.getPresenceKey(SERVICE_IDENTIFIER, Device.PRIMARY_ID),
presenceRenewalExecutorService,
MESSAGES_AVAILABLE_WATCH_KEY,
(_, newState) -> stateTransitions.add(newState),
NOOP_ON_PAGE_FETCH
(_, newState) -> stateTransitions.add(newState)
);
final RuntimeException streamTerminationException = new RuntimeException("Stream terminated");
@@ -464,8 +455,7 @@ class FoundationDbMessagePublisherTest {
&& newState == FoundationDbMessagePublisher.State.MESSAGES_AVAILABLE) {
latch.countDown();
}
},
NOOP_ON_PAGE_FETCH
}
);
// Request two messages one at a time and verify that we only fetch a single batch (batch size = 2) and not two batches
@@ -493,6 +493,36 @@ class FoundationDbMessageStoreTest {
Map.of(generateRandomAciForShard(0), Collections.emptyMap())));
}
@Test
void delete() {
final AciServiceIdentifier deletedMessageAci = new AciServiceIdentifier(UUID.randomUUID());
final byte deletedMessageDeviceId = Device.PRIMARY_ID;
final MessageProtos.Envelope deletedMessage = generateRandomMessage(false);
final AciServiceIdentifier retainedMessageAci = new AciServiceIdentifier(UUID.randomUUID());
final byte retainedMessageDeviceId = Device.PRIMARY_ID;
final MessageProtos.Envelope retainedMessage = generateRandomMessage(false);
final UUID deletedMessageGuid =
foundationDbMessageStore.insert(deletedMessageAci, Map.of(deletedMessageDeviceId, deletedMessage)).join()
.get(deletedMessageDeviceId).messageGuid().orElseThrow();
foundationDbMessageStore.insert(retainedMessageAci, Map.of(retainedMessageDeviceId, retainedMessage)).join();
assertArrayEquals(deletedMessage.toByteArray(),
getItemsInDeviceQueue(deletedMessageAci, deletedMessageDeviceId).getFirst().getValue());
assertArrayEquals(retainedMessage.toByteArray(),
getItemsInDeviceQueue(retainedMessageAci, retainedMessageDeviceId).getFirst().getValue());
foundationDbMessageStore.delete(deletedMessageAci, deletedMessageDeviceId, deletedMessageGuid).join();
assertTrue(getItemsInDeviceQueue(deletedMessageAci, deletedMessageDeviceId).isEmpty());
assertArrayEquals(retainedMessage.toByteArray(),
getItemsInDeviceQueue(retainedMessageAci, retainedMessageDeviceId).getFirst().getValue());
}
@Test
void clearAllForAccount() {
final AciServiceIdentifier deletedAccountIdentifier = new AciServiceIdentifier(UUID.randomUUID());
@@ -564,7 +594,7 @@ class FoundationDbMessageStoreTest {
.toList();
final MessageStream messageStream =
foundationDbMessageStore.getMessages(aci, Device.PRIMARY_ID, batchSize, numMessages, Util.NOOP);
foundationDbMessageStore.getMessages(aci, Device.PRIMARY_ID, batchSize, Util.NOOP);
final List<MessageStreamEntry> retrievedEntries = new ArrayList<>();
StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messageStream.getMessages()))
@@ -878,7 +908,6 @@ class FoundationDbMessageStoreTest {
final CountDownLatch latch = new CountDownLatch(1);
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci, Device.PRIMARY_ID,
FoundationDbMessageStream.DEFAULT_MAX_MESSAGES_PER_SCAN,
FoundationDbMessageStream.DEFAULT_MAX_UNACKNOWLEDGED_MESSAGES,
latch::countDown);
final List<CompletableFuture<Void>> acknowledgeFutures = new ArrayList<>();
final AtomicInteger messageCounter = new AtomicInteger(0);
@@ -949,7 +978,6 @@ class FoundationDbMessageStoreTest {
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci,
deviceId,
FoundationDbMessageStream.DEFAULT_MAX_MESSAGES_PER_SCAN,
FoundationDbMessageStream.DEFAULT_MAX_UNACKNOWLEDGED_MESSAGES,
cleanupLatch::countDown);
final List<MessageStreamEntry> retrievedEntries = new ArrayList<>();
@@ -990,28 +1018,6 @@ class FoundationDbMessageStoreTest {
}
}
@Test
void outstandingUnacknowledgedMessages() {
final int numMessages = 5;
final int maxUnacknowledgedMessages = 3;
final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID());
for (int i = 0; i < numMessages; i++) {
foundationDbMessageStore.insert(aci, Map.of(Device.PRIMARY_ID, generateRandomMessage(false))).join();
}
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci, Device.PRIMARY_ID,
FoundationDbMessageStream.DEFAULT_MAX_MESSAGES_PER_SCAN,
maxUnacknowledgedMessages,
Util.NOOP);
StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messageStream.getMessages()), numMessages)
.expectNextCount(maxUnacknowledgedMessages)
.expectError(TooManyUnacknowledgedMessagesException.class)
.verify();
}
@Test
void discardStaleEphemeralMessages() throws InterruptedException {
final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID());
@@ -1048,7 +1054,6 @@ class FoundationDbMessageStoreTest {
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci, Device.PRIMARY_ID,
FoundationDbMessageStream.DEFAULT_MAX_MESSAGES_PER_SCAN,
FoundationDbMessageStream.DEFAULT_MAX_UNACKNOWLEDGED_MESSAGES,
cleanUpLatch::countDown);
StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messageStream.getMessages()))
// We should have discarded the already-inserted ephemeral message
@@ -8,26 +8,26 @@ package org.whispersystems.textsecuregcm.subscriptions;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.braintree.graphql.clientoperation.CreatePayPalOneTimePaymentMutation;
import jakarta.ws.rs.ServiceUnavailableException;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.http.HttpHeaders;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.whispersystems.textsecuregcm.http.FaultTolerantHttpClient;
@ExtendWith(MockitoExtension.class)
class BraintreeGraphqlClientTest {
private static final String CURRENCY = "xts";
@@ -36,49 +36,40 @@ class BraintreeGraphqlClientTest {
private static final String LOCALE = "xx";
private static final String LOCALIZED_LINE_ITEM_NAME = "Donation to Signal Technology Foundation";
@Mock
private FaultTolerantHttpClient httpClient;
@Mock
private HttpResponse<Object> response;
private BraintreeGraphqlClient braintreeGraphqlClient;
@BeforeEach
void setUp() {
httpClient = mock(FaultTolerantHttpClient.class);
void setUp() throws IOException {
lenient().when(httpClient.send(any(), any())).thenReturn(response);
braintreeGraphqlClient = new BraintreeGraphqlClient(httpClient, "https://example.com", "public", "super-secret");
}
@Test
void createPayPalOneTimePayment() {
final HttpResponse<Object> response = mock(HttpResponse.class);
when(httpClient.sendAsync(any(), any()))
.thenReturn(CompletableFuture.completedFuture(response));
void createPayPalOneTimePayment() throws IOException {
final String paymentId = "PAYID-AAA1AAAA1A11111AA111111A";
when(response.body())
.thenReturn(createPayPalOneTimePaymentResponse(paymentId));
when(response.statusCode())
.thenReturn(200);
final CompletableFuture<CreatePayPalOneTimePaymentMutation.CreatePayPalOneTimePayment> future = braintreeGraphqlClient.createPayPalOneTimePayment(
final CreatePayPalOneTimePaymentMutation.CreatePayPalOneTimePayment result = braintreeGraphqlClient.createPayPalOneTimePayment(
BigDecimal.ONE, CURRENCY,
RETURN_URL, CANCEL_URL, LOCALE, LOCALIZED_LINE_ITEM_NAME);
assertTimeoutPreemptively(Duration.ofSeconds(3), () -> {
final CreatePayPalOneTimePaymentMutation.CreatePayPalOneTimePayment result = future.get();
assertEquals(paymentId, result.paymentId);
assertNotNull(result.approvalUrl);
});
}
@Test
void createPayPalOneTimePaymentHttpError() {
final HttpResponse<Object> response = mock(HttpResponse.class);
when(httpClient.sendAsync(any(), any()))
.thenReturn(CompletableFuture.completedFuture(response));
void createPayPalOneTimePaymentHttpError() throws IOException {
when(response.statusCode())
.thenReturn(500);
final HttpHeaders httpheaders = mock(HttpHeaders.class);
@@ -86,39 +77,21 @@ class BraintreeGraphqlClientTest {
when(response.headers())
.thenReturn(httpheaders);
final CompletableFuture<CreatePayPalOneTimePaymentMutation.CreatePayPalOneTimePayment> future = braintreeGraphqlClient.createPayPalOneTimePayment(
assertThrows(IOException.class, () -> braintreeGraphqlClient.createPayPalOneTimePayment(
BigDecimal.ONE, CURRENCY,
RETURN_URL, CANCEL_URL, LOCALE, LOCALIZED_LINE_ITEM_NAME);
assertTimeoutPreemptively(Duration.ofSeconds(3), () -> {
final ExecutionException e = assertThrows(ExecutionException.class, future::get);
assertTrue(e.getCause() instanceof ServiceUnavailableException);
});
RETURN_URL, CANCEL_URL, LOCALE, LOCALIZED_LINE_ITEM_NAME));
}
@Test
void createPayPalOneTimePaymentGraphQlError() {
final HttpResponse<Object> response = mock(HttpResponse.class);
when(httpClient.sendAsync(any(), any()))
.thenReturn(CompletableFuture.completedFuture(response));
when(response.body())
.thenReturn(createErrorResponse("createPayPalOneTimePayment", "12345"));
when(response.statusCode())
.thenReturn(200);
final CompletableFuture<CreatePayPalOneTimePaymentMutation.CreatePayPalOneTimePayment> future = braintreeGraphqlClient.createPayPalOneTimePayment(
assertThrows(IOException.class, () -> braintreeGraphqlClient.createPayPalOneTimePayment(
BigDecimal.ONE, CURRENCY,
RETURN_URL, CANCEL_URL, LOCALE, LOCALIZED_LINE_ITEM_NAME);
assertTimeoutPreemptively(Duration.ofSeconds(3), () -> {
final ExecutionException e = assertThrows(ExecutionException.class, future::get);
assertTrue(e.getCause() instanceof ServiceUnavailableException);
});
RETURN_URL, CANCEL_URL, LOCALE, LOCALIZED_LINE_ITEM_NAME));
}
private String createPayPalOneTimePaymentResponse(final String paymentId) {
@@ -0,0 +1,124 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.workers;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import net.sourceforge.argparse4j.inf.Namespace;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.MessagesManager;
import org.whispersystems.textsecuregcm.util.TestClock;
import reactor.core.publisher.Flux;
class ClearExpiredFoundationDbMessagesCommandTest {
private MessagesManager messagesManager = mock(MessagesManager.class);
private static class TestClearExpiredFoundationDbMessagesCommand extends ClearExpiredFoundationDbMessagesCommand {
private final CommandDependencies commandDependencies;
private final boolean dryRun;
public TestClearExpiredFoundationDbMessagesCommand(final MessagesManager messagesManager,
final boolean dryRun,
final Clock clock) {
super(clock);
this.commandDependencies = new CommandDependencies(null, null, null, null, messagesManager, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null);
this.dryRun = dryRun;
}
@Override
protected CommandDependencies getCommandDependencies() {
return commandDependencies;
}
@Override
protected Namespace getNamespace() {
return new Namespace(Map.of(
ClearExpiredFoundationDbMessagesCommand.BATCH_SIZE_ARGUMENT, 4,
ClearExpiredFoundationDbMessagesCommand.DRY_RUN_ARGUMENT, dryRun,
ClearExpiredFoundationDbMessagesCommand.MESSAGE_TTL_DAYS_ARGUMENT, 1,
ClearExpiredFoundationDbMessagesCommand.VERSIONSTAMP_TTL_DAYS_ARGUMENT, 10
));
}
}
@ParameterizedTest
@ValueSource(booleans={true, false})
void crawlAccounts(final boolean dryRun) {
final Clock clock = TestClock.pinned(Instant.now());
final Instant messageCutoffTime = clock.instant().minus(Duration.ofDays(1));
final Instant versionstampCutoffTime = clock.instant().minus(Duration.ofDays(10));
final TestClearExpiredFoundationDbMessagesCommand clearExpiredFoundationDbMessagesCommand =
new TestClearExpiredFoundationDbMessagesCommand(messagesManager,
dryRun,
clock);
final List<Account> accounts = new ArrayList<>();
final AciServiceIdentifier[] acis = new AciServiceIdentifier[10];
for (int i = 0; i < 10; i++) {
final UUID accountIdentifier = UUID.randomUUID();
final byte primaryDeviceId = Device.PRIMARY_ID;
final byte linkedDeviceId = 2;
final Device primaryDevice = mock(Device.class);
when(primaryDevice.getId()).thenReturn(primaryDeviceId);
final Device linkedDevice = mock(Device.class);
when(linkedDevice.getId()).thenReturn(linkedDeviceId);
final Account account = mock(Account.class);
when(account.getIdentifier(IdentityType.ACI)).thenReturn(accountIdentifier);
when(account.getDevices()).thenReturn(i % 2 == 0 ? List.of(primaryDevice) : List.of(primaryDevice, linkedDevice));
accounts.add(account);
acis[i] = new AciServiceIdentifier(accountIdentifier);
}
clearExpiredFoundationDbMessagesCommand.crawlAccounts(Flux.fromIterable(accounts));
final List<Byte> oneDeviceId = List.of(Device.PRIMARY_ID);
final List<Byte> twoDeviceIds = List.of(Device.PRIMARY_ID, (byte) 2);
if (!dryRun) {
verify(messagesManager).deleteFoundationDbMessagesBefore(
Map.of(acis[0], oneDeviceId, acis[1], twoDeviceIds, acis[2], oneDeviceId, acis[3], twoDeviceIds),
messageCutoffTime);
verify(messagesManager).deleteFoundationDbMessagesBefore(
Map.of(acis[4], oneDeviceId, acis[5], twoDeviceIds, acis[6], oneDeviceId, acis[7], twoDeviceIds),
messageCutoffTime);
verify(messagesManager).deleteFoundationDbMessagesBefore(
Map.of(acis[8], oneDeviceId, acis[9], twoDeviceIds),
messageCutoffTime);
} else {
verify(messagesManager, never()).deleteFoundationDbMessagesBefore(any(), any());
}
verify(messagesManager).recordFoundationDbVersionstamps();
verify(messagesManager)
.expireOldFoundationDbVersionstamps(versionstampCutoffTime);
}
}
@@ -155,10 +155,8 @@ storageService.userAuthenticationTokenSharedSecret: AAAAAAAAAAAAAAAAAAAAAAAAAAAA
# The below secrets were generated exclusively for testing purposes. Do not use them in any other context.
zkConfig-libsignal-0.42.serverSecret: ALxy0qUiV9B3OgF1GzTgn6g4NSN22ww87p5xOlYkypQJIqxoTBGOPREr4ZXvOfQ/tFYQJxn3xoFJ5DKt+mDOJw8KzWephNaaXBSLcbWb/fPfSUjoXnPL+fcU26OpMIUrIVews/i0Eh4ongRWuLfFUpLyZ34wfgpKkWbIUBjbVT4M5e7GzRPVFOBGibICk9Q66o9l3K4PphKaoMQKlGPo4g85xsVH1HFN5J5u4/pdq80+3E7WvWN4c8NpDZQ7RqtECDpawSc/J4vim9tL7QR6hFYwzvA0cmCcM0NCPFpp69EHB1eRksDvPHiA+NuMqoFwXwIzSHzA86ALPxnyLKB7KgBG06DxfMmMav3dij6giTawgATRsoNFLQ/ol6H0TtYJCAp8oB0D4EV2q7hSue3Kxzh1Vc88/nmLuRR9G3EefC0+CMcxJFQwDMgjFvFBKx3o6m9gJLevYiKcm/NxXX9WtnEzqAh2DRr0G0fvk9NZF2Lw2kWgAX2qkPHZLJ3nKA90BgryBAJsk8Q78N5ghBhQzdgikURLC+mX1fbmMzkmGcwCYDnLpo8qjrIoBZzDAjI4Ty04MaJcLowJqNMmK29btza50WiZdsd4tuVqQAKlqJcERCsUewlZSkWpsDLrZkeUBY0rGCi51FW5WOUvdXwTHtTL2hlcBqP/E8cbBC+yce8AurjJ6Z9HVtM7tVk7a5xRAqwoFRSH7eq5BA60hDq2sgWIQaN1owunKZvsHFn0qzoGKuWAEO0PpbGbHtFDUjxzBkgUIN13yIbem9KPeZm9ZVrjkyDo3uZZsfFFUHnFeasKOt9WMJLLx1s7DttJ4Ns2o02q4e+aQ60oMeWsyMuzKgNMDHgDgfqHxbCi2rm20SgoHnuoph6XArmEOX6a1xLJVxgDtgfm1IbcyyqROXYxe9v2RvMUAnjbLI/fm0rXXhldjVX7Yoo7ZGAlVBuGOC28haRrd684Lcajdequ6Css1geOzOVVH/BGnJtf3RFSMXIv/YByG21/cgL9KFYqQHqZZeLNQpweILMnU0/iVK/fjLvrhyI2jNy1B0Ox62zE2o8EdVT/H1WgXa2NHC591aEqI5EXwribRKUM56v/O3IDBAxC5CLIQcUeDhWouaFqXjfxNza9rFC69smtUXl3sx8KG6Ze7VkXb372daAN+rMWIdq5kbRcetkXxuqTuYOz4NsDnEPnBNNO6hqOv6+dZAQK3wmhOah3NIL0kKNUHpuk+gidQkLehBvahNKpUfh9yBMkEcLNkR7D1r8fAcrA7u2sCKfRero8FOkCc9ChawShJXdcGtKv50d2/4vJp9B0ddUBYdFnbM/siX4VJghb+rSkhCkkXXS7QXFfbO5A4WJLkwthkNezNgqCBmEoda7UcOOaW9KQMFisRy74OZagCUAJCPC4UJw1/N4IJD7Dtw2cNtaxwFyuG6i7sdm9u3Xr9h0JcvKn5Z3BLxmR6WkhO/IraGw+9/ijFpEtB9VFhdQxfnnj4JRneZtQxC9nAY0liDuO41OhGYaWinVVRkljKe7GAmw726P1wYiyd2ajlkbI/7KB9VwxEicEijeyuR6UZDUFqOPk4q+fdkBRS2GuGKiy4ISgha6sVRkb5sLlAsRhmG1W0Anh8d2dHxmE8CzyoAXbschIeY2LJTUIORpvAaFrDI74dagBDNlIVnHw89PGYWnosia9YFMLpsYyjOccQKAGKJLZ8MdcgRw8W2Mw2AwZbQWUUU1VZxdWX6y878WJ6g4at5NJ2YpdZ/qh5zBTDbTDpGnTsv9Ioyw5+91h6qagDXecb1wekN0RZsI3KWXQeOZZ+uxTNRqqpWZhH9QtrEsPRdNyOlVJDmJ1H2Rl3o30Crt8j6EM6ZgR444GuDf/jATe9shz3Ljc0S5/OTEAJL54OfHq9jGgtXS+05AuhlxCC9zYpEBb30xnZD6zxXnz6IB//uVROuWc1BEFhkvn+JcJxpapbKH6PthuOzMVRkf+I3Xz3/bNjiQSlQkmAXlgB1YujgABYnJ6yJXQKP2mR4UJ3UYoGroYoafWycDa+vUYYqIMcK6tbIgvxFx8TmMoQ1MueOIzDt0Nyx3Uov5qVvcG8gyflIv4fbzlu7GTYE8Ov6sRGY8KzF5ywxvrq0VldgfoGF4AGdQ3RxB5EDdlHIvlOG8VRoD+7Ch/S1kemdyvD2co9wN/GfU58Q1DO7dSQTl/O86t1eZBp+8H4IIarAgLunN/vkV34LAYjk1DOfeNxrCnfHz9RWtT3Vy3FJKuaQUotgZRyu36BLSs/ozriMR1nkT2+Luknw/zDD496ZvyAwvtG18Tk5B5b3DSMSUq9vA4h8KKCFfkgTHNeOHFyogNkfwaeGEflkrckI4RTtGrIL+lmW+1LYRoDU8F2T4VzAnyqsfmfT5+g6nbzw7FRXGfEu/E94Xaacj0t90t+eqtBruaoJ9kqw4iJmQdrSonz4fo4yOAXukaTnzFnalXZdoFjNpSbMWOwFhalgT4fI8mUnZBoVOulWrFfs1exJuDy3fki99Z9kwT1gFnZ4SsO6fCRoTiINCEeXkhcCFscOuvZP9su7zhyXWhobzNsct/ejd+CHyDKoNPBjNId5hGwnIAP5F55x+n51UIPvCkotwIGsvbfExLMw/JgwCJCDSHNgZEmXO+xEVozKRbUDK8d0mR46M59k8qaPKkKAORatQPVXOyszQTLx8gnPf/HDDqthyyp7mfjfE09vv3CpREfzkGYZpMWv1aDG2AHpAdrOH3cVW2UQq9uPRtkiHZMZg9CQnapTCmq3YAvsKugvU2CnrnJlACFYO1Hr5RpjfIRMCkBrfHrdFQEwB4/u6opMApJThcbXzhbVEwIwOq/ZcleloJKnN4GdaZyLFphtApVSuMVYDNm0X6KNGSl1kFbgxs8gBBhLxXqqhdfoBnwOtOXHO+kFGY1WzGUJZviHD43glxBIWPRSjD0pPvuWX91IWv/GZuCIkwCa34p+P9v7iKRuoBGievGCJJ+5SUoBQyhhQdpG+gbw1Bs3KSPwkx0IulpQqkInUCyVgxRXZWI61AkDNr7ybYMhq0nPPY3V0xYzN9Wltf8c37m3IWVkzGR3a0JjoUUWtFaCY9fasiOQM1nZUMe/0UTV2ZKjD4US9c2PEHrPPlwVowar4PlUJU1KIAjgsCyo9DhZPyEgPjGYu+tGpMcUImLukfebXsgzFFhyLgLktlMwFHNn6JHchCURY58OOcMzDKK/6IuLU621a+d8gP8U22MozRrL+GNEYwiyF9XM4Hp+ovB3yv6VFkBp7ukAJDETnNy+nPPjt0ShUpp4hj+WDWo/fs6Oy/fs0wPdziBPrWQ7Dn0vDGsXVbTib8rd4UucpZdGaY1yktsG4MNHAMVv+IH1hYcg87bfsUJbfuHgvLB1l5Qz8j7/Ezi54RFQBGS3QkDQnCl/mMmrNCe5xe1soC+rsCRblHuJjujjK/CxgYEs2Lc9ZWPc3FyzGQbblH5hUX1MxP0V1DM/VxpI8EGVWTk6Q3W1yX16EiWkauVbHsyScbniotURYRstCUmA1Qnz9bsSBgjuCftVHZZ4lFmWogd976tG5uGQ+tvu6xCqH+EsGOQ843I/5w0xTPTJcFyQ9cuRoTPzFIeP2wa9AA
genericZkConfig.serverSecret: AIZmPk8ms6TWBTGFcFE1iEuu4kSpTRL1EAPA2ZVWm4EIIF/N811ZhILbCx8QSLBf90mNXhUtsfNF5PY5UdnJMgBGu3AtrVs5erRXf5hi6RxvCkl1QnYs/tcuUGNbkejyR9bPR2uJaK6CxGJS0RRUDWf8f2hQloe/+kWKilM1I/MHSV2+PcyCDJIigPi9RhbD2STXc6cHEpYXReg+1OYSEQk3K2M0qnUoVOAjbPuFXANEPU+106f37w/iF6MhyfWyDCb+oit29DFtoDS31cxheB3x1KVga2ErfnIyHpQrSWYHUdGPZLXc0xRmaa0VwDyyXzK0o3w4oS/F9+xqWYUWkwgsAm9e7dP4l0qVolnPQ67uNj7BFG4JQ0vXxD/JJQ+5B4bHyK+v5ndJpRMXDC9rJw8ehopvDCTXSoICqN7nvY8Fyqhf5zkM880Su2XiBa2paDTVuZgwq07zBeDrrPc2zQ8A4neV6++t95veOfpp94FymnHJ8ILaznKqzJluGDdtCA==
callingZkConfig.serverSecret: AIZmPk8ms6TWBTGFcFE1iEuu4kSpTRL1EAPA2ZVWm4EIIF/N811ZhILbCx8QSLBf90mNXhUtsfNF5PY5UdnJMgBGu3AtrVs5erRXf5hi6RxvCkl1QnYs/tcuUGNbkejyR9bPR2uJaK6CxGJS0RRUDWf8f2hQloe/+kWKilM1I/MHSV2+PcyCDJIigPi9RhbD2STXc6cHEpYXReg+1OYSEQk3K2M0qnUoVOAjbPuFXANEPU+106f37w/iF6MhyfWyDCb+oit29DFtoDS31cxheB3x1KVga2ErfnIyHpQrSWYHUdGPZLXc0xRmaa0VwDyyXzK0o3w4oS/F9+xqWYUWkwgsAm9e7dP4l0qVolnPQ67uNj7BFG4JQ0vXxD/JJQ+5B4bHyK+v5ndJpRMXDC9rJw8ehopvDCTXSoICqN7nvY8Fyqhf5zkM880Su2XiBa2paDTVuZgwq07zBeDrrPc2zQ8A4neV6++t95veOfpp94FymnHJ8ILaznKqzJluGDdtCA==
backupsZkConfig.serverSecret: AIZmPk8ms6TWBTGFcFE1iEuu4kSpTRL1EAPA2ZVWm4EIIF/N811ZhILbCx8QSLBf90mNXhUtsfNF5PY5UdnJMgBGu3AtrVs5erRXf5hi6RxvCkl1QnYs/tcuUGNbkejyR9bPR2uJaK6CxGJS0RRUDWf8f2hQloe/+kWKilM1I/MHSV2+PcyCDJIigPi9RhbD2STXc6cHEpYXReg+1OYSEQk3K2M0qnUoVOAjbPuFXANEPU+106f37w/iF6MhyfWyDCb+oit29DFtoDS31cxheB3x1KVga2ErfnIyHpQrSWYHUdGPZLXc0xRmaa0VwDyyXzK0o3w4oS/F9+xqWYUWkwgsAm9e7dP4l0qVolnPQ67uNj7BFG4JQ0vXxD/JJQ+5B4bHyK+v5ndJpRMXDC9rJw8ehopvDCTXSoICqN7nvY8Fyqhf5zkM880Su2XiBa2paDTVuZgwq07zBeDrrPc2zQ8A4neV6++t95veOfpp94FymnHJ8ILaznKqzJluGDdtCA==
profileAvatarsZkConfig.serverSecret: AIZmPk8ms6TWBTGFcFE1iEuu4kSpTRL1EAPA2ZVWm4EIIF/N811ZhILbCx8QSLBf90mNXhUtsfNF5PY5UdnJMgBGu3AtrVs5erRXf5hi6RxvCkl1QnYs/tcuUGNbkejyR9bPR2uJaK6CxGJS0RRUDWf8f2hQloe/+kWKilM1I/MHSV2+PcyCDJIigPi9RhbD2STXc6cHEpYXReg+1OYSEQk3K2M0qnUoVOAjbPuFXANEPU+106f37w/iF6MhyfWyDCb+oit29DFtoDS31cxheB3x1KVga2ErfnIyHpQrSWYHUdGPZLXc0xRmaa0VwDyyXzK0o3w4oS/F9+xqWYUWkwgsAm9e7dP4l0qVolnPQ67uNj7BFG4JQ0vXxD/JJQ+5B4bHyK+v5ndJpRMXDC9rJw8ehopvDCTXSoICqN7nvY8Fyqhf5zkM880Su2XiBa2paDTVuZgwq07zBeDrrPc2zQ8A4neV6++t95veOfpp94FymnHJ8ILaznKqzJluGDdtCA==
chatZkConfig.serverSecret: AIZmPk8ms6TWBTGFcFE1iEuu4kSpTRL1EAPA2ZVWm4EIIF/N811ZhILbCx8QSLBf90mNXhUtsfNF5PY5UdnJMgBGu3AtrVs5erRXf5hi6RxvCkl1QnYs/tcuUGNbkejyR9bPR2uJaK6CxGJS0RRUDWf8f2hQloe/+kWKilM1I/MHSV2+PcyCDJIigPi9RhbD2STXc6cHEpYXReg+1OYSEQk3K2M0qnUoVOAjbPuFXANEPU+106f37w/iF6MhyfWyDCb+oit29DFtoDS31cxheB3x1KVga2ErfnIyHpQrSWYHUdGPZLXc0xRmaa0VwDyyXzK0o3w4oS/F9+xqWYUWkwgsAm9e7dP4l0qVolnPQ67uNj7BFG4JQ0vXxD/JJQ+5B4bHyK+v5ndJpRMXDC9rJw8ehopvDCTXSoICqN7nvY8Fyqhf5zkM880Su2XiBa2paDTVuZgwq07zBeDrrPc2zQ8A4neV6++t95veOfpp94FymnHJ8ILaznKqzJluGDdtCA==
paymentsService.userAuthenticationTokenSharedSecret: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= # base64-encoded 32-byte secret shared with MobileCoin services used to generate auth tokens for Signal users
paymentsService.fixerApiKey: unset
+5 -10
View File
@@ -327,18 +327,15 @@ storageService:
9Kxq0DY7RCEpdHMCKcOL
-----END CERTIFICATE-----
zkConfig:
serverPublic: AAp8oB0D4EV2q7hSue3Kxzh1Vc88/nmLuRR9G3EefC0+CMcxJFQwDMgjFvFBKx3o6m9gJLevYiKcm/NxXX9WtnFMDHgDgfqHxbCi2rm20SgoHnuoph6XArmEOX6a1xLJVxgDtgfm1IbcyyqROXYxe9v2RvMUAnjbLI/fm0rXXhldjszlVR/wRpybX90RUjFyL/2Achttf3IC/ShWKkB6mWXwuFCcNfzeCCQ+w7cNnDbWscBcrhuou7HZvbt16/YdCXLyp+WdwS8ZkelpITvyK2hsPvf4oxaRLQfVRYXUMX55xpapbKH6PthuOzMVRkf+I3Xz3/bNjiQSlQkmAXlgB1YujgABYnJ6yJXQKP2mR4UJ3UYoGroYoafWycDa+vUYYozaUmzFjsBYWpYE+HyPJlJ2QaFTrpVqxX7NXsSbg8t35IvfWfZME9YBZ2eErDunwkaE4iDQhHl5IXAhbHDrr2QaJ68YIkn7lJSgFDKGFB2kb6BvDUGzcpI/CTHQi6WlCqQidQLJWDFFdlYjrUCQM2vvJtgyGrSc89jdXTFjM31aqmtcPWgWL0qv+RmK/BC392Nsu8WoSJcAE4yhccQuRSemtolgwewnjasoOFBNOPh4+pX55SwhyTVgtwl+NTNVNFydxGp9Me8ogRWElzwA9BFtNAgQtlfgIyZRTetFqLkYmIBDxwMcpizDKES5lPhV2uJJuzcMq/06mVQz2OrXgglWk01uN8U59pfNFpTZhcGQv+MHjwEAudq5eLpt3aFrdxJ7D26Fwl5j215SJ0yZo7vmSEML1vf7FaGh0IL57bRpCvdebB5WapSChUX+PPvCXohVjGrERFvQpeET6pydGGlEKYLWuWa3zFGmPvJJYZ/QfcmIP9zyhqzQT/7a7RIqFA==
serverSecret: secret://zkConfig-libsignal-0.42.serverSecret
callingZkConfig:
serverSecret: secret://callingZkConfig.serverSecret
backupsZkConfig:
serverSecret: secret://backupsZkConfig.serverSecret
chatZkConfig:
serverSecret: secret://chatZkConfig.serverSecret
profileAvatarsZkConfig:
serverSecret: secret://profileAvatarsZkConfig.serverSecret
groupsZkConfig:
serverPublic: AAp8oB0D4EV2q7hSue3Kxzh1Vc88/nmLuRR9G3EefC0+CMcxJFQwDMgjFvFBKx3o6m9gJLevYiKcm/NxXX9WtnFMDHgDgfqHxbCi2rm20SgoHnuoph6XArmEOX6a1xLJVxgDtgfm1IbcyyqROXYxe9v2RvMUAnjbLI/fm0rXXhldjszlVR/wRpybX90RUjFyL/2Achttf3IC/ShWKkB6mWXwuFCcNfzeCCQ+w7cNnDbWscBcrhuou7HZvbt16/YdCXLyp+WdwS8ZkelpITvyK2hsPvf4oxaRLQfVRYXUMX55xpapbKH6PthuOzMVRkf+I3Xz3/bNjiQSlQkmAXlgB1YujgABYnJ6yJXQKP2mR4UJ3UYoGroYoafWycDa+vUYYozaUmzFjsBYWpYE+HyPJlJ2QaFTrpVqxX7NXsSbg8t35IvfWfZME9YBZ2eErDunwkaE4iDQhHl5IXAhbHDrr2QaJ68YIkn7lJSgFDKGFB2kb6BvDUGzcpI/CTHQi6WlCqQidQLJWDFFdlYjrUCQM2vvJtgyGrSc89jdXTFjM31aqmtcPWgWL0qv+RmK/BC392Nsu8WoSJcAE4yhccQuRSemtolgwewnjasoOFBNOPh4+pX55SwhyTVgtwl+NTNVNFydxGp9Me8ogRWElzwA9BFtNAgQtlfgIyZRTetFqLkYmIBDxwMcpizDKES5lPhV2uJJuzcMq/06mVQz2OrXgglWk01uN8U59pfNFpTZhcGQv+MHjwEAudq5eLpt3aFrdxJ7D26Fwl5j215SJ0yZo7vmSEML1vf7FaGh0IL57bRpCvdebB5WapSChUX+PPvCXohVjGrERFvQpeET6pydGGlEKYLWuWa3zFGmPvJJYZ/QfcmIP9zyhqzQT/7a7RIqFA==
serverSecret: secret://zkConfig-libsignal-0.42.serverSecret
dynamicConfig:
type: static
@@ -375,8 +372,6 @@ badges:
svgs:
- light: example-light.svg
dark: example-dark.svg
badgeIdsEnabledForAll:
- TEST
receiptLevels:
'1': TEST