mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-12-01 15:56:47 +00:00
Compare commits
19
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5174550ef3 | ||
|
|
d0fcb9ab54 | ||
|
|
375150a8c3 | ||
|
|
cb28614721 | ||
|
|
f02caf78cd | ||
|
|
8fd72549fb | ||
|
|
1e4774820f | ||
|
|
48cdad7e57 | ||
|
|
392bab5b60 | ||
|
|
6b67604fe7 | ||
|
|
67a03f81b9 | ||
|
|
90b75cbf22 | ||
|
|
4dede4acad | ||
|
|
d225ba3618 | ||
|
|
8790514b8a | ||
|
|
fa4d3c7ca9 | ||
|
|
1f0b2ad92d | ||
|
|
feb00c6ba6 | ||
|
|
f588390bdb |
No files matched your search
@@ -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
|
||||
|
||||
@@ -18,13 +18,13 @@ jobs:
|
||||
id-token: write
|
||||
contents: read
|
||||
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 }}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -79,9 +79,8 @@ storageService.userAuthenticationTokenSharedSecret: AAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
||||
|
||||
zkConfig-libsignal-0.42.serverSecret: ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdef
|
||||
|
||||
genericZkConfig.serverSecret: ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzAA==
|
||||
callingZkConfig.serverSecret: ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzAA==
|
||||
backupsZkConfig.serverSecret: ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzAA==
|
||||
chatZkConfig.serverSecret: ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzAA==
|
||||
|
||||
paymentsService.userAuthenticationTokenSharedSecret: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= # base64-encoded 32-byte secret shared with MobileCoin services used to generate auth tokens for Signal users
|
||||
paymentsService.fixerApiKey: unset
|
||||
|
||||
@@ -128,6 +128,8 @@ dynamoDbTables:
|
||||
expiration: P90D
|
||||
phoneNumberIdentifiers:
|
||||
tableName: Example_PhoneNumberIdentifiers
|
||||
profileAvatars:
|
||||
tableName: Example_ProfileAvatars
|
||||
profiles:
|
||||
tableName: Example_Profiles
|
||||
profilesV2:
|
||||
@@ -316,15 +318,15 @@ storageService:
|
||||
AAAAAAAAAAAAAAAAAAAA
|
||||
-----END CERTIFICATE-----
|
||||
|
||||
zkConfig:
|
||||
serverPublic: ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzAB==
|
||||
serverSecret: secret://zkConfig-libsignal-0.42.serverSecret
|
||||
|
||||
callingZkConfig:
|
||||
serverSecret: secret://callingZkConfig.serverSecret
|
||||
|
||||
backupsZkConfig:
|
||||
serverSecret: secret://backupsZkConfig.serverSecret
|
||||
chatZkConfig:
|
||||
serverSecret: secret://chatZkConfig.serverSecret
|
||||
|
||||
groupsZkConfig:
|
||||
serverPublic: ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzAB==
|
||||
serverSecret: secret://zkConfig-libsignal-0.42.serverSecret
|
||||
|
||||
dynamicConfig:
|
||||
s3Region: a-region
|
||||
|
||||
+24
-11
@@ -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,7 +234,12 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
private GenericZkConfig backupsZkConfig;
|
||||
private GenericZkConfig chatZkConfig;
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
private ZkConfig groupsZkConfig;
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@@ -423,6 +429,10 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
return gcpAttachments;
|
||||
}
|
||||
|
||||
public BackupConfiguration getBackupConfiguration() {
|
||||
return backup;
|
||||
}
|
||||
|
||||
public FaultTolerantRedisClusterFactory getCacheClusterConfiguration() {
|
||||
return cacheCluster;
|
||||
}
|
||||
@@ -487,16 +497,19 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
return paymentsService;
|
||||
}
|
||||
|
||||
public ZkConfig getZkConfig() {
|
||||
return zkConfig;
|
||||
/// ZK secret limited to Chat Service
|
||||
public GenericZkConfig getChatZkConfig() {
|
||||
return chatZkConfig;
|
||||
}
|
||||
|
||||
/// ZK secret shared with Calling Service
|
||||
public GenericZkConfig getCallingZkConfig() {
|
||||
return callingZkConfig;
|
||||
}
|
||||
|
||||
public GenericZkConfig getBackupsZkConfig() {
|
||||
return backupsZkConfig;
|
||||
/// ZK secret shared with Groups Service
|
||||
public ZkConfig getGroupsZkConfig() {
|
||||
return groupsZkConfig;
|
||||
}
|
||||
|
||||
public RemoteConfigConfiguration getRemoteConfigConfiguration() {
|
||||
|
||||
@@ -265,6 +265,7 @@ import org.whispersystems.textsecuregcm.storage.OneTimeDonationsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.PagedSingleUseKEMPreKeyStore;
|
||||
import org.whispersystems.textsecuregcm.storage.PersistentTimer;
|
||||
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
|
||||
import org.whispersystems.textsecuregcm.storage.ProfileAvatars;
|
||||
import org.whispersystems.textsecuregcm.storage.Profiles;
|
||||
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ProfilesV2;
|
||||
@@ -538,6 +539,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
Profiles profilesV1 = new Profiles(dynamoDbClient, dynamoDbAsyncClient,
|
||||
config.getDynamoDbTables().getProfilesV1().getTableName());
|
||||
ProfilesV2 profiles = new ProfilesV2(dynamoDbClient, dynamoDbAsyncClient, config.getDynamoDbTables().getProfilesV2().getTableName());
|
||||
ProfileAvatars profileAvatars = new ProfileAvatars(dynamoDbClient,
|
||||
config.getDynamoDbTables().getProfileAvatars().getTableName(), RemoveExpiredAccountsCommand.MAX_IDLE_DURATION, clock);
|
||||
|
||||
S3AsyncClient asyncKeysS3Client = S3AsyncClient.builder()
|
||||
.credentialsProvider(awsCredentialsProvider)
|
||||
@@ -618,6 +621,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
.threads(16).build();
|
||||
final ScheduledExecutorService registrationIdentityTokenRefreshExecutor =
|
||||
ScheduledExecutorServiceBuilder.of(environment, "registrationIdentityTokenRefresh").threads(1).build();
|
||||
final ScheduledExecutorService presenceRenewalExecutor =
|
||||
ScheduledExecutorServiceBuilder.of(environment, "presenceRenewal").threads(4).build();
|
||||
|
||||
Scheduler messageDeliveryScheduler = Schedulers.fromExecutorService(
|
||||
ExecutorServiceBuilder.of(environment, "messageDelivery")
|
||||
@@ -740,7 +745,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
storageServiceExecutor, retryExecutor, config.getSecureStorageServiceConfiguration());
|
||||
DisconnectionRequestManager disconnectionRequestManager = new DisconnectionRequestManager(pubsubClient,
|
||||
disconnectionRequestListenerExecutor, retryExecutor);
|
||||
ProfilesManager profilesManager = new ProfilesManager(profilesV1, profiles, cacheCluster, retryExecutor, asyncCdnS3Client,
|
||||
ProfilesManager profilesManager = new ProfilesManager(profilesV1, profiles, profileAvatars, cacheCluster, retryExecutor, asyncCdnS3Client,
|
||||
config.getCdnConfiguration().bucket());
|
||||
MessagesCache messagesCache = new MessagesCache(messagesCluster, messageDeliveryScheduler,
|
||||
messageDeletionAsyncExecutor, retryExecutor, clock);
|
||||
@@ -748,6 +753,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
config.getFoundationDbMessagesConfiguration().activeEpoch(),
|
||||
new VersionstampUUIDCipher(config.getFoundationDbMessagesConfiguration().currentVersionstampCipherKey(),
|
||||
config.getFoundationDbMessagesConfiguration().versionstampCipherKeys().get(config.getFoundationDbMessagesConfiguration().currentVersionstampCipherKey()).value()),
|
||||
presenceRenewalExecutor,
|
||||
Clock.systemUTC());
|
||||
ClientReleaseManager clientReleaseManager = new ClientReleaseManager(clientReleases,
|
||||
recurringJobExecutor,
|
||||
@@ -908,17 +914,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());
|
||||
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(),
|
||||
@@ -929,7 +936,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
config.getCdn3StorageManagerConfiguration());
|
||||
BackupManager backupManager = new BackupManager(
|
||||
backupsDb,
|
||||
backupsGenericZkSecretParams,
|
||||
chatGenericZkSecretParams,
|
||||
rateLimiters,
|
||||
tusAttachmentGenerator,
|
||||
cdn3BackupCredentialGenerator,
|
||||
@@ -937,7 +944,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
svrbCredentialsGenerator,
|
||||
secureValueRecoveryBClient,
|
||||
clock,
|
||||
dynamicConfigurationManager);
|
||||
config.getBackupConfiguration());
|
||||
final BackupMetrics backupMetrics = new BackupMetrics();
|
||||
|
||||
final AppleDeviceChecks appleDeviceChecks = new AppleDeviceChecks(
|
||||
@@ -954,7 +961,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,
|
||||
@@ -1047,7 +1054,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,
|
||||
@@ -1064,7 +1071,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
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, 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),
|
||||
@@ -1089,14 +1096,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, zkSecretParams),
|
||||
new KeysAnonymousGrpcService(accountsManager, keysManager, groupZkSecretParams, Clock.systemUTC()),
|
||||
new ProfileAnonymousGrpcService(accountsManager, profilesManager, profileBadgeConverter, profileCdnPolicyGenerator, chatGenericZkSecretParams, groupZkSecretParams, rateLimiters, clock),
|
||||
new MessagesAnonymousGrpcService(accountsManager, rateLimiters, messageSender, groupSendTokenUtil, messageByteLimitCardinalityEstimator, spamChecker, Clock.systemUTC()),
|
||||
new BackupsAnonymousGrpcService(backupManager, backupMetrics, config.getAttachments().maxAttachmentUploadSizeInBytes(), config.getAttachments().maxMessageBackupUploadSizeInBytes()),
|
||||
new CredentialsAnonymousGrpcService(accountsManager, ExternalServiceDefinitions.SVR.generatorFactory().apply(config, Clock.systemUTC())),
|
||||
new 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))
|
||||
@@ -1231,14 +1237,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),
|
||||
@@ -1252,7 +1258,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)
|
||||
@@ -1371,7 +1378,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
static void main(String[] args) throws Exception {
|
||||
new WhisperServerService().run(args);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
+5
@@ -45,6 +45,11 @@ public class ConfiguredProfileBadgeConverter implements ProfileBadgeConverter, B
|
||||
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,
|
||||
|
||||
+4
-4
@@ -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);
|
||||
}
|
||||
}
|
||||
+9
@@ -64,6 +64,7 @@ public class DynamoDbTables {
|
||||
private final TableWithExpiration messages;
|
||||
private final TableWithExpiration onetimeDonations;
|
||||
private final Table phoneNumberIdentifiers;
|
||||
private final Table profileAvatars;
|
||||
private final Table profiles;
|
||||
private final Table profilesV2;
|
||||
private final Table pushChallenge;
|
||||
@@ -94,6 +95,7 @@ public class DynamoDbTables {
|
||||
@JsonProperty("messages") final TableWithExpiration messages,
|
||||
@JsonProperty("onetimeDonations") final TableWithExpiration onetimeDonations,
|
||||
@JsonProperty("phoneNumberIdentifiers") final Table phoneNumberIdentifiers,
|
||||
@JsonProperty("profileAvatars") final Table profileAvatars,
|
||||
@JsonProperty("profiles") final Table profiles,
|
||||
@JsonProperty("profilesV2") final Table profilesV2,
|
||||
@JsonProperty("pushChallenge") final Table pushChallenge,
|
||||
@@ -123,6 +125,7 @@ public class DynamoDbTables {
|
||||
this.messages = messages;
|
||||
this.onetimeDonations = onetimeDonations;
|
||||
this.phoneNumberIdentifiers = phoneNumberIdentifiers;
|
||||
this.profileAvatars = profileAvatars;
|
||||
this.profiles = profiles;
|
||||
this.profilesV2 = profilesV2;
|
||||
this.pushChallenge = pushChallenge;
|
||||
@@ -238,6 +241,12 @@ public class DynamoDbTables {
|
||||
return phoneNumberIdentifiers;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
public Table getProfileAvatars() {
|
||||
return profileAvatars;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
public Table getProfilesV1() {
|
||||
|
||||
-8
@@ -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;
|
||||
}
|
||||
|
||||
+96
-97
@@ -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();
|
||||
}
|
||||
}
|
||||
+15
-18
@@ -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);
|
||||
|
||||
+13
-3
@@ -8,7 +8,6 @@ package org.whispersystems.textsecuregcm.grpc;
|
||||
import com.google.protobuf.ByteString;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
@@ -44,6 +43,8 @@ import org.signal.chat.account.UsernameNotAvailable;
|
||||
import org.signal.chat.common.AccountIdentifiers;
|
||||
import org.signal.chat.errors.FailedPrecondition;
|
||||
import org.signal.libsignal.usernames.BaseUsernameException;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.ZkCredentialPublicKey;
|
||||
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
|
||||
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
|
||||
@@ -93,6 +94,10 @@ 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();
|
||||
@@ -271,9 +276,14 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
|
||||
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
|
||||
|
||||
final Account authenticatedAccount = getAuthenticatedAccount();
|
||||
final byte[] zkCredentialKey = request.getPublicKey().toByteArray();
|
||||
final ZkCredentialPublicKey zkCredentialKey;
|
||||
try {
|
||||
zkCredentialKey = new ZkCredentialPublicKey(request.getPublicKey().toByteArray());
|
||||
} catch (InvalidInputException _) {
|
||||
throw GrpcExceptions.invalidArguments("invalid public key bytes");
|
||||
}
|
||||
|
||||
if (Arrays.equals(authenticatedAccount.getZkCredentialKey(), zkCredentialKey)) {
|
||||
if (authenticatedAccount.getZkCredentialKey().map(zkCredentialKey::equals).orElse(false)) {
|
||||
return SetZkCredentialKeyResponse.newBuilder()
|
||||
.setRotationId(Objects.requireNonNull(authenticatedAccount.getZkCredentialKeyRotationId()))
|
||||
.build();
|
||||
|
||||
+45
-28
@@ -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");
|
||||
}
|
||||
|
||||
+179
@@ -0,0 +1,179 @@
|
||||
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.common.Badge;
|
||||
import org.signal.chat.common.BadgeSvg;
|
||||
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 org.whispersystems.textsecuregcm.entities.Badge badge = levelConfiguration.badge();
|
||||
final Badge commonBadge = 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 -> BadgeSvg.newBuilder().setLight(s.getLight()).setDark(s.getDark()).build())
|
||||
.toList())
|
||||
.build();
|
||||
final LevelConfiguration.Builder builder = LevelConfiguration.newBuilder().setBadge(commonBadge);
|
||||
if (badge instanceof final PurchasableBadge purchasableBadge) {
|
||||
builder.setBadgeDurationSeconds(purchasableBadge.getDuration().toSeconds());
|
||||
}
|
||||
return builder.build();
|
||||
}
|
||||
}
|
||||
+132
-4
@@ -5,12 +5,21 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.util.Optional;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.protobuf.Empty;
|
||||
import java.time.Clock;
|
||||
import java.util.Base64;
|
||||
import java.util.Optional;
|
||||
import org.signal.chat.errors.FailedUnidentifiedAuthorization;
|
||||
import org.signal.chat.errors.FailedZkAuthentication;
|
||||
import org.signal.chat.errors.NotFound;
|
||||
import org.signal.chat.profile.CredentialType;
|
||||
import org.signal.chat.profile.DeleteAvatarRequest;
|
||||
import org.signal.chat.profile.DeleteAvatarResponse;
|
||||
import org.signal.chat.profile.ExtendAvatarTTLRequest;
|
||||
import org.signal.chat.profile.ExtendAvatarTTLResponse;
|
||||
import org.signal.chat.profile.GetAvatarUploadFormRequest;
|
||||
import org.signal.chat.profile.GetAvatarUploadFormResponse;
|
||||
import org.signal.chat.profile.GetExpiringProfileKeyCredentialAnonymousRequest;
|
||||
import org.signal.chat.profile.GetExpiringProfileKeyCredentialAnonymousResponse;
|
||||
import org.signal.chat.profile.GetUnversionedProfileAnonymousRequest;
|
||||
@@ -18,44 +27,75 @@ import org.signal.chat.profile.GetUnversionedProfileAnonymousResponse;
|
||||
import org.signal.chat.profile.GetVersionedProfileAnonymousRequest;
|
||||
import org.signal.chat.profile.GetVersionedProfileAnonymousResponse;
|
||||
import org.signal.chat.profile.SimpleProfileAnonymousGrpc;
|
||||
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.ServerSecretParams;
|
||||
import org.signal.libsignal.zkgroup.VerificationFailedException;
|
||||
import org.signal.libsignal.zkgroup.avatars.AvatarUploadCredentialPresentation;
|
||||
import org.signal.libsignal.zkgroup.profiles.ServerZkProfileOperations;
|
||||
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
|
||||
import org.whispersystems.textsecuregcm.badges.ProfileBadgeConverter;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
|
||||
import org.whispersystems.textsecuregcm.util.ProfileHelper;
|
||||
|
||||
public class ProfileAnonymousGrpcService extends SimpleProfileAnonymousGrpc.ProfileAnonymousImplBase {
|
||||
private final AccountsManager accountsManager;
|
||||
private final ProfilesManager profilesManager;
|
||||
private final ProfileBadgeConverter profileBadgeConverter;
|
||||
private final ServerZkProfileOperations zkProfileOperations;
|
||||
private final GenericServerSecretParams genericServerSecretParams;
|
||||
private final GroupSendTokenUtil groupSendTokenUtil;
|
||||
|
||||
private final PostPolicyGenerator policyGenerator;
|
||||
|
||||
private final RateLimiters rateLimiters;
|
||||
|
||||
private final Clock clock;
|
||||
|
||||
public ProfileAnonymousGrpcService(
|
||||
final AccountsManager accountsManager,
|
||||
final ProfilesManager profilesManager,
|
||||
final ProfileBadgeConverter profileBadgeConverter,
|
||||
final ServerSecretParams serverSecretParams) {
|
||||
final PostPolicyGenerator policyGenerator,
|
||||
final GenericServerSecretParams genericServerSecretParams,
|
||||
final ServerSecretParams serverSecretParams,
|
||||
final RateLimiters rateLimiters,
|
||||
final Clock clock) {
|
||||
this(accountsManager,
|
||||
profilesManager,
|
||||
profileBadgeConverter,
|
||||
policyGenerator,
|
||||
genericServerSecretParams,
|
||||
rateLimiters,
|
||||
clock,
|
||||
new ServerZkProfileOperations(serverSecretParams),
|
||||
new GroupSendTokenUtil(serverSecretParams, Clock.systemUTC()));
|
||||
new GroupSendTokenUtil(serverSecretParams, clock));
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
ProfileAnonymousGrpcService(final AccountsManager accountsManager,
|
||||
final ProfilesManager profilesManager,
|
||||
final ProfileBadgeConverter profileBadgeConverter,
|
||||
final PostPolicyGenerator policyGenerator,
|
||||
final GenericServerSecretParams genericServerSecretParams,
|
||||
final RateLimiters rateLimiters,
|
||||
final Clock clock,
|
||||
final ServerZkProfileOperations zkProfileOperations,
|
||||
final GroupSendTokenUtil groupSendTokenUtil) {
|
||||
this.accountsManager = accountsManager;
|
||||
this.profilesManager = profilesManager;
|
||||
this.profileBadgeConverter = profileBadgeConverter;
|
||||
this.policyGenerator = policyGenerator;
|
||||
this.genericServerSecretParams = genericServerSecretParams;
|
||||
this.rateLimiters = rateLimiters;
|
||||
this.clock = clock;
|
||||
this.zkProfileOperations = zkProfileOperations;
|
||||
this.groupSendTokenUtil = groupSendTokenUtil;
|
||||
}
|
||||
@@ -152,4 +192,92 @@ public class ProfileAnonymousGrpcService extends SimpleProfileAnonymousGrpc.Prof
|
||||
return accountsManager.getByServiceIdentifier(targetIdentifier)
|
||||
.filter(targetAccount -> UnidentifiedAccessUtil.checkUnidentifiedAccess(targetAccount, unidentifiedAccessKey));
|
||||
}
|
||||
|
||||
@Override
|
||||
public GetAvatarUploadFormResponse getAvatarUploadForm(final GetAvatarUploadFormRequest request) throws RateLimitExceededException {
|
||||
final AvatarUploadCredentialPresentation presentation;
|
||||
|
||||
try {
|
||||
presentation = new AvatarUploadCredentialPresentation(
|
||||
request.getAvatarCredentialsPresentation().toByteArray());
|
||||
|
||||
presentation.verify(clock.instant(), this.genericServerSecretParams);
|
||||
|
||||
} catch (InvalidInputException _) {
|
||||
throw GrpcExceptions.invalidArguments("invalid credential presentation");
|
||||
|
||||
} catch (VerificationFailedException _) {
|
||||
return GetAvatarUploadFormResponse.newBuilder()
|
||||
.setInvalidCredentialsPresentation(FailedZkAuthentication.getDefaultInstance())
|
||||
.build();
|
||||
}
|
||||
|
||||
final byte[] identity = presentation.getCommitment();
|
||||
|
||||
rateLimiters.getProfileAvatarBytesLimiter().validate(Base64.getEncoder().encodeToString(identity), request.getUploadLength());
|
||||
|
||||
final String avatar = ProfileHelper.generateAvatarObjectName();
|
||||
|
||||
profilesManager.setAvatarForIdentity(identity, avatar);
|
||||
|
||||
return GetAvatarUploadFormResponse.newBuilder()
|
||||
.setAvatarUploadForm(ProfileGrpcHelper.generateAvatarUploadForm(avatar, request.getUploadLength(), policyGenerator, clock))
|
||||
.build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ExtendAvatarTTLResponse extendAvatarTTL(final ExtendAvatarTTLRequest request) {
|
||||
final AvatarUploadCredentialPresentation presentation;
|
||||
try {
|
||||
presentation = new AvatarUploadCredentialPresentation(
|
||||
request.getAvatarCredentialsPresentation().toByteArray());
|
||||
} catch (InvalidInputException _) {
|
||||
throw GrpcExceptions.invalidArguments("invalid credential presentation");
|
||||
}
|
||||
|
||||
try {
|
||||
presentation.verify(clock.instant(), this.genericServerSecretParams);
|
||||
|
||||
} catch (VerificationFailedException _) {
|
||||
return ExtendAvatarTTLResponse.newBuilder()
|
||||
.setInvalidCredentialsPresentation(FailedZkAuthentication.getDefaultInstance())
|
||||
.build();
|
||||
}
|
||||
|
||||
final byte[] identity = presentation.getCommitment();
|
||||
|
||||
return profilesManager.extendAvatarTtlForIdentity(identity)
|
||||
.map(extendedPath -> ExtendAvatarTTLResponse.newBuilder()
|
||||
.setPath(extendedPath)
|
||||
.build())
|
||||
.orElseGet(() -> ExtendAvatarTTLResponse.newBuilder()
|
||||
.setNotFound(NotFound.getDefaultInstance())
|
||||
.build());
|
||||
}
|
||||
|
||||
@Override
|
||||
public DeleteAvatarResponse deleteAvatar(final DeleteAvatarRequest request) {
|
||||
final AvatarUploadCredentialPresentation presentation;
|
||||
try {
|
||||
presentation = new AvatarUploadCredentialPresentation(
|
||||
request.getAvatarCredentialsPresentation().toByteArray());
|
||||
} catch (InvalidInputException _) {
|
||||
throw GrpcExceptions.invalidArguments("invalid credential presentation");
|
||||
}
|
||||
|
||||
try {
|
||||
presentation.verify(clock.instant(), this.genericServerSecretParams);
|
||||
|
||||
} catch (VerificationFailedException _) {
|
||||
return DeleteAvatarResponse.newBuilder()
|
||||
.setInvalidCredentialsPresentation(FailedZkAuthentication.getDefaultInstance())
|
||||
.build();
|
||||
}
|
||||
|
||||
final byte[] identity = presentation.getCommitment();
|
||||
|
||||
profilesManager.deleteAvatarForIdentity(identity);
|
||||
|
||||
return DeleteAvatarResponse.newBuilder().setSuccess(Empty.getDefaultInstance()).build();
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import com.google.common.annotations.VisibleForTesting;
|
||||
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;
|
||||
@@ -17,6 +18,7 @@ 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;
|
||||
import org.signal.chat.profile.GetUnversionedProfileResult;
|
||||
@@ -32,6 +34,7 @@ import org.signal.libsignal.zkgroup.profiles.ServerZkProfileOperations;
|
||||
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessChecksum;
|
||||
import org.whispersystems.textsecuregcm.badges.ProfileBadgeConverter;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
|
||||
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
|
||||
@@ -40,6 +43,12 @@ import org.whispersystems.textsecuregcm.storage.VersionedProfileV1;
|
||||
import org.whispersystems.textsecuregcm.util.ProfileHelper;
|
||||
|
||||
public class ProfileGrpcHelper {
|
||||
|
||||
private static final S3UploadForm PROTOTYPE_AVATAR_UPLOAD_FORM = S3UploadForm.newBuilder()
|
||||
.setAcl(PostPolicyGenerator.ACL)
|
||||
.setAlgorithm(PostPolicyGenerator.ALGORITHM)
|
||||
.build();
|
||||
|
||||
static Optional<GetVersionedProfileResult> getVersionedProfile(final Account account,
|
||||
final ProfilesManager profilesManager,
|
||||
final byte[] requestVersion,
|
||||
@@ -217,6 +226,20 @@ public class ProfileGrpcHelper {
|
||||
});
|
||||
}
|
||||
|
||||
public static S3UploadForm generateAvatarUploadForm(final String objectName, final int uploadLength,
|
||||
final PostPolicyGenerator policyGenerator, final Clock clock) {
|
||||
final PostPolicyGenerator.SignedPostPolicy policy =
|
||||
policyGenerator.createFor(objectName, uploadLength, clock.instant());
|
||||
|
||||
return PROTOTYPE_AVATAR_UPLOAD_FORM.toBuilder()
|
||||
.setKey(objectName)
|
||||
.setCredential(policy.credential())
|
||||
.setDate(policy.formattedTimestamp())
|
||||
.setPolicy(policy.encodedPolicy())
|
||||
.setSignature(policy.signature())
|
||||
.build();
|
||||
}
|
||||
|
||||
/**
|
||||
* Computes the SHA-256 hash of the given data.
|
||||
* <p>
|
||||
|
||||
+52
-19
@@ -5,11 +5,14 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import java.time.Clock;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.Arrays;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Function;
|
||||
@@ -17,6 +20,8 @@ import java.util.stream.Collectors;
|
||||
import org.signal.chat.common.S3UploadForm;
|
||||
import org.signal.chat.errors.FailedPrecondition;
|
||||
import org.signal.chat.errors.NotFound;
|
||||
import org.signal.chat.profile.GetAvatarCredentialsRequest;
|
||||
import org.signal.chat.profile.GetAvatarCredentialsResponse;
|
||||
import org.signal.chat.profile.GetUnversionedProfileRequest;
|
||||
import org.signal.chat.profile.GetUnversionedProfileResponse;
|
||||
import org.signal.chat.profile.GetVersionedProfileRequest;
|
||||
@@ -28,6 +33,14 @@ import org.signal.chat.profile.SetProfileResponse;
|
||||
import org.signal.chat.profile.SetProfileResult;
|
||||
import org.signal.chat.profile.SetProfileV1Request.AvatarChange;
|
||||
import org.signal.chat.profile.SimpleProfileGrpc;
|
||||
import org.signal.libsignal.protocol.ServiceId;
|
||||
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.VerificationFailedException;
|
||||
import org.signal.libsignal.zkgroup.avatars.AvatarUploadCredentialRequest;
|
||||
import org.signal.libsignal.zkgroup.avatars.AvatarUploadCredentialResponse;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
|
||||
import org.whispersystems.textsecuregcm.badges.ProfileBadgeConverter;
|
||||
@@ -52,20 +65,18 @@ import org.whispersystems.textsecuregcm.util.ProfileHelper;
|
||||
|
||||
public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(ProfileGrpcService.class);
|
||||
|
||||
private final Clock clock;
|
||||
private final AccountsManager accountsManager;
|
||||
private final ProfilesManager profilesManager;
|
||||
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
|
||||
private final Map<String, BadgeConfiguration> badgeConfigurationMap;
|
||||
private final PostPolicyGenerator policyGenerator;
|
||||
private final GenericServerSecretParams genericServerSecretParams;
|
||||
private final ProfileBadgeConverter profileBadgeConverter;
|
||||
private final RateLimiters rateLimiters;
|
||||
|
||||
private static final S3UploadForm PROTOTYPE_AVATAR_UPLOAD_FORM = S3UploadForm.newBuilder()
|
||||
.setAcl(PostPolicyGenerator.ACL)
|
||||
.setAlgorithm(PostPolicyGenerator.ALGORITHM)
|
||||
.build();
|
||||
|
||||
private record AvatarData(Optional<String> currentAvatar,
|
||||
Optional<String> finalAvatar,
|
||||
Optional<S3UploadForm> uploadAttributes) {}
|
||||
@@ -77,6 +88,7 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
|
||||
final BadgesConfiguration badgesConfiguration,
|
||||
final PostPolicyGenerator policyGenerator,
|
||||
final GenericServerSecretParams genericServerSecretParams,
|
||||
final ProfileBadgeConverter profileBadgeConverter,
|
||||
final RateLimiters rateLimiters) {
|
||||
this.clock = clock;
|
||||
@@ -86,6 +98,7 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
|
||||
this.badgeConfigurationMap = badgesConfiguration.getBadges().stream().collect(Collectors.toMap(
|
||||
BadgeConfiguration::getId, Function.identity()));
|
||||
this.policyGenerator = policyGenerator;
|
||||
this.genericServerSecretParams = genericServerSecretParams;
|
||||
this.profileBadgeConverter = profileBadgeConverter;
|
||||
this.rateLimiters = rateLimiters;
|
||||
}
|
||||
@@ -136,7 +149,7 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
|
||||
case AVATAR_CHANGE_UPDATE -> {
|
||||
final String updateAvatarObjectName = ProfileHelper.generateAvatarObjectName();
|
||||
yield new AvatarData(currentAvatar, Optional.of(updateAvatarObjectName),
|
||||
Optional.of(generateAvatarUploadForm(updateAvatarObjectName)));
|
||||
Optional.of(ProfileGrpcHelper.generateAvatarUploadForm(updateAvatarObjectName, ProfileHelper.MAX_PROFILE_AVATAR_SIZE_BYTES, policyGenerator, clock)));
|
||||
}
|
||||
};
|
||||
|
||||
@@ -205,6 +218,39 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
|
||||
.build());
|
||||
}
|
||||
|
||||
@Override
|
||||
public GetAvatarCredentialsResponse getAvatarCredentials(final GetAvatarCredentialsRequest request) {
|
||||
|
||||
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
|
||||
|
||||
final Account account = accountsManager.getByAccountIdentifier(authenticatedDevice.accountIdentifier())
|
||||
.orElseThrow(() -> GrpcExceptions.invalidCredentials("account not found"));
|
||||
|
||||
if (account.getZkCredentialKey().isEmpty()) {
|
||||
return GetAvatarCredentialsResponse.newBuilder()
|
||||
.setMissingZkCredentialKey(FailedPrecondition.newBuilder().setDescription("account requires ZK credential key"))
|
||||
.build();
|
||||
}
|
||||
|
||||
try {
|
||||
final AvatarUploadCredentialRequest credentialRequest = new AvatarUploadCredentialRequest(
|
||||
request.getAvatarCredentialsRequest().toByteArray());
|
||||
|
||||
final AvatarUploadCredentialResponse credentialResponse = credentialRequest.issueCredential(
|
||||
new ServiceId.Aci(account.getIdentifier(IdentityType.ACI)),
|
||||
account.getZkCredentialKey().get(),
|
||||
Objects.requireNonNull(account.getZkCredentialKeyRotationId()),
|
||||
clock.instant().truncatedTo(ChronoUnit.DAYS),
|
||||
this.genericServerSecretParams);
|
||||
|
||||
return GetAvatarCredentialsResponse.newBuilder()
|
||||
.setAvatarCredentials(ByteString.copyFrom(credentialResponse.serialize()))
|
||||
.build();
|
||||
} catch (InvalidInputException | VerificationFailedException _) {
|
||||
throw GrpcExceptions.invalidArguments("invalid credential request");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public GetUnversionedProfileResponse getUnversionedProfile(final GetUnversionedProfileRequest request) throws RateLimitExceededException {
|
||||
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
|
||||
@@ -263,17 +309,4 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
|
||||
throw GrpcExceptions.invalidArguments("Request must include commitment during migration");
|
||||
}
|
||||
}
|
||||
|
||||
private S3UploadForm generateAvatarUploadForm(final String objectName) {
|
||||
final PostPolicyGenerator.SignedPostPolicy policy =
|
||||
policyGenerator.createFor(objectName, ProfileHelper.MAX_PROFILE_AVATAR_SIZE_BYTES, clock.instant());
|
||||
|
||||
return PROTOTYPE_AVATAR_UPLOAD_FORM.toBuilder()
|
||||
.setKey(objectName)
|
||||
.setCredential(policy.credential())
|
||||
.setDate(policy.formattedTimestamp())
|
||||
.setPolicy(policy.encodedPolicy())
|
||||
.setSignature(policy.signature())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
+71
-160
@@ -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());
|
||||
|
||||
@@ -28,6 +28,7 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
|
||||
ALLOCATE_DEVICE("allocateDevice", new RateLimiterConfig(6, Duration.ofMinutes(2), false)),
|
||||
VERIFY_DEVICE("verifyDevice", new RateLimiterConfig(6, Duration.ofMinutes(2), false)),
|
||||
PROFILE("profile", new RateLimiterConfig(4320, Duration.ofSeconds(20), true)),
|
||||
PROFILE_AVATAR_BYTES("profileAvatarBytes", new RateLimiterConfig(DataSize.mebibytes(100).toBytes(), Duration.ofNanos(10000), true)),
|
||||
STICKER_PACK("stickerPack", new RateLimiterConfig(50, Duration.ofMinutes(72), false)),
|
||||
USERNAME_LOOKUP("usernameLookup", new RateLimiterConfig(100, Duration.ofMinutes(15), true)),
|
||||
USERNAME_SET("usernameSet", new RateLimiterConfig(100, Duration.ofMinutes(15), false)),
|
||||
@@ -134,6 +135,10 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
|
||||
return forDescriptor(For.PROFILE);
|
||||
}
|
||||
|
||||
public RateLimiter getProfileAvatarBytesLimiter() {
|
||||
return forDescriptor(For.PROFILE_AVATAR_BYTES);
|
||||
}
|
||||
|
||||
public RateLimiter getStickerPackLimiter() {
|
||||
return forDescriptor(For.STICKER_PACK);
|
||||
}
|
||||
|
||||
@@ -9,12 +9,9 @@ import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
import com.fasterxml.jackson.annotation.JsonFilter;
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.core.JsonGenerator;
|
||||
import com.fasterxml.jackson.core.JsonParser;
|
||||
import com.fasterxml.jackson.databind.DeserializationContext;
|
||||
import com.fasterxml.jackson.databind.JsonDeserializer;
|
||||
import com.fasterxml.jackson.databind.JsonSerializer;
|
||||
import com.fasterxml.jackson.databind.SerializerProvider;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
@@ -33,6 +30,7 @@ import java.util.UUID;
|
||||
import javax.annotation.Nullable;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.signal.libsignal.zkgroup.ZkCredentialPublicKey;
|
||||
import org.signal.libsignal.zkgroup.backups.BackupCredentialType;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
@@ -43,6 +41,7 @@ import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.util.ByteArrayBase64UrlAdapter;
|
||||
import org.whispersystems.textsecuregcm.util.IdentityKeyAdapter;
|
||||
import org.whispersystems.textsecuregcm.util.ZkCredentialPublicKeyAdapter;
|
||||
|
||||
@JsonFilter("Account")
|
||||
public class Account {
|
||||
@@ -128,7 +127,9 @@ public class Account {
|
||||
|
||||
@JsonProperty("zck")
|
||||
@Nullable
|
||||
private byte[] zkCredentialKey;
|
||||
@JsonSerialize(using = ZkCredentialPublicKeyAdapter.Serializer.class)
|
||||
@JsonDeserialize(using = ZkCredentialPublicKeyAdapter.Deserializer.class)
|
||||
private ZkCredentialPublicKey zkCredentialKey;
|
||||
|
||||
@JsonProperty("zckr")
|
||||
@Nullable
|
||||
@@ -560,12 +561,11 @@ public class Account {
|
||||
this.usernameHolds = usernameHolds;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public byte[] getZkCredentialKey() {
|
||||
return zkCredentialKey;
|
||||
public Optional<ZkCredentialPublicKey> getZkCredentialKey() {
|
||||
return Optional.ofNullable(zkCredentialKey);
|
||||
}
|
||||
|
||||
public void setZkCredentialKey(@Nullable final byte[] zkCredentialKey) {
|
||||
public void setZkCredentialKey(@Nullable final ZkCredentialPublicKey zkCredentialKey) {
|
||||
this.zkCredentialKey = zkCredentialKey;
|
||||
}
|
||||
|
||||
|
||||
@@ -327,7 +327,8 @@ public class Accounts {
|
||||
accountToCreate.setBackupVoucher(existingAccount.getBackupVoucher());
|
||||
|
||||
// Carry over the existing ZK credential key to the new account
|
||||
accountToCreate.setZkCredentialKey(existingAccount.getZkCredentialKey());
|
||||
accountToCreate.setZkCredentialKey(existingAccount.getZkCredentialKey().orElse(null));
|
||||
accountToCreate.setZkCredentialKeyRotationId(existingAccount.getZkCredentialKeyRotationId());
|
||||
|
||||
final List<TransactWriteItem> writeItems = new ArrayList<>();
|
||||
|
||||
|
||||
+142
@@ -0,0 +1,142 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Flow;
|
||||
import java.util.function.BiConsumer;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import org.reactivestreams.Subscription;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStream;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import reactor.adapter.JdkFlowAdapter;
|
||||
import reactor.core.publisher.BaseSubscriber;
|
||||
|
||||
/// A temporary message stream that can mirror message acknowledgements (deletion requests) to FoundationDB
|
||||
public class AcknowledgementMirroringMessageStream implements MessageStream {
|
||||
|
||||
private final RedisDynamoDbMessageStream redisDynamoDbMessageStream;
|
||||
private final FoundationDbMessageStream foundationDbMessageStream;
|
||||
|
||||
private final Set<UUID> messagesPendingAcknowledgement = new HashSet<>();
|
||||
|
||||
private static final int HIGH_PENDING_ACKNOWLEDGEMENT_COUNT_WARNING_THRESHOLD = 1024;
|
||||
|
||||
@VisibleForTesting
|
||||
static final int MAX_PENDING_ACKNOWLEDGEMENTS = 8192;
|
||||
|
||||
private static final Counter HIGH_PENDING_ACKNOWLEDGEMENT_COUNT_WARNING_COUNTER =
|
||||
Metrics.counter(MetricsUtil.name(AcknowledgementMirroringMessageStream.class, "highPendingAcknowledgementCount"));
|
||||
|
||||
private static final Counter MAX_PENDING_ACKNOWLEDGEMENT_LIMIT_BREACHED_COUNTER =
|
||||
Metrics.counter(MetricsUtil.name(AcknowledgementMirroringMessageStream.class, "maxPendingAcknowledgementLimitBreached"));
|
||||
|
||||
private static class FoundationDbSubscriber extends BaseSubscriber<MessageStreamEntry.Envelope> {
|
||||
|
||||
private final BiConsumer<UUID, Long> mirroredMessageHandler;
|
||||
|
||||
private FoundationDbSubscriber(final BiConsumer<UUID, Long> mirroredMessageHandler) {
|
||||
this.mirroredMessageHandler = mirroredMessageHandler;
|
||||
}
|
||||
|
||||
public void handleRedisDynamoDbMessageStreamEntry(final MessageStreamEntry messageStreamEntry) {
|
||||
final boolean isMirroredMessage = switch (messageStreamEntry) {
|
||||
case MessageStreamEntry.Envelope envelopeEntry ->
|
||||
UUIDUtil.fromByteString(envelopeEntry.message().getServerGuid()).version() == 8;
|
||||
|
||||
case MessageStreamEntry.QueueEmpty _ -> false;
|
||||
};
|
||||
|
||||
if (isMirroredMessage) {
|
||||
request(1);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void hookOnSubscribe(final Subscription subscription) {
|
||||
// The base `hookOnSubscribe` requests `Long.MAX_VALUE` elements, and that is something we're explicitly trying
|
||||
// to avoid with this subscriber
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void hookOnNext(final MessageStreamEntry.Envelope envelope) {
|
||||
mirroredMessageHandler.accept(
|
||||
UUIDUtil.fromByteString(envelope.message().getServerGuid()), envelope.message().getServerTimestamp());
|
||||
}
|
||||
}
|
||||
|
||||
public AcknowledgementMirroringMessageStream(final RedisDynamoDbMessageStream redisDynamoDbMessageStream,
|
||||
final FoundationDbMessageStream foundationDbMessageStream) {
|
||||
|
||||
this.redisDynamoDbMessageStream = redisDynamoDbMessageStream;
|
||||
this.foundationDbMessageStream = foundationDbMessageStream;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Flow.Publisher<MessageStreamEntry> getMessages() {
|
||||
final FoundationDbSubscriber subscriber = new FoundationDbSubscriber(this::handleMirroredMessageAcknowledged);
|
||||
|
||||
JdkFlowAdapter.flowPublisherToFlux(foundationDbMessageStream.getMessages())
|
||||
.filter(messageStreamEntry -> messageStreamEntry instanceof MessageStreamEntry.Envelope)
|
||||
.cast(MessageStreamEntry.Envelope.class)
|
||||
.subscribe(subscriber);
|
||||
|
||||
return JdkFlowAdapter.publisherToFlowPublisher(
|
||||
JdkFlowAdapter.flowPublisherToFlux(redisDynamoDbMessageStream.getMessages())
|
||||
// Mirror demand and termination signals to the FoundationDB message stream
|
||||
.doOnNext(subscriber::handleRedisDynamoDbMessageStreamEntry)
|
||||
.doFinally(_ -> subscriber.dispose()));
|
||||
}
|
||||
|
||||
@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) {
|
||||
handleMirroredMessageAcknowledged(messageGuid, serverTimestamp);
|
||||
}
|
||||
|
||||
return redisDynamoDbMessageStream.acknowledgeMessage(messageGuid, serverTimestamp);
|
||||
}
|
||||
|
||||
private void handleMirroredMessageAcknowledged(final UUID messageGuid, final long serverTimestamp) {
|
||||
// Before we can acknowledge and delete the message in FoundationDB, two things need to happen:
|
||||
//
|
||||
// 1. The client needs to acknowledge the message on the Redis/DDB stream.
|
||||
// 2. The message needs to pass through the FoundationDB message stream pipeline because it needs to be registered
|
||||
// in the acknowledged message buffer machinery before it can be deleted.
|
||||
//
|
||||
// We can't guarantee the order in which these two things happen, so we use a synchronized set to coordinate and
|
||||
// determine when both have happened.
|
||||
synchronized (messagesPendingAcknowledgement) {
|
||||
if (messagesPendingAcknowledgement.remove(messageGuid)) {
|
||||
// One of the two streams had already acknowledged this message, and this is the second acknowledgement. Now we
|
||||
// can pass the acknowledgement along to FoundationDB.
|
||||
foundationDbMessageStream.acknowledgeMessage(messageGuid, serverTimestamp);
|
||||
} else {
|
||||
// Either this message came from FoundationDB and got auto-acknowledged before getting explicitly acknowledged
|
||||
// on the Redis/DynamoDB stream or the message got explicitly acknowledged on the Redis/DynamoDB stream before
|
||||
// passing through the FoundationDB stream. Either way, wait for both streams to have done their part.
|
||||
if (messagesPendingAcknowledgement.add(messageGuid)) {
|
||||
if (messagesPendingAcknowledgement.size() == HIGH_PENDING_ACKNOWLEDGEMENT_COUNT_WARNING_THRESHOLD) {
|
||||
HIGH_PENDING_ACKNOWLEDGEMENT_COUNT_WARNING_COUNTER.increment();
|
||||
}
|
||||
|
||||
if (messagesPendingAcknowledgement.size() > MAX_PENDING_ACKNOWLEDGEMENTS) {
|
||||
MAX_PENDING_ACKNOWLEDGEMENT_LIMIT_BREACHED_COUNTER.increment();
|
||||
throw new IllegalStateException("Too many pending acknowledgements");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
-66
@@ -1,66 +0,0 @@
|
||||
/*
|
||||
* 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.FoundationDbMessageStore;
|
||||
|
||||
/// A temporary message stream that can mirror message acknowledgements (deletion requests) to FoundationDB
|
||||
public class DeletionMirroringRedisDynamoDbMessageStream implements MessageStream {
|
||||
|
||||
private final RedisDynamoDbMessageStream redisDynamoDbMessageStream;
|
||||
private final FoundationDbMessageStore foundationDbMessageStore;
|
||||
private final ExperimentEnrollmentManager experimentEnrollmentManager;
|
||||
|
||||
private final AciServiceIdentifier accountIdentifier;
|
||||
private final byte deviceId;
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(DeletionMirroringRedisDynamoDbMessageStream.class);
|
||||
|
||||
public DeletionMirroringRedisDynamoDbMessageStream(final RedisDynamoDbMessageStream redisDynamoDbMessageStream,
|
||||
final FoundationDbMessageStore foundationDbMessageStore,
|
||||
final ExperimentEnrollmentManager experimentEnrollmentManager,
|
||||
final UUID accountIdentifier,
|
||||
final byte deviceId) {
|
||||
|
||||
this.redisDynamoDbMessageStream = redisDynamoDbMessageStream;
|
||||
this.foundationDbMessageStore = foundationDbMessageStore;
|
||||
this.experimentEnrollmentManager = experimentEnrollmentManager;
|
||||
|
||||
this.accountIdentifier = new AciServiceIdentifier(accountIdentifier);
|
||||
this.deviceId = deviceId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Flow.Publisher<MessageStreamEntry> getMessages() {
|
||||
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)) {
|
||||
|
||||
foundationDbMessageStore.delete(accountIdentifier, deviceId, messageGuid)
|
||||
.whenComplete((_, throwable) -> {
|
||||
if (throwable != null) {
|
||||
logger.warn("Failed to delete message {}/{}/{} from FoundationDb", accountIdentifier.uuid(), deviceId,
|
||||
messageGuid, throwable);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return redisDynamoDbMessageStream.acknowledgeMessage(messageGuid, serverTimestamp);
|
||||
}
|
||||
}
|
||||
@@ -279,12 +279,15 @@ public class MessagesManager {
|
||||
}
|
||||
|
||||
public MessageStream getMessages(final UUID destinationUuid, final Device destinationDevice) {
|
||||
return new DeletionMirroringRedisDynamoDbMessageStream(
|
||||
new RedisDynamoDbMessageStream(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, destinationUuid, destinationDevice),
|
||||
foundationDbMessageStore,
|
||||
experimentEnrollmentManager,
|
||||
destinationUuid,
|
||||
destinationDevice.getId());
|
||||
final RedisDynamoDbMessageStream redisDynamoDbMessageStream =
|
||||
new RedisDynamoDbMessageStream(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager,
|
||||
destinationUuid, destinationDevice);
|
||||
|
||||
return experimentEnrollmentManager.isEnrolled(destinationUuid, MIRROR_DELETIONS_EXPERIMENT_NAME)
|
||||
? new AcknowledgementMirroringMessageStream(
|
||||
redisDynamoDbMessageStream,
|
||||
foundationDbMessageStore.getMessages(new AciServiceIdentifier(destinationUuid), destinationDevice.getId()))
|
||||
: redisDynamoDbMessageStream;
|
||||
}
|
||||
|
||||
Publisher<Envelope> getMessagesForDevice(final UUID destinationUuid, final Device destinationDevice) {
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import org.whispersystems.textsecuregcm.util.AttributeValues;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
|
||||
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ConditionalCheckFailedException;
|
||||
import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.DeleteItemResponse;
|
||||
import software.amazon.awssdk.services.dynamodb.model.PutItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.PutItemResponse;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ReturnValue;
|
||||
import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.UpdateItemResponse;
|
||||
|
||||
public class ProfileAvatars {
|
||||
|
||||
private final DynamoDbClient dynamoDbClient;
|
||||
private final String tableName;
|
||||
private final Duration expiration;
|
||||
private final Clock clock;
|
||||
|
||||
// Identity that owns this profile; hash key; byte array
|
||||
@VisibleForTesting
|
||||
static final String KEY_IDENTITY = "I";
|
||||
|
||||
// URL of the avatar; string
|
||||
@VisibleForTesting
|
||||
static final String ATTR_URL = "U";
|
||||
|
||||
// Expiration timestamp, in seconds since the epoch, of the avatar; number
|
||||
@VisibleForTesting
|
||||
static final String ATTR_TTL = "E";
|
||||
|
||||
public ProfileAvatars(final DynamoDbClient dynamoDbClient, final String tableName, final Duration expiration, final
|
||||
Clock clock) {
|
||||
this.dynamoDbClient = dynamoDbClient;
|
||||
this.tableName = tableName;
|
||||
this.expiration = expiration;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
/// Sets the avatar URL for an identity
|
||||
///
|
||||
/// @return the previous URL, if any
|
||||
public Optional<String> setAvatarUrl(final byte[] identity, final String url) {
|
||||
final PutItemResponse response = dynamoDbClient.putItem(PutItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.item(Map.of(KEY_IDENTITY, AttributeValues.fromByteArray(identity),
|
||||
ATTR_URL, AttributeValues.fromString(url),
|
||||
ATTR_TTL, AttributeValues.fromLong(clock.instant().plus(expiration).getEpochSecond())))
|
||||
.returnValues(ReturnValue.ALL_OLD)
|
||||
.build());
|
||||
|
||||
return Optional.ofNullable(AttributeValues.getString(response.attributes(), ATTR_URL, null));
|
||||
}
|
||||
|
||||
/// @return the avatar URL, if present
|
||||
public Optional<String> updateAvatarTtl(final byte[] identity) {
|
||||
|
||||
final UpdateItemResponse response;
|
||||
try {
|
||||
response = dynamoDbClient.updateItem(UpdateItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.key(Map.of(KEY_IDENTITY, AttributeValues.fromByteArray(identity)))
|
||||
.conditionExpression("attribute_exists(#url)")
|
||||
.updateExpression("SET #ttl = :ttl")
|
||||
.expressionAttributeNames(Map.of(
|
||||
"#ttl", ATTR_TTL,
|
||||
"#url", ATTR_URL))
|
||||
.expressionAttributeValues(
|
||||
Map.of(":ttl", AttributeValues.fromLong(clock.instant().plus(expiration).getEpochSecond())))
|
||||
.returnValues(ReturnValue.ALL_OLD)
|
||||
.build());
|
||||
} catch (ConditionalCheckFailedException _) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
return Optional.ofNullable(AttributeValues.getString(response.attributes(), ATTR_URL, null));
|
||||
}
|
||||
|
||||
/// @return the deleted avatar URL, if present
|
||||
public Optional<String> deleteAvatarUrl(final byte[] identity) {
|
||||
final DeleteItemResponse response = dynamoDbClient.deleteItem(DeleteItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.key(Map.of(KEY_IDENTITY, AttributeValues.fromByteArray(identity)))
|
||||
.returnValues(ReturnValue.ALL_OLD)
|
||||
.build());
|
||||
|
||||
if (!response.hasAttributes()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
return Optional.ofNullable(response.attributes().get(ATTR_URL))
|
||||
.map(AttributeValue::s);
|
||||
}
|
||||
}
|
||||
+63
-9
@@ -14,7 +14,9 @@ import io.lettuce.core.RedisException;
|
||||
import io.lettuce.core.ScriptOutputType;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.io.IOException;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
@@ -29,9 +31,13 @@ import org.whispersystems.textsecuregcm.util.ResilienceUtil;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.util.retry.Retry;
|
||||
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem;
|
||||
import software.amazon.awssdk.services.s3.S3AsyncClient;
|
||||
import software.amazon.awssdk.services.s3.model.CopyObjectRequest;
|
||||
import software.amazon.awssdk.services.s3.model.DeleteObjectRequest;
|
||||
import software.amazon.awssdk.services.s3.model.MetadataDirective;
|
||||
import software.amazon.awssdk.services.s3.model.NoSuchKeyException;
|
||||
|
||||
public class ProfilesManager {
|
||||
|
||||
@@ -44,6 +50,7 @@ public class ProfilesManager {
|
||||
|
||||
private final Profiles profilesV1;
|
||||
private final ProfilesV2 profilesV2;
|
||||
private final ProfileAvatars profileAvatars;
|
||||
private final FaultTolerantRedisClusterClient cacheCluster;
|
||||
private final ScheduledExecutorService retryExecutor;
|
||||
private final S3AsyncClient s3Client;
|
||||
@@ -57,17 +64,19 @@ public class ProfilesManager {
|
||||
|
||||
public ProfilesManager(final Profiles profilesV1,
|
||||
final ProfilesV2 profilesV2,
|
||||
final ProfileAvatars profileAvatars,
|
||||
final FaultTolerantRedisClusterClient cacheCluster,
|
||||
final ScheduledExecutorService retryExecutor,
|
||||
final S3AsyncClient s3Client,
|
||||
final String bucket) throws IOException {
|
||||
this(profilesV1, profilesV2, cacheCluster, retryExecutor, s3Client, bucket,
|
||||
this(profilesV1, profilesV2, profileAvatars, cacheCluster, retryExecutor, s3Client, bucket,
|
||||
ClusterLuaScript.fromResource(cacheCluster, "lua/profile_set.lua", ScriptOutputType.STATUS));
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
ProfilesManager(final Profiles profilesV1,
|
||||
final ProfilesV2 profilesV2,
|
||||
final ProfileAvatars profileAvatars,
|
||||
final FaultTolerantRedisClusterClient cacheCluster,
|
||||
final ScheduledExecutorService retryExecutor,
|
||||
final S3AsyncClient s3Client,
|
||||
@@ -75,6 +84,7 @@ public class ProfilesManager {
|
||||
final ClusterLuaScript setLuaScript) {
|
||||
this.profilesV1 = profilesV1;
|
||||
this.profilesV2 = profilesV2;
|
||||
this.profileAvatars = profileAvatars;
|
||||
this.cacheCluster = cacheCluster;
|
||||
this.retryExecutor = retryExecutor;
|
||||
this.s3Client = s3Client;
|
||||
@@ -124,12 +134,10 @@ public class ProfilesManager {
|
||||
redisSet(uuid, versionedProfile, versionedProfileV1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete all profiles for the given uuid.
|
||||
* <p>
|
||||
* Avatars should be included for explicit delete actions, such as API calls and expired accounts. Implicit
|
||||
* deletions, such as registration, should preserve them, so that PIN recovery includes the avatar.
|
||||
*/
|
||||
/// Delete all profiles for the given uuid.
|
||||
///
|
||||
/// Avatars should be included for explicit delete actions, such as API calls and expired accounts. Implicit
|
||||
/// deletions, such as registration, should preserve them, so that PIN recovery includes the avatar.
|
||||
public CompletableFuture<Void> deleteAll(UUID uuid, final boolean includeAvatar) {
|
||||
|
||||
final CompletableFuture<Void> profilesV1AndAvatars = Mono.fromFuture(profilesV1.deleteAll(uuid))
|
||||
@@ -149,7 +157,7 @@ public class ProfilesManager {
|
||||
.bucket(bucket)
|
||||
.key(avatar)
|
||||
.build())
|
||||
.handle((ignored, throwable) -> {
|
||||
.whenComplete((_, throwable) -> {
|
||||
final String outcome;
|
||||
if (throwable != null) {
|
||||
logger.warn("Error deleting avatar", throwable);
|
||||
@@ -159,7 +167,6 @@ public class ProfilesManager {
|
||||
}
|
||||
|
||||
Metrics.counter(DELETE_AVATAR_COUNTER_NAME, "outcome", outcome).increment();
|
||||
return null;
|
||||
})
|
||||
.thenRun(Util.NOOP);
|
||||
}
|
||||
@@ -284,4 +291,51 @@ public class ProfilesManager {
|
||||
static byte[] getCacheKeyV1(UUID uuid) {
|
||||
return (CACHE_PREFIX_V1 + '{' + uuid.toString() + '}').getBytes();
|
||||
}
|
||||
|
||||
public void deleteAvatarForIdentity(final byte[] identity) {
|
||||
profileAvatars.deleteAvatarUrl(identity).ifPresent(avatar -> Mono.fromFuture(() ->
|
||||
deleteAvatar(avatar))
|
||||
.retry(3)
|
||||
.onErrorComplete()
|
||||
.block());
|
||||
}
|
||||
|
||||
/// Sets an avatar for the identity. If there was already an avatar, it will be deleted from storage.
|
||||
public void setAvatarForIdentity(byte[] identity, String avatar) {
|
||||
profileAvatars.setAvatarUrl(identity, avatar).map(previousAvatar -> Mono.fromFuture(() ->
|
||||
deleteAvatar(previousAvatar))
|
||||
.retry(3)
|
||||
.onErrorComplete()
|
||||
.block());
|
||||
}
|
||||
|
||||
public Optional<String> extendAvatarTtlForIdentity(final byte[] identity) {
|
||||
|
||||
final Optional<String> maybePath = profileAvatars.updateAvatarTtl(identity);
|
||||
|
||||
return maybePath.map(key -> {
|
||||
try {
|
||||
// copying the object to itself extends the expiration...
|
||||
Mono.fromFuture(() -> s3Client.copyObject(CopyObjectRequest.builder()
|
||||
.sourceBucket(bucket)
|
||||
.sourceKey(key)
|
||||
.destinationBucket(bucket)
|
||||
.destinationKey(key)
|
||||
.metadataDirective(MetadataDirective.REPLACE)
|
||||
// ...but there needs to be a trivial change, otherwise it is rejected
|
||||
.metadata(Map.of("t", String.valueOf(Instant.now().getEpochSecond())))
|
||||
.build()))
|
||||
.retryWhen(Retry.max(3).filter(e -> !(e instanceof NoSuchKeyException)))
|
||||
.block();
|
||||
|
||||
return key;
|
||||
} catch (NoSuchKeyException _) {
|
||||
logger.warn("avatar expected to be present is gone");
|
||||
|
||||
profileAvatars.deleteAvatarUrl(identity);
|
||||
|
||||
return null;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
+5
-3
@@ -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()) {
|
||||
|
||||
+192
-54
@@ -5,7 +5,24 @@ import com.apple.foundationdb.KeySelector;
|
||||
import com.apple.foundationdb.StreamingMode;
|
||||
import com.apple.foundationdb.Transaction;
|
||||
import com.apple.foundationdb.tuple.Versionstamp;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.protobuf.InvalidProtocolBufferException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.time.Clock;
|
||||
import java.util.Arrays;
|
||||
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;
|
||||
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;
|
||||
@@ -13,28 +30,63 @@ import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.FluxSink;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/// 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.
|
||||
class FoundationDbMessagePublisher {
|
||||
|
||||
private final Database database;
|
||||
/// The maximum number of messages we will fetch per range query operation to avoid excessive memory consumption
|
||||
private final int maxMessagesPerScan;
|
||||
private final Clock clock;
|
||||
/// Keeps track of the key from which to start reading on the next iteration
|
||||
private volatile KeySelector beginKeyCursor;
|
||||
/// The end key at which we stop reading messages. For finite publisher, this is just past the end-of-queue key at the
|
||||
/// time the publisher was created. For an infinite publisher, this is the end of subspace range.
|
||||
private final KeySelector endKeyExclusive;
|
||||
|
||||
/// Keeps track of the key from which to start reading on the next iteration
|
||||
private volatile KeySelector beginKeyCursor;
|
||||
/// The maximum number of messages we will fetch per range query operation to avoid excessive memory consumption
|
||||
private final int maxMessagesPerScan;
|
||||
|
||||
/// The key that stores the server ID/timestamp indicating when/where the connected client was last known to be
|
||||
/// present. Active publishers refresh this key at regular intervals (see [#renewPresenceFuture]).
|
||||
@Nullable private final byte[] presenceKey;
|
||||
|
||||
// An ID for this specific stream for use when checking "ownership" of a presence value.
|
||||
private final int streamId = NEXT_STREAM_ID.getAndIncrement();
|
||||
|
||||
/// The key that is updated whenever new messages are available in the queue. If null, it is inferred that the publisher
|
||||
/// is finite and will terminate when the end-of-queue at time of publisher creation is reached. Otherwise, the publisher
|
||||
/// is "infinite" and will continue to wait for new messages and publish them in a loop.
|
||||
@Nullable private final byte[] messagesAvailableWatchKey;
|
||||
|
||||
/// 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;
|
||||
|
||||
/// Tracks the current state of the publisher state machine. Initial state presumes that messages are available in the queue.
|
||||
private State state = State.MESSAGES_AVAILABLE;
|
||||
|
||||
private final Flux<FoundationDbMessageStreamEntry.Message> messagePublisher;
|
||||
|
||||
/// Reference to the sink we publish messages to.
|
||||
private volatile FluxSink<FoundationDbMessageStreamEntry.Message> emitter;
|
||||
|
||||
/// Future that completes when the watch for {@link #messagesAvailableWatchKey} triggers.
|
||||
private CompletableFuture<Void> watchFuture;
|
||||
|
||||
/// A future for refreshing the connected client's presence value at regular intervals.
|
||||
@Nullable private ScheduledFuture<?> renewPresenceFuture;
|
||||
|
||||
private final AtomicLong totalRequested = new AtomicLong(0);
|
||||
private final AtomicLong totalEmitted = new AtomicLong(0);
|
||||
|
||||
private static final AtomicInteger NEXT_STREAM_ID = new AtomicInteger();
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(FoundationDbMessagePublisher.class);
|
||||
|
||||
enum State {
|
||||
/// Messages are likely available in the queue. Initial state.
|
||||
@@ -70,49 +122,57 @@ class FoundationDbMessagePublisher {
|
||||
FETCH_OR_PUBLISH_ERROR_OCCURRED
|
||||
}
|
||||
|
||||
/// The key that is updated whenever new messages are available in the queue. If null, it is inferred that the publisher
|
||||
/// is finite and will terminate when the end-of-queue at time of publisher creation is reached. Otherwise, the publisher
|
||||
/// is "infinite" and will continue to wait for new messages and publish them in a loop.
|
||||
@Nullable private final byte[] messagesAvailableWatchKey;
|
||||
/// Listener to watch for state machine transitions; used for testing.
|
||||
private final BiConsumer<State, State> stateChangeListener;
|
||||
private final Flux<FoundationDbMessageStreamEntry.Message> messagePublisher;
|
||||
/// Whether the publisher is finite or infinite.
|
||||
private final boolean terminateOnQueueEmpty;
|
||||
/// 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;
|
||||
|
||||
/// Tracks the current state of the publisher state machine. Initial state presumes that messages are available in the queue.
|
||||
private State state = State.MESSAGES_AVAILABLE;
|
||||
/// Reference to the sink we publish messages to.
|
||||
private volatile FluxSink<FoundationDbMessageStreamEntry.Message> emitter;
|
||||
/// Future that completes when the watch for {@link #messagesAvailableWatchKey} triggers.
|
||||
private CompletableFuture<Void> watchFuture;
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(FoundationDbMessagePublisher.class);
|
||||
|
||||
FoundationDbMessagePublisher(
|
||||
final Database database,
|
||||
final Clock clock,
|
||||
final KeySelector beginKeyInclusive,
|
||||
final KeySelector endKeyExclusive,
|
||||
final Database database,
|
||||
final int maxMessagesPerScan,
|
||||
@Nullable final byte[] presenceKey,
|
||||
@Nullable final ScheduledExecutorService presenceRenewalExecutorService,
|
||||
@Nullable final byte[] messagesAvailableWatchKey,
|
||||
@Nullable final BiConsumer<State, State> stateChangeListener,
|
||||
final Supplier<Consumer<Transaction>> beforePageFetch) {
|
||||
|
||||
this.database = database;
|
||||
this.clock = clock;
|
||||
this.beginKeyCursor = beginKeyInclusive;
|
||||
this.endKeyExclusive = endKeyExclusive;
|
||||
this.database = database;
|
||||
this.maxMessagesPerScan = maxMessagesPerScan;
|
||||
this.presenceKey = presenceKey;
|
||||
this.messagesAvailableWatchKey = messagesAvailableWatchKey;
|
||||
this.terminateOnQueueEmpty = messagesAvailableWatchKey == null;
|
||||
this.stateChangeListener = stateChangeListener != null ? stateChangeListener : (_, _) -> {};
|
||||
this.beforePageFetch = beforePageFetch;
|
||||
this.messagePublisher = Flux.create(emitter -> {
|
||||
|
||||
if (!terminateOnQueueEmpty) {
|
||||
Objects.requireNonNull(presenceKey);
|
||||
Objects.requireNonNull(presenceRenewalExecutorService);
|
||||
}
|
||||
|
||||
this.messagePublisher = Flux.<FoundationDbMessageStreamEntry.Message>create(emitter -> {
|
||||
this.emitter = emitter;
|
||||
emitter.onRequest(_ -> transitionStateOnEvent(Event.DEMAND_REQUESTED));
|
||||
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);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -121,18 +181,22 @@ class FoundationDbMessagePublisher {
|
||||
/// cases when callers need to "catch up" on stored messages without following fresh updates (for example, when a
|
||||
/// client first connects and needs to load stored messages before receiving a "live" stream of new messages).
|
||||
public static FoundationDbMessagePublisher createFinitePublisher(
|
||||
final Database database,
|
||||
final Clock clock,
|
||||
final KeySelector beginKeyInclusive,
|
||||
final KeySelector endKeyExclusive,
|
||||
final Database database,
|
||||
final int maxMessagesPerScan,
|
||||
final Supplier<Consumer<Transaction>> beforePageFetch) {
|
||||
|
||||
return new FoundationDbMessagePublisher(beginKeyInclusive,
|
||||
return new FoundationDbMessagePublisher(database,
|
||||
clock,
|
||||
beginKeyInclusive,
|
||||
endKeyExclusive,
|
||||
database,
|
||||
maxMessagesPerScan,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
beforePageFetch);
|
||||
}
|
||||
|
||||
@@ -140,17 +204,23 @@ class FoundationDbMessagePublisher {
|
||||
/// It waits for new messages and publishes them in a loop. Useful when a client has finished receiving its stored
|
||||
/// messages and is now waiting for a live stream of new messages.
|
||||
public static FoundationDbMessagePublisher createInfinitePublisher(
|
||||
final Database database,
|
||||
final Clock clock,
|
||||
final KeySelector beginKeyInclusive,
|
||||
final KeySelector endKeyExclusive,
|
||||
final Database database,
|
||||
final int maxMessagesPerScan,
|
||||
final byte[] presenceKey,
|
||||
final ScheduledExecutorService presenceRenewalExecutorService,
|
||||
final byte[] messagesAvailableWatchKey,
|
||||
final Supplier<Consumer<Transaction>> beforePageFetch) {
|
||||
|
||||
return new FoundationDbMessagePublisher(beginKeyInclusive,
|
||||
return new FoundationDbMessagePublisher(database,
|
||||
clock,
|
||||
beginKeyInclusive,
|
||||
endKeyExclusive,
|
||||
database,
|
||||
maxMessagesPerScan,
|
||||
presenceKey,
|
||||
presenceRenewalExecutorService,
|
||||
messagesAvailableWatchKey,
|
||||
null,
|
||||
beforePageFetch);
|
||||
@@ -320,6 +390,7 @@ class FoundationDbMessagePublisher {
|
||||
getMessagesBatch()
|
||||
.thenAccept(messageStreamEntries -> {
|
||||
messageStreamEntries.forEach(emitter::next);
|
||||
totalEmitted.addAndGet(messageStreamEntries.size());
|
||||
transitionStateOnEvent(Event.PUBLISHED_MESSAGES);
|
||||
})
|
||||
.exceptionally(t -> {
|
||||
@@ -345,15 +416,6 @@ class FoundationDbMessagePublisher {
|
||||
watchFuture.thenRun(() -> transitionStateOnEvent(Event.MESSAGE_AVAILABLE_WATCH_TRIGGERED));
|
||||
}
|
||||
|
||||
private synchronized void onDispose() {
|
||||
// Unless the state machine is an already terminal state, directly set state to "terminated", since there's no point
|
||||
// in evaluating the state machine when there's no live subscription.
|
||||
if (state != State.TERMINATED && state != State.ERROR) {
|
||||
setState(State.TERMINATED, Event.INTERNAL_TRIGGER);
|
||||
}
|
||||
cancelWatch();
|
||||
}
|
||||
|
||||
/// Cancel the watch (if any). Although inactive watches are automatically timed-out, we explicitly cancel when the
|
||||
/// subscription is disposed to clean up associated resources and to avoid having too many watches open at once.
|
||||
private synchronized void cancelWatch() {
|
||||
@@ -362,4 +424,80 @@ class FoundationDbMessagePublisher {
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void startPresenceRenewal(final ScheduledExecutorService presenceRenewalExecutorService) {
|
||||
final long renewalIntervalMillis =
|
||||
FoundationDbMessageStore.PRESENCE_STALE_THRESHOLD.multipliedBy(4).dividedBy(5).toMillis();
|
||||
|
||||
renewPresenceFuture = presenceRenewalExecutorService.scheduleWithFixedDelay(this::renewPresence,
|
||||
renewalIntervalMillis,
|
||||
renewalIntervalMillis,
|
||||
TimeUnit.MILLISECONDS);
|
||||
}
|
||||
|
||||
private synchronized void renewPresence() {
|
||||
if (state == State.TERMINATED || state == State.ERROR) {
|
||||
return;
|
||||
}
|
||||
|
||||
database.runAsync(transaction -> {
|
||||
setPresence(transaction);
|
||||
return CompletableFuture.completedFuture(null);
|
||||
})
|
||||
.whenComplete((_, throwable) -> {
|
||||
if (throwable != null) {
|
||||
LOGGER.warn("Failed to renew presence; will terminate publisher", throwable);
|
||||
terminateWithError(throwable);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void setPresence(final Transaction transaction) {
|
||||
transaction.set(presenceKey, FoundationDbMessageStore.getPresenceValue(clock.instant(), streamId));
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
synchronized void clearPresence() {
|
||||
if (renewPresenceFuture != null) {
|
||||
renewPresenceFuture.cancel(true);
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
if (Arrays.equals(presenceServerId, FoundationDbMessageStore.getServerId()) && streamId == presenceStreamId) {
|
||||
transaction.clear(presenceKey);
|
||||
}
|
||||
}))
|
||||
.whenComplete((_, throwable) -> {
|
||||
if (throwable != null) {
|
||||
LOGGER.warn("Failed to clear presence on disposal", throwable);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
synchronized void terminateWithError(final Throwable throwable) {
|
||||
if (state != State.TERMINATED && state != State.ERROR) {
|
||||
setState(State.ERROR, Event.INTERNAL_TRIGGER);
|
||||
}
|
||||
|
||||
emitter.error(throwable);
|
||||
}
|
||||
|
||||
private synchronized void onDispose() {
|
||||
// Unless the state machine is an already terminal state, directly set state to "terminated", since there's no point
|
||||
// in evaluating the state machine when there's no live subscription.
|
||||
if (state != State.TERMINATED && state != State.ERROR) {
|
||||
setState(State.TERMINATED, Event.INTERNAL_TRIGGER);
|
||||
}
|
||||
cancelWatch();
|
||||
clearPresence();
|
||||
}
|
||||
}
|
||||
+70
-47
@@ -13,10 +13,12 @@ import io.dropwizard.util.DataSize;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.IdentityHashMap;
|
||||
import java.util.List;
|
||||
@@ -24,16 +26,16 @@ import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
import javax.annotation.Nullable;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.MessageStream;
|
||||
import org.whispersystems.textsecuregcm.util.Conversions;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
/// An implementation of a message store backed by FoundationDB.
|
||||
@@ -54,10 +56,16 @@ public class FoundationDbMessageStore {
|
||||
private final int[] liveEpochs;
|
||||
private final int activeEpoch;
|
||||
private final VersionstampUUIDCipher versionstampUUIDCipher;
|
||||
private final ScheduledExecutorService presenceRenewalExecutorService;
|
||||
private final Clock clock;
|
||||
|
||||
private static final byte[] SERVER_ID = UUIDUtil.toBytes(UUID.randomUUID());
|
||||
private static final int PRESENCE_VALUE_LENGTH = 28;
|
||||
|
||||
private static final Subspace MESSAGES_SUBSPACE = new Subspace(Tuple.from("M"));
|
||||
private static final Duration PRESENCE_STALE_THRESHOLD = Duration.ofMinutes(5);
|
||||
|
||||
@VisibleForTesting
|
||||
static final Duration PRESENCE_STALE_THRESHOLD = Duration.ofMinutes(5);
|
||||
|
||||
/// The (approximate) transaction size beyond which we do not add more messages in a transaction. The estimated size
|
||||
/// includes only message payloads (and not key reads/writes) which we assume will dominate the total
|
||||
@@ -76,12 +84,6 @@ 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
|
||||
@@ -96,6 +98,7 @@ public class FoundationDbMessageStore {
|
||||
public FoundationDbMessageStore(final Map<Integer, List<Database>> databasesByEpochMap,
|
||||
final int activeEpoch,
|
||||
final VersionstampUUIDCipher versionstampUUIDCipher,
|
||||
final ScheduledExecutorService presenceRenewalExecutorService,
|
||||
final Clock clock) {
|
||||
|
||||
final Database[][] databasesByEpochArray = new Database[MAX_EPOCHS][];
|
||||
@@ -107,6 +110,7 @@ public class FoundationDbMessageStore {
|
||||
this.liveEpochs = IntStream.range(0, MAX_EPOCHS).filter(e -> databasesByEpochArray[e] != null).toArray();
|
||||
this.activeEpoch = activeEpoch;
|
||||
this.versionstampUUIDCipher = versionstampUUIDCipher;
|
||||
this.presenceRenewalExecutorService = presenceRenewalExecutorService;
|
||||
this.versionstampClocks = databasesByEpochMap.values().stream()
|
||||
.flatMap(List::stream)
|
||||
.distinct()
|
||||
@@ -339,27 +343,6 @@ public class FoundationDbMessageStore {
|
||||
});
|
||||
}
|
||||
|
||||
// Note that this method is intended only for initial migration support; in general, callers should clear messages
|
||||
// by acknowledging messages via a `FoundationDbMessageStream`.
|
||||
public CompletableFuture<Void> delete(final AciServiceIdentifier aci, final byte deviceId, final UUID messageGuid) {
|
||||
return delete(aci, deviceId, versionstampUUIDCipher.decryptVersionstamp(messageGuid, aci.uuid(), deviceId));
|
||||
}
|
||||
|
||||
private 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());
|
||||
@@ -382,14 +365,14 @@ public class FoundationDbMessageStore {
|
||||
.forEach(action);
|
||||
}
|
||||
|
||||
public MessageStream getMessages(final AciServiceIdentifier aci, final Device destinationDevice) {
|
||||
return getMessages(aci, destinationDevice, FoundationDbMessageStream.DEFAULT_MAX_MESSAGES_PER_SCAN,
|
||||
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);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
MessageStream getMessages(final AciServiceIdentifier aci,
|
||||
final Device destinationDevice,
|
||||
FoundationDbMessageStream getMessages(final AciServiceIdentifier aci,
|
||||
final byte deviceId,
|
||||
final int maxMessagesPerScan,
|
||||
final int maxUnacknowledgedMessages,
|
||||
final Runnable doAfterCleanup) {
|
||||
@@ -401,13 +384,16 @@ public class FoundationDbMessageStore {
|
||||
databasesForQueueByEpoch[epoch] = getShardForAci(aci, epoch);
|
||||
}
|
||||
|
||||
return new FoundationDbMessageStream(getDeviceQueueSubspace(aci, destinationDevice.getId()),
|
||||
return new FoundationDbMessageStream(getDeviceQueueSubspace(aci, deviceId),
|
||||
getPresenceKey(aci, deviceId),
|
||||
getMessagesAvailableWatchKey(aci),
|
||||
databasesForQueueByEpoch,
|
||||
new MessageGuidCodec(aci.uuid(), destinationDevice.getId(), versionstampUUIDCipher),
|
||||
new MessageGuidCodec(aci.uuid(), deviceId, versionstampUUIDCipher),
|
||||
maxMessagesPerScan,
|
||||
maxUnacknowledgedMessages,
|
||||
doAfterCleanup);
|
||||
doAfterCleanup,
|
||||
presenceRenewalExecutorService,
|
||||
clock);
|
||||
}
|
||||
|
||||
/// Record the versionstamp for the current time in each database's versionstamp clock.
|
||||
@@ -530,19 +516,56 @@ public class FoundationDbMessageStore {
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
byte[] getPresenceKey(final AciServiceIdentifier aci, final byte deviceId) {
|
||||
return getDeviceSubspace(aci, deviceId).pack("p");
|
||||
static byte[] getServerId() {
|
||||
return SERVER_ID;
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
boolean isClientPresent(final byte[] presenceValueBytes) {
|
||||
if (presenceValueBytes == null) {
|
||||
static byte[] getPresenceKey(final AciServiceIdentifier aci, final byte deviceId) {
|
||||
return getDeviceSubspace(aci, deviceId).pack("p");
|
||||
}
|
||||
|
||||
static byte[] getPresenceValue(final Instant timestamp, final int streamId) {
|
||||
return ByteBuffer.allocate(PRESENCE_VALUE_LENGTH)
|
||||
.put(SERVER_ID)
|
||||
.putInt(streamId)
|
||||
.putLong(timestamp.toEpochMilli())
|
||||
.array();
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static byte[] getPresenceServerId(final byte[] presenceValue) {
|
||||
if (presenceValue.length != PRESENCE_VALUE_LENGTH) {
|
||||
throw new IllegalArgumentException("Unexpected presence value length: " + presenceValue.length);
|
||||
}
|
||||
|
||||
return Arrays.copyOfRange(presenceValue, 0, 16);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static int getPresenceStreamId(final byte[] presenceValue) {
|
||||
if (presenceValue.length != PRESENCE_VALUE_LENGTH) {
|
||||
throw new IllegalArgumentException("Unexpected presence value length: " + presenceValue.length);
|
||||
}
|
||||
|
||||
return ByteBuffer.wrap(presenceValue).getInt(16);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static Instant getPresenceTimestamp(final byte[] presenceValue) {
|
||||
if (presenceValue.length != PRESENCE_VALUE_LENGTH) {
|
||||
throw new IllegalArgumentException("Unexpected presence value length: " + presenceValue.length);
|
||||
}
|
||||
|
||||
return Instant.ofEpochMilli(ByteBuffer.wrap(presenceValue).getLong(20));
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
boolean isClientPresent(@Nullable final byte[] presenceValue) {
|
||||
if (presenceValue == null) {
|
||||
return false;
|
||||
}
|
||||
final long presenceValue = Conversions.byteArrayToLong(presenceValueBytes);
|
||||
// The presence value is a long with the higher order 16 bits containing a server id, and the lower 48 bits
|
||||
// containing the timestamp (seconds since epoch) that the client updates periodically.
|
||||
final long lastSeenSecondsSinceEpoch = presenceValue & 0x0000ffffffffffffL;
|
||||
return (clock.instant().getEpochSecond() - lastSeenSecondsSinceEpoch) <= PRESENCE_STALE_THRESHOLD.toSeconds();
|
||||
|
||||
return Duration.between(getPresenceTimestamp(presenceValue), clock.instant()).compareTo(PRESENCE_STALE_THRESHOLD) <= 0;
|
||||
}
|
||||
}
|
||||
+35
-6
@@ -13,6 +13,7 @@ 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;
|
||||
@@ -23,6 +24,7 @@ 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;
|
||||
@@ -41,6 +43,7 @@ import reactor.util.function.Tuples;
|
||||
public class FoundationDbMessageStream implements MessageStream {
|
||||
|
||||
private final Subspace deviceQueueSubspace;
|
||||
private final byte[] presenceKey;
|
||||
private final byte[] messagesAvailableWatchKey;
|
||||
private final Database[] databasesByEpoch;
|
||||
private final MessageGuidCodec messageGuidCodec;
|
||||
@@ -48,12 +51,21 @@ public class FoundationDbMessageStream implements MessageStream {
|
||||
private final int maxMessagesPerScan;
|
||||
private final Flow.Publisher<MessageStreamEntry> messageStreamPublisher;
|
||||
private final Runnable doAfterCleanup;
|
||||
private final ScheduledExecutorService presenceRenewalExecutorService;
|
||||
private final Clock clock;
|
||||
|
||||
private final Map<Database, AcknowledgedMessageBuffer> acknowledgedMessageBuffersByDatabase;
|
||||
|
||||
private final Counter staleEphemeralMessagesCounter = Metrics.counter(
|
||||
name(FoundationDbMessageStream.class, "staleEphemeralMessages"));
|
||||
static final int DEFAULT_MAX_MESSAGES_PER_SCAN = 1024;
|
||||
private final Counter messageReadCounter =
|
||||
Metrics.counter(name(FoundationDbMessageStream.class, "messagesRead"));
|
||||
|
||||
private final Counter messageAcknowledgedCounter =
|
||||
Metrics.counter(name(FoundationDbMessageStream.class, "messagesAcknowledged"));
|
||||
|
||||
private final Counter staleEphemeralMessagesCounter =
|
||||
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;
|
||||
|
||||
@@ -63,19 +75,25 @@ public class FoundationDbMessageStream implements MessageStream {
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(FoundationDbMessageStream.class);
|
||||
|
||||
FoundationDbMessageStream(final Subspace deviceQueueSubspace,
|
||||
final byte[] presenceKey,
|
||||
final byte[] messagesAvailableWatchKey,
|
||||
final Database[] databasesByEpoch,
|
||||
final MessageGuidCodec messageGuidCodec,
|
||||
final int maxMessagesPerScan,
|
||||
final int maxUnacknowledgedMessages,
|
||||
final Runnable doAfterCleanup) {
|
||||
final Runnable doAfterCleanup,
|
||||
final ScheduledExecutorService presenceRenewalExecutorService,
|
||||
final Clock clock) {
|
||||
this.deviceQueueSubspace = deviceQueueSubspace;
|
||||
this.presenceKey = presenceKey;
|
||||
this.messagesAvailableWatchKey = messagesAvailableWatchKey;
|
||||
this.databasesByEpoch = databasesByEpoch;
|
||||
this.messageGuidCodec = messageGuidCodec;
|
||||
this.maxMessagesPerScan = maxMessagesPerScan;
|
||||
this.messageStreamPublisher = JdkFlowAdapter.publisherToFlowPublisher(createMessagePublisher());
|
||||
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
|
||||
@@ -116,6 +134,11 @@ public class FoundationDbMessageStream implements MessageStream {
|
||||
sink.next(messageStreamEntry);
|
||||
})
|
||||
.map(fdbMessageStreamEntry -> fdbMessageStreamEntry.toMessageStreamEntry(messageGuidCodec))
|
||||
.doOnNext(messageStreamEntry -> {
|
||||
if (messageStreamEntry instanceof MessageStreamEntry.Envelope) {
|
||||
messageReadCounter.increment();
|
||||
}
|
||||
})
|
||||
.doFinally(_ -> flushAllAcknowledgedMessages().thenRun(doAfterCleanup));
|
||||
}
|
||||
|
||||
@@ -149,9 +172,10 @@ public class FoundationDbMessageStream implements MessageStream {
|
||||
|
||||
return maybeEndOfQueueKeyExclusive
|
||||
.map(endOfQueueKeyExclusive -> FoundationDbMessagePublisher.createFinitePublisher(
|
||||
database,
|
||||
clock,
|
||||
KeySelector.firstGreaterOrEqual(deviceQueueSubspace.range().begin),
|
||||
endOfQueueKeyExclusive,
|
||||
database,
|
||||
maxMessagesPerScan,
|
||||
() -> this.clearAcknowledgedMessages(database))
|
||||
.getMessages())
|
||||
@@ -178,10 +202,13 @@ public class FoundationDbMessageStream implements MessageStream {
|
||||
.orElseGet(() -> KeySelector.firstGreaterOrEqual(deviceQueueSubspace.range().begin));
|
||||
|
||||
return FoundationDbMessagePublisher.createInfinitePublisher(
|
||||
database,
|
||||
clock,
|
||||
infinitePublisherBeginKey,
|
||||
KeySelector.firstGreaterThan(deviceQueueSubspace.range().end),
|
||||
database,
|
||||
maxMessagesPerScan,
|
||||
presenceKey,
|
||||
presenceRenewalExecutorService,
|
||||
messagesAvailableWatchKey,
|
||||
() -> clearAcknowledgedMessages(database)).getMessages();
|
||||
})
|
||||
@@ -225,6 +252,8 @@ public class FoundationDbMessageStream implements MessageStream {
|
||||
final Versionstamp versionstamp = messageGuidCodec.decodeMessageGuid(messageGuid);
|
||||
getAcknowledgedMessageBuffer(versionstamp).acknowledgeMessage(versionstamp);
|
||||
|
||||
messageAcknowledgedCounter.increment();
|
||||
|
||||
return CompletableFuture.completedFuture(null);
|
||||
}
|
||||
|
||||
|
||||
+2
-2
@@ -133,7 +133,7 @@ public class AppleAppStoreClient {
|
||||
final APIError apiError = e.getApiError();
|
||||
Metrics.counter(GET_SUBSCRIPTION_ERROR_COUNTER_NAME, errorTags.and("reason", apiError != null ? apiError.name() : "http_" + e.getHttpStatusCode())).increment();
|
||||
throw switch (e.getApiError()) {
|
||||
case TRANSACTION_ID_NOT_FOUND, ORIGINAL_TRANSACTION_ID_NOT_FOUND -> new SubscriptionNotFoundException();
|
||||
case TRANSACTION_ID_NOT_FOUND, ORIGINAL_TRANSACTION_ID_NOT_FOUND, ACCOUNT_NOT_FOUND -> new SubscriptionNotFoundException();
|
||||
case RATE_LIMIT_EXCEEDED -> new RateLimitExceededException(null);
|
||||
case INVALID_ORIGINAL_TRANSACTION_ID -> new SubscriptionInvalidArgumentsException(e.getApiErrorMessage());
|
||||
case null, default -> throw e;
|
||||
@@ -183,7 +183,7 @@ public class AppleAppStoreClient {
|
||||
|
||||
private static boolean shouldRetry(Throwable e) {
|
||||
return e instanceof APIException apiException && switch (apiException.getApiError()) {
|
||||
case ORIGINAL_TRANSACTION_ID_NOT_FOUND_RETRYABLE, GENERAL_INTERNAL_RETRYABLE, APP_NOT_FOUND_RETRYABLE -> true;
|
||||
case ORIGINAL_TRANSACTION_ID_NOT_FOUND_RETRYABLE, GENERAL_INTERNAL_RETRYABLE, APP_NOT_FOUND_RETRYABLE, ACCOUNT_NOT_FOUND_RETRYABLE -> true;
|
||||
case null, default -> false;
|
||||
};
|
||||
}
|
||||
|
||||
+59
-81
@@ -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;
|
||||
|
||||
+114
-113
@@ -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) {
|
||||
|
||||
+4
-2
@@ -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);
|
||||
|
||||
|
||||
+14
-1
@@ -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;
|
||||
};
|
||||
}
|
||||
}
|
||||
+5
-5
@@ -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;
|
||||
};
|
||||
}
|
||||
}
|
||||
+178
-180
@@ -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;
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.util;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonGenerator;
|
||||
import com.fasterxml.jackson.core.JsonParseException;
|
||||
import com.fasterxml.jackson.core.JsonParser;
|
||||
import com.fasterxml.jackson.databind.DeserializationContext;
|
||||
import com.fasterxml.jackson.databind.JsonDeserializer;
|
||||
import com.fasterxml.jackson.databind.JsonSerializer;
|
||||
import com.fasterxml.jackson.databind.SerializerProvider;
|
||||
import java.io.IOException;
|
||||
import java.util.Base64;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.ZkCredentialPublicKey;
|
||||
|
||||
public class ZkCredentialPublicKeyAdapter {
|
||||
public static class Serializer extends JsonSerializer<ZkCredentialPublicKey> {
|
||||
|
||||
@Override
|
||||
public void serialize(final ZkCredentialPublicKey zkCredentialPublicKey,
|
||||
final JsonGenerator jsonGenerator,
|
||||
final SerializerProvider serializers) throws IOException {
|
||||
|
||||
jsonGenerator.writeString(Base64.getEncoder().encodeToString(zkCredentialPublicKey.serialize()));
|
||||
}
|
||||
}
|
||||
|
||||
public static class Deserializer extends JsonDeserializer<ZkCredentialPublicKey> {
|
||||
|
||||
@Override
|
||||
public ZkCredentialPublicKey deserialize(final JsonParser parser, final DeserializationContext context) throws IOException {
|
||||
final byte[] zkCredentialPublicKeyBytes;
|
||||
|
||||
try {
|
||||
zkCredentialPublicKeyBytes = Base64.getDecoder().decode(parser.getValueAsString());
|
||||
} catch (final IllegalArgumentException e) {
|
||||
throw new JsonParseException(parser, "Could not parse key as a base64-encoded value", e);
|
||||
}
|
||||
|
||||
if (zkCredentialPublicKeyBytes.length == 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
return new ZkCredentialPublicKey(zkCredentialPublicKeyBytes);
|
||||
} catch (final InvalidInputException e) {
|
||||
// this should really never happen, as ZkCredentialPublicKey simply extends ByteArray
|
||||
throw new JsonParseException(parser, "Could not interpret bytes as a ZK credential public key", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+10
-4
@@ -69,6 +69,7 @@ import org.whispersystems.textsecuregcm.storage.MessagesDynamoDb;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesManager;
|
||||
import org.whispersystems.textsecuregcm.storage.PagedSingleUseKEMPreKeyStore;
|
||||
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
|
||||
import org.whispersystems.textsecuregcm.storage.ProfileAvatars;
|
||||
import org.whispersystems.textsecuregcm.storage.Profiles;
|
||||
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ProfilesV2;
|
||||
@@ -220,6 +221,8 @@ public record CommandDependencies(
|
||||
.threads(1).build();
|
||||
final ScheduledExecutorService retryExecutor = ScheduledExecutorServiceBuilder.of(environment, "retry")
|
||||
.threads(1).build();
|
||||
final ScheduledExecutorService presenceRenewalExecutor =
|
||||
ScheduledExecutorServiceBuilder.of(environment, "presenceRenewal").threads(1).build();
|
||||
|
||||
ExternalServiceCredentialsGenerator storageCredentialsGenerator = SecureStorageController.credentialsGenerator(
|
||||
configuration.getSecureStorageServiceConfiguration());
|
||||
@@ -266,6 +269,8 @@ public record CommandDependencies(
|
||||
configuration.getDynamoDbTables().getPhoneNumberIdentifiers().getTableName());
|
||||
Profiles profilesV1 = new Profiles(dynamoDbClient, dynamoDbAsyncClient,
|
||||
configuration.getDynamoDbTables().getProfilesV1().getTableName());
|
||||
ProfileAvatars profileAvatars = new ProfileAvatars(dynamoDbClient,
|
||||
configuration.getDynamoDbTables().getProfileAvatars().getTableName(), RemoveExpiredAccountsCommand.MAX_IDLE_DURATION, clock);
|
||||
ProfilesV2 profiles = new ProfilesV2(dynamoDbClient, dynamoDbAsyncClient,
|
||||
configuration.getDynamoDbTables().getProfilesV2().getTableName());
|
||||
S3AsyncClient asyncKeysS3Client = S3AsyncClient.builder()
|
||||
@@ -313,8 +318,9 @@ public record CommandDependencies(
|
||||
configuration.getFoundationDbMessagesConfiguration().activeEpoch(),
|
||||
new VersionstampUUIDCipher(configuration.getFoundationDbMessagesConfiguration().currentVersionstampCipherKey(),
|
||||
configuration.getFoundationDbMessagesConfiguration().versionstampCipherKeys().get(configuration.getFoundationDbMessagesConfiguration().currentVersionstampCipherKey()).value()),
|
||||
presenceRenewalExecutor,
|
||||
Clock.systemUTC());
|
||||
ProfilesManager profilesManager = new ProfilesManager(profilesV1, profiles, cacheCluster, retryExecutor, asyncCdnS3Client,
|
||||
ProfilesManager profilesManager = new ProfilesManager(profilesV1, profiles, profileAvatars, cacheCluster, retryExecutor, asyncCdnS3Client,
|
||||
configuration.getCdnConfiguration().bucket());
|
||||
ReportMessageDynamoDb reportMessageDynamoDb = new ReportMessageDynamoDb(dynamoDbClient, dynamoDbAsyncClient,
|
||||
configuration.getDynamoDbTables().getReportMessage().getTableName(),
|
||||
@@ -345,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);
|
||||
}
|
||||
@@ -362,7 +368,7 @@ public record CommandDependencies(
|
||||
secureValueRecoveryBCredentialsGenerator,
|
||||
secureValueRecoveryBClient,
|
||||
clock,
|
||||
dynamicConfigurationManager);
|
||||
configuration.getBackupConfiguration());
|
||||
|
||||
final IssuedReceiptsManager issuedReceiptsManager = new IssuedReceiptsManager(
|
||||
configuration.getDynamoDbTables().getIssuedReceipts().getTableName(),
|
||||
@@ -371,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)),
|
||||
|
||||
@@ -269,7 +269,7 @@ message LookupUsernameLinkResponse {
|
||||
}
|
||||
|
||||
message SetZkCredentialKeyRequest {
|
||||
// A serialized Ristretto key with a one-byte type prefix
|
||||
// A serialized libsignal ZkCredentialPublicKey
|
||||
bytes public_key = 1 [(require.exactlySize) = 33];
|
||||
}
|
||||
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -9,6 +9,8 @@ option java_multiple_files = true;
|
||||
|
||||
package org.signal.chat.profile;
|
||||
|
||||
import "google/protobuf/empty.proto";
|
||||
|
||||
import "org/signal/chat/common.proto";
|
||||
import "org/signal/chat/errors.proto";
|
||||
import "org/signal/chat/require.proto";
|
||||
@@ -26,6 +28,11 @@ service Profile {
|
||||
// Retrieves unversioned profile data. Callers with an unidentified access key for the account
|
||||
// should use the version of this method in `ProfileAnonymous` instead.
|
||||
rpc GetUnversionedProfile(GetUnversionedProfileRequest) returns (GetUnversionedProfileResponse) {}
|
||||
|
||||
// Returns anonymous credentials that may be presented with avatar operations in ProfilesAnonymous
|
||||
//
|
||||
// Note: `Accounts.SetZkCredentialKey` is a pre-requisite for this RPC
|
||||
rpc GetAvatarCredentials(GetAvatarCredentialsRequest) returns (GetAvatarCredentialsResponse) {}
|
||||
}
|
||||
|
||||
// Provides methods for working with profiles and profile-related data using "unidentified access"
|
||||
@@ -41,6 +48,24 @@ service ProfileAnonymous {
|
||||
rpc GetUnversionedProfile(GetUnversionedProfileAnonymousRequest) returns (GetUnversionedProfileAnonymousResponse) {}
|
||||
// Retrieves a profile key credential.
|
||||
rpc GetExpiringProfileKeyCredential(GetExpiringProfileKeyCredentialAnonymousRequest) returns (GetExpiringProfileKeyCredentialAnonymousResponse) {}
|
||||
|
||||
// Returns credentials to upload a v2 avatar. After uploading the avatar, the client
|
||||
// must call SetProfile with the new avatar URL in the encrypted `data`.
|
||||
//
|
||||
// Because avatars are uploaded anonymously, they have an expiration equal to the
|
||||
// idle account expiration. Clients must periodically (recommended: every 90 days)
|
||||
// call ExtendAvatarTTL to extend the TTl.
|
||||
//
|
||||
// Note: any existing avatar associated with these credentials will be deleted immediately
|
||||
rpc GetAvatarUploadForm(GetAvatarUploadFormRequest) returns (GetAvatarUploadFormResponse) {}
|
||||
|
||||
// Extends the TTL of the avatar currently associated with the request’s avatar auth credential
|
||||
rpc ExtendAvatarTTL(ExtendAvatarTTLRequest) returns (ExtendAvatarTTLResponse) {}
|
||||
|
||||
// Deletes the avatar currently associated with the request’s avatar auth credential.
|
||||
//
|
||||
// Clients must also call SetProfile to remove the avatar from the encrypted `data`.
|
||||
rpc DeleteAvatar(DeleteAvatarRequest) returns (DeleteAvatarResponse) {}
|
||||
}
|
||||
|
||||
message SetProfileV1Request {
|
||||
@@ -325,3 +350,59 @@ enum CredentialType {
|
||||
CREDENTIAL_TYPE_UNSPECIFIED = 0;
|
||||
CREDENTIAL_TYPE_EXPIRING_PROFILE_KEY = 1;
|
||||
}
|
||||
|
||||
// avatar auth
|
||||
|
||||
message GetAvatarCredentialsRequest {
|
||||
bytes avatar_credentials_request = 1;
|
||||
}
|
||||
|
||||
message GetAvatarCredentialsResponse {
|
||||
oneof response {
|
||||
bytes avatar_credentials = 1;
|
||||
|
||||
// the client must call Accounts.SetZkCredentialKey to call this method
|
||||
errors.FailedPrecondition missing_zk_credential_key = 2 [(tag.reason) = "missing_zk_credential_key"];
|
||||
}
|
||||
}
|
||||
|
||||
message GetAvatarUploadFormRequest {
|
||||
bytes avatar_credentials_presentation = 1;
|
||||
|
||||
// The length of the attachment for the requested upload form. Uploads
|
||||
// performed with this form will be limited to the provided length.
|
||||
uint32 upload_length = 2 [(require.range) = {min: 1, max: 10485760 /* 10 MiB */}];
|
||||
}
|
||||
|
||||
message GetAvatarUploadFormResponse {
|
||||
oneof response {
|
||||
common.S3UploadForm avatar_upload_form = 1;
|
||||
|
||||
errors.FailedZkAuthentication invalid_credentials_presentation = 2 [(tag.reason) = "invalid_credentials_presentation"];
|
||||
}
|
||||
}
|
||||
|
||||
message ExtendAvatarTTLRequest {
|
||||
bytes avatar_credentials_presentation = 1;
|
||||
}
|
||||
|
||||
message ExtendAvatarTTLResponse {
|
||||
oneof response {
|
||||
// The avatar that was extended. May be used as a check against state de-synchronization.
|
||||
string path = 1;
|
||||
errors.FailedZkAuthentication invalid_credentials_presentation = 2 [(tag.reason) = "invalid_credentials_presentation"];
|
||||
// the identity does not have an active avatar
|
||||
errors.NotFound not_found = 3 [(tag.reason) = "no_active_avatar"];
|
||||
}
|
||||
}
|
||||
|
||||
message DeleteAvatarRequest {
|
||||
bytes avatar_credentials_presentation = 1;
|
||||
}
|
||||
|
||||
message DeleteAvatarResponse {
|
||||
oneof response {
|
||||
google.protobuf.Empty success = 1;
|
||||
errors.FailedZkAuthentication invalid_credentials_presentation = 2 [(tag.reason) = "invalid_credentials_presentation"];
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
+3
-10
@@ -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
|
||||
|
||||
+15
-12
@@ -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")
|
||||
|
||||
+1
-9
@@ -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()))
|
||||
|
||||
+11
-7
@@ -8,7 +8,6 @@ package org.whispersystems.textsecuregcm.grpc;
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.AdditionalMatchers.aryEq;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
@@ -61,6 +60,8 @@ import org.signal.chat.account.UsernameNotAvailable;
|
||||
import org.signal.chat.common.AccountIdentifiers;
|
||||
import org.signal.chat.errors.FailedPrecondition;
|
||||
import org.signal.libsignal.usernames.BaseUsernameException;
|
||||
import org.signal.libsignal.zkgroup.ZkCredentialKeyPair;
|
||||
import org.signal.libsignal.zkgroup.ZkCredentialPublicKey;
|
||||
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
|
||||
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
|
||||
import org.whispersystems.textsecuregcm.controllers.AccountController;
|
||||
@@ -120,12 +121,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));
|
||||
@@ -136,6 +139,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();
|
||||
|
||||
@@ -707,15 +711,15 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void setZkCredentialKey(final boolean matchesCurrentZkCredentialKey) {
|
||||
void setZkCredentialKey(final boolean matchesCurrentZkCredentialKey) throws Exception {
|
||||
|
||||
final byte[] publicKey = TestRandomUtil.nextBytes(33);
|
||||
final ZkCredentialPublicKey publicKey = ZkCredentialKeyPair.generate().getPublicKey();
|
||||
final long rotationId = ThreadLocalRandom.current().nextLong(1, Long.MAX_VALUE);
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
|
||||
if (matchesCurrentZkCredentialKey) {
|
||||
when(account.getZkCredentialKey()).thenReturn(publicKey);
|
||||
when(account.getZkCredentialKey()).thenReturn(Optional.of(publicKey));
|
||||
when(account.getZkCredentialKeyRotationId()).thenReturn(rotationId);
|
||||
}
|
||||
|
||||
@@ -724,7 +728,7 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
|
||||
|
||||
final SetZkCredentialKeyResponse response = assertDoesNotThrow(() ->
|
||||
authenticatedServiceStub().setZkCredentialKey(SetZkCredentialKeyRequest.newBuilder()
|
||||
.setPublicKey(ByteString.copyFrom(publicKey))
|
||||
.setPublicKey(ByteString.copyFrom(publicKey.serialize()))
|
||||
.build()));
|
||||
|
||||
if (matchesCurrentZkCredentialKey) {
|
||||
@@ -736,13 +740,13 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
|
||||
final int updateMethodCalls = matchesCurrentZkCredentialKey ? 0 : 1;
|
||||
|
||||
verify(accountsManager, times(updateMethodCalls)).update(eq(AUTHENTICATED_ACI), any());
|
||||
verify(account, times(updateMethodCalls)).setZkCredentialKey(aryEq(publicKey));
|
||||
verify(account, times(updateMethodCalls)).setZkCredentialKey(publicKey);
|
||||
}
|
||||
|
||||
@Test
|
||||
void setZkCredentialKeyRateLimited() throws Exception {
|
||||
|
||||
final byte[] publicKey = TestRandomUtil.nextBytes(33);
|
||||
final byte[] publicKey = ZkCredentialKeyPair.generate().getPublicKey().serialize();
|
||||
final Duration retryDuration = Duration.ofDays(1);
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
|
||||
@@ -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
|
||||
""");
|
||||
}
|
||||
}
|
||||
+26
-24
@@ -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());
|
||||
|
||||
|
||||
+220
@@ -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"));
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
+218
-9
@@ -13,6 +13,8 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.AdditionalMatchers.aryEq;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyBoolean;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
@@ -20,12 +22,15 @@ import static org.mockito.Mockito.spy;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.whispersystems.textsecuregcm.grpc.GrpcTestUtils.assertRateLimitExceeded;
|
||||
import static org.whispersystems.textsecuregcm.grpc.GrpcTestUtils.assertStatusException;
|
||||
import static org.whispersystems.textsecuregcm.grpc.GrpcTestUtils.assertStatusInvalidArgument;
|
||||
|
||||
import com.google.common.net.InetAddresses;
|
||||
import com.google.protobuf.ByteString;
|
||||
import io.grpc.ServerInterceptor;
|
||||
import com.google.rpc.BadRequest;
|
||||
import io.grpc.Status;
|
||||
import io.grpc.StatusRuntimeException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
@@ -38,6 +43,7 @@ import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import java.util.stream.Stream;
|
||||
import javax.annotation.Nullable;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -50,6 +56,12 @@ import org.signal.chat.common.IdentityType;
|
||||
import org.signal.chat.common.ServiceIdentifier;
|
||||
import org.signal.chat.profile.CredentialType;
|
||||
import org.signal.chat.profile.DataEtag;
|
||||
import org.signal.chat.profile.DeleteAvatarRequest;
|
||||
import org.signal.chat.profile.DeleteAvatarResponse;
|
||||
import org.signal.chat.profile.ExtendAvatarTTLRequest;
|
||||
import org.signal.chat.profile.ExtendAvatarTTLResponse;
|
||||
import org.signal.chat.profile.GetAvatarUploadFormRequest;
|
||||
import org.signal.chat.profile.GetAvatarUploadFormResponse;
|
||||
import org.signal.chat.profile.GetExpiringProfileKeyCredentialAnonymousRequest;
|
||||
import org.signal.chat.profile.GetExpiringProfileKeyCredentialAnonymousResponse;
|
||||
import org.signal.chat.profile.GetExpiringProfileKeyCredentialRequest;
|
||||
@@ -66,8 +78,13 @@ import org.signal.chat.profile.ProfileAnonymousGrpc;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.signal.libsignal.protocol.ServiceId;
|
||||
import org.signal.libsignal.protocol.ecc.ECKeyPair;
|
||||
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
|
||||
import org.signal.libsignal.zkgroup.ServerSecretParams;
|
||||
import org.signal.libsignal.zkgroup.VerificationFailedException;
|
||||
import org.signal.libsignal.zkgroup.ZkCredentialKeyPair;
|
||||
import org.signal.libsignal.zkgroup.avatars.AvatarUploadCredentialPresentation;
|
||||
import org.signal.libsignal.zkgroup.avatars.AvatarUploadCredentialRequestContext;
|
||||
import org.signal.libsignal.zkgroup.avatars.AvatarUploadCredentialResponse;
|
||||
import org.signal.libsignal.zkgroup.profiles.ClientZkProfileOperations;
|
||||
import org.signal.libsignal.zkgroup.profiles.ExpiringProfileKeyCredentialResponse;
|
||||
import org.signal.libsignal.zkgroup.profiles.ProfileKey;
|
||||
@@ -78,9 +95,13 @@ import org.signal.libsignal.zkgroup.profiles.ServerZkProfileOperations;
|
||||
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessChecksum;
|
||||
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
|
||||
import org.whispersystems.textsecuregcm.badges.ProfileBadgeConverter;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.entities.Badge;
|
||||
import org.whispersystems.textsecuregcm.entities.BadgeSvg;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
|
||||
@@ -89,6 +110,8 @@ import org.whispersystems.textsecuregcm.storage.VersionedProfile;
|
||||
import org.whispersystems.textsecuregcm.storage.VersionedProfileV1;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
|
||||
import org.whispersystems.textsecuregcm.tests.util.ProfileTestHelper;
|
||||
import org.whispersystems.textsecuregcm.util.MutableClock;
|
||||
import org.whispersystems.textsecuregcm.util.ProfileHelper;
|
||||
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
|
||||
@@ -108,8 +131,15 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
|
||||
@Mock
|
||||
private ProfileBadgeConverter profileBadgeConverter;
|
||||
|
||||
@Mock
|
||||
private RateLimiter profileAvatarBytesRateLimiter;
|
||||
|
||||
private ServerZkProfileOperations zkProfileOperations;
|
||||
|
||||
private final GenericServerSecretParams genericServerSecretParams = GenericServerSecretParams.generate();
|
||||
|
||||
private MutableClock clock;
|
||||
|
||||
@Override
|
||||
protected ProfileAnonymousGrpcService createServiceBeforeEachTest() {
|
||||
getMockRequestAttributesInterceptor().setRequestAttributes(new RequestAttributes(InetAddresses.forString("127.0.0.1"),
|
||||
@@ -118,12 +148,21 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
|
||||
|
||||
zkProfileOperations = spy(new ServerZkProfileOperations(SERVER_SECRET_PARAMS));
|
||||
|
||||
final RateLimiters rateLimiters = mock(RateLimiters.class);
|
||||
when(rateLimiters.getProfileAvatarBytesLimiter()).thenReturn(profileAvatarBytesRateLimiter);
|
||||
|
||||
clock = new MutableClock();
|
||||
|
||||
return new ProfileAnonymousGrpcService(
|
||||
accountsManager,
|
||||
profilesManager,
|
||||
profileBadgeConverter,
|
||||
new PostPolicyGenerator("us-west-1", "profile-bucket", "accessKey", "accessSecret"),
|
||||
genericServerSecretParams,
|
||||
rateLimiters,
|
||||
clock,
|
||||
zkProfileOperations,
|
||||
new GroupSendTokenUtil(SERVER_SECRET_PARAMS, Clock.systemUTC())
|
||||
new GroupSendTokenUtil(SERVER_SECRET_PARAMS, clock)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -788,12 +827,182 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected List<ServerInterceptor> customizeInterceptors(List<ServerInterceptor> serverInterceptors) {
|
||||
return serverInterceptors.stream()
|
||||
// For now, don't validate error conformance because the profiles gRPC service has not been converted to the
|
||||
// updated error model
|
||||
.filter(interceptor -> !(interceptor instanceof ErrorConformanceInterceptor))
|
||||
.toList();
|
||||
@Test
|
||||
void getAvatarUploadForm() throws Exception {
|
||||
final AvatarUploadCredentialPresentation avatarUploadCredentialPresentation = getAvatarUploadCredentialPresentation(
|
||||
genericServerSecretParams, clock);
|
||||
|
||||
final GetAvatarUploadFormRequest request = GetAvatarUploadFormRequest.newBuilder()
|
||||
.setAvatarCredentialsPresentation(ByteString.copyFrom(avatarUploadCredentialPresentation.serialize()))
|
||||
.setUploadLength(100)
|
||||
.build();
|
||||
|
||||
final GetAvatarUploadFormResponse response = authenticatedServiceStub().getAvatarUploadForm(request);
|
||||
|
||||
assertTrue(response.hasAvatarUploadForm());
|
||||
|
||||
final String avatarPath = response.getAvatarUploadForm().getKey();
|
||||
assertFalse(avatarPath.isEmpty());
|
||||
|
||||
verify(profilesManager).setAvatarForIdentity(aryEq(avatarUploadCredentialPresentation.getCommitment()), eq(avatarPath));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAvatarUploadFormInvalidUploadLength() throws Exception {
|
||||
final AvatarUploadCredentialPresentation avatarUploadCredentialPresentation = getAvatarUploadCredentialPresentation(
|
||||
genericServerSecretParams, clock);
|
||||
|
||||
final GetAvatarUploadFormRequest request = GetAvatarUploadFormRequest.newBuilder()
|
||||
.setAvatarCredentialsPresentation(ByteString.copyFrom(avatarUploadCredentialPresentation.serialize()))
|
||||
.setUploadLength(Math.toIntExact(ProfileHelper.MAX_PROFILE_AVATAR_SIZE_BYTES + 1))
|
||||
.build();
|
||||
|
||||
final StatusRuntimeException statusRuntimeException = assertStatusInvalidArgument(
|
||||
() -> authenticatedServiceStub().getAvatarUploadForm(request));
|
||||
|
||||
final List<BadRequest.FieldViolation> fieldViolations = GrpcTestUtils.extractDetail(BadRequest.class, statusRuntimeException)
|
||||
.getFieldViolationsList();
|
||||
|
||||
assertEquals(1, fieldViolations.size());
|
||||
assertEquals("upload_length", fieldViolations.getFirst().getField());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAvatarUploadFormInvalidCredentialsPresentation() throws Exception {
|
||||
final AvatarUploadCredentialPresentation avatarUploadCredentialPresentation = getAvatarUploadCredentialPresentation(
|
||||
genericServerSecretParams, clock);
|
||||
|
||||
final GetAvatarUploadFormRequest request = GetAvatarUploadFormRequest.newBuilder()
|
||||
.setAvatarCredentialsPresentation(ByteString.copyFrom(avatarUploadCredentialPresentation.serialize()))
|
||||
.setUploadLength(100)
|
||||
.build();
|
||||
|
||||
// trigger a verification failure by advancing the clock beyond validity
|
||||
clock.setTimeInstant(clock.instant().plus(Duration.ofDays(3)));
|
||||
|
||||
final GetAvatarUploadFormResponse response = authenticatedServiceStub().getAvatarUploadForm(request);
|
||||
|
||||
assertTrue(response.hasInvalidCredentialsPresentation());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAvatarUploadFormRateLimited() throws Exception {
|
||||
final AvatarUploadCredentialPresentation avatarUploadCredentialPresentation = getAvatarUploadCredentialPresentation(
|
||||
genericServerSecretParams, clock);
|
||||
|
||||
final Duration retryDuration = Duration.ofMinutes(20);
|
||||
doThrow(new RateLimitExceededException(retryDuration))
|
||||
.when(profileAvatarBytesRateLimiter).validate(anyString(), anyLong());
|
||||
|
||||
final GetAvatarUploadFormRequest request = GetAvatarUploadFormRequest.newBuilder()
|
||||
.setAvatarCredentialsPresentation(ByteString.copyFrom(avatarUploadCredentialPresentation.serialize()))
|
||||
.setUploadLength(100)
|
||||
.build();
|
||||
|
||||
assertRateLimitExceeded(retryDuration,
|
||||
() -> authenticatedServiceStub().getAvatarUploadForm(request),
|
||||
profilesManager);
|
||||
}
|
||||
|
||||
@Test
|
||||
void extendAvatarTtl() throws Exception {
|
||||
final String path = "somePath";
|
||||
when(profilesManager.extendAvatarTtlForIdentity(any(byte[].class))).thenReturn(Optional.of(path));
|
||||
|
||||
final AvatarUploadCredentialPresentation avatarUploadCredentialPresentation = getAvatarUploadCredentialPresentation(
|
||||
genericServerSecretParams, clock);
|
||||
|
||||
final ExtendAvatarTTLRequest request = ExtendAvatarTTLRequest.newBuilder()
|
||||
.setAvatarCredentialsPresentation(ByteString.copyFrom(avatarUploadCredentialPresentation.serialize()))
|
||||
.build();
|
||||
|
||||
final ExtendAvatarTTLResponse response = authenticatedServiceStub().extendAvatarTTL(request);
|
||||
|
||||
assertTrue(response.hasPath());
|
||||
|
||||
assertEquals(path, response.getPath());
|
||||
}
|
||||
|
||||
@Test
|
||||
void extendAvatarTtlNoActiveAvatar() throws Exception {
|
||||
when(profilesManager.extendAvatarTtlForIdentity(any(byte[].class))).thenReturn(Optional.empty());
|
||||
|
||||
final AvatarUploadCredentialPresentation avatarUploadCredentialPresentation = getAvatarUploadCredentialPresentation(
|
||||
genericServerSecretParams, clock);
|
||||
|
||||
final ExtendAvatarTTLRequest request = ExtendAvatarTTLRequest.newBuilder()
|
||||
.setAvatarCredentialsPresentation(ByteString.copyFrom(avatarUploadCredentialPresentation.serialize()))
|
||||
.build();
|
||||
|
||||
|
||||
final ExtendAvatarTTLResponse response = authenticatedServiceStub().extendAvatarTTL(request);
|
||||
|
||||
assertTrue(response.hasNotFound());
|
||||
}
|
||||
|
||||
@Test
|
||||
void extendAvatarTtlInvalidCredentialsPresentation() throws Exception {
|
||||
final AvatarUploadCredentialPresentation avatarUploadCredentialPresentation = getAvatarUploadCredentialPresentation(
|
||||
genericServerSecretParams, clock);
|
||||
|
||||
final ExtendAvatarTTLRequest request = ExtendAvatarTTLRequest.newBuilder()
|
||||
.setAvatarCredentialsPresentation(ByteString.copyFrom(avatarUploadCredentialPresentation.serialize()))
|
||||
.build();
|
||||
|
||||
// trigger a verification failure by advancing the clock beyond validity
|
||||
clock.setTimeInstant(clock.instant().plus(Duration.ofDays(3)));
|
||||
|
||||
final ExtendAvatarTTLResponse response = authenticatedServiceStub().extendAvatarTTL(request);
|
||||
|
||||
assertTrue(response.hasInvalidCredentialsPresentation());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteAvatar() throws Exception {
|
||||
final AvatarUploadCredentialPresentation avatarUploadCredentialPresentation = getAvatarUploadCredentialPresentation(
|
||||
genericServerSecretParams, clock);
|
||||
|
||||
final DeleteAvatarRequest request = DeleteAvatarRequest.newBuilder()
|
||||
.setAvatarCredentialsPresentation(ByteString.copyFrom(avatarUploadCredentialPresentation.serialize()))
|
||||
.build();
|
||||
|
||||
final DeleteAvatarResponse response = authenticatedServiceStub().deleteAvatar(request);
|
||||
|
||||
assertTrue(response.hasSuccess());
|
||||
|
||||
verify(profilesManager).deleteAvatarForIdentity(aryEq(avatarUploadCredentialPresentation.getCommitment()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteAvatarInvalidCredentialsPresentation() throws Exception {
|
||||
final AvatarUploadCredentialPresentation avatarUploadCredentialPresentation = getAvatarUploadCredentialPresentation(
|
||||
genericServerSecretParams, clock);
|
||||
|
||||
final DeleteAvatarRequest request = DeleteAvatarRequest.newBuilder()
|
||||
.setAvatarCredentialsPresentation(ByteString.copyFrom(avatarUploadCredentialPresentation.serialize()))
|
||||
.build();
|
||||
|
||||
// trigger a verification failure by advancing the clock beyond validity
|
||||
clock.setTimeInstant(clock.instant().plus(Duration.ofDays(3)));
|
||||
|
||||
final DeleteAvatarResponse response = authenticatedServiceStub().deleteAvatar(request);
|
||||
|
||||
assertTrue(response.hasInvalidCredentialsPresentation());
|
||||
}
|
||||
|
||||
static AvatarUploadCredentialPresentation getAvatarUploadCredentialPresentation(final GenericServerSecretParams serverSecretParams, final Clock clock) throws VerificationFailedException {
|
||||
final ServiceId.Aci aci = new ServiceId.Aci(UUID.randomUUID());
|
||||
final ZkCredentialKeyPair zkCredentialKeyPair = ZkCredentialKeyPair.generate();
|
||||
final long rotationId = ThreadLocalRandom.current().nextLong();
|
||||
|
||||
final AvatarUploadCredentialRequestContext context = AvatarUploadCredentialRequestContext.create(
|
||||
aci,
|
||||
zkCredentialKeyPair, rotationId);
|
||||
|
||||
final AvatarUploadCredentialResponse avatarUploadCredentialResponse = context.getRequest()
|
||||
.issueCredential(aci, zkCredentialKeyPair.getPublicKey(), rotationId, clock.instant().truncatedTo(ChronoUnit.DAYS), serverSecretParams);
|
||||
|
||||
return context.receiveResponse(avatarUploadCredentialResponse, clock.instant(),
|
||||
serverSecretParams.getPublicParams()).present(serverSecretParams.getPublicParams());
|
||||
}
|
||||
}
|
||||
+85
-10
@@ -6,6 +6,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.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
@@ -31,7 +32,6 @@ import com.google.i18n.phonenumbers.PhoneNumberUtil;
|
||||
import com.google.i18n.phonenumbers.Phonenumber;
|
||||
import com.google.protobuf.ByteString;
|
||||
import com.google.rpc.BadRequest;
|
||||
import io.grpc.ServerInterceptor;
|
||||
import io.grpc.Status;
|
||||
import io.grpc.StatusRuntimeException;
|
||||
import java.time.Clock;
|
||||
@@ -60,6 +60,8 @@ import org.mockito.Mock;
|
||||
import org.signal.chat.common.IdentityType;
|
||||
import org.signal.chat.common.ServiceIdentifier;
|
||||
import org.signal.chat.profile.DataEtag;
|
||||
import org.signal.chat.profile.GetAvatarCredentialsRequest;
|
||||
import org.signal.chat.profile.GetAvatarCredentialsResponse;
|
||||
import org.signal.chat.profile.GetUnversionedProfileRequest;
|
||||
import org.signal.chat.profile.GetUnversionedProfileResponse;
|
||||
import org.signal.chat.profile.GetUnversionedProfileResult;
|
||||
@@ -77,7 +79,12 @@ import org.signal.chat.profile.test.PlaintextProfileData;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.signal.libsignal.protocol.ServiceId;
|
||||
import org.signal.libsignal.protocol.ecc.ECKeyPair;
|
||||
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.ZkCredentialKeyPair;
|
||||
import org.signal.libsignal.zkgroup.avatars.AvatarUploadCredentialRequest;
|
||||
import org.signal.libsignal.zkgroup.avatars.AvatarUploadCredentialRequestContext;
|
||||
import org.signal.libsignal.zkgroup.avatars.AvatarUploadCredentialResponse;
|
||||
import org.signal.libsignal.zkgroup.profiles.ProfileKey;
|
||||
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessChecksum;
|
||||
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
|
||||
@@ -106,6 +113,7 @@ import org.whispersystems.textsecuregcm.storage.WriteConflictException;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
|
||||
import org.whispersystems.textsecuregcm.tests.util.ProfileTestHelper;
|
||||
import org.whispersystems.textsecuregcm.util.MockUtils;
|
||||
import org.whispersystems.textsecuregcm.util.MutableClock;
|
||||
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
|
||||
@@ -122,6 +130,8 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
|
||||
.setPhoneNumberSharing(ByteString.copyFrom(TestRandomUtil.nextBytes(29)))
|
||||
.build();
|
||||
|
||||
private final GenericServerSecretParams genericServerSecretParams = GenericServerSecretParams.generate();
|
||||
|
||||
@Mock
|
||||
private AccountsManager accountsManager;
|
||||
|
||||
@@ -143,11 +153,11 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
|
||||
@Mock
|
||||
private ProfileBadgeConverter profileBadgeConverter;
|
||||
|
||||
private Clock clock;
|
||||
private MutableClock clock;
|
||||
|
||||
@Override
|
||||
protected ProfileGrpcService createServiceBeforeEachTest() {
|
||||
clock = Clock.fixed(Instant.ofEpochSecond(42), ZoneId.of("Etc/UTC"));
|
||||
clock = new MutableClock(Clock.fixed(Instant.ofEpochSecond(42), ZoneId.of("Etc/UTC")));
|
||||
|
||||
@SuppressWarnings("unchecked") final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager = mock(DynamicConfigurationManager.class);
|
||||
final DynamicConfiguration dynamicConfiguration = mock(DynamicConfiguration.class);
|
||||
@@ -208,6 +218,7 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
|
||||
dynamicConfigurationManager,
|
||||
badgesConfiguration,
|
||||
policyGenerator,
|
||||
genericServerSecretParams,
|
||||
profileBadgeConverter,
|
||||
rateLimiters
|
||||
);
|
||||
@@ -893,13 +904,77 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
|
||||
assertStatusException(Status.INVALID_ARGUMENT, () -> authenticatedServiceStub().getVersionedProfile(request));
|
||||
}
|
||||
|
||||
@Override
|
||||
protected List<ServerInterceptor> customizeInterceptors(List<ServerInterceptor> serverInterceptors) {
|
||||
return serverInterceptors.stream()
|
||||
// For now, don't validate error conformance because the profiles gRPC service has not been converted to the
|
||||
// updated error model
|
||||
.filter(interceptor -> !(interceptor instanceof ErrorConformanceInterceptor))
|
||||
.toList();
|
||||
@Test
|
||||
void getAvatarCredential() {
|
||||
final ZkCredentialKeyPair zkCredentialKeyPair = ZkCredentialKeyPair.generate();
|
||||
final long rotationId = 617L;
|
||||
|
||||
// this test needs a valid clock
|
||||
clock.setTimeMillis(Instant.now().toEpochMilli());
|
||||
|
||||
when(account.getZkCredentialKey()).thenReturn(Optional.of(zkCredentialKeyPair.getPublicKey()));
|
||||
when(account.getZkCredentialKeyRotationId()).thenReturn(rotationId);
|
||||
|
||||
final AvatarUploadCredentialRequestContext avatarUploadCredentialRequestContext = AvatarUploadCredentialRequestContext.create(
|
||||
new ServiceId.Aci(AUTHENTICATED_ACI), zkCredentialKeyPair, rotationId);
|
||||
final AvatarUploadCredentialRequest credentialRequest = avatarUploadCredentialRequestContext.getRequest();
|
||||
|
||||
final GetAvatarCredentialsResponse response = authenticatedServiceStub().getAvatarCredentials(
|
||||
GetAvatarCredentialsRequest.newBuilder()
|
||||
.setAvatarCredentialsRequest(ByteString.copyFrom(credentialRequest.serialize()))
|
||||
.build());
|
||||
|
||||
assertTrue(response.hasAvatarCredentials());
|
||||
|
||||
assertDoesNotThrow(() -> avatarUploadCredentialRequestContext.receiveResponse(
|
||||
new AvatarUploadCredentialResponse(response.getAvatarCredentials().toByteArray()),
|
||||
genericServerSecretParams.getPublicParams()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAvatarCredentialAccountNotFound() {
|
||||
when(accountsManager.getByAccountIdentifier(AUTHENTICATED_ACI)).thenReturn(Optional.empty());
|
||||
|
||||
final StatusRuntimeException statusRuntimeException = assertStatusException(Status.UNAUTHENTICATED,
|
||||
() -> authenticatedServiceStub().getAvatarCredentials(GetAvatarCredentialsRequest.getDefaultInstance()));
|
||||
assertEquals("account not found", statusRuntimeException.getStatus().getDescription());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAvatarCredentialMissingZkCredentialKey() {
|
||||
when(account.getZkCredentialKey()).thenReturn(Optional.empty());
|
||||
|
||||
final GetAvatarCredentialsResponse response = authenticatedServiceStub().getAvatarCredentials(
|
||||
GetAvatarCredentialsRequest.getDefaultInstance());
|
||||
|
||||
assertTrue(response.hasMissingZkCredentialKey());
|
||||
|
||||
assertEquals("account requires ZK credential key", response.getMissingZkCredentialKey().getDescription());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAvatarCredentialInvalidCredentialRequest() {
|
||||
final ZkCredentialKeyPair zkCredentialKeyPair = ZkCredentialKeyPair.generate();
|
||||
final long rotationId = 617L;
|
||||
final long incorrectRotationId = rotationId + 1;
|
||||
|
||||
// this test needs a valid clock
|
||||
clock.setTimeMillis(Instant.now().toEpochMilli());
|
||||
|
||||
when(account.getZkCredentialKey()).thenReturn(Optional.of(zkCredentialKeyPair.getPublicKey()));
|
||||
when(account.getZkCredentialKeyRotationId()).thenReturn(rotationId);
|
||||
|
||||
final AvatarUploadCredentialRequestContext avatarUploadCredentialRequestContext = AvatarUploadCredentialRequestContext.create(
|
||||
new ServiceId.Aci(AUTHENTICATED_ACI), zkCredentialKeyPair, incorrectRotationId);
|
||||
final AvatarUploadCredentialRequest credentialRequest = avatarUploadCredentialRequestContext.getRequest();
|
||||
|
||||
final StatusRuntimeException statusRuntimeException = assertStatusInvalidArgument(
|
||||
() -> authenticatedServiceStub().getAvatarCredentials(
|
||||
GetAvatarCredentialsRequest.newBuilder()
|
||||
.setAvatarCredentialsRequest(ByteString.copyFrom(credentialRequest.serialize()))
|
||||
.build()));
|
||||
|
||||
assertEquals("invalid credential request", statusRuntimeException.getStatus().getDescription());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
|
||||
+33
-144
@@ -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());
|
||||
}
|
||||
|
||||
@@ -23,6 +23,7 @@ import static org.mockito.Mockito.when;
|
||||
import static org.whispersystems.textsecuregcm.util.CompletableFutureTestUtil.assertFailsWithCause;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.google.i18n.phonenumbers.PhoneNumberUtil;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
@@ -49,7 +50,6 @@ import java.util.function.Consumer;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.stream.Stream;
|
||||
import com.google.i18n.phonenumbers.PhoneNumberUtil;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.Timeout;
|
||||
@@ -59,6 +59,7 @@ 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.signal.libsignal.zkgroup.ZkCredentialKeyPair;
|
||||
import org.signal.libsignal.zkgroup.backups.BackupCredentialType;
|
||||
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
@@ -471,7 +472,7 @@ class AccountsTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testReclaimAccountPreservesFields() {
|
||||
void testReclaimAccountPreservesFields() throws Exception {
|
||||
final String e164 = "+14151112222";
|
||||
final UUID existingUuid = UUID.randomUUID();
|
||||
final Account existingAccount =
|
||||
@@ -479,7 +480,7 @@ class AccountsTest {
|
||||
|
||||
// the backup credential request and share-set are always preserved across account reclaims
|
||||
existingAccount.setBackupCredentialRequests(TestRandomUtil.nextBytes(32), TestRandomUtil.nextBytes(32));
|
||||
existingAccount.setZkCredentialKey(TestRandomUtil.nextBytes(32));
|
||||
existingAccount.setZkCredentialKey(ZkCredentialKeyPair.generate().getPublicKey());
|
||||
createAccount(existingAccount);
|
||||
final Account secondAccount =
|
||||
generateAccount(e164, UUID.randomUUID(), UUID.randomUUID(), List.of(generateDevice(DEVICE_ID_1)));
|
||||
@@ -491,11 +492,11 @@ class AccountsTest {
|
||||
.isEqualTo(existingAccount.getBackupCredentialRequest(BackupCredentialType.MESSAGES).orElseThrow());
|
||||
assertThat(reclaimed.getBackupCredentialRequest(BackupCredentialType.MEDIA).orElseThrow())
|
||||
.isEqualTo(existingAccount.getBackupCredentialRequest(BackupCredentialType.MEDIA).orElseThrow());
|
||||
assertThat(reclaimed.getZkCredentialKey()).isEqualTo(existingAccount.getZkCredentialKey());
|
||||
assertThat(reclaimed.getZkCredentialKey()).hasValue(existingAccount.getZkCredentialKey().orElseThrow());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testReclaimAccount() throws UsernameHashNotAvailableException {
|
||||
void testReclaimAccount() throws Exception {
|
||||
final String e164 = "+14151112222";
|
||||
final Device device = generateDevice(DEVICE_ID_1);
|
||||
final UUID existingUuid = UUID.randomUUID();
|
||||
@@ -506,7 +507,7 @@ class AccountsTest {
|
||||
final Account.BackupVoucher bv = new Account.BackupVoucher(1, Instant.now().plus(Duration.ofDays(1)));
|
||||
existingAccount.setBackupVoucher(bv);
|
||||
// ZK credential keys should be carried over across re-registration
|
||||
existingAccount.setZkCredentialKey(TestRandomUtil.nextBytes(32));
|
||||
existingAccount.setZkCredentialKey(ZkCredentialKeyPair.generate().getPublicKey());
|
||||
|
||||
createAccount(existingAccount);
|
||||
|
||||
|
||||
+146
@@ -0,0 +1,146 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
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.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.EnumSource;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStream;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import reactor.adapter.JdkFlowAdapter;
|
||||
import reactor.core.publisher.Flux;
|
||||
|
||||
class AcknowledgementMirroringMessageStreamTest {
|
||||
|
||||
private RedisDynamoDbMessageStream redisDynamoDbMessageStream;
|
||||
private FoundationDbMessageStream foundationDbMessageStream;
|
||||
|
||||
private AcknowledgementMirroringMessageStream mirroringMessageStream;
|
||||
|
||||
private static long serialMessageTimestamp = 0;
|
||||
|
||||
private enum UUIDVersion {
|
||||
V4,
|
||||
V8
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
redisDynamoDbMessageStream = mock(RedisDynamoDbMessageStream.class);
|
||||
|
||||
when(redisDynamoDbMessageStream.acknowledgeMessage(any(), anyLong()))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
foundationDbMessageStream = mock(FoundationDbMessageStream.class);
|
||||
|
||||
when(foundationDbMessageStream.acknowledgeMessage(any(), anyLong()))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
mirroringMessageStream = new AcknowledgementMirroringMessageStream(
|
||||
redisDynamoDbMessageStream,
|
||||
foundationDbMessageStream);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@EnumSource(UUIDVersion.class)
|
||||
void acknowledgeMessages(final UUIDVersion uuidVersion) {
|
||||
final List<MessageStreamEntry> entries = new ArrayList<>();
|
||||
{
|
||||
for (int i = 0; i < 256; i++) {
|
||||
entries.add(generateEnvelopeEntry(uuidVersion));
|
||||
}
|
||||
|
||||
entries.add(new MessageStreamEntry.QueueEmpty());
|
||||
}
|
||||
|
||||
when(redisDynamoDbMessageStream.getMessages())
|
||||
.thenReturn(JdkFlowAdapter.publisherToFlowPublisher(Flux.fromIterable(entries)));
|
||||
|
||||
when(foundationDbMessageStream.getMessages())
|
||||
.thenReturn(JdkFlowAdapter.publisherToFlowPublisher(Flux.fromIterable(
|
||||
uuidVersion == UUIDVersion.V8 ? entries : Collections.emptyList())));
|
||||
|
||||
JdkFlowAdapter.flowPublisherToFlux(mirroringMessageStream.getMessages())
|
||||
.doOnNext(entry -> {
|
||||
if (entry instanceof MessageStreamEntry.Envelope(MessageProtos.Envelope message)) {
|
||||
mirroringMessageStream.acknowledgeMessage(UUIDUtil.fromByteString(message.getServerGuid()),
|
||||
message.getServerTimestamp());
|
||||
}
|
||||
})
|
||||
.takeUntil(entry -> entry instanceof MessageStreamEntry.QueueEmpty)
|
||||
.then()
|
||||
.block();
|
||||
|
||||
if (uuidVersion == UUIDVersion.V8) {
|
||||
entries.stream()
|
||||
.filter(streamEntry -> streamEntry instanceof MessageStreamEntry.Envelope)
|
||||
.map(streamEntry -> ((MessageStreamEntry.Envelope) streamEntry).message())
|
||||
.forEach(envelope -> verify(foundationDbMessageStream).acknowledgeMessage(
|
||||
UUIDUtil.fromByteString(envelope.getServerGuid()), envelope.getServerTimestamp()));
|
||||
} else {
|
||||
verify(foundationDbMessageStream, never()).acknowledgeMessage(any(), anyLong());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void acknowledgeMessagesOverflow() {
|
||||
final List<MessageStreamEntry> entries = new ArrayList<>();
|
||||
{
|
||||
for (int i = 0; i < AcknowledgementMirroringMessageStream.MAX_PENDING_ACKNOWLEDGEMENTS + 1; i++) {
|
||||
entries.add(generateEnvelopeEntry(UUIDVersion.V8));
|
||||
}
|
||||
|
||||
entries.add(new MessageStreamEntry.QueueEmpty());
|
||||
}
|
||||
|
||||
when(redisDynamoDbMessageStream.getMessages())
|
||||
.thenReturn(JdkFlowAdapter.publisherToFlowPublisher(Flux.fromIterable(entries)));
|
||||
|
||||
when(foundationDbMessageStream.getMessages())
|
||||
.thenReturn(JdkFlowAdapter.publisherToFlowPublisher(Flux.empty()));
|
||||
|
||||
assertThrows(IllegalStateException.class,
|
||||
() -> JdkFlowAdapter.flowPublisherToFlux(mirroringMessageStream.getMessages())
|
||||
.doOnNext(entry -> {
|
||||
if (entry instanceof MessageStreamEntry.Envelope(MessageProtos.Envelope message)) {
|
||||
mirroringMessageStream.acknowledgeMessage(UUIDUtil.fromByteString(message.getServerGuid()),
|
||||
message.getServerTimestamp());
|
||||
}
|
||||
})
|
||||
.takeUntil(entry -> entry instanceof MessageStreamEntry.QueueEmpty)
|
||||
.then()
|
||||
.block());
|
||||
|
||||
verify(foundationDbMessageStream, never()).acknowledgeMessage(any(), anyLong());
|
||||
}
|
||||
|
||||
private static MessageStreamEntry.Envelope generateEnvelopeEntry(final UUIDVersion uuidVersion) {
|
||||
final UUID messageGuid = switch (uuidVersion) {
|
||||
case V4 -> UUID.randomUUID();
|
||||
case V8 -> MessageGuidUtil.generateRandomV8UUID();
|
||||
};
|
||||
|
||||
return new MessageStreamEntry.Envelope(MessageProtos.Envelope.newBuilder()
|
||||
.setServerGuid(UUIDUtil.toByteString(messageGuid))
|
||||
.setServerTimestamp(serialMessageTimestamp++)
|
||||
.build());
|
||||
}
|
||||
}
|
||||
-68
@@ -1,68 +0,0 @@
|
||||
/*
|
||||
* 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.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.times;
|
||||
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.FoundationDbMessageStore;
|
||||
|
||||
class DeletionMirroringRedisDynamoDbMessageStreamTest {
|
||||
|
||||
private FoundationDbMessageStore foundationDbMessageStore;
|
||||
private ExperimentEnrollmentManager experimentEnrollmentManager;
|
||||
|
||||
private DeletionMirroringRedisDynamoDbMessageStream deletionMirroringRedisDynamoDbMessageStream;
|
||||
|
||||
private static final AciServiceIdentifier ACCOUNT_IDENTIFIER = new AciServiceIdentifier(UUID.randomUUID());
|
||||
private static final byte DEVICE_ID = Device.PRIMARY_ID;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
foundationDbMessageStore = mock(FoundationDbMessageStore.class);
|
||||
experimentEnrollmentManager = mock(ExperimentEnrollmentManager.class);
|
||||
|
||||
deletionMirroringRedisDynamoDbMessageStream = new DeletionMirroringRedisDynamoDbMessageStream(
|
||||
mock(RedisDynamoDbMessageStream.class),
|
||||
foundationDbMessageStore,
|
||||
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);
|
||||
|
||||
deletionMirroringRedisDynamoDbMessageStream.acknowledgeMessage(messageGuid, System.currentTimeMillis());
|
||||
|
||||
verify(foundationDbMessageStore, times(expectFoundationDbDeletion ? 1 : 0))
|
||||
.delete(ACCOUNT_IDENTIFIER, DEVICE_ID, messageGuid);
|
||||
}
|
||||
|
||||
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)
|
||||
);
|
||||
}
|
||||
}
|
||||
+9
@@ -275,6 +275,15 @@ public final class DynamoDbExtensionSchema {
|
||||
.build()),
|
||||
List.of(), List.of()),
|
||||
|
||||
PROFILE_AVATARS("profileAvatars_test",
|
||||
ProfileAvatars.KEY_IDENTITY,
|
||||
null,
|
||||
List.of(AttributeDefinition.builder()
|
||||
.attributeName(ProfileAvatars.KEY_IDENTITY)
|
||||
.attributeType(ScalarAttributeType.B)
|
||||
.build()),
|
||||
List.of(), List.of()),
|
||||
|
||||
PROFILES_V2("profilesV2_test",
|
||||
ProfilesV2.KEY_ACCOUNT_UUID,
|
||||
ProfilesV2.KEY_VERSION,
|
||||
|
||||
+156
@@ -0,0 +1,156 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.whispersystems.textsecuregcm.util.AttributeValues;
|
||||
import org.whispersystems.textsecuregcm.util.TestClock;
|
||||
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
|
||||
import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.GetItemResponse;
|
||||
|
||||
class ProfileAvatarsTest {
|
||||
|
||||
@RegisterExtension
|
||||
static final DynamoDbExtension DYNAMO_DB_EXTENSION = new DynamoDbExtension(DynamoDbExtensionSchema.Tables.PROFILE_AVATARS);
|
||||
|
||||
private ProfileAvatars profileAvatars;
|
||||
|
||||
private static final Duration EXPIRATION = Duration.ofDays(1);
|
||||
private static final TestClock CLOCK = TestClock.pinned(Instant.now().truncatedTo(ChronoUnit.SECONDS));
|
||||
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
profileAvatars = new ProfileAvatars(DYNAMO_DB_EXTENSION.getDynamoDbClient(),
|
||||
DynamoDbExtensionSchema.Tables.PROFILE_AVATARS.tableName(), EXPIRATION, CLOCK);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSet() {
|
||||
final byte[] identity = TestRandomUtil.nextBytes(32);
|
||||
final String avatarUrl1 = "avatar";
|
||||
|
||||
{
|
||||
final Optional<String> previousAvatar = profileAvatars.setAvatarUrl(identity, avatarUrl1);
|
||||
assertTrue(previousAvatar.isEmpty());
|
||||
}
|
||||
|
||||
{
|
||||
final GetItemResponse response = DYNAMO_DB_EXTENSION.getDynamoDbClient()
|
||||
.getItem(GetItemRequest.builder()
|
||||
.tableName(DynamoDbExtensionSchema.Tables.PROFILE_AVATARS.tableName())
|
||||
.key(Map.of(ProfileAvatars.KEY_IDENTITY, AttributeValues.fromByteArray(identity)))
|
||||
.build());
|
||||
|
||||
assertTrue(response.hasItem());
|
||||
assertArrayEquals(identity, response.item().get(ProfileAvatars.KEY_IDENTITY).b().asByteArray());
|
||||
assertEquals(avatarUrl1, response.item().get(ProfileAvatars.ATTR_URL).s());
|
||||
assertEquals(CLOCK.instant().plus(EXPIRATION),
|
||||
Instant.ofEpochSecond(Long.parseLong(response.item().get(ProfileAvatars.ATTR_TTL).n())));
|
||||
}
|
||||
|
||||
final String avatarUrl2 = "avatar2";
|
||||
|
||||
{
|
||||
final Optional<String> previousAvatar = profileAvatars.setAvatarUrl(identity, avatarUrl2);
|
||||
assertEquals(Optional.of(avatarUrl1), previousAvatar);
|
||||
}
|
||||
|
||||
{
|
||||
final GetItemResponse response = DYNAMO_DB_EXTENSION.getDynamoDbClient()
|
||||
.getItem(GetItemRequest.builder()
|
||||
.tableName(DynamoDbExtensionSchema.Tables.PROFILE_AVATARS.tableName())
|
||||
.key(Map.of(ProfileAvatars.KEY_IDENTITY, AttributeValues.fromByteArray(identity)))
|
||||
.build());
|
||||
|
||||
assertTrue(response.hasItem());
|
||||
assertArrayEquals(identity, response.item().get(ProfileAvatars.KEY_IDENTITY).b().asByteArray());
|
||||
assertEquals(avatarUrl2, response.item().get(ProfileAvatars.ATTR_URL).s());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testUpdateTtl() {
|
||||
final byte[] identity = TestRandomUtil.nextBytes(32);
|
||||
final String avatarUrl = "avatar";
|
||||
|
||||
profileAvatars.setAvatarUrl(identity, avatarUrl);
|
||||
|
||||
{
|
||||
final GetItemResponse response = DYNAMO_DB_EXTENSION.getDynamoDbClient()
|
||||
.getItem(GetItemRequest.builder()
|
||||
.tableName(DynamoDbExtensionSchema.Tables.PROFILE_AVATARS.tableName())
|
||||
.key(Map.of(ProfileAvatars.KEY_IDENTITY, AttributeValues.fromByteArray(identity)))
|
||||
.build());
|
||||
|
||||
assertTrue(response.hasItem());
|
||||
assertArrayEquals(identity, response.item().get(ProfileAvatars.KEY_IDENTITY).b().asByteArray());
|
||||
assertEquals(CLOCK.instant().plus(EXPIRATION),
|
||||
Instant.ofEpochSecond(Long.parseLong(response.item().get(ProfileAvatars.ATTR_TTL).n())));
|
||||
}
|
||||
final Instant later = CLOCK.instant().plus(Duration.ofDays(30));
|
||||
CLOCK.pin(later);
|
||||
|
||||
profileAvatars.updateAvatarTtl(identity);
|
||||
{
|
||||
final GetItemResponse response = DYNAMO_DB_EXTENSION.getDynamoDbClient()
|
||||
.getItem(GetItemRequest.builder()
|
||||
.tableName(DynamoDbExtensionSchema.Tables.PROFILE_AVATARS.tableName())
|
||||
.key(Map.of(ProfileAvatars.KEY_IDENTITY, AttributeValues.fromByteArray(identity)))
|
||||
.build());
|
||||
|
||||
assertTrue(response.hasItem());
|
||||
assertArrayEquals(identity, response.item().get(ProfileAvatars.KEY_IDENTITY).b().asByteArray());
|
||||
assertEquals(later.plus(EXPIRATION),
|
||||
Instant.ofEpochSecond(Long.parseLong(response.item().get(ProfileAvatars.ATTR_TTL).n())));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testUpdateTtlNotPresent() {
|
||||
final byte[] identity = TestRandomUtil.nextBytes(32);
|
||||
|
||||
assertTrue(profileAvatars.updateAvatarTtl(identity).isEmpty());
|
||||
|
||||
final GetItemResponse response = DYNAMO_DB_EXTENSION.getDynamoDbClient()
|
||||
.getItem(GetItemRequest.builder()
|
||||
.tableName(DynamoDbExtensionSchema.Tables.PROFILE_AVATARS.tableName())
|
||||
.key(Map.of(ProfileAvatars.KEY_IDENTITY, AttributeValues.fromByteArray(identity)))
|
||||
.build());
|
||||
|
||||
assertFalse(response.hasItem(), "item should not be created as a side effect");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDelete() {
|
||||
final byte[] identity = TestRandomUtil.nextBytes(32);
|
||||
|
||||
assertTrue(profileAvatars.deleteAvatarUrl(identity).isEmpty());
|
||||
|
||||
final String avatarUrl = "avatar";
|
||||
|
||||
profileAvatars.setAvatarUrl(identity, avatarUrl);
|
||||
|
||||
final Optional<String> deletedUrl = profileAvatars.deleteAvatarUrl(identity);
|
||||
assertTrue(deletedUrl.isPresent());
|
||||
assertEquals(avatarUrl, deletedUrl.get());
|
||||
|
||||
assertTrue(profileAvatars.deleteAvatarUrl(identity).isEmpty());
|
||||
}
|
||||
|
||||
}
|
||||
+109
-2
@@ -11,10 +11,12 @@ import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.AdditionalMatchers.aryEq;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.argThat;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
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.verifyNoInteractions;
|
||||
@@ -42,6 +44,7 @@ import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.signal.libsignal.protocol.ServiceId;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.profiles.ProfileKey;
|
||||
@@ -56,13 +59,18 @@ import org.whispersystems.textsecuregcm.util.TestRandomUtil;
|
||||
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
|
||||
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem;
|
||||
import software.amazon.awssdk.services.s3.S3AsyncClient;
|
||||
import software.amazon.awssdk.services.s3.model.CopyObjectRequest;
|
||||
import software.amazon.awssdk.services.s3.model.CopyObjectResponse;
|
||||
import software.amazon.awssdk.services.s3.model.DeleteObjectRequest;
|
||||
import software.amazon.awssdk.services.s3.model.NoSuchKeyException;
|
||||
import software.amazon.awssdk.services.s3.model.S3Exception;
|
||||
|
||||
@Timeout(value = 10, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
|
||||
public class ProfilesManagerTest {
|
||||
|
||||
private Profiles profilesV1;
|
||||
private ProfilesV2 profilesV2;
|
||||
private ProfileAvatars profileAvatars;
|
||||
private RedisAdvancedClusterCommands<byte[], byte[]> commands;
|
||||
private RedisAdvancedClusterAsyncCommands<byte[], byte[]> asyncCommands;
|
||||
private S3AsyncClient s3Client;
|
||||
@@ -85,10 +93,11 @@ public class ProfilesManagerTest {
|
||||
|
||||
profilesV1 = mock(Profiles.class);
|
||||
profilesV2 = mock(ProfilesV2.class);
|
||||
profileAvatars = mock(ProfileAvatars.class);
|
||||
s3Client = mock(S3AsyncClient.class);
|
||||
setLuaScript = mock(ClusterLuaScript.class);
|
||||
|
||||
profilesManager = new ProfilesManager(profilesV1, profilesV2, cacheCluster, mock(ScheduledExecutorService.class),
|
||||
profilesManager = new ProfilesManager(profilesV1, profilesV2, profileAvatars, cacheCluster, mock(ScheduledExecutorService.class),
|
||||
s3Client, BUCKET, setLuaScript);
|
||||
}
|
||||
|
||||
@@ -449,6 +458,104 @@ public class ProfilesManagerTest {
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void setAvatarForIdentity() {
|
||||
final byte[] identity = new byte[1];
|
||||
final String url1 = "url1";
|
||||
|
||||
when(profileAvatars.setAvatarUrl(any(byte[].class), anyString()))
|
||||
.thenReturn(Optional.empty());
|
||||
|
||||
profilesManager.setAvatarForIdentity(identity, url1);
|
||||
|
||||
verify(profileAvatars).setAvatarUrl(identity, url1);
|
||||
verifyNoInteractions(s3Client);
|
||||
|
||||
when(profileAvatars.setAvatarUrl(any(byte[].class), anyString()))
|
||||
.thenReturn(Optional.of(url1));
|
||||
|
||||
final String url2 = "url2";
|
||||
profilesManager.setAvatarForIdentity(identity, url2);
|
||||
|
||||
verify(profileAvatars).setAvatarUrl(identity, url2);
|
||||
verify(s3Client).deleteObject(argThat((DeleteObjectRequest r) -> url1.equals(r.key())));
|
||||
}
|
||||
|
||||
@Test
|
||||
void extendAvatarTtlForIdentity() {
|
||||
final String avatarPath = "somePath";
|
||||
when(profileAvatars.updateAvatarTtl(any(byte[].class))).thenReturn(Optional.of(avatarPath));
|
||||
|
||||
assertEquals(Optional.of(avatarPath), profilesManager.extendAvatarTtlForIdentity(new byte[1]));
|
||||
|
||||
final ArgumentCaptor<CopyObjectRequest> copyObjectRequestArgumentCaptor = ArgumentCaptor.forClass(CopyObjectRequest.class);
|
||||
verify(s3Client).copyObject(copyObjectRequestArgumentCaptor.capture());
|
||||
|
||||
assertEquals(avatarPath, copyObjectRequestArgumentCaptor.getValue().sourceKey());
|
||||
assertEquals(avatarPath, copyObjectRequestArgumentCaptor.getValue().destinationKey());
|
||||
}
|
||||
|
||||
@Test
|
||||
void extendAvatarTtlForIdentityNotFound() {
|
||||
when(profileAvatars.updateAvatarTtl(any(byte[].class))).thenReturn(Optional.empty());
|
||||
|
||||
assertTrue(profilesManager.extendAvatarTtlForIdentity(new byte[1]).isEmpty());
|
||||
|
||||
verifyNoInteractions(s3Client);
|
||||
}
|
||||
|
||||
@Test
|
||||
void extendAvatarTtlForIdentityS3NoSuchKey() {
|
||||
final String avatarPath = "somePath";
|
||||
when(profileAvatars.updateAvatarTtl(any(byte[].class))).thenReturn(Optional.of(avatarPath));
|
||||
|
||||
when(s3Client.copyObject(any(CopyObjectRequest.class)))
|
||||
.thenReturn(CompletableFuture.failedFuture(NoSuchKeyException.builder().build()));
|
||||
|
||||
assertTrue(profilesManager.extendAvatarTtlForIdentity(new byte[1]).isEmpty());
|
||||
|
||||
verify(s3Client).copyObject(any(CopyObjectRequest.class));
|
||||
verify(profileAvatars).deleteAvatarUrl(any(byte[].class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void extendAvatarTtlForIdentityS3Retry() {
|
||||
final String avatarPath = "somePath";
|
||||
when(profileAvatars.updateAvatarTtl(any(byte[].class))).thenReturn(Optional.of(avatarPath));
|
||||
|
||||
when(s3Client.copyObject(any(CopyObjectRequest.class)))
|
||||
.thenReturn(CompletableFuture.failedFuture(S3Exception.builder().build()))
|
||||
.thenReturn(CompletableFuture.completedFuture(mock(CopyObjectResponse.class)));
|
||||
|
||||
assertEquals(Optional.of(avatarPath), profilesManager.extendAvatarTtlForIdentity(new byte[1]));
|
||||
|
||||
verify(s3Client, times(2)).copyObject(any(CopyObjectRequest.class));
|
||||
|
||||
verify(profileAvatars, never()).deleteAvatarUrl(any(byte[].class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteAvatarForIdentity() {
|
||||
final String avatarPath = "somePath";
|
||||
when(profileAvatars.deleteAvatarUrl(any(byte[].class))).thenReturn(Optional.of(avatarPath));
|
||||
|
||||
profilesManager.deleteAvatarForIdentity(new byte[1]);
|
||||
|
||||
final ArgumentCaptor<DeleteObjectRequest> deleteObjectRequestArgumentCaptor = ArgumentCaptor.forClass(
|
||||
DeleteObjectRequest.class);
|
||||
verify(s3Client).deleteObject(deleteObjectRequestArgumentCaptor.capture());
|
||||
assertEquals(avatarPath, deleteObjectRequestArgumentCaptor.getValue().key());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteAvatarForIdentityNotFound() {
|
||||
when(profileAvatars.deleteAvatarUrl(any(byte[].class))).thenReturn(Optional.empty());
|
||||
|
||||
profilesManager.deleteAvatarForIdentity(new byte[1]);
|
||||
|
||||
verifyNoInteractions(s3Client);
|
||||
}
|
||||
|
||||
@Nested
|
||||
class Redis {
|
||||
|
||||
@@ -457,7 +564,7 @@ public class ProfilesManagerTest {
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
profilesManager = new ProfilesManager(profilesV1, profilesV2, REDIS_CLUSTER_EXTENSION.getRedisCluster(), mock(ScheduledExecutorService.class),
|
||||
profilesManager = new ProfilesManager(profilesV1, profilesV2, profileAvatars, REDIS_CLUSTER_EXTENSION.getRedisCluster(), mock(ScheduledExecutorService.class),
|
||||
s3Client, BUCKET);
|
||||
}
|
||||
|
||||
|
||||
+173
-10
@@ -2,10 +2,12 @@ package org.whispersystems.textsecuregcm.storage.foundationdb;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyBoolean;
|
||||
import static org.mockito.ArgumentMatchers.anyInt;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@@ -16,20 +18,28 @@ import com.apple.foundationdb.Range;
|
||||
import com.apple.foundationdb.StreamingMode;
|
||||
import com.apple.foundationdb.Transaction;
|
||||
import com.apple.foundationdb.async.AsyncIterable;
|
||||
import com.apple.foundationdb.tuple.Tuple;
|
||||
import com.apple.foundationdb.tuple.Versionstamp;
|
||||
import com.google.protobuf.InvalidProtocolBufferException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.security.SecureRandom;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
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 com.apple.foundationdb.tuple.Tuple;
|
||||
import com.apple.foundationdb.tuple.Versionstamp;
|
||||
import com.google.protobuf.InvalidProtocolBufferException;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.stubbing.Answer;
|
||||
@@ -46,6 +56,8 @@ class FoundationDbMessagePublisherTest {
|
||||
private Database database;
|
||||
private List<FoundationDbMessagePublisher.State> stateTransitions;
|
||||
|
||||
private static ScheduledExecutorService presenceRenewalExecutorService;
|
||||
|
||||
private static final AciServiceIdentifier SERVICE_IDENTIFIER = new AciServiceIdentifier(UUID.randomUUID());
|
||||
|
||||
private static final Range SUBSPACE_RANGE =
|
||||
@@ -56,6 +68,15 @@ class FoundationDbMessagePublisherTest {
|
||||
|
||||
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();
|
||||
|
||||
@BeforeAll
|
||||
static void setUpBeforeAll() {
|
||||
presenceRenewalExecutorService = Executors.newSingleThreadScheduledExecutor();
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
database = mock(Database.class);
|
||||
@@ -65,8 +86,15 @@ class FoundationDbMessagePublisherTest {
|
||||
new SecureRandom().nextBytes(messageGuidCodecKey);
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void tearDownAfterAll() throws InterruptedException {
|
||||
presenceRenewalExecutorService.shutdown();
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
presenceRenewalExecutorService.awaitTermination(1, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@Test
|
||||
void finitePublisherMultipleBatches() throws InvalidProtocolBufferException {
|
||||
void finitePublisherMultipleBatches() {
|
||||
final MessageProtos.Envelope message1 = FoundationDbMessageStoreTest.generateRandomMessage(false);
|
||||
final MessageProtos.Envelope message2 = FoundationDbMessageStoreTest.generateRandomMessage(false);
|
||||
final MessageProtos.Envelope message3 = FoundationDbMessageStoreTest.generateRandomMessage(false);
|
||||
@@ -95,11 +123,14 @@ class FoundationDbMessagePublisherTest {
|
||||
});
|
||||
|
||||
final FoundationDbMessagePublisher finitePublisher = new FoundationDbMessagePublisher(
|
||||
database,
|
||||
CLOCK,
|
||||
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.begin),
|
||||
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.end),
|
||||
database,
|
||||
2, // With 3 messages and batch size set to 2, we'll need to grab 2 batches.
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
(_, newState) -> stateTransitions.add(newState),
|
||||
NOOP_ON_PAGE_FETCH
|
||||
);
|
||||
@@ -166,10 +197,13 @@ class FoundationDbMessagePublisherTest {
|
||||
.thenReturn(watchFuture3);
|
||||
|
||||
final FoundationDbMessagePublisher infinitePublisher = new FoundationDbMessagePublisher(
|
||||
database,
|
||||
CLOCK,
|
||||
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.begin),
|
||||
KeySelector.firstGreaterOrEqual(new byte[]{(byte) 10}),
|
||||
database,
|
||||
2,
|
||||
FoundationDbMessageStore.getPresenceKey(SERVICE_IDENTIFIER, Device.PRIMARY_ID),
|
||||
presenceRenewalExecutorService,
|
||||
MESSAGES_AVAILABLE_WATCH_KEY,
|
||||
(oldState, newState) -> {
|
||||
stateTransitions.add(newState);
|
||||
@@ -215,7 +249,7 @@ class FoundationDbMessagePublisherTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void messageAvailableWatchSignalBuffered() throws InvalidProtocolBufferException {
|
||||
void messageAvailableWatchSignalBuffered() {
|
||||
final MessageProtos.Envelope message1 = FoundationDbMessageStoreTest.generateRandomMessage(false);
|
||||
final MessageProtos.Envelope message2 = FoundationDbMessageStoreTest.generateRandomMessage(false);
|
||||
|
||||
@@ -248,10 +282,13 @@ class FoundationDbMessagePublisherTest {
|
||||
.thenReturn(watchFuture2);
|
||||
|
||||
final FoundationDbMessagePublisher infinitePublisher = new FoundationDbMessagePublisher(
|
||||
database,
|
||||
CLOCK,
|
||||
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.begin),
|
||||
KeySelector.firstGreaterOrEqual(new byte[]{(byte) 10}),
|
||||
database,
|
||||
2,
|
||||
FoundationDbMessageStore.getPresenceKey(SERVICE_IDENTIFIER, Device.PRIMARY_ID),
|
||||
presenceRenewalExecutorService,
|
||||
MESSAGES_AVAILABLE_WATCH_KEY,
|
||||
(oldState, newState) -> {
|
||||
stateTransitions.add(newState);
|
||||
@@ -292,12 +329,15 @@ class FoundationDbMessagePublisherTest {
|
||||
|
||||
@Test
|
||||
@SuppressWarnings({"unchecked", "resource"})
|
||||
void watchCanceledOnSubscriptionCancel() throws InvalidProtocolBufferException {
|
||||
void watchCanceledOnSubscriptionCancel() {
|
||||
final FoundationDbMessagePublisher infinitePublisher = FoundationDbMessagePublisher.createInfinitePublisher(
|
||||
database,
|
||||
CLOCK,
|
||||
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.begin),
|
||||
KeySelector.firstGreaterThan(SUBSPACE_RANGE.end),
|
||||
database,
|
||||
100,
|
||||
FoundationDbMessageStore.getPresenceKey(SERVICE_IDENTIFIER, Device.PRIMARY_ID),
|
||||
presenceRenewalExecutorService,
|
||||
MESSAGES_AVAILABLE_WATCH_KEY,
|
||||
() -> _ -> {});
|
||||
final MessageProtos.Envelope message = FoundationDbMessageStoreTest.generateRandomMessage(false);
|
||||
@@ -325,6 +365,129 @@ class FoundationDbMessagePublisherTest {
|
||||
verify(watchFuture).cancel(true);
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings({"unchecked", "resource"})
|
||||
void terminateWithError() {
|
||||
final MessageProtos.Envelope message = FoundationDbMessageStoreTest.generateRandomMessage(false);
|
||||
|
||||
final KeyValue keyValue = mockKeyValue((byte) 5, message);
|
||||
|
||||
final AsyncIterable<KeyValue> keyValues = mock(AsyncIterable.class);
|
||||
when(keyValues.asList()).thenReturn(CompletableFuture.completedFuture(List.of(keyValue)));
|
||||
|
||||
final Transaction transaction = mock(Transaction.class);
|
||||
when(transaction.getRange(any(KeySelector.class), any(KeySelector.class), anyInt(), anyBoolean(), any(StreamingMode.class)))
|
||||
.thenReturn(keyValues);
|
||||
when(transaction.get(FoundationDbMessageStore.getPresenceKey(SERVICE_IDENTIFIER, Device.PRIMARY_ID)))
|
||||
.thenAnswer(_ -> CompletableFuture.completedFuture(FoundationDbMessageStore.getPresenceValue(CLOCK.instant(), STREAM_ID)));
|
||||
when(transaction.watch(any()))
|
||||
.thenReturn(new CompletableFuture<>());
|
||||
|
||||
when(database.runAsync(any(Function.class))).thenAnswer(
|
||||
(Answer<CompletableFuture<List<? extends MessageStreamEntry>>>) invocationOnMock -> {
|
||||
final Function<Transaction, CompletableFuture<List<? extends MessageStreamEntry>>> f = invocationOnMock.getArgument(
|
||||
0);
|
||||
return f.apply(transaction);
|
||||
});
|
||||
|
||||
final FoundationDbMessagePublisher infinitePublisher = new FoundationDbMessagePublisher(
|
||||
database,
|
||||
CLOCK,
|
||||
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.begin),
|
||||
KeySelector.firstGreaterOrEqual(new byte[]{(byte) 10}),
|
||||
2,
|
||||
FoundationDbMessageStore.getPresenceKey(SERVICE_IDENTIFIER, Device.PRIMARY_ID),
|
||||
presenceRenewalExecutorService,
|
||||
MESSAGES_AVAILABLE_WATCH_KEY,
|
||||
(_, newState) -> stateTransitions.add(newState),
|
||||
NOOP_ON_PAGE_FETCH
|
||||
);
|
||||
|
||||
final RuntimeException streamTerminationException = new RuntimeException("Stream terminated");
|
||||
|
||||
StepVerifier.create(infinitePublisher.getMessages())
|
||||
.expectNext(getExpectedMessageStreamEntry(keyValue))
|
||||
.then(() -> infinitePublisher.terminateWithError(streamTerminationException))
|
||||
.verifyErrorMatches(throwable -> throwable.equals(streamTerminationException));
|
||||
|
||||
assertEquals(List.of(
|
||||
FoundationDbMessagePublisher.State.FETCHING_MESSAGES,
|
||||
FoundationDbMessagePublisher.State.QUEUE_EMPTY,
|
||||
FoundationDbMessagePublisher.State.AWAITING_NEW_MESSAGES,
|
||||
FoundationDbMessagePublisher.State.ERROR
|
||||
),
|
||||
stateTransitions
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void onRequestFlowControl() {
|
||||
final MessageProtos.Envelope message1 = FoundationDbMessageStoreTest.generateRandomMessage(false);
|
||||
final MessageProtos.Envelope message2 = FoundationDbMessageStoreTest.generateRandomMessage(false);
|
||||
final MessageProtos.Envelope message3 = FoundationDbMessageStoreTest.generateRandomMessage(false);
|
||||
|
||||
final KeyValue keyValue1 = mockKeyValue((byte) 5, message1);
|
||||
final KeyValue keyValue2 = mockKeyValue((byte) 6, message2);
|
||||
final KeyValue keyValue3 = mockKeyValue((byte) 7, message3);
|
||||
|
||||
final AsyncIterable<KeyValue> batch1 = mock(AsyncIterable.class);
|
||||
when(batch1.asList()).thenReturn(CompletableFuture.completedFuture(List.of(keyValue1, keyValue2)));
|
||||
|
||||
final AsyncIterable<KeyValue> batch2 = mock(AsyncIterable.class);
|
||||
when(batch2.asList()).thenReturn(CompletableFuture.completedFuture(List.of(keyValue3)));
|
||||
|
||||
final Transaction transaction = mock(Transaction.class);
|
||||
when(transaction.getRange(any(KeySelector.class), any(KeySelector.class), anyInt(), anyBoolean(), any(
|
||||
StreamingMode.class)))
|
||||
.thenReturn(batch1)
|
||||
.thenReturn(batch2);
|
||||
|
||||
when(database.runAsync(any(Function.class))).thenAnswer(
|
||||
(Answer<CompletableFuture<List<? extends MessageStreamEntry>>>) invocationOnMock -> {
|
||||
final Function<Transaction, CompletableFuture<List<? extends MessageStreamEntry>>> f = invocationOnMock.getArgument(
|
||||
0);
|
||||
return f.apply(transaction);
|
||||
});
|
||||
|
||||
final CountDownLatch latch = new CountDownLatch(1);
|
||||
final FoundationDbMessagePublisher finitePublisher = new FoundationDbMessagePublisher(
|
||||
database,
|
||||
CLOCK,
|
||||
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.begin),
|
||||
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.end),
|
||||
2,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
(oldState, newState) -> {
|
||||
if (oldState == FoundationDbMessagePublisher.State.FETCHING_MESSAGES
|
||||
&& 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
|
||||
StepVerifier.create(finitePublisher.getMessages(), 1)
|
||||
.expectNext(getExpectedMessageStreamEntry(keyValue1))
|
||||
.then(() -> {
|
||||
// Wait for the whole batch to have completed publishing before requesting the next message
|
||||
try {
|
||||
assertTrue(latch.await(500, TimeUnit.MILLISECONDS));
|
||||
} catch (final InterruptedException e) {
|
||||
fail(e);
|
||||
}
|
||||
})
|
||||
.thenRequest(1)
|
||||
.expectNext(getExpectedMessageStreamEntry(keyValue2))
|
||||
.verifyTimeout(Duration.ofMillis(500));
|
||||
|
||||
verify(transaction, times(1)).getRange(any(KeySelector.class), any(KeySelector.class), anyInt(), anyBoolean(),
|
||||
any());
|
||||
|
||||
}
|
||||
|
||||
private FoundationDbMessageStreamEntry.Message getExpectedMessageStreamEntry(final KeyValue keyValue) {
|
||||
try {
|
||||
return new FoundationDbMessageStreamEntry.Message(FoundationDbMessageStore.getVersionstamp(keyValue.getKey()),
|
||||
|
||||
+184
-110
@@ -2,6 +2,7 @@ package org.whispersystems.textsecuregcm.storage.foundationdb;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
@@ -18,9 +19,11 @@ import com.google.protobuf.ByteString;
|
||||
import com.google.protobuf.InvalidProtocolBufferException;
|
||||
import io.dropwizard.util.DataSize;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.security.SecureRandom;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
@@ -34,6 +37,9 @@ import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
@@ -43,6 +49,8 @@ import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.stream.Stream;
|
||||
import javax.annotation.Nullable;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Disabled;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -50,6 +58,7 @@ import org.junit.jupiter.api.Timeout;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
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;
|
||||
@@ -60,7 +69,6 @@ import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.FoundationDbClusterExtension;
|
||||
import org.whispersystems.textsecuregcm.storage.MessageStream;
|
||||
import org.whispersystems.textsecuregcm.storage.MessageStreamEntry;
|
||||
import org.whispersystems.textsecuregcm.util.Conversions;
|
||||
import org.whispersystems.textsecuregcm.util.TestClock;
|
||||
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
@@ -77,11 +85,20 @@ class FoundationDbMessageStoreTest {
|
||||
private VersionstampUUIDCipher versionstampUUIDCipher;
|
||||
private FoundationDbMessageStore foundationDbMessageStore;
|
||||
|
||||
private static ScheduledExecutorService presenceRenewalExecutorService;
|
||||
|
||||
private static final TestClock CLOCK = TestClock.pinned(Instant.ofEpochSecond(500));
|
||||
|
||||
private static final int DEFAULT_EPOCH = 0;
|
||||
private static final int FUTURE_EPOCH = 2;
|
||||
|
||||
private static final int STREAM_ID = ThreadLocalRandom.current().nextInt();
|
||||
|
||||
@BeforeAll
|
||||
static void setUpBeforeAll() {
|
||||
presenceRenewalExecutorService = Executors.newSingleThreadScheduledExecutor();
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
final byte[] versionstampCipherKey = new byte[16];
|
||||
@@ -101,9 +118,17 @@ class FoundationDbMessageStoreTest {
|
||||
),
|
||||
DEFAULT_EPOCH,
|
||||
versionstampUUIDCipher,
|
||||
presenceRenewalExecutorService,
|
||||
CLOCK);
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void tearDownAfterAll() throws InterruptedException {
|
||||
presenceRenewalExecutorService.shutdown();
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
presenceRenewalExecutorService.awaitTermination(1, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void insert(final long presenceUpdatedBeforeSeconds,
|
||||
@@ -117,7 +142,7 @@ class FoundationDbMessageStoreTest {
|
||||
.mapToObj(i -> (byte) i)
|
||||
.toList();
|
||||
|
||||
deviceIds.forEach(deviceId -> writePresenceKey(aci, deviceId, 1, presenceUpdatedBeforeSeconds));
|
||||
deviceIds.forEach(deviceId -> writePresenceKey(aci, deviceId, presenceUpdatedBeforeSeconds));
|
||||
|
||||
final Map<Byte, MessageProtos.Envelope> messagesByDeviceId = deviceIds.stream()
|
||||
.collect(Collectors.toMap(Function.identity(), _ -> generateRandomMessage(ephemeral)));
|
||||
@@ -221,13 +246,12 @@ class FoundationDbMessageStoreTest {
|
||||
@Test
|
||||
void versionstampCorrectlyUpdatedOnMultipleInserts() {
|
||||
final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID());
|
||||
writePresenceKey(aci, Device.PRIMARY_ID, 1, 10L);
|
||||
writePresenceKey(aci, Device.PRIMARY_ID, 10L);
|
||||
foundationDbMessageStore.insert(Map.of(aci, Map.of(Device.PRIMARY_ID, generateRandomMessage(false)))).join();
|
||||
final Map<Byte, FoundationDbMessageStore.InsertResult> secondMessageInsertResult = foundationDbMessageStore.insert(aci,
|
||||
Map.of(Device.PRIMARY_ID, generateRandomMessage(false))).join();
|
||||
|
||||
final Optional<Versionstamp> messagesAvailableWatchVersionstamp = getMessagesAvailableWatch(aci);
|
||||
assertTrue(messagesAvailableWatchVersionstamp.isPresent());
|
||||
assertEquals(
|
||||
secondMessageInsertResult.get(Device.PRIMARY_ID).versionstamp(),
|
||||
messagesAvailableWatchVersionstamp);
|
||||
@@ -241,7 +265,7 @@ class FoundationDbMessageStoreTest {
|
||||
.mapToObj(i -> (byte) i)
|
||||
.toList();
|
||||
// Only 1 device has a recent presence, the others do not have presence keys present.
|
||||
writePresenceKey(aci, Device.PRIMARY_ID, 1, 10L);
|
||||
writePresenceKey(aci, Device.PRIMARY_ID, 10L);
|
||||
final Map<Byte, MessageProtos.Envelope> messagesByDeviceId = deviceIds.stream()
|
||||
.collect(Collectors.toMap(Function.identity(), _ -> generateRandomMessage(ephemeral)));
|
||||
final Map<Byte, FoundationDbMessageStore.InsertResult> result = foundationDbMessageStore.insert(aci, messagesByDeviceId).join();
|
||||
@@ -271,7 +295,24 @@ class FoundationDbMessageStoreTest {
|
||||
"Non-ephemeral messages must always be stored");
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void getPresenceServerId() {
|
||||
assertArrayEquals(FoundationDbMessageStore.getServerId(),
|
||||
FoundationDbMessageStore.getPresenceServerId(FoundationDbMessageStore.getPresenceValue(CLOCK.instant(), STREAM_ID)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getPresenceStreamId() {
|
||||
assertEquals(STREAM_ID,
|
||||
FoundationDbMessageStore.getPresenceStreamId(FoundationDbMessageStore.getPresenceValue(CLOCK.instant(), STREAM_ID)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getPresenceTimestamp() {
|
||||
assertEquals(CLOCK.instant().truncatedTo(ChronoUnit.MILLIS),
|
||||
FoundationDbMessageStore.getPresenceTimestamp(FoundationDbMessageStore.getPresenceValue(CLOCK.instant(), STREAM_ID)));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@@ -285,14 +326,14 @@ class FoundationDbMessageStoreTest {
|
||||
Arguments.argumentSet("Presence value doesn't exist",
|
||||
null, false),
|
||||
Arguments.argumentSet("Presence updated recently",
|
||||
Conversions.longToByteArray(constructPresenceValue(42, getEpochSecondsBeforeClock(5))), true),
|
||||
FoundationDbMessageStore.getPresenceValue(CLOCK.instant().minusSeconds(5), STREAM_ID), true),
|
||||
Arguments.argumentSet("Presence updated same second as current time",
|
||||
Conversions.longToByteArray(constructPresenceValue(42, getEpochSecondsBeforeClock(0))), true),
|
||||
FoundationDbMessageStore.getPresenceValue(CLOCK.instant(), STREAM_ID), true),
|
||||
Arguments.argumentSet(
|
||||
"Presence updated exactly at the second before which it would have been considered offline",
|
||||
Conversions.longToByteArray(constructPresenceValue(42, getEpochSecondsBeforeClock(300))), true),
|
||||
FoundationDbMessageStore.getPresenceValue(CLOCK.instant().minus(FoundationDbMessageStore.PRESENCE_STALE_THRESHOLD), STREAM_ID), true),
|
||||
Arguments.argumentSet("Presence expired",
|
||||
Conversions.longToByteArray(constructPresenceValue(42, getEpochSecondsBeforeClock(400))), false)
|
||||
FoundationDbMessageStore.getPresenceValue(CLOCK.instant().minus(FoundationDbMessageStore.PRESENCE_STALE_THRESHOLD.plusSeconds(1)), STREAM_ID), false)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -336,7 +377,7 @@ class FoundationDbMessageStoreTest {
|
||||
final List<AciServiceIdentifier> acis = acisByConfig.get(i);
|
||||
final MultiRecipientTestConfig testConfig = testConfigs.get(i);
|
||||
if (testConfig.devicePresent()) {
|
||||
acis.forEach(aci -> writePresenceKey(aci, Device.PRIMARY_ID, 1, 10L));
|
||||
acis.forEach(aci -> writePresenceKey(aci, Device.PRIMARY_ID, 10L));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -452,36 +493,6 @@ 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());
|
||||
@@ -544,7 +555,6 @@ class FoundationDbMessageStoreTest {
|
||||
@MethodSource
|
||||
void getMessages(final int numMessages, final int batchSize) {
|
||||
final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID());
|
||||
writePresenceKey(aci, Device.PRIMARY_ID, 1, 5L);
|
||||
|
||||
final List<Versionstamp> expectedVersionstamps = IntStream.range(0, numMessages)
|
||||
.mapToObj(_ -> foundationDbMessageStore.insert(aci, Map.of(Device.PRIMARY_ID, generateRandomMessage(false))).join()
|
||||
@@ -553,10 +563,9 @@ class FoundationDbMessageStoreTest {
|
||||
.orElseThrow())
|
||||
.toList();
|
||||
|
||||
final Device device = new Device();
|
||||
device.setId(Device.PRIMARY_ID);
|
||||
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci, device, batchSize, numMessages,
|
||||
Util.NOOP);
|
||||
final MessageStream messageStream =
|
||||
foundationDbMessageStore.getMessages(aci, Device.PRIMARY_ID, batchSize, numMessages, Util.NOOP);
|
||||
|
||||
final List<MessageStreamEntry> retrievedEntries = new ArrayList<>();
|
||||
StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messageStream.getMessages()))
|
||||
.recordWith(() -> retrievedEntries)
|
||||
@@ -592,9 +601,6 @@ class FoundationDbMessageStoreTest {
|
||||
final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID());
|
||||
final byte deviceId = Device.PRIMARY_ID;
|
||||
|
||||
final Device device = new Device();
|
||||
device.setId(deviceId);
|
||||
|
||||
final int messagesPerBatch = 8;
|
||||
|
||||
final AtomicLong serialTimestamp = new AtomicLong();
|
||||
@@ -608,7 +614,7 @@ class FoundationDbMessageStoreTest {
|
||||
final List<MessageProtos.Envelope> liveDefaultEpochMessages = new ArrayList<>();
|
||||
final List<MessageProtos.Envelope> liveFutureEpochMessages = new ArrayList<>();
|
||||
|
||||
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci, device);
|
||||
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci, deviceId);
|
||||
final List<MessageStreamEntry> retrievedEntries = new ArrayList<>();
|
||||
final CountDownLatch queueEmptyLatch = new CountDownLatch(1);
|
||||
|
||||
@@ -625,9 +631,6 @@ class FoundationDbMessageStoreTest {
|
||||
}
|
||||
});
|
||||
|
||||
writePresenceKey(aci, deviceId, 1, 5L, DEFAULT_EPOCH);
|
||||
writePresenceKey(aci, deviceId, 1, 5L, FUTURE_EPOCH);
|
||||
|
||||
StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messageStream.getMessages()))
|
||||
.recordWith(() -> retrievedEntries)
|
||||
.expectNextCount(existingDefaultEpochMessages.size() + existingFutureEpochMessages.size())
|
||||
@@ -656,7 +659,6 @@ class FoundationDbMessageStoreTest {
|
||||
final MessageGuidCodec messageGuidCodec =
|
||||
new MessageGuidCodec(aci.uuid(), Device.PRIMARY_ID, versionstampUUIDCipher);
|
||||
|
||||
writePresenceKey(aci, Device.PRIMARY_ID, 1, 5L);
|
||||
final MessageProtos.Envelope message1 = generateRandomMessage(false);
|
||||
final Versionstamp versionstamp1 = foundationDbMessageStore.insert(aci, Map.of(Device.PRIMARY_ID, message1)).join()
|
||||
.get(Device.PRIMARY_ID)
|
||||
@@ -689,9 +691,7 @@ class FoundationDbMessageStoreTest {
|
||||
}
|
||||
});
|
||||
|
||||
final Device device = new Device();
|
||||
device.setId(Device.PRIMARY_ID);
|
||||
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci, device);
|
||||
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci, Device.PRIMARY_ID);
|
||||
StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messageStream.getMessages()))
|
||||
.expectNext(new MessageStreamEntry.Envelope(message1
|
||||
.toBuilder()
|
||||
@@ -714,7 +714,7 @@ class FoundationDbMessageStoreTest {
|
||||
@Test
|
||||
void getMessagesPublishMoreAfterSubscriptionStarts() {
|
||||
final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID());
|
||||
writePresenceKey(aci, Device.PRIMARY_ID, 1, 5L);
|
||||
|
||||
for (int i = 0; i < 16; i++) {
|
||||
final MessageProtos.Envelope message = generateRandomMessage(false);
|
||||
assertNotNull(foundationDbMessageStore.insert(aci, Map.of(Device.PRIMARY_ID, message)).join());
|
||||
@@ -723,7 +723,7 @@ class FoundationDbMessageStoreTest {
|
||||
final CountDownLatch latch = new CountDownLatch(1);
|
||||
Thread.ofVirtual().start(() -> {
|
||||
try {
|
||||
// Wait until queue is empty
|
||||
// Wait for a first message to get consumed
|
||||
assertTrue(latch.await(1000, TimeUnit.MILLISECONDS));
|
||||
// Then publish more messages
|
||||
for (int i = 0; i < 16; i++) {
|
||||
@@ -735,9 +735,7 @@ class FoundationDbMessageStoreTest {
|
||||
}
|
||||
});
|
||||
|
||||
final Device device = new Device();
|
||||
device.setId(Device.PRIMARY_ID);
|
||||
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci, device);
|
||||
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci, Device.PRIMARY_ID);
|
||||
// Initially only request a single message, then give the go ahead to the publisher. This verifies that we get the
|
||||
// queue empty signal when we consume the initial batch of messages even though the publisher keeps publishing in
|
||||
// the meantime.
|
||||
@@ -751,6 +749,116 @@ class FoundationDbMessageStoreTest {
|
||||
.verifyTimeout(Duration.ofSeconds(3));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getMessagesPresence() {
|
||||
final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID());
|
||||
|
||||
for (int i = 0; i < 16; i++) {
|
||||
foundationDbMessageStore.insert(aci, Map.of(Device.PRIMARY_ID, generateRandomMessage(false))).join();
|
||||
}
|
||||
|
||||
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci, Device.PRIMARY_ID);
|
||||
|
||||
assertFalse(isPresent(aci, Device.PRIMARY_ID));
|
||||
|
||||
StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messageStream.getMessages()), 16)
|
||||
.expectNextCount(16)
|
||||
.then(() -> assertFalse(isPresent(aci, Device.PRIMARY_ID),
|
||||
"Client should not be present until infinite stream begins"))
|
||||
.thenRequest(1)
|
||||
.expectNext(new MessageStreamEntry.QueueEmpty())
|
||||
.then(() -> foundationDbMessageStore.insert(aci, Map.of(Device.PRIMARY_ID, generateRandomMessage(false))).join())
|
||||
.thenRequest(1)
|
||||
.expectNextCount(1)
|
||||
.then(() -> assertTrue(isPresent(aci, Device.PRIMARY_ID),
|
||||
"Client should be present after infinite stream begins"))
|
||||
.verifyTimeout(Duration.ofSeconds(3));
|
||||
|
||||
final Instant deadline = Instant.now().plus(Duration.ofSeconds(1));
|
||||
boolean presenceCleared = false;
|
||||
|
||||
while (!presenceCleared && Instant.now().isBefore(deadline)) {
|
||||
presenceCleared = foundationDbMessageStore.getShardForAci(aci, DEFAULT_EPOCH).runAsync(transaction ->
|
||||
transaction.get(FoundationDbMessageStore.getPresenceKey(aci, Device.PRIMARY_ID)))
|
||||
.thenApply(Objects::isNull)
|
||||
.join();
|
||||
}
|
||||
|
||||
assertTrue(presenceCleared,
|
||||
"Presence should be cleared after subscription disposal");
|
||||
}
|
||||
|
||||
private enum PresenceConflictType {
|
||||
SERVER_ID,
|
||||
STREAM_ID
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@EnumSource
|
||||
void getMessagesPresenceConflictAtDisposal(final PresenceConflictType presenceConflictType) {
|
||||
final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID());
|
||||
|
||||
for (int i = 0; i < 16; i++) {
|
||||
foundationDbMessageStore.insert(aci, Map.of(Device.PRIMARY_ID, generateRandomMessage(false))).join();
|
||||
}
|
||||
|
||||
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci, Device.PRIMARY_ID);
|
||||
|
||||
assertFalse(isPresent(aci, Device.PRIMARY_ID));
|
||||
|
||||
StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messageStream.getMessages()), 16)
|
||||
.expectNextCount(16)
|
||||
.then(() -> assertFalse(isPresent(aci, Device.PRIMARY_ID),
|
||||
"Client should not be present until infinite stream begins"))
|
||||
.thenRequest(1)
|
||||
.expectNext(new MessageStreamEntry.QueueEmpty())
|
||||
.then(() -> foundationDbMessageStore.insert(aci, Map.of(Device.PRIMARY_ID, generateRandomMessage(false))).join())
|
||||
.thenRequest(1)
|
||||
.expectNextCount(1)
|
||||
.then(() -> assertTrue(isPresent(aci, Device.PRIMARY_ID),
|
||||
"Client should be present after infinite stream begins"))
|
||||
.then(() -> {
|
||||
// Overwrite some part of the presence value to simulate a conflict with another server or stream
|
||||
final byte [] presenceValue = switch (presenceConflictType) {
|
||||
case SERVER_ID -> ByteBuffer.wrap(FoundationDbMessageStore.getPresenceValue(CLOCK.instant(), STREAM_ID))
|
||||
.putLong(0, ThreadLocalRandom.current().nextLong())
|
||||
.putLong(8, ThreadLocalRandom.current().nextLong())
|
||||
.array();
|
||||
|
||||
case STREAM_ID -> ByteBuffer.wrap(FoundationDbMessageStore.getPresenceValue(CLOCK.instant(), STREAM_ID))
|
||||
.putInt(16, STREAM_ID + 1)
|
||||
.array();
|
||||
};
|
||||
|
||||
foundationDbMessageStore.getShardForAci(aci, DEFAULT_EPOCH).run(transaction -> {
|
||||
transaction.set(FoundationDbMessageStore.getPresenceKey(aci, Device.PRIMARY_ID), presenceValue);
|
||||
return null;
|
||||
});
|
||||
})
|
||||
.thenCancel()
|
||||
.verify();
|
||||
|
||||
final Instant deadline = Instant.now().plus(Duration.ofSeconds(1));
|
||||
boolean presenceCleared = false;
|
||||
|
||||
while (!presenceCleared && Instant.now().isBefore(deadline)) {
|
||||
presenceCleared = foundationDbMessageStore.getShardForAci(aci, DEFAULT_EPOCH).runAsync(transaction ->
|
||||
transaction.get(FoundationDbMessageStore.getPresenceKey(aci, Device.PRIMARY_ID)))
|
||||
.thenApply(Objects::isNull)
|
||||
.join();
|
||||
}
|
||||
|
||||
assertFalse(presenceCleared,
|
||||
"Presence should not be cleared if presence was established on another instance");
|
||||
}
|
||||
|
||||
private boolean isPresent(final AciServiceIdentifier aci, final byte deviceId) {
|
||||
return foundationDbMessageStore.getShardForAci(aci, DEFAULT_EPOCH).run(transaction ->
|
||||
transaction.get(FoundationDbMessageStore.getPresenceKey(aci, deviceId))
|
||||
.thenApply(foundationDbMessageStore::isClientPresent))
|
||||
.join();
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void acknowledgeMessages(final int numMessages, final Set<Integer> unacknowledgedMessages)
|
||||
@@ -758,7 +866,6 @@ class FoundationDbMessageStoreTest {
|
||||
final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID());
|
||||
final MessageGuidCodec messageGuidCodec =
|
||||
new MessageGuidCodec(aci.uuid(), Device.PRIMARY_ID, versionstampUUIDCipher);
|
||||
writePresenceKey(aci, Device.PRIMARY_ID, 1, 5L);
|
||||
|
||||
final List<Versionstamp> versionstamps = IntStream.range(0, numMessages)
|
||||
.mapToObj(
|
||||
@@ -768,10 +875,8 @@ class FoundationDbMessageStoreTest {
|
||||
.orElseThrow())
|
||||
.toList();
|
||||
|
||||
final Device device = new Device();
|
||||
device.setId(Device.PRIMARY_ID);
|
||||
final CountDownLatch latch = new CountDownLatch(1);
|
||||
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci, device,
|
||||
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci, Device.PRIMARY_ID,
|
||||
FoundationDbMessageStream.DEFAULT_MAX_MESSAGES_PER_SCAN,
|
||||
FoundationDbMessageStream.DEFAULT_MAX_UNACKNOWLEDGED_MESSAGES,
|
||||
latch::countDown);
|
||||
@@ -832,12 +937,7 @@ class FoundationDbMessageStoreTest {
|
||||
void acknowledgeMessagesEpochChange() throws InterruptedException {
|
||||
final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID());
|
||||
final byte deviceId = Device.PRIMARY_ID;
|
||||
|
||||
final Device device = new Device();
|
||||
device.setId(deviceId);
|
||||
|
||||
final int messagesPerBatch = 8;
|
||||
|
||||
final AtomicLong serialTimestamp = new AtomicLong();
|
||||
|
||||
generateAndInsertMessages(aci, deviceId, DEFAULT_EPOCH, messagesPerBatch, serialTimestamp::getAndIncrement);
|
||||
@@ -847,7 +947,7 @@ class FoundationDbMessageStoreTest {
|
||||
final CountDownLatch cleanupLatch = new CountDownLatch(1);
|
||||
|
||||
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci,
|
||||
device,
|
||||
deviceId,
|
||||
FoundationDbMessageStream.DEFAULT_MAX_MESSAGES_PER_SCAN,
|
||||
FoundationDbMessageStream.DEFAULT_MAX_UNACKNOWLEDGED_MESSAGES,
|
||||
cleanupLatch::countDown);
|
||||
@@ -870,7 +970,7 @@ class FoundationDbMessageStoreTest {
|
||||
}
|
||||
|
||||
{
|
||||
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci, device);
|
||||
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci, deviceId);
|
||||
final List<MessageStreamEntry> retrievedEntries = new ArrayList<>();
|
||||
|
||||
StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messageStream.getMessages()))
|
||||
@@ -896,15 +996,12 @@ class FoundationDbMessageStoreTest {
|
||||
final int maxUnacknowledgedMessages = 3;
|
||||
|
||||
final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID());
|
||||
writePresenceKey(aci, Device.PRIMARY_ID, 1, 5L);
|
||||
|
||||
for (int i = 0; i < numMessages; i++) {
|
||||
foundationDbMessageStore.insert(aci, Map.of(Device.PRIMARY_ID, generateRandomMessage(false))).join();
|
||||
}
|
||||
|
||||
final Device device = new Device();
|
||||
device.setId(Device.PRIMARY_ID);
|
||||
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci, device,
|
||||
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci, Device.PRIMARY_ID,
|
||||
FoundationDbMessageStream.DEFAULT_MAX_MESSAGES_PER_SCAN,
|
||||
maxUnacknowledgedMessages,
|
||||
Util.NOOP);
|
||||
@@ -920,7 +1017,7 @@ class FoundationDbMessageStoreTest {
|
||||
final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID());
|
||||
final MessageGuidCodec messageGuidCodec =
|
||||
new MessageGuidCodec(aci.uuid(), Device.PRIMARY_ID, versionstampUUIDCipher);
|
||||
writePresenceKey(aci, Device.PRIMARY_ID, 1, 5L);
|
||||
writePresenceKey(aci, Device.PRIMARY_ID, 5L);
|
||||
|
||||
// Insert an ephemeral message that will be read by the finite publisher and immediately acknowledged and discarded
|
||||
final Versionstamp acknowledgedVersionstamp = foundationDbMessageStore.insert(aci, Map.of(Device.PRIMARY_ID, generateRandomMessage(true)))
|
||||
@@ -949,10 +1046,7 @@ class FoundationDbMessageStoreTest {
|
||||
}
|
||||
});
|
||||
|
||||
final Device device = new Device();
|
||||
device.setId(Device.PRIMARY_ID);
|
||||
|
||||
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci, device,
|
||||
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci, Device.PRIMARY_ID,
|
||||
FoundationDbMessageStream.DEFAULT_MAX_MESSAGES_PER_SCAN,
|
||||
FoundationDbMessageStream.DEFAULT_MAX_UNACKNOWLEDGED_MESSAGES,
|
||||
cleanUpLatch::countDown);
|
||||
@@ -991,15 +1085,14 @@ class FoundationDbMessageStoreTest {
|
||||
final Instant testTime = oldTime.plus(Duration.ofDays(3));
|
||||
|
||||
final List<AciServiceIdentifier> acis = IntStream.range(0, 1024).mapToObj(_ -> new AciServiceIdentifier(UUID.randomUUID())).toList();
|
||||
final Device device = new Device();
|
||||
device.setId(Device.PRIMARY_ID);
|
||||
final byte deviceId = Device.PRIMARY_ID;
|
||||
|
||||
// insert some old messages
|
||||
CompletableFuture.allOf(
|
||||
IntStream.range(0, 10)
|
||||
.mapToObj(_ -> foundationDbMessageStore.insert(
|
||||
acis.stream()
|
||||
.collect(Collectors.toMap(Function.identity(), _ -> Map.of(Device.PRIMARY_ID, generateRandomMessage(false))))))
|
||||
.collect(Collectors.toMap(Function.identity(), _ -> Map.of(deviceId, generateRandomMessage(false))))))
|
||||
.toArray(CompletableFuture[]::new))
|
||||
.join();
|
||||
|
||||
@@ -1013,19 +1106,19 @@ class FoundationDbMessageStoreTest {
|
||||
IntStream.range(0, 10)
|
||||
.mapToObj(_ -> foundationDbMessageStore.insert(
|
||||
acis.stream()
|
||||
.collect(Collectors.toMap(Function.identity(), _ -> Map.of(Device.PRIMARY_ID, generateRandomMessage(false))))))
|
||||
.collect(Collectors.toMap(Function.identity(), _ -> Map.of(deviceId, generateRandomMessage(false))))))
|
||||
.toArray(CompletableFuture[]::new))
|
||||
.join();
|
||||
|
||||
// advance to a future date, and clear messages before the threshold
|
||||
CLOCK.pin(testTime);
|
||||
foundationDbMessageStore.deleteMessagesBefore(
|
||||
acis.stream().collect(Collectors.toMap(Function.identity(), _ -> List.of(Device.PRIMARY_ID))),
|
||||
acis.stream().collect(Collectors.toMap(Function.identity(), _ -> List.of(deviceId))),
|
||||
threshold);
|
||||
|
||||
// make sure we have new but not old messages
|
||||
for (AciServiceIdentifier aci : acis) {
|
||||
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci, device);
|
||||
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci, deviceId);
|
||||
final List<MessageProtos.Envelope> messages =
|
||||
JdkFlowAdapter.flowPublisherToFlux(messageStream.getMessages())
|
||||
.takeUntil(entry -> entry instanceof MessageStreamEntry.QueueEmpty)
|
||||
@@ -1119,35 +1212,16 @@ class FoundationDbMessageStoreTest {
|
||||
|
||||
private void writePresenceKey(final AciServiceIdentifier aci,
|
||||
final byte deviceId,
|
||||
final int serverId,
|
||||
final long secondsBeforeCurrentTime) {
|
||||
|
||||
writePresenceKey(aci, deviceId, serverId, secondsBeforeCurrentTime, DEFAULT_EPOCH);
|
||||
}
|
||||
|
||||
private void writePresenceKey(final AciServiceIdentifier aci,
|
||||
final byte deviceId,
|
||||
final int serverId,
|
||||
final long secondsBeforeCurrentTime,
|
||||
final int epoch) {
|
||||
|
||||
foundationDbMessageStore.getShardForAci(aci, epoch).run(transaction -> {
|
||||
final byte[] presenceKey = foundationDbMessageStore.getPresenceKey(aci, deviceId);
|
||||
final long presenceUpdateEpochSeconds = getEpochSecondsBeforeClock(secondsBeforeCurrentTime);
|
||||
final long presenceValue = constructPresenceValue(serverId, presenceUpdateEpochSeconds);
|
||||
transaction.set(presenceKey, Conversions.longToByteArray(presenceValue));
|
||||
foundationDbMessageStore.getShardForAci(aci, DEFAULT_EPOCH).run(transaction -> {
|
||||
final byte[] presenceKey = FoundationDbMessageStore.getPresenceKey(aci, deviceId);
|
||||
final byte[] presenceValue = FoundationDbMessageStore.getPresenceValue(CLOCK.instant().minusSeconds(secondsBeforeCurrentTime), STREAM_ID);
|
||||
transaction.set(presenceKey, presenceValue);
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
private static long getEpochSecondsBeforeClock(final long secondsBefore) {
|
||||
return CLOCK.instant().minusSeconds(secondsBefore).getEpochSecond();
|
||||
}
|
||||
|
||||
private static long constructPresenceValue(final int serverId, final long presenceUpdateEpochSeconds) {
|
||||
return (long) (serverId & 0x0ffff) << 48 | (presenceUpdateEpochSeconds & 0x0000ffffffffffffL);
|
||||
}
|
||||
|
||||
private AciServiceIdentifier generateRandomAciForShard(final int shardNumber) {
|
||||
return generateRandomAciForShard(shardNumber, DEFAULT_EPOCH);
|
||||
}
|
||||
|
||||
+14
@@ -6,6 +6,7 @@ package org.whispersystems.textsecuregcm.subscriptions;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatException;
|
||||
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.reset;
|
||||
import static org.mockito.Mockito.times;
|
||||
@@ -63,6 +64,19 @@ class AppleAppStoreClientTest {
|
||||
verifyNoInteractions(sandboxClient);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@EnumSource(mode = EnumSource.Mode.INCLUDE, names = {"TRANSACTION_ID_NOT_FOUND", "ORIGINAL_TRANSACTION_ID_NOT_FOUND", "ACCOUNT_NOT_FOUND"})
|
||||
public void notFound(APIError error) throws APIException, IOException {
|
||||
when(productionClient.getAllSubscriptionStatuses(ORIGINAL_TX_ID, new Status[]{}))
|
||||
.thenThrow(new APIException(404, error, "test"));
|
||||
when(sandboxClient.getAllSubscriptionStatuses(ORIGINAL_TX_ID, new Status[]{}))
|
||||
.thenThrow(new APIException(404, error, "test"));
|
||||
|
||||
assertThatExceptionOfType(SubscriptionNotFoundException.class)
|
||||
.isThrownBy(() -> apiWrapper.getAllSubscriptions(ORIGINAL_TX_ID, Tags.empty()));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void fallbackOnNoTransactionFound()
|
||||
throws APIException, IOException, SubscriptionInvalidArgumentsException, SubscriptionNotFoundException, RateLimitExceededException {
|
||||
|
||||
+20
-47
@@ -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) {
|
||||
|
||||
@@ -155,9 +155,9 @@ 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==
|
||||
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
|
||||
paymentsService.coinGeckoApiKey: unset
|
||||
|
||||
@@ -134,6 +134,8 @@ dynamoDbTables:
|
||||
expiration: P90D
|
||||
phoneNumberIdentifiers:
|
||||
tableName: pni_test
|
||||
profileAvatars:
|
||||
tableName: profileAvatars_test
|
||||
profiles:
|
||||
tableName: profiles_test
|
||||
profilesV2:
|
||||
@@ -325,15 +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
|
||||
|
||||
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
|
||||
|
||||
Reference in new issue
Block a user