Compare commits

..
Author SHA1 Message Date
Chris Eager 2d22cc4420 Fix link in comment 2026-09-30 17:29:51 -04:00
Chris Eager 894ec17169 Update to the latest version of the spam filter 2026-09-30 17:20:42 -04:00
dependabot[bot] 59ea29ab61 Bump the minor-actions-dependencies group with 2 updates
Bumps the minor-actions-dependencies group with 2 updates: [actions/setup-java](https://github.com/actions/setup-java) and [aws-actions/configure-aws-credentials](https://github.com/aws-actions/configure-aws-credentials).


Updates `actions/setup-java` from 6.0.0 to 6.0.1
- [Release notes](https://github.com/actions/setup-java/releases)
- [Commits](https://github.com/actions/setup-java/compare/dd06d9cba3e5552c54d9f8ea23572deb30010f7c...de7274f081f381c8f8158605e0321c36c376e2e6)

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

---
updated-dependencies:
- dependency-name: actions/setup-java
  dependency-version: 6.0.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-actions-dependencies
- dependency-name: aws-actions/configure-aws-credentials
  dependency-version: 6.3.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-actions-dependencies
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-09-30 16:38:53 -04:00
Ravi Khadiwala 69fb42ef82 Use exceptions instead of status when getting PaymentDetails 2026-09-30 15:30:18 -05:00
Chris Eager 9ce8f75d76 Update to the latest version of the spam filter 2026-09-30 16:23:00 -04:00
Chris Eager e90c8685f8 Add support for BoringSSL provider via netty-tcnative 2026-09-30 16:22:07 -04:00
Chris Eager 60738acd17 Update to Lettuce 7.8.0
Also, adapt to Lettuce 7.7.0 behavior change (redis/lettuce#3782) with respect to
command rejection in pending connections by eagerly connecting to upstreams in
`FaultTolerantRedisClusterClient` construction.
2026-09-30 16:21:45 -04:00
Chris Eager f618da855f Complete future with exception if message availability subscriptions fail 2026-09-30 16:21:45 -04:00
Jon Chambers 54807b22a3 Limit APNs/FCM token sizes 2026-09-30 16:21:28 -04:00
Jonathan Klabunde Tomer bdf3e1aea1 accept multiple webauthn origins 2026-09-25 11:41:18 -07:00
Chris Eager 416dee5762 Simplify gRPC ProfileKeyCredential issuance 2026-09-25 11:02:35 -04:00
Chris Eager e4c0649cbd Add metrics for TLS handshakes handled by Netty 2026-09-25 10:51:07 -04:00
Chris Eager 87ca4578b3 Use singular “credential” when appropriate 2026-09-25 10:49:14 -04:00
Jon Chambers 740116e1fd Don't insert shared MRM payloads for unresolved recipients 2026-09-25 10:48:59 -04:00
Ravi Khadiwala 438ad9fb8f Retry 441s in MFA integration test 2026-09-24 10:04:13 -05:00
Ameya Lokare eaa5b96079 Use a virtual thread executor for gRPC service callbacks 2026-09-23 11:36:29 -07:00
Chris Eager 3f7012dba4 Fix large gRPC response truncation 2026-09-23 13:32:17 -05:00
Chris Eager 9bbd04afaa Add tests for response backpressure and concurrent, large, responses
The latter is a regression test for hangs (fixed in Netty 4.2.18,
https://github.com/netty/netty/pull/17279) and response truncation.
2026-09-23 13:32:17 -05:00
Ravi Khadiwala 9b8502bb6e Forbid reuse of TOTPs 2026-09-23 13:31:22 -05:00
Ravi Khadiwala 7866ad18fa Unnest GetExpiringProfileKeyCredentialRequest 2026-09-23 13:30:56 -05:00
Chris Eager 4101914040 Add ProfileAnonymous#getProfile response case metric 2026-09-23 13:30:28 -05:00
Chris Eager 40889a1337 Don’t require PROFILES_V2 capability to call setProfile rpc 2026-09-23 13:30:28 -05:00
Jon Chambers 26426dda7f Shorten TTL for shared MRM payloads 2026-09-23 13:29:41 -05:00
Chris Eager d045c45baa Update GooglePlayBillingManager#executeTokenOperation doc 2026-09-23 11:58:58 -04:00
Jon Chambers a409b8e044 Revert "Disable flaky `ClearOrphanedFoundationDbQueuesCommandTest#aciReusedAf…"
This reverts commit acbf1d828c.
2026-09-22 14:32:53 -04:00
Jon Chambers 4289d454f3 Resolve ExtensionContext.Store.CloseableResource deprecation warnings 2026-09-22 14:18:19 -04:00
Jon Chambers 2df897ab0b Clear FoundationDB databases before each test 2026-09-22 14:18:19 -04:00
Katherine 4443c31ee0 Augment FoundationDB metrics to help debug epoch drill mystery 2026-09-21 16:09:03 -04:00
Katherine acbf1d828c Disable flaky ClearOrphanedFoundationDbQueuesCommandTest#aciReusedAfterExistenceCheck 2026-09-21 15:49:02 -04:00
Chris Eager 9379af28fd Add resilience configuration to CommandDependencies 2026-09-21 15:42:44 -04:00
Jonathan Klabunde Tomer de5ae9f7e7 Retire message delivery-loop monitor 2026-09-21 15:24:45 -04:00
Chris Eager c171a89f03 Update BulkheadConfiguration.maxWaitDuration validation 2026-09-21 12:46:40 -04:00
Chris Eager 4bc550320b Update to the latest version of the spam filter 2026-09-21 12:23:13 -04:00
Jon Chambers 361b982357 Use FoundationDB as the source of presence when reading "live" messages from FoundationDB 2026-09-21 12:06:45 -04:00
Ravi Khadiwala 534825fb68 Use stripe-style currency minor-units in donations/configuration 2026-09-21 12:05:20 -04:00
Jon Chambers 9e3d10a6e8 Add bulkheads to FaultTolerantDatabase 2026-09-21 12:04:39 -04:00
Ravi Khadiwala ddb4b5d5dd Adjust default MFA rate-limit 2026-09-21 12:04:17 -04:00
Jon Chambers ca34692cbb Retire the verificationCodePushNotification experiment (now permanently on) 2026-09-21 12:02:16 -04:00
Katherine 2bffd909a5 Allow up to MAX_SHARDS FoundationDB shards 2026-09-21 11:55:47 -04:00
Chris Eager d400e700ac Add comment regarding when a one-time donation record might not be found 2026-09-18 17:38:13 -04:00
Ravi Khadiwala 755a87c74d Clear receipt state before integration tests 2026-09-17 12:50:28 -05:00
Ravi Khadiwala b30fc7aa8b Add a metric for duplicate receipt redemption 2026-09-16 12:43:22 -05:00
Jonathan Klabunde Tomer 4f4bd431f5 gRPC endpoints to verify existing MFA tokens 2026-09-16 10:37:50 -07:00
Jon Chambers 79757458d6 Introduce an experiment to use FoundationDB as the primary source for "live" messages 2026-09-16 10:46:35 -04:00
Jon Chambers c09aab080f Rename the "answer challenge" method and normalize "not permitted" responses 2026-09-16 10:27:38 -04:00
Jon Chambers 580960d958 Add a gRPC endpoint for requesting push challenges 2026-09-16 10:27:38 -04:00
Ravi Khadiwala c21475e3e7 Add an 'impossible' marker to mismatched number logs 2026-09-16 10:17:52 -04:00
Jon Chambers 09b5289d83 Add a gRPC endpoint for reporting spam 2026-09-16 10:16:40 -04:00
Jon Chambers f66bd0858d Introduce ReportMessageHelper 2026-09-16 10:16:40 -04:00
Jon Chambers ce8cc80f66 Retire unused "report spam via e164" pathway 2026-09-16 10:16:40 -04:00
Chris Eager 66b5412103 Update netty to 4.2.18 2026-09-16 10:06:13 -04:00
Chris Eager 11b6894dae Add backend tag to H2FrameProxyHandler writability changed metric 2026-09-16 10:05:55 -04:00
moiseev-signal 02b86d67ad Override domain in KT gRPC errors with chat domain 2026-09-16 09:56:41 -04:00
Jon Chambers f55c3c22fe Clarify naming and reduce duplication in CredentialsGrpcService 2026-09-16 09:20:48 -04:00
Jonathan Klabunde Tomer eb601cd51e Add WebAuthn MFA key support 2026-09-14 10:48:37 -04:00
Jon Chambers 2ee739dbe1 Add a dynamic configuration flag to fail open in the event of upstream captcha errors 2026-09-14 10:35:04 -04:00
Jon Chambers a15b70476d Add a gauge for concurrent FoundationDB transactions 2026-09-14 10:34:58 -04:00
Ameya Lokare 5f124cc812 Port /v1/archives/backupid/limits to gRPC 2026-09-14 10:34:51 -04:00
Chris Eager ce3378354d Address various deprecations 2026-09-14 10:30:24 -04:00
Ravi Khadiwala cb02200a24 Delete updated user at end of testRecoverWithTotp 2026-09-11 16:55:41 -04:00
Ameya Lokare fd36a8909c Improve handling of FoundationDB errors in reactive streams 2026-09-10 10:49:45 -07:00
Ravi Khadiwala 78c15d2a9a Only enable setting MFA from numberless accounts 2026-09-10 10:48:19 -07:00
Ameya Lokare 5815bb8e3f Measure missing mirrored messages' age 2026-09-10 10:47:45 -07:00
Katherine d366cdbcb0 Instrument more FoundationDB calls 2026-09-10 13:46:00 -04:00
Jon Chambers 52b32ce2d4 Add a slightly more descriptive error message if something goes wrong starting FoundationDB 2026-09-10 10:42:13 -07:00
Ameya Lokare e976c4fbb5 Add method to check for account existence by ACI 2026-09-10 10:41:21 -07:00
Ameya Lokare 81f38c1db7 Configure multiple FoundationDB client threads 2026-09-10 10:29:37 -07:00
Ravi Khadiwala 5221b3fb84 Add an integration test for recovering with a TOTP 2026-09-09 16:31:03 -05:00
Jon Chambers 53bd7a5587 Update to Java 26 2026-09-09 11:21:20 -04:00
Katherine 100ab61c82 Add circuit breakers to FoundationDB operations 2026-09-08 14:36:52 -04:00
Ameya Lokare 4d48c40ce1 Add timer to measure warmup time 2026-09-08 10:35:20 -04:00
Ameya Lokare 93ade07c57 Read status key at startup to warm up FoundationDB connections 2026-09-08 10:35:20 -04:00
Jon Chambers c1d8ca3c14 Update to the latest version of the spam filter 2026-09-08 10:34:02 -04:00
Jon Chambers 38707313d7 Retire UpdateGambiaPniMappingsCommand 2026-09-03 12:29:56 -04:00
ameya-signal 8eb2f5cec6 Use content hash to compare message envelopes 2026-09-03 09:28:06 -07:00
ameya-signal a7d66cb8e6 Add ephemeral tag to missing messages counter 2026-09-03 09:28:02 -07:00
ameya-signal 9db804f7c0 Add metrics to measure stream agreement between Redis/Dynamo and FoundationDB 2026-09-03 09:27:57 -07:00
Jon Chambers e93395e334 Retire PopulateAccountRecoveryPasswordsCommand 2026-09-03 12:12:05 -04:00
ameya-signal c9b8645469 Instrument FoundationDB transaction errors in a central place 2026-09-03 12:09:46 -04:00
Katherine f92681dbae Don't fall back to v4 UUIDs if FoundationDB insert fails 2026-09-03 12:09:28 -04:00
Ravi Khadiwala 7489c62fb7 Avoid attribute modification errors on numberless accounts 2026-09-02 16:17:26 -05:00
Ravi Khadiwala 23932b1087 Update constructors in UpdateGambiaPniMappingsCommandTest 2026-09-02 16:15:37 -05:00
Ravi Khadiwala 6b3f66ddc1 Forbid idempotent numberless registration retries if MFA keys are present 2026-09-02 16:56:11 -04:00
Jon Chambers 77e3675fc9 Add a command to map alternate forms of existing Gambian phone numbers to the same PNI 2026-09-02 16:55:49 -04:00
Jon Chambers 2f712b3f93 Add an alternate number form generator for Gambia 2026-09-02 16:55:49 -04:00
Jon Chambers 9b5ad238cf Introduce the AlternatePhoneNumberFormGenerator interface 2026-09-02 16:55:49 -04:00
Ravi Khadiwala 8c62a7f819 Add delay to TOTP confirmation validation 2026-09-02 16:55:35 -04:00
Jonathan Klabunde Tomer 3a75f705c2 Simplify list-MFA-keys RPC
Turns out clients only actually want the metadata, repeating the crypto
parameters is useless
2026-09-02 16:55:26 -04:00
Ameya Lokare d79e37230e Return 401 if receipt credential fails verification, is expired or is
already redeemed
2026-09-02 16:54:12 -04:00
Ameya Lokare 7bc8b93c18 Remove use of account lock executor in
ClearOrphanedFoundationDbQueuesCommand
2026-09-02 16:53:51 -04:00
Ravi Khadiwala b6bed9d772 Remove confusing subscriber_id_mismatch response 2026-09-02 16:34:48 -04:00
Ravi Khadiwala 18e58dd21f Improve error response documentation in subscription.proto 2026-09-02 16:34:48 -04:00
Ravi Khadiwala 6ab0acadfd Document RPCs that require an Accept-Language header 2026-09-02 16:34:48 -04:00
Ravi Khadiwala 6209466d1d Fix accidental renumbering in login_purchase.proto 2026-09-02 16:34:17 -04:00
Ameya Lokare 9483f358cd Remove executor for acquiring locks in AccountLockManager 2026-09-02 16:33:49 -04:00
Ameya Lokare 1c28620b65 Re-use ACI / clear account queues under a pessimistic ACI lock 2026-09-02 16:33:29 -04:00
dependabot[bot] cc50ff7074 Bump the minor-java-dependencies group across 4 directories with 6 updates
Bumps the minor-java-dependencies group with 5 updates in the /api-doc directory:

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

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

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

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

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

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

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



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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Signed-off-by: dependabot[bot] <support@github.com>
2026-08-31 16:58:10 -04:00
Jon Chambers b3506b186d Install gpg before running setup-java 2026-08-31 16:58:10 -04:00
Ameya Lokare a91585d3c0 Unwrap exception on FoundationDB insert 2026-08-31 13:28:59 -05:00
Jonathan Klabunde Tomer 5469341fd6 make some TOTP-specific RPCs generic to any MFA factor 2026-08-31 11:27:11 -07:00
Ravi Khadiwala 9ee081ef28 Add playOptionId to login configuration 2026-08-31 12:59:56 -05:00
Chris Eager 33bf9ccae5 Update sample configuration 2026-08-27 18:45:43 -04:00
Ameya Lokare 2321f42e20 Verify that FoundationDbMessageStore#clearAll clears the entire account
subspace
2026-08-27 17:39:41 -04:00
Chris Eager 355d95c6c6 Add support for issuing libsignal v0.101.0+ call link credentials 2026-08-27 17:39:03 -04:00
Chris Eager 3dde05de8a Revert to Lettuce 7.6.0 2026-08-27 17:36:45 -04:00
dependabot[bot] 1ed282a790 Bump the minor-java-dependencies group across 4 directories with 10 updates
Bumps the minor-java-dependencies group with 8 updates in the /api-doc directory:

| Package | From | To |
| --- | --- | --- |
| io.swagger.core.v3:swagger-maven-plugin-jakarta | `2.2.53` | `2.2.54` |
| [com.google.protobuf:protobuf-bom](https://github.com/protocolbuffers/protobuf) | `4.35.1` | `4.36.0` |
| software.amazon.awssdk:bom | `2.51.4` | `2.54.5` |
| [io.micrometer:micrometer-bom](https://github.com/micrometer-metrics/micrometer-commercial) | `1.17.0` | `1.17.1` |
| [io.opentelemetry.instrumentation:opentelemetry-instrumentation-bom](https://github.com/open-telemetry/opentelemetry-java-instrumentation) | `2.30.0` | `2.31.1` |
| [io.projectreactor:reactor-bom](https://github.com/reactor/reactor) | `2025.0.6` | `2025.0.7` |
| [io.lettuce:lettuce-core](https://github.com/redis/lettuce) | `7.6.0.RELEASE` | `7.7.0.RELEASE` |
| [com.google.guava:guava](https://github.com/google/guava) | `33.7.0-jre` | `33.7.1-jre` |

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

| Package | From | To |
| --- | --- | --- |
| [com.google.protobuf:protobuf-bom](https://github.com/protocolbuffers/protobuf) | `4.35.1` | `4.36.0` |
| software.amazon.awssdk:bom | `2.51.4` | `2.54.5` |
| [io.micrometer:micrometer-bom](https://github.com/micrometer-metrics/micrometer-commercial) | `1.17.0` | `1.17.1` |
| [io.opentelemetry.instrumentation:opentelemetry-instrumentation-bom](https://github.com/open-telemetry/opentelemetry-java-instrumentation) | `2.30.0` | `2.31.1` |
| [io.projectreactor:reactor-bom](https://github.com/reactor/reactor) | `2025.0.6` | `2025.0.7` |
| [io.lettuce:lettuce-core](https://github.com/redis/lettuce) | `7.6.0.RELEASE` | `7.7.0.RELEASE` |
| [com.google.guava:guava](https://github.com/google/guava) | `33.7.0-jre` | `33.7.1-jre` |

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

| Package | From | To |
| --- | --- | --- |
| [com.google.protobuf:protobuf-bom](https://github.com/protocolbuffers/protobuf) | `4.35.1` | `4.36.0` |
| software.amazon.awssdk:bom | `2.51.4` | `2.54.5` |
| [io.micrometer:micrometer-bom](https://github.com/micrometer-metrics/micrometer-commercial) | `1.17.0` | `1.17.1` |
| [io.opentelemetry.instrumentation:opentelemetry-instrumentation-bom](https://github.com/open-telemetry/opentelemetry-java-instrumentation) | `2.30.0` | `2.31.1` |
| [io.projectreactor:reactor-bom](https://github.com/reactor/reactor) | `2025.0.6` | `2025.0.7` |
| [io.lettuce:lettuce-core](https://github.com/redis/lettuce) | `7.6.0.RELEASE` | `7.7.0.RELEASE` |
| [com.google.guava:guava](https://github.com/google/guava) | `33.7.0-jre` | `33.7.1-jre` |
| io.swagger.core.v3:swagger-jaxrs2-jakarta | `2.2.53` | `2.2.54` |
| [io.opentelemetry.instrumentation:opentelemetry-logback-appender-1.0](https://github.com/open-telemetry/opentelemetry-java-instrumentation) | `2.30.0-alpha` | `2.31.1-alpha` |

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

| Package | From | To |
| --- | --- | --- |
| [com.google.protobuf:protobuf-bom](https://github.com/protocolbuffers/protobuf) | `4.35.1` | `4.36.0` |
| software.amazon.awssdk:bom | `2.51.4` | `2.54.5` |
| [io.micrometer:micrometer-bom](https://github.com/micrometer-metrics/micrometer-commercial) | `1.17.0` | `1.17.1` |
| [io.opentelemetry.instrumentation:opentelemetry-instrumentation-bom](https://github.com/open-telemetry/opentelemetry-java-instrumentation) | `2.30.0` | `2.31.1` |
| [io.projectreactor:reactor-bom](https://github.com/reactor/reactor) | `2025.0.6` | `2025.0.7` |
| [io.lettuce:lettuce-core](https://github.com/redis/lettuce) | `7.6.0.RELEASE` | `7.7.0.RELEASE` |
| [com.google.guava:guava](https://github.com/google/guava) | `33.7.0-jre` | `33.7.1-jre` |

Updates `io.swagger.core.v3:swagger-maven-plugin-jakarta` from 2.2.53 to 2.2.54

Updates `com.google.protobuf:protobuf-bom` from 4.35.1 to 4.36.0
- [Release notes](https://github.com/protocolbuffers/protobuf/releases)
- [Commits](https://github.com/protocolbuffers/protobuf/commits)

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

Updates `io.micrometer:micrometer-bom` from 1.17.0 to 1.17.1
- [Commits](https://github.com/micrometer-metrics/micrometer-commercial/commits)

Updates `io.opentelemetry.instrumentation:opentelemetry-instrumentation-bom` from 2.30.0 to 2.31.1
- [Release notes](https://github.com/open-telemetry/opentelemetry-java-instrumentation/releases)
- [Changelog](https://github.com/open-telemetry/opentelemetry-java-instrumentation/blob/main/CHANGELOG.md)
- [Commits](https://github.com/open-telemetry/opentelemetry-java-instrumentation/compare/v2.30.0...v2.31.1)

Updates `io.projectreactor:reactor-bom` from 2025.0.6 to 2025.0.7
- [Release notes](https://github.com/reactor/reactor/releases)
- [Commits](https://github.com/reactor/reactor/compare/2025.0.6...2025.0.7)

Updates `io.lettuce:lettuce-core` from 7.6.0.RELEASE to 7.7.0.RELEASE
- [Release notes](https://github.com/redis/lettuce/releases)
- [Changelog](https://github.com/redis/lettuce/blob/main/RELEASE-NOTES.md)
- [Commits](https://github.com/redis/lettuce/compare/7.6.0.RELEASE...7.7.0.RELEASE)

Updates `com.google.guava:guava` from 33.7.0-jre to 33.7.1-jre
- [Release notes](https://github.com/google/guava/releases)
- [Commits](https://github.com/google/guava/commits)

Updates `com.google.protobuf:protobuf-bom` from 4.35.1 to 4.36.0
- [Release notes](https://github.com/protocolbuffers/protobuf/releases)
- [Commits](https://github.com/protocolbuffers/protobuf/commits)

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

Updates `io.micrometer:micrometer-bom` from 1.17.0 to 1.17.1
- [Commits](https://github.com/micrometer-metrics/micrometer-commercial/commits)

Updates `io.opentelemetry.instrumentation:opentelemetry-instrumentation-bom` from 2.30.0 to 2.31.1
- [Release notes](https://github.com/open-telemetry/opentelemetry-java-instrumentation/releases)
- [Changelog](https://github.com/open-telemetry/opentelemetry-java-instrumentation/blob/main/CHANGELOG.md)
- [Commits](https://github.com/open-telemetry/opentelemetry-java-instrumentation/compare/v2.30.0...v2.31.1)

Updates `io.projectreactor:reactor-bom` from 2025.0.6 to 2025.0.7
- [Release notes](https://github.com/reactor/reactor/releases)
- [Commits](https://github.com/reactor/reactor/compare/2025.0.6...2025.0.7)

Updates `io.lettuce:lettuce-core` from 7.6.0.RELEASE to 7.7.0.RELEASE
- [Release notes](https://github.com/redis/lettuce/releases)
- [Changelog](https://github.com/redis/lettuce/blob/main/RELEASE-NOTES.md)
- [Commits](https://github.com/redis/lettuce/compare/7.6.0.RELEASE...7.7.0.RELEASE)

Updates `com.google.guava:guava` from 33.7.0-jre to 33.7.1-jre
- [Release notes](https://github.com/google/guava/releases)
- [Commits](https://github.com/google/guava/commits)

Updates `io.lettuce:lettuce-core` from 7.6.0.RELEASE to 7.7.0.RELEASE
- [Release notes](https://github.com/redis/lettuce/releases)
- [Changelog](https://github.com/redis/lettuce/blob/main/RELEASE-NOTES.md)
- [Commits](https://github.com/redis/lettuce/compare/7.6.0.RELEASE...7.7.0.RELEASE)

Updates `com.google.guava:guava` from 33.7.0-jre to 33.7.1-jre
- [Release notes](https://github.com/google/guava/releases)
- [Commits](https://github.com/google/guava/commits)

Updates `com.google.protobuf:protobuf-bom` from 4.35.1 to 4.36.0
- [Release notes](https://github.com/protocolbuffers/protobuf/releases)
- [Commits](https://github.com/protocolbuffers/protobuf/commits)

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

Updates `io.micrometer:micrometer-bom` from 1.17.0 to 1.17.1
- [Commits](https://github.com/micrometer-metrics/micrometer-commercial/commits)

Updates `io.opentelemetry.instrumentation:opentelemetry-instrumentation-bom` from 2.30.0 to 2.31.1
- [Release notes](https://github.com/open-telemetry/opentelemetry-java-instrumentation/releases)
- [Changelog](https://github.com/open-telemetry/opentelemetry-java-instrumentation/blob/main/CHANGELOG.md)
- [Commits](https://github.com/open-telemetry/opentelemetry-java-instrumentation/compare/v2.30.0...v2.31.1)

Updates `io.projectreactor:reactor-bom` from 2025.0.6 to 2025.0.7
- [Release notes](https://github.com/reactor/reactor/releases)
- [Commits](https://github.com/reactor/reactor/compare/2025.0.6...2025.0.7)

Updates `com.google.guava:guava` from 33.7.0-jre to 33.7.1-jre
- [Release notes](https://github.com/google/guava/releases)
- [Commits](https://github.com/google/guava/commits)

Updates `com.google.protobuf:protobuf-bom` from 4.35.1 to 4.36.0
- [Release notes](https://github.com/protocolbuffers/protobuf/releases)
- [Commits](https://github.com/protocolbuffers/protobuf/commits)

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

Updates `io.micrometer:micrometer-bom` from 1.17.0 to 1.17.1
- [Commits](https://github.com/micrometer-metrics/micrometer-commercial/commits)

Updates `io.opentelemetry.instrumentation:opentelemetry-instrumentation-bom` from 2.30.0 to 2.31.1
- [Release notes](https://github.com/open-telemetry/opentelemetry-java-instrumentation/releases)
- [Changelog](https://github.com/open-telemetry/opentelemetry-java-instrumentation/blob/main/CHANGELOG.md)
- [Commits](https://github.com/open-telemetry/opentelemetry-java-instrumentation/compare/v2.30.0...v2.31.1)

Updates `io.projectreactor:reactor-bom` from 2025.0.6 to 2025.0.7
- [Release notes](https://github.com/reactor/reactor/releases)
- [Commits](https://github.com/reactor/reactor/compare/2025.0.6...2025.0.7)

Updates `io.lettuce:lettuce-core` from 7.6.0.RELEASE to 7.7.0.RELEASE
- [Release notes](https://github.com/redis/lettuce/releases)
- [Changelog](https://github.com/redis/lettuce/blob/main/RELEASE-NOTES.md)
- [Commits](https://github.com/redis/lettuce/compare/7.6.0.RELEASE...7.7.0.RELEASE)

Updates `com.google.protobuf:protobuf-bom` from 4.35.1 to 4.36.0
- [Release notes](https://github.com/protocolbuffers/protobuf/releases)
- [Commits](https://github.com/protocolbuffers/protobuf/commits)

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

Updates `io.micrometer:micrometer-bom` from 1.17.0 to 1.17.1
- [Commits](https://github.com/micrometer-metrics/micrometer-commercial/commits)

Updates `io.opentelemetry.instrumentation:opentelemetry-instrumentation-bom` from 2.30.0 to 2.31.1
- [Release notes](https://github.com/open-telemetry/opentelemetry-java-instrumentation/releases)
- [Changelog](https://github.com/open-telemetry/opentelemetry-java-instrumentation/blob/main/CHANGELOG.md)
- [Commits](https://github.com/open-telemetry/opentelemetry-java-instrumentation/compare/v2.30.0...v2.31.1)

Updates `io.projectreactor:reactor-bom` from 2025.0.6 to 2025.0.7
- [Release notes](https://github.com/reactor/reactor/releases)
- [Commits](https://github.com/reactor/reactor/compare/2025.0.6...2025.0.7)

Updates `io.lettuce:lettuce-core` from 7.6.0.RELEASE to 7.7.0.RELEASE
- [Release notes](https://github.com/redis/lettuce/releases)
- [Changelog](https://github.com/redis/lettuce/blob/main/RELEASE-NOTES.md)
- [Commits](https://github.com/redis/lettuce/compare/7.6.0.RELEASE...7.7.0.RELEASE)

Updates `com.google.guava:guava` from 33.7.0-jre to 33.7.1-jre
- [Release notes](https://github.com/google/guava/releases)
- [Commits](https://github.com/google/guava/commits)

Updates `com.google.protobuf:protobuf-bom` from 4.35.1 to 4.36.0
- [Release notes](https://github.com/protocolbuffers/protobuf/releases)
- [Commits](https://github.com/protocolbuffers/protobuf/commits)

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

Updates `io.micrometer:micrometer-bom` from 1.17.0 to 1.17.1
- [Commits](https://github.com/micrometer-metrics/micrometer-commercial/commits)

Updates `io.opentelemetry.instrumentation:opentelemetry-instrumentation-bom` from 2.30.0 to 2.31.1
- [Release notes](https://github.com/open-telemetry/opentelemetry-java-instrumentation/releases)
- [Changelog](https://github.com/open-telemetry/opentelemetry-java-instrumentation/blob/main/CHANGELOG.md)
- [Commits](https://github.com/open-telemetry/opentelemetry-java-instrumentation/compare/v2.30.0...v2.31.1)

Updates `io.projectreactor:reactor-bom` from 2025.0.6 to 2025.0.7
- [Release notes](https://github.com/reactor/reactor/releases)
- [Commits](https://github.com/reactor/reactor/compare/2025.0.6...2025.0.7)

Updates `io.lettuce:lettuce-core` from 7.6.0.RELEASE to 7.7.0.RELEASE
- [Release notes](https://github.com/redis/lettuce/releases)
- [Changelog](https://github.com/redis/lettuce/blob/main/RELEASE-NOTES.md)
- [Commits](https://github.com/redis/lettuce/compare/7.6.0.RELEASE...7.7.0.RELEASE)

Updates `com.google.guava:guava` from 33.7.0-jre to 33.7.1-jre
- [Release notes](https://github.com/google/guava/releases)
- [Commits](https://github.com/google/guava/commits)

Updates `io.lettuce:lettuce-core` from 7.6.0.RELEASE to 7.7.0.RELEASE
- [Release notes](https://github.com/redis/lettuce/releases)
- [Changelog](https://github.com/redis/lettuce/blob/main/RELEASE-NOTES.md)
- [Commits](https://github.com/redis/lettuce/compare/7.6.0.RELEASE...7.7.0.RELEASE)

Updates `com.google.guava:guava` from 33.7.0-jre to 33.7.1-jre
- [Release notes](https://github.com/google/guava/releases)
- [Commits](https://github.com/google/guava/commits)

Updates `com.google.protobuf:protobuf-bom` from 4.35.1 to 4.36.0
- [Release notes](https://github.com/protocolbuffers/protobuf/releases)
- [Commits](https://github.com/protocolbuffers/protobuf/commits)

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

Updates `io.micrometer:micrometer-bom` from 1.17.0 to 1.17.1
- [Commits](https://github.com/micrometer-metrics/micrometer-commercial/commits)

Updates `io.opentelemetry.instrumentation:opentelemetry-instrumentation-bom` from 2.30.0 to 2.31.1
- [Release notes](https://github.com/open-telemetry/opentelemetry-java-instrumentation/releases)
- [Changelog](https://github.com/open-telemetry/opentelemetry-java-instrumentation/blob/main/CHANGELOG.md)
- [Commits](https://github.com/open-telemetry/opentelemetry-java-instrumentation/compare/v2.30.0...v2.31.1)

Updates `io.projectreactor:reactor-bom` from 2025.0.6 to 2025.0.7
- [Release notes](https://github.com/reactor/reactor/releases)
- [Commits](https://github.com/reactor/reactor/compare/2025.0.6...2025.0.7)

Updates `com.google.guava:guava` from 33.7.0-jre to 33.7.1-jre
- [Release notes](https://github.com/google/guava/releases)
- [Commits](https://github.com/google/guava/commits)

Updates `com.google.protobuf:protobuf-bom` from 4.35.1 to 4.36.0
- [Release notes](https://github.com/protocolbuffers/protobuf/releases)
- [Commits](https://github.com/protocolbuffers/protobuf/commits)

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

Updates `io.micrometer:micrometer-bom` from 1.17.0 to 1.17.1
- [Commits](https://github.com/micrometer-metrics/micrometer-commercial/commits)

Updates `io.opentelemetry.instrumentation:opentelemetry-instrumentation-bom` from 2.30.0 to 2.31.1
- [Release notes](https://github.com/open-telemetry/opentelemetry-java-instrumentation/releases)
- [Changelog](https://github.com/open-telemetry/opentelemetry-java-instrumentation/blob/main/CHANGELOG.md)
- [Commits](https://github.com/open-telemetry/opentelemetry-java-instrumentation/compare/v2.30.0...v2.31.1)

Updates `io.projectreactor:reactor-bom` from 2025.0.6 to 2025.0.7
- [Release notes](https://github.com/reactor/reactor/releases)
- [Commits](https://github.com/reactor/reactor/compare/2025.0.6...2025.0.7)

Updates `io.lettuce:lettuce-core` from 7.6.0.RELEASE to 7.7.0.RELEASE
- [Release notes](https://github.com/redis/lettuce/releases)
- [Changelog](https://github.com/redis/lettuce/blob/main/RELEASE-NOTES.md)
- [Commits](https://github.com/redis/lettuce/compare/7.6.0.RELEASE...7.7.0.RELEASE)

Updates `com.google.protobuf:protobuf-bom` from 4.35.1 to 4.36.0
- [Release notes](https://github.com/protocolbuffers/protobuf/releases)
- [Commits](https://github.com/protocolbuffers/protobuf/commits)

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

Updates `io.micrometer:micrometer-bom` from 1.17.0 to 1.17.1
- [Commits](https://github.com/micrometer-metrics/micrometer-commercial/commits)

Updates `io.opentelemetry.instrumentation:opentelemetry-instrumentation-bom` from 2.30.0 to 2.31.1
- [Release notes](https://github.com/open-telemetry/opentelemetry-java-instrumentation/releases)
- [Changelog](https://github.com/open-telemetry/opentelemetry-java-instrumentation/blob/main/CHANGELOG.md)
- [Commits](https://github.com/open-telemetry/opentelemetry-java-instrumentation/compare/v2.30.0...v2.31.1)

Updates `io.projectreactor:reactor-bom` from 2025.0.6 to 2025.0.7
- [Release notes](https://github.com/reactor/reactor/releases)
- [Commits](https://github.com/reactor/reactor/compare/2025.0.6...2025.0.7)

Updates `io.lettuce:lettuce-core` from 7.6.0.RELEASE to 7.7.0.RELEASE
- [Release notes](https://github.com/redis/lettuce/releases)
- [Changelog](https://github.com/redis/lettuce/blob/main/RELEASE-NOTES.md)
- [Commits](https://github.com/redis/lettuce/compare/7.6.0.RELEASE...7.7.0.RELEASE)

Updates `com.google.guava:guava` from 33.7.0-jre to 33.7.1-jre
- [Release notes](https://github.com/google/guava/releases)
- [Commits](https://github.com/google/guava/commits)

Updates `com.google.protobuf:protobuf-bom` from 4.35.1 to 4.36.0
- [Release notes](https://github.com/protocolbuffers/protobuf/releases)
- [Commits](https://github.com/protocolbuffers/protobuf/commits)

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

Updates `io.micrometer:micrometer-bom` from 1.17.0 to 1.17.1
- [Commits](https://github.com/micrometer-metrics/micrometer-commercial/commits)

Updates `io.opentelemetry.instrumentation:opentelemetry-instrumentation-bom` from 2.30.0 to 2.31.1
- [Release notes](https://github.com/open-telemetry/opentelemetry-java-instrumentation/releases)
- [Changelog](https://github.com/open-telemetry/opentelemetry-java-instrumentation/blob/main/CHANGELOG.md)
- [Commits](https://github.com/open-telemetry/opentelemetry-java-instrumentation/compare/v2.30.0...v2.31.1)

Updates `io.projectreactor:reactor-bom` from 2025.0.6 to 2025.0.7
- [Release notes](https://github.com/reactor/reactor/releases)
- [Commits](https://github.com/reactor/reactor/compare/2025.0.6...2025.0.7)

Updates `io.lettuce:lettuce-core` from 7.6.0.RELEASE to 7.7.0.RELEASE
- [Release notes](https://github.com/redis/lettuce/releases)
- [Changelog](https://github.com/redis/lettuce/blob/main/RELEASE-NOTES.md)
- [Commits](https://github.com/redis/lettuce/compare/7.6.0.RELEASE...7.7.0.RELEASE)

Updates `com.google.guava:guava` from 33.7.0-jre to 33.7.1-jre
- [Release notes](https://github.com/google/guava/releases)
- [Commits](https://github.com/google/guava/commits)

Updates `io.swagger.core.v3:swagger-jaxrs2-jakarta` from 2.2.53 to 2.2.54

Updates `io.opentelemetry.instrumentation:opentelemetry-logback-appender-1.0` from 2.30.0-alpha to 2.31.1-alpha
- [Release notes](https://github.com/open-telemetry/opentelemetry-java-instrumentation/releases)
- [Changelog](https://github.com/open-telemetry/opentelemetry-java-instrumentation/blob/main/CHANGELOG.md)
- [Commits](https://github.com/open-telemetry/opentelemetry-java-instrumentation/commits)

Updates `io.lettuce:lettuce-core` from 7.6.0.RELEASE to 7.7.0.RELEASE
- [Release notes](https://github.com/redis/lettuce/releases)
- [Changelog](https://github.com/redis/lettuce/blob/main/RELEASE-NOTES.md)
- [Commits](https://github.com/redis/lettuce/compare/7.6.0.RELEASE...7.7.0.RELEASE)

Updates `com.google.guava:guava` from 33.7.0-jre to 33.7.1-jre
- [Release notes](https://github.com/google/guava/releases)
- [Commits](https://github.com/google/guava/commits)

Updates `com.google.protobuf:protobuf-bom` from 4.35.1 to 4.36.0
- [Release notes](https://github.com/protocolbuffers/protobuf/releases)
- [Commits](https://github.com/protocolbuffers/protobuf/commits)

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

Updates `io.micrometer:micrometer-bom` from 1.17.0 to 1.17.1
- [Commits](https://github.com/micrometer-metrics/micrometer-commercial/commits)

Updates `io.opentelemetry.instrumentation:opentelemetry-instrumentation-bom` from 2.30.0 to 2.31.1
- [Release notes](https://github.com/open-telemetry/opentelemetry-java-instrumentation/releases)
- [Changelog](https://github.com/open-telemetry/opentelemetry-java-instrumentation/blob/main/CHANGELOG.md)
- [Commits](https://github.com/open-telemetry/opentelemetry-java-instrumentation/compare/v2.30.0...v2.31.1)

Updates `io.projectreactor:reactor-bom` from 2025.0.6 to 2025.0.7
- [Release notes](https://github.com/reactor/reactor/releases)
- [Commits](https://github.com/reactor/reactor/compare/2025.0.6...2025.0.7)

Updates `com.google.guava:guava` from 33.7.0-jre to 33.7.1-jre
- [Release notes](https://github.com/google/guava/releases)
- [Commits](https://github.com/google/guava/commits)

Updates `com.google.protobuf:protobuf-bom` from 4.35.1 to 4.36.0
- [Release notes](https://github.com/protocolbuffers/protobuf/releases)
- [Commits](https://github.com/protocolbuffers/protobuf/commits)

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

Updates `io.micrometer:micrometer-bom` from 1.17.0 to 1.17.1
- [Commits](https://github.com/micrometer-metrics/micrometer-commercial/commits)

Updates `io.opentelemetry.instrumentation:opentelemetry-instrumentation-bom` from 2.30.0 to 2.31.1
- [Release notes](https://github.com/open-telemetry/opentelemetry-java-instrumentation/releases)
- [Changelog](https://github.com/open-telemetry/opentelemetry-java-instrumentation/blob/main/CHANGELOG.md)
- [Commits](https://github.com/open-telemetry/opentelemetry-java-instrumentation/compare/v2.30.0...v2.31.1)

Updates `io.projectreactor:reactor-bom` from 2025.0.6 to 2025.0.7
- [Release notes](https://github.com/reactor/reactor/releases)
- [Commits](https://github.com/reactor/reactor/compare/2025.0.6...2025.0.7)

Updates `io.lettuce:lettuce-core` from 7.6.0.RELEASE to 7.7.0.RELEASE
- [Release notes](https://github.com/redis/lettuce/releases)
- [Changelog](https://github.com/redis/lettuce/blob/main/RELEASE-NOTES.md)
- [Commits](https://github.com/redis/lettuce/compare/7.6.0.RELEASE...7.7.0.RELEASE)

Updates `com.google.protobuf:protobuf-bom` from 4.35.1 to 4.36.0
- [Release notes](https://github.com/protocolbuffers/protobuf/releases)
- [Commits](https://github.com/protocolbuffers/protobuf/commits)

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

Updates `io.micrometer:micrometer-bom` from 1.17.0 to 1.17.1
- [Commits](https://github.com/micrometer-metrics/micrometer-commercial/commits)

Updates `io.opentelemetry.instrumentation:opentelemetry-instrumentation-bom` from 2.30.0 to 2.31.1
- [Release notes](https://github.com/open-telemetry/opentelemetry-java-instrumentation/releases)
- [Changelog](https://github.com/open-telemetry/opentelemetry-java-instrumentation/blob/main/CHANGELOG.md)
- [Commits](https://github.com/open-telemetry/opentelemetry-java-instrumentation/compare/v2.30.0...v2.31.1)

Updates `io.projectreactor:reactor-bom` from 2025.0.6 to 2025.0.7
- [Release notes](https://github.com/reactor/reactor/releases)
- [Commits](https://github.com/reactor/reactor/compare/2025.0.6...2025.0.7)

Updates `io.lettuce:lettuce-core` from 7.6.0.RELEASE to 7.7.0.RELEASE
- [Release notes](https://github.com/redis/lettuce/releases)
- [Changelog](https://github.com/redis/lettuce/blob/main/RELEASE-NOTES.md)
- [Commits](https://github.com/redis/lettuce/compare/7.6.0.RELEASE...7.7.0.RELEASE)

Updates `com.google.guava:guava` from 33.7.0-jre to 33.7.1-jre
- [Release notes](https://github.com/google/guava/releases)
- [Commits](https://github.com/google/guava/commits)

Updates `com.google.protobuf:protobuf-bom` from 4.35.1 to 4.36.0
- [Release notes](https://github.com/protocolbuffers/protobuf/releases)
- [Commits](https://github.com/protocolbuffers/protobuf/commits)

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

Updates `io.micrometer:micrometer-bom` from 1.17.0 to 1.17.1
- [Commits](https://github.com/micrometer-metrics/micrometer-commercial/commits)

Updates `io.opentelemetry.instrumentation:opentelemetry-instrumentation-bom` from 2.30.0 to 2.31.1
- [Release notes](https://github.com/open-telemetry/opentelemetry-java-instrumentation/releases)
- [Changelog](https://github.com/open-telemetry/opentelemetry-java-instrumentation/blob/main/CHANGELOG.md)
- [Commits](https://github.com/open-telemetry/opentelemetry-java-instrumentation/compare/v2.30.0...v2.31.1)

Updates `io.projectreactor:reactor-bom` from 2025.0.6 to 2025.0.7
- [Release notes](https://github.com/reactor/reactor/releases)
- [Commits](https://github.com/reactor/reactor/compare/2025.0.6...2025.0.7)

Updates `io.lettuce:lettuce-core` from 7.6.0.RELEASE to 7.7.0.RELEASE
- [Release notes](https://github.com/redis/lettuce/releases)
- [Changelog](https://github.com/redis/lettuce/blob/main/RELEASE-NOTES.md)
- [Commits](https://github.com/redis/lettuce/compare/7.6.0.RELEASE...7.7.0.RELEASE)

Updates `com.google.guava:guava` from 33.7.0-jre to 33.7.1-jre
- [Release notes](https://github.com/google/guava/releases)
- [Commits](https://github.com/google/guava/commits)

Updates `io.lettuce:lettuce-core` from 7.6.0.RELEASE to 7.7.0.RELEASE
- [Release notes](https://github.com/redis/lettuce/releases)
- [Changelog](https://github.com/redis/lettuce/blob/main/RELEASE-NOTES.md)
- [Commits](https://github.com/redis/lettuce/compare/7.6.0.RELEASE...7.7.0.RELEASE)

Updates `com.google.guava:guava` from 33.7.0-jre to 33.7.1-jre
- [Release notes](https://github.com/google/guava/releases)
- [Commits](https://github.com/google/guava/commits)

Updates `com.google.protobuf:protobuf-bom` from 4.35.1 to 4.36.0
- [Release notes](https://github.com/protocolbuffers/protobuf/releases)
- [Commits](https://github.com/protocolbuffers/protobuf/commits)

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

Updates `io.micrometer:micrometer-bom` from 1.17.0 to 1.17.1
- [Commits](https://github.com/micrometer-metrics/micrometer-commercial/commits)

Updates `io.opentelemetry.instrumentation:opentelemetry-instrumentation-bom` from 2.30.0 to 2.31.1
- [Release notes](https://github.com/open-telemetry/opentelemetry-java-instrumentation/releases)
- [Changelog](https://github.com/open-telemetry/opentelemetry-java-instrumentation/blob/main/CHANGELOG.md)
- [Commits](https://github.com/open-telemetry/opentelemetry-java-instrumentation/compare/v2.30.0...v2.31.1)

Updates `io.projectreactor:reactor-bom` from 2025.0.6 to 2025.0.7
- [Release notes](https://github.com/reactor/reactor/releases)
- [Commits](https://github.com/reactor/reactor/compare/2025.0.6...2025.0.7)

Updates `com.google.guava:guava` from 33.7.0-jre to 33.7.1-jre
- [Release notes](https://github.com/google/guava/releases)
- [Commits](https://github.com/google/guava/commits)

Updates `com.google.protobuf:protobuf-bom` from 4.35.1 to 4.36.0
- [Release notes](https://github.com/protocolbuffers/protobuf/releases)
- [Commits](https://github.com/protocolbuffers/protobuf/commits)

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

Updates `io.micrometer:micrometer-bom` from 1.17.0 to 1.17.1
- [Commits](https://github.com/micrometer-metrics/micrometer-commercial/commits)

Updates `io.opentelemetry.instrumentation:opentelemetry-instrumentation-bom` from 2.30.0 to 2.31.1
- [Release notes](https://github.com/open-telemetry/opentelemetry-java-instrumentation/releases)
- [Changelog](https://github.com/open-telemetry/opentelemetry-java-instrumentation/blob/main/CHANGELOG.md)
- [Commits](https://github.com/open-telemetry/opentelemetry-java-instrumentation/compare/v2.30.0...v2.31.1)

Updates `io.projectreactor:reactor-bom` from 2025.0.6 to 2025.0.7
- [Release notes](https://github.com/reactor/reactor/releases)
- [Commits](https://github.com/reactor/reactor/compare/2025.0.6...2025.0.7)

Updates `io.lettuce:lettuce-core` from 7.6.0.RELEASE to 7.7.0.RELEASE
- [Release notes](https://github.com/redis/lettuce/releases)
- [Changelog](https://github.com/redis/lettuce/blob/main/RELEASE-NOTES.md)
- [Commits](https://github.com/redis/lettuce/compare/7.6.0.RELEASE...7.7.0.RELEASE)

---
updated-dependencies:
- dependency-name: io.swagger.core.v3:swagger-maven-plugin-jakarta
  dependency-version: 2.2.54
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: com.google.protobuf:protobuf-bom
  dependency-version: 4.36.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: software.amazon.awssdk:bom
  dependency-version: 2.54.5
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: io.micrometer:micrometer-bom
  dependency-version: 1.17.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: io.opentelemetry.instrumentation:opentelemetry-instrumentation-bom
  dependency-version: 2.31.1
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: io.projectreactor:reactor-bom
  dependency-version: 2025.0.7
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: io.lettuce:lettuce-core
  dependency-version: 7.7.0.RELEASE
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: com.google.guava:guava
  dependency-version: 33.7.1-jre
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: com.google.protobuf:protobuf-bom
  dependency-version: 4.36.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: software.amazon.awssdk:bom
  dependency-version: 2.54.5
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: io.micrometer:micrometer-bom
  dependency-version: 1.17.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: io.opentelemetry.instrumentation:opentelemetry-instrumentation-bom
  dependency-version: 2.31.1
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: io.projectreactor:reactor-bom
  dependency-version: 2025.0.7
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: io.lettuce:lettuce-core
  dependency-version: 7.7.0.RELEASE
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: com.google.guava:guava
  dependency-version: 33.7.1-jre
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: io.lettuce:lettuce-core
  dependency-version: 7.7.0.RELEASE
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: com.google.guava:guava
  dependency-version: 33.7.1-jre
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: com.google.protobuf:protobuf-bom
  dependency-version: 4.36.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: software.amazon.awssdk:bom
  dependency-version: 2.54.5
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: io.micrometer:micrometer-bom
  dependency-version: 1.17.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: io.opentelemetry.instrumentation:opentelemetry-instrumentation-bom
  dependency-version: 2.31.1
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: io.projectreactor:reactor-bom
  dependency-version: 2025.0.7
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: com.google.guava:guava
  dependency-version: 33.7.1-jre
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: com.google.protobuf:protobuf-bom
  dependency-version: 4.36.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: software.amazon.awssdk:bom
  dependency-version: 2.54.5
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: io.micrometer:micrometer-bom
  dependency-version: 1.17.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: io.opentelemetry.instrumentation:opentelemetry-instrumentation-bom
  dependency-version: 2.31.1
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: io.projectreactor:reactor-bom
  dependency-version: 2025.0.7
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: io.lettuce:lettuce-core
  dependency-version: 7.7.0.RELEASE
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: com.google.protobuf:protobuf-bom
  dependency-version: 4.36.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: software.amazon.awssdk:bom
  dependency-version: 2.54.5
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: io.micrometer:micrometer-bom
  dependency-version: 1.17.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: io.opentelemetry.instrumentation:opentelemetry-instrumentation-bom
  dependency-version: 2.31.1
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: io.projectreactor:reactor-bom
  dependency-version: 2025.0.7
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: io.lettuce:lettuce-core
  dependency-version: 7.7.0.RELEASE
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: com.google.guava:guava
  dependency-version: 33.7.1-jre
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: com.google.protobuf:protobuf-bom
  dependency-version: 4.36.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: software.amazon.awssdk:bom
  dependency-version: 2.54.5
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: io.micrometer:micrometer-bom
  dependency-version: 1.17.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: io.opentelemetry.instrumentation:opentelemetry-instrumentation-bom
  dependency-version: 2.31.1
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: io.projectreactor:reactor-bom
  dependency-version: 2025.0.7
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: io.lettuce:lettuce-core
  dependency-version: 7.7.0.RELEASE
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: com.google.guava:guava
  dependency-version: 33.7.1-jre
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: io.lettuce:lettuce-core
  dependency-version: 7.7.0.RELEASE
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: com.google.guava:guava
  dependency-version: 33.7.1-jre
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: com.google.protobuf:protobuf-bom
  dependency-version: 4.36.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: software.amazon.awssdk:bom
  dependency-version: 2.54.5
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: io.micrometer:micrometer-bom
  dependency-version: 1.17.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: io.opentelemetry.instrumentation:opentelemetry-instrumentation-bom
  dependency-version: 2.31.1
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: io.projectreactor:reactor-bom
  dependency-version: 2025.0.7
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: com.google.guava:guava
  dependency-version: 33.7.1-jre
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: com.google.protobuf:protobuf-bom
  dependency-version: 4.36.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: software.amazon.awssdk:bom
  dependency-version: 2.54.5
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: io.micrometer:micrometer-bom
  dependency-version: 1.17.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: io.opentelemetry.instrumentation:opentelemetry-instrumentation-bom
  dependency-version: 2.31.1
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: io.projectreactor:reactor-bom
  dependency-version: 2025.0.7
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: io.lettuce:lettuce-core
  dependency-version: 7.7.0.RELEASE
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: com.google.protobuf:protobuf-bom
  dependency-version: 4.36.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: software.amazon.awssdk:bom
  dependency-version: 2.54.5
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: io.micrometer:micrometer-bom
  dependency-version: 1.17.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: io.opentelemetry.instrumentation:opentelemetry-instrumentation-bom
  dependency-version: 2.31.1
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: io.projectreactor:reactor-bom
  dependency-version: 2025.0.7
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: io.lettuce:lettuce-core
  dependency-version: 7.7.0.RELEASE
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: com.google.guava:guava
  dependency-version: 33.7.1-jre
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: com.google.protobuf:protobuf-bom
  dependency-version: 4.36.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: software.amazon.awssdk:bom
  dependency-version: 2.54.5
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: io.micrometer:micrometer-bom
  dependency-version: 1.17.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: io.opentelemetry.instrumentation:opentelemetry-instrumentation-bom
  dependency-version: 2.31.1
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: io.projectreactor:reactor-bom
  dependency-version: 2025.0.7
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: io.lettuce:lettuce-core
  dependency-version: 7.7.0.RELEASE
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: com.google.guava:guava
  dependency-version: 33.7.1-jre
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: io.swagger.core.v3:swagger-jaxrs2-jakarta
  dependency-version: 2.2.54
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: io.opentelemetry.instrumentation:opentelemetry-logback-appender-1.0
  dependency-version: 2.31.1-alpha
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: io.lettuce:lettuce-core
  dependency-version: 7.7.0.RELEASE
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: com.google.guava:guava
  dependency-version: 33.7.1-jre
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: com.google.protobuf:protobuf-bom
  dependency-version: 4.36.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: software.amazon.awssdk:bom
  dependency-version: 2.54.5
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: io.micrometer:micrometer-bom
  dependency-version: 1.17.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: io.opentelemetry.instrumentation:opentelemetry-instrumentation-bom
  dependency-version: 2.31.1
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: io.projectreactor:reactor-bom
  dependency-version: 2025.0.7
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: com.google.guava:guava
  dependency-version: 33.7.1-jre
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: com.google.protobuf:protobuf-bom
  dependency-version: 4.36.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: software.amazon.awssdk:bom
  dependency-version: 2.54.5
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: io.micrometer:micrometer-bom
  dependency-version: 1.17.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: io.opentelemetry.instrumentation:opentelemetry-instrumentation-bom
  dependency-version: 2.31.1
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: io.projectreactor:reactor-bom
  dependency-version: 2025.0.7
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: io.lettuce:lettuce-core
  dependency-version: 7.7.0.RELEASE
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: com.google.protobuf:protobuf-bom
  dependency-version: 4.36.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: software.amazon.awssdk:bom
  dependency-version: 2.54.5
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: io.micrometer:micrometer-bom
  dependency-version: 1.17.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: io.opentelemetry.instrumentation:opentelemetry-instrumentation-bom
  dependency-version: 2.31.1
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: io.projectreactor:reactor-bom
  dependency-version: 2025.0.7
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: io.lettuce:lettuce-core
  dependency-version: 7.7.0.RELEASE
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: com.google.guava:guava
  dependency-version: 33.7.1-jre
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: com.google.protobuf:protobuf-bom
  dependency-version: 4.36.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: software.amazon.awssdk:bom
  dependency-version: 2.54.5
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: io.micrometer:micrometer-bom
  dependency-version: 1.17.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: io.opentelemetry.instrumentation:opentelemetry-instrumentation-bom
  dependency-version: 2.31.1
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: io.projectreactor:reactor-bom
  dependency-version: 2025.0.7
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: io.lettuce:lettuce-core
  dependency-version: 7.7.0.RELEASE
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: com.google.guava:guava
  dependency-version: 33.7.1-jre
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: io.lettuce:lettuce-core
  dependency-version: 7.7.0.RELEASE
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: com.google.guava:guava
  dependency-version: 33.7.1-jre
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: com.google.protobuf:protobuf-bom
  dependency-version: 4.36.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: software.amazon.awssdk:bom
  dependency-version: 2.54.5
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: io.micrometer:micrometer-bom
  dependency-version: 1.17.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: io.opentelemetry.instrumentation:opentelemetry-instrumentation-bom
  dependency-version: 2.31.1
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: io.projectreactor:reactor-bom
  dependency-version: 2025.0.7
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: com.google.guava:guava
  dependency-version: 33.7.1-jre
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: com.google.protobuf:protobuf-bom
  dependency-version: 4.36.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: software.amazon.awssdk:bom
  dependency-version: 2.54.5
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: io.micrometer:micrometer-bom
  dependency-version: 1.17.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: io.opentelemetry.instrumentation:opentelemetry-instrumentation-bom
  dependency-version: 2.31.1
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: io.projectreactor:reactor-bom
  dependency-version: 2025.0.7
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: io.lettuce:lettuce-core
  dependency-version: 7.7.0.RELEASE
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-08-27 17:36:45 -04:00
Jon Chambers d1ec5d7d9c More explicitly link TOTP key length with the TOTP HMAC algorithm 2026-08-27 17:35:05 -04:00
Ravi Khadiwala c09e167f3f Don't forward exception messages in unavailable statuses 2026-08-26 15:03:45 -05:00
Ravi Khadiwala eaa3c5f20f Remove GrpcExceptionMapper 2026-08-26 15:03:45 -05:00
Jon Chambers eb0ffb0c4d Preserve TOTP keys when reclaiming accounts 2026-08-26 16:01:00 -04:00
Jon Chambers 31b34ed06f Add a missing @Test annotation 2026-08-26 15:58:13 -04:00
Jon Chambers b247fc24c1 Use a TOTP algorithm supported by a wider range of authenticator apps 2026-08-26 15:57:41 -04:00
Ravi Khadiwala 56a91f104e Use exact path matchers in the omnibus 2026-08-26 14:56:59 -05:00
Ravi Khadiwala 461fce800a Remove test-only Subscriptions method 2026-08-26 14:56:36 -05:00
Ameya Lokare 7f08e8bf4e Fix overflow when calculating chunk size in ClearOrphanedFoundationDbQueuesCommand 2026-08-26 09:37:57 -07:00
314 changed files with 10289 additions and 4044 deletions

No files matched your search

+7 -6
View File
@@ -12,16 +12,17 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5.7.0
- name: Install APT packages
run: |
sudo apt-get update
# setup-java requires gpg
sudo apt-get install -y protobuf-compiler gpg
pip install sabledocs
- uses: actions/setup-java@de7274f081f381c8f8158605e0321c36c376e2e6 # v6.0.1
with:
distribution: 'temurin'
java-version-file: .java-version
cache: 'maven'
- name: Install gRPC documentation tooling
run: |
sudo apt-get update
sudo apt-get install -y protobuf-compiler
pip install sabledocs
- name: Generate OpenAPI documentation
run: ./mvnw compile
- name: Generate gRPC documentation
+7 -2
View File
@@ -20,12 +20,17 @@ jobs:
issues: write
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5.7.0
- name: Install APT packages
run: |
# setup-java requires gpg
sudo apt update
sudo apt install -y gpg
- uses: actions/setup-java@de7274f081f381c8f8158605e0321c36c376e2e6 # v6.0.1
with:
distribution: 'temurin'
java-version-file: .java-version
cache: 'maven'
- uses: aws-actions/configure-aws-credentials@e6de054238d6b7531b4efff3b6587d9aade6a06c # v6.2.3
- uses: aws-actions/configure-aws-credentials@e1253824e5c10ff9df46874f81ed3ec929e19cfd # v6.3.0
name: Configure AWS credentials from Test account
with:
role-to-assume: ${{ vars.AWS_ROLE }}
+4 -4
View File
@@ -32,11 +32,11 @@ jobs:
- name: Install APT packages
# ca-certificates: required for AWS CRT client
run: |
# Add Docker's official GPG key:
apt update
apt install -y ca-certificates curl
# Maven Wrapper requires `unzip`; see https://github.com/apache/maven-wrapper/issues/425
apt install -y unzip
# setup-java requires gpg
apt install -y ca-certificates curl gpg unzip
# Add Docker's official GPG key:
install -m 0755 -d /etc/apt/keyrings
curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc
chmod a+r /etc/apt/keyrings/docker.asc
@@ -50,7 +50,7 @@ jobs:
# ca-certificates: required for AWS CRT client
apt update && apt install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin ca-certificates
- name: Set up JDK
uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5.7.0
uses: actions/setup-java@de7274f081f381c8f8158605e0321c36c376e2e6 # v6.0.1
with:
distribution: 'temurin'
java-version-file: .java-version
+1 -1
View File
@@ -1 +1 @@
temurin-25
temurin-26
+6
View File
@@ -36,6 +36,12 @@
<groupId>org.eclipse.jetty.http2</groupId>
<artifactId>jetty-http2-client-transport</artifactId>
</dependency>
<dependency>
<groupId>com.webauthn4j</groupId>
<artifactId>webauthn4j-test</artifactId>
<version>${webauthn4j.version}</version>
</dependency>
</dependencies>
<build>
@@ -1,101 +0,0 @@
/*
* Copyright 2023 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.signal.integration;
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 java.io.IOException;
import java.util.Base64;
import org.signal.libsignal.protocol.IdentityKey;
import org.signal.libsignal.protocol.ecc.ECPublicKey;
public final class Codecs {
private Codecs() {
// utility class
}
@FunctionalInterface
public interface CheckedFunction<T, R> {
R apply(T t) throws Exception;
}
public static class Base64BasedSerializer<T> extends JsonSerializer<T> {
private final CheckedFunction<T, byte[]> mapper;
public Base64BasedSerializer(final CheckedFunction<T, byte[]> mapper) {
this.mapper = mapper;
}
@Override
public void serialize(final T value, final JsonGenerator gen, final SerializerProvider serializers) throws IOException {
try {
gen.writeString(Base64.getEncoder().withoutPadding().encodeToString(mapper.apply(value)));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
public static class Base64BasedDeserializer<T> extends JsonDeserializer<T> {
private final CheckedFunction<byte[], T> mapper;
public Base64BasedDeserializer(final CheckedFunction<byte[], T> mapper) {
this.mapper = mapper;
}
@Override
public T deserialize(final JsonParser p, final DeserializationContext ctxt) throws IOException {
try {
return mapper.apply(Base64.getDecoder().decode(p.getValueAsString()));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
public static class ByteArraySerializer extends Base64BasedSerializer<byte[]> {
public ByteArraySerializer() {
super(bytes -> bytes);
}
}
public static class ByteArrayDeserializer extends Base64BasedDeserializer<byte[]> {
public ByteArrayDeserializer() {
super(bytes -> bytes);
}
}
public static class ECPublicKeySerializer extends Base64BasedSerializer<ECPublicKey> {
public ECPublicKeySerializer() {
super(ECPublicKey::serialize);
}
}
public static class ECPublicKeyDeserializer extends Base64BasedDeserializer<ECPublicKey> {
public ECPublicKeyDeserializer() {
super(ECPublicKey::new);
}
}
public static class IdentityKeySerializer extends Base64BasedSerializer<IdentityKey> {
public IdentityKeySerializer() {
super(IdentityKey::serialize);
}
}
public static class IdentityKeyDeserializer extends Base64BasedDeserializer<IdentityKey> {
public IdentityKeyDeserializer() {
super(bytes -> new IdentityKey(bytes, 0));
}
}
}
@@ -10,20 +10,41 @@ import static java.util.Objects.requireNonNull;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.io.Resources;
import com.google.common.net.HttpHeaders;
import com.webauthn4j.data.AuthenticatorAssertionResponse;
import com.webauthn4j.data.PublicKeyCredential;
import com.webauthn4j.data.PublicKeyCredentialDescriptor;
import com.webauthn4j.data.PublicKeyCredentialRequestOptions;
import com.webauthn4j.data.PublicKeyCredentialType;
import com.webauthn4j.data.UserVerificationRequirement;
import com.webauthn4j.data.client.challenge.DefaultChallenge;
import com.webauthn4j.test.client.ClientPlatform;
import io.dropwizard.configuration.ConfigurationValidationException;
import io.dropwizard.jersey.validation.Validators;
import io.grpc.ChannelCredentials;
import io.grpc.ClientInterceptor;
import io.grpc.Grpc;
import io.grpc.ManagedChannel;
import io.grpc.Metadata;
import io.grpc.TlsChannelCredentials;
import io.grpc.stub.MetadataUtils;
import jakarta.validation.ConstraintViolation;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.lang.invoke.MethodHandles;
import java.net.URI;
import java.net.URL;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
import java.util.List;
@@ -32,6 +53,7 @@ import java.util.Optional;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import org.apache.commons.lang3.tuple.Pair;
@@ -43,6 +65,7 @@ import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.eclipse.jetty.websocket.client.ClientUpgradeRequest;
import org.eclipse.jetty.websocket.client.WebSocketClient;
import org.signal.integration.config.Config;
import org.signal.integration.config.WebAuthnConfiguration;
import org.signal.libsignal.protocol.IdentityKey;
import org.signal.libsignal.protocol.ecc.ECKeyPair;
import org.signal.libsignal.protocol.ecc.ECPublicKey;
@@ -58,6 +81,7 @@ import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialPresentation;
import org.signal.libsignal.zkgroup.receipts.ReceiptSerial;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.auth.grpc.RequireAuthenticationInterceptor;
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
import org.whispersystems.textsecuregcm.entities.AccountIdentityResponse;
import org.whispersystems.textsecuregcm.entities.DeviceActivationRequest;
@@ -65,11 +89,15 @@ import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
import org.whispersystems.textsecuregcm.entities.RegistrationRequest;
import org.whispersystems.textsecuregcm.http.FaultTolerantHttpClient;
import org.whispersystems.textsecuregcm.mappers.MfaFailureExceptionMapper;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.TotpManager;
import org.whispersystems.textsecuregcm.util.CertificateUtil;
import org.whispersystems.textsecuregcm.util.HeaderUtils;
import org.whispersystems.textsecuregcm.util.HttpUtils;
import org.whispersystems.textsecuregcm.util.SystemMapper;
import org.whispersystems.textsecuregcm.util.ThrowingSupplier;
import org.whispersystems.textsecuregcm.util.Util;
public final class Operations {
@@ -77,6 +105,8 @@ public final class Operations {
private static final Config CONFIG = loadConfigFromClasspath("config.yml");
private static final String GRPC_DOMAIN = "grpc." + CONFIG.domain();
private static final IntegrationTools INTEGRATION_TOOLS = IntegrationTools.create(CONFIG);
private static final String USER_AGENT = "integration-test";
@@ -85,6 +115,7 @@ public final class Operations {
private static final WebSocketClient WEB_SOCKET_CLIENT = buildWebSocketClient();
private static final ManagedChannel GRPC_CHANNEL = buildGrpcChannel();
private Operations() {
// utility class
@@ -99,6 +130,10 @@ public final class Operations {
);
}
public static WebAuthnConfiguration getWebAuthnConfiguration() {
return CONFIG.webAuthn();
}
public static TestUser registerNumberlessUser(final ReceiptCredential receiptCredential)
throws InvalidInputException, VerificationFailedException {
final String accountPassword = Base64.getEncoder().encodeToString(randomBytes(32));
@@ -113,6 +148,7 @@ public final class Operations {
null,
receiptCredentialPresentation.serialize(),
null,
null,
user.accountAttributes(),
true,
new IdentityKey(aciIdentityKeyPair.getPublicKey()),
@@ -133,6 +169,119 @@ public final class Operations {
return user;
}
public static TestUser recoverNumberlessUserWithTotp(final TestUser testUser, final ThrowingSupplier<Integer, InvalidKeyException> totpSupplier) throws InvalidKeyException {
final TestUser recoveredUser = TestUser.createNumberlessForRecovery(testUser.accountPassword(), testUser.registrationPassword());
final ECKeyPair aciIdentityKeyPair = ECKeyPair.generate();
final ECKeyPair pniIdentityKeyPair = ECKeyPair.generate();
final DeviceActivationRequest deviceActivationRequest = new DeviceActivationRequest(
generateSignedECPreKey(1, aciIdentityKeyPair),
Optional.of(generateSignedECPreKey(2, pniIdentityKeyPair)),
generateSignedKEMPreKey(3, aciIdentityKeyPair),
Optional.of(generateSignedKEMPreKey(4, pniIdentityKeyPair)),
Optional.empty(),
Optional.empty());
// The server only allows one redemption of a TOTP per time-step, which we may have used up during `confirm`. Retry
// until the next time-step.
final Instant retryUntil = Instant.now().plus(TotpManager.TOTP.getTimeStep().plus(Duration.ofSeconds(1)));
while (true) {
final Pair<Integer, AccountIdentityResponse> registrationResponse = apiPost("/v1/registration",
new RegistrationRequest(null,
testUser.registrationPassword(),
null,
totpSupplier.get(),
null,
recoveredUser.accountAttributes(),
true,
new IdentityKey(aciIdentityKeyPair.getPublicKey()),
new IdentityKey(pniIdentityKeyPair.getPublicKey()),
deviceActivationRequest))
// For a numberless account recovery, the username is the ACI
.authorized(testUser.aciUuid().toString(), testUser.accountPassword())
.execute(AccountIdentityResponse.class);
if (registrationResponse.getLeft() == 441 && Instant.now().isBefore(retryUntil)) {
Util.sleep(Duration.ofSeconds(1).toMillis());
continue;
}
Validate.isTrue(HttpUtils.isSuccessfulResponse(registrationResponse.getLeft()),
"Unexpected response code: %d", registrationResponse.getLeft());
recoveredUser.setAciUuid(registrationResponse.getRight().uuid());
return recoveredUser;
}
}
public static TestUser recoverNumberlessUserWithWebAuthn(final TestUser testUser,
final ClientPlatform clientPlatform,
final byte[] credentialId,
final String relyingPartyId) {
final TestUser recoveredUser = TestUser.createNumberlessForRecovery(testUser.accountPassword(), testUser.registrationPassword());
final ECKeyPair aciIdentityKeyPair = ECKeyPair.generate();
final ECKeyPair pniIdentityKeyPair = ECKeyPair.generate();
final RegistrationRequest initialRequest = new RegistrationRequest(null,
testUser.registrationPassword(),
null,
null,
null,
recoveredUser.accountAttributes(),
true,
new IdentityKey(aciIdentityKeyPair.getPublicKey()),
new IdentityKey(pniIdentityKeyPair.getPublicKey()),
new DeviceActivationRequest(generateSignedECPreKey(1, aciIdentityKeyPair),
Optional.of(generateSignedECPreKey(2, pniIdentityKeyPair)),
generateSignedKEMPreKey(3, aciIdentityKeyPair),
Optional.of(generateSignedKEMPreKey(4, pniIdentityKeyPair)),
Optional.empty(),
Optional.empty()));
final Pair<Integer, MfaFailureExceptionMapper.MfaFailureResponse> initialResponse = apiPost("/v1/registration", initialRequest)
// For a numberless account recovery, the username is the ACI
.authorized(testUser.aciUuid().toString(), testUser.accountPassword())
.execute(MfaFailureExceptionMapper.MfaFailureResponse.class);
// we expect (and need) failure with status 441, which will contain the WebAuthn challenge
assert initialResponse.getLeft() == 441;
final MfaFailureExceptionMapper.MfaFailureResponse mfaFailureResponse = initialResponse.getRight();
assert mfaFailureResponse.webAuthnParameters().allowedCredentialIds()
.stream()
.anyMatch(allowedId -> Arrays.equals(allowedId, credentialId));
final PublicKeyCredential<AuthenticatorAssertionResponse, ?> credential =
clientPlatform.get(new PublicKeyCredentialRequestOptions(
new DefaultChallenge(mfaFailureResponse.webAuthnParameters().challenge()),
null,
relyingPartyId,
List.of(new PublicKeyCredentialDescriptor(PublicKeyCredentialType.PUBLIC_KEY, credentialId, null)),
UserVerificationRequirement.DISCOURAGED,
null));
final RegistrationRequest registrationRequest = new RegistrationRequest(null,
testUser.registrationPassword(),
null,
null,
webAuthnVerificationResponseJson(credential),
recoveredUser.accountAttributes(),
true,
new IdentityKey(aciIdentityKeyPair.getPublicKey()),
new IdentityKey(pniIdentityKeyPair.getPublicKey()),
new DeviceActivationRequest(generateSignedECPreKey(1, aciIdentityKeyPair),
Optional.of(generateSignedECPreKey(2, pniIdentityKeyPair)),
generateSignedKEMPreKey(3, aciIdentityKeyPair),
Optional.of(generateSignedKEMPreKey(4, pniIdentityKeyPair)),
Optional.empty(),
Optional.empty()));
final AccountIdentityResponse registrationResponse = apiPost("/v1/registration", registrationRequest)
// For a numberless account recovery, the username is the ACI
.authorized(testUser.aciUuid().toString(), testUser.accountPassword())
.executeExpectSuccess(AccountIdentityResponse.class);
recoveredUser.setAciUuid(registrationResponse.uuid());
return recoveredUser;
}
public static TestUser newRegisteredUser(final String number) {
final byte[] registrationPassword = populateRandomRecoveryPassword(number);
final String accountPassword = Base64.getEncoder().encodeToString(randomBytes(32));
@@ -148,6 +297,7 @@ public final class Operations {
registrationPassword,
null,
null,
null,
accountAttributes,
true,
new IdentityKey(aciIdentityKeyPair.getPublicKey()),
@@ -239,7 +389,7 @@ public final class Operations {
}
}
private static byte[] randomBytes(int numBytes) {
public static byte[] randomBytes(final int numBytes) {
final byte[] bytes = new byte[numBytes];
new SecureRandom().nextBytes(bytes);
return bytes;
@@ -272,6 +422,33 @@ public final class Operations {
return URI.create("https://" + CONFIG.domain() + endpoint + query);
}
public static ManagedChannel grpcChannel() {
return GRPC_CHANNEL;
}
public static ClientInterceptor authorizationInterceptor(final TestUser user, final byte deviceId) {
final String username = "%s.%d".formatted(user.aciUuid().toString(), deviceId);
final Metadata metadata = new Metadata();
metadata.put(RequireAuthenticationInterceptor.AUTHORIZATION_METADATA_KEY,
HeaderUtils.basicAuthHeader(username, user.accountPassword()));
return MetadataUtils.newAttachHeadersInterceptor(metadata);
}
private static ManagedChannel buildGrpcChannel() {
try {
final ByteArrayInputStream rootCert =
new ByteArrayInputStream(CONFIG.rootCert().getBytes(StandardCharsets.UTF_8));
final ChannelCredentials credentials = TlsChannelCredentials.newBuilder().trustManager(rootCert).build();
return Grpc.newChannelBuilderForAddress(GRPC_DOMAIN, 443, credentials)
.userAgent(USER_AGENT)
.build();
} catch (final IOException e) {
throw new UncheckedIOException(e);
}
}
public static class RequestBuilder {
private final HttpRequest.Builder builder;
@@ -322,33 +499,39 @@ public final class Operations {
}
public Pair<Integer, Void> executeExpectSuccess() {
final Pair<Integer, Void> execute = execute();
final RawResponse response = executeRaw();
Validate.isTrue(
HttpUtils.isSuccessfulResponse(execute.getLeft()),
"Unexpected response code: %d",
execute.getLeft());
return execute;
HttpUtils.isSuccessfulResponse(response.statusCode()),
"Unexpected response code: %d, body: %s",
response.statusCode(), response.body());
return Pair.of(response.statusCode(), null);
}
public <T> T executeExpectSuccess(final Class<T> expectedType) {
final Pair<Integer, T> execute = execute(expectedType);
final RawResponse response = executeRaw();
Validate.isTrue(
HttpUtils.isSuccessfulResponse(execute.getLeft()),
"Unexpected response code: %d : %s",
execute.getLeft(), execute.getRight());
return requireNonNull(execute.getRight());
HttpUtils.isSuccessfulResponse(response.statusCode()),
"Unexpected response code: %d, body: %s",
response.statusCode(), response.body());
return requireNonNull(parseBody(response.body(), expectedType));
}
public void executeExpectStatusCode(final int expectedStatusCode) {
final Pair<Integer, Void> execute = execute(Void.class);
final RawResponse response = executeRaw();
Validate.isTrue(
execute.getLeft() == expectedStatusCode,
"Unexpected response code: %d",
execute.getLeft()
);
response.statusCode() == expectedStatusCode,
"Unexpected response code: %d (expected %d), body: %s",
response.statusCode(), expectedStatusCode, response.body());
}
public <T> Pair<Integer, T> execute(final Class<T> expectedType) {
final RawResponse response = executeRaw();
return Pair.of(response.statusCode(), parseBody(response.body(), expectedType));
}
private record RawResponse(int statusCode, String body) {}
private RawResponse executeRaw() {
builder.uri(serverUri(endpoint, queryParams))
.header(HttpHeaders.USER_AGENT, USER_AGENT);
return CLIENT.sendAsync(builder.build(), HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8))
@@ -358,19 +541,24 @@ public final class Operations {
error.printStackTrace();
}
})
.thenApply(response -> {
try {
final T result = expectedType.equals(Void.class)
? null
: SystemMapper.jsonMapper().readValue(response.body(), expectedType);
return Pair.of(response.statusCode(), result);
} catch (final IOException e) {
throw new RuntimeException(e);
}
})
.thenApply(response -> new RawResponse(response.statusCode(), response.body()))
.join();
}
@Nullable
private static <T> T parseBody(final String body, final Class<T> expectedType) {
if (expectedType.equals(Void.class)) {
return null;
}
try {
return SystemMapper.jsonMapper().readValue(body, expectedType);
} catch (final IOException e) {
throw new RuntimeException(
"Could not parse response body as %s, body: %s".formatted(expectedType.getSimpleName(), body), e);
}
}
}
private static FaultTolerantHttpClient buildClient() {
@@ -416,7 +604,7 @@ public final class Operations {
final String path,
final Map<String, String> headers) throws IOException {
final URI uri = URI.create("wss://grpc." + CONFIG.domain() + path);
final URI uri = URI.create("wss://" + GRPC_DOMAIN + path);
final ClientUpgradeRequest request = new ClientUpgradeRequest(uri);
headers.forEach(request::setHeader);
@@ -466,4 +654,34 @@ public final class Operations {
throw new RuntimeException(e);
}
}
/// Serializes an assertion into the [specification](https://www.w3.org/TR/webauthn/#dictdef-authenticationresponsejson) format.
static String webAuthnVerificationResponseJson(final PublicKeyCredential<AuthenticatorAssertionResponse, ?> credential) {
final AuthenticatorAssertionResponse response = credential.getResponse();
return """
{
"id": "%s",
"rawId": "%s",
"type": "public-key",
"clientExtensionResults": {},
"response": {
"clientDataJSON": "%s",
"authenticatorData": "%s",
"signature": "%s",
"userHandle": %s
}
}
""".formatted(
base64Url(credential.getRawId()),
base64Url(credential.getRawId()),
base64Url(response.getClientDataJSON()),
base64Url(response.getAuthenticatorData()),
base64Url(response.getSignature()),
response.getUserHandle() == null ? "null" : "\"" + base64Url(response.getUserHandle()) + "\"");
}
private static String base64Url(@Nullable final byte[] bytes) {
return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
}
}
@@ -1,61 +0,0 @@
/*
* Copyright 2023 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.signal.integration;
import jakarta.annotation.Nullable;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.commons.lang3.tuple.Pair;
import org.signal.libsignal.protocol.IdentityKeyPair;
import org.signal.libsignal.protocol.ecc.ECKeyPair;
import org.signal.libsignal.protocol.state.SignedPreKeyRecord;
public class TestDevice {
private final byte deviceId;
private final Map<Integer, Pair<IdentityKeyPair, SignedPreKeyRecord>> signedPreKeys = new ConcurrentHashMap<>();
public static TestDevice create(
final byte deviceId,
final IdentityKeyPair aciIdentityKeyPair,
@Nullable final IdentityKeyPair pniIdentityKeyPair) {
final TestDevice device = new TestDevice(deviceId);
device.addSignedPreKey(aciIdentityKeyPair);
if (pniIdentityKeyPair != null) {
device.addSignedPreKey(pniIdentityKeyPair);
}
return device;
}
public TestDevice(final byte deviceId) {
this.deviceId = deviceId;
}
public byte deviceId() {
return deviceId;
}
public SignedPreKeyRecord latestSignedPreKey(final IdentityKeyPair identity) {
final int id = signedPreKeys.entrySet()
.stream()
.filter(p -> p.getValue().getLeft().equals(identity))
.mapToInt(Map.Entry::getKey)
.max()
.orElseThrow();
return signedPreKeys.get(id).getRight();
}
public SignedPreKeyRecord addSignedPreKey(final IdentityKeyPair identity) {
final int nextId = signedPreKeys.keySet().stream().mapToInt(k -> k + 1).max().orElse(0);
final ECKeyPair keyPair = ECKeyPair.generate();
final byte[] signature = keyPair.getPrivateKey().calculateSignature(keyPair.getPublicKey().serialize());
final SignedPreKeyRecord signedPreKeyRecord = new SignedPreKeyRecord(nextId, System.currentTimeMillis(), keyPair, signature);
signedPreKeys.put(nextId, Pair.of(identity, signedPreKeyRecord));
return signedPreKeyRecord;
}
}
@@ -5,29 +5,15 @@
package org.signal.integration;
import static java.util.Objects.requireNonNull;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import java.security.SecureRandom;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.security.SecureRandom;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import org.signal.libsignal.protocol.IdentityKey;
import org.signal.libsignal.protocol.IdentityKeyPair;
import org.signal.libsignal.protocol.InvalidKeyException;
import org.signal.libsignal.protocol.ecc.ECPublicKey;
import org.signal.libsignal.protocol.state.SignedPreKeyRecord;
import javax.annotation.Nullable;
import org.signal.libsignal.protocol.util.KeyHelper;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import javax.annotation.Nullable;
public class TestUser {
@@ -36,21 +22,14 @@ public class TestUser {
@Nullable
private final Integer pniRegistrationId;
private final IdentityKeyPair aciIdentityKey;
private final Map<Byte, TestDevice> devices = new ConcurrentHashMap<>();
private final byte[] unidentifiedAccessKey;
@Nullable
private String phoneNumber;
private final String phoneNumber;
@Nullable
private IdentityKeyPair pniIdentityKey;
private final String accountPassword;
private String accountPassword;
private byte[] registrationPassword;
private final byte[] registrationPassword;
private UUID aciUuid;
@@ -58,40 +37,44 @@ public class TestUser {
private UUID pniUuid;
public static TestUser createNumberless(final String accountPassword, final byte[] accountRecoveryPassword) {
final IdentityKeyPair aciIdentityKey = IdentityKeyPair.generate();
final int registrationId = KeyHelper.generateRegistrationId(false);
final byte[] unidentifiedAccessKey = new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH];
new SecureRandom().nextBytes(unidentifiedAccessKey);
final byte[] unidentifiedAccessKey = Operations.randomBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
return new TestUser(
registrationId,
null,
aciIdentityKey,
null,
null,
unidentifiedAccessKey,
accountPassword,
accountRecoveryPassword);
}
public static TestUser createNumberlessForRecovery(final String accountPassword, final byte[] accountRecoveryPassword) {
// Recovering a numberless account requires PNI keys (though they are discarded by the server)
final int registrationId = KeyHelper.generateRegistrationId(false);
final int pniRegistrationId = KeyHelper.generateRegistrationId(false);
final byte[] unidentifiedAccessKey = new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH];
new SecureRandom().nextBytes(unidentifiedAccessKey);
return new TestUser(
registrationId,
pniRegistrationId,
null,
unidentifiedAccessKey,
accountPassword,
accountRecoveryPassword);
}
public static TestUser create(final String phoneNumber, final String accountPassword, final byte[] registrationPassword) {
// ACI identity key pair
final IdentityKeyPair aciIdentityKey = IdentityKeyPair.generate();
// PNI identity key pair
final IdentityKeyPair pniIdentityKey = IdentityKeyPair.generate();
// registration id
final int registrationId = KeyHelper.generateRegistrationId(false);
final int pniRegistrationId = KeyHelper.generateRegistrationId(false);
// uak
final byte[] unidentifiedAccessKey = new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH];
new SecureRandom().nextBytes(unidentifiedAccessKey);
return new TestUser(
registrationId,
pniRegistrationId,
aciIdentityKey,
phoneNumber,
pniIdentityKey,
unidentifiedAccessKey,
accountPassword,
registrationPassword);
@@ -100,39 +83,26 @@ public class TestUser {
public TestUser(
final int registrationId,
@Nullable final Integer pniRegistrationId,
final IdentityKeyPair aciIdentityKey,
@Nullable final String phoneNumber,
@Nullable final IdentityKeyPair pniIdentityKey,
final byte[] unidentifiedAccessKey,
final String accountPassword,
final byte[] registrationPassword) {
this.registrationId = registrationId;
this.pniRegistrationId = pniRegistrationId;
this.aciIdentityKey = aciIdentityKey;
this.phoneNumber = phoneNumber;
this.pniIdentityKey = pniIdentityKey;
this.unidentifiedAccessKey = unidentifiedAccessKey;
this.accountPassword = accountPassword;
this.registrationPassword = registrationPassword;
devices.put(Device.PRIMARY_ID, TestDevice.create(Device.PRIMARY_ID, aciIdentityKey, pniIdentityKey));
}
public int registrationId() {
return registrationId;
}
public IdentityKeyPair aciIdentityKey() {
return aciIdentityKey;
}
public Optional<String> phoneNumber() {
return Optional.ofNullable(phoneNumber);
}
public Optional<IdentityKeyPair> pniIdentityKey() {
return Optional.ofNullable(pniIdentityKey);
}
public String accountPassword() {
return accountPassword;
}
@@ -151,9 +121,8 @@ public class TestUser {
public AccountAttributes accountAttributes() {
return new AccountAttributes(true, registrationId, pniRegistrationId, "".getBytes(StandardCharsets.UTF_8), "", true,
DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES, null)
.setUnidentifiedAccessKey(unidentifiedAccessKey)
.setRecoveryPassword(registrationPassword);
DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES, registrationPassword)
.setUnidentifiedAccessKey(unidentifiedAccessKey);
}
public void setAciUuid(final UUID aciUuid) {
@@ -163,59 +132,4 @@ public class TestUser {
public void setPniUuid(@Nullable final UUID pniUuid) {
this.pniUuid = pniUuid;
}
public void setPhoneNumber(@Nullable final String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public void setPniIdentityKey(@Nullable final IdentityKeyPair pniIdentityKey) {
this.pniIdentityKey = pniIdentityKey;
}
public void setAccountPassword(final String accountPassword) {
this.accountPassword = accountPassword;
}
public void setRegistrationPassword(final byte[] registrationPassword) {
this.registrationPassword = registrationPassword;
}
public PreKeySetPublicView preKeys(final byte deviceId, final boolean pni) {
final IdentityKeyPair identity = pni
? pniIdentityKey
: aciIdentityKey;
final TestDevice device = requireNonNull(devices.get(deviceId));
final SignedPreKeyRecord signedPreKeyRecord = device.latestSignedPreKey(identity);
try {
return new PreKeySetPublicView(
Collections.emptyList(),
identity.getPublicKey(),
new SignedPreKeyPublicView(
signedPreKeyRecord.getId(),
signedPreKeyRecord.getKeyPair().getPublicKey(),
signedPreKeyRecord.getSignature()
)
);
} catch (InvalidKeyException e) {
throw new RuntimeException(e);
}
}
public record SignedPreKeyPublicView(
int keyId,
@JsonSerialize(using = Codecs.ECPublicKeySerializer.class)
@JsonDeserialize(using = Codecs.ECPublicKeyDeserializer.class)
ECPublicKey publicKey,
@JsonSerialize(using = Codecs.ByteArraySerializer.class)
@JsonDeserialize(using = Codecs.ByteArrayDeserializer.class)
byte[] signature) {
}
public record PreKeySetPublicView(
List<String> preKeys,
@JsonSerialize(using = Codecs.IdentityKeySerializer.class)
@JsonDeserialize(using = Codecs.IdentityKeyDeserializer.class)
IdentityKey identityKey,
SignedPreKeyPublicView signedPreKey) {
}
}
@@ -18,5 +18,6 @@ public record Config(@NotBlank String domain,
@NotBlank String prescribedRegistrationCode,
@NotBlank String prescribedReceiptSerial,
@NotBlank String prescribedReceiptCredential,
@NotBlank String serverZkPublicParams) {
@NotBlank String serverZkPublicParams,
@NotNull @Valid WebAuthnConfiguration webAuthn) {
}
@@ -0,0 +1,13 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.signal.integration.config;
import jakarta.validation.constraints.NotBlank;
public record WebAuthnConfiguration(
@NotBlank String relyingPartyId,
@NotBlank String origin) {
}
@@ -5,18 +5,61 @@
package org.signal.integration;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.eatthepath.otp.TimeBasedOneTimePasswordGenerator;
import com.google.protobuf.ByteString;
import com.webauthn4j.data.AttestationConveyancePreference;
import com.webauthn4j.data.AuthenticatorAttestationResponse;
import com.webauthn4j.data.AuthenticatorSelectionCriteria;
import com.webauthn4j.data.PublicKeyCredential;
import com.webauthn4j.data.PublicKeyCredentialCreationOptions;
import com.webauthn4j.data.PublicKeyCredentialParameters;
import com.webauthn4j.data.PublicKeyCredentialRpEntity;
import com.webauthn4j.data.PublicKeyCredentialType;
import com.webauthn4j.data.PublicKeyCredentialUserEntity;
import com.webauthn4j.data.ResidentKeyRequirement;
import com.webauthn4j.data.UserVerificationRequirement;
import com.webauthn4j.data.attestation.statement.COSEAlgorithmIdentifier;
import com.webauthn4j.data.client.Origin;
import com.webauthn4j.data.client.challenge.DefaultChallenge;
import com.webauthn4j.test.EmulatorUtil;
import com.webauthn4j.test.authenticator.webauthn.WebAuthnAuthenticatorAdaptor;
import com.webauthn4j.test.client.ClientPlatform;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.Duration;
import java.time.Instant;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.http.HttpStatus;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.signal.chat.account.AccountsGrpc;
import org.signal.chat.account.ConfirmTotpKeyRequest;
import org.signal.chat.account.ConfirmTotpKeyResponse;
import org.signal.chat.account.FinishWebAuthnRegistrationRequest;
import org.signal.chat.account.FinishWebAuthnRegistrationResponse;
import org.signal.chat.account.GenerateTotpKeyRequest;
import org.signal.chat.account.GenerateTotpKeyResponse;
import org.signal.chat.account.ListMfaKeysRequest;
import org.signal.chat.account.ListMfaKeysResponse;
import org.signal.chat.account.StartWebAuthnRegistrationRequest;
import org.signal.chat.account.StartWebAuthnRegistrationResponse;
import org.signal.chat.account.TotpParameters;
import org.signal.integration.config.WebAuthnConfiguration;
import org.signal.libsignal.protocol.IdentityKey;
import org.signal.libsignal.protocol.ecc.ECKeyPair;
import org.signal.libsignal.usernames.BaseUsernameException;
@@ -39,18 +82,149 @@ public class AccountTest {
public void testCreateNumberlessAccount()
throws VerificationFailedException, InvalidInputException {
final Operations.Receipt receipt = Operations.getPrescribedReceipt();
final TestUser user = Operations.registerNumberlessUser(receipt.credential());
Operations.deleteReceipt(receipt.serial());
TestUser user = null;
try {
user = Operations.registerNumberlessUser(receipt.credential());
final Pair<Integer, AccountIdentityResponse> execute = Operations.apiGet("/v1/accounts/whoami")
.authorized(user)
.execute(AccountIdentityResponse.class);
assertEquals(HttpStatus.SC_OK, execute.getLeft());
} finally {
Operations.deleteReceipt(receipt.serial());
Operations.deleteUser(user);
if (user != null) {
Operations.deleteUser(user);
}
}
}
@Nested
class RecoverWithMfa {
private TestUser user;
@BeforeEach
void setup() throws InvalidInputException, VerificationFailedException {
final Operations.Receipt receipt = Operations.getPrescribedReceipt();
// Clear receipt state in case a previous run had an unclean failure
Operations.deleteReceipt(receipt.serial());
user = Operations.registerNumberlessUser(receipt.credential());
}
@AfterEach
void teardown() throws InvalidInputException {
final Operations.Receipt receipt = Operations.getPrescribedReceipt();
Operations.deleteReceipt(receipt.serial());
if (user != null) {
Operations.deleteUser(user);
}
}
@Test
public void testRecoverWithTotp() throws NoSuchAlgorithmException, InvalidKeyException {
final GenerateTotpKeyResponse generateTotpKeyResponse =
getAccountsStubForUser(user).generateTotpKey(GenerateTotpKeyRequest.getDefaultInstance());
assertEquals(GenerateTotpKeyResponse.ResponseCase.KEY_GENERATED, generateTotpKeyResponse.getResponseCase());
final TotpParameters totpParameters = generateTotpKeyResponse.getKeyGenerated().getTotpParameters();
final TimeBasedOneTimePasswordGenerator totpGenerator = new TimeBasedOneTimePasswordGenerator(
Duration.ofSeconds(totpParameters.getTimeStepSeconds()),
totpParameters.getPasswordLength(),
totpParameters.getAlgorithm());
final SecretKey totpKey = new SecretKeySpec(
generateTotpKeyResponse.getKeyGenerated().getKey().toByteArray(),
totpParameters.getAlgorithm());
final byte[] totpMetadata = Operations.randomBytes(160);
final ConfirmTotpKeyResponse confirmTotpKeyResponse = getAccountsStubForUser(user)
.confirmTotpKey(ConfirmTotpKeyRequest.newBuilder()
.setOneTimePassword(totpGenerator.generateOneTimePassword(totpKey, Instant.now()))
.setMetadataCiphertext(ByteString.copyFrom(totpMetadata))
.build());
assertEquals(ConfirmTotpKeyResponse.ResponseCase.KEY_CONFIRMED, confirmTotpKeyResponse.getResponseCase());
final int keyId = confirmTotpKeyResponse.getKeyConfirmed().getKeyId();
final TestUser recoveredUser = Operations.recoverNumberlessUserWithTotp(user, () ->
totpGenerator.generateOneTimePassword(totpKey, Instant.now()));
assertEquals(user.aciUuid(), recoveredUser.aciUuid());
// MFA key should remain set after re-registration
final Map<Integer, ListMfaKeysResponse.MfaKeyMetadata> mfaKeys =
getAccountsStubForUser(recoveredUser).listMfaKeys(ListMfaKeysRequest.getDefaultInstance()).getKeysMap();
assertEquals(1, mfaKeys.size());
assertTrue(mfaKeys.containsKey(keyId));
assertEquals(ListMfaKeysResponse.MfaKeyMetadata.MfaKeyType.MFA_KEY_TYPE_TOTP, mfaKeys.get(keyId).getType());
assertArrayEquals(totpMetadata, mfaKeys.get(keyId).getMetadataCiphertext().toByteArray());
}
@Test
public void testRecoverWithWebAuthn() {
final WebAuthnConfiguration webAuthnConfiguration = Operations.getWebAuthnConfiguration();
final ClientPlatform clientPlatform = new ClientPlatform(new Origin(webAuthnConfiguration.origin()), new WebAuthnAuthenticatorAdaptor(EmulatorUtil.NONE_ATTESTATION_AUTHENTICATOR));
final COSEAlgorithmIdentifier algorithm = COSEAlgorithmIdentifier.ES256;
final StartWebAuthnRegistrationResponse startWebAuthnRegistrationResponse =
getAccountsStubForUser(user).startWebAuthnRegistration(StartWebAuthnRegistrationRequest.getDefaultInstance());
assertEquals(StartWebAuthnRegistrationResponse.ResponseCase.PARAMS,
startWebAuthnRegistrationResponse.getResponseCase());
final StartWebAuthnRegistrationResponse.WebAuthnCreateParameters webAuthnCreateParameters = startWebAuthnRegistrationResponse.getParams();
assertTrue(
webAuthnCreateParameters.getAllowedAlgorithmsList().contains(algorithm.getValue()));
final PublicKeyCredential<AuthenticatorAttestationResponse, ?> credential =
clientPlatform.create(new PublicKeyCredentialCreationOptions(
new PublicKeyCredentialRpEntity(webAuthnConfiguration.relyingPartyId(), "test"),
new PublicKeyCredentialUserEntity(webAuthnCreateParameters.getUserHandle().toByteArray(), "test", "test"),
new DefaultChallenge(),
List.of(new PublicKeyCredentialParameters(PublicKeyCredentialType.PUBLIC_KEY, algorithm)),
null,
List.of(),
new AuthenticatorSelectionCriteria(
null, false, ResidentKeyRequirement.DISCOURAGED, UserVerificationRequirement.DISCOURAGED),
AttestationConveyancePreference.NONE,
null));
final byte[] metadataCiphertext = Operations.randomBytes(160);
final FinishWebAuthnRegistrationResponse finishWebAuthnRegistrationResponse = getAccountsStubForUser(user)
.finishWebAuthnRegistration(FinishWebAuthnRegistrationRequest.newBuilder()
.setAttestationObject(ByteString.copyFrom(credential.getResponse().getAttestationObject()))
.setCollectedClientDataJsonBytes(ByteString.copyFrom(credential.getResponse().getClientDataJSON()))
.setMetadataCiphertext(ByteString.copyFrom(metadataCiphertext))
.build());
assertEquals(FinishWebAuthnRegistrationResponse.ResponseCase.KEY_CONFIRMED,
finishWebAuthnRegistrationResponse.getResponseCase());
final int keyId = finishWebAuthnRegistrationResponse.getKeyConfirmed().getKeyId();
final TestUser recoveredUser = Operations.recoverNumberlessUserWithWebAuthn(user, clientPlatform, credential.getRawId(),
webAuthnConfiguration.relyingPartyId());
assertEquals(user.aciUuid(), recoveredUser.aciUuid());
// MFA key should remain set after re-registration
final Map<Integer, ListMfaKeysResponse.MfaKeyMetadata> mfaKeys =
getAccountsStubForUser(recoveredUser).listMfaKeys(ListMfaKeysRequest.getDefaultInstance()).getKeysMap();
assertEquals(1, mfaKeys.size());
assertTrue(mfaKeys.containsKey(keyId));
assertEquals(ListMfaKeysResponse.MfaKeyMetadata.MfaKeyType.MFA_KEY_TYPE_WEBAUTHN, mfaKeys.get(keyId).getType());
assertArrayEquals(metadataCiphertext, mfaKeys.get(keyId).getMetadataCiphertext().toByteArray());
}
}
private static AccountsGrpc.AccountsBlockingStub getAccountsStubForUser(final TestUser user) {
return AccountsGrpc
.newBlockingStub(Operations.grpcChannel())
.withInterceptors(Operations.authorizationInterceptor(user, Device.PRIMARY_ID));
}
@Test
public void testCreateAccount() {
final TestUser user = Operations.newRegisteredUser("+19995550101");
+23 -15
View File
@@ -45,7 +45,7 @@
</modules>
<properties>
<aws.sdk2.version>2.51.4</aws.sdk2.version>
<aws.sdk2.version>2.54.7</aws.sdk2.version>
<braintree.version>3.53.0</braintree.version>
<commons-csv.version>1.14.1</commons-csv.version>
<commons-io.version>2.22.0</commons-io.version>
@@ -55,10 +55,10 @@
<foundationdb.version>7.3.76</foundationdb.version>
<foundationdb.api-version>730</foundationdb.api-version>
<foundationdb.client-library-sha256>af099848721d08904ff9e5d38fade0de24d92e86451ea491d9ab5ce84adcf62a</foundationdb.client-library-sha256>
<google-cloud-libraries.version>26.86.0</google-cloud-libraries.version>
<google-cloud-libraries.version>26.87.0</google-cloud-libraries.version>
<grpc.version>1.76.3</grpc.version> <!-- should be kept in sync with the value from Google libraries-bom -->
<gson.version>2.14.0</gson.version>
<guava.version>33.7.0-jre</guava.version>
<guava.version>33.7.1-jre</guava.version>
<!-- several libraries (AWS, Google Cloud) use Apache http components transitively, and we need to align them -->
<httpcore.version>4.4.16</httpcore.version>
<httpclient.version>4.5.14</httpclient.version>
@@ -71,25 +71,28 @@
<!-- dropwizard references a constant removed in 1.6. See also: dependabot.yml -->
<logback.version>1.5.38</logback.version>
<logback-access-common.version>2.0.15</logback-access-common.version>
<lettuce.version>7.6.0.RELEASE</lettuce.version>
<libphonenumber.version>9.0.37</libphonenumber.version>
<lettuce.version>7.8.0.RELEASE</lettuce.version>
<libphonenumber.version>9.0.38</libphonenumber.version>
<logstash.logback.version>9.0</logstash.logback.version>
<log4j-bom.version>2.26.1</log4j-bom.version>
<luajava.version>4.1.0</luajava.version>
<micrometer.version>1.17.0</micrometer.version>
<netty.version>4.2.17.Final</netty.version>
<micrometer.version>1.17.1</micrometer.version>
<netty.version>4.2.18.Final</netty.version>
<!-- netty-bom doesn't manage the BoringSSL uber-jar; keep in sync with netty's tcnative.version -->
<netty-tcnative.version>2.0.84.Final</netty-tcnative.version>
<!-- must be greater than or equal to the value from Google libraries-bom, see https://protobuf.dev/support/cross-version-runtime-guarantee/ -->
<!-- the latest 4.x should be fine https://central.sonatype.com/artifact/com.google.protobuf/protobuf-java/versions -->
<protobuf.version>4.35.1</protobuf.version>
<protobuf.version>4.36.0</protobuf.version>
<pushy.version>0.15.6</pushy.version>
<reactor-bom.version>2025.0.6</reactor-bom.version> <!-- 3.8.4, see https://github.com/reactor/reactor#bom-versioning-scheme -->
<reactor-bom.version>2025.0.7</reactor-bom.version> <!-- 3.8.4, see https://github.com/reactor/reactor#bom-versioning-scheme -->
<resilience4j.version>2.4.0</resilience4j.version>
<semver4j.version>3.1.0</semver4j.version>
<simple-grpc.version>0.2.1</simple-grpc.version>
<slf4j.version>2.0.18</slf4j.version>
<stripe.version>33.3.0</stripe.version>
<swagger.version>2.2.53</swagger.version>
<stripe.version>33.4.0</stripe.version>
<swagger.version>2.2.54</swagger.version>
<testcontainers.version>2.0.5</testcontainers.version>
<webauthn4j.version>0.31.9.RELEASE</webauthn4j.version>
<!-- images to use in tests via testcontainers -->
<dynamodb.image>amazon/dynamodb-local:3.3.1@sha256:ff89bd48ff32cd8d9be5fee8873b65b8854dc408f1afe881be6eb00247bc0dab</dynamodb.image>
@@ -97,7 +100,7 @@
<redis.image>redis:7.4-alpine@sha256:6ab0b6e7381779332f97b8ca76193e45b0756f38d4c0dcda72dbb3c32061ab99</redis.image>
<redis-cluster.image>docker.io/bitnamilegacy/redis-cluster:7.4.3@sha256:a53d023fdfaf8a8d7ddc58da040d3494e4cb45772644618ffa44c42dcd32b9af</redis-cluster.image>
<docker.image>eclipse-temurin:25-jre-resolute@sha256:71bfb73662d4146bdc9ee2f97418a764d5ab4e83f4e90baec3b3dcda14071007</docker.image>
<docker.image>eclipse-temurin:26-jre-resolute@sha256:c3b6e31e48772c98e8868654e5f21fb2c3670e67c055ddd76d8cf37e62113eb5</docker.image>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
@@ -140,6 +143,11 @@
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-tcnative-boringssl-static</artifactId>
<version>${netty-tcnative.version}</version>
</dependency>
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-bom</artifactId>
@@ -199,7 +207,7 @@
<dependency>
<groupId>io.opentelemetry.instrumentation</groupId>
<artifactId>opentelemetry-instrumentation-bom</artifactId>
<version>2.30.0</version>
<version>2.31.1</version>
<type>pom</type>
<scope>import</scope>
</dependency>
@@ -317,7 +325,7 @@
<dependency>
<groupId>org.signal</groupId>
<artifactId>libsignal-server</artifactId>
<version>0.101.0</version>
<version>0.101.2</version>
</dependency>
<dependency>
<groupId>org.signal</groupId>
@@ -532,7 +540,7 @@
<artifactId>maven-compiler-plugin</artifactId>
<version>3.15.0</version>
<configuration>
<release>25</release>
<release>26</release>
</configuration>
</plugin>
+4 -1
View File
@@ -79,7 +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
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==
callingZkConfigPreV101.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==
callingZkConfigV101.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
@@ -101,3 +102,5 @@ hlrLookup.apiKey: AAAAAAAAAAA
hlrLookup.apiSecret: AAAAAAAAAAA
foundationDbMessages.versionstampCipherKey.0: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=
registrationWebAuthn.userHandleBlindingSecret: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=
+12 -1
View File
@@ -315,8 +315,11 @@ storageService:
AAAAAAAAAAAAAAAAAAAA
-----END CERTIFICATE-----
callingZkConfigPreV101:
serverSecret: secret://callingZkConfigPreV101.serverSecret
callingZkConfig:
serverSecret: secret://callingZkConfig.serverSecret
serverSecret: secret://callingZkConfigV101.serverSecret
chatZkConfig:
serverSecret: secret://chatZkConfig.serverSecret
@@ -384,6 +387,7 @@ subscription: # configuration for Stripe subscriptions
loginPurchase:
playProductId: login_example
playOptionId: login_option_example
appStoreProductId: login_example
oneTimeDonations:
@@ -568,3 +572,10 @@ foundationDbMessages:
- messages-1
- messages-2
- messages-3
registrationWebAuthn:
relyingPartyId: example.org
origins:
- https://example.org
challengeTtl: PT2M
userHandleBlindingSecret: secret://registrationWebAuthn.userHandleBlindingSecret
+24 -3
View File
@@ -15,14 +15,13 @@
<commons-compress.version>1.28.0</commons-compress.version>
<dynamodb-lock-client.version>1.5.0</dynamodb-lock-client.version>
<firebase-admin.version>9.10.0</firebase-admin.version>
<libphonenumber-geocoder.version>3.37</libphonenumber-geocoder.version>
<libphonenumber-geocoder.version>3.38</libphonenumber-geocoder.version>
<google-androidpublisher.version>v3-rev20250904-2.0.0</google-androidpublisher.version>
<java-jwt.version>4.6.0</java-jwt.version>
<java-uuid-generator.version>5.2.0</java-uuid-generator.version>
<!-- *all* opentelemetry-logback-appender versions are "alpha" despite the advanced version number -->
<opentelemetry-logback-appender-1.0.version>2.30.0-alpha</opentelemetry-logback-appender-1.0.version>
<opentelemetry-logback-appender-1.0.version>2.31.1-alpha</opentelemetry-logback-appender-1.0.version>
<storekit.version>5.2.0</storekit.version>
<webauthn4j.version>0.31.9.RELEASE</webauthn4j.version>
</properties>
<dependencies>
@@ -58,6 +57,11 @@
<artifactId>webauthn4j-appattest</artifactId>
<version>${webauthn4j.version}</version>
</dependency>
<dependency>
<groupId>com.webauthn4j</groupId>
<artifactId>webauthn4j-core</artifactId>
<version>${webauthn4j.version}</version>
</dependency>
<dependency>
<groupId>io.swagger.core.v3</groupId>
<artifactId>swagger-jaxrs2-jakarta</artifactId>
@@ -322,6 +326,10 @@
<version>4.3.0</version>
</dependency>
<dependency>
<groupId>io.github.resilience4j</groupId>
<artifactId>resilience4j-bulkhead</artifactId>
</dependency>
<dependency>
<groupId>io.github.resilience4j</groupId>
<artifactId>resilience4j-circuitbreaker</artifactId>
@@ -505,6 +513,11 @@
<artifactId>netty-resolver-dns</artifactId>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-tcnative-boringssl-static</artifactId>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-transport</artifactId>
@@ -572,6 +585,13 @@
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.webauthn4j</groupId>
<artifactId>webauthn4j-test</artifactId>
<version>${webauthn4j.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.uuid</groupId>
<artifactId>java-uuid-generator</artifactId>
@@ -780,6 +800,7 @@
<jvmFlag>-Djdk.nio.maxCachedBufferSize=262144</jvmFlag>
<jvmFlag>-Dlog4j2.formatMsgNoLookups=true</jvmFlag>
<jvmFlag>-Djdk.tls.server.newSessionTicketCount=0</jvmFlag>
<jvmFlag>-Djdk.tls.server.enableSessionTicketExtension=false</jvmFlag>
<jvmFlag>-XX:MaxRAMPercentage=75</jvmFlag>
<jvmFlag>-XX:+HeapDumpOnOutOfMemoryError</jvmFlag>
<jvmFlag>-XX:HeapDumpPath=/tmp/heapdump.bin</jvmFlag>
@@ -20,6 +20,7 @@ import org.whispersystems.textsecuregcm.configuration.AwsCredentialsProviderFact
import org.whispersystems.textsecuregcm.configuration.BackupConfiguration;
import org.whispersystems.textsecuregcm.configuration.BadgesConfiguration;
import org.whispersystems.textsecuregcm.configuration.BraintreeConfiguration;
import org.whispersystems.textsecuregcm.configuration.BulkheadConfiguration;
import org.whispersystems.textsecuregcm.configuration.CallQualitySurveyConfiguration;
import org.whispersystems.textsecuregcm.configuration.Cdn3StorageManagerConfiguration;
import org.whispersystems.textsecuregcm.configuration.CdnConfiguration;
@@ -67,6 +68,7 @@ import org.whispersystems.textsecuregcm.configuration.TotpConfiguration;
import org.whispersystems.textsecuregcm.configuration.TurnConfiguration;
import org.whispersystems.textsecuregcm.configuration.UnidentifiedDeliveryConfiguration;
import org.whispersystems.textsecuregcm.configuration.VirtualThreadConfiguration;
import org.whispersystems.textsecuregcm.configuration.WebAuthnConfiguration;
import org.whispersystems.textsecuregcm.configuration.ZkConfig;
import org.whispersystems.websocket.configuration.WebSocketConfiguration;
@@ -228,6 +230,11 @@ public class WhisperServerConfiguration extends Configuration {
@JsonProperty
private PaymentsServiceConfiguration paymentsService;
@Valid
@NotNull
@JsonProperty
private GenericZkConfig callingZkConfigPreV101;
@Valid
@NotNull
@JsonProperty
@@ -332,9 +339,6 @@ public class WhisperServerConfiguration extends Configuration {
@JsonProperty
private KeyTransparencyServiceConfiguration keyTransparencyService;
@JsonProperty
private boolean logMessageDeliveryLoops;
@JsonProperty
private IdlePrimaryDeviceReminderConfiguration idlePrimaryDeviceReminder =
new IdlePrimaryDeviceReminderConfiguration(Duration.ofDays(30));
@@ -345,6 +349,9 @@ public class WhisperServerConfiguration extends Configuration {
@JsonProperty
private Map<String, @Valid RetryConfiguration> retries = Collections.emptyMap();
@JsonProperty
private Map<String, @Valid BulkheadConfiguration> bulkheads = Collections.emptyMap();
@Valid
@NotNull
@JsonProperty
@@ -385,6 +392,11 @@ public class WhisperServerConfiguration extends Configuration {
@JsonProperty
private TotpConfiguration registrationTotp = TotpConfiguration.DEFAULT;
@Valid
@NotNull
@JsonProperty
private WebAuthnConfiguration registrationWebAuthn;
public TlsKeyStoreConfiguration getTlsKeyStoreConfiguration() {
return tlsKeyStore;
}
@@ -514,6 +526,11 @@ public class WhisperServerConfiguration extends Configuration {
return chatZkConfig;
}
/// ZK secret shared with Calling Service
public GenericZkConfig getCallingZkConfigPreV101() {
return callingZkConfigPreV101;
}
/// ZK secret shared with Calling Service
public GenericZkConfig getCallingZkConfig() {
return callingZkConfig;
@@ -596,10 +613,6 @@ public class WhisperServerConfiguration extends Configuration {
return keyTransparencyService;
}
public boolean logMessageDeliveryLoops() {
return logMessageDeliveryLoops;
}
public IdlePrimaryDeviceReminderConfiguration idlePrimaryDeviceReminderConfiguration() {
return idlePrimaryDeviceReminder;
}
@@ -612,6 +625,10 @@ public class WhisperServerConfiguration extends Configuration {
return retries;
}
public Map<String, BulkheadConfiguration> getBulkheadConfigurations() {
return bulkheads;
}
public RetryConfiguration getGeneralRedisRetryConfiguration() {
return generalRedisRetry;
}
@@ -643,4 +660,8 @@ public class WhisperServerConfiguration extends Configuration {
public TotpConfiguration getRegistrationTotpConfiguration() {
return registrationTotp;
}
public WebAuthnConfiguration getRegistrationWebAuthnConfiguration() {
return registrationWebAuthn;
}
}
@@ -97,6 +97,7 @@ import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator
import org.whispersystems.textsecuregcm.auth.IdlePrimaryDeviceAuthenticatedWebSocketUpgradeFilter;
import org.whispersystems.textsecuregcm.auth.PhoneVerificationTokenManager;
import org.whispersystems.textsecuregcm.auth.RegistrationLockVerificationManager;
import org.whispersystems.textsecuregcm.auth.webauthn.WebAuthnCeremonyManager;
import org.whispersystems.textsecuregcm.auth.grpc.ProhibitAuthenticationInterceptor;
import org.whispersystems.textsecuregcm.auth.grpc.RequireAuthenticationInterceptor;
import org.whispersystems.textsecuregcm.backup.BackupAuthManager;
@@ -111,6 +112,7 @@ import org.whispersystems.textsecuregcm.captcha.CaptchaClient;
import org.whispersystems.textsecuregcm.captcha.RegistrationCaptchaManager;
import org.whispersystems.textsecuregcm.captcha.ShortCodeExpander;
import org.whispersystems.textsecuregcm.configuration.BadgeConfiguration;
import org.whispersystems.textsecuregcm.configuration.FoundationDbExternalClientConfiguration;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.configuration.secrets.SecretStore;
import org.whispersystems.textsecuregcm.configuration.secrets.SecretsModule;
@@ -168,6 +170,7 @@ import org.whispersystems.textsecuregcm.grpc.CredentialsGrpcService;
import org.whispersystems.textsecuregcm.grpc.DevicesGrpcService;
import org.whispersystems.textsecuregcm.grpc.DonationsGrpcService;
import org.whispersystems.textsecuregcm.grpc.ErrorConformanceInterceptor;
import org.whispersystems.textsecuregcm.grpc.ConcurrentCallLimitingInterceptor;
import org.whispersystems.textsecuregcm.grpc.ErrorMappingInterceptor;
import org.whispersystems.textsecuregcm.grpc.ExternalServiceDefinitions;
import org.whispersystems.textsecuregcm.grpc.GroupSendTokenUtil;
@@ -197,29 +200,26 @@ import org.whispersystems.textsecuregcm.grpc.net.SniMapper;
import org.whispersystems.textsecuregcm.jetty.JettyHttpConfigurationCustomizer;
import org.whispersystems.textsecuregcm.keytransparency.KeyTransparencyServiceClient;
import org.whispersystems.textsecuregcm.limits.CardinalityEstimator;
import org.whispersystems.textsecuregcm.limits.MessageDeliveryLoopMonitor;
import org.whispersystems.textsecuregcm.limits.NoopMessageDeliveryLoopMonitor;
import org.whispersystems.textsecuregcm.limits.PushChallengeManager;
import org.whispersystems.textsecuregcm.limits.RateLimitByIpFilter;
import org.whispersystems.textsecuregcm.limits.RateLimitChallengeManager;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.limits.RedisMessageDeliveryLoopMonitor;
import org.whispersystems.textsecuregcm.mappers.BackupExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.CompletionExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.DeviceLimitExceededExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.GrpcStatusRuntimeExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.IOExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.IllegalStateExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.ImpossiblePhoneNumberExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.InvalidWebsocketAddressExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.JsonMappingExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.MfaFailureExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.NonNormalizedPhoneNumberExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.ObsoletePhoneNumberFormatExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.RegistrationLockFailureExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.RegistrationServiceSenderExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.ServerRejectedExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.SubscriptionExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.PurchaseExceptionMapper;
import org.whispersystems.textsecuregcm.metrics.BackupMetrics;
import org.whispersystems.textsecuregcm.metrics.CallQualitySurveyManager;
import org.whispersystems.textsecuregcm.metrics.MessageMetrics;
@@ -273,14 +273,14 @@ 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.PhoneNumberRecoveryPasswords;
import org.whispersystems.textsecuregcm.storage.PhoneNumberRecoveryPasswordsManager;
import org.whispersystems.textsecuregcm.storage.ProfileAvatars;
import org.whispersystems.textsecuregcm.storage.Profiles;
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
import org.whispersystems.textsecuregcm.storage.ProfilesV2;
import org.whispersystems.textsecuregcm.storage.PushChallengeDynamoDb;
import org.whispersystems.textsecuregcm.storage.RedeemedReceiptsManager;
import org.whispersystems.textsecuregcm.storage.PhoneNumberRecoveryPasswords;
import org.whispersystems.textsecuregcm.storage.PhoneNumberRecoveryPasswordsManager;
import org.whispersystems.textsecuregcm.storage.RemoteConfigs;
import org.whispersystems.textsecuregcm.storage.RemoteConfigsManager;
import org.whispersystems.textsecuregcm.storage.RepeatedUseECSignedPreKeyStore;
@@ -290,22 +290,25 @@ import org.whispersystems.textsecuregcm.storage.ReportMessageManager;
import org.whispersystems.textsecuregcm.storage.SingleUseECPreKeyStore;
import org.whispersystems.textsecuregcm.storage.SubscriptionManager;
import org.whispersystems.textsecuregcm.storage.Subscriptions;
import org.whispersystems.textsecuregcm.storage.TotpManager;
import org.whispersystems.textsecuregcm.storage.VerificationSessionManager;
import org.whispersystems.textsecuregcm.storage.VerificationSessions;
import org.whispersystems.textsecuregcm.storage.devicecheck.AppleDeviceCheckManager;
import org.whispersystems.textsecuregcm.storage.devicecheck.AppleDeviceCheckTrustAnchor;
import org.whispersystems.textsecuregcm.storage.devicecheck.AppleDeviceChecks;
import org.whispersystems.textsecuregcm.storage.foundationdb.FaultTolerantDatabase;
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStore;
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDBWarmup;
import org.whispersystems.textsecuregcm.storage.foundationdb.VersionstampUUIDCipher;
import org.whispersystems.textsecuregcm.subscriptions.AppleAppStoreClient;
import org.whispersystems.textsecuregcm.subscriptions.AppleAppStoreManager;
import org.whispersystems.textsecuregcm.subscriptions.BankMandateTranslator;
import org.whispersystems.textsecuregcm.subscriptions.BraintreeManager;
import org.whispersystems.textsecuregcm.subscriptions.GooglePlayBillingManager;
import org.whispersystems.textsecuregcm.subscriptions.LoginPurchaseManager;
import org.whispersystems.textsecuregcm.subscriptions.PayPalDonationsTranslator;
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
import org.whispersystems.textsecuregcm.subscriptions.StripeManager;
import org.whispersystems.textsecuregcm.purchases.AppleAppStoreClient;
import org.whispersystems.textsecuregcm.purchases.AppleAppStoreManager;
import org.whispersystems.textsecuregcm.purchases.BankMandateTranslator;
import org.whispersystems.textsecuregcm.purchases.BraintreeManager;
import org.whispersystems.textsecuregcm.purchases.GooglePlayBillingManager;
import org.whispersystems.textsecuregcm.purchases.LoginPurchaseManager;
import org.whispersystems.textsecuregcm.purchases.PayPalDonationsTranslator;
import org.whispersystems.textsecuregcm.purchases.PaymentProvider;
import org.whispersystems.textsecuregcm.purchases.StripeManager;
import org.whispersystems.textsecuregcm.telephony.CarrierDataProvider;
import org.whispersystems.textsecuregcm.telephony.hlrlookup.HlrLookupCarrierDataProvider;
import org.whispersystems.textsecuregcm.util.BufferingInterceptor;
@@ -334,7 +337,6 @@ import org.whispersystems.textsecuregcm.workers.DeleteUserCommand;
import org.whispersystems.textsecuregcm.workers.IdleDeviceNotificationSchedulerFactory;
import org.whispersystems.textsecuregcm.workers.MessagePersisterServiceCommand;
import org.whispersystems.textsecuregcm.workers.NotifyIdleDevicesCommand;
import org.whispersystems.textsecuregcm.workers.PopulateAccountRecoveryPasswordsCommand;
import org.whispersystems.textsecuregcm.workers.ProcessScheduledJobsServiceCommand;
import org.whispersystems.textsecuregcm.workers.RegenerateSecondaryDynamoDbTableDataCommand;
import org.whispersystems.textsecuregcm.workers.RemoveExpiredAccountsCommand;
@@ -415,8 +417,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
bootstrap.addCommand(new RegenerateSecondaryDynamoDbTableDataCommand());
bootstrap.addCommand(new PopulateAccountRecoveryPasswordsCommand());
ServiceLoader.load(SpamFilter.class)
.stream()
.map(ServiceLoader.Provider::get)
@@ -443,6 +443,9 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
config.getRetryConfigurations().forEach((name, configuration) ->
ResilienceUtil.getRetryRegistry().addConfiguration(name, configuration.toRetryConfigBuilder().build()));
config.getBulkheadConfigurations().forEach((name, configuration) ->
ResilienceUtil.getBulkheadRegistry().addConfiguration(name, configuration.toBulkheadConfig().build()));
ResilienceUtil.setGeneralRedisRetryConfiguration(config.getGeneralRedisRetryConfiguration());
ScheduledExecutorService dynamicConfigurationExecutor = ScheduledExecutorServiceBuilder.of(environment, "dynamicConfiguration")
@@ -502,9 +505,20 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
// we'd like, but is the least bad option given current constraints.
fdb.disableShutdownHook();
final Map<Integer, List<Database>> messageDatabasesByEpoch;
final FoundationDbExternalClientConfiguration externalClientConfiguration = config.getFoundationDbMessagesConfiguration()
.externalClientConfiguration();
if (externalClientConfiguration != null) {
// If threadsPerClient is not specified, we default to the cluster size so that there is 1:1 correspondence between
// Database objects and threads.
final int clientThreadsPerVersion = externalClientConfiguration.threadsPerClient()
.orElseGet(() -> config.getFoundationDbMessagesConfiguration().clusters().size());
externalClientConfiguration.clientLibraryPaths().forEach(path -> fdb.options().setExternalClientLibrary(path));
fdb.options().setClientThreadsPerVersion(clientThreadsPerVersion);
}
final Map<Integer, List<FaultTolerantDatabase>> messageDatabasesByEpoch;
{
final Map<String, Database> databasesByName =
final Map<String, FaultTolerantDatabase> faultTolerantDatabasesByName =
config.getFoundationDbMessagesConfiguration().clusters().entrySet().stream()
.collect(Collectors.toUnmodifiableMap(Map.Entry::getKey,
entry -> {
@@ -516,7 +530,9 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
database.options().setTransactionRetryLimit(
config.getFoundationDbMessagesConfiguration().transactionRetryLimit());
return database;
return new FaultTolerantDatabase(database, entry.getKey(),
config.getFoundationDbMessagesConfiguration().circuitBreakerConfigurationName(),
config.getFoundationDbMessagesConfiguration().bulkheadConfigurationName());
} catch (final IOException e) {
throw new UncheckedIOException(e);
}
@@ -525,8 +541,10 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
messageDatabasesByEpoch = config.getFoundationDbMessagesConfiguration().epochs().entrySet().stream()
.collect(Collectors.toUnmodifiableMap(Map.Entry::getKey,
entry -> entry.getValue().stream()
.map(databasesByName::get)
.map(faultTolerantDatabasesByName::get)
.toList()));
environment.lifecycle().manage(new FoundationDBWarmup(faultTolerantDatabasesByName));
}
final AwsCredentialsProvider cdnCredentialsProvider = config.getCdnConfiguration().credentials().build();
@@ -648,7 +666,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
final ScheduledExecutorService retryExecutor = ScheduledExecutorServiceBuilder.of(environment, "retry")
.threads(16).build();
final ScheduledExecutorService registrationIdentityTokenRefreshExecutor =
ScheduledExecutorServiceBuilder.of(environment, "registrationIdentityTokenRefresh").threads(1).build();
ScheduledExecutorServiceBuilder.of(environment, "registrationIdentityTokenRefresh").threads(1).build();
final ScheduledExecutorService presenceRenewalExecutor =
ScheduledExecutorServiceBuilder.of(environment, "presenceRenewal").threads(4).build();
@@ -669,10 +687,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
.workQueue(receiptSenderQueue)
.rejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy())
.build();
ExecutorService accountLockExecutor = ExecutorServiceBuilder.of(environment, "accountLock")
.minThreads(8)
.maxThreads(8)
.build();
// unbounded executor (same as cachedThreadPool)
ExecutorService remoteStorageHttpExecutor = ExecutorServiceBuilder.of(environment, "remoteStorage")
.minThreads(0)
@@ -712,11 +726,11 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
final ManagedEventLoopGroup<NioEventLoopGroup> dnsResolutionEventLoopGroup = new ManagedEventLoopGroup<>(new NioEventLoopGroup());
final DnsNameResolver cloudflareDnsResolver = new DnsNameResolverBuilder(dnsResolutionEventLoopGroup.getEventLoopGroup().next())
.resolvedAddressTypes(ResolvedAddressTypes.IPV6_PREFERRED)
.completeOncePreferredResolved(false)
.channelType(NioDatagramChannel.class)
.socketChannelType(NioSocketChannel.class)
.build();
.resolvedAddressTypes(ResolvedAddressTypes.IPV6_PREFERRED)
.completeOncePreferredResolved(false)
.channelType(NioDatagramChannel.class)
.socketChannelType(NioSocketChannel.class)
.build();
ExternalServiceCredentialsGenerator directoryV2CredentialsGenerator = DirectoryV2Controller.credentialsGenerator(
config.getDirectoryV2Configuration().getDirectoryV2ClientConfiguration());
@@ -802,12 +816,19 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
changeNumberWaitingPeriods, config.getChangeNumber().postRegistrationWaitingPeriod(), clock);
AccountLockManager accountLockManager = new AccountLockManager(dynamoDbClient,
config.getDynamoDbTables().getDeletedAccountsLock().getTableName());
AccountsManager accountsManager = new AccountsManager(accounts, phoneNumberIdentifiers, cacheCluster,
final TotpManager totpManager = new TotpManager(rateLimitersCluster, config.getRegistrationTotpConfiguration().maxValidationDelay());
final WebAuthnCeremonyManager webAuthnCeremonyManager = new WebAuthnCeremonyManager(
config.getRegistrationWebAuthnConfiguration().relyingPartyId(),
config.getRegistrationWebAuthnConfiguration().origins(),
config.getRegistrationWebAuthnConfiguration().challengeTtl(),
config.getRegistrationWebAuthnConfiguration().userHandleBlindingSecret().value(),
rateLimitersCluster);
final AccountsManager accountsManager = new AccountsManager(accounts, phoneNumberIdentifiers, cacheCluster,
pubsubClient, accountLockManager, keysManager, messagesManager, profilesManager,
changeNumberWaitingPeriodManager, secureStorageClient, secureValueRecovery2Client, disconnectionRequestManager,
phoneNumberRecoveryPasswordsManager, accountLockExecutor, messagePollExecutor,
phoneNumberRecoveryPasswordsManager, messagePollExecutor,
retryExecutor, clock, config.getLinkDeviceSecretConfiguration().secret().value(),
config.getRegistrationTotpConfiguration().maxValidationDelay());
webAuthnCeremonyManager, totpManager);
RemoteConfigsManager remoteConfigsManager = new RemoteConfigsManager(remoteConfigs, config.getRemoteConfigConfiguration().globalConfig());
APNSender apnSender = new APNSender(apnSenderExecutor, Clock.systemUTC(), config.getApnConfiguration());
FcmSender fcmSender = new FcmSender(fcmSenderExecutor, config.getFcmConfiguration().credentials().value());
@@ -828,8 +849,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
config.getDynamoDbTables().getDonationPermits().getTableName(), config.getDynamoDbTables().getDonationPermits().getExpiration(), dynamoDbClient);
Subscriptions subscriptions = new Subscriptions(
config.getDynamoDbTables().getSubscriptions().getTableName(), dynamoDbClient);
MessageDeliveryLoopMonitor messageDeliveryLoopMonitor =
config.logMessageDeliveryLoops() ? new RedisMessageDeliveryLoopMonitor(rateLimitersCluster) : new NoopMessageDeliveryLoopMonitor();
CallQualitySurveyManager callQualitySurveyManager = new CallQualitySurveyManager(asnInfoProviderSupplier,
config.getCallQualitySurveyConfiguration().pubSubPublisher().build(),
Clock.systemUTC(),
@@ -941,6 +960,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
config.getCdnConfiguration().credentials().secretAccessKey().value());
ServerSecretParams groupZkSecretParams = new ServerSecretParams(config.getGroupsZkConfig().serverSecret().value());
GenericServerSecretParams callingPreV101GenericZkSecretParams = new GenericServerSecretParams(config.getCallingZkConfigPreV101().serverSecret().value());
GenericServerSecretParams callingGenericZkSecretParams = new GenericServerSecretParams(config.getCallingZkConfig().serverSecret().value());
GenericServerSecretParams chatGenericZkSecretParams = new GenericServerSecretParams(config.getChatZkConfig().serverSecret().value());
ServerZkProfileOperations zkProfileOperations = new ServerZkProfileOperations(groupZkSecretParams);
@@ -1058,7 +1078,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
final HttpClient shortCodeRetrieverHttpClient = HttpClient.newBuilder().version(HttpClient.Version.HTTP_2)
.connectTimeout(Duration.ofSeconds(10)).build();
final ShortCodeExpander shortCodeRetriever = new ShortCodeExpander(shortCodeRetrieverHttpClient, config.getShortCodeRetrieverConfiguration().baseUrl());
final CaptchaChecker captchaChecker = new CaptchaChecker(shortCodeRetriever, captchaClientSupplier);
final CaptchaChecker captchaChecker = new CaptchaChecker(shortCodeRetriever, captchaClientSupplier, dynamicConfigurationManager);
final RegistrationCaptchaManager registrationCaptchaManager = new RegistrationCaptchaManager(captchaChecker);
@@ -1082,6 +1102,9 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
final ValidatingInterceptor validatingInterceptor = new ValidatingInterceptor();
final ConcurrentCallLimitingInterceptor concurrentCallLimitingInterceptor =
new ConcurrentCallLimitingInterceptor(config.getVirtualThreadConfiguration().maxConcurrentThreadsPerExecutor());
final ExternalRequestFilter grpcExternalRequestFilter = new ExternalRequestFilter(
config.getExternalRequestFilterConfiguration().permittedInternalRanges(),
config.getExternalRequestFilterConfiguration().grpcMethods());
@@ -1090,8 +1113,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
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,
clientReleaseManager);
pushNotificationManager, pushNotificationScheduler, disconnectionRequestManager, clientReleaseManager);
final CertificateGenerator certificateGenerator =
new CertificateGenerator(config.getDeliveryCertificate().certificate(),
@@ -1113,7 +1135,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new CredentialsGrpcService(accountsManager, certificateGenerator, zkAuthOperations, callingGenericZkSecretParams, rateLimiters, Clock.systemUTC(), ExternalServiceDefinitions.createExternalServiceList(config, Clock.systemUTC())),
new KeysGrpcService(accountsManager, keysManager, rateLimiters),
new ProfileGrpcService(clock, accountsManager, profilesManager, asnInfoProviderSupplier, dynamicConfigurationManager, config.getBadges(), profileCdnPolicyGenerator, chatGenericZkSecretParams, profileBadgeConverter, rateLimiters),
new MessagesGrpcService(accountsManager, rateLimiters, messageSender, messageByteLimitCardinalityEstimator, spamChecker, messageDispatcher, Clock.systemUTC()),
new MessagesGrpcService(accountsManager, reportMessageManager, phoneNumberIdentifiers, rateLimiters, messageSender, messageByteLimitCardinalityEstimator, spamChecker, messageDispatcher, Clock.systemUTC()),
new BackupsGrpcService(accountsManager, backupAuthManager, backupMetrics),
new DevicesGrpcService(accountsManager),
new AttachmentsGrpcService(experimentEnrollmentManager, rateLimiters, gcsAttachmentGenerator,
@@ -1139,7 +1161,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
remoteDeprecationFilter,
metricServerInterceptor,
requestAttributesInterceptor,
requireAuthenticationInterceptor))
requireAuthenticationInterceptor,
concurrentCallLimitingInterceptor))
.toList();
final List<ServerServiceDefinition> unauthenticatedServices = Stream.of(
new AccountsAnonymousGrpcService(accountsManager, rateLimiters, groupSendTokenUtil),
@@ -1167,7 +1190,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
remoteDeprecationFilter,
metricServerInterceptor,
requestAttributesInterceptor,
prohibitAuthenticationInterceptor))
prohibitAuthenticationInterceptor,
concurrentCallLimitingInterceptor))
.toList();
final ManagedEventLoopGroup<DefaultEventLoopGroup> omnibusLocalEventLoopGroup = new ManagedEventLoopGroup<>(new DefaultEventLoopGroup());
@@ -1177,20 +1201,26 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
.forAddress(grpcLocalAddress)
.channelType(LocalServerChannel.class)
.bossEventLoopGroup(omnibusLocalEventLoopGroup.getEventLoopGroup())
.workerEventLoopGroup(omnibusLocalEventLoopGroup.getEventLoopGroup());
.workerEventLoopGroup(omnibusLocalEventLoopGroup.getEventLoopGroup())
.executor(ManagedExecutors.newVirtualThreadPerTaskExecutor("managed-grpc-virtual-thread", environment));
authenticatedServices.forEach(serverBuilder::addService);
unauthenticatedServices.forEach(serverBuilder::addService);
final ManagedGrpcServer localGrpcServer = new ManagedGrpcServer(serverBuilder.build());
final String websocketServletPath = "/v1/websocket/";
final String provisioningWebsocketServletPath = "/v1/websocket/provisioning/";
final SocketAddress websocketAddress =
new InetSocketAddress(config.getGrpc().websocketAddress(), config.getGrpc().websocketPort());
final OmnibusRouter omnibusRouter = new OmnibusRouter(List.of(
new OmnibusRouter.OmnibusRoute("/v1/websocket", websocketAddress),
new OmnibusRouter.OmnibusRoute("/v1/provisioning", websocketAddress)),
final OmnibusRouter omnibusRouter = new OmnibusRouter(Map.of(
websocketServletPath, websocketAddress,
provisioningWebsocketServletPath, websocketAddress),
grpcLocalAddress);
@Nullable final Mapping<String, SslContext> sniMapping = config.getGrpc().h2c()
? null
: SniMapper.buildSniMapping(config.getTlsKeyStoreConfiguration().path(), config.getTlsKeyStoreConfiguration().password().value());
: SniMapper.buildSniMapping(config.getTlsKeyStoreConfiguration().path(),
config.getTlsKeyStoreConfiguration().password().value(),
config.getGrpc().sslProvider());
final OmnibusH2Server omnibusH2Server = new OmnibusH2Server(
sniMapping,
omnibusNioEventLoopGroup.getEventLoopGroup(),
@@ -1217,9 +1247,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
.setAuthenticator(accountAuthenticator)
.buildAuthFilter();
final String websocketServletPath = "/v1/websocket/";
final String provisioningWebsocketServletPath = "/v1/websocket/provisioning/";
MetricsHttpEventHandler.configure(environment, Metrics.globalRegistry, clientReleaseManager, Set.of(websocketServletPath, provisioningWebsocketServletPath, "/health-check"));
// BufferingInterceptor is needed on the base environment but not the WebSocketEnvironment,
@@ -1250,7 +1277,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
webSocketEnvironment.setConnectListener(
new AuthenticatedConnectListener(accountsManager, receiptSender, messagesManager, messageMetrics, pushNotificationManager,
pushNotificationScheduler, disconnectionRequestManager,
messageDeliveryScheduler, asnInfoProviderSupplier, clientReleaseManager, messageDeliveryLoopMonitor, experimentEnrollmentManager
messageDeliveryScheduler, asnInfoProviderSupplier, clientReleaseManager, experimentEnrollmentManager
));
webSocketEnvironment.jersey().register(new RateLimitByIpFilter(rateLimiters));
webSocketEnvironment.jersey().register(new RequestStatisticsFilter(TrafficSource.WEBSOCKET));
@@ -1269,9 +1296,9 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
experimentEnrollmentManager, config.getAttachments().maxAttachmentUploadSizeInBytes()),
new ArchiveController(accountsManager, backupAuthManager, backupManager, backupMetrics, config.getAttachments().maxAttachmentUploadSizeInBytes(), config.getAttachments().maxMessageBackupUploadSizeInBytes()),
new CallRoutingControllerV2(rateLimiters, cloudflareTurnCredentialsManager),
new CallLinkController(rateLimiters, callingGenericZkSecretParams),
new CallLinkController(rateLimiters, callingGenericZkSecretParams, callingPreV101GenericZkSecretParams),
new CallQualitySurveyController(callQualitySurveyManager),
new CertificateController(accountsManager, certificateGenerator, zkAuthOperations, callingGenericZkSecretParams, clock),
new CertificateController(accountsManager, certificateGenerator, zkAuthOperations, callingGenericZkSecretParams, callingPreV101GenericZkSecretParams, clock),
new ChallengeController(accountsManager, rateLimitChallengeManager, challengeConstraintChecker),
new DeviceController(accountsManager, rateLimiters, persistentTimer),
new DeviceCheckController(clock, accountsManager, backupAuthManager, appleDeviceCheckManager, rateLimiters,
@@ -1297,7 +1324,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new VerificationController(registrationServiceClient, new VerificationSessionManager(verificationSessions),
pushNotificationManager, registrationCaptchaManager, phoneNumberRecoveryPasswordsManager,
phoneNumberIdentifiers, rateLimiters, accountsManager, carrierDataProvider, registrationFraudChecker,
dynamicConfigurationManager, experimentEnrollmentManager, clock),
dynamicConfigurationManager, clock),
new SubscriptionController(clock, config.getSubscription(), config.getOneTimeDonations(),
config.getLoginPurchase(), subscriptionManager, stripeManager, braintreeManager, googlePlayBillingManager,
appleAppStoreManager,
@@ -1366,7 +1393,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
List.of(
new LoggingUnhandledExceptionMapper(),
new CompletionExceptionMapper(),
new GrpcStatusRuntimeExceptionMapper(),
new IOExceptionMapper(),
new RateLimitExceededExceptionMapper(),
new InvalidWebsocketAddressExceptionMapper(),
@@ -1377,10 +1403,11 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new NonNormalizedPhoneNumberExceptionMapper(),
new ObsoletePhoneNumberFormatExceptionMapper(),
new RegistrationServiceSenderExceptionMapper(),
new SubscriptionExceptionMapper(),
new PurchaseExceptionMapper(),
new BackupExceptionMapper(),
new JsonMappingExceptionMapper(),
new RegistrationLockFailureExceptionMapper()
new RegistrationLockFailureExceptionMapper(),
new MfaFailureExceptionMapper()
).forEach(exceptionMapper -> {
environment.jersey().register(exceptionMapper);
webSocketEnvironment.jersey().register(exceptionMapper);
@@ -0,0 +1,29 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.auth;
import javax.annotation.Nullable;
import org.whispersystems.textsecuregcm.auth.webauthn.AuthenticationCeremonyParameters;
import org.whispersystems.textsecuregcm.util.NoStackTraceException;
public class MfaFailureException extends NoStackTraceException {
private final @Nullable AuthenticationCeremonyParameters webAuthnParameters;
private final boolean hasTotp;
public MfaFailureException(@Nullable AuthenticationCeremonyParameters webAuthnParameters, boolean hasTotpKey) {
this.webAuthnParameters = webAuthnParameters;
this.hasTotp = hasTotpKey;
}
public @Nullable AuthenticationCeremonyParameters getWebAuthnParameters() {
return webAuthnParameters;
}
public boolean hasTotpKey() {
return hasTotp;
}
}
@@ -0,0 +1,16 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.auth.webauthn;
import java.time.Duration;
import java.util.List;
/// Server-generated parameters for a freshly-initiated authentication ceremony.
public record AuthenticationCeremonyParameters(
byte[] challenge,
Duration timeout,
List<byte[]> allowedCredentialIds) {
}
@@ -0,0 +1,15 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.auth.webauthn;
import java.util.List;
/// Server-generated parameters for a freshly-initiated registration ceremony.
public record RegistrationCeremonyParameters(
byte[] userHandle,
List<Long> allowedAlgorithms,
List<byte[]> excludedCredentialIds) {
}
@@ -0,0 +1,17 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.auth.webauthn;
import com.webauthn4j.data.attestation.authenticator.AttestedCredentialData;
import com.webauthn4j.data.client.CollectedClientData;
/// Results of a registration ceremony for persisting.
public record RegistrationCeremonyResult(
AttestedCredentialData attestedCredentialData,
CollectedClientData collectedClientData,
long signCount
) {
}
@@ -0,0 +1,27 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.auth.webauthn;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import io.swagger.v3.oas.annotations.media.Schema;
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
import java.util.List;
public record WebAuthnAuthenticationParameters(
@Schema(description = "The authentication ceremony challenge.")
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
byte[] challenge,
@Schema(description = "The number of seconds the challenge will be valid.")
long timeoutSeconds,
@Schema(description = "A list of authenticators previously registered to the account.")
@JsonDeserialize(contentUsing = ByteArrayAdapter.Deserializing.class)
@JsonSerialize(contentUsing = ByteArrayAdapter.Serializing.class)
List<byte[]> allowedCredentialIds) {}
@@ -0,0 +1,234 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.auth.webauthn;
import com.google.common.annotations.VisibleForTesting;
import com.webauthn4j.WebAuthnManager;
import com.webauthn4j.credential.CredentialRecord;
import com.webauthn4j.data.AuthenticationData;
import com.webauthn4j.data.AuthenticationParameters;
import com.webauthn4j.data.PublicKeyCredentialParameters;
import com.webauthn4j.data.PublicKeyCredentialType;
import com.webauthn4j.data.RegistrationData;
import com.webauthn4j.data.RegistrationParameters;
import com.webauthn4j.data.RegistrationRequest;
import com.webauthn4j.data.attestation.statement.COSEAlgorithmIdentifier;
import com.webauthn4j.data.client.Origin;
import com.webauthn4j.server.ServerProperty;
import com.webauthn4j.util.exception.WebAuthnException;
import com.webauthn4j.verifier.exception.BadChallengeException;
import com.webauthn4j.verifier.exception.VerificationException;
import io.lettuce.core.SetArgs;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.time.Duration;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
import org.whispersystems.textsecuregcm.util.HmacUtils;
import org.whispersystems.textsecuregcm.util.ResilienceUtil;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
import tools.jackson.core.JacksonException;
/// Handles WebAuthn registration and authentication operations.
public class WebAuthnCeremonyManager {
/// [relying party ID - WebAuthn TR](https://www.w3.org/TR/webauthn/#relying-party-identifier)
private final String rpId;
/// [origin - WebAuthn TR](https://www.w3.org/TR/webauthn/#dom-collectedclientdata-origin)
private final Set<Origin> origins;
private final byte[] blindingSecret;
private final Duration challengeTtl;
private final FaultTolerantRedisClusterClient challengeStorageCluster;
private final WebAuthnManager webAuthnManager;
private static final String RETRY_NAME = ResilienceUtil.name(WebAuthnCeremonyManager.class);
/// Ed25519 support is fairly limited, while ES256 is broadly supported
private static final List<PublicKeyCredentialParameters> ALLOWED_WEBAUTHN_CREDENTIAL_ALGORITHMS = List.of(
new PublicKeyCredentialParameters(PublicKeyCredentialType.PUBLIC_KEY, COSEAlgorithmIdentifier.Ed25519),
new PublicKeyCredentialParameters(PublicKeyCredentialType.PUBLIC_KEY, COSEAlgorithmIdentifier.ES256)
);
private static final SecureRandom SECURE_RANDOM = new SecureRandom();
public WebAuthnCeremonyManager(final String rpId, final List<String> origins, final Duration challengeTtl, final byte[] blindingSecret,
final FaultTolerantRedisClusterClient challengeStorageCluster) {
this.rpId = rpId;
this.origins = origins.stream().map(Origin::new).collect(Collectors.toSet());
this.challengeTtl = challengeTtl;
this.blindingSecret = blindingSecret;
this.challengeStorageCluster = challengeStorageCluster;
this.webAuthnManager = WebAuthnManager.createNonStrictWebAuthnManager();
}
/// Initiates a WebAuthn registration ceremony
///
/// @param identifier The account identifier
///
/// @param existingCredentials a list of already-stored credential records for the user; their IDs
/// will be provided to the client to help prevent registering a duplicate ID on the same
/// authenticator
///
/// @return parameters the client must use for its step in the registration ceremony. `identifier` will be blinded, so
/// that it is a [non-identifiable user handle](https://www.w3.org/TR/webauthn/#sctn-user-handle-privacy)
public RegistrationCeremonyParameters startRegistration(final UUID identifier, final List<? extends CredentialRecord> existingCredentials) {
return new RegistrationCeremonyParameters(
blindIdentifier(identifier),
ALLOWED_WEBAUTHN_CREDENTIAL_ALGORITHMS.stream().map(pkcp -> pkcp.getAlg().getValue()).toList(),
existingCredentials.stream().map(credentialRecord -> credentialRecord.getAttestedCredentialData().getCredentialId()).toList()
);
}
/// Verifies that the supplied authenticator response components form a
/// valid WebAuthn registration ceremony with acceptable parameters.
///
/// @param serializedAttestationObject the "attestation object" from the authenticator response,
/// serialized in the format specified by the WebAuthn TR. Its attestation format must be `none`
/// and any attestation statement must have been cleared to mitigate privacy risks.
///
/// @param collectedClientDataJson the "collected client data" from the authenticator response,
/// serialized in the [format specified by the WebAuthn TR](https://www.w3.org/TR/webauthn/#sctn-generating-an-attestation-object)
///
/// @return a record that can be stored for future authentication.
///
/// @throws WebAuthnException if the supplied authenticator response is
/// invalid for any reason (structurally or due to selecting unacceptable
/// parameters, for example an unsupported signature algorithm)
public RegistrationCeremonyResult verifyRegistration(
final byte[] serializedAttestationObject, final String collectedClientDataJson) throws WebAuthnException {
final RegistrationData registrationData;
try {
registrationData = webAuthnManager.parse(
new RegistrationRequest(serializedAttestationObject, collectedClientDataJson.getBytes(StandardCharsets.UTF_8)));
} catch (final JacksonException e) {
throw new WebAuthnException(e);
}
// These shouldn't ever be null, because the upstream RPC inputs are not nullable. However, the fields are annotated as
// nullable.
if (registrationData.getAttestationObject() == null) {
throw new WebAuthnException("Attestation object must not be null");
}
if (registrationData.getCollectedClientData() == null) {
throw new WebAuthnException("Collected client data must not be null");
}
if (!"none".equals(registrationData.getAttestationObject().getAttestationStatement().getFormat())) {
// Refuse any attestations; clients must clear them to prevent sharing information we don't want to store
throw new WebAuthnException("attestation format must be 'none'");
}
final ServerProperty serverProperties = ServerProperty.builder()
// we aren't verifying any signatures for registration, so we don't need to bother saving a
// challenge; accept whatever is supplied
.challenge(registrationData.getCollectedClientData().getChallenge())
.origins(origins)
.rpId(rpId)
.build();
webAuthnManager.verify(registrationData,
new RegistrationParameters(serverProperties, ALLOWED_WEBAUTHN_CREDENTIAL_ALGORITHMS, false, true));
return new RegistrationCeremonyResult(
registrationData.getAttestationObject().getAuthenticatorData().getAttestedCredentialData(),
registrationData.getCollectedClientData(),
registrationData.getAttestationObject().getAuthenticatorData().getSignCount());
}
/// Initiates a WebAuthn authentication ceremony.
///
/// Each call generates, and replaces any existing, [challenge](https://www.w3.org/TR/webauthn/#sctn-cryptographic-challenges).
///
/// @param identifier the identifier of the account to be authenticated
/// @param existingCredentials a list of stored credential records for the user being authenticated
///
/// @return a [AuthenticationCeremonyParameters] record with the details
/// needed by a client in possession of a matching authenticator to complete
/// the ceremony
public AuthenticationCeremonyParameters startAuthentication(final UUID identifier, List<? extends CredentialRecord> existingCredentials) {
final byte[] challengeKey = challengeKey(identifier);
final byte[] challenge = new byte[16];
SECURE_RANDOM.nextBytes(challenge);
ResilienceUtil.getGeneralRedisRetry(RETRY_NAME)
.executeRunnable(
() -> challengeStorageCluster.withBinaryCluster(cluster -> cluster.sync().set(challengeKey, challenge, SetArgs.Builder.ex(challengeTtl.toSeconds()))));
return new AuthenticationCeremonyParameters(
challenge,
challengeTtl,
existingCredentials.stream().map(cr -> cr.getAttestedCredentialData().getCredentialId()).toList());
}
/// Parses an authenticator response JSON blob, whose format is specified in the WebAuthn Technical Report
public AuthenticationData parseAuthenticationResponse(final String authenticationResponseJson) throws WebAuthnException {
try {
return webAuthnManager.parseAuthenticationResponseJSON(authenticationResponseJson);
} catch (final NullPointerException | JacksonException e) {
throw new WebAuthnException(e);
}
}
/// Verifies an authenticator response to a WebAuthn authentication ceremony, consuming any existing stored challenge.
///
/// If verification succeeds, the `CredentialRecord` is [updated in-place](https://www.w3.org/TR/webauthn-3/#authn-ceremony-update-credential-record).
///
/// @param identifier the identifier of the account to be authenticated
/// @param matchingCredential the stored credential record for the account to be authenticated with an ID matching the one from the authenticator response
/// @param authenticationData the parsed authenticator response
///
///
/// @throws VerificationException if the response could not be verified for any reason (incorrect signature, incorrect or expired challenge)
public void verifyAuthentication(
final UUID identifier,
final CredentialRecord matchingCredential,
final AuthenticationData authenticationData) throws VerificationException {
final byte[] challengeKey = challengeKey(identifier);
@Nullable final byte[] challenge = ResilienceUtil.getGeneralRedisRetry(RETRY_NAME)
.executeSupplier(() -> challengeStorageCluster.withBinaryCluster(cluster -> cluster.sync().getdel(challengeKey)));
//noinspection ConstantValue
if (challenge == null) {
throw new BadChallengeException("no challenge stored");
}
final byte[] credentialId = matchingCredential.getAttestedCredentialData().getCredentialId();
final AuthenticationParameters authenticationParameters = new AuthenticationParameters(
ServerProperty.builder()
.origins(origins)
.rpId(rpId)
.challenge(() -> challenge)
.build(),
matchingCredential,
List.of(credentialId),
false,
true);
webAuthnManager.verify(authenticationData, authenticationParameters);
}
/// @return `true` if [CredentialRecord]s represent the same actual credential ID. Note that this is more specific than
/// whether they came from the same authenticator device, which cannot be determined in general.
public static boolean isSameCredential(final CredentialRecord a, final CredentialRecord b) {
return Arrays.equals(a.getAttestedCredentialData().getCredentialId(), b.getAttestedCredentialData().getCredentialId());
}
@VisibleForTesting
static byte[] challengeKey(final UUID identifier) {
return String.format("webauthn_challenge::{%s}", identifier).getBytes(StandardCharsets.UTF_8);
}
private byte[] blindIdentifier(final UUID identifier) {
return HmacUtils.hmac256Truncated(blindingSecret, UUIDUtil.toBytes(identifier), 32);
}
}
@@ -9,7 +9,6 @@ import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import com.google.common.annotations.VisibleForTesting;
import io.micrometer.core.instrument.Metrics;
import jakarta.ws.rs.BadRequestException;
import java.io.IOException;
import java.util.Locale;
import java.util.Optional;
@@ -19,6 +18,8 @@ import java.util.function.Function;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
public class CaptchaChecker {
private static final Logger logger = LoggerFactory.getLogger(CaptchaChecker.class);
@@ -33,12 +34,15 @@ public class CaptchaChecker {
private final ShortCodeExpander shortCodeExpander;
private final Function<String, CaptchaClient> captchaClientSupplier;
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
public CaptchaChecker(
final ShortCodeExpander shortCodeRetriever,
final Function<String, CaptchaClient> captchaClientSupplier) {
final Function<String, CaptchaClient> captchaClientSupplier,
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
this.shortCodeExpander = shortCodeRetriever;
this.captchaClientSupplier = captchaClientSupplier;
this.dynamicConfigurationManager = dynamicConfigurationManager;
}
@@ -105,12 +109,21 @@ public class CaptchaChecker {
throw new InvalidCaptchaArgumentException("invalid captcha site-key");
}
final AssessmentResult result = client.verify(maybeAci, siteKey, parsedAction, token, ip, userAgent);
Metrics.counter(ASSESSMENTS_COUNTER_NAME,
"action", action,
"score", result.getScoreString(),
"provider", provider)
.increment();
return result;
try {
final AssessmentResult result = client.verify(maybeAci, siteKey, parsedAction, token, ip, userAgent);
Metrics.counter(ASSESSMENTS_COUNTER_NAME,
"action", action,
"score", result.getScoreString(),
"provider", provider)
.increment();
return result;
} catch (final IOException | RuntimeException e) {
if (dynamicConfigurationManager.getConfiguration().getCaptchaConfiguration().isFailOpen()) {
logger.warn("Failed to verify captcha; failing open", e);
return AssessmentResult.alwaysValid();
}
throw e;
}
}
}
@@ -6,13 +6,12 @@
package org.whispersystems.textsecuregcm.configuration;
import com.apple.itunes.storekit.model.Environment;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import java.util.List;
import java.util.Map;
import org.whispersystems.textsecuregcm.configuration.secrets.SecretString;
import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel;
import org.whispersystems.textsecuregcm.purchases.ReceiptLevel;
import javax.annotation.Nullable;
/**
@@ -13,7 +13,7 @@ import com.fasterxml.jackson.annotation.Nulls;
import io.dropwizard.validation.ValidationMethod;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel;
import org.whispersystems.textsecuregcm.purchases.ReceiptLevel;
import java.util.List;
import java.util.Map;
import java.util.Objects;
@@ -13,7 +13,7 @@ import java.util.Map;
import java.util.Set;
import javax.annotation.Nullable;
import org.whispersystems.textsecuregcm.configuration.secrets.SecretString;
import org.whispersystems.textsecuregcm.subscriptions.PaymentMethod;
import org.whispersystems.textsecuregcm.purchases.PaymentMethod;
/**
* @param merchantId the Braintree merchant ID
@@ -0,0 +1,45 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.github.resilience4j.bulkhead.BulkheadConfig;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
import java.time.Duration;
public class BulkheadConfiguration {
@JsonProperty
@Min(1)
private int maxConcurrentCalls = BulkheadConfig.DEFAULT_MAX_CONCURRENT_CALLS;
@JsonProperty
@NotNull
private Duration maxWaitDuration = BulkheadConfig.DEFAULT_MAX_WAIT_DURATION;
public int getMaxConcurrentCalls() {
return maxConcurrentCalls;
}
public void setMaxConcurrentCalls(final int maxConcurrentCalls) {
this.maxConcurrentCalls = maxConcurrentCalls;
}
public Duration getMaxWaitDuration() {
return maxWaitDuration;
}
public void setMaxWaitDuration(final Duration maxWaitDuration) {
this.maxWaitDuration = maxWaitDuration;
}
public BulkheadConfig.Builder toBulkheadConfig() {
return BulkheadConfig.custom()
.maxConcurrentCalls(maxConcurrentCalls)
.maxWaitDuration(maxWaitDuration);
}
}
@@ -0,0 +1,22 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.PositiveOrZero;
import java.util.List;
import java.util.Optional;
/// Configuration for FoundationDB external clients. Primarily exists because an external client must be specified to
/// make use of the multi-threaded client feature.
///
/// @param clientLibraryPaths a list of paths to external client libraries (generally .so files on Linux). This allows
/// us to run multiple FDB client versions concurrently if needed; however, during normal operation, we expect the list
/// to be a single path pointing to the current FDB client library
/// @param threadsPerClient the number of networking threads spawned per client
public record FoundationDbExternalClientConfiguration(@NotEmpty List<@NotBlank String> clientLibraryPaths,
Optional<@PositiveOrZero Integer> threadsPerClient) {}
@@ -5,6 +5,7 @@
package org.whispersystems.textsecuregcm.configuration;
import jakarta.annotation.Nullable;
import jakarta.validation.Valid;
import jakarta.validation.constraints.AssertTrue;
import jakarta.validation.constraints.Max;
@@ -25,7 +26,7 @@ import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessage
/// @param batchPriorityTransactionTimeout the maximum time for a batch priority transaction. Should be greater than or equal to {@link transactionTimeout}
/// @param batchPriorityTransactionRetryLimit the maximum number of retries permitted _within_ a batch priority transaction
public record FoundationDbMessagesConfiguration(@NotEmpty Map<String, @Valid FoundationDbDatabaseFactory> clusters,
@NotEmpty Map<@PositiveOrZero @Max(FoundationDbMessageStore.MAX_EPOCHS - 1) Integer, @Size(min = 1, max = FoundationDbMessageStore.MAX_SHARDS - 1) List<String>> epochs,
@NotEmpty Map<@PositiveOrZero @Max(FoundationDbMessageStore.MAX_EPOCHS - 1) Integer, @Size(min = 1, max = FoundationDbMessageStore.MAX_SHARDS) List<String>> epochs,
@PositiveOrZero @Max(FoundationDbMessageStore.MAX_EPOCHS - 1) int activeEpoch,
@NotEmpty Map<@PositiveOrZero @Max(63) Integer, SecretBytes> versionstampCipherKeys,
@PositiveOrZero @Max(63) int currentVersionstampCipherKey,
@@ -33,7 +34,10 @@ public record FoundationDbMessagesConfiguration(@NotEmpty Map<String, @Valid Fou
@NotNull Duration transactionTimeout,
@PositiveOrZero long transactionRetryLimit,
@NotNull Duration batchPriorityTransactionTimeout,
@PositiveOrZero long batchPriorityTransactionRetryLimit) {
@PositiveOrZero long batchPriorityTransactionRetryLimit,
@Nullable String circuitBreakerConfigurationName,
@Nullable String bulkheadConfigurationName,
@Nullable @Valid FoundationDbExternalClientConfiguration externalClientConfiguration) {
public static final long DEFAULT_MAX_WATCHES_PER_CLIENT = 10_000;
public static final Duration DEFAULT_TRANSACTION_TIMEOUT = Duration.ofSeconds(1);
@@ -8,8 +8,7 @@ package org.whispersystems.textsecuregcm.configuration;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import java.util.Map;
import org.whispersystems.textsecuregcm.configuration.secrets.SecretString;
import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel;
import org.whispersystems.textsecuregcm.purchases.ReceiptLevel;
/**
* @param credentialsJson Service account credentials for Play Billing API
@@ -4,6 +4,7 @@
*/
package org.whispersystems.textsecuregcm.configuration;
import io.netty.handler.ssl.SslProvider;
import jakarta.validation.constraints.NotNull;
import java.time.Duration;
@@ -15,13 +16,15 @@ import java.time.Duration;
/// @param websocketPort The port of a listening websocket server for handling legacy requests
/// @param idleTimeout The duration after which an idle connection may be disconnected
/// @param h2c If true, listen for plaintext h2c with prior-knowledge
/// @param sslProvider The TLS implementation used to terminate TLS. Defaults to `OPENSSL`.
public record GrpcConfiguration(
@NotNull String bindAddress,
@NotNull Integer port,
@NotNull String websocketAddress,
@NotNull Integer websocketPort,
@NotNull Duration idleTimeout,
boolean h2c) {
boolean h2c,
@NotNull SslProvider sslProvider) {
public GrpcConfiguration {
if (bindAddress == null || bindAddress.isEmpty()) {
@@ -33,5 +36,8 @@ public record GrpcConfiguration(
if (idleTimeout == null) {
idleTimeout = Duration.ofMinutes(5);
}
if (sslProvider == null) {
sslProvider = SslProvider.OPENSSL;
}
}
}
@@ -9,7 +9,7 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.NotEmpty;
import java.util.EnumMap;
import java.util.Map;
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
import org.whispersystems.textsecuregcm.purchases.PaymentProvider;
import org.whispersystems.textsecuregcm.util.EnumMapUtil;
public class IssuedReceiptsTableConfiguration extends DynamoDbTables.Table {
@@ -12,7 +12,9 @@ import java.time.Duration;
/// Configuration for one-time Signal Login purchases
///
/// @param playProductId the Google Play Billing productId clients should purchase to obtain a Signal Login
/// @param playOptionId the Google Play Billing optionId clients should purchase to obtain a Signal Login
/// @param appStoreProductId the App Store productId clients should purchase to obtain a Signal Login
public record LoginPurchaseConfiguration(
@NotEmpty String playProductId,
@NotEmpty String playOptionId,
@NotEmpty String appStoreProductId) {}
@@ -13,7 +13,7 @@ import java.util.Map;
import java.util.Set;
import org.whispersystems.textsecuregcm.configuration.secrets.SecretBytes;
import org.whispersystems.textsecuregcm.configuration.secrets.SecretString;
import org.whispersystems.textsecuregcm.subscriptions.PaymentMethod;
import org.whispersystems.textsecuregcm.purchases.PaymentMethod;
public record StripeConfiguration(@NotNull SecretString apiKey,
@NotNull SecretBytes idempotencyKeyGenerator,
@@ -12,7 +12,7 @@ import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.util.Map;
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
import org.whispersystems.textsecuregcm.purchases.PaymentProvider;
public record SubscriptionPriceConfiguration(@Valid @NotEmpty Map<PaymentProvider, @NotBlank String> processorIds,
@NotNull @DecimalMin("0.01") BigDecimal amount) {
@@ -0,0 +1,21 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import java.time.Duration;
import java.util.List;
import org.whispersystems.textsecuregcm.configuration.secrets.SecretBytes;
import org.whispersystems.textsecuregcm.util.ExactlySize;
public record WebAuthnConfiguration(
@NotBlank String relyingPartyId,
@NotEmpty List<@NotBlank String> origins,
@NotNull Duration challengeTtl,
@NotNull @ExactlySize(32) SecretBytes userHandleBlindingSecret) {
}
@@ -35,6 +35,9 @@ public class DynamicCaptchaConfiguration {
@NotNull
private Map<Action, BigDecimal> scoreFloorByAction = Collections.emptyMap();
@JsonProperty
private boolean failOpen = false;
public BigDecimal getScoreFloor() {
return scoreFloor;
}
@@ -66,4 +69,11 @@ public class DynamicCaptchaConfiguration {
this.hCaptchaSiteKeys = hCaptchaSiteKeys;
}
public boolean isFailOpen() {
return failOpen;
}
public void setFailOpen(final boolean failOpen) {
this.failOpen = failOpen;
}
}
@@ -239,6 +239,10 @@ public class AccountController {
}
});
if (StringUtils.isNotEmpty(attributes.getRegistrationLock()) && a.getNumber().isEmpty()) {
throw new BadRequestException("account does not have a phone number");
}
a.setRegistrationLockFromAttributes(attributes);
a.setUnidentifiedAccessKey(attributes.getUnidentifiedAccessKey());
a.setUnrestrictedUnidentifiedAccess(attributes.isUnrestrictedUnidentifiedAccess());
@@ -2,6 +2,7 @@ package org.whispersystems.textsecuregcm.controllers;
import io.dropwizard.auth.Auth;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
@@ -9,6 +10,7 @@ import jakarta.ws.rs.BadRequestException;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.core.MediaType;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
@@ -26,13 +28,16 @@ import org.whispersystems.textsecuregcm.limits.RateLimiters;
public class CallLinkController {
private final RateLimiters rateLimiters;
private final GenericServerSecretParams genericServerSecretParams;
private final GenericServerSecretParams genericServerSecretParamsPreV101;
public CallLinkController(
final RateLimiters rateLimiters,
final GenericServerSecretParams genericServerSecretParams
final GenericServerSecretParams genericServerSecretParams,
final GenericServerSecretParams genericServerSecretParamsPreV101
) {
this.rateLimiters = rateLimiters;
this.genericServerSecretParams = genericServerSecretParams;
this.genericServerSecretParamsPreV101 = genericServerSecretParamsPreV101;
}
@POST
@@ -52,7 +57,9 @@ public class CallLinkController {
@ApiResponse(responseCode = "429", description = "Ratelimited.")
public CreateCallLinkCredential getCreateAuth(
final @Auth AuthenticatedDevice auth,
final @NotNull @Valid GetCreateCallLinkCredentialsRequest request
final @NotNull @Valid GetCreateCallLinkCredentialsRequest request,
@Parameter(description = "Whether to use libsignal v0.101.0+ secret params")
final @QueryParam("v101") boolean v101
) throws RateLimitExceededException {
rateLimiters.getCreateCallLinkLimiter().validate(auth.accountIdentifier());
@@ -67,7 +74,7 @@ public class CallLinkController {
}
return new CreateCallLinkCredential(
createCallLinkCredentialRequest.issueCredential(new ServiceId.Aci(auth.accountIdentifier()), truncatedDayTimestamp, genericServerSecretParams).serialize(),
createCallLinkCredentialRequest.issueCredential(new ServiceId.Aci(auth.accountIdentifier()), truncatedDayTimestamp, v101 ? genericServerSecretParams : genericServerSecretParamsPreV101).serialize(),
truncatedDayTimestamp.getEpochSecond()
);
}
@@ -10,6 +10,7 @@ import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import com.google.common.annotations.VisibleForTesting;
import io.dropwizard.auth.Auth;
import io.micrometer.core.instrument.Metrics;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.ws.rs.BadRequestException;
import jakarta.ws.rs.DefaultValue;
@@ -49,6 +50,7 @@ public class CertificateController {
private final CertificateGenerator certificateGenerator;
private final ServerZkAuthOperations serverZkAuthOperations;
private final GenericServerSecretParams genericServerSecretParams;
private final GenericServerSecretParams genericServerSecretParamsPreV101;
private final Clock clock;
@VisibleForTesting
@@ -61,12 +63,14 @@ public class CertificateController {
@Nonnull CertificateGenerator certificateGenerator,
@Nonnull ServerZkAuthOperations serverZkAuthOperations,
@Nonnull GenericServerSecretParams genericServerSecretParams,
@Nonnull GenericServerSecretParams genericServerSecretParamsPreV101,
@Nonnull Clock clock) {
this.accountsManager = accountsManager;
this.certificateGenerator = Objects.requireNonNull(certificateGenerator);
this.serverZkAuthOperations = Objects.requireNonNull(serverZkAuthOperations);
this.genericServerSecretParams = genericServerSecretParams;
this.genericServerSecretParamsPreV101 = genericServerSecretParamsPreV101;
this.clock = Objects.requireNonNull(clock);
}
@@ -95,7 +99,9 @@ public class CertificateController {
public GroupCredentials getGroupAuthenticationCredentials(
@Auth AuthenticatedDevice auth,
@QueryParam("redemptionStartSeconds") long startSeconds,
@QueryParam("redemptionEndSeconds") long endSeconds) {
@QueryParam("redemptionEndSeconds") long endSeconds,
@Parameter(description = "Whether to use libsignal v0.101.0+ secret params")
@QueryParam("v101") boolean v101) {
final RedemptionRange redemptionRange;
try {
@@ -127,7 +133,7 @@ public class CertificateController {
(int) redemption.getEpochSecond()));
callLinkAuthCredentials.add(new GroupCredentials.CallLinkAuthCredential(
CallLinkAuthCredentialResponse.issueCredential(aci, redemption, genericServerSecretParams).serialize(),
CallLinkAuthCredentialResponse.issueCredential(aci, redemption, v101 ? genericServerSecretParams : genericServerSecretParamsPreV101).serialize(),
redemption.getEpochSecond()));
}
@@ -40,8 +40,8 @@ import org.whispersystems.textsecuregcm.storage.AccountBadge;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.DonationPermitsManager;
import org.whispersystems.textsecuregcm.storage.RedeemedReceiptsManager;
import org.whispersystems.textsecuregcm.subscriptions.ReceiptCredentialPresentationFactory;
import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel;
import org.whispersystems.textsecuregcm.purchases.ReceiptCredentialPresentationFactory;
import org.whispersystems.textsecuregcm.purchases.ReceiptLevel;
@Path("/v1/donation")
@Tag(name = "Donations")
@@ -29,15 +29,15 @@ import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialRequest;
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialResponse;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.mappers.SubscriptionExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.PurchaseExceptionMapper;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.subscriptions.LoginPurchaseManager;
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidArgumentsException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionNotFoundException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentRequiredException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptAlreadyRedeemedException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptRequestedForOpenPaymentException;
import org.whispersystems.textsecuregcm.purchases.LoginPurchaseManager;
import org.whispersystems.textsecuregcm.purchases.PaymentProvider;
import org.whispersystems.textsecuregcm.purchases.PurchaseInvalidArgumentsException;
import org.whispersystems.textsecuregcm.purchases.PurchaseNotFoundException;
import org.whispersystems.textsecuregcm.purchases.PurchasePaymentRequiredException;
import org.whispersystems.textsecuregcm.purchases.PurchaseReceiptAlreadyRedeemedException;
import org.whispersystems.textsecuregcm.purchases.PurchaseReceiptRequestedForOpenPaymentException;
@Path("/v1/login-purchase")
@io.swagger.v3.oas.annotations.tags.Tag(name = "LoginPurchase")
@@ -91,7 +91,7 @@ public class LoginPurchaseController {
@ApiResponse(responseCode = "402", description = "The purchase did not complete successfully. The body may include ChargeFailure details.",
content = @Content(schema = @Schema(
nullable = true,
implementation = SubscriptionExceptionMapper.ChargeFailureResponse.class)))
implementation = PurchaseExceptionMapper.ChargeFailureResponse.class)))
@ApiResponse(responseCode = "403", description = "The request was made on an authenticated channel")
@ApiResponse(responseCode = "404", description = "The payment provider has no purchase with the provided purchaseIdentifier")
@ApiResponse(responseCode = "409", description = "The purchase was already redeemed for a receipt credential, but with a different receipt credential request")
@@ -102,7 +102,7 @@ public class LoginPurchaseController {
public Response createLoginReceiptCredential(
@Auth final Optional<AuthenticatedDevice> authenticatedAccount,
@NotNull @Valid final CreateLoginReceiptCredentialRequest request)
throws IOException, SubscriptionPaymentRequiredException, SubscriptionInvalidArgumentsException, SubscriptionNotFoundException, RateLimitExceededException, SubscriptionReceiptAlreadyRedeemedException {
throws IOException, PurchasePaymentRequiredException, PurchaseInvalidArgumentsException, PurchaseNotFoundException, RateLimitExceededException, PurchaseReceiptAlreadyRedeemedException {
if (!dynamicConfigurationManager.getConfiguration().getLoginPurchaseConfiguration().enabled()) {
throw new BadRequestException("login purchases are not enabled");
@@ -125,7 +125,7 @@ public class LoginPurchaseController {
return Response.ok(
new CreateLoginReceiptCredentialResponse(receiptCredentialResponse.serialize()))
.build();
} catch (SubscriptionReceiptRequestedForOpenPaymentException e) {
} catch (PurchaseReceiptRequestedForOpenPaymentException e) {
return Response.noContent().build();
} catch (VerificationFailedException e) {
throw new BadRequestException("receipt credential request failed verification", e);
@@ -91,9 +91,9 @@ import org.whispersystems.textsecuregcm.spam.SpamChecker;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
import org.whispersystems.textsecuregcm.storage.ReportMessageHelper;
import org.whispersystems.textsecuregcm.storage.ReportMessageManager;
import org.whispersystems.textsecuregcm.util.HeaderUtils;
import org.whispersystems.textsecuregcm.util.Util;
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
@Path("/v1/messages")
@@ -605,7 +605,7 @@ public class MessageController {
CompletableFuture.allOf(resolvedRecipients.values()
.stream()
.map(account -> account.getAccountIdentifier())
.map(Account::getAccountIdentifier)
.map(accountIdentifier ->
rateLimiters.getStoriesLimiter().validateAsync(accountIdentifier).toCompletableFuture())
.toList()
@@ -731,45 +731,10 @@ public class MessageController {
@Path("/report/{source}/{messageGuid}")
public Response reportSpamMessage(
@Auth AuthenticatedDevice auth,
@PathParam("source") String source,
@PathParam("source") UUID source,
@PathParam("messageGuid") UUID messageGuid,
@Nullable SpamReport spamReport,
@HeaderParam(HttpHeaders.USER_AGENT) String userAgent
) {
final Optional<String> sourceNumber;
final Optional<UUID> sourceAci;
final Optional<UUID> sourcePni;
boolean sourceAccountDeleted = false;
if (source.startsWith("+")) {
sourceNumber = Optional.of(source);
final Optional<Account> maybeAccount = accountsManager.getByE164(source);
if (maybeAccount.isPresent()) {
sourceAci = maybeAccount.map(Account::getAccountIdentifier);
sourcePni = maybeAccount.flatMap(Account::getPhoneNumberIdentifier);
} else {
sourcePni = Optional.ofNullable(phoneNumberIdentifiers.getPhoneNumberIdentifier(source).join());
sourceAci = sourcePni.flatMap(accountsManager::findRecentlyDeletedAccountIdentifier);
sourceAccountDeleted = true;
}
} else {
sourceAci = Optional.of(UUID.fromString(source));
final Optional<Account> sourceAccount = accountsManager.getByAccountIdentifier(sourceAci.get());
if (sourceAccount.isEmpty()) {
logger.warn("Could not find source: {}", sourceAci.get());
sourcePni = accountsManager.findRecentlyDeletedPhoneNumberIdentifier(sourceAci.get());
sourceNumber = sourcePni.flatMap(pni ->
Util.getCanonicalNumber(phoneNumberIdentifiers.getPhoneNumber(pni).join()));
sourceAccountDeleted = true;
} else {
sourceNumber = sourceAccount.flatMap(Account::getNumber);
sourcePni = sourceAccount.flatMap(Account::getPhoneNumberIdentifier);
}
}
final UUID spamReporterUuid = auth.accountIdentifier();
@HeaderParam(HttpHeaders.USER_AGENT) String userAgent) {
// spam report token is optional, but if provided ensure it is non-empty.
final Optional<byte[]> maybeSpamReportToken =
@@ -777,7 +742,14 @@ public class MessageController {
.flatMap(r -> Optional.ofNullable(r.token()))
.filter(t -> t.length > 0);
reportMessageManager.report(sourceNumber, sourceAci, sourcePni, messageGuid, spamReporterUuid, maybeSpamReportToken, userAgent, sourceAccountDeleted);
ReportMessageHelper.reportMessage(new AciServiceIdentifier(source),
new AciServiceIdentifier(auth.accountIdentifier()),
messageGuid,
maybeSpamReportToken.orElse(null),
userAgent,
accountsManager,
phoneNumberIdentifiers,
reportMessageManager);
return Response.status(Status.ACCEPTED)
.build();
@@ -62,21 +62,23 @@ import org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil;
import org.whispersystems.textsecuregcm.limits.RateLimitedByIp;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.purchases.BraintreeManager;
import org.whispersystems.textsecuregcm.purchases.ChargeFailure;
import org.whispersystems.textsecuregcm.purchases.CustomerAwareSubscriptionPaymentProcessor;
import org.whispersystems.textsecuregcm.purchases.PayPalDonationsTranslator;
import org.whispersystems.textsecuregcm.purchases.PaymentDetails;
import org.whispersystems.textsecuregcm.purchases.PaymentMethod;
import org.whispersystems.textsecuregcm.purchases.PaymentProvider;
import org.whispersystems.textsecuregcm.purchases.PurchaseInvalidAmountException;
import org.whispersystems.textsecuregcm.purchases.PurchaseNotFoundException;
import org.whispersystems.textsecuregcm.purchases.PurchasePaymentRequiredException;
import org.whispersystems.textsecuregcm.purchases.PurchaseProcessorException;
import org.whispersystems.textsecuregcm.purchases.PurchaseReceiptRequestedForOpenPaymentException;
import org.whispersystems.textsecuregcm.purchases.StripeManager;
import org.whispersystems.textsecuregcm.storage.DonationPermitsManager;
import org.whispersystems.textsecuregcm.storage.IssuedReceiptsManager;
import org.whispersystems.textsecuregcm.storage.OneTimeDonationsManager;
import org.whispersystems.textsecuregcm.storage.WriteConflictException;
import org.whispersystems.textsecuregcm.subscriptions.BraintreeManager;
import org.whispersystems.textsecuregcm.subscriptions.ChargeFailure;
import org.whispersystems.textsecuregcm.subscriptions.CustomerAwareSubscriptionPaymentProcessor;
import org.whispersystems.textsecuregcm.subscriptions.PayPalDonationsTranslator;
import org.whispersystems.textsecuregcm.subscriptions.PaymentDetails;
import org.whispersystems.textsecuregcm.subscriptions.PaymentMethod;
import org.whispersystems.textsecuregcm.subscriptions.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;
@@ -179,7 +181,7 @@ public class OneTimeDonationController {
@HeaderParam(HeaderUtils.DONATION_PERMIT) final Optional<DonationPermitHeader> donationPermitHeader,
@NotNull @Valid final CreateBoostRequest request,
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent) throws SubscriptionInvalidAmountException {
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent) throws PurchaseInvalidAmountException {
if (authenticatedAccount.isPresent()) {
throw new ForbiddenException("must not use authenticated connection for one-time donation operations");
@@ -199,7 +201,7 @@ public class OneTimeDonationController {
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
}
validateRequestCurrencyAmount(request, BigDecimal.valueOf(request.amount), stripeManager);
validateRequestCurrencyAmount(request, request.amount, stripeManager);
final PaymentIntent paymentIntent = stripeManager.createPaymentIntent(request.currency, request.amount,
request.level,
getClientPlatform(userAgent));
@@ -212,7 +214,7 @@ public class OneTimeDonationController {
*
* @throws BadRequestException indicates validation failed. Inspect {@code response.error} for details
*/
private void validateRequestCurrencyAmount(final CreateBoostRequest request, final BigDecimal amount,
private void validateRequestCurrencyAmount(final CreateBoostRequest request, final long amount,
final CustomerAwareSubscriptionPaymentProcessor manager) {
final Map<String, String> errorBody = switch (OneTimeDonationUtil.validateOneTimeDonationRequest(request.currency,
@@ -222,11 +224,9 @@ public class OneTimeDonationController {
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.UnsupportedCurrency _ ->
Map.of("error", "unsupported_currency");
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.AmountBelowMinimum(final BigDecimal min) ->
Map.of("error", "amount_below_currency_minimum",
"minimum", min.toString());
Map.of("error", "amount_below_currency_minimum", "minimum", min.toString());
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.AmountAboveSepaLimit(final BigDecimal max) ->
Map.of("error", "amount_above_sepa_limit",
"maximum", max.toString());
Map.of("error", "amount_above_sepa_limit", "maximum", max.toString());
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.Success _ -> Collections.emptyMap();
};
@@ -265,7 +265,7 @@ public class OneTimeDonationController {
throw new ForbiddenException("must not use authenticated connection for one-time donation operations");
}
validateRequestCurrencyAmount(request, BigDecimal.valueOf(request.amount), braintreeManager);
validateRequestCurrencyAmount(request, request.amount, braintreeManager);
final List<Locale> acceptableLanguages =
HeaderUtils.getAcceptableLanguagesForRequest(containerRequestContext);
final OneTimeDonationUtil.LocalizedPayPalDonationLineItem localizedLineItem = OneTimeDonationUtil.localizePayPalDonationLineItem(
@@ -301,13 +301,13 @@ public class OneTimeDonationController {
public ConfirmPayPalBoostResponse confirmPayPalBoost(
@Auth final Optional<AuthenticatedDevice> authenticatedAccount,
@NotNull @Valid final ConfirmPayPalBoostRequest request,
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent) throws SubscriptionProcessorException, IOException {
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent) throws PurchaseProcessorException, IOException {
if (authenticatedAccount.isPresent()) {
throw new ForbiddenException("must not use authenticated connection for one-time donation operations");
}
validateRequestCurrencyAmount(request, BigDecimal.valueOf(request.amount), braintreeManager);
validateRequestCurrencyAmount(request, request.amount, braintreeManager);
final BraintreeManager.PayPalChargeSuccessDetails chargeSuccessDetails = braintreeManager.captureOneTimePayment(
request.payerId, request.paymentId,
request.paymentToken, request.currency, request.amount, request.level, getClientPlatform(userAgent));
@@ -315,7 +315,7 @@ public class OneTimeDonationController {
return new ConfirmPayPalBoostResponse(chargeSuccessDetails.paymentId());
}
public static class CreateBoostReceiptCredentialsRequest {
public static class CreateBoostReceiptCredentialRequest {
/**
* a payment ID from {@link #processor}
@@ -329,10 +329,10 @@ public class OneTimeDonationController {
public PaymentProvider processor = PaymentProvider.STRIPE;
}
public record CreateBoostReceiptCredentialsSuccessResponse(byte[] receiptCredentialResponse) {
public record CreateBoostReceiptCredentialSuccessResponse(byte[] receiptCredentialResponse) {
}
public record CreateBoostReceiptCredentialsErrorResponse(
public record CreateBoostReceiptCredentialErrorResponse(
@JsonInclude(JsonInclude.Include.NON_NULL) ChargeFailure chargeFailure) {}
@POST
@@ -340,36 +340,32 @@ public class OneTimeDonationController {
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@ManagedAsync
public Response createBoostReceiptCredentials(
public Response createBoostReceiptCredential(
@Auth final Optional<AuthenticatedDevice> authenticatedAccount,
@NotNull @Valid final CreateBoostReceiptCredentialsRequest request,
@NotNull @Valid final CreateBoostReceiptCredentialRequest request,
@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 Optional<PaymentDetails> maybePaymentDetails = (switch (request.processor) {
case STRIPE -> stripeManager.claimOneTimePurchase(request.paymentIntentId);
case BRAINTREE -> braintreeManager.claimOneTimePurchase(request.paymentIntentId);
case GOOGLE_PLAY_BILLING -> throw new BadRequestException("cannot use play billing for one-time donations");
case APPLE_APP_STORE -> throw new BadRequestException("cannot use app store purchases for one-time donations");
});
if (maybePaymentDetails.isEmpty()) {
final PaymentDetails paymentDetails;
try {
paymentDetails = (switch (request.processor) {
case STRIPE -> stripeManager.claimOneTimePurchase(request.paymentIntentId);
case BRAINTREE -> braintreeManager.claimOneTimePurchase(request.paymentIntentId);
case GOOGLE_PLAY_BILLING -> throw new BadRequestException("cannot use play billing for one-time donations");
case APPLE_APP_STORE -> throw new BadRequestException("cannot use app store purchases for one-time donations");
});
} catch (PurchaseNotFoundException _) {
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
final PaymentDetails paymentDetails = maybePaymentDetails.get();
if (paymentDetails.status() == PaymentStatus.PROCESSING) {
} catch (PurchaseReceiptRequestedForOpenPaymentException _) {
return Response.noContent().build();
}
if (paymentDetails.status() != PaymentStatus.SUCCEEDED) {
} catch (PurchasePaymentRequiredException e) {
throw new WebApplicationException(Response.status(Response.Status.PAYMENT_REQUIRED)
.entity(new CreateBoostReceiptCredentialsErrorResponse(paymentDetails.chargeFailure())).build());
.entity(new CreateBoostReceiptCredentialErrorResponse(e.getChargeFailure().orElse(null))).build());
}
// The payment was successful, try to issue the receipt credential
final OneTimeDonationUtil.DonationLevelDetails levelDetails;
try {
levelDetails = OneTimeDonationUtil.getLevelDetails(paymentDetails, oneTimeDonationConfiguration);
@@ -377,6 +373,7 @@ public class OneTimeDonationController {
throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
}
// try to issue the receipt credential
final ReceiptCredentialRequest receiptCredentialRequest;
try {
receiptCredentialRequest = new ReceiptCredentialRequest(request.receiptCredentialRequest);
@@ -408,7 +405,7 @@ public class OneTimeDonationController {
UserAgentTagUtil.getPlatformTag(userAgent)))
.increment();
return Response.ok(
new CreateBoostReceiptCredentialsSuccessResponse(receiptCredentialResponse.serialize()))
new CreateBoostReceiptCredentialSuccessResponse(receiptCredentialResponse.serialize()))
.build();
}
}
@@ -53,6 +53,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.auth.BasicAuthorizationHeader;
import org.whispersystems.textsecuregcm.auth.InvalidRegistrationSessionException;
import org.whispersystems.textsecuregcm.auth.MfaFailureException;
import org.whispersystems.textsecuregcm.auth.PhoneVerificationTokenManager;
import org.whispersystems.textsecuregcm.auth.RecoveryPasswordVerificationFailedException;
import org.whispersystems.textsecuregcm.auth.RegistrationLockFailureException;
@@ -66,18 +67,21 @@ import org.whispersystems.textsecuregcm.entities.RegistrationLockFailure;
import org.whispersystems.textsecuregcm.entities.RegistrationRequest;
import org.whispersystems.textsecuregcm.filters.RemoteAddressFilter;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.mappers.MfaFailureExceptionMapper;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.spam.RegistrationFraudChecker;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.AnnotatedTotpKey;
import org.whispersystems.textsecuregcm.storage.AnnotatedWebAuthnCredential;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import org.whispersystems.textsecuregcm.storage.DeviceIdentityInfo;
import org.whispersystems.textsecuregcm.storage.DeviceSpec;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.storage.PhoneNumberRecoveryPasswordsManager;
import org.whispersystems.textsecuregcm.storage.ReceiptAlreadyRedeemedException;
import org.whispersystems.textsecuregcm.subscriptions.ReceiptCredentialPresentationFactory;
import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel;
import org.whispersystems.textsecuregcm.purchases.ReceiptCredentialPresentationFactory;
import org.whispersystems.textsecuregcm.purchases.ReceiptLevel;
import org.whispersystems.textsecuregcm.util.HeaderUtils;
import org.whispersystems.textsecuregcm.util.Util;
@@ -141,7 +145,7 @@ public class RegistrationController {
""")
@ApiResponse(responseCode = "200", description = "Account creation succeeded", useReturnTypeSchema = true)
@ApiResponse(responseCode = "400", description = "Invalid session ID or receipt credential presentation")
@ApiResponse(responseCode = "401", description = "The session identified in the request is not verified")
@ApiResponse(responseCode = "401", description = "The session identified in the request is not verified, or the receipt credential presented fails verification, is expired, or is already redeemed")
@ApiResponse(responseCode = "403", description = "Verification failed for the provided Registration Recovery Password")
@ApiResponse(responseCode = "409", description = "The caller has not explicitly elected to skip transferring data from another device, but a device transfer is technically possible")
@ApiResponse(responseCode = "422", description = "The request did not pass validation")
@@ -149,7 +153,12 @@ public class RegistrationController {
@ApiResponse(responseCode = "429", description = "Too many attempts", headers = @Header(
name = "Retry-After",
description = "If present, an positive integer indicating the number of seconds before a subsequent attempt could succeed"))
@ApiResponse(responseCode = "441", description = "A valid one-time password (TOTP) is required, but either no password was provided or it was incorrect")
@ApiResponse(responseCode = "441",
description = """
Second factor authentication failed. Either the account has one or more factors configured, and the request’s
factor was incorrect or absent, or the account has no factors, but the request included a factor.
""",
content = @Content(schema = @Schema(implementation = MfaFailureExceptionMapper.MfaFailureResponse.class)))
@ApiResponse(responseCode = "499", description = "Client must support post-quantum ratchet")
public AccountCreationResponse register(
@Parameter(
@@ -171,7 +180,7 @@ public class RegistrationController {
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
@NotNull @Valid final RegistrationRequest registrationRequest,
@Context final ContainerRequestContext requestContext)
throws RateLimitExceededException, InterruptedException, RegistrationLockFailureException {
throws RateLimitExceededException, InterruptedException, RegistrationLockFailureException, MfaFailureException {
if (!registrationRequest.isEverySignedKeyValid(userAgent)) {
throw new WebApplicationException("Invalid signature", 422);
@@ -219,7 +228,7 @@ public class RegistrationController {
final ContainerRequestContext requestContext,
final String userAgent,
final String signalAgent)
throws RateLimitExceededException, InterruptedException, RegistrationLockFailureException {
throws RateLimitExceededException, InterruptedException, RegistrationLockFailureException, MfaFailureException {
if (registrationRequest.pniIdentityKey() == null) {
// RegistrationRequest checks that either all phone number-associated information is present or all is absent
@@ -249,7 +258,7 @@ public class RegistrationController {
// There can be at most one existing account for a set of numbers in the same equivalence class, so it's sufficient
// to find the first one.
final Optional<Account> existingAccount = Util.getAlternateForms(number)
Optional<Account> existingAccount = Util.getAlternateForms(number)
.stream()
.map(accounts::getByE164)
.filter(Optional::isPresent)
@@ -274,7 +283,7 @@ public class RegistrationController {
registrationRequest.accountAttributes().getRegistrationLock(),
userAgent, RegistrationLockVerificationManager.Flow.REGISTRATION, verificationType);
checkTotp(existingAccount.get(), registrationRequest.totp());
existingAccount = Optional.of(checkMfa(existingAccount.get(), registrationRequest.webAuthnResponse(), registrationRequest.totp()));
}
final Account account = accounts.create(number,
@@ -348,12 +357,12 @@ public class RegistrationController {
try {
serverZkReceiptOperations.verifyReceiptCredentialPresentation(receiptCredentialPresentation);
} catch (VerificationFailedException _) {
throw new BadRequestException("Receipt credential presentation verification failed");
throw new NotAuthorizedException("Receipt credential presentation verification failed");
}
final Instant receiptExpiration = Instant.ofEpochSecond(receiptCredentialPresentation.getReceiptExpirationTime());
if (clock.instant().isAfter(receiptExpiration)) {
throw new BadRequestException("Receipt is already expired");
throw new NotAuthorizedException("Receipt is already expired");
}
final long receiptLevel = receiptCredentialPresentation.getReceiptLevel();
@@ -386,7 +395,7 @@ public class RegistrationController {
final AccountIdentityResponse accountIdentityResponse = new AccountIdentityResponseBuilder(account).build();
return new AccountCreationResponse(accountIdentityResponse, false);
} catch (ReceiptAlreadyRedeemedException _) {
throw new BadRequestException("Receipt already redeemed");
throw new NotAuthorizedException("Receipt already redeemed");
}
}
@@ -394,7 +403,7 @@ public class RegistrationController {
final String password,
final RegistrationRequest registrationRequest,
final String userAgent,
final String signalAgent) throws RegistrationLockFailureException, RateLimitExceededException {
final String signalAgent) throws RegistrationLockFailureException, RateLimitExceededException, MfaFailureException {
if (!dynamicConfigurationManager.getConfiguration().getLoginPurchaseConfiguration().enabled()) {
throw new BadRequestException("login purchases are not enabled");
@@ -412,7 +421,7 @@ public class RegistrationController {
throw new BadRequestException("Must specify a PNI-associated identity key when recovering an account by identifier");
}
final Account existingAccount = accounts.getByAccountIdentifier(accountIdentifier)
Account existingAccount = accounts.getByAccountIdentifier(accountIdentifier)
.orElseThrow(ForbiddenException::new);
final boolean passwordVerified = existingAccount.getAccountRecoveryPassword()
@@ -423,14 +432,14 @@ public class RegistrationController {
throw new ForbiddenException();
}
checkTotp(existingAccount, registrationRequest.totp());
if (!registrationRequest.skipDeviceTransfer() && existingAccount.hasCapability(DeviceCapability.TRANSFER)) {
// If a device transfer is possible, clients must explicitly opt out of a transfer (i.e. after prompting the user)
// before we'll let them recover an account and start "from scratch"
throw new WebApplicationException(Response.status(409, "device transfer available").build());
}
existingAccount = checkMfa(existingAccount, registrationRequest.webAuthnResponse(), registrationRequest.totp());
final Account reclaimedAccount = existingAccount.getNumber().isPresent()
? recoverAccountWithPhoneNumber(existingAccount, registrationRequest, password, userAgent, signalAgent)
: recoverAccountWithoutPhoneNumber(existingAccount, registrationRequest, password, userAgent, signalAgent);
@@ -508,11 +517,39 @@ public class RegistrationController {
userAgent);
}
private void checkTotp(final Account account, @Nullable final Integer totp) throws RateLimitExceededException {
rateLimiters.getCheckTotpLimiter().validate(account.getAccountIdentifier());
/// @return the maybe-updated [Account] reference. Callers must use it to avoid stale reads and updates.
private Account checkMfa(final Account account, @Nullable final String webAuthn, @Nullable final Integer totp) throws RateLimitExceededException, MfaFailureException {
if (!accounts.verifyTotp(account, clock.instant(), totp)) {
throw new WebApplicationException(441);
final boolean hasTotp = account.getMfaKeys().values().stream().anyMatch(k -> k instanceof AnnotatedTotpKey);
final boolean hasWebAuthn = account.getMfaKeys().values().stream().anyMatch(k -> k instanceof AnnotatedWebAuthnCredential);
if (!hasTotp && !hasWebAuthn) {
if (totp != null || webAuthn != null) {
throw new MfaFailureException(null, false);
}
return account;
}
if (totp != null || webAuthn != null) {
rateLimiters.getCheckMfaLimiter().validate(account.getAccountIdentifier());
}
final Optional<Account> updatedAccount;
if (hasWebAuthn && webAuthn != null) {
updatedAccount = accounts.verifyWebAuthnAuthentication(account, webAuthn);
} else {
updatedAccount = Optional.empty();
}
final boolean webAuthnVerified = updatedAccount.isPresent();
final boolean totpVerified = hasTotp && totp != null
&& accounts.verifyTotp(account, clock.instant(), totp);
if (webAuthnVerified || totpVerified) {
return updatedAccount.orElse(account);
}
throw new MfaFailureException(accounts.startWebAuthnAuthentication(account).orElse(null), hasTotp);
}
}
@@ -72,32 +72,32 @@ import org.whispersystems.textsecuregcm.configuration.SubscriptionLevelConfigura
import org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil;
import org.whispersystems.textsecuregcm.limits.RateLimitedByIp;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.mappers.SubscriptionExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.PurchaseExceptionMapper;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.storage.DonationPermitsManager;
import org.whispersystems.textsecuregcm.storage.SubscriberCredentials;
import org.whispersystems.textsecuregcm.storage.SubscriptionManager;
import org.whispersystems.textsecuregcm.storage.Subscriptions;
import org.whispersystems.textsecuregcm.subscriptions.AppleAppStoreManager;
import org.whispersystems.textsecuregcm.subscriptions.BankMandateTranslator;
import org.whispersystems.textsecuregcm.subscriptions.BankTransferType;
import org.whispersystems.textsecuregcm.subscriptions.BraintreeManager;
import org.whispersystems.textsecuregcm.subscriptions.ChargeFailure;
import org.whispersystems.textsecuregcm.subscriptions.CurrencyConfiguration;
import org.whispersystems.textsecuregcm.subscriptions.CustomerAwareSubscriptionPaymentProcessor;
import org.whispersystems.textsecuregcm.subscriptions.GooglePlayBillingManager;
import org.whispersystems.textsecuregcm.subscriptions.LevelConfiguration;
import org.whispersystems.textsecuregcm.subscriptions.PaymentMethod;
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
import org.whispersystems.textsecuregcm.subscriptions.ProcessorCustomer;
import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel;
import org.whispersystems.textsecuregcm.subscriptions.StripeManager;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidArgumentsException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidLevelException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentRequiresActionException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptRequestedForOpenPaymentException;
import org.whispersystems.textsecuregcm.purchases.AppleAppStoreManager;
import org.whispersystems.textsecuregcm.purchases.BankMandateTranslator;
import org.whispersystems.textsecuregcm.purchases.BankTransferType;
import org.whispersystems.textsecuregcm.purchases.BraintreeManager;
import org.whispersystems.textsecuregcm.purchases.ChargeFailure;
import org.whispersystems.textsecuregcm.purchases.CurrencyConfiguration;
import org.whispersystems.textsecuregcm.purchases.CustomerAwareSubscriptionPaymentProcessor;
import org.whispersystems.textsecuregcm.purchases.GooglePlayBillingManager;
import org.whispersystems.textsecuregcm.purchases.LevelConfiguration;
import org.whispersystems.textsecuregcm.purchases.PaymentMethod;
import org.whispersystems.textsecuregcm.purchases.PaymentProvider;
import org.whispersystems.textsecuregcm.purchases.ProcessorCustomer;
import org.whispersystems.textsecuregcm.purchases.ReceiptLevel;
import org.whispersystems.textsecuregcm.purchases.StripeManager;
import org.whispersystems.textsecuregcm.purchases.PurchaseException;
import org.whispersystems.textsecuregcm.purchases.PurchaseInvalidArgumentsException;
import org.whispersystems.textsecuregcm.purchases.PurchaseInvalidLevelException;
import org.whispersystems.textsecuregcm.purchases.PurchasePaymentRequiresActionException;
import org.whispersystems.textsecuregcm.purchases.PurchaseReceiptRequestedForOpenPaymentException;
import org.whispersystems.textsecuregcm.util.HeaderUtils;
@Path("/v1/subscription")
@@ -171,7 +171,9 @@ public class SubscriptionController {
buildDonationLevelsConfiguration(subscriptionConfiguration, oneTimeDonationConfiguration, badgeTranslator,
acceptableLanguages),
new BackupConfiguration(backupLevels, subscriptionConfiguration.getbackupFreeTierMediaDuration().toDays()),
new LoginConfiguration(ReceiptLevel.LOGIN.getValue(), loginPurchaseConfiguration.playProductId(),
new LoginConfiguration(ReceiptLevel.LOGIN.getValue(),
loginPurchaseConfiguration.playProductId(),
loginPurchaseConfiguration.playOptionId(),
loginPurchaseConfiguration.appStoreProductId()),
oneTimeDonationConfiguration.sepaMaximumEuros());
}
@@ -195,7 +197,7 @@ public class SubscriptionController {
@ManagedAsync
public Response deleteSubscriber(
@Auth Optional<AuthenticatedDevice> authenticatedAccount,
@PathParam("subscriberId") String subscriberId) throws SubscriptionException, RateLimitExceededException {
@PathParam("subscriberId") String subscriberId) throws PurchaseException, RateLimitExceededException {
SubscriberCredentials subscriberCredentials =
SubscriberCredentials.process(authenticatedAccount, subscriberId, clock);
subscriptionManager.deleteSubscriber(subscriberCredentials);
@@ -227,7 +229,7 @@ public class SubscriptionController {
@HeaderParam(HttpHeaders.USER_AGENT) @Nullable final String userAgent,
@PathParam("subscriberId") String subscriberId) throws SubscriptionException {
@PathParam("subscriberId") String subscriberId) throws PurchaseException {
SubscriberCredentials subscriberCredentials =
SubscriberCredentials.process(authenticatedAccount, subscriberId, clock);
@@ -275,7 +277,7 @@ public class SubscriptionController {
@PathParam("subscriberId") String subscriberId,
@QueryParam("type") @DefaultValue("CARD") PaymentMethod paymentMethodType,
@HeaderParam(HttpHeaders.USER_AGENT) @Nullable final String userAgentString) throws SubscriptionException {
@HeaderParam(HttpHeaders.USER_AGENT) @Nullable final String userAgentString) throws PurchaseException {
SubscriberCredentials subscriberCredentials =
SubscriberCredentials.process(authenticatedAccount, subscriberId, clock);
@@ -330,7 +332,7 @@ public class SubscriptionController {
@NotNull @Valid CreatePayPalBillingAgreementRequest request,
@Context ContainerRequestContext containerRequestContext,
@HeaderParam(HttpHeaders.USER_AGENT) @Nullable final String userAgentString)
throws SubscriptionException, IOException {
throws PurchaseException, IOException {
final SubscriberCredentials subscriberCredentials =
SubscriberCredentials.process(authenticatedAccount, subscriberId, clock);
@@ -363,7 +365,7 @@ public class SubscriptionController {
@Auth Optional<AuthenticatedDevice> authenticatedAccount,
@PathParam("subscriberId") String subscriberId,
@PathParam("processor") PaymentProvider processor,
@PathParam("paymentMethodToken") @NotEmpty String paymentMethodToken) throws SubscriptionException, IOException {
@PathParam("paymentMethodToken") @NotEmpty String paymentMethodToken) throws PurchaseException, IOException {
SubscriberCredentials subscriberCredentials =
SubscriberCredentials.process(authenticatedAccount, subscriberId, clock);
@@ -403,7 +405,7 @@ public class SubscriptionController {
@PathParam("subscriberId") String subscriberId,
@PathParam("level") long level,
@PathParam("currency") String currency,
@PathParam("idempotencyKey") String idempotencyKey) throws SubscriptionException {
@PathParam("idempotencyKey") String idempotencyKey) throws PurchaseException {
SubscriberCredentials subscriberCredentials =
SubscriberCredentials.process(authenticatedAccount, subscriberId, clock);
try {
@@ -422,19 +424,19 @@ public class SubscriptionController {
subscriptionManager.updateSubscriptionLevelForCustomer(subscriberCredentials, record, manager, level,
currency, idempotencyKey, subscriptionTemplateId, this::subscriptionsAreSameType);
return new SetSubscriptionLevelSuccessResponse(level);
} catch (SubscriptionInvalidLevelException e) {
} catch (PurchaseInvalidLevelException e) {
throw new BadRequestException(Response.status(Response.Status.BAD_REQUEST)
.entity(new SubscriptionController.SetSubscriptionLevelErrorResponse(List.of(
new SubscriptionController.SetSubscriptionLevelErrorResponse.Error(
SubscriptionController.SetSubscriptionLevelErrorResponse.Error.Type.UNSUPPORTED_LEVEL,
null))))
.build());
} catch (SubscriptionPaymentRequiresActionException e) {
} catch (PurchasePaymentRequiresActionException e) {
throw new BadRequestException(Response.status(Response.Status.BAD_REQUEST)
.entity(new SetSubscriptionLevelErrorResponse(List.of(new SetSubscriptionLevelErrorResponse.Error(
SetSubscriptionLevelErrorResponse.Error.Type.PAYMENT_REQUIRES_ACTION, null))))
.build());
} catch (SubscriptionInvalidArgumentsException e) {
} catch (PurchaseInvalidArgumentsException e) {
throw new BadRequestException(Response.status(Response.Status.BAD_REQUEST)
.entity(new SetSubscriptionLevelErrorResponse(List.of(new SetSubscriptionLevelErrorResponse.Error(
SetSubscriptionLevelErrorResponse.Error.Type.INVALID_ARGUMENTS, e.getMessage()))))
@@ -474,7 +476,7 @@ public class SubscriptionController {
public SetSubscriptionLevelSuccessResponse setAppStoreSubscription(
@Auth Optional<AuthenticatedDevice> authenticatedAccount,
@PathParam("subscriberId") String subscriberId,
@PathParam("originalTransactionId") String originalTransactionId) throws SubscriptionException, RateLimitExceededException {
@PathParam("originalTransactionId") String originalTransactionId) throws PurchaseException, RateLimitExceededException {
final SubscriberCredentials subscriberCredentials =
SubscriberCredentials.process(authenticatedAccount, subscriberId, clock);
@@ -518,7 +520,7 @@ public class SubscriptionController {
public SetSubscriptionLevelSuccessResponse setPlayStoreSubscription(
@Auth Optional<AuthenticatedDevice> authenticatedAccount,
@PathParam("subscriberId") String subscriberId,
@PathParam("purchaseToken") String purchaseToken) throws SubscriptionException, RateLimitExceededException {
@PathParam("purchaseToken") String purchaseToken) throws PurchaseException, RateLimitExceededException {
final SubscriberCredentials subscriberCredentials =
SubscriberCredentials.process(authenticatedAccount, subscriberId, clock);
@@ -549,6 +551,8 @@ public class SubscriptionController {
long level,
@Schema(description = "The play billing productID associated with a Signal Login purchase")
String playProductId,
@Schema(description = "The play billing optionID to use to purchase a Signal Login")
String playOptionId,
@Schema(description = "The App Store productID associated with a Signal Login purchase")
String appStoreProductId) {}
@@ -622,7 +626,7 @@ public class SubscriptionController {
String currency,
@Schema(
description = "The amount paid for the subscription in the currency's smallest unit",
description = "The amount paid for the subscription in the currency's minor unit",
externalDocs = @ExternalDocumentation(description = "Stripe Currencies", url = "https://docs.stripe.com/currencies"))
BigDecimal amount,
@@ -661,7 +665,7 @@ public class SubscriptionController {
@ManagedAsync
public GetSubscriptionInformationResponse getSubscriptionInformation(
@Auth Optional<AuthenticatedDevice> authenticatedAccount,
@PathParam("subscriberId") String subscriberId) throws SubscriptionException, RateLimitExceededException {
@PathParam("subscriberId") String subscriberId) throws PurchaseException, RateLimitExceededException {
SubscriberCredentials subscriberCredentials =
SubscriberCredentials.process(authenticatedAccount, subscriberId, clock);
return subscriptionManager.getSubscriptionInformation( subscriberCredentials)
@@ -674,7 +678,7 @@ public class SubscriptionController {
subscriptionInformation.active(),
subscriptionInformation.cancelAtPeriodEnd(),
subscriptionInformation.price().currency(),
subscriptionInformation.price().amount(),
BigDecimal.valueOf(subscriptionInformation.price().amount()),
subscriptionInformation.status().getApiValue(),
subscriptionInformation.paymentProvider(),
subscriptionInformation.paymentMethod(),
@@ -684,12 +688,12 @@ public class SubscriptionController {
.orElseGet(() -> new GetSubscriptionInformationResponse(null, null));
}
public record GetReceiptCredentialsRequest(
public record GetReceiptCredentialRequest(
@Schema(description = "A ReceiptCredentialRequest encoded in standard base64 with padding")
@NotEmpty byte[] receiptCredentialRequest) {
}
public record GetReceiptCredentialsResponse(
public record GetReceiptCredentialResponse(
@Schema(description = "A ReceiptCredentialResponse encoded in standard base64 with padding")
@NotEmpty byte[] receiptCredentialResponse) {
}
@@ -707,7 +711,7 @@ public class SubscriptionController {
invoice. Clients SHOULD retry requests at this endpoint with the same ReceiptCredentialRequest value until
receiving a response. After receiving a response, clients should then compute the ReceiptCredentialPresentation
and redeem it at the receipt redemption endpoint. Once the first attempt is made there, the same
ReceiptCredentialRequest MUST NOT be used again to request receipt credentials.
ReceiptCredentialRequest MUST NOT be used again to request a receipt credential.
Note that you may in fact redeem TWO or more invoices for the same ReceiptCredentialRequest while retrying this
operation if a later invoice gets paid while you are retrying. However, the returned receipt is always for the
@@ -735,7 +739,7 @@ public class SubscriptionController {
}
}
""",
implementation = SubscriptionExceptionMapper.ChargeFailureResponse.class)))
implementation = PurchaseExceptionMapper.ChargeFailureResponse.class)))
@ApiResponse(responseCode = "403", description = "subscriberId authentication failure OR account authentication is present")
@ApiResponse(responseCode = "404", description = "subscriberId is not found OR malformed OR no subscription setup on the subscriber id")
@ApiResponse(responseCode = "409", description = "latest paid receipt on subscription was already redeemed for a receipt credential but with a different receipt credential request")
@@ -743,16 +747,17 @@ public class SubscriptionController {
name = "Retry-After",
description = "If present, a positive integer indicating the number of seconds before a subsequent attempt could succeed"))
@ManagedAsync
public Response createSubscriptionReceiptCredentials(
public Response createSubscriptionReceiptCredential(
@Auth Optional<AuthenticatedDevice> authenticatedAccount,
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
@PathParam("subscriberId") String subscriberId,
@NotNull @Valid GetReceiptCredentialsRequest request) throws SubscriptionException, RateLimitExceededException {
@NotNull @Valid GetReceiptCredentialRequest request) throws PurchaseException, RateLimitExceededException {
SubscriberCredentials subscriberCredentials = SubscriberCredentials.process(authenticatedAccount, subscriberId, clock);
try {
final SubscriptionManager.ReceiptResult receiptCredential = subscriptionManager.createReceiptCredentials(
final SubscriptionManager.ReceiptResult receiptCredential = subscriptionManager.createReceiptCredential(
subscriberCredentials, request.receiptCredentialRequest(),
r -> SubscriptionsUtil.receiptExpirationWithGracePeriod(subscriptionConfiguration, r));
r -> SubscriptionsUtil.receiptExpirationWithGracePeriod(subscriptionConfiguration, r),
userAgent);
final ReceiptCredentialResponse receiptCredentialResponse = receiptCredential.receiptCredentialResponse();
final CustomerAwareSubscriptionPaymentProcessor.ReceiptItem receipt = receiptCredential.receiptItem();
@@ -765,8 +770,8 @@ public class SubscriptionController {
.toLowerCase(Locale.ROOT)),
UserAgentTagUtil.getPlatformTag(userAgent)))
.increment();
return Response.ok(new GetReceiptCredentialsResponse(receiptCredentialResponse.serialize())).build();
} catch (SubscriptionReceiptRequestedForOpenPaymentException e) {
return Response.ok(new GetReceiptCredentialResponse(receiptCredentialResponse.serialize())).build();
} catch (PurchaseReceiptRequestedForOpenPaymentException e) {
return Response.noContent().build();
}
}
@@ -778,7 +783,7 @@ public class SubscriptionController {
public Response setDefaultPaymentMethodForIdeal(
@Auth Optional<AuthenticatedDevice> authenticatedAccount,
@PathParam("subscriberId") String subscriberId,
@PathParam("setupIntentId") @NotEmpty String setupIntentId) throws SubscriptionException, IOException {
@PathParam("setupIntentId") @NotEmpty String setupIntentId) throws PurchaseException, IOException {
SubscriberCredentials subscriberCredentials =
SubscriberCredentials.process(authenticatedAccount, subscriberId, clock);
@@ -789,7 +794,7 @@ public class SubscriptionController {
private void setDefaultPaymentMethod(final CustomerAwareSubscriptionPaymentProcessor manager,
final String paymentMethodId,
final SubscriberCredentials requestData) throws SubscriptionException, IOException {
final SubscriberCredentials requestData) throws PurchaseException, IOException {
try {
final Subscriptions.Record record = subscriptionManager.getSubscriber(requestData);
@@ -800,7 +805,7 @@ public class SubscriptionController {
manager
.setDefaultPaymentMethodForCustomer(processorCustomer.customerId(), paymentMethodId, record.subscriptionId);
} catch (final SubscriptionInvalidArgumentsException e) {
} catch (final PurchaseInvalidArgumentsException e) {
// Here, invalid arguments must mean that the client has made requests out of order, and needs to finish
// setting up the paymentMethod first
throw new ClientErrorException(Status.CONFLICT);
@@ -7,7 +7,6 @@ package org.whispersystems.textsecuregcm.controllers;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import com.google.common.annotations.VisibleForTesting;
import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber;
@@ -73,9 +72,7 @@ import org.whispersystems.textsecuregcm.entities.SubmitVerificationCodeRequest;
import org.whispersystems.textsecuregcm.entities.UpdateVerificationSessionRequest;
import org.whispersystems.textsecuregcm.entities.VerificationCodeRequest;
import org.whispersystems.textsecuregcm.entities.VerificationSessionResponse;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.filters.RemoteAddressFilter;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.mappers.RegistrationServiceSenderExceptionMapper;
import org.whispersystems.textsecuregcm.metrics.CaptchaMetrics;
@@ -132,9 +129,6 @@ public class VerificationController {
private static final String EXISTING_ACCOUNT_PLATFORM = "existingAccountPlatform";
private static final String EXISTING_ACCOUNT_RECENTLY_SEEN_TAG_NAME = "existingAccountRecentlySeen";
@VisibleForTesting
static final String VERIFICATION_CODE_PUSH_NOTIFICATION_EXPERIMENT_NAME = "verificationCodePushNotification";
private final RegistrationServiceClient registrationServiceClient;
private final VerificationSessionManager verificationSessionManager;
private final PushNotificationManager pushNotificationManager;
@@ -146,7 +140,6 @@ public class VerificationController {
private final CarrierDataProvider carrierDataProvider;
private final RegistrationFraudChecker registrationFraudChecker;
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
private final ExperimentEnrollmentManager experimentEnrollmentManager;
private final Clock clock;
public VerificationController(final RegistrationServiceClient registrationServiceClient,
@@ -160,7 +153,6 @@ public class VerificationController {
final CarrierDataProvider carrierDataProvider,
final RegistrationFraudChecker registrationFraudChecker,
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
final ExperimentEnrollmentManager experimentEnrollmentManager,
final Clock clock) {
this.registrationServiceClient = registrationServiceClient;
this.verificationSessionManager = verificationSessionManager;
@@ -173,7 +165,6 @@ public class VerificationController {
this.carrierDataProvider = carrierDataProvider;
this.registrationFraudChecker = registrationFraudChecker;
this.dynamicConfigurationManager = dynamicConfigurationManager;
this.experimentEnrollmentManager = experimentEnrollmentManager;
this.clock = clock;
}
@@ -665,8 +656,6 @@ public class VerificationController {
}
accountsManager.getByE164(registrationServiceSession.number())
.filter(existingAccount ->
experimentEnrollmentManager.isEnrolled(existingAccount.getAccountIdentifier(), VERIFICATION_CODE_PUSH_NOTIFICATION_EXPERIMENT_NAME))
.ifPresent(existingAccount -> {
try {
pushNotificationManager.sendVerificationCodeRequestedNotifications(existingAccount, clock.instant());
@@ -4,7 +4,8 @@
*/
package org.whispersystems.textsecuregcm.entities;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
public record ApnRegistrationId(@NotEmpty String apnRegistrationId) {
public record ApnRegistrationId(@NotBlank @Size(max = 1024) String apnRegistrationId) {
}
@@ -4,7 +4,8 @@
*/
package org.whispersystems.textsecuregcm.entities;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
public record GcmRegistrationId(@NotEmpty String gcmRegistrationId) {
public record GcmRegistrationId(@NotBlank @Size(max = 1024) String gcmRegistrationId) {
}
@@ -14,10 +14,12 @@ import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.Valid;
import jakarta.validation.constraints.AssertTrue;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.PositiveOrZero;
import java.util.List;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import jakarta.validation.constraints.PositiveOrZero;
import jakarta.validation.constraints.Size;
import org.apache.commons.lang3.ArrayUtils;
import org.signal.libsignal.protocol.IdentityKey;
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
import org.whispersystems.textsecuregcm.util.IdentityKeyAdapter;
@@ -45,18 +47,29 @@ public record RegistrationRequest(@Schema(requiredMode = Schema.RequiredMode.NOT
@Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED, description = """
A base64-encoded receipt credential presentation that allows for redeeming a Signal Login.
Must be provided if `sessionId` and `recoveryPassword` are not provided;
must not be provided if `sessionId` or `recoveryPassword` is provided.
must not be provided if `sessionId` or `recoveryPassword` is provided. Must not be
provided if recovering a previously used account.
""")
@Nullable
byte[] receiptCredentialPresentation,
@Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED, description = """
A TOTP one-time password; required if recovering an account that has TOTP keys.
A TOTP one-time password; required if recovering an account that has TOTP keys. Must
not be provided if `receiptCredentialPresentation` is provided.
""")
@PositiveOrZero
@Nullable
Integer totp,
@Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED, description = """
A JSON-serialized assertion response from a completed authentication ceremony.
See https://www.w3.org/TR/webauthn/#authenticatorassertionresponse.
""")
@Nullable
// There is no documented max size, but 8kiB should be enough
@Size(min = 1, max = 8192)
String webAuthnResponse,
@NotNull
@Valid
@Schema(requiredMode = Schema.RequiredMode.REQUIRED)
@@ -142,4 +155,18 @@ public record RegistrationRequest(@Schema(requiredMode = Schema.RequiredMode.NOT
deviceActivationRequest().pniPqLastResortPreKey().isPresent())
.allMatch(present -> present == expectPresence);
}
@VisibleForTesting
@AssertTrue
@Schema(hidden = true)
boolean isMfaAbsentWhenUsingReceipt() {
return ArrayUtils.isEmpty(receiptCredentialPresentation) || (totp == null && webAuthnResponse == null);
}
@VisibleForTesting
@AssertTrue
@Schema(hidden = true)
boolean isAtMostOneMfaPresent() {
return totp == null || webAuthnResponse == null;
}
}
@@ -23,6 +23,7 @@ import java.util.Optional;
import java.util.UUID;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.signal.chat.account.Capabilities;
import org.signal.chat.account.ChangeNumberRequest;
import org.signal.chat.account.ChangeNumberResponse;
@@ -41,6 +42,10 @@ import org.signal.chat.account.DeleteUsernameHashResponse;
import org.signal.chat.account.DeleteUsernameLinkRequest;
import org.signal.chat.account.DeleteUsernameLinkResponse;
import org.signal.chat.account.ExternalServiceCredentials;
import org.signal.chat.account.FinishMfaVerificationRequest;
import org.signal.chat.account.FinishMfaVerificationResponse;
import org.signal.chat.account.FinishWebAuthnRegistrationRequest;
import org.signal.chat.account.FinishWebAuthnRegistrationResponse;
import org.signal.chat.account.GenerateTotpKeyRequest;
import org.signal.chat.account.GenerateTotpKeyResponse;
import org.signal.chat.account.GetAccountDataReportRequest;
@@ -51,27 +56,34 @@ import org.signal.chat.account.GetCapabilitiesRequest;
import org.signal.chat.account.GetCapabilitiesResponse;
import org.signal.chat.account.GetEntitlementsRequest;
import org.signal.chat.account.GetEntitlementsResponse;
import org.signal.chat.account.ListTotpKeysRequest;
import org.signal.chat.account.ListTotpKeysResponse;
import org.signal.chat.account.ListMfaKeysRequest;
import org.signal.chat.account.ListMfaKeysResponse;
import org.signal.chat.account.ListMfaKeysResponse.MfaKeyMetadata.MfaKeyType;
import org.signal.chat.account.StartMfaVerificationResponse.WebAuthnAuthenticationParameters;
import org.signal.chat.account.RegistrationLockFailure;
import org.signal.chat.account.RemoveTotpKeyRequest;
import org.signal.chat.account.RemoveTotpKeyResponse;
import org.signal.chat.account.RemoveMfaKeyRequest;
import org.signal.chat.account.RemoveMfaKeyResponse;
import org.signal.chat.account.ReserveUsernameHashRequest;
import org.signal.chat.account.ReserveUsernameHashResponse;
import org.signal.chat.account.SetDiscoverableByPhoneNumberRequest;
import org.signal.chat.account.SetDiscoverableByPhoneNumberResponse;
import org.signal.chat.account.SetMfaKeyMetadataRequest;
import org.signal.chat.account.SetMfaKeyMetadataResponse;
import org.signal.chat.account.SetRegistrationLockRequest;
import org.signal.chat.account.SetRegistrationLockResponse;
import org.signal.chat.account.SetRegistrationRecoveryPasswordRequest;
import org.signal.chat.account.SetRegistrationRecoveryPasswordResponse;
import org.signal.chat.account.SetTotpKeyMetadataRequest;
import org.signal.chat.account.SetTotpKeyMetadataResponse;
import org.signal.chat.account.SetUsernameLinkRequest;
import org.signal.chat.account.SetUsernameLinkResponse;
import org.signal.chat.account.SetZkCredentialKeyRequest;
import org.signal.chat.account.SetZkCredentialKeyResponse;
import org.signal.chat.account.SimpleAccountsGrpc;
import org.signal.chat.account.StaleDevices;
import org.signal.chat.account.StartMfaVerificationRequest;
import org.signal.chat.account.StartMfaVerificationResponse;
import org.signal.chat.account.StartWebAuthnRegistrationRequest;
import org.signal.chat.account.StartWebAuthnRegistrationResponse;
import org.signal.chat.account.StartWebAuthnRegistrationResponse.WebAuthnCreateParameters;
import org.signal.chat.account.TotpParameters;
import org.signal.chat.account.UsernameNotAvailable;
import org.signal.chat.common.AccountIdentifiers;
@@ -90,6 +102,8 @@ import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
import org.whispersystems.textsecuregcm.auth.UnverifiedRegistrationSessionException;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
import org.whispersystems.textsecuregcm.auth.webauthn.AuthenticationCeremonyParameters;
import org.whispersystems.textsecuregcm.auth.webauthn.RegistrationCeremonyParameters;
import org.whispersystems.textsecuregcm.controllers.MessageDeliveryNotAllowedException;
import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
@@ -104,10 +118,13 @@ import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.push.MessageTooLargeException;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.AnnotatedMfaKey;
import org.whispersystems.textsecuregcm.storage.AnnotatedTotpKey;
import org.whispersystems.textsecuregcm.storage.AnnotatedWebAuthnCredential;
import org.whispersystems.textsecuregcm.storage.ChangeNumberManager;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import org.whispersystems.textsecuregcm.storage.PhoneNumberRecoveryPasswordsManager;
import org.whispersystems.textsecuregcm.storage.TooManyMfaKeysException;
import org.whispersystems.textsecuregcm.storage.TooManyTotpKeysException;
import org.whispersystems.textsecuregcm.storage.TotpKey;
import org.whispersystems.textsecuregcm.storage.UsernameHashNotAvailableException;
@@ -118,7 +135,6 @@ import org.whispersystems.textsecuregcm.util.SystemMapper;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
import org.whispersystems.textsecuregcm.util.UsernameHashZkProofVerifier;
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem;
import javax.annotation.Nullable;
public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
@@ -131,7 +147,7 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
private final Clock clock;
private final ChangeNumberManager changeNumberManager;
private static class TotpKeyNotFoundException extends NoStackTraceRuntimeException {
private static class MfaKeyNotFoundException extends NoStackTraceRuntimeException {
}
public AccountsGrpcService(final AccountsManager accountsManager,
@@ -559,6 +575,11 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
@Override
public GenerateTotpKeyResponse generateTotpKey(final GenerateTotpKeyRequest request) {
try {
final Account account = getAuthenticatedAccount();
if (account.getNumber().isPresent()) {
throw GrpcExceptions.invalidArguments("TOTP keys may not be generated for an account with a number");
}
final TotpKey pendingTotpKey =
accountsManager.generatePendingTotpKey(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier());
@@ -568,91 +589,193 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
.setTotpParameters(toGrpcTotpParameters(pendingTotpKey.totpParameters()))
.build())
.build();
} catch (final TooManyTotpKeysException e) {
} catch (final TooManyTotpKeysException _) {
return GenerateTotpKeyResponse.newBuilder()
.setTooManyTotpKeys(FailedPrecondition.getDefaultInstance())
.build();
} catch (final TooManyMfaKeysException _) {
return GenerateTotpKeyResponse.newBuilder()
.setTooManyMfaKeys(FailedPrecondition.getDefaultInstance())
.build();
}
}
@Override
public ConfirmTotpKeyResponse confirmTotpKey(final ConfirmTotpKeyRequest request) {
final Optional<Byte> maybeConfirmedTotpKeyId =
accountsManager.confirmPendingTotpKey(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier(),
request.getOneTimePassword(),
clock.instant(),
request.getMetadataCiphertext().toByteArray());
try {
final Account account = getAuthenticatedAccount();
if (account.getNumber().isPresent()) {
throw GrpcExceptions.invalidArguments("TOTP keys may not be added to an account with a number");
}
return maybeConfirmedTotpKeyId.map(keyId -> ConfirmTotpKeyResponse.newBuilder()
.setKeyConfirmed(ConfirmTotpKeyResponse.KeyConfirmed.newBuilder()
.setKeyId(keyId)
.build())
.build()).orElseGet(() -> ConfirmTotpKeyResponse.newBuilder()
.setOneTimePasswordNotVerified(FailedPrecondition.getDefaultInstance())
.build());
final Optional<Byte> maybeConfirmedTotpKeyId =
accountsManager.confirmPendingTotpKey(
AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier(),
request.getOneTimePassword(),
clock.instant(),
request.getMetadataCiphertext().toByteArray());
return maybeConfirmedTotpKeyId.map(keyId -> ConfirmTotpKeyResponse.newBuilder()
.setKeyConfirmed(ConfirmTotpKeyResponse.KeyConfirmed.newBuilder()
.setKeyId(keyId)
.build())
.build()).orElseGet(() -> ConfirmTotpKeyResponse.newBuilder()
.setOneTimePasswordNotVerified(FailedPrecondition.getDefaultInstance())
.build());
} catch (TooManyMfaKeysException _) {
return ConfirmTotpKeyResponse.newBuilder()
.setTooManyMfaKeys(FailedPrecondition.getDefaultInstance())
.build();
}
}
@Override
public ListTotpKeysResponse listTotpKeys(final ListTotpKeysRequest request) {
final ListTotpKeysResponse.Builder responseBuilder = ListTotpKeysResponse.newBuilder();
public StartWebAuthnRegistrationResponse startWebAuthnRegistration(final StartWebAuthnRegistrationRequest request) {
getAuthenticatedAccount().getTotpKeys().forEach((keyId, totpKey) -> {
assert totpKey.metadataCiphertext() != null;
final Account account = getAuthenticatedAccount();
if (account.getNumber().isPresent()) {
throw GrpcExceptions.invalidArguments("WebAuthn keys may not be set for an account with a number");
}
responseBuilder.putKeys(keyId, ListTotpKeysResponse.TotpKeyMetadata.newBuilder()
.setMetadataCiphertext(ByteString.copyFrom(totpKey.metadataCiphertext()))
.setTotpParameters(toGrpcTotpParameters(totpKey.totpKey().totpParameters()))
.build());
try {
final RegistrationCeremonyParameters registrationParameters =
accountsManager.startWebAuthnRegistration(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier());
return StartWebAuthnRegistrationResponse.newBuilder()
.setParams(WebAuthnCreateParameters.newBuilder()
.setUserHandle(ByteString.copyFrom(registrationParameters.userHandle()))
.addAllAllowedAlgorithms(registrationParameters.allowedAlgorithms())
.addAllExcludeCredentialIds(
registrationParameters.excludedCredentialIds().stream().map(ByteString::copyFrom).toList()))
.build();
} catch (TooManyMfaKeysException _) {
return StartWebAuthnRegistrationResponse.newBuilder()
.setTooManyMfaKeys(FailedPrecondition.getDefaultInstance())
.build();
}
}
@Override
public FinishWebAuthnRegistrationResponse finishWebAuthnRegistration(final FinishWebAuthnRegistrationRequest request) {
final Account account = getAuthenticatedAccount();
if (account.getNumber().isPresent()) {
throw GrpcExceptions.invalidArguments("WebAuthn keys may not be set for an account with a number");
}
try {
final Optional<Byte> maybeKeyId = accountsManager.finishWebAuthnRegistration(
AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier(),
request.getAttestationObject().toByteArray(),
request.getCollectedClientDataJson(),
request.getMetadataCiphertext().toByteArray());
return maybeKeyId.map(
keyId -> FinishWebAuthnRegistrationResponse.newBuilder()
.setKeyConfirmed(FinishWebAuthnRegistrationResponse.KeyConfirmed.newBuilder().setKeyId(keyId)))
.orElseGet(() -> FinishWebAuthnRegistrationResponse.newBuilder().setKeyNotConfirmed(FailedPrecondition.getDefaultInstance()))
.build();
} catch (TooManyMfaKeysException _) {
return FinishWebAuthnRegistrationResponse.newBuilder()
.setTooManyMfaKeys(FailedPrecondition.getDefaultInstance())
.build();
}
}
@Override
public ListMfaKeysResponse listMfaKeys(final ListMfaKeysRequest request) {
final ListMfaKeysResponse.Builder responseBuilder = ListMfaKeysResponse.newBuilder();
getAuthenticatedAccount().getMfaKeys().forEach((keyId, mfaKey) -> {
assert mfaKey.metadataCiphertext() != null;
responseBuilder.putKeys(
keyId,
ListMfaKeysResponse.MfaKeyMetadata.newBuilder()
.setMetadataCiphertext(ByteString.copyFrom(mfaKey.metadataCiphertext()))
.setType(switch (mfaKey) {
case AnnotatedTotpKey _ -> MfaKeyType.MFA_KEY_TYPE_TOTP;
case AnnotatedWebAuthnCredential _ -> MfaKeyType.MFA_KEY_TYPE_WEBAUTHN;
}).build());
});
return responseBuilder.build();
}
@Override
public SetTotpKeyMetadataResponse setTotpKeyMetadata(final SetTotpKeyMetadataRequest request) {
final byte keyId = validateTotpKeyId(request.getKeyId());
public SetMfaKeyMetadataResponse setMfaKeyMetadata(final SetMfaKeyMetadataRequest request) {
final byte keyId = validateMfaKeyId(request.getKeyId());
try {
accountsManager.update(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier(), account -> {
final Map<Byte, AnnotatedTotpKey> totpKeys = new HashMap<>(account.getTotpKeys());
@Nullable final AnnotatedTotpKey existingKey = totpKeys.get(keyId);
final Map<Byte, AnnotatedMfaKey> mfaKeys = new HashMap<>(account.getMfaKeys());
@Nullable final AnnotatedMfaKey existingKey = mfaKeys.get(keyId);
if (existingKey == null) {
throw new TotpKeyNotFoundException();
throw new MfaKeyNotFoundException();
}
totpKeys.put(keyId, new AnnotatedTotpKey(existingKey.totpKey(), request.getMetadataCiphertext().toByteArray()));
mfaKeys.put(keyId, existingKey.withMetadataCiphertext(request.getMetadataCiphertext().toByteArray()));
account.setTotpKeys(totpKeys);
account.setMfaKeys(mfaKeys);
});
return SetTotpKeyMetadataResponse.newBuilder()
.setMetadataUpdated(SetTotpKeyMetadataResponse.MetadataUpdated.getDefaultInstance())
return SetMfaKeyMetadataResponse.newBuilder()
.setSuccess(SetMfaKeyMetadataResponse.MetadataUpdated.getDefaultInstance())
.build();
} catch (final TotpKeyNotFoundException _) {
return SetTotpKeyMetadataResponse.newBuilder()
} catch (final MfaKeyNotFoundException _) {
return SetMfaKeyMetadataResponse.newBuilder()
.setKeyNotFound(NotFound.getDefaultInstance())
.build();
}
}
@Override
public RemoveTotpKeyResponse removeTotpKey(final RemoveTotpKeyRequest request) {
final byte keyId = validateTotpKeyId(request.getKeyId());
public RemoveMfaKeyResponse removeMfaKey(final RemoveMfaKeyRequest request) {
final byte keyId = validateMfaKeyId(request.getKeyId());
accountsManager.update(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier(), account -> {
final Map<Byte, AnnotatedTotpKey> totpKeys = new HashMap<>(account.getTotpKeys());
totpKeys.remove(keyId);
final Map<Byte, AnnotatedMfaKey> mfaKeys = new HashMap<>(account.getMfaKeys());
mfaKeys.remove(keyId);
account.setTotpKeys(totpKeys);
account.setMfaKeys(mfaKeys);
});
return RemoveTotpKeyResponse.getDefaultInstance();
return RemoveMfaKeyResponse.getDefaultInstance();
}
private byte validateTotpKeyId(final int keyId) {
if (keyId < 0 || keyId > Account.MAX_TOTP_KEY_ID) {
throw GrpcExceptions.invalidArguments("TOTP key ID out of range");
@Override
public StartMfaVerificationResponse startMfaVerification(final StartMfaVerificationRequest request) {
final Account account = getAuthenticatedAccount();
final StartMfaVerificationResponse.Builder builder = StartMfaVerificationResponse.newBuilder()
.setHasTotp(account.getMfaKeys().values().stream().anyMatch(AnnotatedTotpKey.class::isInstance));
accountsManager.startWebAuthnAuthentication(account)
.map(AccountsGrpcService::toGrpcWebAuthnAuthenticationParameters)
.ifPresent(builder::setWebauthnAuthenticationParameters);
return builder.build();
}
@Override
public FinishMfaVerificationResponse finishMfaVerification(final FinishMfaVerificationRequest request) throws RateLimitExceededException {
rateLimiters.getCheckMfaLimiter().validate(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier());
final Account account = getAuthenticatedAccount();
final boolean success = switch (request.getCredentialCase()) {
case TOTP_PASSWORD -> accountsManager.verifyTotp(account, clock.instant(), request.getTotpPassword());
case WEBAUTHN_AUTHENTICATION_RESPONSE_JSON ->
accountsManager.verifyWebAuthnAuthentication(account, request.getWebauthnAuthenticationResponseJson()).isPresent();
case CREDENTIAL_NOT_SET -> false;
};
return FinishMfaVerificationResponse.newBuilder().setSuccess(success).build();
}
private byte validateMfaKeyId(final int keyId) {
if (keyId < 0 || keyId > Account.MAX_MFA_KEY_ID) {
throw GrpcExceptions.invalidArguments("MFA key ID out of range");
}
return (byte) keyId;
@@ -666,6 +789,14 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
.build();
}
private static WebAuthnAuthenticationParameters toGrpcWebAuthnAuthenticationParameters(final AuthenticationCeremonyParameters parameters) {
return WebAuthnAuthenticationParameters.newBuilder()
.setChallenge(ByteString.copyFrom(parameters.challenge()))
.setTimeoutSeconds((int) parameters.timeout().toSeconds())
.addAllAllowedCredentialIds(parameters.allowedCredentialIds().stream().map(ByteString::copyFrom).toList())
.build();
}
private static AccountIdentifiers buildAccountIdentifiers(final Account account) {
final AccountIdentifiers.Builder accountIdentifiersBuilder = AccountIdentifiers.newBuilder()
.addServiceIdentifiers(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(new AciServiceIdentifier(account.getAccountIdentifier())));
@@ -16,6 +16,7 @@ import java.util.Optional;
import java.util.stream.Collectors;
import org.signal.chat.backup.GetBackupAuthCredentialsRequest;
import org.signal.chat.backup.GetBackupAuthCredentialsResponse;
import org.signal.chat.backup.GetBackupIdLimitsResponse;
import org.signal.chat.backup.RedeemReceiptRequest;
import org.signal.chat.backup.RedeemReceiptResponse;
import org.signal.chat.backup.SetBackupIdRequest;
@@ -138,6 +139,16 @@ public class BackupsGrpcService extends SimpleBackupsGrpc.BackupsImplBase {
}
}
@Override
public GetBackupIdLimitsResponse getBackupIdLimits(final Empty request) {
final Account account = authenticatedAccount();
final BackupAuthManager.BackupIdRotationLimit limit = backupAuthManager.checkBackupIdRotationLimit(account);
return GetBackupIdLimitsResponse.newBuilder()
.setHasPermitsRemaining(limit.hasPermitsRemaining())
.setRetryAfterSeconds(limit.nextPermitAvailable().getSeconds())
.build();
}
@Override
public Throwable mapException(final Throwable throwable) {
return switch (throwable) {
@@ -1,14 +1,18 @@
package org.whispersystems.textsecuregcm.grpc;
import java.io.IOException;
import com.google.protobuf.Empty;
import org.signal.chat.challenge.AnswerChallengeRequest;
import org.signal.chat.challenge.AnswerChallengeResponse;
import org.signal.chat.challenge.RequestPushChallengeRequest;
import org.signal.chat.challenge.RequestPushChallengeResponse;
import org.signal.chat.challenge.SimpleChallengeGrpc;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
import org.signal.chat.errors.FailedPrecondition;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
import org.whispersystems.textsecuregcm.captcha.InvalidCaptchaArgumentException;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.limits.RateLimitChallengeManager;
import org.whispersystems.textsecuregcm.push.NotPushRegisteredException;
import org.whispersystems.textsecuregcm.spam.ChallengeConstraintChecker;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
@@ -28,19 +32,21 @@ public class ChallengeGrpcService extends SimpleChallengeGrpc.ChallengeImplBase
}
@Override
public AnswerChallengeResponse handleChallengeResponse(final AnswerChallengeRequest request)
public AnswerChallengeResponse answerChallenge(final AnswerChallengeRequest request)
throws RateLimitExceededException, IOException {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
final Account account = accountsManager.getByAccountIdentifier(authenticatedDevice.accountIdentifier())
.orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials"));
final ChallengeConstraintChecker.ChallengeConstraints constraints = challengeConstraintChecker.challengeConstraintsGrpc(
account);
final Account account = requireAuthenticatedAccount();
final ChallengeConstraintChecker.ChallengeConstraints constraints =
challengeConstraintChecker.challengeConstraintsGrpc(account);
final boolean success = switch (request.getRequestCase()) {
case PUSH -> constraints.pushPermitted() && rateLimitChallengeManager.answerPushChallenge(account,
request.getPush().getChallenge());
case PUSH -> {
if (!constraints.pushPermitted()) {
throw GrpcExceptions.rateLimitExceeded(null);
}
yield rateLimitChallengeManager.answerPushChallenge(account, request.getPush().getChallenge());
}
case CAPTCHA -> {
try {
yield rateLimitChallengeManager.answerCaptchaChallenge(
@@ -49,7 +55,7 @@ public class ChallengeGrpcService extends SimpleChallengeGrpc.ChallengeImplBase
RequestAttributesUtil.getRemoteAddress().getHostAddress(),
RequestAttributesUtil.getUserAgent().orElse(null),
constraints.captchaScoreThreshold());
} catch (InvalidCaptchaArgumentException e) {
} catch (final InvalidCaptchaArgumentException e) {
throw GrpcExceptions.invalidArguments(e.getMessage());
}
}
@@ -60,4 +66,32 @@ public class ChallengeGrpcService extends SimpleChallengeGrpc.ChallengeImplBase
.setSuccess(success)
.build();
}
@Override
public RequestPushChallengeResponse requestPushChallenge(final RequestPushChallengeRequest request) {
final Account account = requireAuthenticatedAccount();
final ChallengeConstraintChecker.ChallengeConstraints constraints =
challengeConstraintChecker.challengeConstraintsGrpc(account);
if (!constraints.pushPermitted()) {
throw GrpcExceptions.rateLimitExceeded(null);
}
try {
rateLimitChallengeManager.sendPushChallenge(account);
} catch (NotPushRegisteredException _) {
return RequestPushChallengeResponse.newBuilder()
.setNoPushToken(FailedPrecondition.getDefaultInstance())
.build();
}
return RequestPushChallengeResponse.newBuilder()
.setSentPushChallenge(Empty.getDefaultInstance())
.build();
}
private Account requireAuthenticatedAccount() {
return accountsManager.getByAccountIdentifier(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier())
.orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials"));
}
}
@@ -0,0 +1,73 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc;
import com.google.common.annotations.VisibleForTesting;
import io.grpc.ForwardingServerCallListener;
import io.grpc.Metadata;
import io.grpc.ServerCall;
import io.grpc.ServerCallHandler;
import io.grpc.ServerInterceptor;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Metrics;
import java.util.concurrent.atomic.AtomicInteger;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
/// Limits the number of concurrent gRPC calls. Returns `io.grpc.Status.UNAVAILABLE` if the limit is exceeded. This
/// interceptor is meant to be used alongside a virtual thread executor. Unfortunately, we can't re-use
/// [org.whispersystems.textsecuregcm.util.BoundedVirtualThreadFactory] directly because the gRPC stack does not
/// gracefully handle [java.util.concurrent.RejectedExecutionException]s (see
/// [issue](https://github.com/grpc/grpc-java/issues/636))
public class ConcurrentCallLimitingInterceptor implements ServerInterceptor {
private final int maxConcurrentCalls;
private final AtomicInteger concurrentCalls = new AtomicInteger(0);
private final Counter rejectedCallCounter;
public ConcurrentCallLimitingInterceptor(final int maxConcurrentCalls) {
this.maxConcurrentCalls = maxConcurrentCalls;
Metrics.gauge(MetricsUtil.name(ConcurrentCallLimitingInterceptor.class, "active"),
concurrentCalls, AtomicInteger::doubleValue);
this.rejectedCallCounter =
Metrics.counter(MetricsUtil.name(ConcurrentCallLimitingInterceptor.class, "rejected"));
}
@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(final ServerCall<ReqT, RespT> call,
final Metadata headers, final ServerCallHandler<ReqT, RespT> next) {
if (concurrentCalls.incrementAndGet() > maxConcurrentCalls) {
concurrentCalls.decrementAndGet();
rejectedCallCounter.increment();
return ServerInterceptorUtil.closeWithStatusException(call, GrpcExceptions.unavailable());
}
try {
return new ForwardingServerCallListener.SimpleForwardingServerCallListener<>(next.startCall(call, headers)) {
@Override
public void onComplete() {
concurrentCalls.decrementAndGet();
super.onComplete();
}
@Override
public void onCancel() {
concurrentCalls.decrementAndGet();
super.onCancel();
}
};
} catch (final Exception e) {
concurrentCalls.decrementAndGet();
throw e;
}
}
@VisibleForTesting
int getActiveCalls() {
return concurrentCalls.get();
}
}
@@ -12,9 +12,10 @@ import java.time.temporal.ChronoUnit;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import org.signal.chat.common.ZkCredential;
import org.signal.chat.credentials.ExternalServiceType;
import org.signal.chat.credentials.GetCreateCallLinkCredentialsRequest;
import org.signal.chat.credentials.GetCreateCallLinkCredentialsResponse;
import org.signal.chat.credentials.GetCreateCallLinkCredentialRequest;
import org.signal.chat.credentials.GetCreateCallLinkCredentialResponse;
import org.signal.chat.credentials.GetDeliveryCertificateRequest;
import org.signal.chat.credentials.GetDeliveryCertificateResponse;
import org.signal.chat.credentials.GetExternalServiceCredentialsRequest;
@@ -138,14 +139,14 @@ public class CredentialsGrpcService extends SimpleCredentialsGrpc.CredentialsImp
.orElseThrow(
() -> new IllegalStateException("account without PNI must have auth credential salt")),
redemption));
responseBuilder.addGroupCredentials(GetGroupCredentialsResponse.CredentialAndRedemptionTime.newBuilder()
.setRedemptionTimeSeconds(redemption.getEpochSecond())
responseBuilder.addGroupCredentials(ZkCredential.newBuilder()
.setRedemptionTime(redemption.getEpochSecond())
.setCredential(ByteString.copyFrom(
authCredentialWithPniResponse.serialize()))
.build());
responseBuilder.addCallLinkAuthCredentials(GetGroupCredentialsResponse.CredentialAndRedemptionTime.newBuilder()
.setRedemptionTimeSeconds(redemption.getEpochSecond())
responseBuilder.addCallLinkAuthCredentials(ZkCredential.newBuilder()
.setRedemptionTime(redemption.getEpochSecond())
.setCredential(ByteString.copyFrom(
CallLinkAuthCredentialResponse.issueCredential(aci, redemption, serverSecretParams).serialize()))
.build());
@@ -155,7 +156,7 @@ public class CredentialsGrpcService extends SimpleCredentialsGrpc.CredentialsImp
}
@Override
public GetCreateCallLinkCredentialsResponse getCreateCallLinkCredentials(final GetCreateCallLinkCredentialsRequest request)
public GetCreateCallLinkCredentialResponse getCreateCallLinkCredential(final GetCreateCallLinkCredentialRequest request)
throws RateLimitExceededException {
final UUID accountIdentifier = AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier();
@@ -167,8 +168,7 @@ public class CredentialsGrpcService extends SimpleCredentialsGrpc.CredentialsImp
final CreateCallLinkCredentialRequest createCallLinkCredentialRequest =
new CreateCallLinkCredentialRequest(request.getCredentialRequest().toByteArray());
return GetCreateCallLinkCredentialsResponse.newBuilder()
.setRedemptionTimeSeconds(truncatedDayTimestamp.getEpochSecond())
return GetCreateCallLinkCredentialResponse.newBuilder()
.setCredential(ByteString.copyFrom(createCallLinkCredentialRequest.issueCredential(
new ServiceId.Aci(accountIdentifier),
truncatedDayTimestamp,
@@ -28,8 +28,8 @@ import org.whispersystems.textsecuregcm.storage.AccountBadge;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.DonationPermitsManager;
import org.whispersystems.textsecuregcm.storage.RedeemedReceiptsManager;
import org.whispersystems.textsecuregcm.subscriptions.ReceiptCredentialPresentationFactory;
import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel;
import org.whispersystems.textsecuregcm.purchases.ReceiptCredentialPresentationFactory;
import org.whispersystems.textsecuregcm.purchases.ReceiptLevel;
public class DonationsGrpcService extends SimpleDonationsGrpc.DonationsImplBase {
@@ -12,12 +12,13 @@ import io.grpc.ServerCallHandler;
import io.grpc.ServerInterceptor;
import io.grpc.Status;
import io.grpc.StatusRuntimeException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import org.whispersystems.textsecuregcm.util.logging.ImpossibleEvents;
import java.io.IOException;
import java.io.UncheckedIOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.storage.AccountNotFoundException;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import org.whispersystems.textsecuregcm.util.logging.ImpossibleEvents;
/**
* This interceptor observes responses from the service and if the response status is {@link Status#UNKNOWN}
@@ -52,6 +53,7 @@ public class ErrorMappingInterceptor implements ServerInterceptor {
final StatusRuntimeException statusException = switch (cause) {
case ConvertibleToGrpcStatus e -> e.toStatusRuntimeException();
case AccountNotFoundException _ -> GrpcExceptions.invalidCredentials("invalid credentials");
case UncheckedIOException e -> {
log.warn("RPC {} encountered UncheckedIOException", call.getMethodDescriptor().getFullMethodName(), e.getCause());
yield GrpcExceptions.unavailable();
@@ -62,7 +64,7 @@ public class ErrorMappingInterceptor implements ServerInterceptor {
}
case IllegalStateException e -> {
ImpossibleEvents.logImpossible(log, e.getMessage(), e);
yield GrpcExceptions.unavailable(e.getMessage());
yield GrpcExceptions.unavailable();
}
case null -> {
log.error("RPC {} finished with status UNKNOWN: {}",
@@ -72,7 +74,7 @@ public class ErrorMappingInterceptor implements ServerInterceptor {
default -> {
log.error("RPC {} finished with status UNKNOWN",
call.getMethodDescriptor().getFullMethodName(), status.getCause());
yield GrpcExceptions.unavailable(status.getCause().getMessage());
yield GrpcExceptions.unavailable();
}
};
super.close(statusException.getStatus(), statusException.getTrailers());
@@ -0,0 +1,26 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.rpc.ErrorInfo;
import java.io.UncheckedIOException;
import java.util.Optional;
public class ErrorUtil {
public static Optional<ErrorInfo> errorInfo(final com.google.rpc.Status statusProto) {
return statusProto.getDetailsList().stream()
.filter(any -> any.is(ErrorInfo.class))
.map(errorInfo -> {
try {
return errorInfo.unpack(ErrorInfo.class);
} catch (final InvalidProtocolBufferException e) {
throw new UncheckedIOException(e);
}
})
.findFirst();
}
}
@@ -6,22 +6,19 @@
package org.whispersystems.textsecuregcm.grpc;
import com.google.common.annotations.VisibleForTesting;
import io.grpc.Status;
import org.signal.keytransparency.client.AciMonitorRequest;
import org.signal.keytransparency.client.ConsistencyParameters;
import com.google.protobuf.Any;
import com.google.rpc.ErrorInfo;
import com.google.rpc.Status;
import io.grpc.StatusRuntimeException;
import io.grpc.protobuf.StatusProto;
import org.signal.keytransparency.client.DistinguishedRequest;
import org.signal.keytransparency.client.DistinguishedResponse;
import org.signal.keytransparency.client.E164MonitorRequest;
import org.signal.keytransparency.client.E164SearchRequest;
import org.signal.keytransparency.client.MonitorRequest;
import org.signal.keytransparency.client.MonitorResponse;
import org.signal.keytransparency.client.MonitorResponseV2;
import org.signal.keytransparency.client.SearchRequest;
import org.signal.keytransparency.client.SearchResponse;
import org.signal.keytransparency.client.SearchResponseV2;
import org.signal.keytransparency.client.SimpleKeyTransparencyQueryServiceGrpc;
import org.signal.keytransparency.client.UsernameHashMonitorRequest;
import org.whispersystems.textsecuregcm.controllers.AccountController;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.keytransparency.KeyTransparencyServiceClient;
@@ -88,4 +85,28 @@ public class KeyTransparencyGrpcService extends
return request;
}
@Override
public Throwable mapException(final Throwable throwable) {
// Reconstruct the exception so that we can override the backing service domain with chat's own domain.
if (throwable instanceof StatusRuntimeException s) {
final ErrorInfo.Builder errInfoBuilder = ErrorInfo.newBuilder()
.setDomain(GrpcExceptions.DOMAIN);
final Status statusProto = StatusProto.fromStatusAndTrailers(s.getStatus(), s.getTrailers());
ErrorUtil.errorInfo(statusProto)
.map(ErrorInfo::getReason)
.ifPresent(errInfoBuilder::setReason);
return StatusProto.toStatusRuntimeException(Status.newBuilder()
// See https://github.com/signalapp/key-transparency-server/blob/30b7a2a40604fbe04545d47f26e4c5a35f5d3161/cmd/kt-server/errors.go#L32
// for a list of error codes that the key transparency service can generate.
.setCode(statusProto.getCode())
.setMessage(statusProto.getMessage())
.addDetails(Any.pack(errInfoBuilder.build()))
.build());
}
return throwable;
}
}
@@ -10,7 +10,6 @@ import org.signal.chat.errors.FailedPrecondition;
import org.signal.chat.errors.NotFound;
import org.signal.chat.purchase.CreateLoginReceiptCredentialRequest;
import org.signal.chat.purchase.CreateLoginReceiptCredentialResponse;
import org.signal.chat.purchase.PaymentRequired;
import org.signal.chat.purchase.SimpleLoginPurchaseGrpc;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.VerificationFailedException;
@@ -19,14 +18,13 @@ import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialResponse;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.subscriptions.LoginPurchaseManager;
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionChargeFailurePaymentRequiredException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidArgumentsException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionNotFoundException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentRequiredException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptAlreadyRedeemedException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptRequestedForOpenPaymentException;
import org.whispersystems.textsecuregcm.purchases.LoginPurchaseManager;
import org.whispersystems.textsecuregcm.purchases.PaymentProvider;
import org.whispersystems.textsecuregcm.purchases.PurchaseInvalidArgumentsException;
import org.whispersystems.textsecuregcm.purchases.PurchaseNotFoundException;
import org.whispersystems.textsecuregcm.purchases.PurchasePaymentRequiredException;
import org.whispersystems.textsecuregcm.purchases.PurchaseReceiptAlreadyRedeemedException;
import org.whispersystems.textsecuregcm.purchases.PurchaseReceiptRequestedForOpenPaymentException;
public class LoginPurchaseGrpcService extends SimpleLoginPurchaseGrpc.LoginPurchaseImplBase {
@@ -66,28 +64,23 @@ public class LoginPurchaseGrpcService extends SimpleLoginPurchaseGrpc.LoginPurch
.setResult(CreateLoginReceiptCredentialResponse.CreateLoginReceiptCredentialResult.newBuilder()
.setReceiptCredentialResponse(ByteString.copyFrom(receiptCredentialResponse.serialize())))
.build();
} catch (final SubscriptionReceiptRequestedForOpenPaymentException e) {
} catch (final PurchaseReceiptRequestedForOpenPaymentException e) {
return CreateLoginReceiptCredentialResponse.newBuilder()
.setPaymentStillProcessing(FailedPrecondition.getDefaultInstance())
.build();
} catch (final SubscriptionChargeFailurePaymentRequiredException e) {
} catch (final PurchasePaymentRequiredException e) {
return CreateLoginReceiptCredentialResponse.newBuilder()
.setPaymentRequired(PaymentRequired.newBuilder()
.setChargeFailure(SubscriptionsUtil.toChargeFailure(e.getProcessor(), e.getChargeFailure())))
.setPaymentRequired(SubscriptionsUtil.toPaymentRequired(e))
.build();
} catch (final SubscriptionPaymentRequiredException e) {
return CreateLoginReceiptCredentialResponse.newBuilder()
.setPaymentRequired(PaymentRequired.getDefaultInstance())
.build();
} catch (final SubscriptionNotFoundException e) {
} catch (final PurchaseNotFoundException e) {
return CreateLoginReceiptCredentialResponse.newBuilder()
.setPaymentNotFound(NotFound.getDefaultInstance())
.build();
} catch (final SubscriptionReceiptAlreadyRedeemedException e) {
} catch (final PurchaseReceiptAlreadyRedeemedException e) {
return CreateLoginReceiptCredentialResponse.newBuilder()
.setReceiptAlreadyIssued(FailedPrecondition.getDefaultInstance())
.build();
} catch (final SubscriptionInvalidArgumentsException e) {
} catch (final PurchaseInvalidArgumentsException e) {
throw GrpcExceptions.invalidArguments(e.errorDetail().orElse(""));
} catch (final VerificationFailedException e) {
throw GrpcExceptions.fieldViolation("receipt_credential_request",
@@ -19,7 +19,6 @@ import org.whispersystems.textsecuregcm.auth.DisconnectionRequestListener;
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestManager;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.limits.MessageDeliveryLoopMonitor;
import org.whispersystems.textsecuregcm.metrics.MessageMetrics;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
@@ -69,7 +68,6 @@ public class MessageDispatcher {
private final PushNotificationManager pushNotificationManager;
private final PushNotificationScheduler pushNotificationScheduler;
private final ClientReleaseManager clientReleaseManager;
private final MessageDeliveryLoopMonitor messageDeliveryLoopMonitor;
private final DisconnectionRequestManager disconnectionRequestManager;
public MessageDispatcher(final ReceiptSender receiptSender,
@@ -77,7 +75,6 @@ public class MessageDispatcher {
final MessageMetrics messageMetrics,
final PushNotificationManager pushNotificationManager,
final PushNotificationScheduler pushNotificationScheduler,
final MessageDeliveryLoopMonitor messageDeliveryLoopMonitor,
final DisconnectionRequestManager disconnectionRequestManager,
final ClientReleaseManager clientReleaseManager) {
this.receiptSender = receiptSender;
@@ -85,7 +82,6 @@ public class MessageDispatcher {
this.messageMetrics = messageMetrics;
this.pushNotificationManager = pushNotificationManager;
this.pushNotificationScheduler = pushNotificationScheduler;
this.messageDeliveryLoopMonitor = messageDeliveryLoopMonitor;
this.disconnectionRequestManager = disconnectionRequestManager;
this.clientReleaseManager = clientReleaseManager;
}
@@ -140,12 +136,6 @@ public class MessageDispatcher {
.name(SEND_MESSAGES_FLUX_NAME)
.tap(Micrometer.metrics(Metrics.globalRegistry))
.limitRate(MESSAGE_PUBLISHER_LIMIT_RATE)
// Check the first message we send for message-delivery loops
.switchOnFirst((firstEntry, flux) -> {
recordDeliveryAttempt(account, device, userAgentString, firstEntry);
return flux;
})
.flatMapSequential(entry -> switch (entry) {
case MessageStreamEntry.Envelope(final MessageProtos.Envelope envelope) -> {
final UUID serverGuid = UUIDUtil.fromByteString(envelope.getServerGuid());
@@ -237,17 +227,6 @@ public class MessageDispatcher {
});
}
private void recordDeliveryAttempt(final Account account, final Device device, final String userAgent,
final Signal<? extends MessageStreamEntry> firstEntry) {
if (firstEntry.get() instanceof MessageStreamEntry.Envelope(final MessageProtos.Envelope message)) {
messageDeliveryLoopMonitor.recordDeliveryAttempt(account.getAccountIdentifier(),
device.getId(),
UUIDUtil.fromByteString(message.getServerGuid()),
userAgent,
MessageMetrics.GRPC_CHANNEL);
}
}
private void maybeSendDeliveryReceipt(
final Device device,
final PendingAcknowledgementTracker.UnacknowledgedEnvelope unacknowledgedEnvelope) {
@@ -20,6 +20,8 @@ import org.signal.chat.errors.NotFound;
import org.signal.chat.messages.GetMessagesRequest;
import org.signal.chat.messages.GetMessagesResponse;
import org.signal.chat.messages.IndividualRecipientMessageBundle;
import org.signal.chat.messages.ReportMessageRequest;
import org.signal.chat.messages.ReportMessageResponse;
import org.signal.chat.messages.SendAuthenticatedSenderMessageRequest;
import org.signal.chat.messages.SendMessageAuthenticatedSenderResponse;
import org.signal.chat.messages.SendMessageType;
@@ -44,6 +46,9 @@ import org.whispersystems.textsecuregcm.spam.SpamChecker;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
import org.whispersystems.textsecuregcm.storage.ReportMessageHelper;
import org.whispersystems.textsecuregcm.storage.ReportMessageManager;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
import reactor.adapter.JdkFlowAdapter;
import reactor.core.publisher.Flux;
@@ -52,6 +57,8 @@ import javax.annotation.Nullable;
public class MessagesGrpcService extends SimpleMessagesGrpc.MessagesImplBase {
private final AccountsManager accountsManager;
private final ReportMessageManager reportMessageManager;
private final PhoneNumberIdentifiers phoneNumberIdentifiers;
private final RateLimiters rateLimiters;
private final MessageSender messageSender;
private final CardinalityEstimator messageByteLimitEstimator;
@@ -63,6 +70,8 @@ public class MessagesGrpcService extends SimpleMessagesGrpc.MessagesImplBase {
SendMessageAuthenticatedSenderResponse.newBuilder().setSuccess(Empty.getDefaultInstance()).build();
public MessagesGrpcService(final AccountsManager accountsManager,
final ReportMessageManager reportMessageManager,
final PhoneNumberIdentifiers phoneNumberIdentifiers,
final RateLimiters rateLimiters,
final MessageSender messageSender,
final CardinalityEstimator messageByteLimitEstimator,
@@ -71,6 +80,8 @@ public class MessagesGrpcService extends SimpleMessagesGrpc.MessagesImplBase {
final Clock clock) {
this.accountsManager = accountsManager;
this.reportMessageManager = reportMessageManager;
this.phoneNumberIdentifiers = phoneNumberIdentifiers;
this.rateLimiters = rateLimiters;
this.messageSender = messageSender;
this.messageByteLimitEstimator = messageByteLimitEstimator;
@@ -261,4 +272,22 @@ public class MessagesGrpcService extends SimpleMessagesGrpc.MessagesImplBase {
throw GrpcExceptions.invalidArguments("unrecognized envelope type");
};
}
@Override
public ReportMessageResponse reportMessage(final ReportMessageRequest request) {
final ServiceIdentifier sourceServiceIdentifier =
GrpcServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getSourceServiceIdentifier());
ReportMessageHelper.reportMessage(
sourceServiceIdentifier,
new AciServiceIdentifier(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier()),
UUIDUtil.fromByteString(request.getMessageGuid()),
request.getReportSpamToken().isEmpty() ? null : request.getReportSpamToken().toByteArray(),
RequestAttributesUtil.getUserAgent().orElse(null),
accountsManager,
phoneNumberIdentifiers,
reportMessageManager);
return ReportMessageResponse.getDefaultInstance();
}
}
@@ -127,7 +127,7 @@ public class MetricServerInterceptor implements ServerInterceptor {
@Override
public void close(final Status status, final Metadata responseHeaders) {
if (!status.isOk()) {
reason = errorInfo(StatusProto.fromStatusAndTrailers(status, responseHeaders))
reason = ErrorUtil.errorInfo(StatusProto.fromStatusAndTrailers(status, responseHeaders))
.map(ErrorInfo::getReason)
.orElse(DEFAULT_ERROR_REASON);
}
@@ -232,16 +232,4 @@ public class MetricServerInterceptor implements ServerInterceptor {
}
}
private static Optional<ErrorInfo> errorInfo(final com.google.rpc.Status statusProto) {
return statusProto.getDetailsList().stream()
.filter(any -> any.is(ErrorInfo.class))
.map(errorInfo -> {
try {
return errorInfo.unpack(ErrorInfo.class);
} catch (final InvalidProtocolBufferException e) {
throw new UncheckedIOException(e);
}
})
.findFirst();
}
}
@@ -7,16 +7,16 @@ import java.util.Locale;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration;
import org.whispersystems.textsecuregcm.subscriptions.CustomerAwareSubscriptionPaymentProcessor;
import org.whispersystems.textsecuregcm.subscriptions.PayPalDonationsTranslator;
import org.whispersystems.textsecuregcm.subscriptions.PaymentDetails;
import org.whispersystems.textsecuregcm.subscriptions.PaymentMethod;
import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionCurrencyUtil;
import org.whispersystems.textsecuregcm.purchases.CustomerAwareSubscriptionPaymentProcessor;
import org.whispersystems.textsecuregcm.purchases.PayPalDonationsTranslator;
import org.whispersystems.textsecuregcm.purchases.PaymentDetails;
import org.whispersystems.textsecuregcm.purchases.PaymentMethod;
import org.whispersystems.textsecuregcm.purchases.ReceiptLevel;
import org.whispersystems.textsecuregcm.purchases.SubscriptionCurrencyUtil;
public class OneTimeDonationUtil {
private static final String EURO_CURRENCY_CODE = "EUR";
public static final String EURO_CURRENCY_CODE = "EUR";
private static final Logger LOGGER = LoggerFactory.getLogger(OneTimeDonationUtil.class);
@@ -51,7 +51,7 @@ public class OneTimeDonationUtil {
public static OneTimeDonationRequestValidationResult validateOneTimeDonationRequest(
final String currency,
final BigDecimal amount,
final long amount,
final long level,
final PaymentMethod paymentMethod,
final OneTimeDonationConfiguration oneTimeDonationConfiguration,
@@ -69,21 +69,17 @@ public class OneTimeDonationUtil {
return new OneTimeDonationRequestValidationResult.UnsupportedCurrency();
}
final BigDecimal minCurrencyAmountMajorUnits = oneTimeDonationConfiguration.currencies()
.get(currency.toLowerCase(Locale.ROOT)).minimum();
final BigDecimal minCurrencyAmountMinorUnits = SubscriptionCurrencyUtil.convertConfiguredAmountToApiAmount(
currency,
minCurrencyAmountMajorUnits);
if (minCurrencyAmountMinorUnits.compareTo(amount) > 0) {
return new OneTimeDonationRequestValidationResult.AmountBelowMinimum(minCurrencyAmountMajorUnits);
final BigDecimal minCurrencyAmount =
oneTimeDonationConfiguration.currencies().get(currency.toLowerCase(Locale.ROOT)).minimum();
if (SubscriptionCurrencyUtil.convertPrimaryToMinorUnits(currency, minCurrencyAmount) > amount) {
return new OneTimeDonationRequestValidationResult.AmountBelowMinimum(minCurrencyAmount);
}
if (paymentMethod == PaymentMethod.SEPA_DEBIT &&
amount.compareTo(SubscriptionCurrencyUtil.convertConfiguredAmountToApiAmount(
EURO_CURRENCY_CODE,
oneTimeDonationConfiguration.sepaMaximumEuros())) > 0) {
return new OneTimeDonationRequestValidationResult.AmountAboveSepaLimit(
oneTimeDonationConfiguration.sepaMaximumEuros());
if (paymentMethod == PaymentMethod.SEPA_DEBIT) {
final BigDecimal sepaMaximumEuros = oneTimeDonationConfiguration.sepaMaximumEuros();
if (amount > SubscriptionCurrencyUtil.convertPrimaryToMinorUnits(EURO_CURRENCY_CODE, sepaMaximumEuros)) {
return new OneTimeDonationRequestValidationResult.AmountAboveSepaLimit(sepaMaximumEuros);
}
}
return new OneTimeDonationRequestValidationResult.Success();
}
@@ -96,7 +92,7 @@ public class OneTimeDonationUtil {
// independently.
final Locale locale = SubscriptionsUtil.getPayPalLocale(acceptableLocales);
final String localizedLineItemName = payPalDonationsTranslator.translate(acceptableLocales,
org.whispersystems.textsecuregcm.subscriptions.PayPalDonationsTranslator.ONE_TIME_DONATION_LINE_ITEM_KEY);
org.whispersystems.textsecuregcm.purchases.PayPalDonationsTranslator.ONE_TIME_DONATION_LINE_ITEM_KEY);
return new LocalizedPayPalDonationLineItem(locale, localizedLineItemName);
}
@@ -8,17 +8,15 @@ import static org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil.getClientP
import static org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil.toChargeFailure;
import com.google.protobuf.ByteString;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.Clock;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import org.signal.chat.errors.FailedPrecondition;
import org.signal.chat.errors.FailedZkAuthentication;
import org.signal.chat.errors.NotFound;
@@ -26,14 +24,13 @@ 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.CreateBoostReceiptCredentialRequest;
import org.signal.chat.purchase.CreateBoostReceiptCredentialResponse;
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;
@@ -44,18 +41,21 @@ import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfigurati
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.purchases.BraintreeManager;
import org.whispersystems.textsecuregcm.purchases.PayPalDonationsTranslator;
import org.whispersystems.textsecuregcm.purchases.PaymentDetails;
import org.whispersystems.textsecuregcm.purchases.PaymentProvider;
import org.whispersystems.textsecuregcm.purchases.PurchaseInvalidAmountException;
import org.whispersystems.textsecuregcm.purchases.PurchaseNotFoundException;
import org.whispersystems.textsecuregcm.purchases.PurchasePaymentRequiredException;
import org.whispersystems.textsecuregcm.purchases.PurchaseProcessorException;
import org.whispersystems.textsecuregcm.purchases.PurchaseReceiptRequestedForOpenPaymentException;
import org.whispersystems.textsecuregcm.purchases.StripeManager;
import org.whispersystems.textsecuregcm.purchases.SubscriptionCurrencyUtil;
import org.whispersystems.textsecuregcm.storage.DonationPermitsManager;
import org.whispersystems.textsecuregcm.storage.IssuedReceiptsManager;
import org.whispersystems.textsecuregcm.storage.OneTimeDonationsManager;
import org.whispersystems.textsecuregcm.storage.WriteConflictException;
import org.whispersystems.textsecuregcm.subscriptions.BraintreeManager;
import org.whispersystems.textsecuregcm.subscriptions.PayPalDonationsTranslator;
import org.whispersystems.textsecuregcm.subscriptions.PaymentDetails;
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
import org.whispersystems.textsecuregcm.subscriptions.PaymentStatus;
import org.whispersystems.textsecuregcm.subscriptions.StripeManager;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidAmountException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorException;
public class OneTimeDonationsGrpcService extends SimpleOneTimeDonationsGrpc.OneTimeDonationsImplBase {
@@ -115,18 +115,18 @@ public class OneTimeDonationsGrpcService extends SimpleOneTimeDonationsGrpc.OneT
.build();
}
final org.whispersystems.textsecuregcm.subscriptions.PaymentMethod paymentMethod =
final org.whispersystems.textsecuregcm.purchases.PaymentMethod paymentMethod =
switch (request.getPaymentMethod()) {
case PAYMENT_METHOD_CARD -> org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.CARD;
case PAYMENT_METHOD_SEPA_DEBIT -> org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.SEPA_DEBIT;
case PAYMENT_METHOD_IDEAL -> org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.IDEAL;
case PAYMENT_METHOD_CARD -> org.whispersystems.textsecuregcm.purchases.PaymentMethod.CARD;
case PAYMENT_METHOD_SEPA_DEBIT -> org.whispersystems.textsecuregcm.purchases.PaymentMethod.SEPA_DEBIT;
case PAYMENT_METHOD_IDEAL -> org.whispersystems.textsecuregcm.purchases.PaymentMethod.IDEAL;
default -> throw GrpcExceptions.fieldViolation("payment_method", "Unsupported payment method");
};
final OneTimeDonationUtil.OneTimeDonationRequestValidationResult validationResult =
OneTimeDonationUtil.validateOneTimeDonationRequest(
request.getCurrency(),
BigDecimal.valueOf(request.getAmount()),
request.getAmount(),
request.getLevel(),
paymentMethod,
oneTimeDonationConfiguration,
@@ -142,18 +142,22 @@ public class OneTimeDonationsGrpcService extends SimpleOneTimeDonationsGrpc.OneT
case final OneTimeDonationUtil.OneTimeDonationRequestValidationResult.AmountBelowMinimum r ->
CreateBoostResponse.newBuilder()
.setAmountBelowMinimum(AmountBelowMinimumError.newBuilder()
.setMinimum(r.minimum().toString()).build()).build();
.setMinimum(SubscriptionCurrencyUtil.convertPrimaryToMinorUnits(request.getCurrency(),
r.minimum()))
.build()).build();
case final OneTimeDonationUtil.OneTimeDonationRequestValidationResult.AmountAboveSepaLimit r ->
CreateBoostResponse.newBuilder()
.setAmountAboveSepaLimit(AmountAboveSepaLimitError.newBuilder()
.setMaximum(r.maximum().toString()).build()).build();
.setMaximum(SubscriptionCurrencyUtil.convertPrimaryToMinorUnits(
OneTimeDonationUtil.EURO_CURRENCY_CODE, r.maximum()))
.build()).build();
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.Success _ -> {
try {
final com.stripe.model.PaymentIntent paymentIntent = stripeManager.createPaymentIntent(
request.getCurrency(), request.getAmount(), request.getLevel(),
getClientPlatform(RequestAttributesUtil.getUserAgent().orElse(null)));
yield CreateBoostResponse.newBuilder().setClientSecret(paymentIntent.getClientSecret()).build();
} catch (final SubscriptionInvalidAmountException e) {
} catch (final PurchaseInvalidAmountException e) {
yield CreateBoostResponse.newBuilder()
.setInvalidAmount(FailedPrecondition.newBuilder()
.setDescription(e.getErrorCode()).build())
@@ -169,9 +173,9 @@ public class OneTimeDonationsGrpcService extends SimpleOneTimeDonationsGrpc.OneT
final OneTimeDonationUtil.OneTimeDonationRequestValidationResult validationResult =
OneTimeDonationUtil.validateOneTimeDonationRequest(
request.getCurrency(),
BigDecimal.valueOf(request.getAmount()),
request.getAmount(),
request.getLevel(),
org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.PAYPAL,
org.whispersystems.textsecuregcm.purchases.PaymentMethod.PAYPAL,
oneTimeDonationConfiguration,
braintreeManager);
@@ -185,7 +189,9 @@ public class OneTimeDonationsGrpcService extends SimpleOneTimeDonationsGrpc.OneT
case final OneTimeDonationUtil.OneTimeDonationRequestValidationResult.AmountBelowMinimum r ->
CreatePayPalBoostResponse.newBuilder()
.setAmountBelowMinimum(AmountBelowMinimumError.newBuilder()
.setMinimum(r.minimum().toString()).build()).build();
.setMinimum(SubscriptionCurrencyUtil.convertPrimaryToMinorUnits(request.getCurrency(),
r.minimum()))
.build()).build();
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.AmountAboveSepaLimit _ ->
throw new IllegalStateException("SEPA limit should not trigger for PayPal");
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.Success _ -> {
@@ -213,9 +219,9 @@ public class OneTimeDonationsGrpcService extends SimpleOneTimeDonationsGrpc.OneT
final OneTimeDonationUtil.OneTimeDonationRequestValidationResult validationResult =
OneTimeDonationUtil.validateOneTimeDonationRequest(
request.getCurrency(),
BigDecimal.valueOf(request.getAmount()),
request.getAmount(),
request.getLevel(),
org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.PAYPAL,
org.whispersystems.textsecuregcm.purchases.PaymentMethod.PAYPAL,
oneTimeDonationConfiguration,
braintreeManager);
@@ -229,7 +235,9 @@ public class OneTimeDonationsGrpcService extends SimpleOneTimeDonationsGrpc.OneT
case final OneTimeDonationUtil.OneTimeDonationRequestValidationResult.AmountBelowMinimum r ->
ConfirmPayPalBoostResponse.newBuilder()
.setAmountBelowMinimum(AmountBelowMinimumError.newBuilder()
.setMinimum(r.minimum().toString()).build()).build();
.setMinimum(SubscriptionCurrencyUtil.convertPrimaryToMinorUnits(request.getCurrency(),
r.minimum()))
.build()).build();
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.AmountAboveSepaLimit _ ->
throw new IllegalStateException("SEPA limit should not trigger for PayPal");
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.Success _ -> {
@@ -243,7 +251,7 @@ public class OneTimeDonationsGrpcService extends SimpleOneTimeDonationsGrpc.OneT
yield ConfirmPayPalBoostResponse.newBuilder()
.setResult(ConfirmPayPalBoostResponse.ConfirmPayPalBoostResult.newBuilder()
.setPaymentId(chargeSuccessDetails.paymentId()).build()).build();
} catch (final SubscriptionProcessorException e) {
} catch (final PurchaseProcessorException e) {
yield ConfirmPayPalBoostResponse.newBuilder()
.setChargeFailure(SubscriptionsUtil.toChargeFailure(e.getProcessor(), e.getChargeFailure()))
.build();
@@ -253,34 +261,28 @@ public class OneTimeDonationsGrpcService extends SimpleOneTimeDonationsGrpc.OneT
}
@Override
public CreateBoostReceiptCredentialsResponse createBoostReceiptCredentials(
final CreateBoostReceiptCredentialsRequest request) throws IOException {
public CreateBoostReceiptCredentialResponse createBoostReceiptCredential(
final CreateBoostReceiptCredentialRequest request) throws IOException {
final PaymentProvider processor = PaymentProvider.fromProto(request.getProcessor())
.orElseThrow(() -> GrpcExceptions.fieldViolation("processor", "Unsupported payment processor"));
final Optional<PaymentDetails> maybePaymentDetails = switch (processor) {
case STRIPE -> stripeManager.claimOneTimePurchase(request.getPaymentIntentId());
case BRAINTREE -> braintreeManager.claimOneTimePurchase(request.getPaymentIntentId());
default -> throw GrpcExceptions.fieldViolation("processor", "Unsupported payment processor");
};
if (maybePaymentDetails.isEmpty()) {
return CreateBoostReceiptCredentialsResponse.newBuilder()
final PaymentDetails paymentDetails;
try {
paymentDetails = switch (processor) {
case STRIPE -> stripeManager.claimOneTimePurchase(request.getPaymentIntentId());
case BRAINTREE -> braintreeManager.claimOneTimePurchase(request.getPaymentIntentId());
default -> throw GrpcExceptions.fieldViolation("processor", "Unsupported payment processor");
};
} catch (PurchaseNotFoundException _) {
return CreateBoostReceiptCredentialResponse.newBuilder()
.setPaymentNotFound(NotFound.getDefaultInstance()).build();
}
final PaymentDetails paymentDetails = maybePaymentDetails.get();
if (paymentDetails.status() == PaymentStatus.PROCESSING) {
return CreateBoostReceiptCredentialsResponse.newBuilder()
} catch (PurchaseReceiptRequestedForOpenPaymentException _) {
return CreateBoostReceiptCredentialResponse.newBuilder()
.setPaymentStillProcessing(FailedPrecondition.getDefaultInstance()).build();
}
if (paymentDetails.status() != PaymentStatus.SUCCEEDED) {
final PaymentRequired.Builder paymentRequiredBuilder = PaymentRequired.newBuilder();
if (paymentDetails.chargeFailure() != null) {
paymentRequiredBuilder.setChargeFailure(toChargeFailure(processor, paymentDetails.chargeFailure()));
}
return CreateBoostReceiptCredentialsResponse.newBuilder()
.setPaymentRequired(paymentRequiredBuilder).build();
} catch (PurchasePaymentRequiredException e) {
return CreateBoostReceiptCredentialResponse.newBuilder()
.setPaymentRequired(SubscriptionsUtil.toPaymentRequired(e)).build();
}
final OneTimeDonationUtil.DonationLevelDetails levelDetails;
@@ -308,7 +310,7 @@ public class OneTimeDonationsGrpcService extends SimpleOneTimeDonationsGrpc.OneT
issuedReceiptsManager.recordOneTimeIssuance(
paymentDetails.id(), processor, receiptCredentialRequest, expiration);
} catch (final WriteConflictException e) {
return CreateBoostReceiptCredentialsResponse.newBuilder()
return CreateBoostReceiptCredentialResponse.newBuilder()
.setReceiptAlreadyIssued(FailedPrecondition.getDefaultInstance()).build();
}
@@ -328,8 +330,8 @@ public class OneTimeDonationsGrpcService extends SimpleOneTimeDonationsGrpc.OneT
UserAgentTagUtil.getPlatformTag(RequestAttributesUtil.getUserAgent().orElse(null))))
.increment();
return CreateBoostReceiptCredentialsResponse.newBuilder()
.setResult(CreateBoostReceiptCredentialsResponse.CreateBoostReceiptCredentialsResult.newBuilder()
return CreateBoostReceiptCredentialResponse.newBuilder()
.setResult(CreateBoostReceiptCredentialResponse.CreateBoostReceiptCredentialResult.newBuilder()
.setReceiptCredentialResponse(ByteString.copyFrom(receiptCredentialResponse.serialize()))
.build())
.build();
@@ -1,6 +1,5 @@
package org.whispersystems.textsecuregcm.grpc;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -17,9 +16,10 @@ import org.signal.chat.purchase.SimpleProductConfigurationGrpc;
import org.whispersystems.textsecuregcm.configuration.LoginPurchaseConfiguration;
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration;
import org.whispersystems.textsecuregcm.configuration.SubscriptionConfiguration;
import org.whispersystems.textsecuregcm.subscriptions.CustomerAwareSubscriptionPaymentProcessor;
import org.whispersystems.textsecuregcm.subscriptions.PaymentMethod;
import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel;
import org.whispersystems.textsecuregcm.purchases.CustomerAwareSubscriptionPaymentProcessor;
import org.whispersystems.textsecuregcm.purchases.PaymentMethod;
import org.whispersystems.textsecuregcm.purchases.ReceiptLevel;
import org.whispersystems.textsecuregcm.purchases.SubscriptionCurrencyUtil;
public class ProductConfigurationGrpcService extends SimpleProductConfigurationGrpc.ProductConfigurationImplBase {
private final GetConfigurationResponse configurationResponse;
@@ -32,7 +32,8 @@ public class ProductConfigurationGrpcService extends SimpleProductConfigurationG
final long backupMediaStorageAllowanceBytes) {
this.configurationResponse = GetConfigurationResponse.newBuilder()
.setBackup(buildBackupConfiguration(subscriptionConfiguration, backupMediaStorageAllowanceBytes))
.setSepaMaximumEuros(oneTimeDonationConfiguration.sepaMaximumEuros().toString())
.setSepaMaximumEuros(SubscriptionCurrencyUtil.convertPrimaryToMinorUnits(
OneTimeDonationUtil.EURO_CURRENCY_CODE, oneTimeDonationConfiguration.sepaMaximumEuros()))
.putAllCurrencies(buildCurrencyConfigurations(subscriptionConfiguration, oneTimeDonationConfiguration, paymentProcessors))
.putAllBadgeLevels(buildLevelConfigurations(subscriptionConfiguration, oneTimeDonationConfiguration))
.setLogin(buildLoginConfiguration(loginPurchaseConfiguration))
@@ -95,26 +96,29 @@ public class ProductConfigurationGrpcService extends SimpleProductConfigurationG
return LoginConfiguration.newBuilder()
.setLevel(ReceiptLevel.LOGIN.getValue())
.setPlayProductId(loginPurchaseConfiguration.playProductId())
.setPlayOptionId(loginPurchaseConfiguration.playOptionId())
.setAppStoreProductId(loginPurchaseConfiguration.appStoreProductId())
.build();
}
private static CurrencyConfiguration toProtoCurrencyConfiguration(
final String currency,
final org.whispersystems.textsecuregcm.subscriptions.CurrencyConfiguration config) {
final org.whispersystems.textsecuregcm.purchases.CurrencyConfiguration config) {
final CurrencyConfiguration.Builder builder = CurrencyConfiguration.newBuilder()
.setMinimum(config.minimum().toString())
.setMinimum(SubscriptionCurrencyUtil.convertPrimaryToMinorUnits(currency, config.minimum()))
.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())
.addAllAmounts(amounts.stream()
.map(amount -> SubscriptionCurrencyUtil.convertPrimaryToMinorUnits(currency, amount))
.toList())
.build()));
config.subscription()
.forEach((levelId, amount) -> builder.putSubscription(levelId, amount.toString()));
.forEach((levelId, amount) -> builder.putSubscription(levelId, SubscriptionCurrencyUtil.convertPrimaryToMinorUnits(currency, amount)));
config.backupSubscription()
.forEach((levelId, amount) -> builder.putBackupSubscription(levelId, amount.toString()));
.forEach((levelId, amount) -> builder.putBackupSubscription(levelId, SubscriptionCurrencyUtil.convertPrimaryToMinorUnits(currency, amount)));
return builder.build();
}
}
@@ -7,6 +7,7 @@ package org.whispersystems.textsecuregcm.grpc;
import com.google.common.annotations.VisibleForTesting;
import com.google.protobuf.Empty;
import io.micrometer.core.instrument.Metrics;
import java.time.Clock;
import java.util.Base64;
import java.util.Optional;
@@ -20,10 +21,10 @@ 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.GetProfileAnonymousRequest;
import org.signal.chat.profile.GetProfileAnonymousResponse;
import org.signal.chat.profile.GetProfileKeyCredentialRequest;
import org.signal.chat.profile.GetProfileKeyCredentialResponse;
import org.signal.chat.profile.SimpleProfileAnonymousGrpc;
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
import org.signal.libsignal.zkgroup.InvalidInputException;
@@ -36,6 +37,7 @@ import org.whispersystems.textsecuregcm.badges.ProfileBadgeConverter;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
@@ -43,6 +45,9 @@ import org.whispersystems.textsecuregcm.storage.ProfilesManager;
import org.whispersystems.textsecuregcm.util.ProfileHelper;
public class ProfileAnonymousGrpcService extends SimpleProfileAnonymousGrpc.ProfileAnonymousImplBase {
private static final String GET_PROFILE_RESPONSE_CASE_COUNTER_NAME = MetricsUtil.name(ProfileAnonymousGrpcService.class, "getProfile");
private final AccountsManager accountsManager;
private final ProfilesManager profilesManager;
private final ProfileBadgeConverter profileBadgeConverter;
@@ -118,7 +123,7 @@ public class ProfileAnonymousGrpcService extends SimpleProfileAnonymousGrpc.Prof
}
final byte[] version = request.getRequest().getVersion().toByteArray();
return targetAccount.flatMap(account -> ProfileGrpcHelper
final GetProfileAnonymousResponse response = targetAccount.flatMap(account -> ProfileGrpcHelper
.getProfile(account, profilesManager, profileBadgeConverter, version)
// If the etag matches, drop the result
@@ -131,39 +136,51 @@ public class ProfileAnonymousGrpcService extends SimpleProfileAnonymousGrpc.Prof
.getProfileV1(account, profilesManager, profileBadgeConverter, version)
.map(v1Result -> GetProfileAnonymousResponse.newBuilder().setProfileV1(v1Result).build())))
.orElseGet(() -> GetProfileAnonymousResponse.newBuilder().setNotFound(NotFound.getDefaultInstance()).build());
Metrics.counter(GET_PROFILE_RESPONSE_CASE_COUNTER_NAME, "responseCase", response.getResponseCase().name())
.increment();
return response;
}
@Override
public GetExpiringProfileKeyCredentialAnonymousResponse getExpiringProfileKeyCredential(
final GetExpiringProfileKeyCredentialAnonymousRequest request) {
final ServiceIdentifier targetIdentifier = GrpcServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getRequest().getAccountIdentifier());
public GetProfileKeyCredentialResponse getProfileKeyCredential(
final GetProfileKeyCredentialRequest request) {
final ServiceIdentifier targetIdentifier = GrpcServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getAccountIdentifier());
if (request.getRequest().getCredentialType() != CredentialType.CREDENTIAL_TYPE_EXPIRING_PROFILE_KEY) {
if (request.getCredentialType() != CredentialType.CREDENTIAL_TYPE_EXPIRING_PROFILE_KEY) {
throw GrpcExceptions.invalidArguments("invalid credential type");
}
final Optional<Account> maybeAccount = getTargetAccountAndValidateUnidentifiedAccess(
targetIdentifier, request.getUnidentifiedAccessKey().toByteArray());
final Optional<Account> maybeAccount = accountsManager.getByServiceIdentifier(targetIdentifier);
if (maybeAccount.isEmpty()) {
return GetProfileKeyCredentialResponse.newBuilder()
.setNotFound(NotFound.getDefaultInstance())
.build();
}
return maybeAccount.map(account ->
ProfileGrpcHelper.getExpiringProfileKeyCredentialResult(account,
request.getRequest().getVersion().toByteArray(), request.getRequest().getCredentialRequest().toByteArray(),
profilesManager, zkProfileOperations)
.map(result -> GetExpiringProfileKeyCredentialAnonymousResponse.newBuilder()
.setResult(result)
.build())
.orElseGet(() -> GetExpiringProfileKeyCredentialAnonymousResponse.newBuilder()
.setNotFound(NotFound.getDefaultInstance())
.build())).orElseGet(() -> GetExpiringProfileKeyCredentialAnonymousResponse.newBuilder()
.setNotFound(NotFound.getDefaultInstance())
.build());
final Account account = maybeAccount.get();
}
if (!UnidentifiedAccessUtil.checkUnidentifiedAccess(account, request.getUnidentifiedAccessKey().toByteArray())) {
return GetProfileKeyCredentialResponse.newBuilder()
.setFailedUnidentifiedAuthorization(FailedUnidentifiedAuthorization.getDefaultInstance())
.build();
}
private Optional<Account> getTargetAccountAndValidateUnidentifiedAccess(final ServiceIdentifier targetIdentifier, final byte[] unidentifiedAccessKey) {
return accountsManager.getByServiceIdentifier(targetIdentifier)
.filter(targetAccount -> UnidentifiedAccessUtil.checkUnidentifiedAccess(targetAccount, unidentifiedAccessKey));
// By presenting the correct unidentified access key, the client has confirmed they have the current profile key.
// If the credential request is somehow for a different profile version, then the below will fail (and it’s
// a client bug).
return account.getCurrentProfileVersion()
.flatMap(currentVersion ->
ProfileGrpcHelper.getProfileKeyCredentialResult(account,
currentVersion, request.getCredentialRequest().toByteArray(),
profilesManager, zkProfileOperations)
.map(result -> GetProfileKeyCredentialResponse.newBuilder()
.setResult(result)
.build()))
.orElseGet(() -> GetProfileKeyCredentialResponse.newBuilder()
.setNotFound(NotFound.getDefaultInstance())
.build());
}
@Override
@@ -172,7 +189,7 @@ public class ProfileAnonymousGrpcService extends SimpleProfileAnonymousGrpc.Prof
try {
presentation = new AvatarUploadCredentialPresentation(
request.getAvatarCredentialsPresentation().toByteArray());
request.getAvatarCredentialPresentation().toByteArray());
presentation.verify(clock.instant(), this.genericServerSecretParams);
@@ -181,7 +198,7 @@ public class ProfileAnonymousGrpcService extends SimpleProfileAnonymousGrpc.Prof
} catch (VerificationFailedException _) {
return GetAvatarUploadFormResponse.newBuilder()
.setInvalidCredentialsPresentation(FailedZkAuthentication.getDefaultInstance())
.setInvalidCredentialPresentation(FailedZkAuthentication.getDefaultInstance())
.build();
}
@@ -203,7 +220,7 @@ public class ProfileAnonymousGrpcService extends SimpleProfileAnonymousGrpc.Prof
final AvatarUploadCredentialPresentation presentation;
try {
presentation = new AvatarUploadCredentialPresentation(
request.getAvatarCredentialsPresentation().toByteArray());
request.getAvatarCredentialPresentation().toByteArray());
} catch (InvalidInputException _) {
throw GrpcExceptions.invalidArguments("invalid credential presentation");
}
@@ -213,7 +230,7 @@ public class ProfileAnonymousGrpcService extends SimpleProfileAnonymousGrpc.Prof
} catch (VerificationFailedException _) {
return ExtendAvatarTTLResponse.newBuilder()
.setInvalidCredentialsPresentation(FailedZkAuthentication.getDefaultInstance())
.setInvalidCredentialPresentation(FailedZkAuthentication.getDefaultInstance())
.build();
}
@@ -233,7 +250,7 @@ public class ProfileAnonymousGrpcService extends SimpleProfileAnonymousGrpc.Prof
final AvatarUploadCredentialPresentation presentation;
try {
presentation = new AvatarUploadCredentialPresentation(
request.getAvatarCredentialsPresentation().toByteArray());
request.getAvatarCredentialPresentation().toByteArray());
} catch (InvalidInputException _) {
throw GrpcExceptions.invalidArguments("invalid credential presentation");
}
@@ -243,7 +260,7 @@ public class ProfileAnonymousGrpcService extends SimpleProfileAnonymousGrpc.Prof
} catch (VerificationFailedException _) {
return DeleteAvatarResponse.newBuilder()
.setInvalidCredentialsPresentation(FailedZkAuthentication.getDefaultInstance())
.setInvalidCredentialPresentation(FailedZkAuthentication.getDefaultInstance())
.build();
}
@@ -17,7 +17,7 @@ import java.util.Optional;
import org.bouncycastle.crypto.digests.TupleHash;
import org.signal.chat.common.S3UploadForm;
import org.signal.chat.profile.AccountInfo;
import org.signal.chat.profile.GetExpiringProfileKeyCredentialResult;
import org.signal.chat.profile.GetProfileKeyCredentialResult;
import org.signal.chat.profile.LegacyProfileResult;
import org.signal.chat.profile.ProfileResult;
import org.signal.chat.profile.ProfileResultOrBuilder;
@@ -128,7 +128,7 @@ public class ProfileGrpcHelper {
return accountInfoBuilder.build();
}
static Optional<GetExpiringProfileKeyCredentialResult> getExpiringProfileKeyCredentialResult(
static Optional<GetProfileKeyCredentialResult> getProfileKeyCredentialResult(
final Account account,
final byte[] version,
final byte[] encodedCredentialRequest,
@@ -156,7 +156,7 @@ public class ProfileGrpcHelper {
throw GrpcExceptions.invalidArguments("invalid credential request");
}
return GetExpiringProfileKeyCredentialResult.newBuilder()
return GetProfileKeyCredentialResult.newBuilder()
.setProfileKeyCredential(ByteString.copyFrom(profileKeyCredentialResponse.serialize()))
.build();
});
@@ -21,12 +21,11 @@ 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.GetAvatarCredentialRequest;
import org.signal.chat.profile.GetAvatarCredentialResponse;
import org.signal.chat.profile.GetProfileRequest;
import org.signal.chat.profile.GetProfileResponse;
import org.signal.chat.profile.PaymentsForbiddenInRegion;
import org.signal.chat.profile.ProfilesV2CapabilityRequired;
import org.signal.chat.profile.SetProfileRequest;
import org.signal.chat.profile.SetProfileResponse;
import org.signal.chat.profile.SetProfileResult;
@@ -54,7 +53,6 @@ import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountBadge;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
import org.whispersystems.textsecuregcm.storage.VersionedProfile;
@@ -111,12 +109,6 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
final Account account = accountsManager.getByAccountIdentifier(authenticatedDevice.accountIdentifier())
.orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials"));
if (!account.hasCapability(DeviceCapability.PROFILES_V2)) {
return SetProfileResponse.newBuilder()
.setProfilesV2CapabilityRequired(ProfilesV2CapabilityRequired.getDefaultInstance())
.build();
}
validateRequest(request);
final byte[] expectedCurrentVersion = request.getExpectedCurrentVersion().toByteArray();
@@ -221,7 +213,7 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
}
@Override
public GetAvatarCredentialsResponse getAvatarCredentials(final GetAvatarCredentialsRequest request) {
public GetAvatarCredentialResponse getAvatarCredential(final GetAvatarCredentialRequest request) {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
@@ -229,14 +221,14 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
.orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials"));
if (account.getZkCredentialKey().isEmpty()) {
return GetAvatarCredentialsResponse.newBuilder()
return GetAvatarCredentialResponse.newBuilder()
.setMissingZkCredentialKey(FailedPrecondition.newBuilder().setDescription("account requires ZK credential key"))
.build();
}
try {
final AvatarUploadCredentialRequest credentialRequest = new AvatarUploadCredentialRequest(
request.getAvatarCredentialsRequest().toByteArray());
request.getAvatarCredentialRequest().toByteArray());
final AvatarUploadCredentialResponse credentialResponse = credentialRequest.issueCredential(
new ServiceId.Aci(account.getAccountIdentifier()),
@@ -245,8 +237,8 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
clock.instant().truncatedTo(ChronoUnit.DAYS),
this.genericServerSecretParams);
return GetAvatarCredentialsResponse.newBuilder()
.setAvatarCredentials(ByteString.copyFrom(credentialResponse.serialize()))
return GetAvatarCredentialResponse.newBuilder()
.setAvatarCredential(ByteString.copyFrom(credentialResponse.serialize()))
.build();
} catch (InvalidInputException | VerificationFailedException _) {
throw GrpcExceptions.invalidArguments("invalid credential request");
@@ -5,16 +5,15 @@ import static org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil.getPayPalL
import com.google.protobuf.ByteString;
import com.google.protobuf.Empty;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.time.Clock;
import java.util.Locale;
import java.util.Optional;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import org.signal.chat.errors.FailedPrecondition;
import org.signal.chat.errors.FailedUnidentifiedAuthorization;
import org.signal.chat.errors.FailedZkAuthentication;
import org.signal.chat.errors.NotFound;
import org.signal.chat.purchase.CreatePayPalPaymentMethodRequest;
@@ -25,11 +24,10 @@ 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.GetReceiptCredentialRequest;
import org.signal.chat.purchase.GetReceiptCredentialResponse;
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;
@@ -51,29 +49,28 @@ import org.whispersystems.textsecuregcm.storage.DonationPermitsManager;
import org.whispersystems.textsecuregcm.storage.SubscriberCredentials;
import org.whispersystems.textsecuregcm.storage.SubscriptionManager;
import org.whispersystems.textsecuregcm.storage.Subscriptions;
import org.whispersystems.textsecuregcm.subscriptions.AppleAppStoreManager;
import org.whispersystems.textsecuregcm.subscriptions.BankMandateTranslator;
import org.whispersystems.textsecuregcm.subscriptions.BankTransferType;
import org.whispersystems.textsecuregcm.subscriptions.BraintreeManager;
import org.whispersystems.textsecuregcm.subscriptions.CustomerAwareSubscriptionPaymentProcessor;
import org.whispersystems.textsecuregcm.subscriptions.GooglePlayBillingManager;
import org.whispersystems.textsecuregcm.subscriptions.ProcessorCustomer;
import org.whispersystems.textsecuregcm.subscriptions.StripeManager;
import org.whispersystems.textsecuregcm.subscriptions.SubscriberIdCreationNotPermittedException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionChargeFailurePaymentRequiredException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionForbiddenException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInformation;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidArgumentsException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidIdempotencyKeyException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidLevelException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionNotFoundException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentRequiredException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentRequiresActionException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorConflictException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptAlreadyRedeemedException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptRequestedForOpenPaymentException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionStatus;
import org.whispersystems.textsecuregcm.purchases.AppleAppStoreManager;
import org.whispersystems.textsecuregcm.purchases.BankMandateTranslator;
import org.whispersystems.textsecuregcm.purchases.BankTransferType;
import org.whispersystems.textsecuregcm.purchases.BraintreeManager;
import org.whispersystems.textsecuregcm.purchases.CustomerAwareSubscriptionPaymentProcessor;
import org.whispersystems.textsecuregcm.purchases.GooglePlayBillingManager;
import org.whispersystems.textsecuregcm.purchases.ProcessorCustomer;
import org.whispersystems.textsecuregcm.purchases.StripeManager;
import org.whispersystems.textsecuregcm.purchases.SubscriberIdCreationNotPermittedException;
import org.whispersystems.textsecuregcm.purchases.PurchaseForbiddenException;
import org.whispersystems.textsecuregcm.purchases.SubscriptionInformation;
import org.whispersystems.textsecuregcm.purchases.PurchaseInvalidArgumentsException;
import org.whispersystems.textsecuregcm.purchases.PurchaseInvalidIdempotencyKeyException;
import org.whispersystems.textsecuregcm.purchases.PurchaseInvalidLevelException;
import org.whispersystems.textsecuregcm.purchases.PurchaseNotFoundException;
import org.whispersystems.textsecuregcm.purchases.PurchasePaymentRequiredException;
import org.whispersystems.textsecuregcm.purchases.PurchasePaymentRequiresActionException;
import org.whispersystems.textsecuregcm.purchases.PurchaseProcessorConflictException;
import org.whispersystems.textsecuregcm.purchases.PurchaseProcessorException;
import org.whispersystems.textsecuregcm.purchases.PurchaseReceiptAlreadyRedeemedException;
import org.whispersystems.textsecuregcm.purchases.PurchaseReceiptRequestedForOpenPaymentException;
import org.whispersystems.textsecuregcm.purchases.SubscriptionStatus;
public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.SubscriptionsImplBase {
@@ -140,9 +137,8 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
subscriptionManager.updateSubscriber(subscriberCredentials, creationPermitted);
return UpdateSubscriberResponse.newBuilder().setSuccess(Empty.getDefaultInstance()).build();
} catch (final SubscriptionForbiddenException e) {
return UpdateSubscriberResponse.newBuilder().setSubscriberIdMismatch(
FailedUnidentifiedAuthorization.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
} catch (final PurchaseForbiddenException _) {
throw GrpcExceptions.invalidArguments("subscriber-ids must be randomly generated");
} catch (SubscriberIdCreationNotPermittedException _) {
if (request.getDonationPermit().isEmpty()) {
throw GrpcExceptions.invalidArguments("donation permit is required to create a subscriber ID");
@@ -165,9 +161,9 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
request.getSubscriberId().toByteArray(), clock);
subscriptionManager.deleteSubscriber(subscriberCredentials);
return DeleteSubscriberResponse.newBuilder().setSuccess(Empty.getDefaultInstance()).build();
} catch (final SubscriptionNotFoundException e) {
} catch (final PurchaseNotFoundException e) {
return DeleteSubscriberResponse.newBuilder().setSubscriberNotFound(NotFound.newBuilder().build()).build();
} catch (final SubscriptionInvalidArgumentsException e) {
} catch (final PurchaseInvalidArgumentsException e) {
return DeleteSubscriberResponse.newBuilder().setCannotCancelSubscription(
FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
}
@@ -206,12 +202,9 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
return CreatePaymentMethodResponse.newBuilder().setResult(
CreatePaymentMethodResponse.CreatePaymentMethodResult.newBuilder().setClientSecret(token)
.setPaymentProvider(customerAwareSubscriptionPaymentProcessor.getProvider().toProto()).build()).build();
} catch (final SubscriptionNotFoundException e) {
} catch (final PurchaseNotFoundException | PurchaseForbiddenException _) {
return CreatePaymentMethodResponse.newBuilder().setSubscriberNotFound(NotFound.newBuilder()).build();
} catch (final SubscriptionForbiddenException e) {
return CreatePaymentMethodResponse.newBuilder().setSubscriberIdMismatch(
FailedUnidentifiedAuthorization.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
} catch (final SubscriptionProcessorConflictException e) {
} catch (final PurchaseProcessorConflictException e) {
return CreatePaymentMethodResponse.newBuilder().setSubscriptionProcessorConflict(
FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
}
@@ -231,13 +224,10 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
return CreatePayPalPaymentMethodResponse.newBuilder().setResult(
CreatePayPalPaymentMethodResponse.CreatePayPalPaymentMethodResult.newBuilder()
.setApprovalUrl(details.approvalUrl()).setToken(details.billingAgreementToken()).build()).build();
} catch (final SubscriptionNotFoundException e) {
} catch (final PurchaseNotFoundException | PurchaseForbiddenException _) {
return CreatePayPalPaymentMethodResponse.newBuilder().setSubscriberNotFound(NotFound.newBuilder().build())
.build();
} catch (final SubscriptionForbiddenException e) {
return CreatePayPalPaymentMethodResponse.newBuilder().setSubscriberIdMismatch(
FailedUnidentifiedAuthorization.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
} catch (final SubscriptionProcessorConflictException e) {
} catch (final PurchaseProcessorConflictException e) {
return CreatePayPalPaymentMethodResponse.newBuilder().setSubscriptionProcessorConflict(
FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
}
@@ -267,22 +257,20 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
};
final Subscriptions.Record record = subscriptionManager.getSubscriber(subscriberCredentials);
return record.getProcessorCustomer().map(
processorCustomer -> setDefaultPaymentMethodForCustomer(manager, processorCustomer, paymentMethodId,
record.subscriptionId)).orElseGet(() ->
return record.getProcessorCustomer()
.map(processorCustomer ->
setDefaultPaymentMethodForCustomer(manager, processorCustomer, paymentMethodId, record.subscriptionId))
// a missing customer ID indicates the client made requests out of order,
// and needs to call create_payment_method to create a customer for the given payment method
SetDefaultPaymentMethodResponse.newBuilder().setPaymentMethodNotSetUp(FailedPrecondition.newBuilder().build())
.orElseGet(() -> SetDefaultPaymentMethodResponse.newBuilder()
.setPaymentMethodNotSetUp(FailedPrecondition.newBuilder().build())
.build());
} catch (final SubscriptionNotFoundException e) {
} catch (final PurchaseNotFoundException | PurchaseForbiddenException _) {
return SetDefaultPaymentMethodResponse.newBuilder().setSubscriberNotFound(NotFound.newBuilder().build()).build();
} catch (final SubscriptionForbiddenException e) {
return SetDefaultPaymentMethodResponse.newBuilder().setSubscriberIdMismatch(
FailedUnidentifiedAuthorization.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
} catch (final SubscriptionProcessorConflictException e) {
} catch (final PurchaseProcessorConflictException _) {
return SetDefaultPaymentMethodResponse.newBuilder()
.setSubscriptionProcessorConflict(
FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
.setPaymentMethodNotSetUp(FailedPrecondition.newBuilder().build())
.build();
}
}
@@ -292,7 +280,7 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
try {
processor.setDefaultPaymentMethodForCustomer(processorCustomer.customerId(), paymentMethodId, subscriptionId);
return SetDefaultPaymentMethodResponse.newBuilder().setSuccess(Empty.getDefaultInstance()).build();
} catch (final SubscriptionInvalidArgumentsException e) {
} catch (final PurchaseInvalidArgumentsException e) {
// Here, invalid arguments must mean that the client has made requests out of order, and needs to finish
// setting up the paymentMethod first
return SetDefaultPaymentMethodResponse.newBuilder()
@@ -310,16 +298,14 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
request.getSubscriberId().toByteArray(), clock);
try {
final Subscriptions.Record record = subscriptionManager.getSubscriber(subscriberCredentials);
return record.getProcessorCustomer().map(
processorCustomer -> setSubscriptionLevelForCustomer(processorCustomer, subscriberCredentials, record,
request)).orElseGet(() -> SetSubscriptionLevelResponse.newBuilder()
.setPaymentMethodNotSetUp(FailedPrecondition.newBuilder().build()).build());
return record.getProcessorCustomer().map(processorCustomer ->
setSubscriptionLevelForCustomer(processorCustomer, subscriberCredentials, record, request))
.orElseGet(() -> SetSubscriptionLevelResponse.newBuilder()
.setPaymentMethodNotSetUp(FailedPrecondition.newBuilder().build())
.build());
} catch (final SubscriptionNotFoundException e) {
} catch (final PurchaseNotFoundException | PurchaseForbiddenException _) {
return SetSubscriptionLevelResponse.newBuilder().setSubscriberNotFound(NotFound.newBuilder().build()).build();
} catch (final SubscriptionForbiddenException e) {
return SetSubscriptionLevelResponse.newBuilder().setSubscriberIdMismatch(
FailedUnidentifiedAuthorization.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
}
}
@@ -358,20 +344,20 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
return SetSubscriptionLevelResponse.newBuilder().setSuccess(
SetSubscriptionLevelResponse.SetSubscriptionLevelResult.newBuilder().setLevel(request.getLevel()).build())
.build();
} catch (final SubscriptionInvalidIdempotencyKeyException e) {
} catch (final PurchaseInvalidIdempotencyKeyException e) {
return SetSubscriptionLevelResponse.newBuilder()
.setInvalidIdempotencyKey(FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build())
.build();
} catch (final SubscriptionProcessorException e) {
} catch (final PurchaseProcessorException e) {
return SetSubscriptionLevelResponse.newBuilder()
.setChargeFailure(SubscriptionsUtil.toChargeFailure(e.getProcessor(), e.getChargeFailure())).build();
} catch (final SubscriptionPaymentRequiresActionException e) {
} catch (final PurchasePaymentRequiresActionException e) {
return SetSubscriptionLevelResponse.newBuilder().setPaymentRequiresAction(FailedPrecondition.newBuilder().build())
.build();
} catch (final SubscriptionInvalidLevelException e) {
} catch (final PurchaseInvalidLevelException e) {
return SetSubscriptionLevelResponse.newBuilder()
.setInvalidLevelTransition(FailedPrecondition.newBuilder().build()).build();
} catch (final SubscriptionProcessorConflictException e) {
} catch (final PurchaseProcessorConflictException e) {
return SetSubscriptionLevelResponse.newBuilder().setSubscriptionProcessorConflict(
FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
}
@@ -394,18 +380,15 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
};
return SetIapSubscriptionResponse.newBuilder()
.setSuccess(SetIapSubscriptionResponse.SetIapSubscriptionResult.newBuilder().setLevel(level).build()).build();
} catch (final SubscriptionNotFoundException e) {
} catch (final PurchaseNotFoundException | PurchaseForbiddenException _) {
return SetIapSubscriptionResponse.newBuilder().setSubscriberNotFound(NotFound.newBuilder().build()).build();
} catch (final SubscriptionForbiddenException e) {
return SetIapSubscriptionResponse.newBuilder().setSubscriberIdMismatch(
FailedUnidentifiedAuthorization.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
} catch (final SubscriptionProcessorConflictException e) {
} catch (final PurchaseProcessorConflictException e) {
return SetIapSubscriptionResponse.newBuilder().setSubscriptionProcessorConflict(
FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
} catch (final SubscriptionPaymentRequiredException e) {
} catch (final PurchasePaymentRequiredException e) {
return SetIapSubscriptionResponse.newBuilder().setPaymentRequired(FailedPrecondition.newBuilder().build())
.build();
} catch (final SubscriptionInvalidArgumentsException e) {
} catch (final PurchaseInvalidArgumentsException e) {
return SetIapSubscriptionResponse.newBuilder()
.setInvalidTransaction(FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build())
.build();
@@ -422,12 +405,9 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
.map(SubscriptionsGrpcService::buildSubscriptionInformationResponse).orElseGet(
() -> GetSubscriptionInformationResponse.newBuilder().setNoSubscription(Empty.getDefaultInstance())
.build());
} catch (final SubscriptionNotFoundException e) {
} catch (final PurchaseNotFoundException | PurchaseForbiddenException _) {
return GetSubscriptionInformationResponse.newBuilder().setSubscriberNotFound(NotFound.newBuilder().build())
.build();
} catch (final SubscriptionForbiddenException e) {
return GetSubscriptionInformationResponse.newBuilder().setSubscriberIdMismatch(
FailedUnidentifiedAuthorization.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
}
}
@@ -437,7 +417,7 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
final GetSubscriptionInformationResponse.Subscription.Builder subscription = GetSubscriptionInformationResponse.Subscription.newBuilder()
.setLevel(info.level()).setEndOfCurrentPeriod(info.endOfCurrentPeriod().getEpochSecond())
.setActive(info.active()).setCancelAtPeriodEnd(info.cancelAtPeriodEnd()).setCurrency(info.price().currency())
.setAmount(info.price().amount().longValue()).setStatus(toProtoSubscriptionStatus(info.status()))
.setAmount(info.price().amount()).setStatus(toProtoSubscriptionStatus(info.status()))
.setProcessor(info.paymentProvider().toProto()).setPaymentMethod(info.paymentMethod().toProtoPaymentMethod())
.setPaymentProcessing(info.paymentProcessing());
if (info.billingCycleAnchor() != null) {
@@ -451,14 +431,15 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
}
@Override
public GetReceiptCredentialsResponse getReceiptCredentials(final GetReceiptCredentialsRequest request)
public GetReceiptCredentialResponse getReceiptCredential(final GetReceiptCredentialRequest request)
throws RateLimitExceededException {
final SubscriberCredentials subscriberCredentials = SubscriberCredentials.process(
request.getSubscriberId().toByteArray(), clock);
try {
final SubscriptionManager.ReceiptResult result = subscriptionManager.createReceiptCredentials(
final SubscriptionManager.ReceiptResult result = subscriptionManager.createReceiptCredential(
subscriberCredentials, request.getReceiptCredentialRequest().toByteArray(),
r -> SubscriptionsUtil.receiptExpirationWithGracePeriod(subscriptionConfiguration, r));
r -> SubscriptionsUtil.receiptExpirationWithGracePeriod(subscriptionConfiguration, r),
RequestAttributesUtil.getUserAgent().orElse(null));
Metrics.counter(RECEIPT_ISSUED_COUNTER_NAME,
Tags.of(
Tag.of(PROCESSOR_TAG_NAME, result.paymentProvider().toString()),
@@ -468,30 +449,23 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
.toLowerCase(Locale.ROOT)),
UserAgentTagUtil.getPlatformTag(RequestAttributesUtil.getUserAgent().orElse(null))))
.increment();
return GetReceiptCredentialsResponse.newBuilder().setSuccess(
GetReceiptCredentialsResponse.GetReceiptCredentialsResult.newBuilder()
return GetReceiptCredentialResponse.newBuilder().setSuccess(
GetReceiptCredentialResponse.GetReceiptCredentialResult.newBuilder()
.setReceiptCredentialResponse(ByteString.copyFrom(result.receiptCredentialResponse().serialize()))
.build()).build();
} catch (final SubscriptionReceiptRequestedForOpenPaymentException e) {
return GetReceiptCredentialsResponse.newBuilder().setNoPaidInvoice(FailedPrecondition.newBuilder().build())
} catch (final PurchaseReceiptRequestedForOpenPaymentException e) {
return GetReceiptCredentialResponse.newBuilder().setNoPaidInvoice(FailedPrecondition.newBuilder().build())
.build();
} catch (final SubscriptionChargeFailurePaymentRequiredException e) {
return GetReceiptCredentialsResponse.newBuilder().setPaymentRequired(
PaymentRequired.newBuilder()
.setChargeFailure(SubscriptionsUtil.toChargeFailure(e.getProcessor(), e.getChargeFailure())).build()).build();
} catch (final SubscriptionPaymentRequiredException e) {
return GetReceiptCredentialsResponse.newBuilder()
.setPaymentRequired(PaymentRequired.newBuilder().build()).build();
} catch (final SubscriptionInvalidArgumentsException e) {
} catch (final PurchasePaymentRequiredException e) {
return GetReceiptCredentialResponse.newBuilder()
.setPaymentRequired(SubscriptionsUtil.toPaymentRequired(e)).build();
} catch (final PurchaseInvalidArgumentsException e) {
throw GrpcExceptions.invalidArguments(e.errorDetail().orElse(""));
} catch (final SubscriptionReceiptAlreadyRedeemedException e) {
return GetReceiptCredentialsResponse.newBuilder().setAlreadyRedeemed(FailedPrecondition.newBuilder().build())
} catch (final PurchaseReceiptAlreadyRedeemedException e) {
return GetReceiptCredentialResponse.newBuilder().setAlreadyRedeemed(FailedPrecondition.newBuilder().build())
.build();
} catch (final SubscriptionNotFoundException e) {
return GetReceiptCredentialsResponse.newBuilder().setSubscriberNotFound(NotFound.newBuilder().build()).build();
} catch (final SubscriptionForbiddenException e) {
return GetReceiptCredentialsResponse.newBuilder().setSubscriberIdMismatch(
FailedUnidentifiedAuthorization.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
} catch (final PurchaseNotFoundException | PurchaseForbiddenException _) {
return GetReceiptCredentialResponse.newBuilder().setSubscriberNotFound(NotFound.newBuilder().build()).build();
}
}
@@ -13,6 +13,7 @@ import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.signal.chat.purchase.PaymentRequired;
import org.signal.libsignal.zkgroup.VerificationFailedException;
import org.signal.libsignal.zkgroup.donation.DonationPermit;
import org.whispersystems.textsecuregcm.badges.BadgeTranslator;
@@ -25,13 +26,14 @@ import org.whispersystems.textsecuregcm.entities.PurchasableBadge;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.storage.DonationPermitsManager;
import org.whispersystems.textsecuregcm.subscriptions.ChargeFailure;
import org.whispersystems.textsecuregcm.subscriptions.CurrencyConfiguration;
import org.whispersystems.textsecuregcm.subscriptions.CustomerAwareSubscriptionPaymentProcessor;
import org.whispersystems.textsecuregcm.subscriptions.LevelConfiguration;
import org.whispersystems.textsecuregcm.subscriptions.PaymentMethod;
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel;
import org.whispersystems.textsecuregcm.purchases.ChargeFailure;
import org.whispersystems.textsecuregcm.purchases.CurrencyConfiguration;
import org.whispersystems.textsecuregcm.purchases.CustomerAwareSubscriptionPaymentProcessor;
import org.whispersystems.textsecuregcm.purchases.LevelConfiguration;
import org.whispersystems.textsecuregcm.purchases.PaymentMethod;
import org.whispersystems.textsecuregcm.purchases.PaymentProvider;
import org.whispersystems.textsecuregcm.purchases.PurchasePaymentRequiredException;
import org.whispersystems.textsecuregcm.purchases.ReceiptLevel;
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
import org.whispersystems.textsecuregcm.util.ua.UnrecognizedUserAgentException;
import org.whispersystems.textsecuregcm.util.ua.UserAgentUtil;
@@ -163,6 +165,12 @@ public class SubscriptionsUtil {
.increment();
}
public static PaymentRequired toPaymentRequired(final PurchasePaymentRequiredException e) {
final PaymentRequired.Builder builder = PaymentRequired.newBuilder();
e.getChargeFailure().ifPresent(chargeFailure -> builder.setChargeFailure(toChargeFailure(e.getProcessor(), chargeFailure)));
return builder.build();
}
public static org.signal.chat.purchase.ChargeFailure toChargeFailure(final PaymentProvider processor,
final ChargeFailure chargeFailure) {
final org.signal.chat.purchase.ChargeFailure.Builder builder = org.signal.chat.purchase.ChargeFailure.newBuilder()
@@ -0,0 +1,123 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc.net;
import com.google.common.annotations.VisibleForTesting;
import io.netty.handler.ssl.OpenSsl;
import io.netty.handler.ssl.ReferenceCountedOpenSslEngine;
import io.netty.internal.tcnative.SSL;
import java.net.Socket;
import java.security.Principal;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.Optional;
import javax.annotation.Nullable;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.X509ExtendedKeyManager;
import javax.net.ssl.X509KeyManager;
/// A server key manager for netty's BoringSSL provider that uses a client's signature algorithm preferences, enabling
/// support for ed25519.
///
/// This works around [netty#10916](https://github.com/netty/netty/issues/10916) by addressing two issues in key selection:
///
/// 1. Netty’s engine only declares support for RSA- and EC-family key types, and
/// 2. the handshake session's peer signature algorithm converter (`io.netty.handler.ssl.SignatureAlgorithmConverter`)
/// doesn't match BoringSSL's `ed25519`, so ed25519 gets dropped, even if one is presented as a candidate
class BoringSslServerKeyManager extends X509ExtendedKeyManager {
private final X509KeyManager delegate;
@VisibleForTesting
BoringSslServerKeyManager(final X509KeyManager delegate) {
if (!"BoringSSL".equals(OpenSsl.versionString())) {
throw new IllegalStateException("BoringSSL required, found " + OpenSsl.versionString());
}
this.delegate = delegate;
}
/// @throws IllegalArgumentException if `keyManagers` contains no [X509KeyManager]
static BoringSslServerKeyManager wrap(final KeyManager[] keyManagers) {
return Arrays.stream(keyManagers)
.filter(X509KeyManager.class::isInstance)
.map(X509KeyManager.class::cast)
.findFirst()
.map(BoringSslServerKeyManager::new)
.orElseThrow(() -> new IllegalArgumentException("No X509KeyManager found"));
}
@Override
public String chooseEngineServerAlias(final String keyType, final Principal[] issuers, final SSLEngine engine) {
if (!(engine instanceof ReferenceCountedOpenSslEngine openSslEngine)) {
throw new IllegalArgumentException("BoringSslServerKeyManager requires netty's OpenSSL provider");
}
@Nullable final String[] peerSignatureAlgorithms = SSL.getSigAlgs(openSslEngine.sslPointer());
if (peerSignatureAlgorithms == null) {
return null;
}
for (final String signatureAlgorithm : peerSignatureAlgorithms) {
final Optional<String> maybeAlias = getJdkKeyType(signatureAlgorithm)
// The Netty OpenSSL engine doesn't advertise support for Ed25519, and so we can't include the engine in the
// delegate's selection process. Instead, we loop through the peer signature algorithms and find a matching key.
.map(jdkKeyType -> delegate.chooseServerAlias(jdkKeyType, issuers, null));
if (maybeAlias.isPresent()) {
return maybeAlias.get();
}
}
return null;
}
/// Maps a [BoringSSL signature algorithm name](https://github.com/google/boringssl/blob/8525ff3/ssl/ssl_privkey.cc#L420-L433)
/// to the JDK key type that can produce it
@VisibleForTesting
static Optional<String> getJdkKeyType(final String signatureAlgorithm) {
if (signatureAlgorithm.equals("ed25519")) {
return Optional.of("EdDSA");
} else if (signatureAlgorithm.startsWith("ecdsa_")) {
return Optional.of("EC");
} else if (signatureAlgorithm.startsWith("rsa_pss_rsae_")) {
return Optional.of("RSA");
}
// We don't need to be exhaustive, because we require TLS 1.3 and only use a limited number of key types.
return Optional.empty();
}
@Override
public String chooseServerAlias(final String keyType, final Principal[] issuers, final Socket socket) {
return delegate.chooseServerAlias(keyType, issuers, socket);
}
@Override
public String[] getServerAliases(final String keyType, final Principal[] issuers) {
return delegate.getServerAliases(keyType, issuers);
}
@Override
public String chooseClientAlias(final String[] keyTypes, final Principal[] issuers, final Socket socket) {
return delegate.chooseClientAlias(keyTypes, issuers, socket);
}
@Override
public String[] getClientAliases(final String keyType, final Principal[] issuers) {
return delegate.getClientAliases(keyType, issuers);
}
@Override
public X509Certificate[] getCertificateChain(final String alias) {
return delegate.getCertificateChain(alias);
}
@Override
public PrivateKey getPrivateKey(final String alias) {
return delegate.getPrivateKey(alias);
}
}
@@ -20,9 +20,11 @@ public class H2FrameProxyHandler extends ChannelInboundHandlerAdapter {
private static final Logger logger = LoggerFactory.getLogger(H2FrameProxyHandler.class);
private static final String WRITABILITY_CHANGED_COUNTER_NAME = MetricsUtil.name(H2FrameProxyHandler.class, "writabilityChanged");
private static final String BACKEND_TAG_NAME = "backend";
private final Channel peerStream;
private final String proxyNameTag;
private final String backendNameTag;
// If we fail to write to the peerStream, we want to close the inbound channel. Rather than allocate a new listener
// that captures the inbound ChannelHandlerContext on every message, we capture the ChannelHandlerContext in
@@ -30,9 +32,10 @@ public class H2FrameProxyHandler extends ChannelInboundHandlerAdapter {
// one channel, but we already have a designated peerStream so this handler is fundamentally single-channel.
private ChannelFutureListener closeInboundOnPeerFailure = null;
public H2FrameProxyHandler(final Channel peerStream, final String proxyNameTag) {
public H2FrameProxyHandler(final Channel peerStream, final String proxyNameTag, final String backendNameTag) {
this.peerStream = peerStream;
this.proxyNameTag = proxyNameTag;
this.backendNameTag = backendNameTag;
}
@Override
@@ -50,15 +53,30 @@ public class H2FrameProxyHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelWritabilityChanged(final ChannelHandlerContext peerCtx) throws Exception {
Metrics.counter(WRITABILITY_CHANGED_COUNTER_NAME,
"isWritable", Boolean.toString(peerCtx.channel().isWritable()),
"proxy", proxyNameTag)
"isWritable", Boolean.toString(peerCtx.channel().isWritable()),
"proxy", proxyNameTag,
BACKEND_TAG_NAME, backendNameTag)
.increment();
ctx.channel().config().setAutoRead(peerStream.isWritable());
setAutoRead(ctx.channel(), peerStream.isWritable());
super.channelWritabilityChanged(peerCtx);
}
});
}
/// Set auto-read on `channel`, ensuring the call happens on the channel’s event loop.
///
/// [io.netty.channel.ChannelConfig#setAutoRead] implementations appear to handle calls from outside the event
/// loop, but without conservatively ensuring the call happens on the event loop, proxied responses are sometimes
/// truncated.
private static void setAutoRead(final Channel channel, final boolean autoRead) {
if (!channel.eventLoop().inEventLoop()) {
channel.eventLoop().execute(() -> setAutoRead(channel, autoRead));
return;
}
channel.config().setAutoRead(autoRead);
}
@Override
public void channelRead(final ChannelHandlerContext ctx, final Object msg) {
logger.trace("Received frame {}", msg);
@@ -59,6 +59,8 @@ public class OmnibusH2Server implements Managed {
private static final OmnibusExceptionHandler SESSION_EXCEPTION_HANDLER =
new OmnibusExceptionHandler("omnibus-session", List.of(Http2Exception.class));
private static final OmnibusLoadShedHandler LOAD_SHED_HANDLER = new OmnibusLoadShedHandler();
private static final TlsHandshakeMetricsHandler TLS_HANDSHAKE_METRICS_HANDLER =
new TlsHandshakeMetricsHandler(Metrics.globalRegistry);
private static final String IDLE_DISCONNECT_COUNTER_NAME = MetricsUtil.name(OmnibusH2Server.class, "idleDisconnect");
private final @Nullable Mapping<String, SslContext> sslContextBySni;
@@ -134,6 +136,7 @@ public class OmnibusH2Server implements Managed {
});
} else {
ch.pipeline().addLast(new SniHandler(sslContextBySni));
ch.pipeline().addLast(TLS_HANDSHAKE_METRICS_HANDLER);
ch.pipeline().addLast(new ApplicationProtocolNegotiationHandler(ApplicationProtocolNames.HTTP_2) {
@Override
protected void configurePipeline(final ChannelHandlerContext ctx, final String protocol) {
@@ -145,7 +145,7 @@ public class OmnibusH2StreamHandler extends ChannelInboundHandlerAdapter {
// Connected, open a new H2 stream to the backend so we can proxy the client's frames
logger.trace("Opening a HTTP/2 stream to the backend {}", target);
final Channel backendConnection = connectFuture.channel();
createBackendProxyStream(ctx, backendConnection, headersFrame);
createBackendProxyStream(ctx, backendConnection, headersFrame, backendTag);
});
}
@@ -155,13 +155,15 @@ public class OmnibusH2StreamHandler extends ChannelInboundHandlerAdapter {
/// @param backendConnection An established H2 connection [Channel], on which a new h2 stream will be opened
/// @param headersFrame The first `headersFrame` from the client h2 stream that should be forwarded to the new
/// backend stream
/// @param backendTag The backend this stream targets, for metrics
private void createBackendProxyStream(
final ChannelHandlerContext clientStreamCtx,
final Channel backendConnection,
final Http2HeadersFrame headersFrame) {
final Http2HeadersFrame headersFrame,
final String backendTag) {
new Http2StreamChannelBootstrap(backendConnection)
// Forwards response frames from the backend back to the client stream
.handler(new H2FrameProxyHandler(clientStreamCtx.channel(), "responseStream"))
.handler(new H2FrameProxyHandler(clientStreamCtx.channel(), "responseStream", backendTag))
.open()
.addListener((io.netty.util.concurrent.Future<Http2StreamChannel> streamFuture) -> {
if (!streamFuture.isSuccess()) {
@@ -194,7 +196,7 @@ public class OmnibusH2StreamHandler extends ChannelInboundHandlerAdapter {
clientStreamCtx.pipeline().replace(
OmnibusH2StreamHandler.this,
"backend-to-client-proxy",
new H2FrameProxyHandler(backendStream, "requestStream"));
new H2FrameProxyHandler(backendStream, "requestStream", backendTag));
clientStreamCtx.channel().pipeline().fireChannelRead(headersFrame);
// Resume inbound reads, which should now be forwarded
@@ -5,26 +5,21 @@
package org.whispersystems.textsecuregcm.grpc.net;
import java.net.SocketAddress;
import java.util.List;
import java.util.Map;
public class OmnibusRouter {
public record OmnibusRoute(String prefix, SocketAddress backend) {}
private final List<OmnibusRoute> prefixRoutes;
private final Map<String, SocketAddress> routes;
private final SocketAddress defaultBackend;
public OmnibusRouter(final List<OmnibusRoute> prefixRoutes, final SocketAddress defaultBackend) {
this.prefixRoutes = prefixRoutes;
public OmnibusRouter(final Map<String, SocketAddress> routes, final SocketAddress defaultBackend) {
this.routes = routes;
this.defaultBackend = defaultBackend;
}
SocketAddress match(final String path) {
for (final OmnibusRoute route : prefixRoutes) {
if (path.startsWith(route.prefix)) {
return route.backend;
}
}
return defaultBackend;
SocketAddress match(final String fullPath) {
final int queryIndex = fullPath.indexOf('?');
final String path = queryIndex >= 0 ? fullPath.substring(0, queryIndex) : fullPath;
return routes.getOrDefault(path, defaultBackend);
}
}
@@ -7,8 +7,10 @@ package org.whispersystems.textsecuregcm.grpc.net;
import com.google.common.annotations.VisibleForTesting;
import io.netty.handler.ssl.ApplicationProtocolConfig;
import io.netty.handler.ssl.ApplicationProtocolNames;
import io.netty.handler.ssl.OpenSsl;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.SslProvider;
import io.netty.util.Mapping;
import java.io.FileInputStream;
import java.io.IOException;
@@ -49,25 +51,35 @@ public class SniMapper {
///
/// @param keyStorePath The path to the [KeyStore]
/// @param keyStorePassword The password for the keyStore
/// @param sslProvider The TLS implementation to use
/// @return A [Mapping] that maps domains to the corresponding [SslContext] containing the certificates for that
/// domain
public static Mapping<String, SslContext> buildSniMapping(final String keyStorePath, final String keyStorePassword)
throws IOException {
public static Mapping<String, SslContext> buildSniMapping(final String keyStorePath, final String keyStorePassword,
final SslProvider sslProvider) throws IOException {
try (final FileInputStream fis = new FileInputStream(keyStorePath)) {
return buildSniMapping(fis, keyStorePassword);
return buildSniMapping(fis, keyStorePassword, sslProvider);
}
}
@VisibleForTesting
static Mapping<String, SslContext> buildSniMapping(final InputStream keyStore, final String keyStorePassword)
throws IOException {
static Mapping<String, SslContext> buildSniMapping(final InputStream keyStore, final String keyStorePassword,
final SslProvider sslProvider) throws IOException {
if (sslProvider != SslProvider.JDK && sslProvider != SslProvider.OPENSSL) {
throw new IllegalArgumentException("Unsupported SSL provider: " + sslProvider);
}
if (sslProvider == SslProvider.OPENSSL) {
OpenSsl.ensureAvailability();
}
try {
final Map<String, KeyStore> domainKeyStores = partitionByDomain(keyStore, keyStorePassword.toCharArray());
final Map<String, SslContext> sslContextsByDomain = new HashMap<>();
for (final Map.Entry<String, KeyStore> entry : domainKeyStores.entrySet()) {
final KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(entry.getValue(), keyStorePassword.toCharArray());
sslContextsByDomain.put(entry.getKey(), buildSslContext(kmf));
sslContextsByDomain.put(entry.getKey(), buildSslContext(kmf, sslProvider));
}
// Netty expects the SNI mapping to always return an SslContext. Per RFC-6066 it's valid to continue the handshake
@@ -78,15 +90,23 @@ public class SniMapper {
.orElseThrow(() -> new IllegalArgumentException("Key store contained no certificates"))
.getValue();
logger.info("Loaded TLS contexts for domains: {}", sslContextsByDomain.keySet());
logger.info("Loaded {} TLS contexts for domains: {}", sslProvider, sslContextsByDomain.keySet());
return hostname -> sslContextsByDomain.getOrDefault(hostname, defaultSslContext);
} catch (NoSuchAlgorithmException | KeyStoreException | CertificateException | UnrecoverableKeyException e) {
throw new IOException("Failed to load keystore", e);
}
}
private static SslContext buildSslContext(final KeyManagerFactory kmf) throws SSLException {
return SslContextBuilder.forServer(kmf)
private static SslContext buildSslContext(final KeyManagerFactory kmf, final SslProvider sslProvider)
throws SSLException {
final SslContextBuilder sslContextBuilder = sslProvider == SslProvider.OPENSSL
// work around netty's OpenSSL provider not selecting Ed25519 certificates on its own
? SslContextBuilder.forServer(BoringSslServerKeyManager.wrap(kmf.getKeyManagers()))
: SslContextBuilder.forServer(kmf);
return sslContextBuilder
.sslProvider(sslProvider)
.applicationProtocolConfig(new ApplicationProtocolConfig(
ApplicationProtocolConfig.Protocol.ALPN,
ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE,
@@ -0,0 +1,58 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc.net;
import com.google.common.annotations.VisibleForTesting;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Tags;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.ssl.SslHandler;
import io.netty.handler.ssl.SslHandshakeCompletionEvent;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
/// Counts completed TLS handshakes, tagged with `success` and `exception`.
///
/// Must be added after the [io.netty.handler.ssl.SniHandler] or [SslHandler]; removes itself once the handshake completes.
@ChannelHandler.Sharable
public class TlsHandshakeMetricsHandler extends ChannelInboundHandlerAdapter {
@VisibleForTesting
static final String HANDSHAKE_COUNTER_NAME = MetricsUtil.name(TlsHandshakeMetricsHandler.class, "handshake");
@VisibleForTesting
static final String SUCCESS_TAG_NAME = "success";
@VisibleForTesting
static final String EXCEPTION_TAG_NAME = "exception";
private final MeterRegistry meterRegistry;
public TlsHandshakeMetricsHandler(final MeterRegistry meterRegistry) {
this.meterRegistry = meterRegistry;
}
@Override
public void userEventTriggered(final ChannelHandlerContext ctx, final Object evt) throws Exception {
if (evt instanceof SslHandshakeCompletionEvent handshakeCompletionEvent) {
final Tags tags;
if (handshakeCompletionEvent.isSuccess()) {
tags = Tags.of(SUCCESS_TAG_NAME, "true",
EXCEPTION_TAG_NAME, "none");
} else {
tags = Tags.of(SUCCESS_TAG_NAME, "false",
EXCEPTION_TAG_NAME, handshakeCompletionEvent.cause().getClass().getSimpleName());
}
meterRegistry.counter(HANDSHAKE_COUNTER_NAME, tags).increment();
ctx.pipeline().remove(this);
}
super.userEventTriggered(ctx, evt);
}
}
@@ -1,20 +0,0 @@
package org.whispersystems.textsecuregcm.limits;
import java.util.UUID;
public interface MessageDeliveryLoopMonitor {
/**
* Records an attempt to deliver a message with the given GUID to the given account/device pair and returns the number
* of consecutive attempts to deliver the same message and logs a warning if the message appears to be in a delivery
* loop. This method is intended to detect cases where a message remains at the head of a device's queue after
* repeated attempts to deliver the message, and so the given message GUID should be the first message of a "page"
* sent to clients.
*
* @param accountIdentifier the identifier of the destination account
* @param deviceId the destination device's ID within the given account
* @param messageGuid the GUID of the message
* @param userAgent the User-Agent header supplied by the caller
* @param context a human-readable string identifying the mechanism of message delivery (e.g. "rest" or "websocket")
*/
void recordDeliveryAttempt(UUID accountIdentifier, byte deviceId, UUID messageGuid, String userAgent, String context);
}
@@ -1,13 +0,0 @@
package org.whispersystems.textsecuregcm.limits;
import java.util.UUID;
public class NoopMessageDeliveryLoopMonitor implements MessageDeliveryLoopMonitor {
public NoopMessageDeliveryLoopMonitor() {
}
public void recordDeliveryAttempt(final UUID accountIdentifier, final byte deviceId, final UUID messageGuid, final String userAgent, final String context) {
}
}
@@ -65,7 +65,7 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
CREATE_DONATION_PERMIT("createDonationCredential", new RateLimiterConfig(30, Duration.ofHours(4), true)),
ONE_TIME_DONATION("oneTimeDonation", new RateLimiterConfig(5, Duration.ofMinutes(1), true)),
ADD_SUBSCRIPTION_PAYMENT_METHOD("addSubscriptionPaymentMethod", new RateLimiterConfig(10, Duration.ofMinutes(1), true)),
CHECK_TOTP("checkTotp", new RateLimiterConfig(5, Duration.ofSeconds(6), false))
CHECK_MFA("checkMfa", new RateLimiterConfig(50, Duration.ofHours(12), false))
;
private final String id;
@@ -252,7 +252,7 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
return forDescriptor(For.CREATE_DONATION_PERMIT);
}
public RateLimiter getCheckTotpLimiter() {
return forDescriptor(For.CHECK_TOTP);
public RateLimiter getCheckMfaLimiter() {
return forDescriptor(For.CHECK_MFA);
}
}
@@ -1,73 +0,0 @@
package org.whispersystems.textsecuregcm.limits;
import com.google.common.annotations.VisibleForTesting;
import io.lettuce.core.ScriptOutputType;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.time.Duration;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
public class RedisMessageDeliveryLoopMonitor implements MessageDeliveryLoopMonitor {
private final ClusterLuaScript getDeliveryAttemptsScript;
private static final Duration DELIVERY_ATTEMPTS_COUNTER_TTL = Duration.ofHours(1);
private static final int DELIVERY_LOOP_THRESHOLD = 5;
private static final Logger logger = LoggerFactory.getLogger(MessageDeliveryLoopMonitor.class);
public RedisMessageDeliveryLoopMonitor(final FaultTolerantRedisClusterClient rateLimitCluster) {
try {
getDeliveryAttemptsScript =
ClusterLuaScript.fromResource(rateLimitCluster, "lua/get_delivery_attempt_count.lua", ScriptOutputType.INTEGER);
} catch (final IOException e) {
throw new UncheckedIOException("Failed to load 'get delivery attempt count' script", e);
}
}
/**
* Records an attempt to deliver a message with the given GUID to the given account/device pair and returns the number
* of consecutive attempts to deliver the same message and logs a warning if the message appears to be in a delivery
* loop. This method is intended to detect cases where a message remains at the head of a device's queue after
* repeated attempts to deliver the message, and so the given message GUID should be the first message of a "page"
* sent to clients.
*
* @param accountIdentifier the identifier of the destination account
* @param deviceId the destination device's ID within the given account
* @param messageGuid the GUID of the message
* @param userAgent the User-Agent header supplied by the caller
* @param context a human-readable string identifying the mechanism of message delivery (e.g. "rest" or "websocket")
*/
public void recordDeliveryAttempt(final UUID accountIdentifier,
final byte deviceId,
final UUID messageGuid,
final String userAgent,
final String context) {
incrementDeliveryAttemptCount(accountIdentifier, deviceId, messageGuid)
.thenAccept(deliveryAttemptCount -> {
if (deliveryAttemptCount == DELIVERY_LOOP_THRESHOLD) {
logger.warn("Detected loop delivering message {} via {} to {}:{} ({})",
messageGuid, context, accountIdentifier, deviceId, userAgent);
}
});
}
@VisibleForTesting
CompletableFuture<Long> incrementDeliveryAttemptCount(final UUID accountIdentifier, final byte deviceId, final UUID messageGuid) {
final String firstMessageGuidKey = "firstMessageGuid::{" + accountIdentifier + ":" + deviceId + "}";
final String deliveryAttemptsKey = "firstMessageDeliveryAttempts::{" + accountIdentifier + ":" + deviceId + "}";
return getDeliveryAttemptsScript.executeAsync(
List.of(firstMessageGuidKey, deliveryAttemptsKey),
List.of(messageGuid.toString(), String.valueOf(DELIVERY_ATTEMPTS_COUNTER_TTL.toSeconds())))
.thenApply(result -> (long) result);
}
}
@@ -1,36 +0,0 @@
/*
* Copyright 2023 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.mappers;
import io.dropwizard.jersey.errors.ErrorMessage;
import io.grpc.StatusRuntimeException;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.ext.ExceptionMapper;
import jakarta.ws.rs.ext.Provider;
@Provider
public class GrpcStatusRuntimeExceptionMapper implements ExceptionMapper<StatusRuntimeException> {
@Override
public Response toResponse(final StatusRuntimeException exception) {
int httpCode = switch (exception.getStatus().getCode()) {
case OK -> 200;
case INVALID_ARGUMENT, FAILED_PRECONDITION, OUT_OF_RANGE -> 400;
case UNAUTHENTICATED -> 401;
case PERMISSION_DENIED -> 403;
case NOT_FOUND -> 404;
case ALREADY_EXISTS, ABORTED -> 409;
case CANCELLED -> 499;
case UNKNOWN, UNIMPLEMENTED, DEADLINE_EXCEEDED, RESOURCE_EXHAUSTED, INTERNAL, UNAVAILABLE, DATA_LOSS -> 500;
};
return Response.status(httpCode)
.entity(new ErrorMessage(httpCode, exception.getMessage()))
.type(MediaType.APPLICATION_JSON_TYPE)
.build();
}
}
@@ -0,0 +1,40 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.mappers;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.ext.ExceptionMapper;
import javax.annotation.Nullable;
import org.whispersystems.textsecuregcm.auth.MfaFailureException;
import org.whispersystems.textsecuregcm.auth.webauthn.WebAuthnAuthenticationParameters;
public class MfaFailureExceptionMapper implements ExceptionMapper<MfaFailureException> {
@Override
public Response toResponse(final MfaFailureException exception) {
return Response.status(441)
.entity(new MfaFailureResponse(
exception.getWebAuthnParameters() == null
? null
: new WebAuthnAuthenticationParameters(exception.getWebAuthnParameters().challenge(),
exception.getWebAuthnParameters().timeout().toSeconds(),
exception.getWebAuthnParameters().allowedCredentialIds()),
exception.hasTotpKey()))
.build();
}
@Schema(description = """
Information about the account's MFA status.
""")
public record MfaFailureResponse(
@Schema(description = "If the account has a WebAuthn credential, this field contains parameters for an authentication ceremony.")
@Nullable WebAuthnAuthenticationParameters webAuthnParameters,
@Schema(description = "Whether the account has a TOTP key configured")
boolean hasTotpKey) {
}
}
@@ -12,63 +12,62 @@ import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.ext.ExceptionMapper;
import java.util.Map;
import org.whispersystems.textsecuregcm.subscriptions.SubscriberIdCreationNotPermittedException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionChargeFailurePaymentRequiredException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionException;
import org.whispersystems.textsecuregcm.subscriptions.ChargeFailure;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionForbiddenException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidAmountException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidArgumentsException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionNotFoundException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentRequiredException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorConflictException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptAlreadyRedeemedException;
import org.whispersystems.textsecuregcm.purchases.ChargeFailure;
import org.whispersystems.textsecuregcm.purchases.PurchaseException;
import org.whispersystems.textsecuregcm.purchases.PurchaseForbiddenException;
import org.whispersystems.textsecuregcm.purchases.PurchaseInvalidAmountException;
import org.whispersystems.textsecuregcm.purchases.PurchaseInvalidArgumentsException;
import org.whispersystems.textsecuregcm.purchases.PurchaseNotFoundException;
import org.whispersystems.textsecuregcm.purchases.PurchasePaymentRequiredException;
import org.whispersystems.textsecuregcm.purchases.PurchaseProcessorConflictException;
import org.whispersystems.textsecuregcm.purchases.PurchaseProcessorException;
import org.whispersystems.textsecuregcm.purchases.PurchaseReceiptAlreadyRedeemedException;
import org.whispersystems.textsecuregcm.purchases.SubscriberIdCreationNotPermittedException;
public class SubscriptionExceptionMapper implements ExceptionMapper<SubscriptionException> {
public class PurchaseExceptionMapper implements ExceptionMapper<PurchaseException> {
@VisibleForTesting
public static final int PROCESSOR_ERROR_STATUS_CODE = 440;
public record ChargeFailureResponse(String processor, ChargeFailure chargeFailure) {}
@Override
public Response toResponse(final SubscriptionException exception) {
public Response toResponse(final PurchaseException exception) {
// Some exceptions have specific error body formats
if (exception instanceof SubscriptionInvalidAmountException e) {
if (exception instanceof PurchaseInvalidAmountException e) {
return Response
.status(Response.Status.BAD_REQUEST)
.entity(Map.of("error", e.getErrorCode()))
.type(MediaType.APPLICATION_JSON_TYPE)
.build();
}
if (exception instanceof SubscriptionProcessorException e) {
if (exception instanceof PurchaseProcessorException e) {
return Response.status(PROCESSOR_ERROR_STATUS_CODE)
.entity(new ChargeFailureResponse(e.getProcessor().name(), e.getChargeFailure()))
.type(MediaType.APPLICATION_JSON_TYPE)
.build();
}
if (exception instanceof SubscriptionChargeFailurePaymentRequiredException e) {
if (exception instanceof PurchasePaymentRequiredException e && e.getChargeFailure().isPresent()) {
return Response
.status(Response.Status.PAYMENT_REQUIRED)
.entity(new ChargeFailureResponse(e.getProcessor().name(), e.getChargeFailure()))
.entity(new ChargeFailureResponse(e.getProcessor().name(), e.getChargeFailure().get()))
.type(MediaType.APPLICATION_JSON_TYPE)
.build();
}
// Otherwise, we'll return a generic error message WebApplicationException, with a detailed error if one is provided
final Response.Status status = (switch (exception) {
case SubscriptionNotFoundException _ -> Response.Status.NOT_FOUND;
case SubscriptionForbiddenException _ -> Response.Status.FORBIDDEN;
case SubscriptionInvalidArgumentsException _ -> Response.Status.BAD_REQUEST;
case SubscriptionProcessorConflictException _ -> Response.Status.CONFLICT;
case SubscriptionPaymentRequiredException _ -> Response.Status.PAYMENT_REQUIRED;
case SubscriptionReceiptAlreadyRedeemedException _ -> Response.Status.CONFLICT;
case PurchaseNotFoundException _ -> Response.Status.NOT_FOUND;
case PurchaseForbiddenException _ -> Response.Status.FORBIDDEN;
case PurchaseInvalidArgumentsException _ -> Response.Status.BAD_REQUEST;
case PurchaseProcessorConflictException _ -> Response.Status.CONFLICT;
case PurchasePaymentRequiredException _ -> Response.Status.PAYMENT_REQUIRED;
case PurchaseReceiptAlreadyRedeemedException _ -> Response.Status.CONFLICT;
case SubscriberIdCreationNotPermittedException _ -> Response.Status.UNAUTHORIZED;
default -> Response.Status.INTERNAL_SERVER_ERROR;
});
// If the SubscriptionException came with suitable error message, include that in the response body. Otherwise,
// If the PurchaseException came with suitable error message, include that in the response body. Otherwise,
// don't provide any message to the WebApplicationException constructor so the response includes the default
// HTTP error message for the status.
final WebApplicationException wae = exception.errorDetail()
@@ -1,3 +1,8 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.mappers;
import jakarta.ws.rs.core.Response;
@@ -2,7 +2,7 @@
* Copyright 2025 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.subscriptions;
package org.whispersystems.textsecuregcm.purchases;
import com.apple.itunes.storekit.client.APIError;
import com.apple.itunes.storekit.client.APIException;
@@ -126,15 +126,15 @@ public class AppleAppStoreClient {
}
public StatusResponse getAllSubscriptions(final String originalTransactionId, final Tags errorTags)
throws SubscriptionNotFoundException, SubscriptionInvalidArgumentsException, RateLimitExceededException {
throws PurchaseNotFoundException, PurchaseInvalidArgumentsException, RateLimitExceededException {
try {
return lookupByTransactionId(originalTransactionId, errorTags,
(env, txId) -> client(env).getAllSubscriptionStatuses(txId, EMPTY_STATUSES));
} catch (APIException e) {
switch (e.getApiError()) {
case TRANSACTION_ID_NOT_FOUND, ORIGINAL_TRANSACTION_ID_NOT_FOUND, ACCOUNT_NOT_FOUND -> throw new SubscriptionNotFoundException();
case TRANSACTION_ID_NOT_FOUND, ORIGINAL_TRANSACTION_ID_NOT_FOUND, ACCOUNT_NOT_FOUND -> throw new PurchaseNotFoundException();
case RATE_LIMIT_EXCEEDED -> throw new RateLimitExceededException(null);
case INVALID_ORIGINAL_TRANSACTION_ID -> throw new SubscriptionInvalidArgumentsException(e.getApiErrorMessage());
case INVALID_ORIGINAL_TRANSACTION_ID -> throw new PurchaseInvalidArgumentsException(e.getApiErrorMessage());
case null, default -> throw new UncheckedIOException(new IOException(e));
}
} catch (IOException e) {
@@ -1,4 +1,4 @@
package org.whispersystems.textsecuregcm.subscriptions;
package org.whispersystems.textsecuregcm.purchases;
import com.apple.itunes.storekit.model.JWSRenewalInfoDecodedPayload;
import com.apple.itunes.storekit.model.JWSTransactionDecodedPayload;
@@ -3,7 +3,7 @@
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.subscriptions;
package org.whispersystems.textsecuregcm.purchases;
import com.apple.itunes.storekit.model.AutoRenewStatus;
import com.apple.itunes.storekit.model.JWSTransactionDecodedPayload;
@@ -14,7 +14,6 @@ import com.apple.itunes.storekit.model.Type;
import io.micrometer.core.instrument.Tags;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
@@ -67,16 +66,16 @@ public class AppleAppStoreManager implements SubscriptionPaymentProcessor, OneTi
* @param originalTransactionId The originalTransactionId associated with the subscription
* @return the subscription level of the valid transaction.
* @throws RateLimitExceededException If rate-limited
* @throws SubscriptionNotFoundException If the provided originalTransactionId was not found
* @throws SubscriptionPaymentRequiredException If the originalTransactionId exists but is in a state that does not
* @throws PurchaseNotFoundException If the provided originalTransactionId was not found
* @throws PurchasePaymentRequiredException If the originalTransactionId exists but is in a state that does not
* grant the user an entitlement
* @throws SubscriptionInvalidArgumentsException If the transaction is valid but does not contain a subscription
* @throws PurchaseInvalidArgumentsException If the transaction is valid but does not contain a subscription
*/
public Long validateTransaction(final String originalTransactionId)
throws SubscriptionInvalidArgumentsException, RateLimitExceededException, SubscriptionNotFoundException, SubscriptionPaymentRequiredException {
throws PurchaseInvalidArgumentsException, RateLimitExceededException, PurchaseNotFoundException, PurchasePaymentRequiredException {
final AppleAppStoreDecodedTransaction tx = lookupAndValidateTransaction(originalTransactionId, Tags.of(LOOKUP_TYPE_TAG, "validate"));
if (!isSubscriptionActive(tx)) {
throw new SubscriptionPaymentRequiredException();
throw new PurchasePaymentRequiredException(getProvider());
}
return getLevel(tx.transaction()).getValue();
}
@@ -91,20 +90,20 @@ public class AppleAppStoreManager implements SubscriptionPaymentProcessor, OneTi
*
* @param originalTransactionId The originalTransactionId associated with the subscription
* @throws RateLimitExceededException If rate-limited
* @throws SubscriptionInvalidArgumentsException If the transaction is valid but does not contain a subscription, or
* @throws PurchaseInvalidArgumentsException If the transaction is valid but does not contain a subscription, or
* the transaction has not already been cancelled with storekit
*/
@Override
public void cancelAllActiveSubscriptions(String originalTransactionId)
throws SubscriptionInvalidArgumentsException, RateLimitExceededException {
throws PurchaseInvalidArgumentsException, RateLimitExceededException {
try {
final AppleAppStoreDecodedTransaction tx = lookupSubscription(originalTransactionId, Tags.of(LOOKUP_TYPE_TAG, "cancel"));
if (tx.signedTransaction().getStatus() != Status.EXPIRED &&
tx.signedTransaction().getStatus() != Status.REVOKED &&
tx.renewalInfo().getAutoRenewStatus() != AutoRenewStatus.OFF) {
throw new SubscriptionInvalidArgumentsException("must cancel subscription with storekit before deleting");
throw new PurchaseInvalidArgumentsException("must cancel subscription with storekit before deleting");
}
} catch (SubscriptionNotFoundException _) {
} catch (PurchaseNotFoundException _) {
// If the subscription is not found there is no need to do anything, so we can squash it
}
// The subscription will not auto-renew, so we can stop tracking it
@@ -112,7 +111,7 @@ public class AppleAppStoreManager implements SubscriptionPaymentProcessor, OneTi
@Override
public SubscriptionInformation getSubscriptionInformation(final String originalTransactionId)
throws RateLimitExceededException, SubscriptionNotFoundException {
throws RateLimitExceededException, PurchaseNotFoundException {
final AppleAppStoreDecodedTransaction tx = lookupSubscription(originalTransactionId, Tags.of(LOOKUP_TYPE_TAG, "info"));
final SubscriptionStatus status = switch (tx.signedTransaction().getStatus()) {
case ACTIVE -> SubscriptionStatus.ACTIVE;
@@ -138,10 +137,10 @@ public class AppleAppStoreManager implements SubscriptionPaymentProcessor, OneTi
@Override
public ReceiptItem getReceiptItem(String originalTransactionId)
throws RateLimitExceededException, SubscriptionNotFoundException, SubscriptionPaymentRequiredException {
throws RateLimitExceededException, PurchaseNotFoundException, PurchasePaymentRequiredException {
final AppleAppStoreDecodedTransaction tx = lookupSubscription(originalTransactionId, Tags.of(LOOKUP_TYPE_TAG, "receipt"));
if (!isSubscriptionActive(tx)) {
throw new SubscriptionPaymentRequiredException();
throw new PurchasePaymentRequiredException(getProvider());
}
// A new transactionId might be generated if you restore a subscription on a new device. webOrderLineItemId is
@@ -155,48 +154,46 @@ public class AppleAppStoreManager implements SubscriptionPaymentProcessor, OneTi
}
@Override
public Optional<PaymentDetails> claimOneTimePurchase(final String transactionId)
throws RateLimitExceededException, SubscriptionInvalidArgumentsException {
public PaymentDetails claimOneTimePurchase(final String transactionId)
throws RateLimitExceededException, PurchaseInvalidArgumentsException, PurchaseNotFoundException, PurchasePaymentRequiredException {
final Optional<JWSTransactionDecodedPayload> maybeTransaction =
appleAppStoreClient.lookupTransaction(transactionId, Tags.of(LOOKUP_TYPE_TAG, "one_time"));
if (maybeTransaction.isEmpty()) {
return Optional.empty();
throw new PurchaseNotFoundException();
}
final JWSTransactionDecodedPayload transaction = maybeTransaction.get();
if (transaction.getType() != Type.CONSUMABLE) {
throw new SubscriptionInvalidArgumentsException("transaction is not a consumable one-time purchase");
throw new PurchaseInvalidArgumentsException("transaction is not a consumable one-time purchase");
}
final PaymentStatus paymentStatus = transaction.getRevocationDate() == null
? PaymentStatus.SUCCEEDED
: PaymentStatus.FAILED;
return Optional.of(new PaymentDetails(
if (transaction.getRevocationDate() != null) {
throw new PurchasePaymentRequiredException(getProvider());
}
return new PaymentDetails(
Objects.requireNonNull(transaction.getTransactionId()),
getLevel(transaction),
paymentStatus,
transaction.getPurchaseDate() != null ? Instant.ofEpochMilli(transaction.getPurchaseDate()) : null,
null));
Instant.ofEpochMilli(transaction.getPurchaseDate()));
}
private AppleAppStoreDecodedTransaction lookupSubscription(final String originalTransactionId, final Tags tags)
throws RateLimitExceededException, SubscriptionNotFoundException {
throws RateLimitExceededException, PurchaseNotFoundException {
try {
return lookupAndValidateTransaction(originalTransactionId, tags);
} catch (SubscriptionInvalidArgumentsException e) {
} catch (PurchaseInvalidArgumentsException e) {
// Shouldn't happen because we previously validated this transactionId before storing it
throw new UncheckedIOException(new IOException(e));
}
}
private AppleAppStoreDecodedTransaction lookupAndValidateTransaction(final String originalTransactionId, final Tags errorTags)
throws SubscriptionInvalidArgumentsException, RateLimitExceededException, SubscriptionNotFoundException {
throws PurchaseInvalidArgumentsException, RateLimitExceededException, PurchaseNotFoundException {
final StatusResponse statuses = appleAppStoreClient.getAllSubscriptions(originalTransactionId, errorTags);
final SubscriptionGroupIdentifierItem item = statuses.getData().stream()
.filter(s -> subscriptionGroupId.equals(s.getSubscriptionGroupIdentifier())).findFirst()
.orElseThrow(() -> new SubscriptionInvalidArgumentsException("transaction did not contain a backup subscription", null));
.orElseThrow(() -> new PurchaseInvalidArgumentsException("transaction did not contain a backup subscription", null));
final List<AppleAppStoreDecodedTransaction> txs = item.getLastTransactions().stream()
.map(txItem -> appleAppStoreClient.verifySubscription(statuses.getEnvironment(), txItem))
@@ -208,7 +205,7 @@ public class AppleAppStoreManager implements SubscriptionPaymentProcessor, OneTi
// Get All Subscriptions only requires that the transaction be some transaction associated with the
// subscription. This is too flexible, since we'd like to key on the originalTransactionId in the
// SubscriptionManager.
throw new SubscriptionInvalidArgumentsException("transactionId did not include a paid subscription or the provided transactionId was not an originalTransactionId", null);
throw new PurchaseInvalidArgumentsException("transactionId did not include a paid subscription or the provided transactionId was not an originalTransactionId", null);
}
if (txs.size() > 1) {
@@ -219,10 +216,10 @@ public class AppleAppStoreManager implements SubscriptionPaymentProcessor, OneTi
}
private SubscriptionPrice getSubscriptionPrice(final AppleAppStoreDecodedTransaction tx) {
final BigDecimal amount = new BigDecimal(tx.transaction().getPrice()).scaleByPowerOfTen(-3);
return new SubscriptionPrice(
tx.transaction().getCurrency().toUpperCase(Locale.ROOT),
SubscriptionCurrencyUtil.convertConfiguredAmountToApiAmount(tx.transaction().getCurrency(), amount));
SubscriptionCurrencyUtil.convertAppleMoneyToMinorUnits(
tx.transaction().getCurrency(), tx.transaction().getPrice()));
}
private ReceiptLevel getLevel(final JWSTransactionDecodedPayload tx) {
@@ -3,7 +3,7 @@
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.subscriptions;
package org.whispersystems.textsecuregcm.purchases;
import java.util.List;
import java.util.Locale;
@@ -3,7 +3,7 @@
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.subscriptions;
package org.whispersystems.textsecuregcm.purchases;
public enum BankTransferType {
SEPA_DEBIT
@@ -3,7 +3,7 @@
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.subscriptions;
package org.whispersystems.textsecuregcm.purchases;
import com.apollographql.apollo3.api.ApolloResponse;
import com.apollographql.apollo3.api.Operation;
@@ -3,7 +3,7 @@
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.subscriptions;
package org.whispersystems.textsecuregcm.purchases;
import com.braintree.graphql.clientoperation.ChargePayPalOneTimePaymentMutation;
import com.braintree.graphql.clientoperation.CreatePayPalBillingAgreementMutation;
@@ -48,6 +48,7 @@ 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.subscriptions.DonationsPubsub;
import org.whispersystems.textsecuregcm.util.ExecutorUtil;
import org.whispersystems.textsecuregcm.util.GoogleApiUtil;
import org.whispersystems.textsecuregcm.util.SystemMapper;
@@ -131,14 +132,10 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
}
@Override
public Optional<PaymentDetails> claimOneTimePurchase(final String paymentId) {
public PaymentDetails claimOneTimePurchase(final String paymentId)
throws PurchaseNotFoundException, PurchaseReceiptRequestedForOpenPaymentException, PurchasePaymentRequiredException {
try {
final Transaction transaction = braintreeGateway.transaction().find(paymentId);
ChargeFailure chargeFailure = null;
if (!getPaymentStatus(transaction.getStatus()).equals(PaymentStatus.SUCCEEDED)) {
chargeFailure = createChargeFailure(transaction);
}
final ReceiptLevel level = Optional.ofNullable(transaction.getCustomFields())
.map(m -> m.get(BraintreeGraphqlClient.LEVEL_METADATA_NAME))
.map(Long::parseLong)
@@ -146,14 +143,13 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
.orElseThrow(() -> new IllegalStateException(
"failed to retrieve level metadata from payment intent %s".formatted(paymentId)));
return Optional.of(new PaymentDetails(transaction.getGraphQLId(),
level,
getPaymentStatus(transaction.getStatus()),
transaction.getCreatedAt().toInstant(),
chargeFailure));
return switch (getPaymentStatus(transaction.getStatus())) {
case SUCCEEDED -> new PaymentDetails(transaction.getGraphQLId(), level, transaction.getCreatedAt().toInstant());
case PROCESSING -> throw new PurchaseReceiptRequestedForOpenPaymentException();
case UNKNOWN, FAILED -> throw new PurchasePaymentRequiredException(getProvider(), createChargeFailure(transaction));
};
} catch (final NotFoundException e) {
return Optional.empty();
throw new PurchaseNotFoundException();
}
}
@@ -168,7 +164,7 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
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 {
throws PurchaseProcessorException, IOException {
final TokenizePayPalOneTimePaymentMutation.TokenizePayPalOneTimePayment response = braintreeGraphqlClient.tokenizePayPalOneTimePayment(
payerId, paymentId, paymentToken);
final ChargePayPalOneTimePaymentMutation.ChargePaymentMethod chargeResponse = braintreeGraphqlClient.chargeOneTimePayment(
@@ -214,7 +210,7 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
switch (unsuccessfulTx.getProcessorResponseCode()) {
case GENERIC_DECLINED_PROCESSOR_CODE, PAYPAL_FUNDING_INSTRUMENT_DECLINED_PROCESSOR_CODE ->
throw new SubscriptionProcessorException(getProvider(), createChargeFailure(unsuccessfulTx));
throw new PurchaseProcessorException(getProvider(), createChargeFailure(unsuccessfulTx));
default -> {
logger.info("PayPal charge unexpectedly failed: {}", unsuccessfulTx.getProcessorResponseCode());
@@ -306,12 +302,8 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
};
}
private BigDecimal convertApiAmountToBraintreeAmount(final String currency, final long amount) {
return switch (currency.toLowerCase(Locale.ROOT)) {
// JPY is the only supported zero-decimal currency
case "jpy" -> BigDecimal.valueOf(amount);
default -> BigDecimal.valueOf(amount).scaleByPowerOfTen(-2);
};
private BigDecimal convertApiAmountToBraintreeAmount(final String currency, final long amountMinorUnits) {
return SubscriptionCurrencyUtil.convertMinorToPrimaryUnits(currency, amountMinorUnits);
}
public record PayPalOneTimePaymentApprovalDetails(String approvalUrl, String paymentId) {
@@ -368,11 +360,11 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
@Override
public SubscriptionId createSubscription(final String customerId, final String planId, final long level,
final long lastSubscriptionCreatedAt)
throws SubscriptionProcessorConflictException, SubscriptionProcessorException {
throws PurchaseProcessorConflictException, PurchaseProcessorException {
final com.braintreegateway.PaymentMethod paymentMethod = getDefaultPaymentMethod(customerId);
if (paymentMethod == null) {
throw new SubscriptionProcessorConflictException();
throw new PurchaseProcessorConflictException();
}
final Optional<Subscription> maybeExistingSubscription = paymentMethod.getSubscriptions().stream()
@@ -406,7 +398,7 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
throw Optional
.ofNullable(result.getTarget())
.flatMap(subscription -> subscription.getTransactions().stream().findFirst())
.map(transaction -> new SubscriptionProcessorException(getProvider(),
.map(transaction -> new PurchaseProcessorException(getProvider(),
createChargeFailure(transaction)))
.orElseThrow(() -> new BraintreeException(result.getMessage()));
}
@@ -422,7 +414,7 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
@Override
public CustomerAwareSubscriptionPaymentProcessor.SubscriptionId updateSubscription(final Object subscriptionObj,
final String planId, final long level,
final String idempotencyKey) throws SubscriptionProcessorConflictException, SubscriptionProcessorException {
final String idempotencyKey) throws PurchaseProcessorConflictException, PurchaseProcessorException {
if (!(subscriptionObj instanceof final Subscription subscription)) {
throw new IllegalArgumentException("invalid subscription object: " + subscriptionObj.getClass().getName());
@@ -434,7 +426,7 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
endSubscription(subscription);
final Transaction transaction = getLatestTransactionForSubscription(subscription)
.orElseThrow(SubscriptionProcessorConflictException::new);
.orElseThrow(PurchaseProcessorConflictException::new);
final Customer customer = transaction.getCustomer();
@@ -480,7 +472,7 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
return new SubscriptionInformation(
new SubscriptionPrice(plan.getCurrencyIsoCode().toUpperCase(Locale.ROOT),
SubscriptionCurrencyUtil.convertBraintreeAmountToApiAmount(plan.getCurrencyIsoCode(), plan.getPrice())),
SubscriptionCurrencyUtil.convertBraintreeAmountToMinorUnits(plan.getCurrencyIsoCode(), plan.getPrice())),
level,
anchor,
endOfCurrentPeriod,
@@ -587,17 +579,17 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
@Override
public ReceiptItem getReceiptItem(final String subscriptionId)
throws SubscriptionReceiptRequestedForOpenPaymentException, SubscriptionChargeFailurePaymentRequiredException {
throws PurchaseReceiptRequestedForOpenPaymentException, PurchasePaymentRequiredException {
final Subscription subscription = getSubscription(getSubscription(subscriptionId));
final Transaction transaction = getLatestTransactionForSubscription(subscription)
.orElseThrow(SubscriptionReceiptRequestedForOpenPaymentException::new);
.orElseThrow(PurchaseReceiptRequestedForOpenPaymentException::new);
if (!getPaymentStatus(transaction.getStatus()).equals(PaymentStatus.SUCCEEDED)) {
final SubscriptionStatus subscriptionStatus = getSubscriptionStatus(subscription.getStatus(), true);
if (subscriptionStatus.equals(SubscriptionStatus.ACTIVE) || subscriptionStatus.equals(
SubscriptionStatus.PAST_DUE)) {
throw new SubscriptionReceiptRequestedForOpenPaymentException();
throw new PurchaseReceiptRequestedForOpenPaymentException();
}
throw new SubscriptionChargeFailurePaymentRequiredException(getProvider(), createChargeFailure(transaction));
throw new PurchasePaymentRequiredException(getProvider(), createChargeFailure(transaction));
}
final Instant paidAt = transaction.getSubscriptionDetails().getBillingPeriodStartDate().toInstant();
@@ -3,7 +3,7 @@
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.subscriptions;
package org.whispersystems.textsecuregcm.purchases;
public record BraintreePlanMetadata(long level) {
@@ -3,7 +3,7 @@
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.subscriptions;
package org.whispersystems.textsecuregcm.purchases;
import io.swagger.v3.oas.annotations.ExternalDocumentation;
import io.swagger.v3.oas.annotations.media.Schema;
@@ -1,4 +1,4 @@
package org.whispersystems.textsecuregcm.subscriptions;
package org.whispersystems.textsecuregcm.purchases;
import io.swagger.v3.oas.annotations.media.Schema;
@@ -3,7 +3,7 @@
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.subscriptions;
package org.whispersystems.textsecuregcm.purchases;
import java.io.IOException;
import java.util.Set;
@@ -41,12 +41,12 @@ public interface CustomerAwareSubscriptionPaymentProcessor extends SubscriptionP
* @param paymentMethodToken a processor-specific token previously acquired at
* {@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
* @throws PurchaseInvalidArgumentsException If the paymentMethodToken is invalid or the payment method has not
* 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, IOException;
@Nullable String currentSubscriptionId) throws PurchaseInvalidArgumentsException, IOException;
Object getSubscription(String subscriptionId);
@@ -58,13 +58,13 @@ public interface CustomerAwareSubscriptionPaymentProcessor extends SubscriptionP
* @param level The level of the subscription
* @param lastSubscriptionCreatedAt The timestamp of the last successfully created subscription
* @return A subscription identifier
* @throws SubscriptionProcessorException If there was a failure processing the charge
* @throws SubscriptionPaymentRequiresActionException If the payment requires additional steps before charging
* @throws SubscriptionInvalidIdempotencyKeyException If the idempotency key was reused on a modified request
* @throws SubscriptionProcessorConflictException If there was no payment method on the customer
* @throws PurchaseProcessorException If there was a failure processing the charge
* @throws PurchasePaymentRequiresActionException If the payment requires additional steps before charging
* @throws PurchaseInvalidIdempotencyKeyException If the idempotency key was reused on a modified request
* @throws PurchaseProcessorConflictException If there was no payment method on the customer
*/
SubscriptionId createSubscription(String customerId, String templateId, long level, long lastSubscriptionCreatedAt)
throws SubscriptionProcessorException, SubscriptionPaymentRequiresActionException, SubscriptionInvalidIdempotencyKeyException, SubscriptionProcessorConflictException;
throws PurchaseProcessorException, PurchasePaymentRequiresActionException, PurchaseInvalidIdempotencyKeyException, PurchaseProcessorConflictException;
/**
* Update an existing subscription on a customer
@@ -74,15 +74,15 @@ public interface CustomerAwareSubscriptionPaymentProcessor extends SubscriptionP
* @param level The target level of the subscription
* @param idempotencyKey An idempotency key to prevent retries of successful requests
* @return A subscription identifier
* @throws SubscriptionProcessorException If there was a failure processing the charge
* @throws SubscriptionInvalidIdempotencyKeyException If the idempotency key was reused on a modified request
* @throws SubscriptionInvalidLevelException If the level transition is not permitted
* @throws SubscriptionPaymentRequiresActionException If the payment requires additional steps before charging
* @throws SubscriptionProcessorConflictException If there was no payment method on the customer
* @throws PurchaseProcessorException If there was a failure processing the charge
* @throws PurchaseInvalidIdempotencyKeyException If the idempotency key was reused on a modified request
* @throws PurchaseInvalidLevelException If the level transition is not permitted
* @throws PurchasePaymentRequiresActionException If the payment requires additional steps before charging
* @throws PurchaseProcessorConflictException If there was no payment method on the customer
*/
SubscriptionId updateSubscription(Object subscription, String templateId, long level, String idempotencyKey)
throws SubscriptionInvalidIdempotencyKeyException, SubscriptionInvalidLevelException,
SubscriptionPaymentRequiresActionException, SubscriptionProcessorException, SubscriptionProcessorConflictException;
throws PurchaseInvalidIdempotencyKeyException, PurchaseInvalidLevelException,
PurchasePaymentRequiresActionException, PurchaseProcessorException, PurchaseProcessorConflictException;
/**
* @param subscription
@@ -3,7 +3,7 @@
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.subscriptions;
package org.whispersystems.textsecuregcm.purchases;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
@@ -132,7 +132,7 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor, O
*
*/
public void acknowledgePurchase()
throws RateLimitExceededException, SubscriptionNotFoundException {
throws RateLimitExceededException, PurchaseNotFoundException {
if (!requiresAck) {
// We've already acknowledged this purchase on a previous attempt, nothing to do
return;
@@ -153,12 +153,12 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor, O
* @param purchaseToken The play store billing purchaseToken that represents a subscription purchase
* @return A {@link ValidatedToken} that can be acknowledged
* @throws RateLimitExceededException If rate-limited by play-billing
* @throws SubscriptionNotFoundException If the provided purchaseToken was not found in play-billing
* @throws SubscriptionPaymentRequiredException If the purchaseToken exists but is in a state that does not grant the
* @throws PurchaseNotFoundException If the provided purchaseToken was not found in play-billing
* @throws PurchasePaymentRequiredException If the purchaseToken exists but is in a state that does not grant the
* user an entitlement
*/
public ValidatedToken validateToken(String purchaseToken)
throws RateLimitExceededException, SubscriptionNotFoundException, SubscriptionPaymentRequiredException {
throws RateLimitExceededException, PurchaseNotFoundException, PurchasePaymentRequiredException {
final SubscriptionPurchaseV2 subscription = lookupSubscription(purchaseToken);
final SubscriptionState state = SubscriptionState
.fromString(subscription.getSubscriptionState())
@@ -173,7 +173,7 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor, O
if (state != SubscriptionState.ACTIVE
&& state != SubscriptionState.IN_GRACE_PERIOD
&& state != SubscriptionState.CANCELED) {
throw new SubscriptionPaymentRequiredException(
throw new PurchasePaymentRequiredException(getProvider(),
"Cannot acknowledge purchase for subscription in state " + subscription.getSubscriptionState());
}
@@ -212,14 +212,14 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor, O
executeTokenOperation(pub ->
pub.purchases().subscriptions().cancel(packageName, purchase.getProductId(), purchaseToken));
} catch (SubscriptionNotFoundException e) {
} catch (PurchaseNotFoundException e) {
// If the subscription is not found there is no need to do anything, so we can squash it
}
}
@Override
public SubscriptionInformation getSubscriptionInformation(final String purchaseToken)
throws RateLimitExceededException, SubscriptionNotFoundException {
throws RateLimitExceededException, PurchaseNotFoundException {
final SubscriptionPurchaseV2 subscription = lookupSubscription(purchaseToken);
final SubscriptionPrice price = getSubscriptionPrice(subscription);
@@ -270,12 +270,12 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor, O
final Money price = lineItem.getAutoRenewingPlan().getRecurringPrice();
return new SubscriptionPrice(
price.getCurrencyCode().toUpperCase(Locale.ROOT),
SubscriptionCurrencyUtil.convertGoogleMoneyToApiAmount(price));
SubscriptionCurrencyUtil.convertGoogleMoneyToMinorUnits(price));
}
@Override
public ReceiptItem getReceiptItem(String purchaseToken)
throws RateLimitExceededException, SubscriptionNotFoundException, SubscriptionPaymentRequiredException {
throws RateLimitExceededException, PurchaseNotFoundException, PurchasePaymentRequiredException {
final SubscriptionPurchaseV2 subscription = lookupSubscription(purchaseToken);
Metrics.counter(GET_RECEIPT_COUNTER_NAME, subscriptionTags(subscription)).increment();
@@ -288,7 +288,7 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor, O
// We don't need to check any state at this point, just whether the subscription is currently valid. If the
// subscription is in a grace period, the expiration time will be dynamically extended, see
// https://developer.android.com/google/play/billing/lifecycle/subscriptions#grace-period
throw new SubscriptionPaymentRequiredException();
throw new PurchasePaymentRequiredException(getProvider());
}
if (requiresAcknowledgement(subscription)) {
@@ -318,55 +318,49 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor, O
/// will fail, it just means we've told the play store that the purchase is complete. If the client fails after the
/// acknowledgement, they can just retry with no issue.
@Override
public Optional<PaymentDetails> claimOneTimePurchase(final String purchaseToken)
throws IOException, RateLimitExceededException, SubscriptionInvalidArgumentsException {
try {
final ProductPurchaseV2 productPurchaseV2 = executeTokenOperation(
public PaymentDetails claimOneTimePurchase(final String purchaseToken)
throws IOException, RateLimitExceededException, PurchaseInvalidArgumentsException, PurchaseNotFoundException, PurchasePaymentRequiredException, PurchaseReceiptRequestedForOpenPaymentException {
final ProductPurchaseV2 productPurchaseV2 = executeTokenOperation(
publisher -> publisher.purchases().productsv2().getproductpurchasev2(packageName, purchaseToken));
final PaymentStatus paymentStatus = Optional
.ofNullable(productPurchaseV2.getPurchaseStateContext())
.map(PurchaseStateContext::getPurchaseState)
.flatMap(PurchaseState::fromString)
.map(purchaseState -> switch (purchaseState) {
case PENDING -> PaymentStatus.PROCESSING;
case CANCELLED -> PaymentStatus.FAILED;
case PURCHASED -> PaymentStatus.SUCCEEDED;
case PURCHASE_STATE_UNSPECIFIED -> PaymentStatus.UNKNOWN;
})
.orElse(PaymentStatus.UNKNOWN);
final PurchaseState purchaseState = Optional
.ofNullable(productPurchaseV2.getPurchaseStateContext())
.map(PurchaseStateContext::getPurchaseState)
.flatMap(PurchaseState::fromString)
.orElse(PurchaseState.PURCHASE_STATE_UNSPECIFIED);
final ProductLineItem lineItem = getLineItem(productPurchaseV2);
final String productId = lineItem.getProductId();
final ReceiptLevel level = productIdToLevel(productId);
Instant purchaseTime = null;
if (paymentStatus == PaymentStatus.SUCCEEDED) {
purchaseTime = parseTimestamp(productPurchaseV2.getPurchaseCompletionTime())
.orElseThrow(() -> new IOException("Invalid purchase time"));
final ConsumptionState consumptionState = Optional
.ofNullable(lineItem.getProductOfferDetails())
.map(ProductOfferDetails::getConsumptionState)
.flatMap(ConsumptionState::fromString)
.orElseThrow(() -> new IllegalStateException("Purchase did not contain a consumption state: " + lineItem.getProductOfferDetails()));
if (consumptionState == ConsumptionState.YET_TO_BE_CONSUMED) {
// Mark this token as consumed
executeTokenOperation(publisher ->
publisher.purchases().products().consume(packageName, productId, purchaseToken));
}
switch (purchaseState) {
case PURCHASED -> {
}
return Optional.of(new PaymentDetails(purchaseToken, level, paymentStatus, purchaseTime, null));
} catch (SubscriptionNotFoundException e) {
return Optional.empty();
case PENDING -> throw new PurchaseReceiptRequestedForOpenPaymentException();
case CANCELLED, PURCHASE_STATE_UNSPECIFIED -> throw new PurchasePaymentRequiredException(getProvider());
}
final ProductLineItem lineItem = getLineItem(productPurchaseV2);
final String productId = lineItem.getProductId();
final ReceiptLevel level = productIdToLevel(productId);
final Instant purchaseTime = parseTimestamp(productPurchaseV2.getPurchaseCompletionTime())
.orElseThrow(() -> new IOException("Invalid purchase time"));
final ConsumptionState consumptionState = Optional
.ofNullable(lineItem.getProductOfferDetails())
.map(ProductOfferDetails::getConsumptionState)
.flatMap(ConsumptionState::fromString)
.orElseThrow(() -> new IllegalStateException(
"Purchase did not contain a consumption state: " + lineItem.getProductOfferDetails()));
if (consumptionState == ConsumptionState.YET_TO_BE_CONSUMED) {
// Mark this token as consumed
executeTokenOperation(publisher ->
publisher.purchases().products().consume(packageName, productId, purchaseToken));
}
return new PaymentDetails(purchaseToken, level, purchaseTime);
}
private ProductLineItem getLineItem(final ProductPurchaseV2 purchase) throws SubscriptionInvalidArgumentsException {
private ProductLineItem getLineItem(final ProductPurchaseV2 purchase) throws PurchaseInvalidArgumentsException {
final List<ProductLineItem> lineItems = purchase.getProductLineItem();
if (lineItems == null || lineItems.isEmpty()) {
throw new SubscriptionInvalidArgumentsException("purchase has no line items");
throw new PurchaseInvalidArgumentsException("purchase has no line items");
}
if (lineItems.size() > 1) {
logger.warn("{} line items found for purchase {}, expected 1", lineItems.size(), purchase.getOrderId());
@@ -380,21 +374,21 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor, O
}
/**
* Asynchronously execute a synchronous API call on a purchaseToken, mapping expected errors to the appropriate
* {@link SubscriptionException}
* Execute a synchronous API call on a purchaseToken, mapping expected errors to the appropriate
* {@link PurchaseException}
*
* @param apiCall An API call that operates on a purchaseToken
* @param <R> The result of the API call
* @return A stage that completes with the result of the API call
*/
private <R> R executeTokenOperation(final ApiCall<R> apiCall)
throws RateLimitExceededException, SubscriptionNotFoundException {
throws RateLimitExceededException, PurchaseNotFoundException {
try {
return apiCall.req(androidPublisher).execute();
} catch (HttpResponseException e) {
if (e.getStatusCode() == Response.Status.NOT_FOUND.getStatusCode()
|| e.getStatusCode() == Response.Status.GONE.getStatusCode()) {
throw new SubscriptionNotFoundException();
throw new PurchaseNotFoundException();
}
if (e.getStatusCode() == Response.Status.TOO_MANY_REQUESTS.getStatusCode()) {
throw new RateLimitExceededException(null);
@@ -418,7 +412,7 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor, O
}
private SubscriptionPurchaseV2 lookupSubscription(final String purchaseToken)
throws RateLimitExceededException, SubscriptionNotFoundException {
throws RateLimitExceededException, PurchaseNotFoundException {
return executeTokenOperation(publisher -> publisher.purchases().subscriptionsv2().get(packageName, purchaseToken));
}
Loaded 100 of 314 files, more files were not shown because too many files have changed in this diff. Show more