Compare commits

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


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

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

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

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

Signed-off-by: dependabot[bot] <support@github.com>
2026-08-03 10:35:00 -04:00
Ravi Khadiwala 1e2a873753 Remove test subscriber-id 2026-08-03 10:01:12 -04:00
Jon Chambers e60daa75a8 Don't assume presence of phone numbers for spam reports 2026-08-03 09:39:44 -04:00
Ameya Lokare a3d01a94d4 Update metrics for spam reports from numberless accounts 2026-08-03 09:16:59 -04:00
Katherine Yen 0117ed1a0b Register KeyTransparencyGrpcService 2026-08-03 09:16:37 -04:00
Jonathan Klabunde Tomer f3194cf45b Update to the latest version of the spam filter 2026-07-29 16:15:34 -07:00
ravi-signal 29c5f8b218 Do not allow accounts without phone numbers to perform PNI key operations 2026-07-29 16:13:16 -07:00
Jonathan Klabunde Tomer d7447b111d Add support for pessimistic locking of phone-number-less accounts 2026-07-29 15:44:31 -07:00
Jon Chambers 850286dbfc Don't assume presence of phone numbers when regenerating secondary tables 2026-07-29 15:42:13 -07:00
ravi-signal f55a0af55e Add deprecation annotation to getIdentityKey 2026-07-29 15:42:02 -07:00
Jon Chambers 2f1843d5d2 Don't assume presence of phone numbers when checking for prohibited payment regions 2026-07-29 15:41:51 -07:00
Jon Chambers 78e7e992da Add utility methods for getting country/region codes for accounts that may not have phone numbers 2026-07-29 15:41:40 -07:00
ameya-signal ef2d25704e Don't allow or set registration lock on accounts with no phone number 2026-07-29 15:41:22 -07:00
Jon Chambers fc44fb1235 Fix a comparison between incompatible types 2026-07-29 17:09:16 -04:00
Jon Chambers 20dc6390b9 Don't set phone number identity keys in tests unless a phone number is also present 2026-07-29 15:06:37 -04:00
Jon Chambers 262f7de742 Update to the latest version of the spam filter 2026-07-29 14:46:40 -04:00
Jon Chambers fad055aa44 Reject attempts to change phone numbers if the account doesn't have a number in the first place 2026-07-29 14:44:58 -04:00
Jon Chambers 9426d0bd9e Revert "Reject attempts to change phone numbers if the account doesn't have a number in the first place"
This reverts commit 87cdc6f84a8323c4dce6a85e3f8337cf8e1d94cd.
2026-07-29 14:44:58 -04:00
Jon Chambers e1d2b3aac7 Reject attempts to change phone numbers if the account doesn't have a number in the first place 2026-07-29 14:44:58 -04:00
Jonathan Klabunde Tomer d415a3365a add optional getter for PNI identity key 2026-07-29 14:42:43 -04:00
Jon Chambers 8fc63dd4d6 Don't generate "includes e164" delivery certificates for accounts without phone numbers 2026-07-29 14:42:04 -04:00
Jon Chambers ac4d61978b Don't assume presence of phone numbers when generating account identity responses 2026-07-29 14:41:26 -04:00
Jon Chambers 79935ea22a Don't assume presence of phone numbers in integration tests 2026-07-29 14:41:26 -04:00
Jon Chambers 478a4bda7d Don't assume presence of phone numbers in account data reports 2026-07-29 14:40:08 -04:00
Jon Chambers 70d0bda779 Make "discoverable by phone number" contingent upon having a phone number in the first place 2026-07-29 14:40:08 -04:00
Ameya Lokare 4f4284d1cc Don't assume destination account phone number exists when updating spam report metrics 2026-07-29 14:39:37 -04:00
Ameya Lokare c12206ace0 Only update parsed time zone metric if the phone number was present 2026-07-29 14:38:39 -04:00
Ameya Lokare d46818e465 Default to preferred server-local time if account has no phone number 2026-07-29 14:38:39 -04:00
Jon Chambers 4440022796 Update to the latest version of the spam filter 2026-07-28 17:45:43 -04:00
Jon Chambers f1d2ce2814 Add methods for getting phone numbers and phone number identifiers that do not assume presence 2026-07-28 17:30:06 -04:00
Jon Chambers 1072d9d39b Convert Account documentation to Markdown 2026-07-28 17:30:06 -04:00
Jon Chambers 20cf3d7429 Rename Account#getUUID() to Account#getAccountIdentifier() 2026-07-28 17:30:06 -04:00
Jon Chambers 7b472afbcb Remove an ancient test 2026-07-28 17:30:06 -04:00
Katherine Yen c6619c7488 Adjust metric name in TrimOversizedFoundationDbMessageQueuesCommand 2026-07-28 17:29:39 -04:00
Jon Chambers 751b4b6ecc Detect and measure FoundationDB message consumer conflicts 2026-07-28 17:28:58 -04:00
Ravi Khadiwala 888b746294 Remove badges from product configuration 2026-07-28 16:20:05 -05:00
Ravi Khadiwala 8e9253181c Add badges to remote config 2026-07-28 16:20:05 -05:00
Ravi Khadiwala 257dd76b68 Implement grpc remote config 2026-07-28 16:13:16 -05:00
Ravi Khadiwala 76ca81d9f1 Sink remote config logic down a layer 2026-07-28 16:13:16 -05:00
Jon Chambers 0eeb6605db Use a programmatically-generated keystore in OmnibusH2ServerTest 2026-07-24 09:26:06 -04:00
Jon Chambers ac8d5f81bf Use a programmatically-generated keystore in SniMapperTest 2026-07-24 09:26:06 -04:00
Jon Chambers 3447345d02 Update to the latest version of the spam filter 2026-07-23 16:49:40 -04:00
Jon Chambers ab0235a574 Update to Ubuntu 26.04 as a base image 2026-07-23 16:49:05 -04:00
Jon Chambers 38c5a292fb Update test container images 2026-07-23 16:49:05 -04:00
Jon Chambers 35663956b5 Update deployment base image and specify full image rather than just the SHA256 2026-07-23 16:49:05 -04:00
Jon Chambers d5a0c63de8 Update Maven Wrapper 2026-07-23 16:49:05 -04:00
ravi-signal 2f0a081d2e Handle duplicated tokens in /v2/svr/auth/check 2026-07-23 15:48:33 -05:00
Chris Eager adfab44ed6 Opt out of anonymous Stripe telemetry_id 2026-07-23 16:48:09 -04:00
Katherine Yen 24cea1926a Add timeout, retries, and priority to trimQueue operation 2026-07-23 16:47:56 -04:00
Ravi Khadiwala 242a5f6a78 Allow ignoring the return value of status asserts 2026-07-23 16:47:40 -04:00
Katherine Yen 45dab47ea8 Disable flaky FoundationDbMessageStoreTest#trimQueue 2026-07-22 15:15:55 -04:00
Katherine Yen 0587a08017 Disable flaky FoundationDbMessageStoreTest#estimateQueueSizeAndSplitPoints 2026-07-22 15:11:38 -04:00
Ravi Khadiwala 02d6138848 Add marker for unexpected error logs 2026-07-22 14:35:17 -04:00
Jon Chambers 07444bffb4 Limit message range size based on outstanding demand 2026-07-22 14:32:26 -04:00
Katherine 4f8ca893f0 Add a crawler to trim oversized queues in FoundationDB 2026-07-22 11:43:22 -04:00
Ravi Khadiwala 7bb94bc99e Drop username_hash from ConfirmUsernameResponse 2026-07-22 10:34:44 -05:00
Ravi Khadiwala f6ca5e55a5 Make timeout for storage usage queries configurable 2026-07-22 10:34:23 -05:00
Andrew 4e2bca886e Specify AccountIdentifiers contract more tightly 2026-07-22 10:33:55 -05:00
ameya-signal 088037b412 Fix watch leak when watch is set after subscription is disposed 2026-07-21 10:26:38 -05:00
ameya-signal 548c688df2 Add counter for FoundationDB watch operations 2026-07-21 10:26:29 -05:00
Chris Eager 8b103030ed Update to the latest version of the spam filter 2026-07-21 10:26:18 -05:00
Ravi Khadiwala 6a8bf7f78e Temporarily disable flaky test 2026-07-17 13:44:14 -05:00
Jonathan Klabunde Tomer 98ba337787 remove primary-device requirement on three accounts grpc endpoints 2026-07-17 10:54:41 -07:00
Ameya Lokare 4410da5fb2 Use Mono.fromFuture(() ->) instead of Mono.fromFuture() to defer
evaluation
2026-07-17 10:53:44 -07:00
Ameya Lokare 607c839dda Add a utility method that returns a cancellation-safe result from
`database.runAsync`
2026-07-17 10:53:44 -07:00
Chris Eager bb3ad8d116 Add FoundationDB timeouts and retries 2026-07-17 12:47:11 -05:00
Chris Eager 2dcd43318e Update permissions in workflows/test.yml 2026-07-17 12:43:07 -05:00
Ravi Khadiwala b255c37978 Hoist user-agent tag out of publisher in copyMedia 2026-07-17 12:42:27 -05:00
Ravi Khadiwala ea411e2f1e Change ConfigureUnidentifiedAccessRequest to a oneof 2026-07-17 12:41:03 -05:00
Ravi Khadiwala 70f83326ef Make log stripping more consistent 2026-07-17 12:40:47 -05:00
Ravi Khadiwala 90a5ad589b Fix close code check in test 2026-07-15 11:35:57 -05:00
Ravi Khadiwala 749d9c4f92 Require donation permit headers 2026-07-15 11:35:46 -05:00
ravi-signal 3d45706a35 Add GetCapabilities rpcs 2026-07-15 11:35:20 -05:00
Ravi Khadiwala ed90c1c15c Drop unversioned profiles from grpc service 2026-07-14 16:06:31 -05:00
Ravi Khadiwala 5147fe57f2 Update stripe SDK to 33.1.0 2026-07-14 16:05:51 -05:00
Jon Chambers 1d366c98a9 Mirror demand signals and establish presence when mirroring reads to FoundationDB 2026-07-14 08:56:57 -07:00
Jon Chambers 8c19171284 Retire AcknowledgementMirroringMessageStream 2026-07-14 08:56:57 -07:00
Katherine 47a461ef1f Update description for status code 400 on KT endpoints 2026-07-14 11:55:43 -04:00
Jon Chambers a959656c96 Terminate the publisher if presence renewal fails 2026-07-14 11:10:51 -04:00
Jon Chambers ab08a3a0e4 Address some synchronization holes with presence renewal 2026-07-11 10:16:31 -04:00
Jon Chambers 688d3a2212 Log exceptions when fetching end-of-queue keys 2026-07-10 14:29:44 -07:00
Jon Chambers 25fdc95843 Update to the latest version of the spam filter 2026-07-10 14:13:30 -04:00
Ameya Lokare d3c93dd1a2 Port AccountControllerV2 to gRPC 2026-07-10 13:56:49 -04:00
Jonathan Klabunde Tomer 54ea7a288c test with smaller number of accounts 2026-07-10 13:56:18 -04:00
Jonathan Klabunde Tomer e2cb484743 async fetch messages in test 2026-07-10 13:56:18 -04:00
Jonathan Klabunde Tomer 45f176d5a8 re-enable FoundationDbMessageStoreTest#deleteExpiredMessages 2026-07-10 13:56:18 -04:00
Jon Chambers 450945a9cc Perform end-of-queue-key processing outside of a transaction retry loop 2026-07-10 13:55:37 -04:00
Ravi Khadiwala 253671c206 Improve assertion failure message in GracefulShutdownIntegrationTest 2026-07-10 13:54:33 -04:00
Jon Chambers cdd461b8f4 Simplify FoundationDbMessageStream construction 2026-07-10 10:47:03 -04:00
Jon Chambers d9a54a0d42 Don't parse messages inside of a retryable transaction block 2026-07-10 10:47:03 -04:00
Jon Chambers 3f3aa89b0f Retire batched acknowledgement system in favor of point deletions 2026-07-10 10:47:03 -04:00
Ravi Khadiwala 55fa60dd4e Setting apns push tokens should always update the timestamp 2026-07-10 10:46:41 -04:00
Ravi Khadiwala b539df8e48 Add some missing authentication specifiers 2026-07-10 10:46:28 -04:00
Ravi Khadiwala 0cd0716eb5 Register ProductConfigurationGrpcService in WhisperServerService 2026-07-10 10:46:28 -04:00
Jon Chambers 6386aada73 Add an "active requests" gauge for WebSocket requests 2026-07-10 10:46:16 -04:00
Jon Chambers 5c44398bb5 Add an "active requests" counter to the gRPC metrics interceptor 2026-07-10 10:46:16 -04:00
Jon Chambers 54736bb117 Update logback to 1.5.38 2026-07-10 10:46:07 -04:00
ravi-signal aed8e60789 Create a dedicated graceful shutdown test 2026-07-09 13:52:21 -05:00
Jon Chambers 5fa50e8ad7 Increment a counter for timeouts rather than logging the full exception 2026-07-09 09:49:32 -04:00
Jon Chambers fdaba751bd Update logback to 1.5.33 2026-07-09 09:48:48 -04:00
Ravi Khadiwala 0eebb58956 Remove unused badgeIdsEnabledForAll configuration 2026-07-09 09:48:18 -04:00
Ravi Khadiwala 6bb85d77a7 Add badge/backup entitlement RPC 2026-07-09 09:48:18 -04:00
Ravi Khadiwala 9e3844ee5a Add issue hook to integration test workflow 2026-07-07 12:30:08 -05:00
Jonathan Klabunde Tomer 7ee8e349e2 add command to periodically clear expired messages from foundationdb 2026-07-06 14:17:12 -04:00
Katherine 4d9e252697 Support group send endorsement authentication for versioned profile fetches on ProfileAnonymous gRPC service 2026-07-06 14:10:07 -04:00
Jon Chambers 222e5a033b Add an experiment to partially mirror reads from FoundationDB 2026-07-06 14:01:24 -04:00
Jon Chambers 8c6fbbfa65 Revert "Switch back to AcknowledgementMirroringMessageStream"
This reverts commit 5174550ef3.
2026-07-02 15:52:45 -04:00
Jon Chambers b0b2122d8c Establish presence asynchronously rather than blocking onSubscribe 2026-07-02 14:47:02 -04:00
Jon Chambers d7711e235b Revert "Simplify demand mirroring"
This reverts commit d0fcb9ab54.
2026-07-02 12:38:11 -04:00
Jon Chambers 5174550ef3 Switch back to AcknowledgementMirroringMessageStream 2026-07-02 12:09:29 -04:00
Jon Chambers d0fcb9ab54 Simplify demand mirroring 2026-07-02 12:08:21 -04:00
Jon Chambers 375150a8c3 Dispose of the mirrored FoundationDB stream when the Redis/DynamoDB stream terminates for any reason 2026-07-01 18:18:30 -04:00
Jon Chambers cb28614721 Guard against null presence values 2026-07-01 18:17:48 -04:00
Ameya Lokare f02caf78cd Make OneTimeDonationController sync 2026-07-01 18:17:16 -04:00
Jon Chambers 8fd72549fb Temporarily switch back to point deletes 2026-07-01 14:34:05 -04:00
dependabot[bot] 1e4774820f Bump actions/checkout from 6.0.3 to 7.0.0
Bumps [actions/checkout](https://github.com/actions/checkout) from 6.0.3 to 7.0.0.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/df4cb1c069e1874edd31b4311f1884172cec0e10...9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0)

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

Signed-off-by: dependabot[bot] <support@github.com>
2026-07-01 14:32:54 -04:00
dependabot[bot] 48cdad7e57 Bump the minor-actions-dependencies group with 2 updates
Bumps the minor-actions-dependencies group with 2 updates: [actions/setup-java](https://github.com/actions/setup-java) and [aws-actions/configure-aws-credentials](https://github.com/aws-actions/configure-aws-credentials).


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

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

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

Signed-off-by: dependabot[bot] <support@github.com>
2026-07-01 14:16:24 -04:00
Chris Eager 392bab5b60 Consolidate and clarify ZK configuration 2026-07-01 14:14:20 -04:00
ravi-signal 6b67604fe7 Move donation/backup configuration to own service
Also, add an etag so configuration can be sent only if it changes
2026-07-01 12:19:00 -05:00
Ravi Khadiwala 67a03f81b9 Add username_link_handle to AccountIdentifiers message 2026-07-01 12:16:12 -05:00
Ravi Khadiwala 90b75cbf22 Add a test for our Any typeUrls 2026-07-01 12:15:43 -05:00
Ameya Lokare 4dede4acad Keep track of number of emitted messages so we don't fetch messages on
every onRequest()
2026-06-30 16:38:51 -07:00
Jon Chambers d225ba3618 Align FoundationDB default page size with mirroring page size 2026-06-30 17:14:06 -04:00
Jon Chambers 8790514b8a Establish presence when fetching messages from FoundationDB 2026-06-30 11:36:22 -04:00
Jon Chambers fa4d3c7ca9 Avoid automatic, unbounded requests on subscription 2026-06-30 11:36:22 -04:00
Jon Chambers 1f0b2ad92d Reapply "Mirror message reads/acknowledgements via FoundationDbMessageStream"
This reverts commit 28aefe0ebe.
2026-06-30 11:36:22 -04:00
Chris Eager feb00c6ba6 Add avatars to profiles gRPC 2026-06-29 13:15:07 -05:00
Ravi Khadiwala f588390bdb Handle ACCOUNT_NOT_FOUND errors in AppleAppStoreClient 2026-06-29 13:11:00 -05:00
Jon Chambers 355b320c92 Don't attempt to send empty message bundles when changing numbers 2026-06-26 15:51:28 -04:00
Jon Chambers 40fb9c4cee Fix a bogus assertion for "change number" message-sending 2026-06-26 15:51:28 -04:00
Ravi Khadiwala aa5ac70ad3 Select lifecycle-manager based on environment variable (like in FoundationDbClusterExtension) 2026-06-25 17:42:04 -04:00
Jon Chambers 2abf55e395 Don't trigger state transitions inside retryable transactions 2026-06-25 17:41:33 -04:00
Jon Chambers 808bb16103 Add basic read/acknowledgement counters to RedisDynamoDbMessageStream 2026-06-25 17:41:11 -04:00
Ameya Lokare 4743abcfbd Port OneTimeDonationController to gRPC 2026-06-25 17:40:49 -04:00
Katherine 1b09529ece Use V2 key transparency query RPCs 2026-06-24 15:02:34 -07:00
Chris Eager 0c3c390a0b Update Donation-Permit header parameter documentation 2026-06-24 14:51:46 -07:00
Chris Eager ca4ee141d8 Disable a flaky test 2026-06-24 13:18:07 -05:00
Jonathan Klabunde TomerandJon Chambers 671a6e1d7c address review comments
Co-authored-by: Jon Chambers <63609320+jon-signal@users.noreply.github.com>
2026-06-24 12:14:52 -05:00
Jonathan Klabunde Tomer f4e16676c9 add FoundationDbMessageStore api to clear messages before a given time 2026-06-24 12:14:52 -05:00
Chris Eager 78b3147491 Implement donation permit spending 2026-06-24 12:13:21 -05:00
Ravi Khadiwala 8b617b64f8 Add metric for requested attachment upload size 2026-06-24 12:11:57 -05:00
Jon Chambers 28aefe0ebe Revert "Mirror message reads/acknowledgements via FoundationDbMessageStream"
This reverts commit 4e52317e26.
2026-06-24 13:01:13 -04:00
Jon Chambers 4e52317e26 Mirror message reads/acknowledgements via FoundationDbMessageStream 2026-06-24 10:18:15 -04:00
Ravi Khadiwala 99465c1f41 Update to the latest version of the spam filter 2026-06-23 13:13:49 -05:00
Chris Eager 041c29bfa8 Update foundationdb to 7.3.68 2026-06-23 13:11:05 -05:00
Chris Eager 8e5ad7f52e Remove unused mocking in CredentialsGrpcServiceTest 2026-06-23 13:11:05 -05:00
Jon Chambers ca5d203f1c Make RegistrationServiceClient blocking 2026-06-23 13:09:12 -05:00
ravi-signal 9a9b15ee0a Add per-element constraint validation 2026-06-23 13:08:39 -05:00
ravi-signal 503941ec6a Add a load-shedding GOAWAY 2026-06-23 13:07:49 -05:00
Ravi Khadiwala ac720595e6 Add header to disable messages on authenticated websocket 2026-06-18 15:28:41 -05:00
Jonathan Klabunde Tomer 8deb5a803a foundationdb "versionstamp clock" 2026-06-18 13:27:59 -07:00
Jon Chambers 45f96cd702 Delete messages from FoundationDB asynchronously 2026-06-18 14:06:26 -04:00
Chris Eager 4a3275ad63 Add POST /v1/donation/permit 2026-06-18 13:06:18 -05:00
Ameya Lokare 911feceacb Handle "no sender available" error code from registration service 2026-06-18 09:03:02 -04:00
Jon Chambers fe0956c8f7 Don't add Dropwizard metrics to shared registries 2026-06-18 09:02:33 -04:00
Jon Chambers 60002a8a0f Port StickerController to gRPC 2026-06-18 08:51:00 -04:00
Ameya Lokare 1876b71d39 Port SubscriptionController to gRPC 2026-06-18 08:27:38 -04:00
Jon Chambers 3cfe8b9f6c Mirror message writes/deletions to FoundationDB 2026-06-18 08:27:03 -04:00
Jon Chambers 691a4162e1 Update to the latest version of the spam filter 2026-06-18 08:25:07 -04:00
Ravi Khadiwala 9505e7b1a1 Fix incorrect mockito matcher in BackupManagerTest 2026-06-17 12:43:34 -05:00
Jon Chambers 569f4f31e8 Update to the latest version of the spam filter 2026-06-17 08:46:11 -04:00
Ravi Khadiwala 06519ce9d1 Use uint64 for backups.proto object length 2026-06-17 08:45:43 -04:00
Jon Chambers 024fa9ce5f Move "active epoch" configuration from dynamic to static configuration 2026-06-17 08:35:07 -04:00
Jon Chambers 7c9e3d029b Remove an unused availableProcessors variable 2026-06-17 08:33:29 -04:00
Jon Chambers cc6ef53f91 Retire unused methods in MessagesManager 2026-06-17 08:33:29 -04:00
Ravi Khadiwala 4c0f454209 Add a generic STREAM_CLOSED status 2026-06-17 08:32:47 -04:00
Chris Eager 9c393972e9 Update to the latest version of the spam filter 2026-06-16 20:02:56 -05:00
Jon Chambers 31c1bb8940 Support multiple "configuration epochs" of the FoundationDB message store 2026-06-16 09:06:18 -04:00
Jon Chambers c3b2b43813 Port CallLinkController to gRPC 2026-06-16 09:02:24 -04:00
Jon Chambers 19f2574799 Update to the latest version of the spam filter 2026-06-16 09:02:03 -04:00
Ravi Khadiwala adb5b6a4ea Check message type before deserializing source serviceId 2026-06-11 13:16:20 -05:00
Ravi Khadiwala e79eb9904d Update to the latest version of the spam filter 2026-06-11 11:36:07 -05:00
ravi-signal fcdc0bbd74 Generate grpc api documentation 2026-06-11 11:35:20 -05:00
Ravi Khadiwala b6317a1b43 Add gRPC message retrieval 2026-06-11 11:34:07 -05:00
Ravi Khadiwala 329d229ac7 Revert "Remove unused ClosableEpoch"
This reverts commit d0e022c23b.
2026-06-11 11:34:07 -05:00
Ravi Khadiwala c50b4e52b0 Move some message retrieval metrics to MessageMetrics 2026-06-11 11:34:07 -05:00
Ravi Khadiwala 660011017d Throw checked exceptions from CaptchaChecker 2026-06-11 11:33:56 -04:00
Jon Chambers 82e3c16fba Port CallRoutingControllerV2 to gRPC 2026-06-11 11:31:57 -04:00
Jon Chambers ae9f43bb3c Don't include IOException messages in gRPC error responses 2026-06-11 11:31:57 -04:00
Jonathan Klabunde Tomer ab4b5a1298 ignore disconnects from already-disconnected message listeners 2026-06-11 11:31:24 -04:00
Katherine Yen 97a77ce23e Remove duplicate constructor for invalid argument gRPC exception with no details 2026-06-11 11:30:56 -04:00
Ameya Lokare 50ef5272f7 Fix handling write conflicts when redeeming subscription receipt
credentials
2026-06-11 11:30:16 -04:00
Chris Eager d6c7c5e7bf Use ProfileHelper.isPaymentAddressUpdateForbidden for both REST and gRPC 2026-06-11 10:29:14 -05:00
Ameya Lokare 32befd7c9a Port DonationController to gRPC 2026-06-11 11:28:23 -04:00
Jon Chambers dd93833324 Avoid retaining messages while waiting for acknowledgement 2026-06-11 11:14:02 -04:00
Jon Chambers 5d624b463a Acknowledge messages by ID rather than by passing the whole message around 2026-06-11 11:14:02 -04:00
Jon Chambers f524d9fb25 Retire string-based service identifiers/UUIDs in Envelope entities 2026-06-10 14:28:30 -04:00
Jon Chambers 4a9302033a Remove the additional callback executor from FoundationDbMessageStore 2026-06-10 13:12:40 -04:00
Jon Chambers 292f03586b Add an IP-based rate limiter for adding payment methods for subscriptions 2026-06-10 11:29:51 -04:00
Jon Chambers 8257859834 Add an IP-based rate limiter for creating one-time donations 2026-06-10 11:29:51 -04:00
Katherine Yen 2c5210e7c4 Fix a flaky test by waiting for the async insert to complete before attempting to remove the message 2026-06-08 17:42:35 -04:00
Katherine b93da1323b Discard ephemeral messages from the finite publisher in FoundationDB 2026-06-08 17:23:21 -04:00
Ravi Khadiwala d9c39cc12b Update messages integration test to use websocket 2026-06-08 16:01:23 -05:00
Ravi Khadiwala d69027ce5c Remove REST message retrieval entities 2026-06-08 16:01:23 -05:00
Jon Chambers a4381a2617 Parse FoundationDB envelopes at load time and add GUIDs later 2026-06-08 16:56:53 -04:00
Jon Chambers 3e4ad32fce Introduce AcknowledgedMessageBuffer 2026-06-08 16:56:15 -04:00
Jon Chambers c3a48fd08b Port CertificateController to gRPC 2026-06-08 16:55:53 -04:00
Ravi Khadiwala 7471a21fee Update to the latest version of the spam filter 2026-06-05 12:41:26 -05:00
Ameya Lokare 13a5458344 Port ChallengeController to gRPC 2026-06-05 12:32:46 -05:00
Ravi Khadiwala 704b53aa79 Close responses in WhisperServerServiceTest 2026-06-05 12:30:09 -05:00
Jon Chambers 5774ffdeab Wait for test message insertion to complete before attempting to read 2026-06-05 10:22:34 -04:00
Ravi Khadiwala fac7dbbeb7 Add a timeout to WhisperServerServiceTest 2026-06-04 18:06:27 -05:00
Ravi Khadiwala 29b1ec694b Update to the latest version of the spam filter 2026-06-03 11:39:07 -05:00
dependabot[bot] 181004f031 Bump the minor-actions-dependencies group with 2 updates
Bumps the minor-actions-dependencies group with 2 updates: [actions/checkout](https://github.com/actions/checkout) and [aws-actions/configure-aws-credentials](https://github.com/aws-actions/configure-aws-credentials).


Updates `actions/checkout` from 6.0.2 to 6.0.3
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/de0fac2e4500dabe0009e67214ff5f5447ce83dd...df4cb1c069e1874edd31b4311f1884172cec0e10)

Updates `aws-actions/configure-aws-credentials` from 6.1.0 to 6.2.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/ec61189d14ec14c8efccab744f656cffd0e33f37...e7f100cf4c008499ea8adda475de1042d6975c7b)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-version: 6.0.3
  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.2.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-06-03 12:03:36 -04:00
Jon Chambers bb18a84808 Add an experiment to recompress messages just before delivery 2026-06-03 12:00:34 -04:00
Jon Chambers 27fb4f227d Revert "Add an experiment to skip envelope expansion"
This reverts commit 0d32ca120d.
2026-06-03 12:00:34 -04:00
Ravi Khadiwala 324c4eafb6 Retire REST message retrieval
Remove `GET /v1/messages`
2026-06-03 10:59:41 -05:00
Jon Chambers 0d32ca120d Add an experiment to skip envelope expansion 2026-06-02 16:01:06 -04:00
Katherine 69a954e889 Discard stale ephemeral messages in FoundationDB 2026-06-02 16:00:25 -04:00
Jon Chambers d57ed3133c Avoid spurious padding 2026-06-01 16:51:56 -05:00
Jon Chambers 4a9f44b88c Use an all-zero IV and the parameter block as the first plaintext block 2026-06-01 16:51:56 -05:00
Jon Chambers 264897656b Actually make the "copy to S3" command available 2026-05-29 10:03:47 -04:00
Chris Eager f8f60c92ff Use getByPhoneNumberIdentifier in getAccountsForChangeNumber 2026-05-29 10:00:17 -04:00
Jon Chambers e6c24c373d Update to the latest version of the spam filter 2026-05-29 09:59:17 -04:00
Jon Chambers ab34e7c10e Update to the latest version of the spam filter 2026-05-28 16:50:48 -04:00
Jon Chambers c32d15617b Add a command for copying files from the open internet to S3 2026-05-28 16:17:37 -04:00
Jon Chambers 11136868ac Update to the latest version of the spam filter 2026-05-28 10:37:58 -04:00
Katherine 81167a8ae5 Add a device capability for username change sync messages 2026-05-27 15:34:01 -04:00
ameya-signal a6bf60e4cb Fix flaky test FoundationDbMessageStoreTest#getMessagesPublishMoreAfterQueueEmpty 2026-05-27 15:33:07 -04:00
Jon Chambers 15698aee46 Wire PaymentsGrpcService up as an authenticated service 2026-05-27 15:32:49 -04:00
Katherine b2942a8dbd Limit the number of unacknowledged FoundationDB messages 2026-05-27 15:32:27 -04:00
Jon Chambers f10cc26144 Include optional call ID hashes in call quality survey responses 2026-05-27 15:31:53 -04:00
Katherine Yen d4581931ff Update to the latest version of the spam filter 2026-05-27 15:31:32 -04:00
Chris Eager 41b953f5a1 Add rotation_id to ZK Credential key 2026-05-27 14:23:20 -05:00
Jon Chambers 3f1df3032f Update to the latest version of the spam filter 2026-05-26 09:17:49 -04:00
Jon Chambers cb6123125f Only send verification code push notifications to primary devices 2026-05-26 09:17:32 -04:00
Jon Chambers 9f6d80cb39 Update to the latest version of the spam filter 2026-05-21 14:33:55 -04:00
Jon Chambers da439e7144 Guard against NullPointerExceptions when getting details from a GoogleJsonResponseException 2026-05-21 13:10:44 -04:00
Jonathan Klabunde Tomer 22656396dc serialize account current profile version as base64 2026-05-21 13:10:03 -04:00
Chris Eager 90b280d6a0 Convert Subscriptions to sync DynamoDB client 2026-05-21 13:09:31 -04:00
Chris Eager 482a1b7bb5 Convert RedeemedReceiptsManager to sync DynamoDB client 2026-05-21 13:09:31 -04:00
Chris Eager fea4300d7d Convert RegistrationRecoveryPasswords to sync DynamoDB client 2026-05-21 13:08:49 -04:00
Chris Eager 66b0ed16d1 Convert VerificationSessions to sync DynamoDB client 2026-05-21 13:08:49 -04:00
Ameya Lokare defbc1c853 Implement FoundationDbMessageStream#acknowledgeMessage 2026-05-21 13:07:50 -04:00
Jon Chambers 68a5e4e8ee Update to the latest version of the spam filter 2026-05-20 12:49:36 -04:00
Jon Chambers f83efce4d4 Add a phased enrollment mechanism for verification code push notifications 2026-05-20 12:20:00 -04:00
Jon Chambers 0945e953f2 Send a "verification code requested" push notification to existing accounts 2026-05-20 12:20:00 -04:00
Jon Chambers 51f6e57bbd Allow differing TTLs by notification type 2026-05-20 12:20:00 -04:00
Jon Chambers 539a84d0d0 Allow PushNotification data to be any type of object 2026-05-20 12:20:00 -04:00
Ravi Khadiwala 848c457bbe Use micrometer's netty metrics 2026-05-20 12:18:27 -04:00
Ravi Khadiwala c5ae3963b5 Fix ProxyProtocolHandlerTest resource leak
Also replace AbstractLeakDetectionTest with netty LeakPresenceExtension
2026-05-19 16:33:00 -05:00
ravi-signal 771fecd396 Fix flaky backpressure test 2026-05-19 15:59:35 -05:00
Chris Eager b9a24fedea Move handleAccountCreated() call to outside re-registration 2026-05-19 13:07:44 -05:00
Ravi Khadiwala 9d3b6ebb4a Update to the latest version of the spam filter 2026-05-19 11:30:51 -05:00
Chris Eager 2cf91af5d9 Remove obsolete client public keys table from config 2026-05-19 11:19:19 -05:00
Chris Eager d0e022c23b Remove unused ClosableEpoch 2026-05-19 11:19:19 -05:00
Chris Eager 460e5cb499 Use DynamoDB for change number waiting periods
DynamoDB is even simpler for integration tests.
2026-05-19 11:18:10 -05:00
Jonathan Klabunde Tomer 23305e4460 add a counter for profile version format 2026-05-19 09:15:20 -07:00
Jonathan Klabunde Tomer 06d96a04df store account profile current version as byte array, not hex 2026-05-19 09:15:20 -07:00
Jon Chambers 022f2b874d Bypass circuit breakers, timeouts when clearing Redis instances before test runs 2026-05-19 11:32:09 -04:00
Ravi Khadiwala b09a9b8f39 Add netty dependencies from omnibus 2026-05-18 11:55:59 -05:00
Chris Eager 4e72422cfd Add netty dependencies to POM 2026-05-18 11:53:21 -05:00
Chris Eager d41c73917f Update integration test with post-registration change number waiting period 2026-05-18 11:49:56 -05:00
Chris Eager dd29ee1f27 Refactor Change Number waiting period to dedicated manager
This simplifies integration testing.
2026-05-18 11:49:56 -05:00
Chris Eager 9dc6e049f4 Remove obsolete remote config response 2026-05-18 11:31:20 -05:00
Jon Chambers 7fe3d4a30f Retire oversized message warning metrics 2026-05-18 11:29:54 -05:00
Jon Chambers 88a308fac0 Reduce max message size to 96 KiB 2026-05-18 11:29:54 -05:00
Ravi Khadiwala 34f5351a4c Update to the latest version of the spam filter 2026-05-18 11:29:15 -05:00
Ravi Khadiwala 59f704b6cc Add omnibus H2 server and update to dropwizard 5.0.1 2026-05-18 11:27:17 -05:00
Ravi Khadiwala 0f7d5d7fa4 normalize header combination, special-case user-agent header 2026-05-18 11:25:48 -05:00
Ravi Khadiwala 1ae361b15f Update to the latest version of the spam filter 2026-05-15 12:14:42 -05:00
Ravi Khadiwala 2c9676a1ef Revert omnibus H2 server and dropwizard 5.0.1 2026-05-15 12:13:54 -05:00
Ravi Khadiwala 2ae5c92df2 Update to the latest version of the spam filter 2026-05-15 10:15:23 -05:00
Ravi Khadiwala 3c02f8c3e1 Add documentation to BackupInfo responses 2026-05-15 09:49:40 -05:00
Ravi Khadiwala 4c4282162f Update to dropwizard 5.0.1 2026-05-15 09:44:38 -05:00
Ravi Khadiwala 0beeb8a935 Add h2 omnibus server 2026-05-15 09:44:38 -05:00
Ravi Khadiwala 8d0ad7b085 h2 websocket support 2026-05-15 09:44:38 -05:00
Chris Eager 12e265fb71 Refine Profiles gRPC errors and documentation 2026-05-14 10:55:44 -05:00
Chris Eager 90c27f6969 Add post-registration change number waiting period 2026-05-14 10:55:02 -05:00
Jon Chambers f045e3ee0f Introduce an emergency "read only" mode for messages 2026-05-11 11:43:41 -04:00
Ravi Khadiwala 4485e26562 rename maxUploadSizeInBytes to maxAttachmentUploadSizeInBytes 2026-05-08 13:39:36 -05:00
Ravi Khadiwala 05b7a140fc Add a configuration field for max message backup upload size 2026-05-08 13:18:17 -05:00
Ameya Lokare bde52d775e Update to the latest version of the spam filter 2026-05-07 12:36:51 -07:00
Ravi Khadiwala 59f2f04b7c Handle BackupFailedZkAuthenticationException in grpc SetPublicKey 2026-05-07 11:43:24 -05:00
Chris Eager 305b015784 Update to the latest version of the spam filter 2026-05-06 12:53:24 -05:00
Chris Eager f6ebde8185 Add Profile gRPC services to server 2026-05-06 12:48:58 -05:00
dependabot[bot] 58d4a3b687 Bump aws-actions/configure-aws-credentials
Bumps the minor-actions-dependencies group with 1 update: [aws-actions/configure-aws-credentials](https://github.com/aws-actions/configure-aws-credentials).


Updates `aws-actions/configure-aws-credentials` from 6.0.0 to 6.1.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/8df5847569e6427dd6c4fb1cf565c83acfa8afa7...ec61189d14ec14c8efccab744f656cffd0e33f37)

---
updated-dependencies:
- dependency-name: aws-actions/configure-aws-credentials
  dependency-version: 6.1.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-05-06 12:48:47 -05:00
Chris Eager 9c6ec78a4e Match profiles V2 test table name in Java and configuration 2026-04-29 19:57:20 -05:00
Chris Eager 1e3b2c8ce8 Profiles gRPC: initial v2 implementation 2026-04-29 10:32:18 -05:00
Katherine Yen 1b11c3efc2 Log when DynamoDB/JSON phone numbers differ 2026-04-29 10:28:27 -05:00
Ravi Khadiwala b441fde213 Enforce key-ids fit in a positive signed 32-bit int 2026-04-29 10:28:15 -05:00
Jon Chambers de5cb3370d Don't try to decode null session IDs 2026-04-17 14:51:07 -04:00
Ameya Lokare 52b4e0b87f Enforce rate limiting on batch identity check endpoint 2026-04-17 13:52:41 -04:00
Jon Chambers 3e19b415b6 Always use fresh, non-cached Account instances when changing numbers 2026-04-17 13:47:54 -04:00
Jon Chambers 3790b53496 Update to the latest version of the spam filter 2026-04-17 11:48:27 -04:00
Jon Chambers 6c26c38b96 Turn on compact object headers 2026-04-17 11:47:58 -04:00
Chris Eager aa1ff253fb Enforce AccountAttributes#isUnrestrictedUakValid 2026-04-17 09:54:53 -04:00
Jon Chambers 1301bfda93 Avoid blocking in an async context 2026-04-17 09:54:36 -04:00
Jon Chambers c02667e2e4 Add unit tests for PhoneVerificationTokenManager 2026-04-17 09:54:36 -04:00
Jon Chambers 9e6cbe8f82 Always use fresh/non-cached copies of accounts when making modifications 2026-04-17 09:41:59 -04:00
Chris Eager 1e2d27585a Add gRPC size annotations; allow non-empty UAK for unrestricted 2026-04-16 13:18:56 -05:00
Chris Eager c70674ed26 Update serialization test 2026-04-16 13:18:56 -05:00
Chris Eager 0281756c01 Add metrics for invalid unrestricted UAK 2026-04-16 13:18:56 -05:00
Chris Eager 5e1338a571 Factor out DeviceAttributes from AccountAttributes 2026-04-16 13:18:56 -05:00
Chris Eager 149de6c464 Add UAK validator to AccountAttributes 2026-04-16 13:18:56 -05:00
Chris Eager b551e0cb34 Require UAKs to be non-zero length or null 2026-04-16 13:18:56 -05:00
Chris Eager 2344d3d9b7 Add AccountAttributes serialization test 2026-04-16 13:18:56 -05:00
Chris Eager 04aa528ad8 Add Accounts.SetZkCredentialKey 2026-04-16 12:13:34 -05:00
Jon Chambers 1b5c602351 Retire the device count override system 2026-04-16 12:52:15 -04:00
Ravi Khadiwala bbeeed9d1f Remove unused static grpcAllowList configuration 2026-04-15 18:05:06 -04:00
Chris Eager aabbbe486f Update exception for empty non-sync messages to MessageSender 2026-04-15 17:03:10 -05:00
Jon Chambers b702d9d5a9 Remove service level objectives for captcha outcome distribution 2026-04-15 18:01:59 -04:00
Jon Chambers efc39573e4 Use CaptchaMetrics to measure captcha scores for sending messages and verification 2026-04-15 16:40:06 -04:00
Jon Chambers 87e88dd3a1 Introduce CaptchaMetrics 2026-04-15 16:40:06 -04:00
Chris Eager 4ae82cbb59 Add @NotEmpty validation to IncomingMessageList 2026-04-15 16:38:19 -04:00
Jon Chambers dcb5187629 Retire V1 authentication tokens 2026-04-15 16:37:52 -04:00
Jon Chambers bb589d6daa Retire AccountsManager#updateDeviceAuthentication 2026-04-15 16:37:52 -04:00
Ameya Lokare bb7d855aca Prevent reg lock bypass on alternate phone number forms 2026-04-15 16:37:18 -04:00
Ameya Lokare 288b9f82d7 Prevent potentially orphaned usernames due to concurrent username
confirmation during account deletion
2026-04-15 16:36:41 -04:00
Ameya Lokare 61f5998e8a Add rate limiter to batch profile check 2026-04-15 16:35:24 -04:00
Chris Eager 53a35a827e Remove obsolete Profiles cache key 2026-04-14 11:01:57 -05:00
Chris Eager a3c712f8d3 Migrate Profiles cache key to use hash tag 2026-04-14 09:50:52 -05:00
Jon Chambers 56f25f5a39 Avoid overflows when calculating media ciphertext size 2026-04-14 10:46:16 -04:00
Chris Eager 68b3e9a07c Exclude ExpiringProfileKeyCredentialProfileResponse.credential for non-current versions 2026-04-14 09:23:53 -05:00
Chris Eager 5190b197e8 Update to Java 25 2026-04-14 09:13:50 -05:00
Chris Eager 09c18205d4 Validate level in OneTimeDonationController 2026-04-13 17:12:35 -05:00
Chris Eager ea1e4f02d0 Clean up trivial warnings in OneTimeDonationController 2026-04-13 17:12:35 -05:00
Chris Eager b5e490b987 Make gift amount validation consistent between PayPal and Stripe 2026-04-13 17:12:35 -05:00
Chris Eager 7b8141d174 Update Maven plugins 2026-04-13 17:10:54 -05:00
Chris Eager 83ebd994c7 Update to the latest version of the spam filter 2026-04-13 17:02:33 -05:00
Ravi Khadiwala c4a48dd1e6 Add a base64url gRPC validator and apply it to backup copy 2026-04-13 17:01:38 -05:00
Ravi Khadiwala 5bb7edcade Reject DeviceCheck assertions if they race with a counter update 2026-04-13 17:01:25 -05:00
Chris Eager 75948dc617 Update to the latest version of the spam filter 2026-04-09 16:43:44 -05:00
Ameya Lokare 0edfcab8dd Update dependencies 2026-04-09 16:40:41 -05:00
Ravi Khadiwala 95843529ba Add comments to explain why we remove RRPs early 2026-04-09 16:35:08 -05:00
Ravi Khadiwala 3930b1841e Add missing join() in when deleting RRPs after verification 2026-04-09 16:35:08 -05:00
Jon Chambers 070aa5f0cd Limit cardinality of HTTP methods in request metrics 2026-04-09 17:35:06 -04:00
Jon Chambers 0d42f37a5c Add a (failing!) test for spurious HTTP methods in request metrics 2026-04-09 17:35:06 -04:00
Jon Chambers 837065bfbd Retire commands for removing accounts/devices that do not support SPQR 2026-04-09 17:34:50 -04:00
Jon Chambers 2f9ec6936f Update to the latest version of the spam filter 2026-04-01 20:22:19 -04:00
Jon Chambers fb455bf1db Encode message versionstamps as GUIDs 2026-04-01 20:18:47 -04:00
Jon Chambers d2cbdd4609 Prohibit pre-set message GUIDs when inserting into FoundationDB 2026-04-01 20:18:47 -04:00
Jon Chambers 844e103c86 Include shard ID as user data in message versionstamps 2026-04-01 20:18:47 -04:00
Jon Chambers 2500e85c01 Introduce VersionstampUUIDCipher 2026-04-01 20:07:47 -04:00
Jon Chambers 971d9d64a8 Update to the latest version of the spam filter 2026-04-01 14:49:50 -04:00
Katherine cfac798f9e Handle account reclamation with equivalent phone numbers 2026-04-01 11:29:06 -04:00
Jon Chambers 34e8e04793 Update to the latest version of the spam filter 2026-04-01 11:28:40 -04:00
Jon Chambers 0664c04074 Update to the latest version of the spam filter 2026-03-31 15:41:27 -04:00
Ameya Lokare e454b29c6a FoundationDB message stream implementation 2026-03-31 15:40:57 -04:00
Jon Chambers 4a8313eb67 Add a handleVerificationCompleted hook to RegistrationFraudChecker 2026-03-31 15:24:06 -04:00
Ravi Khadiwala fa145d7889 Use 'response' rather than 'outcome' in backups.proto responses 2026-03-31 11:11:25 -05:00
Ravi Khadiwala edcc61d4ba Add reason annotations to backups.proto 2026-03-31 11:11:25 -05:00
Ravi Khadiwala 34c7106e7e Add reason annotations to account.proto 2026-03-31 11:11:25 -05:00
Ravi Khadiwala ee409af54a Add reason annotations to messages.proto 2026-03-31 11:11:25 -05:00
Ravi Khadiwala 04c4d993a6 Make reason tags upper-case 2026-03-31 11:11:25 -05:00
Ravi Khadiwala 0ee06d83b7 Add byte-based rate-limit to attachments 2026-03-31 11:10:15 -05:00
ravi-signal f9d3cd8d82 Add and enforce uploadLength in backup endpoints 2026-03-31 11:08:08 -05:00
Jon Chambers 771c98fd92 Susbcribe on a separate scheduler for non-SPQR account removal 2026-03-31 11:07:10 -05:00
ravi-signal 82d9107865 Add an attachment uploadLength parameter and enforce it 2026-03-31 11:05:18 -05:00
adel-signal f2b0264fac calling: add dynamic turn configuration for testing new cloudflare TURN endpoints 2026-03-30 11:13:33 -05:00
Jon Chambers 132611f159 Add a command for removing accounts that do not support SPQR 2026-03-30 11:34:02 -04:00
Jon Chambers a741edd80f Add a command for removing linked devices that do not support SPQR 2026-03-30 11:34:02 -04:00
Jon Chambers 8c3dd7aa48 Update to the latest version of the spam filter 2026-03-30 11:30:05 -04:00
Chris Eager b0792dd0a7 Update to the latest version of the spam filter 2026-03-24 15:17:52 -05:00
Jon Chambers d9d6560b47 Add request/response byte counters to the gRPC metrics interceptor 2026-03-24 15:03:10 -04:00
Jon Chambers 8cc0948a34 Use an EnumSet for CAPABILITIES_REQUIRED_FOR_NEW_DEVICES 2026-03-24 15:01:43 -04:00
Jon Chambers 575280da74 Don't allow linked devices that are missing capabilities required at registration time 2026-03-24 15:01:43 -04:00
Jon Chambers 46bfc12869 Check for SPQR capability in third-party clients in remote deprecation filter 2026-03-24 14:29:20 -04:00
Jon Chambers 73ec57e911 Avoid constructing a Metadata.Key for authentication on every server call 2026-03-24 14:29:20 -04:00
ravi-signal fb84066f09 Match KeyController's rate limit key in KeysGrpcService 2026-03-24 13:26:25 -05:00
Ravi Khadiwala 4d24c814cc Check if resolvedRecipients is empty before inserting an MRM 2026-03-24 13:15:57 -05:00
Jon Chambers 9dc807a255 Remove the "unrecognized UA" remote deprecation reason 2026-03-24 14:10:51 -04:00
Jon Chambers 5d59538924 Modernize RemoteDeprecationFilterTest 2026-03-24 14:10:51 -04:00
Jon Chambers 04c102e51f Convert DynamicRemoteDeprecationConfiguration to a record 2026-03-24 14:10:51 -04:00
Jon Chambers 71bc23ed02 Standardize formatting in DynamicRemoteDeprecationConfiguration 2026-03-24 14:10:51 -04:00
ravi-signal 7c26965ece Use a JWT for external attachment auth and add a maxLen claim 2026-03-19 15:19:43 -05:00
Jon Chambers 5c3a82c257 Update to the latest version of the spam filter 2026-03-19 13:58:29 -04:00
Jon Chambers 5fedb48b55 Update to the latest version of the spam filter 2026-03-18 10:01:31 -04:00
Jon Chambers 69d9fc12ca Simplify MessagesCache#getEarliestUndeliveredTimestamp 2026-03-17 14:19:22 -04:00
Ravi Khadiwala 81f2499889 Port AttachmentController to gRPC 2026-03-17 13:18:18 -05:00
Jon Chambers 82a3bba7ec Clean up last vestiges of "total queue index" system 2026-03-17 14:17:11 -04:00
Jon Chambers ee09d6b334 Make sure the client connection process has completed before persisting messages 2026-03-16 12:35:49 -04:00
Jon Chambers dc215cab54 Add a command to discard now-unsued message cache queue indices 2026-03-16 11:43:03 -04:00
Jon Chambers 99bbbbe1ac Retire "total queue index" from message management scripts 2026-03-16 11:43:03 -04:00
Jon Chambers 38121bcbfa Use a shorter default node claim TTL 2026-03-16 10:07:38 -04:00
Jon Chambers 5e7a50a36d Simplify and use a shorter delay in MessagePersisterIntegrationTest 2026-03-16 10:07:38 -04:00
Jon Chambers 17531c5927 Remove a spurious rate limit response annotation 2026-03-16 09:35:37 -04:00
Jon Chambers e7df1aeb5b Add a configurable pause between persisted nodes 2026-03-16 09:35:19 -04:00
Jon Chambers dc8e03bd40 Fetch messages to persist via the same pathway as messages to deliver 2026-03-16 09:34:59 -04:00
Jon Chambers 4578150e5a Add a test for fetching messages when a queue is locked for persistence 2026-03-16 09:34:59 -04:00
Jon Chambers bd97e70a56 Add a test for fetching messages with a "discardable" first page 2026-03-16 09:34:59 -04:00
Jon Chambers 206f114b34 Add a (failing!) test for persisting messages when the entire first page is discardable 2026-03-16 09:34:59 -04:00
Ameya Lokare 2dc4db3918 Revert "Update to Java 25"
Back to Java 24 for now
2026-03-13 18:32:36 -07:00
Jon Chambers 98dc758bb7 Update to the latest version of the spam filter 2026-03-13 19:24:10 -04:00
Jon Chambers b4c594c657 Add scan COUNT arguments and rate limits for queue scans 2026-03-13 18:20:51 -04:00
Chris Eager b55afdd704 Update to Java 25 2026-03-13 18:20:30 -04:00
Chris Eager 136cddf6e2 Add Profiles OpenAPI annotations 2026-03-13 18:20:18 -04:00
ravi-signal b7d455ed11 Validate pre-key key-id ranges 2026-03-12 16:37:28 -05:00
Chris Eager ac23b8e79e Add additional null check for app store's APIException#getApiError 2026-03-12 16:36:32 -05:00
Jon Chambers af2d276f37 Log dropped persistence errors via a hook 2026-03-12 17:32:33 -04:00
Jon Chambers 8154bb1047 Add a dedicated counter for "persist node" events 2026-03-12 12:12:07 -04:00
Jon Chambers b647853983 Add better logging for unhandled persister errors 2026-03-12 12:11:38 -04:00
Jon Chambers 3350922456 Don't destroy persister schedulers/executors while the persister is still running 2026-03-12 11:15:49 -04:00
Jon Chambers 69af979bfa Use a SCAN-based strategy for message persisters 2026-03-12 10:04:04 -04:00
Jon Chambers a142916fef Resolve minor warnings/suggestions throughout MessagePersister and MessagePersisterTest 2026-03-12 10:04:04 -04:00
Ameya Lokare 9ff1431488 Update to the latest version of the spam filter 2026-03-11 11:11:09 -07:00
Ameya Lokare cf2d3369cb Change ChallengeRequired token type to string 2026-03-11 10:57:32 -07:00
Chris Eager c41ae57871 Cancel a subscription immediately if the currency is no longer supported 2026-03-11 12:54:41 -05:00
Ameya Lokare 6d351aad7b Update to the latest version of the spam filter 2026-03-09 14:01:00 -07:00
Ameya Lokare a320504fdc Include raw "Accept-Language" header value in RequestAttributes 2026-03-09 13:46:46 -07:00
Jon Chambers 11df65b8d8 Keep a count of open WebSockets by ASN region 2026-03-09 16:29:20 -04:00
Katherine e96149ecf5 Add null check for app store's APIException#getApiError 2026-03-09 16:28:57 -04:00
Ravi Khadiwala db66d4ef18 Add size annotations to AccountAttributes 2026-03-06 15:05:39 -06:00
Ravi Khadiwala 610782b8c3 Add annotation-based validations to a number of services 2026-03-06 15:05:39 -06:00
Jon Chambers aae1541e88 Include required device capabilities when creating users in integration tests 2026-03-06 15:53:18 -05:00
Ravi Khadiwala 1cf3bf5ecf Add a oneof case for the unrestricted access path in gRPC services 2026-03-06 14:49:26 -06:00
Ravi Khadiwala a90fa5db02 Fix oneof field validation 2026-03-06 14:49:26 -06:00
Jon Chambers f5f217f3de Prevent capability downgrades for SPARSE_POST_QUANTUM_RATCHET 2026-03-06 12:18:04 -05:00
Graeme Connell c93aa7a9b9 Require SPARSE_POST_QUANTUM_RATCHET at registration time 2026-03-06 12:18:04 -05:00
Jon Chambers d519a80f90 Remove AccountLockManager#withLockAsync 2026-03-05 09:54:05 -05:00
Jon Chambers ec2cb8581c Make account deletion a blocking operation 2026-03-05 09:54:05 -05:00
Jon Chambers 405b04f07b Make adding/removing devices blocking and remove async update plumbing 2026-03-05 09:54:05 -05:00
Jon Chambers 31de1fc1a3 Remove asynchronous account update plumbing 2026-03-05 09:54:05 -05:00
Jon Chambers de458c3e6a Remove AccountsManager#updateDeviceAsync 2026-03-05 09:54:05 -05:00
Jon Chambers 8df3f3c150 Update version number in a comment 2026-03-04 18:05:10 -05:00
dependabot[bot] 8800b79f97 Bump aws-actions/configure-aws-credentials from 5.1.1 to 6.0.0
Bumps [aws-actions/configure-aws-credentials](https://github.com/aws-actions/configure-aws-credentials) from 5.1.1 to 6.0.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/61815dcd50bd041e203e49132bacad1fd04d2708...8df5847569e6427dd6c4fb1cf565c83acfa8afa7)

---
updated-dependencies:
- dependency-name: aws-actions/configure-aws-credentials
  dependency-version: 6.0.0
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-03-04 13:03:27 -05:00
Ravi Khadiwala a66b8b278e Register implemented gRPC services 2026-03-03 12:34:48 -06:00
Ravi Khadiwala 9e2d8125f0 Move the envelope type down to the device level 2026-03-03 12:34:16 -06:00
Chris Eager 865ecc0005 Update to the latest version of the spam filter 2026-03-02 10:29:14 -06:00
Jon Chambers 175c9ad823 Remove DynamicConfigurationManager (unused) from AccountsManager 2026-02-27 17:25:56 -05:00
Ravi Khadiwala 13c017c869 Update to the latest version of the spam filter 2026-02-27 16:24:53 -06:00
ravi-signal f872ade347 Remove ChallengeRequired variants from sealed-sender gRPC responses 2026-02-27 16:01:44 -06:00
Jon Chambers 80893152c9 Remove reactor-grpc as a dependency 2026-02-27 16:59:36 -05:00
Chris Eager 6d87b24ba3 Remove deprecated X-Signal-Key header 2026-02-27 15:50:38 -06:00
Jon Chambers 065809e34f Use simple-grpc in KeysGrpcService and KeysAnonymousGrpcService 2026-02-27 16:49:15 -05:00
Jon Chambers c63cbc304f Use simple-grpc in DevicesGrpcService 2026-02-26 17:31:13 -05:00
Jon Chambers 5d306f8d15 Make username-related operations blocking 2026-02-26 17:20:34 -05:00
Jon Chambers ad9c03186a Use simple-grpc in AccountsGrpcService/AccountsAnonymousGrpcService 2026-02-26 17:08:54 -05:00
Jon Chambers 69825dd2a4 Remove unused ClientPublicKeys infrastructure
We're planning on using a different authentication strategy for gRPC
2026-02-26 17:08:05 -05:00
Ravi Khadiwala c8d4ea97e4 Make GrpcAllowListInterceptor dynamically configurable 2026-02-24 16:44:05 -05:00
Ravi Khadiwala f17a39386b Rearrange gRPC interceptor ordering 2026-02-24 16:40:07 -05:00
Ravi Khadiwala 77c4962db8 Don't reuse metadata in ServerInterceptorUtil 2026-02-24 16:40:07 -05:00
Jon Chambers eedc4e23fe Use simple-grpc for PaymentsGrpcService 2026-02-24 16:36:23 -05:00
Chris Eager b43e63c6f0 Update to the latest version of the spam filter 2026-02-24 15:33:59 -06:00
Katherine b318dd2db7 Remove support for searching identifiers by version 2026-02-24 16:33:48 -05:00
Chris Eager 5b3679f56e Update to the latest version of the spam filter 2026-02-23 12:38:34 -06:00
Ravi Khadiwala 8f13beb53b Increse SVR credential validity period to match max account idle duration 2026-02-23 13:38:20 -05:00
Chris Eager c0432d828d Handle MCC-only HLR responses 2026-02-23 12:37:49 -06:00
Jon Chambers f390aabb3a Add "additional specifiers" dimensions to open WebSocket counters and simplify meter construction 2026-02-20 16:33:21 -05:00
Jon Chambers cb3363410c Revert "Add tags from "additional specifiers" to requests-by-version counter"
This reverts commit e0632e9800.
2026-02-20 16:33:21 -05:00
Ravi Khadiwala 1d1570464d Fix one missed int32->uint32 cdn number conversion 2026-02-20 16:18:02 -05:00
Chris Eager 541e93fc98 Remove explicit percentile configuration 2026-02-20 15:12:44 -06:00
Chris Eager d87cf01a9b Use default distribution statistic config as parent 2026-02-20 15:12:26 -06:00
Chris Eager b61c7e2345 Update to the latest version of the spam filter 2026-02-20 15:11:22 -06:00
Ravi Khadiwala 2137fc519d Split BackupInfo RPC into media/message variants 2026-02-19 13:34:21 -05:00
Ravi Khadiwala f7922856fe Use consistent success indicator in backups.proto 2026-02-19 13:34:21 -05:00
Jon Chambers 99c811273b Correctly parse iOS/Android additional specifiers 2026-02-19 12:59:54 -05:00
Jon Chambers ac5b62478c Add a (failing!) test for parsing OS information for iOS/Android 2026-02-19 12:59:54 -05:00
ravi-signalandJon Chambers 207d95dfdd Select only matching entitlements from storekit list
Co-authored-by: Jon Chambers <63609320+jon-signal@users.noreply.github.com>
2026-02-19 11:59:11 -06:00
Jon Chambers c78541f00b Update to the latest version of the spam filter 2026-02-18 13:46:22 -05:00
Jon Chambers 6b9734f70f Add an "is disposable?" field to CarrierData 2026-02-18 13:31:55 -05:00
Ravi Khadiwala a99635fbee Actually use updated account in getBackupAuthCredentials 2026-02-18 13:31:35 -05:00
Jon Chambers e0632e9800 Add tags from "additional specifiers" to requests-by-version counter 2026-02-18 13:30:50 -05:00
Jon Chambers 24029ef00c Add a utility method to get OS, OS version, and libsignal version tags from UA additional specifiers 2026-02-18 13:30:50 -05:00
Jon Chambers 5ffcdb1c3f Avoid unnecessary re-parsing of User-Agent strings 2026-02-18 13:21:12 -05:00
Jon Chambers d659af566b Remove utility method for testing if clients are using libsignal networking 2026-02-18 13:07:45 -05:00
Ravi Khadiwala 5850eeb87b Avoid reading modified account when generating backup credentials 2026-02-17 15:23:57 -05:00
Chris Eager 368e705b68 Migrate one-time donations tests to OneTimeDonationControllerTest 2026-02-17 13:58:56 -06:00
Chris Eager 39beb59b58 Add PayPalLineItemInput with localized description 2026-02-17 13:58:56 -06:00
Chris Eager 118b1d31cf Update apollo-client-maven-plugin to 7.1.0 2026-02-17 13:58:56 -06:00
Chris Eager 24a483a689 Update to the latest version of the spam filter 2026-02-17 13:58:24 -06:00
Chris Eager 183cbab4f3 Remove duplicate integration AccountTest#testCreateAccountAtomic 2026-02-17 13:58:09 -06:00
ravi-signal 81031b7b2f Ensure details are included on all gRPC error statuses 2026-02-17 13:54:16 -06:00
Ravi Khadiwala d6a0129c5a Treat missing backup after authentication as an authentication failure 2026-02-17 14:52:27 -05:00
Ravi Khadiwala 225e756e38 cdn number can be unsigned 2026-02-17 14:52:27 -05:00
Ameya Lokare f5a3b93849 Improve captcha response error handling 2026-02-12 11:57:27 -08:00
Ravi Khadiwala 8fa1f85924 Update to the latest version of the spam filter 2026-02-11 16:44:13 -06:00
Ravi Khadiwala 809ba29ce8 Update error model in messages.proto 2026-02-11 16:35:38 -06:00
Ravi Khadiwala 1009f3ba51 Update error model in keys.proto 2026-02-11 16:33:04 -06:00
Ravi Khadiwala 8804f28cb8 Update error model in device.proto 2026-02-11 17:21:42 -05:00
Chris Eager a9f81e2ba6 Update to the latest version of the spam filter 2026-02-09 12:35:55 -06:00
ravi-signal 7e9da6d7ce Add a request tag for listen port 2026-02-05 16:18:09 -06:00
Ravi Khadiwala ea80077c25 Fix incorrect comment in account.proto 2026-02-05 17:17:24 -05:00
Chris Eager 0ab471f7dd Update to the latest version of the spam filter 2026-02-05 16:07:03 -06:00
Chris Eager fa9fb1f0a2 Move inline versions to properties in service/pom.xml 2026-02-05 15:53:25 -06:00
Chris Eager 800902414f Update libphonenumber geocoder to 3.23 2026-02-05 15:53:25 -06:00
Chris Eager c13a34b2c8 Improve SchedulingUtil.getZoneId for PhoneNumberType.UNKONWN numbers 2026-02-05 15:51:41 -06:00
Chris Eager 5ec8628b51 Update to the latest version of the spam filter 2026-02-04 15:59:34 -06:00
Jon Chambers ad21f002ab Add a counter to verify that it's safe to remove legacy combined UAK credentials 2026-02-04 15:50:59 -06:00
Jon Chambers 1e5fcbdd20 Add a utility method for getting UA tags from request contexts 2026-02-04 15:50:59 -06:00
Ravi Khadiwala d34fc29ba2 Add null checks in IncomingMessageList 2026-02-04 15:50:45 -06:00
Chris Eager e0bf1df16f Update to the latest version of the spam filter 2026-02-04 14:19:23 -06:00
Chris Eager 9a1c450458 Make VerificationSession.sessionId not-null 2026-02-04 12:07:44 -06:00
Chris Eager e5209d84bf Update to the latest version of the spam filter 2026-02-04 10:21:45 -06:00
Chris Eager 969788b267 Include sessionId in VerificationSession record 2026-02-04 10:06:25 -06:00
Chris Eager d0bbaaea52 Update to the latest version of the spam filter 2026-01-30 13:13:26 -06:00
Chris Eager b01ef94c69 Update to the latest version of the spam filter 2026-01-30 11:52:34 -06:00
Jonathan Klabunde Tomer 040f3190cb directly subscribe to item publisher in account crawlers 2026-01-30 10:16:26 -06:00
Chris Eager 77bf44fda5 Remove deprecated /v2/accounts/phone_number_identity_key_distribution 2026-01-30 10:13:41 -06:00
Ravi Khadiwala 185654fc10 Use userAgent instead of signalAgent as metrics platform tag 2026-01-30 10:13:21 -06:00
Ravi Khadiwala 159e1f13f0 Fix credential age calculation 2026-01-30 10:13:21 -06:00
Jon Chambers 61ab765391 Require that LinkDeviceRequest has non-null account attributes 2026-01-30 10:13:11 -06:00
Jon Chambers 63c39645d2 Add a (failing!) test for attempting to link a device with null account attributes 2026-01-30 10:13:11 -06:00
Chris Eager cf518ce910 Update to the latest version of the spam filter 2026-01-30 09:44:20 -06:00
Ravi Khadiwala e14dbfc9ad Fix merge conflict in HlrLookupResult 2026-01-29 11:24:18 -06:00
Ravi Khadiwala 734d369fb1 Update to the latest version of the spam filter 2026-01-29 11:17:08 -06:00
ravi-signal ee81faa82d Add an allow-list for gRPC methods 2026-01-29 11:15:04 -06:00
Jon Chambers c0d0d5f5da Extract "is ported" data from HLR Lookup responses 2026-01-29 12:14:26 -05:00
Jon Chambers ff8194ae5f Add "is ported" to CarrierData 2026-01-29 12:14:26 -05:00
Jon Chambers c69abb5200 Instrument credits spent 2026-01-29 12:14:00 -05:00
Ravi Khadiwala fb1c20582e Instrument /v2/svr/auth/check credential age 2026-01-28 17:44:11 -05:00
Ravi Khadiwala 0357b25f92 Update to the latest version of the spam filter 2026-01-28 16:42:23 -06:00
Ravi Khadiwala d197e22e0a Fix argument to updateWithRetries updater 2026-01-28 17:39:32 -05:00
ravi-signal e6116044f8 Instrument registration recovery password modifications 2026-01-28 16:37:50 -06:00
ravi-signal 2a7e99e9f0 Update credentials and calling gRPC services to new error model 2026-01-28 16:36:12 -06:00
Ravi Khadiwala 8023a9346f Convert call quality gRPC service to new error model 2026-01-28 17:35:11 -05:00
Ravi Khadiwala 517c5b8056 Call CallQualitySurveryManager#validateRequest 2026-01-28 17:35:11 -05:00
dependabot[bot] a6a089e93f Bump actions/setup-java in the minor-actions-dependencies group
Bumps the minor-actions-dependencies group with 1 update: [actions/setup-java](https://github.com/actions/setup-java).


Updates `actions/setup-java` from 5.0.0 to 5.2.0
- [Release notes](https://github.com/actions/setup-java/releases)
- [Commits](https://github.com/actions/setup-java/compare/dded0888837ed1f317902acf8a20df0ad188d165...be666c2fcd27ec809703dec50e508c2fdc7f6654)

---
updated-dependencies:
- dependency-name: actions/setup-java
  dependency-version: 5.2.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-01-26 13:48:55 -05:00
dependabot[bot] 6c2999dd55 Bump actions/checkout from 5.0.0 to 6.0.2
Bumps [actions/checkout](https://github.com/actions/checkout) from 5.0.0 to 6.0.2.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/08c6903cd8c0fde910a37f88322edcfb5dd907a8...de0fac2e4500dabe0009e67214ff5f5447ce83dd)

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

Signed-off-by: dependabot[bot] <support@github.com>
2026-01-26 13:05:12 -05:00
dependabot[bot] 14862c58c8 Bump aws-actions/configure-aws-credentials from 4.2.1 to 5.1.1
Bumps [aws-actions/configure-aws-credentials](https://github.com/aws-actions/configure-aws-credentials) from 4.2.1 to 5.1.1.
- [Release notes](https://github.com/aws-actions/configure-aws-credentials/releases)
- [Changelog](https://github.com/aws-actions/configure-aws-credentials/blob/main/CHANGELOG.md)
- [Commits](https://github.com/aws-actions/configure-aws-credentials/compare/b47578312673ae6fa5b5096b330d9fbac3d116df...61815dcd50bd041e203e49132bacad1fd04d2708)

---
updated-dependencies:
- dependency-name: aws-actions/configure-aws-credentials
  dependency-version: 5.1.1
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-01-26 13:05:02 -05:00
Ravi Khadiwala 645161cc09 add dependabot.yml 2026-01-26 11:36:30 -05:00
Jon Chambers 065e730200 Update to the latest version of the spam filter 2026-01-23 16:37:38 -05:00
Ravi Khadiwala 7e7bef32cc Convert service protos to line comments 2026-01-23 16:37:01 -05:00
ravi-signal 5b1d4ce95e Convert backup services to use new error model 2026-01-23 14:25:15 -06:00
Ravi Khadiwala 12d9637f21 Update to the latest version of the spam filter 2026-01-23 14:24:17 -06:00
ravi-signal 924ab88e93 Update dependencies 2026-01-23 13:32:20 -06:00
Jon Chambers 187cd9e163 Update to the latest version of the spam filter 2026-01-23 12:30:21 -05:00
Jon Chambers 2ed60209b1 Store carrier information in verification sessions 2026-01-23 12:09:19 -05:00
Jon Chambers 9ffb588c6a Pass carrier data from lookup services to registration service 2026-01-23 12:09:19 -05:00
Jon Chambers 5043175cb4 Standardize on javax.annotation.Nullable 2026-01-23 12:09:19 -05:00
Jon Chambers 953a473c74 Resolve minor warnings/suggestions throughout VerificationController 2026-01-23 12:09:19 -05:00
Jon Chambers 3b87527f39 Add a system to look up mobile network data 2026-01-23 11:51:14 -05:00
ravi-signal 023296feaf Make Backup methods synchronous 2026-01-21 14:01:58 -06:00
Jon Chambers b4db86a39b Update to the latest version of the spam filter 2026-01-21 13:52:34 -05:00
Jon Chambers e0b89d6228 Update AWS SDK to 2.41.11 2026-01-21 10:22:07 -06:00
Chris Eager bcd8ed8d35 Update to the latest version of the spam filter 2026-01-21 10:21:32 -06:00
Ameya Lokare cb9b90b81d Update to the latest version of the spam filter 2026-01-14 11:56:36 -08:00
Ameya Lokare 265bcfe51b Update to the latest version of the spam filter 2026-01-14 11:12:04 -08:00
Jon Chambers 4b1a0259fc Resolve a warning about potentially-null results from a Flux#toList call 2026-01-14 09:36:53 -06:00
Jon Chambers 14e7652339 Remove an unused logger 2026-01-14 09:36:53 -06:00
Jon Chambers 8d53b2d8a6 Make key-fetching asynchronous 2026-01-14 09:36:53 -06:00
Chris Eager 8ee097d25a Remove temporary unidentifiedDelivery.rotated.privateKey 2026-01-14 09:36:26 -06:00
Jordan Rose 94c9d48da1 Add option to omit full signer certificate from sealed sender certificates 2026-01-13 13:43:28 -06:00
Ravi Khadiwala a1b1d051f5 Use enriched gRPC status errors 2026-01-13 11:24:35 -05:00
Jon Chambers 77eaec0150 Update to the latest version of the spam filter 2026-01-13 11:16:01 -05:00
Jon Chambers 7d39f72ed6 Update to Testcontainers 2.0.3 2026-01-13 11:02:04 -05:00
Jon Chambers 8c3a38979a Update inadvertent/legacy JUnit 4 imports to JUnit 5 2026-01-13 11:02:04 -05:00
Jon Chambers af02cb93c0 Update to the latest version of the spam filter 2026-01-13 10:41:54 -05:00
Jon Chambers c25c8807a6 Notify registered message delivery listeners when messages are delivered 2026-01-13 10:24:11 -05:00
Jon Chambers dad2bd5c29 Introduce MessageDeliveryListener 2026-01-13 10:24:11 -05:00
Chris Eager 7e511d1f66 Add temporary unidentifiedDelivery.rotated.privateKey 2026-01-12 16:26:37 -06:00
Chris Eager 49daf3909c Set paymentProcessing = true for draft invoices 2026-01-09 16:30:07 -06:00
Chris Eager a1f7710ccb Remove explicit percentile configuration from DistributionStatisticConfig 2026-01-06 15:48:15 -05:00
ravi-signal 807b08b31b Make googlePlayBilling.credentialsJson not a secret 2026-01-06 14:47:45 -06:00
Ravi Khadiwala 9a43f76663 Add source tag to appstore API errors 2026-01-06 15:47:05 -05:00
Chris Eager 7f5097bd33 Update logback to 1.5.23 2026-01-05 17:01:11 -06:00
Chris Eager 54443f7015 Set the logging context on the PatternLayout 2026-01-05 17:01:11 -06:00
Chris Eager e1c44dd374 Remove Datadog fields from logstash output 2026-01-05 17:01:11 -06:00
ravi-signal eaabbd5188 Add nested message validation 2026-01-05 16:23:11 -06:00
ravi-signal 9c4047a90b Remove row-based one-time PQ key store 2025-12-10 16:22:03 -06:00
Katherine Yen 33f506a431 Add registration ID to GetPreKeysResponse 2025-12-10 16:21:34 -06:00
Jon Chambers 7fd0cb32f6 Revert "Include client version in the large message counter tags"
This reverts commit 3ac7a41f9b.
2025-12-10 17:21:26 -05:00
ravi-signal fecb032d8f Ignore failures to update cache after a read 2025-12-10 16:21:18 -06:00
Jon Chambers 1913dbf6f9 Update to the latest version of the spam filter 2025-12-10 11:18:36 -05:00
Jon Chambers de09de895b Update to the latest version of the spam filter 2025-12-10 11:03:04 -05:00
sunday 09942b17a0 feat: add static factory for custom S3 endpoint in S3ObjectMonitor for local testing 2025-12-10 10:52:19 -05:00
Jon Chambers 1d74ecf092 Update to the latest version of the spam filter 2025-12-10 09:56:34 -05:00
Jon Chambers 3ac7a41f9b Include client version in the large message counter tags 2025-12-10 09:46:15 -05:00
Jon Chambers e1c901c5cf Increment a counter when we receive large-but-not-disallowed messages 2025-12-10 09:46:15 -05:00
Jon Chambers 9c35ad0722 Introduce RegistrationFraudChecker#checkSendVerificationCodeAttempt 2025-12-10 09:42:29 -05:00
Jon Chambers 5f25b6a412 Use long instead of int for rate limiter permits 2025-12-10 09:41:51 -05:00
Jon Chambers 77d04ccb70 Rename "dynamic rate limiter" to "leaky bucket rate limiter" 2025-12-10 09:29:44 -05:00
Jonathan Klabunde Tomer 504310cc14 handle Logstash markers in otel logs 2025-12-10 09:29:23 -05:00
Jon Chambers 62798229bf Fix a very (survery?) small typo 2025-12-10 09:29:04 -05:00
Jordan Rose 730e0205f8 Update to libsignal v0.86.6 2025-12-05 11:01:38 -05:00
Katherine 31d6ac71a4 Retire creation timestamp from device endpoints 2025-12-05 10:55:20 -05:00
Chris Eager b887d1f7c0 Fix potentially null errorCode in switch 2025-12-05 10:54:58 -05:00
Jon Chambers 92f8623ad8 Update to the latest version of the spam filter 2025-12-04 09:38:39 -05:00
Jon Chambers 7445225906 Update to the latest version of the spam filter 2025-12-03 16:50:27 -05:00
Jon Chambers 0d2bee7599 Update to the latest version of the spam filter 2025-12-03 15:07:06 -05:00
Jon Chambers 78aa81dd56 Pass client-provided route optimization data to registration service 2025-12-03 14:55:43 -05:00
Jon Chambers 08f6ec639c Update to the latest version of the spam filter 2025-12-02 15:59:54 -05:00
Jonathan Klabunde Tomer 6c3cfc88b5 retire /v1/config
It's been supplanted by /v2/config for all clients beyond the 90-day window.
We still have [some traffic](https://signal.grafana.net/goto/bf5tjk346v1moa?orgId=1)
but it's all from expired/third-party clients (note the lack of a recognized
version number in the client-version tag).
2025-12-02 12:52:39 -08:00
Jon Chambers 389d44fd80 Remove legacy delete-via-REST plumbing 2025-12-02 15:45:18 -05:00
Jon Chambers 7604306818 Retire REST-based message deletion 2025-12-02 15:45:18 -05:00
Jon Chambers 92e133b21f Shut down command dependencies in LIFO order 2025-12-02 15:45:01 -05:00
Jon Chambers 4af50986e0 Minor corrections to docs for POST /v1/registration 2025-12-02 15:44:43 -05:00
Jon Chambers c72458b47a Perform basic input validation on call quality survey responses 2025-12-01 09:56:09 -05:00
Jon Chambers aa2f9e5a65 Accept start/end timestamps as milliseconds since the epoch 2025-11-26 09:00:54 -05:00
Jonathan Klabunde Tomer f13837d2f2 improve OpenTelemetry logging 2025-11-25 12:23:00 -08:00
Jonathan Klabunde Tomer 3ff2af47cb Revert "support JSON logging and prefer it in sample config"
This reverts commit 4d5cc4dc22.
2025-11-25 12:23:00 -08:00
Jon Chambers c719da3527 Update to the latest version of the spam filter 2025-11-25 12:22:38 -05:00
Jon Chambers 0ea52b785e Update to the latest version of the spam filter 2025-11-25 11:27:05 -05:00
Jon Chambers 1ce1c298d3 Add hooks so spam filters can register Dropwizard commands 2025-11-25 11:07:57 -05:00
Jonathan Klabunde Tomer 4d5cc4dc22 support JSON logging and prefer it in sample config
We won't actually remove OTLP logging support until testing side-by-side and
seeing that things look good.
2025-11-24 16:05:28 -08:00
Jon Chambers 640274108e Make CommandDependencies public 2025-11-24 10:47:00 -05:00
748 changed files with 51595 additions and 21855 deletions

No files matched your search

+20
View File
@@ -0,0 +1,20 @@
version: 2
updates:
- package-ecosystem: github-actions
directory: /
schedule:
interval: monthly
groups:
minor-actions-dependencies:
# GitHub Actions: Only group minor and patch updates (we want to carefully review major updates)
update-types: [ minor, patch ]
- package-ecosystem: maven
directory: /
schedule:
interval: monthly
groups:
minor-java-dependencies:
# Java: Only group minor and patch updates (we want to carefully review major updates)
update-types: [ minor, patch ]
+19 -7
View File
@@ -11,23 +11,35 @@ jobs:
contents: write
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
- uses: actions/setup-java@dded0888837ed1f317902acf8a20df0ad188d165 # v5.0.0
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: actions/setup-java@03ad4de0992f5dab5e18fcb136590ce7c4a0ac95 # v5.6.0
with:
distribution: 'temurin'
java-version-file: .java-version
cache: 'maven'
- name: Compile and Build OpenAPI file
- 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: Update Documentation
- name: Generate gRPC documentation
run: |
protoc -I service/src/main/proto service/src/main/proto/org/signal/chat/*.proto \
-o api-doc/grpc/descriptor.pb --include_source_info
cd api-doc/grpc && sabledocs
- name: Push documentation to gh-pages
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
cp -r api-doc/target/openapi/signal-server-openapi.yaml /tmp/
git config user.email "github@signal.org"
git config user.name "Documentation Updater"
git fetch origin gh-pages
git checkout gh-pages
cp /tmp/signal-server-openapi.yaml .
git diff --quiet || git commit -a -m "Updating documentation"
cp api-doc/target/openapi/signal-server-openapi.yaml .
rm -rf grpc
cp -r api-doc/grpc/sabledocs_output grpc
git add -A signal-server-openapi.yaml grpc
git diff --cached --quiet || git commit -m "Updating documentation"
git push origin gh-pages -q
+12 -3
View File
@@ -17,14 +17,15 @@ jobs:
permissions:
id-token: write
contents: read
issues: write
steps:
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
- uses: actions/setup-java@dded0888837ed1f317902acf8a20df0ad188d165 # v5.0.0
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: actions/setup-java@03ad4de0992f5dab5e18fcb136590ce7c4a0ac95 # v5.6.0
with:
distribution: 'temurin'
java-version-file: .java-version
cache: 'maven'
- uses: aws-actions/configure-aws-credentials@b47578312673ae6fa5b5096b330d9fbac3d116df # v5.0.0
- uses: aws-actions/configure-aws-credentials@e6de054238d6b7531b4efff3b6587d9aade6a06c # v6.2.3
name: Configure AWS credentials from Test account
with:
role-to-assume: ${{ vars.AWS_ROLE }}
@@ -35,3 +36,11 @@ jobs:
echo "${INTEGRATION_TEST_CONFIG}" > integration-tests/src/main/resources/config.yml
- name: Run and verify integration tests
run: ./mvnw clean compile test-compile failsafe:integration-test failsafe:verify -P aws-sso
- name: Open an issue on failure
if: ${{ failure() && github.event_name == 'schedule' }}
env:
GH_TOKEN: ${{ github.token }}
run: |
gh issue create \
--title "Failed server integration tests ($(date +'%Y-%m-%d'))" \
--body "Workflow **${{ github.workflow }}** failed. See the run: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}"
+24 -19
View File
@@ -1,5 +1,8 @@
name: Service CI
permissions:
contents: read
on:
pull_request:
push:
@@ -9,39 +12,31 @@ on:
jobs:
build:
runs-on: ubuntu-latest
container: ubuntu:24.04
container: ubuntu:26.04
timeout-minutes: 20
services:
foundationdb0:
# Note: this should generally match the version of the FoundationDB SERVER deployed in production; it's okay if
# it's a little behind the CLIENT version.
image: foundationdb/foundationdb:7.3.62
# Note: this should generally match the version of the FoundationDB SERVER deployed in production; no need to
# bump it purely to match the CLIENT version
image: foundationdb/foundationdb:7.3.68
options: --name foundationdb0
foundationdb1:
# Note: this should generally match the version of the FoundationDB SERVER deployed in production; it's okay if
# it's a little behind the CLIENT version.
image: foundationdb/foundationdb:7.3.62
# Note: this should generally match the version of the FoundationDB SERVER deployed in production; no need to
# bump it purely to match the CLIENT version
image: foundationdb/foundationdb:7.3.68
options: --name foundationdb1
steps:
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
- name: Set up JDK
uses: actions/setup-java@dded0888837ed1f317902acf8a20df0ad188d165 # v5.0.0
with:
distribution: 'temurin'
java-version-file: .java-version
cache: 'maven'
env:
# work around an issue with actions/runner setting an incorrect HOME in containers, which breaks maven caching
# https://github.com/actions/setup-java/issues/356
HOME: /root
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Install APT packages
# ca-certificates: required for AWS CRT client
run: |
# Add Docker's official GPG key:
apt update
apt install -y ca-certificates curl
# Maven Wrapper requires `unzip`; see https://github.com/apache/maven-wrapper/issues/425
apt install -y unzip
install -m 0755 -d /etc/apt/keyrings
curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc
chmod a+r /etc/apt/keyrings/docker.asc
@@ -54,6 +49,16 @@ jobs:
# ca-certificates: required for AWS CRT client
apt update && apt install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin ca-certificates
- name: Set up JDK
uses: actions/setup-java@03ad4de0992f5dab5e18fcb136590ce7c4a0ac95 # v5.6.0
with:
distribution: 'temurin'
java-version-file: .java-version
cache: 'maven'
env:
# work around an issue with actions/runner setting an incorrect HOME in containers, which breaks maven caching
# https://github.com/actions/setup-java/issues/356
HOME: /root
- name: Configure FoundationDB0 database
run: docker exec foundationdb0 /usr/bin/fdbcli --exec 'configure new single memory'
- name: Configure FoundationDB1 database
@@ -61,7 +66,7 @@ jobs:
- name: Download and install FoundationDB client
run: |
./mvnw -e -B -Pexclude-spam-filter clean prepare-package -DskipTests=true
cp service/target/jib-extra/usr/lib/libfdb_c.x86_64.so /usr/lib/libfdb_c.x86_64.so
cp service/target/jib-extra/usr/lib/libfdb_c.so /usr/lib/libfdb_c.x86_64.so
ldconfig
- name: Build with Maven
run: ./mvnw -e -B clean verify -DfoundationDb.serviceContainerNamePrefix=foundationdb
+4
View File
@@ -29,3 +29,7 @@ deployer.log
.classpath
.settings
.DS_Store
# Generated gRPC documentation build artifacts
/api-doc/grpc/descriptor.pb
/api-doc/grpc/sabledocs_output/
+1 -1
View File
@@ -1 +1 @@
temurin-24
temurin-25
BIN
View File
Binary file not shown.
+4 -3
View File
@@ -14,7 +14,8 @@
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.11/apache-maven-3.9.11-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.3.4/maven-wrapper-3.3.4.jar
distributionSha256Sum=0d7125e8c91097b36edb990ea5934e6c68b4440eef4ea96510a0f6815e7eeadb
wrapperVersion=3.3.4
distributionType=only-script
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.16/apache-maven-3.9.16-bin.zip
distributionSha256Sum=5af3b743dd8b876b5c45da33b676251e5f1687712644abb4ee519ca56e1d89ce
wrapperSha256Sum=4e2fbf6554bc8a4702cdfdd3bef464f423393d784ddbb037216320ce55d5e4e1
+2
View File
@@ -0,0 +1,2 @@
main-page-content-file = "../../service/src/main/proto/org/signal/chat/README.md"
markdown-extensions = ["fenced_code", "tables"]
+20
View File
@@ -10,6 +10,10 @@
<modelVersion>4.0.0</modelVersion>
<artifactId>integration-tests</artifactId>
<properties>
<jetty.http2-client.version>12.1.5</jetty.http2-client.version>
</properties>
<dependencies>
<dependency>
<groupId>org.whispersystems.textsecure</groupId>
@@ -21,6 +25,22 @@
<groupId>software.amazon.awssdk</groupId>
<artifactId>dynamodb</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.jetty.websocket</groupId>
<artifactId>jetty-websocket-jetty-api</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.jetty.websocket</groupId>
<artifactId>jetty-websocket-jetty-client</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.jetty.http2</groupId>
<artifactId>jetty-http2-client-transport</artifactId>
<version>${jetty.http2-client.version}</version>
</dependency>
</dependencies>
<build>
@@ -9,27 +9,32 @@ import java.time.Clock;
import java.time.Duration;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.signal.integration.config.Config;
import org.whispersystems.textsecuregcm.metrics.NoopAwsSdkMetricPublisher;
import org.whispersystems.textsecuregcm.registration.VerificationSession;
import org.whispersystems.textsecuregcm.storage.ChangeNumberWaitingPeriods;
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswords;
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
import org.whispersystems.textsecuregcm.storage.PhoneNumberRecoveryPasswords;
import org.whispersystems.textsecuregcm.storage.PhoneNumberRecoveryPasswordsManager;
import org.whispersystems.textsecuregcm.storage.VerificationSessionManager;
import org.whispersystems.textsecuregcm.storage.VerificationSessions;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
public class IntegrationTools {
private final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager;
private final PhoneNumberRecoveryPasswordsManager phoneNumberRecoveryPasswordsManager;
private final VerificationSessionManager verificationSessionManager;
private final PhoneNumberIdentifiers phoneNumberIdentifiers;
private final ChangeNumberWaitingPeriods changeNumberWaitingPeriods;
public static IntegrationTools create(final Config config) {
final AwsCredentialsProvider credentialsProvider = DefaultCredentialsProvider.builder().build();
@@ -37,36 +42,49 @@ public class IntegrationTools {
final DynamoDbAsyncClient dynamoDbAsyncClient =
config.dynamoDbClient().buildAsyncClient(credentialsProvider, new NoopAwsSdkMetricPublisher());
final RegistrationRecoveryPasswords registrationRecoveryPasswords = new RegistrationRecoveryPasswords(
config.dynamoDbTables().registrationRecovery(), Duration.ofDays(1), dynamoDbAsyncClient, Clock.systemUTC());
final DynamoDbClient dynamoDbClient =
config.dynamoDbClient().buildSyncClient(credentialsProvider, new NoopAwsSdkMetricPublisher());
final PhoneNumberRecoveryPasswords phoneNumberRecoveryPasswords = new PhoneNumberRecoveryPasswords(
config.dynamoDbTables().registrationRecovery(), Duration.ofDays(1), dynamoDbClient, Clock.systemUTC());
final VerificationSessions verificationSessions = new VerificationSessions(
dynamoDbAsyncClient, config.dynamoDbTables().verificationSessions(), Clock.systemUTC());
dynamoDbClient, config.dynamoDbTables().verificationSessions(), Clock.systemUTC());
return new IntegrationTools(
new RegistrationRecoveryPasswordsManager(registrationRecoveryPasswords),
new PhoneNumberRecoveryPasswordsManager(phoneNumberRecoveryPasswords),
new VerificationSessionManager(verificationSessions),
new PhoneNumberIdentifiers(dynamoDbAsyncClient, config.dynamoDbTables().phoneNumberIdentifiers())
new PhoneNumberIdentifiers(dynamoDbAsyncClient, config.dynamoDbTables().phoneNumberIdentifiers()),
new ChangeNumberWaitingPeriods(config.dynamoDbTables().changeNumberWaitingPeriods(), dynamoDbClient)
);
}
private IntegrationTools(
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager,
final PhoneNumberRecoveryPasswordsManager phoneNumberRecoveryPasswordsManager,
final VerificationSessionManager verificationSessionManager,
final PhoneNumberIdentifiers phoneNumberIdentifiers) {
this.registrationRecoveryPasswordsManager = registrationRecoveryPasswordsManager;
final PhoneNumberIdentifiers phoneNumberIdentifiers,
final ChangeNumberWaitingPeriods changeNumberWaitingPeriods) {
this.phoneNumberRecoveryPasswordsManager = phoneNumberRecoveryPasswordsManager;
this.verificationSessionManager = verificationSessionManager;
this.phoneNumberIdentifiers = phoneNumberIdentifiers;
this.changeNumberWaitingPeriods = changeNumberWaitingPeriods;
}
public CompletableFuture<Void> populateRecoveryPassword(final String phoneNumber, final byte[] password) {
return phoneNumberIdentifiers
.getPhoneNumberIdentifier(phoneNumber)
.thenCompose(pni -> registrationRecoveryPasswordsManager.store(pni, password));
public void populateRecoveryPassword(final String phoneNumber, final byte[] password) {
try {
final UUID pni = phoneNumberIdentifiers
.getPhoneNumberIdentifier(phoneNumber).get(5, TimeUnit.SECONDS);
phoneNumberRecoveryPasswordsManager.store(pni, password);
} catch (ExecutionException | InterruptedException | TimeoutException e) {
throw new RuntimeException("failed to get pni", e);
}
}
public CompletableFuture<Optional<String>> peekVerificationSessionPushChallenge(final String sessionId) {
return verificationSessionManager.findForId(sessionId)
.thenApply(maybeSession -> maybeSession.map(VerificationSession::pushChallenge));
public Optional<String> peekVerificationSessionPushChallenge(final String sessionId) {
return verificationSessionManager.findForId(sessionId).map(VerificationSession::pushChallenge);
}
public void clearChangeNumberWaitingPeriod(TestUser user) {
changeNumberWaitingPeriods.delete(user.aciUuid());
}
}
@@ -20,18 +20,28 @@ import java.net.URL;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import org.apache.commons.lang3.tuple.Pair;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.http2.client.HTTP2Client;
import org.eclipse.jetty.http2.client.transport.HttpClientTransportOverHTTP2;
import org.eclipse.jetty.io.ClientConnector;
import org.eclipse.jetty.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.libsignal.protocol.IdentityKey;
import org.signal.libsignal.protocol.ecc.ECKeyPair;
@@ -49,6 +59,7 @@ import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
import org.whispersystems.textsecuregcm.entities.RegistrationRequest;
import org.whispersystems.textsecuregcm.http.FaultTolerantHttpClient;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.util.CertificateUtil;
import org.whispersystems.textsecuregcm.util.HeaderUtils;
import org.whispersystems.textsecuregcm.util.HttpUtils;
import org.whispersystems.textsecuregcm.util.SystemMapper;
@@ -65,6 +76,8 @@ public final class Operations {
private static final FaultTolerantHttpClient CLIENT = buildClient();
private static final WebSocketClient WEB_SOCKET_CLIENT = buildWebSocketClient();
private Operations() {
// utility class
@@ -83,14 +96,15 @@ public final class Operations {
// register account
final RegistrationRequest registrationRequest = new RegistrationRequest(null,
registrationPassword,
null,
accountAttributes,
true,
new IdentityKey(aciIdentityKeyPair.getPublicKey()),
new IdentityKey(pniIdentityKeyPair.getPublicKey()),
new DeviceActivationRequest(generateSignedECPreKey(1, aciIdentityKeyPair),
generateSignedECPreKey(2, pniIdentityKeyPair),
Optional.of(generateSignedECPreKey(2, pniIdentityKeyPair)),
generateSignedKEMPreKey(3, aciIdentityKeyPair),
generateSignedKEMPreKey(4, pniIdentityKeyPair),
Optional.of(generateSignedKEMPreKey(4, pniIdentityKeyPair)),
Optional.empty(),
Optional.empty()));
@@ -99,7 +113,7 @@ public final class Operations {
.executeExpectSuccess(AccountIdentityResponse.class);
user.setAciUuid(registrationResponse.uuid());
user.setPniUuid(registrationResponse.pni());
registrationResponse.pni().ifPresent(user::setPniUuid);
return user;
}
@@ -117,17 +131,21 @@ public final class Operations {
}
public static String peekVerificationSessionPushChallenge(final String sessionId) {
return INTEGRATION_TOOLS.peekVerificationSessionPushChallenge(sessionId).join()
return INTEGRATION_TOOLS.peekVerificationSessionPushChallenge(sessionId)
.orElseThrow(() -> new RuntimeException("push challenge not found for the verification session"));
}
public static byte[] populateRandomRecoveryPassword(final String number) {
final byte[] recoveryPassword = randomBytes(32);
INTEGRATION_TOOLS.populateRecoveryPassword(number, recoveryPassword).join();
INTEGRATION_TOOLS.populateRecoveryPassword(number, recoveryPassword);
return recoveryPassword;
}
public static void clearChangeNumberWaitingPeriod(final TestUser user) {
INTEGRATION_TOOLS.clearChangeNumberWaitingPeriod(user);
}
public static <T> T sendEmptyRequestAuthenticated(
final String endpoint,
final String method,
@@ -214,14 +232,10 @@ public final class Operations {
}
private static <R> RequestBuilder withJsonBody(final String endpoint, final String method, final R input) {
try {
final byte[] body = SystemMapper.jsonMapper().writeValueAsBytes(input);
return new RequestBuilder(HttpRequest.newBuilder()
.header(HttpHeaders.CONTENT_TYPE, "application/json")
.method(method, HttpRequest.BodyPublishers.ofByteArray(body)), endpoint);
} catch (final JsonProcessingException e) {
throw new RuntimeException(e);
}
final byte[] body = encodeJsonBody(input);
return new RequestBuilder(HttpRequest.newBuilder()
.header(HttpHeaders.CONTENT_TYPE, "application/json")
.method(method, HttpRequest.BodyPublishers.ofByteArray(body)), endpoint);
}
public RequestBuilder authorized(final TestUser user) {
@@ -301,6 +315,7 @@ public final class Operations {
})
.join();
}
}
private static FaultTolerantHttpClient buildClient() {
@@ -313,6 +328,53 @@ public final class Operations {
}
}
private static WebSocketClient buildWebSocketClient() {
try {
final KeyStore trustStore = CertificateUtil.buildKeyStoreForPem(CONFIG.rootCert());
final SslContextFactory.Client sslContextFactory = new SslContextFactory.Client();
sslContextFactory.setTrustStore(trustStore);
final ClientConnector connector = new ClientConnector();
connector.setSslContextFactory(sslContextFactory);
final HTTP2Client http2Client = new HTTP2Client(connector);
final HttpClient httpClient = new HttpClient(new HttpClientTransportOverHTTP2(http2Client));
final WebSocketClient wsClient = new WebSocketClient(httpClient);
wsClient.start();
return wsClient;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static WebsocketClientSession authenticatedWebsocket(final TestUser user, final byte deviceId) throws IOException {
final String username = "%s.%d".formatted(user.aciUuid().toString(), deviceId);
return connect("/v1/websocket/", Map.of(HttpHeaders.AUTHORIZATION, HeaderUtils.basicAuthHeader(username, user.accountPassword())));
}
public static WebsocketClientSession anonymousWebsocket() throws IOException {
return connect("/v1/websocket/", Collections.emptyMap());
}
private static WebsocketClientSession connect(
final String path,
final Map<String, String> headers) throws IOException {
final URI uri = URI.create("wss://grpc." + CONFIG.domain() + path);
final ClientUpgradeRequest request = new ClientUpgradeRequest(uri);
headers.forEach(request::setHeader);
final WebsocketClientSession listener = new WebsocketClientSession();
try {
WEB_SOCKET_CLIENT.connect(listener, request).get(5, TimeUnit.SECONDS);
} catch (Exception e) {
throw new IOException(e);
}
logger.info("Successfully connected to websocket on {}", uri);
return listener;
}
private static Config loadConfigFromClasspath(final String filename) {
try {
final URL configFileUrl = Resources.getResource(filename);
@@ -341,4 +403,12 @@ public final class Operations {
final byte[] signature = identityKeyPair.getPrivateKey().calculateSignature(pubKey.serialize());
return new KEMSignedPreKey(id, pubKey, signature);
}
public static <R> byte[] encodeJsonBody(final R input) {
try {
return SystemMapper.jsonMapper().writeValueAsBytes(input);
} catch (final JsonProcessingException e) {
throw new RuntimeException(e);
}
}
}
@@ -14,7 +14,7 @@ import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import org.signal.libsignal.protocol.IdentityKey;
@@ -26,6 +26,8 @@ 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 {
@@ -39,8 +41,10 @@ public class TestUser {
private final byte[] unidentifiedAccessKey;
@Nullable
private String phoneNumber;
@Nullable
private IdentityKeyPair pniIdentityKey;
private String accountPassword;
@@ -49,6 +53,7 @@ public class TestUser {
private UUID aciUuid;
@Nullable
private UUID pniUuid;
@@ -103,12 +108,12 @@ public class TestUser {
return aciIdentityKey;
}
public String phoneNumber() {
return phoneNumber;
public Optional<String> phoneNumber() {
return Optional.ofNullable(phoneNumber);
}
public IdentityKeyPair pniIdentityKey() {
return pniIdentityKey;
public Optional<IdentityKeyPair> pniIdentityKey() {
return Optional.ofNullable(pniIdentityKey);
}
public String accountPassword() {
@@ -123,29 +128,30 @@ public class TestUser {
return aciUuid;
}
public UUID pniUuid() {
return pniUuid;
public Optional<UUID> pniUuid() {
return Optional.ofNullable(pniUuid);
}
public AccountAttributes accountAttributes() {
return new AccountAttributes(true, registrationId, pniRegistrationId, "".getBytes(StandardCharsets.UTF_8), "", true, Set.of())
.withUnidentifiedAccessKey(unidentifiedAccessKey)
.withRecoveryPassword(registrationPassword);
return new AccountAttributes(true, registrationId, pniRegistrationId, "".getBytes(StandardCharsets.UTF_8), "", true,
DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES, null)
.setUnidentifiedAccessKey(unidentifiedAccessKey)
.setRecoveryPassword(registrationPassword);
}
public void setAciUuid(final UUID aciUuid) {
this.aciUuid = aciUuid;
}
public void setPniUuid(final UUID pniUuid) {
public void setPniUuid(@Nullable final UUID pniUuid) {
this.pniUuid = pniUuid;
}
public void setPhoneNumber(final String phoneNumber) {
public void setPhoneNumber(@Nullable final String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public void setPniIdentityKey(final IdentityKeyPair pniIdentityKey) {
public void setPniIdentityKey(@Nullable final IdentityKeyPair pniIdentityKey) {
this.pniIdentityKey = pniIdentityKey;
}
@@ -0,0 +1,150 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.signal.integration;
import com.google.protobuf.InvalidProtocolBufferException;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.ByteBuffer;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicLong;
import org.eclipse.jetty.websocket.api.Callback;
import org.eclipse.jetty.websocket.api.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.util.SystemMapper;
import org.whispersystems.websocket.messages.WebSocketMessage;
import org.whispersystems.websocket.messages.WebSocketMessageFactory;
import org.whispersystems.websocket.messages.WebSocketRequestMessage;
import org.whispersystems.websocket.messages.WebSocketResponseMessage;
import org.whispersystems.websocket.messages.protobuf.ProtobufWebSocketMessageFactory;
public class WebsocketClientSession implements Session.Listener.AutoDemanding {
private static final Logger log = LoggerFactory.getLogger(WebsocketClientSession.class);
private final WebSocketMessageFactory messageFactory = new ProtobufWebSocketMessageFactory();
private final AtomicLong requestId = new AtomicLong();
private final ConcurrentHashMap<Long, CompletableFuture<WebSocketResponseMessage>> responseFutures = new ConcurrentHashMap<>();
private final List<MessageProtos.Envelope> receivedEnvelopes = new CopyOnWriteArrayList<>();
private final CompletableFuture<Session> opened = new CompletableFuture<>();
private final CompletableFuture<Void> queueEmpty = new CompletableFuture<>();
private final CompletableFuture<Integer> closed = new CompletableFuture<>();
@Override
public void onWebSocketOpen(final Session session) {
opened.complete(session);
}
@Override
public void onWebSocketBinary(final ByteBuffer payload, final Callback callback) {
try {
final WebSocketMessage message = messageFactory.parseMessage(payload);
switch (message.getType()) {
case REQUEST_MESSAGE -> {
log.info("received request message {} {}", message.getRequestMessage().getVerb(), message.getRequestMessage().getPath());
switch (message.getRequestMessage().getPath()) {
case "/api/v1/message" -> acknowledge(message.getRequestMessage());
case "/api/v1/queue/empty" -> queueEmpty.complete(null);
default -> throw new IllegalStateException("Unexpected path: " + message.getRequestMessage().getPath());
}
}
case RESPONSE_MESSAGE -> {
final WebSocketResponseMessage response = message.getResponseMessage();
log.info("received response message {}", response.getStatus());
final CompletableFuture<WebSocketResponseMessage> future = responseFutures.remove(response.getRequestId());
if (future == null) {
throw new IllegalArgumentException("Received response with no matching request: " + response.getRequestId());
}
future.complete(response);
}
default -> throw new IllegalStateException("Unexpected message type: " + message.getType());
}
callback.succeed();
} catch (final Exception e) {
log.warn("Failed to process message received over the websocket", e);
callback.fail(e);
opened.join().close(1006, e.getMessage(), Callback.NOOP);
}
}
@Override
public void onWebSocketClose(final int statusCode, final String reason, final Callback callback) {
log.info("Received websocket close: {}", statusCode);
closed.complete(statusCode);
final IOException exception = new IOException("WebSocket closed: " + statusCode + " " + reason);
responseFutures.values()
.forEach(f -> f.completeExceptionally(exception));
responseFutures.clear();
if (!queueEmpty.isDone()) {
queueEmpty.completeExceptionally(exception);
}
callback.succeed();
}
public <T> WebSocketResponseMessage sendRequest(
final String verb,
final String path,
final List<String> headers,
final T body) {
final Session session = opened.join();
final long id = requestId.incrementAndGet();
final CompletableFuture<WebSocketResponseMessage> future = new CompletableFuture<>();
responseFutures.put(id, future);
final Optional<byte[]> maybeBody = Optional.ofNullable(body).map(Operations::encodeJsonBody);
final byte[] bytes = messageFactory.createRequest(Optional.of(id), verb, path, headers, maybeBody).toByteArray();
session.sendBinary(ByteBuffer.wrap(bytes), Callback.from(() -> {}, throwable -> {
if (responseFutures.remove(id) != null) {
future.completeExceptionally(throwable);
}
}));
return future.join();
}
public List<MessageProtos.Envelope> getReceivedEnvelopes() {
return receivedEnvelopes;
}
public void waitForQueueEmpty() {
queueEmpty.join();
}
public void close(final int closeCode) {
final Session session = opened.join();
session.close(closeCode, "client close", Callback.NOOP);
closed.join();
}
private void acknowledge(WebSocketRequestMessage message) {
final byte[] envelopeBytes = message.getBody()
.orElseThrow(() -> new IllegalStateException("Messages should have a response body"));
try {
final MessageProtos.Envelope envelope = MessageProtos.Envelope.parseFrom(envelopeBytes);
receivedEnvelopes.add(envelope);
final Session session = opened.join();
final WebSocketMessage response = messageFactory.createResponse(message.getRequestId(), 200, "",
Collections.emptyList(), Optional.empty());
session.sendBinary(ByteBuffer.wrap(response.toByteArray()), Callback.NOOP);
} catch (InvalidProtocolBufferException e) {
throw new IllegalStateException(e);
}
}
public static <R> R decode(Class<R> expectedType, WebSocketResponseMessage message) {
try {
return SystemMapper.jsonMapper()
.readValue(message.getBody().orElseThrow(() -> new IllegalStateException("No response body")), expectedType);
} catch (final IOException e) {
throw new UncheckedIOException(e);
}
}
}
@@ -9,5 +9,6 @@ import jakarta.validation.constraints.NotBlank;
public record DynamoDbTables(@NotBlank String registrationRecovery,
@NotBlank String verificationSessions,
@NotBlank String phoneNumberIdentifiers) {
@NotBlank String phoneNumberIdentifiers,
@NotBlank String changeNumberWaitingPeriods) {
}
@@ -13,6 +13,7 @@ import java.util.Base64;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.http.HttpStatus;
import org.junit.jupiter.api.Test;
@@ -45,19 +46,6 @@ public class AccountTest {
}
}
@Test
public void testCreateAccountAtomic() {
final TestUser user = Operations.newRegisteredUser("+19995550201");
try {
final Pair<Integer, AccountIdentityResponse> execute = Operations.apiGet("/v1/accounts/whoami")
.authorized(user)
.execute(AccountIdentityResponse.class);
assertEquals(HttpStatus.SC_OK, execute.getLeft());
} finally {
Operations.deleteUser(user);
}
}
@Test
public void changePhoneNumber() {
final TestUser user = Operations.newRegisteredUser("+19995550301");
@@ -75,14 +63,20 @@ public class AccountTest {
Map.of(Device.PRIMARY_ID, Operations.generateSignedKEMPreKey(2, pniIdentityKeyPair)),
Map.of(Device.PRIMARY_ID, 17));
final AccountIdentityResponse accountIdentityResponse =
Operations.apiPut("/v2/accounts/number", changeNumberRequest)
.authorized(user)
.executeExpectSuccess(AccountIdentityResponse.class);
try {
Operations.clearChangeNumberWaitingPeriod(user);
assertEquals(user.aciUuid(), accountIdentityResponse.uuid());
assertNotEquals(user.pniUuid(), accountIdentityResponse.pni());
assertEquals(targetNumber, accountIdentityResponse.number());
final AccountIdentityResponse accountIdentityResponse =
Operations.apiPut("/v2/accounts/number", changeNumberRequest)
.authorized(user)
.executeExpectSuccess(AccountIdentityResponse.class);
assertEquals(user.aciUuid(), accountIdentityResponse.uuid());
assertNotEquals(user.pniUuid(), accountIdentityResponse.pni());
assertEquals(Optional.of(targetNumber), accountIdentityResponse.number());
} finally {
Operations.deleteUser(user);
}
}
@Test
@@ -6,43 +6,68 @@
package org.signal.integration;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
import com.google.common.net.HttpHeaders;
import jakarta.ws.rs.core.MediaType;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.List;
import org.apache.commons.lang3.tuple.Pair;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import org.whispersystems.textsecuregcm.entities.IncomingMessage;
import org.whispersystems.textsecuregcm.entities.IncomingMessageList;
import org.whispersystems.textsecuregcm.entities.OutgoingMessageEntityList;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.entities.SendMessageResponse;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.websocket.messages.WebSocketResponseMessage;
@Timeout(value = 1, unit = TimeUnit.MINUTES, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
public class MessagingTest {
TestUser userA;
TestUser userB;
@BeforeEach
public void setup() {
userA = Operations.newRegisteredUser("+19995550102");
userB = Operations.newRegisteredUser("+19995550103");
}
@AfterEach
public void teardown() {
Operations.deleteUser(userA);
Operations.deleteUser(userB);
}
@Test
public void testSendMessageUnsealed() {
final TestUser userA = Operations.newRegisteredUser("+19995550102");
final TestUser userB = Operations.newRegisteredUser("+19995550103");
try {
public void testSendMessageUnsealed() throws IOException {
final byte[] expectedContent = "Hello, World!".getBytes(StandardCharsets.UTF_8);
final IncomingMessage message = new IncomingMessage(1, Device.PRIMARY_ID, userB.registrationId(), expectedContent);
final IncomingMessageList messages = new IncomingMessageList(List.of(message), false, true, System.currentTimeMillis());
Operations
.apiPut("/v1/messages/%s".formatted(userB.aciUuid().toString()), messages)
.authorized(userA)
.execute(SendMessageResponse.class);
final WebsocketClientSession websocketA = Operations.authenticatedWebsocket(userA, Device.PRIMARY_ID);
final WebSocketResponseMessage responseMessage = websocketA.sendRequest(
"PUT",
"/v1/messages/%s".formatted(userB.aciUuid().toString()),
List.of(HttpHeaders.CONTENT_TYPE + ":" + MediaType.APPLICATION_JSON),
messages);
assertEquals(200, responseMessage.getStatus());
assertDoesNotThrow(() -> WebsocketClientSession.decode(SendMessageResponse.class, responseMessage));
final Pair<Integer, OutgoingMessageEntityList> receiveMessages = Operations.apiGet("/v1/messages")
.authorized(userB)
.execute(OutgoingMessageEntityList.class);
final WebsocketClientSession websocketB = Operations.authenticatedWebsocket(userB, Device.PRIMARY_ID);
assertTimeoutPreemptively(Duration.ofSeconds(5), websocketB::waitForQueueEmpty);
final byte[] actualContent = receiveMessages.getRight().messages().getFirst().content();
assertArrayEquals(expectedContent, actualContent);
} finally {
Operations.deleteUser(userA);
Operations.deleteUser(userB);
}
assertEquals(1, websocketB.getReceivedEnvelopes().size());
final MessageProtos.Envelope envelope = websocketB.getReceivedEnvelopes().getFirst();
assertArrayEquals(expectedContent, envelope.getContent().toByteArray());
websocketB.close(1000);
websocketA.close(1000);
}
}
Vendored
+234 -247
View File
@@ -19,290 +19,277 @@
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Apache Maven Wrapper startup batch script, version 3.2.0
#
# Required ENV vars:
# ------------------
# JAVA_HOME - location of a JDK home dir
# Apache Maven Wrapper startup batch script, version 3.3.4
#
# Optional ENV vars
# -----------------
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
# e.g. to debug Maven itself, use
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
# JAVA_HOME - location of a JDK home dir, required when download maven via java source
# MVNW_REPOURL - repo url base for downloading maven distribution
# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output
# ----------------------------------------------------------------------------
if [ -z "$MAVEN_SKIP_RC" ] ; then
set -euf
[ "${MVNW_VERBOSE-}" != debug ] || set -x
if [ -f /usr/local/etc/mavenrc ] ; then
. /usr/local/etc/mavenrc
fi
if [ -f /etc/mavenrc ] ; then
. /etc/mavenrc
fi
if [ -f "$HOME/.mavenrc" ] ; then
. "$HOME/.mavenrc"
fi
fi
# OS specific support. $var _must_ be set to either true or false.
cygwin=false;
darwin=false;
mingw=false
# OS specific support.
native_path() { printf %s\\n "$1"; }
case "$(uname)" in
CYGWIN*) cygwin=true ;;
MINGW*) mingw=true;;
Darwin*) darwin=true
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
if [ -z "$JAVA_HOME" ]; then
if [ -x "/usr/libexec/java_home" ]; then
JAVA_HOME="$(/usr/libexec/java_home)"; export JAVA_HOME
else
JAVA_HOME="/Library/Java/Home"; export JAVA_HOME
fi
fi
;;
CYGWIN* | MINGW*)
[ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")"
native_path() { cygpath --path --windows "$1"; }
;;
esac
if [ -z "$JAVA_HOME" ] ; then
if [ -r /etc/gentoo-release ] ; then
JAVA_HOME=$(java-config --jre-home)
fi
fi
# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin ; then
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=$(cygpath --unix "$JAVA_HOME")
[ -n "$CLASSPATH" ] &&
CLASSPATH=$(cygpath --path --unix "$CLASSPATH")
fi
# For Mingw, ensure paths are in UNIX format before anything is touched
if $mingw ; then
[ -n "$JAVA_HOME" ] && [ -d "$JAVA_HOME" ] &&
JAVA_HOME="$(cd "$JAVA_HOME" || (echo "cannot cd into $JAVA_HOME."; exit 1); pwd)"
fi
if [ -z "$JAVA_HOME" ]; then
javaExecutable="$(which javac)"
if [ -n "$javaExecutable" ] && ! [ "$(expr "\"$javaExecutable\"" : '\([^ ]*\)')" = "no" ]; then
# readlink(1) is not available as standard on Solaris 10.
readLink=$(which readlink)
if [ ! "$(expr "$readLink" : '\([^ ]*\)')" = "no" ]; then
if $darwin ; then
javaHome="$(dirname "\"$javaExecutable\"")"
javaExecutable="$(cd "\"$javaHome\"" && pwd -P)/javac"
else
javaExecutable="$(readlink -f "\"$javaExecutable\"")"
fi
javaHome="$(dirname "\"$javaExecutable\"")"
javaHome=$(expr "$javaHome" : '\(.*\)/bin')
JAVA_HOME="$javaHome"
export JAVA_HOME
fi
fi
fi
if [ -z "$JAVACMD" ] ; then
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# set JAVACMD and JAVACCMD
set_java_home() {
# For Cygwin and MinGW, ensure paths are in Unix format before anything is touched
if [ -n "${JAVA_HOME-}" ]; then
if [ -x "$JAVA_HOME/jre/sh/java" ]; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
JAVACCMD="$JAVA_HOME/jre/sh/javac"
else
JAVACMD="$JAVA_HOME/bin/java"
JAVACCMD="$JAVA_HOME/bin/javac"
if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then
echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2
echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2
return 1
fi
fi
else
JAVACMD="$(\unset -f command 2>/dev/null; \command -v java)"
fi
fi
JAVACMD="$(
'set' +e
'unset' -f command 2>/dev/null
'command' -v java
)" || :
JAVACCMD="$(
'set' +e
'unset' -f command 2>/dev/null
'command' -v javac
)" || :
if [ ! -x "$JAVACMD" ] ; then
echo "Error: JAVA_HOME is not defined correctly." >&2
echo " We cannot execute $JAVACMD" >&2
exit 1
fi
if [ -z "$JAVA_HOME" ] ; then
echo "Warning: JAVA_HOME environment variable is not set."
fi
# traverses directory structure from process work directory to filesystem root
# first directory with .mvn subdirectory is considered project base directory
find_maven_basedir() {
if [ -z "$1" ]
then
echo "Path not specified to find_maven_basedir"
return 1
fi
basedir="$1"
wdir="$1"
while [ "$wdir" != '/' ] ; do
if [ -d "$wdir"/.mvn ] ; then
basedir=$wdir
break
if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then
echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2
return 1
fi
# workaround for JBEAP-8937 (on Solaris 10/Sparc)
if [ -d "${wdir}" ]; then
wdir=$(cd "$wdir/.." || exit 1; pwd)
fi
# end of workaround
fi
}
# hash string like Java String::hashCode
hash_string() {
str="${1:-}" h=0
while [ -n "$str" ]; do
char="${str%"${str#?}"}"
h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296))
str="${str#?}"
done
printf '%s' "$(cd "$basedir" || exit 1; pwd)"
printf %x\\n $h
}
# concatenates all lines of a file
concat_lines() {
if [ -f "$1" ]; then
# Remove \r in case we run on Windows within Git Bash
# and check out the repository with auto CRLF management
# enabled. Otherwise, we may read lines that are delimited with
# \r\n and produce $'-Xarg\r' rather than -Xarg due to word
# splitting rules.
tr -s '\r\n' ' ' < "$1"
fi
verbose() { :; }
[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; }
die() {
printf %s\\n "$1" >&2
exit 1
}
log() {
if [ "$MVNW_VERBOSE" = true ]; then
printf '%s\n' "$1"
fi
trim() {
# MWRAPPER-139:
# Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds.
# Needed for removing poorly interpreted newline sequences when running in more
# exotic environments such as mingw bash on Windows.
printf "%s" "${1}" | tr -d '[:space:]'
}
BASE_DIR=$(find_maven_basedir "$(dirname "$0")")
if [ -z "$BASE_DIR" ]; then
exit 1;
fi
scriptDir="$(dirname "$0")"
scriptName="$(basename "$0")"
MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}; export MAVEN_PROJECTBASEDIR
log "$MAVEN_PROJECTBASEDIR"
##########################################################################################
# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
# This allows using the maven wrapper in projects that prohibit checking in binary data.
##########################################################################################
wrapperJarPath="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar"
if [ -r "$wrapperJarPath" ]; then
log "Found $wrapperJarPath"
else
log "Couldn't find $wrapperJarPath, downloading it ..."
if [ -n "$MVNW_REPOURL" ]; then
wrapperUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar"
else
wrapperUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar"
fi
while IFS="=" read -r key value; do
# Remove '\r' from value to allow usage on windows as IFS does not consider '\r' as a separator ( considers space, tab, new line ('\n'), and custom '=' )
safeValue=$(echo "$value" | tr -d '\r')
case "$key" in (wrapperUrl) wrapperUrl="$safeValue"; break ;;
esac
done < "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.properties"
log "Downloading from: $wrapperUrl"
if $cygwin; then
wrapperJarPath=$(cygpath --path --windows "$wrapperJarPath")
fi
if command -v wget > /dev/null; then
log "Found wget ... using wget"
[ "$MVNW_VERBOSE" = true ] && QUIET="" || QUIET="--quiet"
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
wget $QUIET "$wrapperUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath"
else
wget $QUIET --http-user="$MVNW_USERNAME" --http-password="$MVNW_PASSWORD" "$wrapperUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath"
fi
elif command -v curl > /dev/null; then
log "Found curl ... using curl"
[ "$MVNW_VERBOSE" = true ] && QUIET="" || QUIET="--silent"
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
curl $QUIET -o "$wrapperJarPath" "$wrapperUrl" -f -L || rm -f "$wrapperJarPath"
else
curl $QUIET --user "$MVNW_USERNAME:$MVNW_PASSWORD" -o "$wrapperJarPath" "$wrapperUrl" -f -L || rm -f "$wrapperJarPath"
fi
else
log "Falling back to using Java to download"
javaSource="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/MavenWrapperDownloader.java"
javaClass="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/MavenWrapperDownloader.class"
# For Cygwin, switch paths to Windows format before running javac
if $cygwin; then
javaSource=$(cygpath --path --windows "$javaSource")
javaClass=$(cygpath --path --windows "$javaClass")
fi
if [ -e "$javaSource" ]; then
if [ ! -e "$javaClass" ]; then
log " - Compiling MavenWrapperDownloader.java ..."
("$JAVA_HOME/bin/javac" "$javaSource")
fi
if [ -e "$javaClass" ]; then
log " - Running MavenWrapperDownloader.java ..."
("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$wrapperUrl" "$wrapperJarPath") || rm -f "$wrapperJarPath"
fi
fi
fi
fi
##########################################################################################
# End of extension
##########################################################################################
# If specified, validate the SHA-256 sum of the Maven wrapper jar file
wrapperSha256Sum=""
# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties
while IFS="=" read -r key value; do
case "$key" in (wrapperSha256Sum) wrapperSha256Sum=$value; break ;;
case "${key-}" in
distributionUrl) distributionUrl=$(trim "${value-}") ;;
distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;;
esac
done < "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.properties"
if [ -n "$wrapperSha256Sum" ]; then
wrapperSha256Result=false
if command -v sha256sum > /dev/null; then
if echo "$wrapperSha256Sum $wrapperJarPath" | sha256sum -c - > /dev/null 2>&1; then
wrapperSha256Result=true
done <"$scriptDir/.mvn/wrapper/maven-wrapper.properties"
[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
case "${distributionUrl##*/}" in
maven-mvnd-*bin.*)
MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/
case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in
*AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;;
:Darwin*x86_64) distributionPlatform=darwin-amd64 ;;
:Darwin*arm64) distributionPlatform=darwin-aarch64 ;;
:Linux*x86_64*) distributionPlatform=linux-amd64 ;;
*)
echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2
distributionPlatform=linux-amd64
;;
esac
distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip"
;;
maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;;
*) MVN_CMD="mvn${scriptName#mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;;
esac
# apply MVNW_REPOURL and calculate MAVEN_HOME
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}"
distributionUrlName="${distributionUrl##*/}"
distributionUrlNameMain="${distributionUrlName%.*}"
distributionUrlNameMain="${distributionUrlNameMain%-bin}"
MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}"
MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")"
exec_maven() {
unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || :
exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD"
}
if [ -d "$MAVEN_HOME" ]; then
verbose "found existing MAVEN_HOME at $MAVEN_HOME"
exec_maven "$@"
fi
case "${distributionUrl-}" in
*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;;
*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;;
esac
# prepare tmp dir
if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then
clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; }
trap clean HUP INT TERM EXIT
else
die "cannot create temp dir"
fi
mkdir -p -- "${MAVEN_HOME%/*}"
# Download and Install Apache Maven
verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
verbose "Downloading from: $distributionUrl"
verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
# select .zip or .tar.gz
if ! command -v unzip >/dev/null; then
distributionUrl="${distributionUrl%.zip}.tar.gz"
distributionUrlName="${distributionUrl##*/}"
fi
# verbose opt
__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR=''
[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v
# normalize http auth
case "${MVNW_PASSWORD:+has-password}" in
'') MVNW_USERNAME='' MVNW_PASSWORD='' ;;
has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;;
esac
if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then
verbose "Found wget ... using wget"
wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl"
elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then
verbose "Found curl ... using curl"
curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl"
elif set_java_home; then
verbose "Falling back to use Java to download"
javaSource="$TMP_DOWNLOAD_DIR/Downloader.java"
targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName"
cat >"$javaSource" <<-END
public class Downloader extends java.net.Authenticator
{
protected java.net.PasswordAuthentication getPasswordAuthentication()
{
return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() );
}
public static void main( String[] args ) throws Exception
{
setDefault( new Downloader() );
java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() );
}
}
END
# For Cygwin/MinGW, switch paths to Windows format before running javac and java
verbose " - Compiling Downloader.java ..."
"$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java"
verbose " - Running Downloader.java ..."
"$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")"
fi
# If specified, validate the SHA-256 sum of the Maven distribution zip file
if [ -n "${distributionSha256Sum-}" ]; then
distributionSha256Result=false
if [ "$MVN_CMD" = mvnd.sh ]; then
echo "Checksum validation is not supported for maven-mvnd." >&2
echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
exit 1
elif command -v sha256sum >/dev/null; then
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c - >/dev/null 2>&1; then
distributionSha256Result=true
fi
elif command -v shasum > /dev/null; then
if echo "$wrapperSha256Sum $wrapperJarPath" | shasum -a 256 -c > /dev/null 2>&1; then
wrapperSha256Result=true
elif command -v shasum >/dev/null; then
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then
distributionSha256Result=true
fi
else
echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available."
echo "Please install either command, or disable validation by removing 'wrapperSha256Sum' from your maven-wrapper.properties."
echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2
echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
exit 1
fi
if [ $wrapperSha256Result = false ]; then
echo "Error: Failed to validate Maven wrapper SHA-256, your Maven wrapper might be compromised." >&2
echo "Investigate or delete $wrapperJarPath to attempt a clean download." >&2
echo "If you updated your Maven version, you need to update the specified wrapperSha256Sum property." >&2
if [ $distributionSha256Result = false ]; then
echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2
echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2
exit 1
fi
fi
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=$(cygpath --path --windows "$JAVA_HOME")
[ -n "$CLASSPATH" ] &&
CLASSPATH=$(cygpath --path --windows "$CLASSPATH")
[ -n "$MAVEN_PROJECTBASEDIR" ] &&
MAVEN_PROJECTBASEDIR=$(cygpath --path --windows "$MAVEN_PROJECTBASEDIR")
# unzip and move
if command -v unzip >/dev/null; then
unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip"
else
tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar"
fi
# Provide a "standardized" way to retrieve the CLI args that will
# work with both Windows and non-Windows executions.
MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $*"
export MAVEN_CMD_LINE_ARGS
# Find the actual extracted directory name (handles snapshots where filename != directory name)
actualDistributionDir=""
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
# First try the expected directory name (for regular distributions)
if [ -d "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" ]; then
if [ -f "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/bin/$MVN_CMD" ]; then
actualDistributionDir="$distributionUrlNameMain"
fi
fi
# shellcheck disable=SC2086 # safe args
exec "$JAVACMD" \
$MAVEN_OPTS \
$MAVEN_DEBUG_OPTS \
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
"-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"
# If not found, search for any directory with the Maven executable (for snapshots)
if [ -z "$actualDistributionDir" ]; then
# enable globbing to iterate over items
set +f
for dir in "$TMP_DOWNLOAD_DIR"/*; do
if [ -d "$dir" ]; then
if [ -f "$dir/bin/$MVN_CMD" ]; then
actualDistributionDir="$(basename "$dir")"
break
fi
fi
done
set -f
fi
if [ -z "$actualDistributionDir" ]; then
verbose "Contents of $TMP_DOWNLOAD_DIR:"
verbose "$(ls -la "$TMP_DOWNLOAD_DIR")"
die "Could not find Maven distribution directory in extracted archive"
fi
verbose "Found extracted Maven distribution directory: $actualDistributionDir"
printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$actualDistributionDir/mvnw.url"
mv -- "$TMP_DOWNLOAD_DIR/$actualDistributionDir" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME"
clean || :
exec_maven "$@"
Vendored
+154 -170
View File
@@ -1,3 +1,4 @@
<# : batch portion
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@@ -7,7 +8,7 @@
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM http://www.apache.org/licenses/LICENSE-2.0
@REM https://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@@ -18,188 +19,171 @@
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Apache Maven Wrapper startup batch script, version 3.2.0
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM Apache Maven Wrapper startup batch script, version 3.3.4
@REM
@REM Optional ENV vars
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM MVNW_REPOURL - repo url base for downloading maven distribution
@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM set title of command window
title %0
@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %*
if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %*
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
set WRAPPER_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar"
FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperUrl" SET WRAPPER_URL=%%B
@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0)
@SET __MVNW_CMD__=
@SET __MVNW_ERROR__=
@SET __MVNW_PSMODULEP_SAVE=%PSModulePath%
@SET PSModulePath=
@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @(
IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B)
)
@SET PSModulePath=%__MVNW_PSMODULEP_SAVE%
@SET __MVNW_PSMODULEP_SAVE=
@SET __MVNW_ARG0_NAME__=
@SET MVNW_USERNAME=
@SET MVNW_PASSWORD=
@IF NOT "%__MVNW_CMD__%"=="" ("%__MVNW_CMD__%" %*)
@echo Cannot start maven from wrapper >&2 && exit /b 1
@GOTO :EOF
: end batch / begin powershell #>
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
if exist %WRAPPER_JAR% (
if "%MVNW_VERBOSE%" == "true" (
echo Found %WRAPPER_JAR%
)
) else (
if not "%MVNW_REPOURL%" == "" (
SET WRAPPER_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar"
)
if "%MVNW_VERBOSE%" == "true" (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %WRAPPER_URL%
)
$ErrorActionPreference = "Stop"
if ($env:MVNW_VERBOSE -eq "true") {
$VerbosePreference = "Continue"
}
powershell -Command "&{"^
"$webclient = new-object System.Net.WebClient;"^
"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
"}"^
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%WRAPPER_URL%', '%WRAPPER_JAR%')"^
"}"
if "%MVNW_VERBOSE%" == "true" (
echo Finished downloading %WRAPPER_JAR%
)
)
@REM End of extension
# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties
$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl
if (!$distributionUrl) {
Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
}
@REM If specified, validate the SHA-256 sum of the Maven wrapper jar file
SET WRAPPER_SHA_256_SUM=""
FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperSha256Sum" SET WRAPPER_SHA_256_SUM=%%B
)
IF NOT %WRAPPER_SHA_256_SUM%=="" (
powershell -Command "&{"^
"$hash = (Get-FileHash \"%WRAPPER_JAR%\" -Algorithm SHA256).Hash.ToLower();"^
"If('%WRAPPER_SHA_256_SUM%' -ne $hash){"^
" Write-Output 'Error: Failed to validate Maven wrapper SHA-256, your Maven wrapper might be compromised.';"^
" Write-Output 'Investigate or delete %WRAPPER_JAR% to attempt a clean download.';"^
" Write-Output 'If you updated your Maven version, you need to update the specified wrapperSha256Sum property.';"^
" exit 1;"^
"}"^
"}"
if ERRORLEVEL 1 goto error
)
switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) {
"maven-mvnd-*" {
$USE_MVND = $true
$distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip"
$MVN_CMD = "mvnd.cmd"
break
}
default {
$USE_MVND = $false
$MVN_CMD = $script -replace '^mvnw','mvn'
break
}
}
@REM Provide a "standardized" way to retrieve the CLI args that will
@REM work with both Windows and non-Windows executions.
set MAVEN_CMD_LINE_ARGS=%*
# apply MVNW_REPOURL and calculate MAVEN_HOME
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
if ($env:MVNW_REPOURL) {
$MVNW_REPO_PATTERN = if ($USE_MVND -eq $False) { "/org/apache/maven/" } else { "/maven/mvnd/" }
$distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace "^.*$MVNW_REPO_PATTERN",'')"
}
$distributionUrlName = $distributionUrl -replace '^.*/',''
$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$',''
%MAVEN_JAVA_EXE% ^
%JVM_CONFIG_MAVEN_PROPS% ^
%MAVEN_OPTS% ^
%MAVEN_DEBUG_OPTS% ^
-classpath %WRAPPER_JAR% ^
"-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^
%WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end
$MAVEN_M2_PATH = "$HOME/.m2"
if ($env:MAVEN_USER_HOME) {
$MAVEN_M2_PATH = "$env:MAVEN_USER_HOME"
}
:error
set ERROR_CODE=1
if (-not (Test-Path -Path $MAVEN_M2_PATH)) {
New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null
}
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
$MAVEN_WRAPPER_DISTS = $null
if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) {
$MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists"
} else {
$MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists"
}
if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat"
if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd"
:skipRcPost
$MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain"
$MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join ''
$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME"
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%"=="on" pause
if (Test-Path -Path "$MAVEN_HOME" -PathType Container) {
Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME"
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
exit $?
}
if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE%
if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) {
Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl"
}
cmd /C exit /B %ERROR_CODE%
# prepare tmp dir
$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile
$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir"
$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null
trap {
if ($TMP_DOWNLOAD_DIR.Exists) {
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
}
}
New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null
# Download and Install Apache Maven
Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
Write-Verbose "Downloading from: $distributionUrl"
Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
$webclient = New-Object System.Net.WebClient
if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) {
$webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD)
}
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null
# If specified, validate the SHA-256 sum of the Maven distribution zip file
$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum
if ($distributionSha256Sum) {
if ($USE_MVND) {
Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties."
}
Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash
if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) {
Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property."
}
}
# unzip and move
Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null
# Find the actual extracted directory name (handles snapshots where filename != directory name)
$actualDistributionDir = ""
# First try the expected directory name (for regular distributions)
$expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain"
$expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD"
if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) {
$actualDistributionDir = $distributionUrlNameMain
}
# If not found, search for any directory with the Maven executable (for snapshots)
if (!$actualDistributionDir) {
Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object {
$testPath = Join-Path $_.FullName "bin/$MVN_CMD"
if (Test-Path -Path $testPath -PathType Leaf) {
$actualDistributionDir = $_.Name
}
}
}
if (!$actualDistributionDir) {
Write-Error "Could not find Maven distribution directory in extracted archive"
}
Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir"
Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -NewName $MAVEN_HOME_NAME | Out-Null
try {
Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null
} catch {
if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) {
Write-Error "fail to move MAVEN_HOME"
}
} finally {
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
}
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
+69 -73
View File
@@ -14,6 +14,14 @@
<enabled>false</enabled>
</snapshots>
</repository>
<repository>
<id>signal-build-artifacts</id>
<name>Signal Build Artifacts</name>
<url>https://build-artifacts.signal.org/libraries/maven</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
@@ -37,60 +45,57 @@
</modules>
<properties>
<aws.sdk2.version>2.33.8</aws.sdk2.version>
<braintree.version>3.44.0</braintree.version>
<aws.sdk2.version>2.42.27</aws.sdk2.version>
<braintree.version>3.48.0</braintree.version>
<commons-csv.version>1.14.1</commons-csv.version>
<commons-io.version>2.20.0</commons-io.version>
<dropwizard.version>4.0.16</dropwizard.version>
<!-- Note: when updating FoundationDB, also include a copy of `libfdb_c.so` from the FoundationDB release at
src/main/jib/usr/lib/libfdb_c.so. We use x86_64 builds without AVX instructions enabled (i.e. FoundationDB versions
with even-numbered patch versions). Also when updating FoundationDB, make sure to update the version of FoundationDB
used by GitHub Actions. -->
<foundationdb.version>7.3.62</foundationdb.version>
<commons-io.version>2.21.0</commons-io.version>
<dropwizard.version>5.0.1</dropwizard.version>
<!-- Note: We use x86_64 builds without AVX instructions enabled (i.e. FoundationDB versions with even-numbered
patch versions). Also when updating FoundationDB, make sure to update the version of FoundationDBused by GitHub
Actions. -->
<foundationdb.version>7.3.68</foundationdb.version>
<foundationdb.api-version>730</foundationdb.api-version>
<foundationdb.client-library-sha256>bfed237b787fae3cde1222676e6bfbb0d218fc27bf9e903397a7a7aa96fb2d33</foundationdb.client-library-sha256>
<google-cloud-libraries.version>26.67.0</google-cloud-libraries.version>
<grpc.version>1.73.0</grpc.version> <!-- should be kept in sync with the value from Google libraries-bom -->
<foundationdb.client-library-sha256>8c96a1f7ab561cd38e16e4c269c5e50ae0fd8063854e0d72c89339a7ac1b6873</foundationdb.client-library-sha256>
<google-cloud-libraries.version>26.79.0</google-cloud-libraries.version>
<grpc.version>1.76.3</grpc.version> <!-- should be kept in sync with the value from Google libraries-bom -->
<gson.version>2.13.2</gson.version>
<guava.version>33.5.0-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>
<jackson.version>2.20.0</jackson.version>
<jackson.version>2.21.2</jackson.version>
<junit-pioneer.version>2.3.0</junit-pioneer.version>
<jsr305.version>3.0.2</jsr305.version>
<kotlin.version>2.2.20</kotlin.version>
<!-- Logback 1.5.14+ has a null pointer bug: https://github.com/qos-ch/logback/issues/929. -->
<logback.version>1.5.13</logback.version>
<logback-access-common.version>2.0.6</logback-access-common.version>
<lettuce.version>6.8.1.RELEASE</lettuce.version>
<libphonenumber.version>9.0.13</libphonenumber.version>
<kotlin.version>2.3.20</kotlin.version>
<logback.version>1.5.38</logback.version>
<logback-access-common.version>2.0.12</logback-access-common.version>
<lettuce.version>7.5.1.RELEASE</lettuce.version>
<libphonenumber.version>9.0.21</libphonenumber.version>
<logstash.logback.version>8.1</logstash.logback.version>
<log4j-bom.version>2.25.1</log4j-bom.version>
<log4j-bom.version>2.25.4</log4j-bom.version>
<luajava.version>3.5.0</luajava.version>
<micrometer.version>1.15.4</micrometer.version>
<netty.version>4.1.127.Final</netty.version>
<micrometer.version>1.16.4</micrometer.version>
<netty.version>4.2.13.Final</netty.version>
<!-- Must be less than or equal to the value from Google libraries-bom which controls the protobuf runtime version.
See https://protobuf.dev/support/cross-version-runtime-guarantee/. -->
<protoc.version>4.29.4</protoc.version>
<protoc.version>4.33.2</protoc.version>
<pushy.version>0.15.4</pushy.version>
<reactive.grpc.version>1.2.4</reactive.grpc.version>
<reactor-bom.version>2024.0.10</reactor-bom.version> <!-- 3.7.11, see https://github.com/reactor/reactor#bom-versioning-scheme -->
<resilience4j.version>2.3.0</resilience4j.version>
<reactor-bom.version>2025.0.4</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.1.0</simple-grpc.version>
<simple-grpc.version>0.2.0</simple-grpc.version>
<slf4j.version>2.0.17</slf4j.version>
<stripe.version>30.2.0</stripe.version>
<swagger.version>2.2.36</swagger.version>
<testcontainers.version>1.21.3</testcontainers.version>
<stripe.version>33.1.0</stripe.version>
<swagger.version>2.2.46</swagger.version>
<testcontainers.version>2.0.4</testcontainers.version>
<!-- images to use in tests via testcontainers -->
<dynamodb.image>amazon/dynamodb-local:3.0.0@sha256:2fed5e3a965a4ba5aa6ac82baec57058b5a3848e959d705518f3fd579a77e76b</dynamodb.image>
<localstack.image>localstack/localstack:4@sha256:5a97e0f9917a3f0d9630bb13b9d8ccf10cbe52f33252807d3b4e21418cc21348</localstack.image>
<redis.image>redis:7.4-alpine@sha256:af1d0fc3f63b02b13ff7906c9baf7c5b390b8881ca08119cd570677fe2f60b55</redis.image>
<dynamodb.image>amazon/dynamodb-local:3.3.0@sha256:d89f8fcc6b1a39cb35976c248ed42a28c66ae00dc043099210f5571e42648ab4</dynamodb.image>
<localstack.image>localstack/localstack:4.14@sha256:3ebc37595918b8accb852f8048fef2aff047d465167edd655528065b07bc364a</localstack.image>
<redis.image>redis:7.4-alpine@sha256:6ab0b6e7381779332f97b8ca76193e45b0756f38d4c0dcda72dbb3c32061ab99</redis.image>
<redis-cluster.image>docker.io/bitnamilegacy/redis-cluster:7.4.3@sha256:a53d023fdfaf8a8d7ddc58da040d3494e4cb45772644618ffa44c42dcd32b9af</redis-cluster.image>
<!-- eclipse-temurin:24.0.2_12-jre-noble (note: always use the multi-arch manifest *LIST* here) -->
<docker.image.sha256>85ecfc9bbb42af046d2bacbf1219d2005be4840cbfa16c2e6fd910d9ccfec95b</docker.image.sha256>
<docker.image>eclipse-temurin:25-jre-resolute@sha256:17ddcc32b1f296155738c4b2f689208e46bf0cf4eb0b215c717717deb8b74b90</docker.image>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
@@ -143,11 +148,6 @@
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>com.salesforce.servicelibs</groupId>
<artifactId>reactor-grpc-stub</artifactId>
<version>${reactive.grpc.version}</version>
</dependency>
<dependency>
<groupId>io.github.resilience4j</groupId>
<artifactId>resilience4j-bom</artifactId>
@@ -165,14 +165,14 @@
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-bom</artifactId>
<version>1.54.0</version>
<version>1.60.1</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>io.opentelemetry.instrumentation</groupId>
<artifactId>opentelemetry-instrumentation-bom</artifactId>
<version>2.20.0</version>
<version>2.26.1</version>
<type>pom</type>
<scope>import</scope>
</dependency>
@@ -249,13 +249,7 @@
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.3.5</version>
</dependency>
<dependency>
<groupId>org.ow2.asm</groupId>
<artifactId>asm</artifactId>
<version>9.8</version>
<scope>test</scope>
<version>1.3.6</version>
</dependency>
<dependency>
<groupId>com.stripe</groupId>
@@ -277,6 +271,11 @@
<artifactId>gson</artifactId>
<version>${gson.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>com.redis</groupId>
<artifactId>testcontainers-redis</artifactId>
@@ -286,7 +285,7 @@
<dependency>
<groupId>org.signal</groupId>
<artifactId>libsignal-server</artifactId>
<version>0.80.3</version>
<version>0.100.0</version>
</dependency>
<dependency>
<groupId>org.signal</groupId>
@@ -354,7 +353,7 @@
</dependency>
<dependency>
<groupId>org.wiremock</groupId>
<artifactId>wiremock</artifactId>
<artifactId>wiremock-jetty12</artifactId>
<version>3.13.1</version>
<scope>test</scope>
</dependency>
@@ -363,6 +362,11 @@
<artifactId>mockito-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
@@ -410,7 +414,7 @@
<extension>
<groupId>kr.motd.maven</groupId>
<artifactId>os-maven-plugin</artifactId>
<version>1.7.0</version>
<version>1.7.1</version>
</extension>
</extensions>
<pluginManagement>
@@ -418,27 +422,27 @@
<plugin>
<groupId>com.google.cloud.tools</groupId>
<artifactId>jib-maven-plugin</artifactId>
<version>3.4.4</version>
<version>3.4.6</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.5.2</version>
<version>3.5.5</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<version>3.5.2</version>
<version>3.5.4</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.4.2</version>
<version>3.5.0</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.6.0</version>
<version>3.6.1</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
@@ -448,7 +452,7 @@
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>3.1.0</version>
<version>3.6.3</version>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
@@ -470,14 +474,6 @@
<pluginArtifact>io.grpc:protoc-gen-grpc-java:${grpc.version}:exe:${os.detected.classifier}</pluginArtifact>
<protocPlugins>
<protocPlugin>
<id>reactor-grpc</id>
<groupId>com.salesforce.servicelibs</groupId>
<artifactId>reactor-grpc</artifactId>
<version>${reactive.grpc.version}</version>
<mainClass>com.salesforce.reactorgrpc.ReactorGrpcGenerator</mainClass>
</protocPlugin>
<protocPlugin>
<id>simple</id>
<groupId>org.signal</groupId>
@@ -502,16 +498,16 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.13.0</version>
<version>3.15.0</version>
<configuration>
<release>24</release>
<release>25</release>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.4.2</version>
<version>3.5.0</version>
<configuration>
<archive>
<manifest>
@@ -524,7 +520,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>3.8.1</version>
<version>3.10.0</version>
<executions>
<execution>
<!--
@@ -544,7 +540,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-enforcer-plugin</artifactId>
<version>3.5.0</version>
<version>3.6.2</version>
<executions>
<execution>
<goals>
@@ -565,7 +561,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-install-plugin</artifactId>
<version>3.1.3</version>
<version>3.1.4</version>
<configuration>
<skip>true</skip>
</configuration>
@@ -574,7 +570,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId>
<version>3.1.3</version>
<version>3.1.4</version>
<configuration>
<skip>true</skip>
</configuration>
+6 -5
View File
@@ -4,9 +4,6 @@ stripe.idempotencyKeyGenerator: abcdefg12345678= # base64 for creating request i
braintree.publicKey: unset
braintree.privateKey: unset
googlePlayBilling.credentialsJson: |
{ "json": true }
appleAppStore.encodedKey: unset
directoryV2.client.userAuthenticationTokenSharedSecret: abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG= # base64-encoded secret shared with CDS to generate auth tokens for Signal users
@@ -82,9 +79,8 @@ storageService.userAuthenticationTokenSharedSecret: AAAAAAAAAAAAAAAAAAAAAAAAAAAA
zkConfig-libsignal-0.42.serverSecret: ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdef
genericZkConfig.serverSecret: ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzAA==
callingZkConfig.serverSecret: ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzAA==
backupsZkConfig.serverSecret: ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzAA==
chatZkConfig.serverSecret: ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzAA==
paymentsService.userAuthenticationTokenSharedSecret: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= # base64-encoded 32-byte secret shared with MobileCoin services used to generate auth tokens for Signal users
paymentsService.fixerApiKey: unset
@@ -100,3 +96,8 @@ turn.cloudflare.apiToken: ABCDEFGHIJKLM
linkDevice.secret: AAAAAAAAAAA=
tlsKeyStore.password: unset
hlrLookup.apiKey: AAAAAAAAAAA
hlrLookup.apiSecret: AAAAAAAAAAA
foundationDbMessages.versionstampCipherKey.0: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=
+63 -20
View File
@@ -48,7 +48,10 @@ braintree:
}
googlePlayBilling:
credentialsJson: secret://googlePlayBilling.credentialsJson
credentialsJson: |
{
"credential": "configuration"
}
packageName: package.name
applicationName: test
productIdToLevel: {}
@@ -71,7 +74,6 @@ appleDeviceCheck:
deviceCheck:
backupRedemptionDuration: P30D
backupRedemptionLevel: 201
dynamoDbClient:
region: us-west-2 # AWS Region
@@ -89,17 +91,21 @@ dynamoDbTables:
tableName: Example_AppleDeviceCheckPublicKeys
backups:
tableName: Example_Backups
changeNumberWaitingPeriods:
tableName: Example_ChangeNumberWaitingPeriods
clientReleases:
tableName: Example_ClientReleases
deletedAccounts:
tableName: Example_DeletedAccounts
deletedAccountsLock:
tableName: Example_DeletedAccountsLock
donationPermits:
tableName: Example_DonationPermits
expiration: P7D # Duration of time until rows expire
issuedReceipts:
tableName: Example_IssuedReceipts
expiration: P30D # Duration of time until rows expire
generator: abcdefg12345678= # random base64-encoded binary sequence
maxIssuedReceiptsPerPaymentId:
maxReceiptsPerSubscriptionPayment:
STRIPE: 1
BRAINTREE: 1
GOOGLE_PLAY_BILLING: 1
@@ -108,8 +114,6 @@ dynamoDbTables:
tableName: Example_Keys
ecSignedPreKeys:
tableName: Example_EC_Signed_Pre_Keys
pqKeys:
tableName: Example_PQ_Keys
pagedPqKeys:
tableName: Example_PQ_Paged_Keys
pqLastResortKeys:
@@ -122,8 +126,12 @@ dynamoDbTables:
expiration: P90D
phoneNumberIdentifiers:
tableName: Example_PhoneNumberIdentifiers
profileAvatars:
tableName: Example_ProfileAvatars
profiles:
tableName: Example_Profiles
profilesV2:
tableName: Example_ProfilesV2
pushChallenge:
tableName: Example_PushChallenge
pushNotificationExperimentSamples:
@@ -143,8 +151,6 @@ dynamoDbTables:
expiration: P7D
subscriptions:
tableName: Example_Subscriptions
clientPublicKeys:
tableName: Example_ClientPublicKeys
verificationSessions:
tableName: Example_VerificationSessions
@@ -230,10 +236,13 @@ messageCache: # Redis server configuration for message store cache
cluster:
configurationUri: redis://redis.example.com:6379/
attachments:
maxAttachmentUploadSizeInBytes: 1024
maxMessageBackupUploadSizeInBytes: 1024
gcpAttachments: # GCP Storage configuration
domain: example.com
email: user@example.cocm
maxSizeInBytes: 1024
pathPrefix:
rsaSigningKey: secret://gcpAttachments.rsaSigningKey
@@ -275,6 +284,7 @@ unidentifiedDelivery:
certificate: CgIIAQ==
privateKey: secret://unidentifiedDelivery.privateKey
expiresDays: 7
embedSigner: true
shortCode:
baseUrl: https://example.com/shortcodes/
@@ -306,15 +316,15 @@ storageService:
AAAAAAAAAAAAAAAAAAAA
-----END CERTIFICATE-----
zkConfig:
serverPublic: ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzAB==
serverSecret: secret://zkConfig-libsignal-0.42.serverSecret
callingZkConfig:
serverSecret: secret://callingZkConfig.serverSecret
backupsZkConfig:
serverSecret: secret://backupsZkConfig.serverSecret
chatZkConfig:
serverSecret: secret://chatZkConfig.serverSecret
groupsZkConfig:
serverPublic: ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzAB==
serverSecret: secret://zkConfig-libsignal-0.42.serverSecret
dynamicConfig:
s3Region: a-region
@@ -353,10 +363,8 @@ badges:
svgs:
- light: example-light.svg
dark: example-dark.svg
badgeIdsEnabledForAll:
- TEST
receiptLevels:
'1': TEST
ONE_TIME_DONATION: TEST
subscription: # configuration for Stripe subscriptions
badgeExpiration: P30D
@@ -375,14 +383,16 @@ subscription: # configuration for Stripe subscriptions
STRIPE: price_example # stripe Price ID
BRAINTREE: plan_example # braintree Plan ID
loginPurchase:
playProductId: login_example
appStoreProductId: login_example
oneTimeDonations:
sepaMaximumEuros: '10000'
boost:
level: 1
expiration: P90D
badge: EXAMPLE
gift:
level: 10
expiration: P90D
badge: EXAMPLE
currencies:
@@ -510,6 +520,7 @@ idlePrimaryDeviceReminder:
grpc:
port: 50051
websocketPort: 8080
asnTable:
s3Region: a-region
@@ -526,3 +537,35 @@ callQualitySurvey:
{
"credential": "configuration"
}
hlrLookup:
apiKey: secret://hlrLookup.apiKey
apiSecret: secret://hlrLookup.apiSecret
foundationDbMessages:
maxWatchesPerClient: 10000
transactionTimeout: PT1S
transactionRetryLimit: 3
batchPriorityTransactionTimeout: PT5S
batchPriorityTransactionRetryLimit: 10
versionstampCipherKeys:
0: secret://foundationDbMessages.versionstampCipherKey.0
currentVersionstampCipherKey: 0
clusters:
"messages-0":
clusterFileUrl: http://clusterfiles.example.com/messages-0
"messages-1":
clusterFileUrl: http://clusterfiles.example.com/messages-1
"messages-2":
clusterFileUrl: http://clusterfiles.example.com/messages-2
"messages-3":
clusterFileUrl: http://clusterfiles.example.com/messages-3
epochs:
0:
- messages-0
- messages-1
1:
- messages-0
- messages-1
- messages-2
- messages-3
+92 -44
View File
@@ -11,12 +11,19 @@
<artifactId>service</artifactId>
<properties>
<firebase-admin.version>9.6.0</firebase-admin.version>
<java-uuid-generator.version>5.1.0</java-uuid-generator.version>
<apollo-api-jvm.version>3.8.5</apollo-api-jvm.version>
<commons-compress.version>1.28.0</commons-compress.version>
<dynamodb-lock-client.version>1.4.0</dynamodb-lock-client.version>
<firebase-admin.version>9.7.0</firebase-admin.version>
<libphonenumber-geocoder.version>3.23</libphonenumber-geocoder.version>
<google-androidpublisher.version>v3-rev20250904-2.0.0</google-androidpublisher.version>
<storekit.version>3.6.0</storekit.version>
<webauthn4j.version>0.29.6.RELEASE</webauthn4j.version>
<java-jwt.version>4.5.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.22.0-alpha</opentelemetry-logback-appender-1.0.version>
<storekit.version>4.0.0</storekit.version>
<webauthn4j.version>0.30.2.RELEASE</webauthn4j.version>
<jetty.http2-client.version>12.1.5</jetty.http2-client.version>
</properties>
<dependencies>
@@ -131,6 +138,12 @@
<groupId>io.dropwizard</groupId>
<artifactId>dropwizard-jetty</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.jetty.http2</groupId>
<artifactId>jetty-http2-client-transport</artifactId>
<scope>test</scope>
<version>${jetty.http2-client.version}</version>
</dependency>
<dependency>
<groupId>io.dropwizard</groupId>
<artifactId>dropwizard-validation</artifactId>
@@ -204,8 +217,7 @@
<dependency>
<groupId>io.opentelemetry.instrumentation</groupId>
<artifactId>opentelemetry-logback-appender-1.0</artifactId>
<!-- *all* opentelemetry-logback-appender versions are "alpha" despite the advanced version number -->
<version>2.19.0-alpha</version>
<version>${opentelemetry-logback-appender-1.0.version}</version>
<exclusions>
<!-- incubator packages aren't included in the opentelemetry BOM, and we don't use them -->
<exclusion>
@@ -237,15 +249,15 @@
<dependency>
<groupId>org.eclipse.jetty.websocket</groupId>
<artifactId>websocket-jetty-api</artifactId>
<artifactId>jetty-websocket-jetty-api</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-servlets</artifactId>
<groupId>org.eclipse.jetty.ee10</groupId>
<artifactId>jetty-ee10-servlets</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.jetty.websocket</groupId>
<artifactId>websocket-jetty-client</artifactId>
<artifactId>jetty-websocket-jetty-client</artifactId>
<scope>test</scope>
</dependency>
@@ -260,32 +272,18 @@
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-compress</artifactId>
<version>1.28.0</version>
<version>${commons-compress.version}</version>
</dependency>
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-pubsub</artifactId>
<exclusions>
<!-- our direct import of guava brings in a more recent version of failureaccess, so excluding it here -->
<exclusion>
<groupId>com.google.guava</groupId>
<artifactId>failureaccess</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.google.firebase</groupId>
<artifactId>firebase-admin</artifactId>
<version>${firebase-admin.version}</version>
<exclusions>
<!-- our direct import of guava brings in a more recent version of failureaccess, so excluding it here -->
<exclusion>
<groupId>com.google.guava</groupId>
<artifactId>failureaccess</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
@@ -297,11 +295,6 @@
<groupId>io.opentelemetry.instrumentation</groupId>
<artifactId>opentelemetry-instrumentation-api-incubator</artifactId>
</exclusion>
<!-- our direct import of guava brings in a more recent version of failureaccess, so excluding it here -->
<exclusion>
<groupId>com.google.guava</groupId>
<artifactId>failureaccess</artifactId>
</exclusion>
</exclusions>
</dependency>
@@ -375,11 +368,6 @@
<artifactId>jackson-jaxrs-json-provider</artifactId>
</dependency>
<dependency>
<groupId>com.salesforce.servicelibs</groupId>
<artifactId>reactor-grpc-stub</artifactId>
</dependency>
<dependency>
<groupId>org.foundationdb</groupId>
<artifactId>fdb-java</artifactId>
@@ -408,7 +396,7 @@
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>dynamodb-lock-client</artifactId>
<version>1.4.0</version>
<version>${dynamodb-lock-client.version}</version>
</dependency>
<dependency>
@@ -450,7 +438,7 @@
<dependency>
<groupId>com.googlecode.libphonenumber</groupId>
<artifactId>geocoder</artifactId>
<version>3.14</version>
<version>${libphonenumber-geocoder.version}</version>
</dependency>
<dependency>
@@ -458,17 +446,65 @@
<artifactId>argparse4j</artifactId>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-buffer</artifactId>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-codec-haproxy</artifactId>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-codec-http2</artifactId>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-handler</artifactId>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-common</artifactId>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-resolver</artifactId>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-resolver-dns</artifactId>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-transport</artifactId>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-transport-native-epoll</artifactId>
<classifier>linux-x86_64</classifier>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-pkitesting</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-testsuite-common</artifactId>
<scope>test</scope>
<version>${netty.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.test-framework</groupId>
<artifactId>jersey-test-framework-core</artifactId>
@@ -521,13 +557,13 @@
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>localstack</artifactId>
<artifactId>testcontainers-localstack</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>junit-jupiter</artifactId>
<artifactId>testcontainers-junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
@@ -542,6 +578,12 @@
<artifactId>google-auth-library-oauth2-http</artifactId>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk18on</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.stripe</groupId>
<artifactId>stripe-java</artifactId>
@@ -555,7 +597,7 @@
<dependency>
<groupId>com.apollographql.apollo3</groupId>
<artifactId>apollo-api-jvm</artifactId>
<version>3.8.5</version>
<version>${apollo-api-jvm.version}</version>
<exclusions>
<exclusion>
@@ -574,7 +616,7 @@
<dependency>
<groupId>com.squareup.okio</groupId>
<artifactId>okio-jvm</artifactId>
<version>3.15.0</version>
<version>3.16.4</version>
</dependency>
</dependencies>
@@ -587,7 +629,7 @@
<plugin>
<groupId>io.github.download-maven-plugin</groupId>
<artifactId>download-maven-plugin</artifactId>
<version>2.0.0</version>
<version>2.1.0</version>
<executions>
<execution>
@@ -602,6 +644,7 @@
<configuration>
<url>https://github.com/apple/foundationdb/releases/download/${foundationdb.version}/libfdb_c.x86_64.so</url>
<outputDirectory>${project.build.directory}/jib-extra/usr/lib</outputDirectory>
<outputFileName>libfdb_c.so</outputFileName>
<sha256>${foundationdb.client-library-sha256}</sha256>
</configuration>
</plugin>
@@ -689,7 +732,7 @@
</executions>
<configuration>
<from>
<image>eclipse-temurin@sha256:${docker.image.sha256}</image>
<image>${docker.image}</image>
<platforms>
<platform>
<architecture>amd64</architecture>
@@ -715,6 +758,9 @@
<jvmFlag>-XX:MaxRAMPercentage=75</jvmFlag>
<jvmFlag>-XX:+HeapDumpOnOutOfMemoryError</jvmFlag>
<jvmFlag>-XX:HeapDumpPath=/tmp/heapdump.bin</jvmFlag>
<!-- This will likely become the default in a future version of Java, and we can remove this flag when
that happens. Please see https://openjdk.org/jeps/534 for details. -->
<jvmFlag>-XX:+UseCompactObjectHeaders</jvmFlag>
</jvmFlags>
<ports>
<port>8080</port>
@@ -847,7 +893,7 @@
<plugin>
<groupId>com.github.aoudiamoncef</groupId>
<artifactId>apollo-client-maven-plugin</artifactId>
<version>5.0.0</version>
<version>7.1.0</version>
<executions>
<execution>
<goals>
@@ -860,6 +906,8 @@
<name>braintree</name>
<compilerParams>
<schemaPackageName>com.braintree.graphql.client</schemaPackageName>
<!-- override the default in 7.1.0, see https://github.com/aoudiamoncef/apollo-client-maven-plugin/issues/84 -->
<operationManifestFormat>none</operationManifestFormat>
</compilerParams>
</compilationUnit>
</braintree>
@@ -10,20 +10,20 @@ import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import java.time.Duration;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.whispersystems.textsecuregcm.attachments.TusConfiguration;
import org.whispersystems.textsecuregcm.configuration.ApnConfiguration;
import org.whispersystems.textsecuregcm.configuration.AppleAppStoreConfiguration;
import org.whispersystems.textsecuregcm.configuration.AppleDeviceCheckConfiguration;
import org.whispersystems.textsecuregcm.configuration.AttachmentsConfiguration;
import org.whispersystems.textsecuregcm.configuration.AwsCredentialsProviderFactory;
import org.whispersystems.textsecuregcm.configuration.BackupConfiguration;
import org.whispersystems.textsecuregcm.configuration.BadgesConfiguration;
import org.whispersystems.textsecuregcm.configuration.BraintreeConfiguration;
import org.whispersystems.textsecuregcm.configuration.CallQualitySurveyConfiguration;
import org.whispersystems.textsecuregcm.configuration.Cdn3StorageManagerConfiguration;
import org.whispersystems.textsecuregcm.configuration.CdnConfiguration;
import org.whispersystems.textsecuregcm.configuration.ChangeNumberConfiguration;
import org.whispersystems.textsecuregcm.configuration.CircuitBreakerConfiguration;
import org.whispersystems.textsecuregcm.configuration.ClientReleaseConfiguration;
import org.whispersystems.textsecuregcm.configuration.DefaultAwsCredentialsFactory;
@@ -35,14 +35,16 @@ import org.whispersystems.textsecuregcm.configuration.ExternalRequestFilterConfi
import org.whispersystems.textsecuregcm.configuration.FaultTolerantRedisClientFactory;
import org.whispersystems.textsecuregcm.configuration.FaultTolerantRedisClusterFactory;
import org.whispersystems.textsecuregcm.configuration.FcmConfiguration;
import org.whispersystems.textsecuregcm.configuration.FoundationDbMessagesConfiguration;
import org.whispersystems.textsecuregcm.configuration.GcpAttachmentsConfiguration;
import org.whispersystems.textsecuregcm.configuration.GenericZkConfig;
import org.whispersystems.textsecuregcm.configuration.GooglePlayBillingConfiguration;
import org.whispersystems.textsecuregcm.configuration.GrpcConfiguration;
import org.whispersystems.textsecuregcm.configuration.HlrLookupConfiguration;
import org.whispersystems.textsecuregcm.configuration.IdlePrimaryDeviceReminderConfiguration;
import org.whispersystems.textsecuregcm.configuration.KeyTransparencyServiceConfiguration;
import org.whispersystems.textsecuregcm.configuration.LinkDeviceSecretConfiguration;
import org.whispersystems.textsecuregcm.configuration.MaxDeviceConfiguration;
import org.whispersystems.textsecuregcm.configuration.LoginPurchaseConfiguration;
import org.whispersystems.textsecuregcm.configuration.MessageByteLimitCardinalityEstimatorConfiguration;
import org.whispersystems.textsecuregcm.configuration.MessageCacheConfiguration;
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration;
@@ -67,7 +69,7 @@ import org.whispersystems.textsecuregcm.configuration.VirtualThreadConfiguration
import org.whispersystems.textsecuregcm.configuration.ZkConfig;
import org.whispersystems.websocket.configuration.WebSocketConfiguration;
/** @noinspection MismatchedQueryAndUpdateOfCollection, WeakerAccess */
// @noinspection MismatchedQueryAndUpdateOfCollection, WeakerAccess
public class WhisperServerConfiguration extends Configuration {
@NotNull
@@ -120,11 +122,21 @@ public class WhisperServerConfiguration extends Configuration {
@JsonProperty
private DynamoDbTables dynamoDbTables;
@NotNull
@Valid
@JsonProperty
private AttachmentsConfiguration attachments;
@NotNull
@Valid
@JsonProperty
private GcpAttachmentsConfiguration gcpAttachments;
@NotNull
@Valid
@JsonProperty
private BackupConfiguration backup = new BackupConfiguration();
@NotNull
@Valid
@JsonProperty
@@ -180,11 +192,6 @@ public class WhisperServerConfiguration extends Configuration {
@JsonProperty
private MessageCacheConfiguration messageCache;
@Valid
@NotNull
@JsonProperty
private List<MaxDeviceConfiguration> maxDevices = new LinkedList<>();
@Valid
@NotNull
@JsonProperty
@@ -220,11 +227,6 @@ public class WhisperServerConfiguration extends Configuration {
@JsonProperty
private PaymentsServiceConfiguration paymentsService;
@Valid
@NotNull
@JsonProperty
private ZkConfig zkConfig;
@Valid
@NotNull
@JsonProperty
@@ -233,7 +235,12 @@ public class WhisperServerConfiguration extends Configuration {
@Valid
@NotNull
@JsonProperty
private GenericZkConfig backupsZkConfig;
private GenericZkConfig chatZkConfig;
@Valid
@NotNull
@JsonProperty
private ZkConfig groupsZkConfig;
@Valid
@NotNull
@@ -260,6 +267,11 @@ public class WhisperServerConfiguration extends Configuration {
@NotNull
private OneTimeDonationConfiguration oneTimeDonations;
@Valid
@JsonProperty
@NotNull
private LoginPurchaseConfiguration loginPurchase;
@Valid
@JsonProperty
@NotNull
@@ -332,6 +344,11 @@ public class WhisperServerConfiguration extends Configuration {
@JsonProperty
private Map<String, @Valid RetryConfiguration> retries = Collections.emptyMap();
@Valid
@NotNull
@JsonProperty
private HlrLookupConfiguration hlrLookup;
@JsonProperty
@Valid
@NotNull
@@ -352,6 +369,16 @@ public class WhisperServerConfiguration extends Configuration {
@JsonProperty
private CallQualitySurveyConfiguration callQualitySurvey;
@Valid
@NotNull
@JsonProperty
private ChangeNumberConfiguration changeNumber = new ChangeNumberConfiguration(Duration.ofHours(1));
@Valid
@NotNull
@JsonProperty
private FoundationDbMessagesConfiguration foundationDbMessages;
public TlsKeyStoreConfiguration getTlsKeyStoreConfiguration() {
return tlsKeyStore;
}
@@ -400,10 +427,18 @@ public class WhisperServerConfiguration extends Configuration {
return webSocket;
}
public AttachmentsConfiguration getAttachments() {
return attachments;
}
public GcpAttachmentsConfiguration getGcpAttachmentsConfiguration() {
return gcpAttachments;
}
public BackupConfiguration getBackupConfiguration() {
return backup;
}
public FaultTolerantRedisClusterFactory getCacheClusterConfiguration() {
return cacheCluster;
}
@@ -464,31 +499,23 @@ public class WhisperServerConfiguration extends Configuration {
return unidentifiedDelivery;
}
public Map<String, Integer> getMaxDevices() {
Map<String, Integer> results = new HashMap<>();
for (MaxDeviceConfiguration maxDeviceConfiguration : maxDevices) {
results.put(maxDeviceConfiguration.getNumber(),
maxDeviceConfiguration.getCount());
}
return results;
}
public PaymentsServiceConfiguration getPaymentsServiceConfiguration() {
return paymentsService;
}
public ZkConfig getZkConfig() {
return zkConfig;
/// ZK secret limited to Chat Service
public GenericZkConfig getChatZkConfig() {
return chatZkConfig;
}
/// ZK secret shared with Calling Service
public GenericZkConfig getCallingZkConfig() {
return callingZkConfig;
}
public GenericZkConfig getBackupsZkConfig() {
return backupsZkConfig;
/// ZK secret shared with Groups Service
public ZkConfig getGroupsZkConfig() {
return groupsZkConfig;
}
public RemoteConfigConfiguration getRemoteConfigConfiguration() {
@@ -511,6 +538,10 @@ public class WhisperServerConfiguration extends Configuration {
return oneTimeDonations;
}
public LoginPurchaseConfiguration getLoginPurchase() {
return loginPurchase;
}
public PagedSingleUseKEMPreKeyStoreConfiguration getPagedSingleUseKEMPreKeyStore() {
return pagedSingleUseKEMPreKeyStore;
}
@@ -590,4 +621,16 @@ public class WhisperServerConfiguration extends Configuration {
public CallQualitySurveyConfiguration getCallQualitySurveyConfiguration() {
return callQualitySurvey;
}
public HlrLookupConfiguration getHlrLookupConfiguration() {
return hlrLookup;
}
public ChangeNumberConfiguration getChangeNumber() {
return changeNumber;
}
public FoundationDbMessagesConfiguration getFoundationDbMessagesConfiguration() {
return foundationDbMessages;
}
}
File diff suppressed because it is too large. Load diff
@@ -10,6 +10,6 @@ public interface AttachmentGenerator {
record Descriptor(Map<String, String> headers, String signedUploadLocation) {}
Descriptor generateAttachment(final String key);
Descriptor generateAttachment(final String key, final long uploadLength);
}
@@ -0,0 +1,20 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.attachments;
import java.security.SecureRandom;
import java.util.Base64;
public class AttachmentUtil {
public static final String CDN3_EXPERIMENT_NAME = "cdn3";
private AttachmentUtil() {}
public static String generateAttachmentKey(final SecureRandom secureRandom) {
final byte[] bytes = new byte[15];
secureRandom.nextBytes(bytes);
return Base64.getUrlEncoder().encodeToString(bytes);
}
}
@@ -24,16 +24,16 @@ public class GcsAttachmentGenerator implements AttachmentGenerator {
private final CanonicalRequestSigner canonicalRequestSigner;
public GcsAttachmentGenerator(@Nonnull String domain, @Nonnull String email,
int maxSizeInBytes, @Nonnull String pathPrefix, @Nonnull String rsaSigningKey)
@Nonnull String pathPrefix, @Nonnull String rsaSigningKey)
throws IOException, InvalidKeyException, InvalidKeySpecException {
this.canonicalRequestGenerator = new CanonicalRequestGenerator(domain, email, maxSizeInBytes, pathPrefix);
this.canonicalRequestGenerator = new CanonicalRequestGenerator(domain, email, pathPrefix);
this.canonicalRequestSigner = new CanonicalRequestSigner(rsaSigningKey);
}
@Override
public Descriptor generateAttachment(final String key) {
public Descriptor generateAttachment(final String key, final long uploadLength) {
final ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC);
final CanonicalRequest canonicalRequest = canonicalRequestGenerator.createFor(key, now);
final CanonicalRequest canonicalRequest = canonicalRequestGenerator.createFor(key, now, uploadLength);
return new Descriptor(getHeaderMap(canonicalRequest), getSignedUploadLocation(canonicalRequest));
}
@@ -50,5 +50,4 @@ public class GcsAttachmentGenerator implements AttachmentGenerator {
"x-goog-resumable", "start");
}
}
@@ -6,8 +6,7 @@
package org.whispersystems.textsecuregcm.attachments;
import org.apache.http.HttpHeaders;
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
import org.whispersystems.textsecuregcm.auth.JwtGenerator;
import org.whispersystems.textsecuregcm.util.HeaderUtils;
import java.nio.charset.StandardCharsets;
import java.time.Clock;
@@ -18,28 +17,22 @@ public class TusAttachmentGenerator implements AttachmentGenerator {
private static final String ATTACHMENTS = "attachments";
final ExternalServiceCredentialsGenerator credentialsGenerator;
final String tusUri;
private final JwtGenerator jwtGenerator;
private final String tusUri;
public TusAttachmentGenerator(final TusConfiguration cfg) {
this.tusUri = cfg.uploadUri();
this.credentialsGenerator = credentialsGenerator(Clock.systemUTC(), cfg);
}
private static ExternalServiceCredentialsGenerator credentialsGenerator(final Clock clock, final TusConfiguration cfg) {
return ExternalServiceCredentialsGenerator
.builder(cfg.userAuthenticationTokenSharedSecret())
.prependUsername(false)
.withClock(clock)
.build();
this.jwtGenerator = new JwtGenerator(cfg.userAuthenticationTokenSharedSecret().value(), Clock.systemUTC());
}
@Override
public Descriptor generateAttachment(final String key) {
final ExternalServiceCredentials credentials = credentialsGenerator.generateFor(ATTACHMENTS + "/" + key);
public Descriptor generateAttachment(final String key, final long uploadLength) {
final String token = jwtGenerator.generateJwt(ATTACHMENTS, key,
builder -> builder.withClaim(JwtGenerator.MAX_LENGTH_CLAIM_KEY, uploadLength));
final String b64Key = Base64.getEncoder().encodeToString(key.getBytes(StandardCharsets.UTF_8));
final Map<String, String> headers = Map.of(
HttpHeaders.AUTHORIZATION, HeaderUtils.basicAuthHeader(credentials),
HttpHeaders.AUTHORIZATION, HeaderUtils.bearerAuthHeader(token),
"Upload-Metadata", String.format("filename %s", b64Key)
);
return new Descriptor(headers, tusUri + "/" + ATTACHMENTS);
@@ -6,10 +6,10 @@
package org.whispersystems.textsecuregcm.attachments;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.Positive;
import org.whispersystems.textsecuregcm.configuration.secrets.SecretBytes;
import org.whispersystems.textsecuregcm.util.ExactlySize;
public record TusConfiguration(
@ExactlySize(32) SecretBytes userAuthenticationTokenSharedSecret,
@NotEmpty String uploadUri
){}
@NotEmpty String uploadUri){}
@@ -10,7 +10,6 @@ import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import com.google.common.annotations.VisibleForTesting;
import io.dropwizard.auth.Authenticator;
import io.dropwizard.auth.basic.BasicCredentials;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tags;
import java.time.Clock;
@@ -20,7 +19,6 @@ import java.time.temporal.ChronoUnit;
import java.util.Optional;
import java.util.UUID;
import org.apache.commons.lang3.StringUtils;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
@@ -36,9 +34,6 @@ public class AccountAuthenticator implements Authenticator<BasicCredentials, Aut
private static final String DAYS_SINCE_LAST_SEEN_DISTRIBUTION_NAME = name(AccountAuthenticator.class, "daysSinceLastSeen");
private static final String IS_PRIMARY_DEVICE_TAG = "isPrimary";
private static final Counter OLD_TOKEN_VERSION_COUNTER =
Metrics.counter(name(AccountAuthenticator.class, "oldTokenVersionCounter"));
@VisibleForTesting
static final char DEVICE_ID_SEPARATOR = '.';
@@ -104,15 +99,8 @@ public class AccountAuthenticator implements Authenticator<BasicCredentials, Aut
SaltedTokenHash deviceSaltedTokenHash = device.get().getAuthTokenHash();
if (deviceSaltedTokenHash.verify(basicCredentials.getPassword())) {
succeeded = true;
Account authenticatedAccount = updateLastSeen(account.get(), device.get());
if (deviceSaltedTokenHash.getVersion() != SaltedTokenHash.CURRENT_VERSION) {
OLD_TOKEN_VERSION_COUNTER.increment();
authenticatedAccount = accountsManager.updateDeviceAuthentication(
authenticatedAccount,
device.get(),
SaltedTokenHash.generateFor(basicCredentials.getPassword())); // new credentials have current version
}
return Optional.of(new AuthenticatedDevice(authenticatedAccount.getIdentifier(IdentityType.ACI),
final Account authenticatedAccount = updateLastSeen(account.get(), device.get());
return Optional.of(new AuthenticatedDevice(authenticatedAccount.getAccountIdentifier(),
device.get().getId(),
Instant.ofEpochMilli(authenticatedAccount.getPrimaryDevice().getLastSeen())));
} else {
@@ -137,7 +125,7 @@ public class AccountAuthenticator implements Authenticator<BasicCredentials, Aut
@VisibleForTesting
public Account updateLastSeen(Account account, Device device) {
// compute a non-negative integer between 0 and 86400.
long n = Util.ensureNonNegativeLong(account.getUuid().getLeastSignificantBits());
long n = Util.ensureNonNegativeLong(account.getAccountIdentifier().getLeastSignificantBits());
final long lastSeenOffsetSeconds = n % ChronoUnit.DAYS.getDuration().toSeconds();
// produce a truncated timestamp which is either today at UTC midnight
@@ -153,7 +141,7 @@ public class AccountAuthenticator implements Authenticator<BasicCredentials, Aut
Metrics.summary(DAYS_SINCE_LAST_SEEN_DISTRIBUTION_NAME, IS_PRIMARY_DEVICE_TAG, String.valueOf(device.isPrimary()))
.record(Duration.ofMillis(todayInMillisWithOffset - device.getLastSeen()).toDays());
return accountsManager.updateDeviceLastSeen(account, device, Util.todayInMillis(clock));
return accountsManager.updateDeviceLastSeen(account.getAccountIdentifier(), device, Util.todayInMillis(clock));
}
return account;
@@ -16,6 +16,9 @@ public class Anonymous {
public Anonymous(String header) {
try {
this.unidentifiedSenderAccessKey = Base64.getDecoder().decode(header);
if (unidentifiedSenderAccessKey.length != UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH) {
throw new WebApplicationException("access key length must be 16", Response.Status.UNAUTHORIZED);
}
} catch (IllegalArgumentException e) {
throw new WebApplicationException(e, Response.Status.UNAUTHORIZED);
}
@@ -7,39 +7,51 @@ package org.whispersystems.textsecuregcm.auth;
import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;
import java.security.InvalidKeyException;
import java.util.concurrent.TimeUnit;
import org.signal.libsignal.protocol.ecc.ECPrivateKey;
import org.whispersystems.textsecuregcm.entities.MessageProtos.SenderCertificate;
import org.whispersystems.textsecuregcm.entities.MessageProtos.ServerCertificate;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
public class CertificateGenerator {
private final ECPrivateKey privateKey;
private final int expiresDays;
private final ECPrivateKey privateKey;
private final int expiresDays;
private final boolean embedSigner;
private final ServerCertificate serverCertificate;
private final int serverCertificateId;
public CertificateGenerator(byte[] serverCertificate, ECPrivateKey privateKey, int expiresDays)
throws InvalidProtocolBufferException
{
this.privateKey = privateKey;
this.expiresDays = expiresDays;
public CertificateGenerator(byte[] serverCertificate, ECPrivateKey privateKey, int expiresDays, boolean embedSigner)
throws InvalidProtocolBufferException {
this.privateKey = privateKey;
this.expiresDays = expiresDays;
this.embedSigner = embedSigner;
this.serverCertificate = ServerCertificate.parseFrom(serverCertificate);
this.serverCertificateId = ServerCertificate.Certificate
.parseFrom(this.serverCertificate.getCertificate())
.getId();
}
public byte[] createFor(final Account account, final byte deviceId, boolean includeE164) throws InvalidKeyException {
public byte[] createFor(final Account account, final byte deviceId, boolean includeE164) {
if (includeE164 && account.getNumberOptional().isEmpty()) {
throw new IllegalArgumentException();
}
SenderCertificate.Certificate.Builder builder = SenderCertificate.Certificate.newBuilder()
.setSenderDevice(Math.toIntExact(deviceId))
.setExpires(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(expiresDays))
.setIdentityKey(ByteString.copyFrom(account.getIdentityKey(IdentityType.ACI).serialize()))
.setSigner(serverCertificate)
.setSenderUuid(account.getUuid().toString());
.setIdentityKey(ByteString.copyFrom(account.getAccountIdentityKey().serialize()))
.setSenderUuid(UUIDUtil.toByteString(account.getAccountIdentifier()));
if (includeE164) {
builder.setSender(account.getNumber());
builder.setSenderE164(account.getNumberOptional().get());
}
if (embedSigner) {
builder.setSignerCertificate(serverCertificate);
} else {
builder.setSignerId(serverCertificateId);
}
byte[] certificate = builder.build().toByteArray();
@@ -47,10 +59,10 @@ public class CertificateGenerator {
signature = privateKey.calculateSignature(certificate);
return SenderCertificate.newBuilder()
.setCertificate(ByteString.copyFrom(certificate))
.setSignature(ByteString.copyFrom(signature))
.build()
.toByteArray();
.setCertificate(ByteString.copyFrom(certificate))
.setSignature(ByteString.copyFrom(signature))
.build()
.toByteArray();
}
}
@@ -16,13 +16,17 @@ import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.http.FaultTolerantHttpClient;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import org.whispersystems.textsecuregcm.util.SystemMapper;
@@ -37,6 +41,8 @@ public class CloudflareTurnCredentialsManager {
private final FaultTolerantHttpClient cloudflareTurnClient;
private final DnsNameResolver dnsNameResolver;
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
private final ExperimentEnrollmentManager experimentEnrollmentManager;
private final Duration clientCredentialTtl;
@@ -63,7 +69,9 @@ public class CloudflareTurnCredentialsManager {
final ExecutorService executor,
@Nullable final String retryConfigurationName,
final ScheduledExecutorService retryExecutor,
final DnsNameResolver dnsNameResolver) {
final DnsNameResolver dnsNameResolver,
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
final ExperimentEnrollmentManager experimentEnrollmentManager) {
this.cloudflareTurnClient = FaultTolerantHttpClient.newBuilder("cloudflare-turn", executor)
.withCircuitBreaker(circuitBreakerConfigurationName)
@@ -74,6 +82,8 @@ public class CloudflareTurnCredentialsManager {
this.cloudflareTurnUrlsWithIps = cloudflareTurnUrlsWithIps;
this.cloudflareTurnHostname = cloudflareTurnHostname;
this.dnsNameResolver = dnsNameResolver;
this.dynamicConfigurationManager = dynamicConfigurationManager;
this.experimentEnrollmentManager = experimentEnrollmentManager;
final String credentialsRequestBody;
@@ -95,15 +105,27 @@ public class CloudflareTurnCredentialsManager {
this.clientCredentialTtl = clientCredentialTtl;
}
public TurnToken retrieveFromCloudflare() throws IOException {
public TurnToken retrieveFromCloudflare(UUID accountUuid) throws IOException {
final List<String> cloudflareTurnComposedUrls;
final List<String> turnUrls;
final List<String> turnUrlsWithIps;
final String turnHostname;
if (experimentEnrollmentManager.isEnrolled(accountUuid, "turnBeta")) {
turnUrls = dynamicConfigurationManager.getConfiguration().getTurnConfiguration().getUrls();
turnUrlsWithIps = dynamicConfigurationManager.getConfiguration().getTurnConfiguration().getUrlsWithIps();
turnHostname = dynamicConfigurationManager.getConfiguration().getTurnConfiguration().getHostname();
} else {
turnUrls = this.cloudflareTurnUrls;
turnUrlsWithIps = this.cloudflareTurnUrlsWithIps;
turnHostname = this.cloudflareTurnHostname;
}
try {
cloudflareTurnComposedUrls = dnsNameResolver.resolveAll(cloudflareTurnHostname).get().stream()
cloudflareTurnComposedUrls = dnsNameResolver.resolveAll(turnHostname).get().stream()
.map(i -> switch (i) {
case Inet6Address i6 -> "[" + i6.getHostAddress() + "]";
default -> i.getHostAddress();
})
.flatMap(i -> cloudflareTurnUrlsWithIps.stream().map(u -> u.formatted(i)))
.flatMap(i -> turnUrlsWithIps.stream().map(u -> u.formatted(i)))
.toList();
} catch (Exception e) {
throw new IOException(e);
@@ -129,9 +151,9 @@ public class CloudflareTurnCredentialsManager {
cloudflareTurnResponse.iceServers().username(),
cloudflareTurnResponse.iceServers().credential(),
clientCredentialTtl.toSeconds(),
cloudflareTurnUrls == null ? Collections.emptyList() : cloudflareTurnUrls,
turnUrls,
cloudflareTurnComposedUrls,
cloudflareTurnHostname
turnHostname
);
}
}
@@ -0,0 +1,24 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.auth;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.core.Response;
import java.util.Base64;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.donation.DonationPermit;
public record DonationPermitHeader(DonationPermit permit) {
public static DonationPermitHeader valueOf(String header) {
try {
return new DonationPermitHeader(new DonationPermit(Base64.getDecoder().decode(header)));
} catch (InvalidInputException | IllegalArgumentException e) {
// Base64 throws IllegalArgumentException; DonationPermit ctor throws InvalidInputException
throw new WebApplicationException(e, Response.Status.UNAUTHORIZED);
}
}
}
@@ -192,17 +192,9 @@ public class ExternalServiceCredentialsGenerator {
: Optional.empty();
}
/**
* Given an instance of {@link ExternalServiceCredentials} object and the max allowed age for those credentials,
* checks if credentials are valid and not expired.
* @param credentials an instance of {@link ExternalServiceCredentials}
* @param maxAgeSeconds age in seconds
* @return An optional with a timestamp (seconds) of when the credentials were generated,
* or an empty optional if the password doesn't match the username for any reason (including malformed data)
*/
public Optional<Long> validateAndGetTimestamp(final ExternalServiceCredentials credentials, final long maxAgeSeconds) {
return validateAndGetTimestamp(credentials)
.filter(ts -> currentTimeSeconds() - ts <= maxAgeSeconds);
@VisibleForTesting
boolean isCredentialExpired(final long credentialTimestamp, final long maxAgeSeconds) {
return currentTimeSeconds() - credentialTimestamp > maxAgeSeconds;
}
private boolean shouldDeriveUsername() {
@@ -7,20 +7,37 @@ package org.whispersystems.textsecuregcm.auth;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
public class ExternalServiceCredentialsSelector {
private ExternalServiceCredentialsSelector() {}
public record CredentialInfo(String token, boolean valid, ExternalServiceCredentials credentials, long timestamp) {
public enum CredentialStatus {
// The token passes verification, is not expired, and is the most recent token available
VALID,
// The token was malformed or the signature was invalid
FAILED_VERIFICATION,
// The credential was correctly signed, but exceeded the maximum credential age
EXPIRED,
// There was a more recent credential available with the same username
REPLACED
}
public record CredentialInfo(String token, ExternalServiceCredentials credentials, long timestamp, CredentialStatus status) {
/**
* @return a copy of this record with valid=false
* @return a copy of this record that indicates it has been replaced with a more up-to-date token
*/
private CredentialInfo invalidate() {
return new CredentialInfo(token, false, credentials, timestamp);
private CredentialInfo replaced() {
return new CredentialInfo(token, credentials, timestamp, CredentialStatus.REPLACED);
}
public boolean valid() {
return status == CredentialStatus.VALID;
}
}
@@ -29,13 +46,13 @@ public class ExternalServiceCredentialsSelector {
* A credential is valid if it passes validation by the provided credentialsGenerator AND it is the most recent
* credential in the provided list for a username.
*
* @param tokens A list of credentials, potentially with different usernames
* @param tokens A set of credentials, potentially with different usernames
* @param credentialsGenerator To validate these credentials
* @param maxAgeSeconds The maximum allowable age of the credential
* @return A {@link CredentialInfo} for each provided token
* @return An unordered list of {@link CredentialInfo} for each provided token
*/
public static List<CredentialInfo> check(
final List<String> tokens,
final Set<String> tokens,
final ExternalServiceCredentialsGenerator credentialsGenerator,
final long maxAgeSeconds) {
@@ -47,13 +64,18 @@ public class ExternalServiceCredentialsSelector {
// (note that password part may also contain ':' characters)
final String[] parts = token.split(":", 2);
if (parts.length != 2) {
results.add(new CredentialInfo(token, false, null, 0L));
results.add(new CredentialInfo(token, null, 0L, CredentialStatus.FAILED_VERIFICATION));
continue;
}
final ExternalServiceCredentials credentials = new ExternalServiceCredentials(parts[0], parts[1]);
final Optional<Long> maybeTimestamp = credentialsGenerator.validateAndGetTimestamp(credentials, maxAgeSeconds);
final Optional<Long> maybeTimestamp = credentialsGenerator.validateAndGetTimestamp(credentials);
if (maybeTimestamp.isEmpty()) {
results.add(new CredentialInfo(token, false, null, 0L));
results.add(new CredentialInfo(token, credentials, 0L, CredentialStatus.FAILED_VERIFICATION));
continue;
}
final long credentialTs = maybeTimestamp.get();
if (credentialsGenerator.isCredentialExpired(credentialTs, maxAgeSeconds)) {
results.add(new CredentialInfo(token, credentials, credentialTs, CredentialStatus.EXPIRED));
continue;
}
@@ -62,17 +84,17 @@ public class ExternalServiceCredentialsSelector {
final long timestamp = maybeTimestamp.get();
final CredentialInfo best = bestForUsername.get(credentials.username());
if (best == null) {
bestForUsername.put(credentials.username(), new CredentialInfo(token, true, credentials, timestamp));
bestForUsername.put(credentials.username(), new CredentialInfo(token, credentials, timestamp, CredentialStatus.VALID));
continue;
}
if (best.timestamp() < timestamp) {
// we found a better credential for the username
bestForUsername.put(credentials.username(), new CredentialInfo(token, true, credentials, timestamp));
bestForUsername.put(credentials.username(), new CredentialInfo(token, credentials, timestamp, CredentialStatus.VALID));
// mark the previous best as an invalid credential, since we have a better credential now
results.add(best.invalidate());
results.add(best.replaced());
} else {
// the credential we already had was more recent, this one can be marked invalid
results.add(new CredentialInfo(token, false, null, 0L));
results.add(new CredentialInfo(token, null, 0L, CredentialStatus.REPLACED));
}
}
@@ -10,10 +10,9 @@ import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Metrics;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.Optional;
import org.eclipse.jetty.websocket.server.JettyServerUpgradeRequest;
import org.eclipse.jetty.websocket.server.JettyServerUpgradeResponse;
import org.eclipse.jetty.ee10.websocket.server.JettyServerUpgradeRequest;
import org.eclipse.jetty.ee10.websocket.server.JettyServerUpgradeResponse;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.websocket.auth.AuthenticatedWebSocketUpgradeFilter;
@@ -0,0 +1,10 @@
package org.whispersystems.textsecuregcm.auth;
import org.whispersystems.textsecuregcm.util.NoStackTraceException;
public class InvalidRegistrationSessionException extends NoStackTraceException {
public InvalidRegistrationSessionException(final String message) {
super(message);
}
}
@@ -0,0 +1,39 @@
/*
* Copyright 2026 Signal Messenger, LLC
*
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.auth;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import java.time.Clock;
import java.time.Instant;
import java.util.function.Consumer;
/// Generates JWT tokens for external services to validate. This class always uses symmetric HMAC-SHA256 with a shared secret
public class JwtGenerator {
public static final String MAX_LENGTH_CLAIM_KEY = "maxLen";
public static final String SCOPE_CLAIM_KEY = "scope";
private final Algorithm algorithm;
private final Clock clock;
public JwtGenerator(final byte[] sharedSecret, final Clock clock) {
this.algorithm = Algorithm.HMAC256(sharedSecret);
this.clock = clock;
}
public String generateJwt(final String audience, final String subject, Consumer<JWTCreator.Builder> claimCustomizer) {
final Instant now = clock.instant();
JWTCreator.Builder builder = JWT.create()
.withAudience(audience)
.withSubject(subject)
.withIssuedAt(now);
claimCustomizer.accept(builder);
return builder.sign(algorithm);
}
}
@@ -7,18 +7,14 @@ package org.whispersystems.textsecuregcm.auth;
import io.grpc.Status;
import io.grpc.StatusRuntimeException;
import jakarta.ws.rs.BadRequestException;
import jakarta.ws.rs.ForbiddenException;
import jakarta.ws.rs.NotAuthorizedException;
import jakarta.ws.rs.ServerErrorException;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.core.Response;
import java.io.IOException;
import java.security.MessageDigest;
import java.time.Duration;
import java.util.concurrent.CancellationException;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.entities.PhoneVerificationRequest;
@@ -26,7 +22,7 @@ import org.whispersystems.textsecuregcm.entities.RegistrationServiceSession;
import org.whispersystems.textsecuregcm.registration.RegistrationServiceClient;
import org.whispersystems.textsecuregcm.spam.RegistrationRecoveryChecker;
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
import org.whispersystems.textsecuregcm.storage.PhoneNumberRecoveryPasswordsManager;
public class PhoneVerificationTokenManager {
@@ -37,16 +33,16 @@ public class PhoneVerificationTokenManager {
private final PhoneNumberIdentifiers phoneNumberIdentifiers;
private final RegistrationServiceClient registrationServiceClient;
private final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager;
private final PhoneNumberRecoveryPasswordsManager phoneNumberRecoveryPasswordsManager;
private final RegistrationRecoveryChecker registrationRecoveryChecker;
public PhoneVerificationTokenManager(final PhoneNumberIdentifiers phoneNumberIdentifiers,
final RegistrationServiceClient registrationServiceClient,
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager,
final PhoneNumberRecoveryPasswordsManager phoneNumberRecoveryPasswordsManager,
final RegistrationRecoveryChecker registrationRecoveryChecker) {
this.phoneNumberIdentifiers = phoneNumberIdentifiers;
this.registrationServiceClient = registrationServiceClient;
this.registrationRecoveryPasswordsManager = registrationRecoveryPasswordsManager;
this.phoneNumberRecoveryPasswordsManager = phoneNumberRecoveryPasswordsManager;
this.registrationRecoveryChecker = registrationRecoveryChecker;
}
@@ -54,74 +50,90 @@ public class PhoneVerificationTokenManager {
* Checks if a {@link PhoneVerificationRequest} has a token that verifies the caller has confirmed access to the e164
* number
*
* @param requestContext the container request context
* @param number the e164 presented for verification
* @param request the request with exactly one verification token (RegistrationService sessionId or registration
* recovery password)
* @param sessionId a verification session ID; exactly one of {@code sessionId} or {@code recoveryPassword} must be
* non-null
* @param recoveryPassword a registration recovery password; exactly one of {@code sessionId} or
* {@code recoveryPassword} must be non-null
* @return if verification was successful, returns the verification type
* @throws BadRequestException if the number does not match the sessionId’s number, or the remote service rejects
* @throws InvalidRegistrationSessionException if the number does not match the sessionId’s number, or the remote service rejects
* the session ID as invalid
* @throws NotAuthorizedException if the session is not verified
* @throws ForbiddenException if the recovery password is not valid
* @throws UnverifiedRegistrationSessionException if the session is not verified
* @throws RecoveryPasswordVerificationFailedException if the recovery password is not valid
* @throws InterruptedException if verification did not complete before a timeout
* @throws IOException if there was an error talking to registration service
*/
public PhoneVerificationRequest.VerificationType verify(final ContainerRequestContext requestContext, final String number, final PhoneVerificationRequest request)
throws InterruptedException {
public PhoneVerificationRequest.VerificationType verify(
final String number,
@Nullable final String userAgent,
@Nullable final String acceptLanguage,
@Nullable final String mostRecentProxy,
@Nullable final byte[] sessionId,
@Nullable final byte[] recoveryPassword)
throws InterruptedException, UnverifiedRegistrationSessionException, InvalidRegistrationSessionException, IOException, RecoveryPasswordVerificationFailedException {
if ((sessionId == null) == (recoveryPassword == null)) {
throw new IllegalArgumentException("Exactly one of session ID or recovery password must non-null");
}
final PhoneVerificationRequest.VerificationType verificationType = sessionId != null
? PhoneVerificationRequest.VerificationType.SESSION
: PhoneVerificationRequest.VerificationType.RECOVERY_PASSWORD;
final PhoneVerificationRequest.VerificationType verificationType = request.verificationType();
switch (verificationType) {
case SESSION -> verifyBySessionId(number, request.decodeSessionId());
case RECOVERY_PASSWORD -> verifyByRecoveryPassword(requestContext, number, request.recoveryPassword());
case SESSION -> verifyBySessionId(number, sessionId);
case RECOVERY_PASSWORD -> verifyByRecoveryPassword(number, userAgent, acceptLanguage, mostRecentProxy, recoveryPassword);
}
return verificationType;
}
private void verifyBySessionId(final String number, final byte[] sessionId) throws InterruptedException {
private void verifyBySessionId(final String number, final byte[] sessionId)
throws UnverifiedRegistrationSessionException, InvalidRegistrationSessionException, IOException {
try {
final RegistrationServiceSession session = registrationServiceClient
.getSession(sessionId, REGISTRATION_RPC_TIMEOUT)
.get(VERIFICATION_TIMEOUT_SECONDS, TimeUnit.SECONDS)
.orElseThrow(() -> new NotAuthorizedException("session not verified"));
.orElseThrow(UnverifiedRegistrationSessionException::new);
if (!MessageDigest.isEqual(number.getBytes(), session.number().getBytes())) {
throw new BadRequestException("number does not match session");
throw new InvalidRegistrationSessionException("number does not match session");
}
if (!session.verified()) {
throw new NotAuthorizedException("session not verified");
throw new UnverifiedRegistrationSessionException();
}
} catch (final ExecutionException e) {
if (e.getCause() instanceof StatusRuntimeException grpcRuntimeException) {
if (grpcRuntimeException.getStatus().getCode() == Status.Code.INVALID_ARGUMENT) {
throw new BadRequestException();
}
} catch (final StatusRuntimeException e) {
if (e.getStatus().getCode() == Status.Code.INVALID_ARGUMENT) {
throw new InvalidRegistrationSessionException(e.getMessage());
}
logger.error("Registration service failure", e);
throw new ServerErrorException(Response.Status.SERVICE_UNAVAILABLE);
} catch (final CancellationException | TimeoutException e) {
logger.error("Registration service failure", e);
throw new ServerErrorException(Response.Status.SERVICE_UNAVAILABLE);
throw new IOException("Registration service failure", e);
}
}
private void verifyByRecoveryPassword(final ContainerRequestContext requestContext, final String number, final byte[] recoveryPassword)
throws InterruptedException {
if (!registrationRecoveryChecker.checkRegistrationRecoveryAttempt(requestContext, number)) {
throw new ForbiddenException("recoveryPassword couldn't be verified");
private void verifyByRecoveryPassword(
final String number,
@Nullable final String userAgent,
@Nullable final String acceptLanguage,
@Nullable final String mostRecentProxy,
final byte[] recoveryPassword)
throws InterruptedException, IOException, RecoveryPasswordVerificationFailedException {
if (!registrationRecoveryChecker.checkRegistrationRecoveryAttempt(number, userAgent, acceptLanguage, mostRecentProxy)) {
throw new RecoveryPasswordVerificationFailedException();
}
try {
final boolean verified = registrationRecoveryPasswordsManager.verify(phoneNumberIdentifiers.getPhoneNumberIdentifier(number).join(), recoveryPassword)
final UUID phoneNumberIdentifier = phoneNumberIdentifiers.getPhoneNumberIdentifier(number)
.get(VERIFICATION_TIMEOUT_SECONDS, TimeUnit.SECONDS);
final boolean verified = phoneNumberRecoveryPasswordsManager.verify(phoneNumberIdentifier, recoveryPassword);
if (!verified) {
throw new ForbiddenException("recoveryPassword couldn't be verified");
throw new RecoveryPasswordVerificationFailedException();
}
} catch (final ExecutionException | TimeoutException e) {
throw new ServerErrorException(Response.Status.SERVICE_UNAVAILABLE);
throw new IOException("registration service unavailable", e);
}
}
}
@@ -0,0 +1,6 @@
package org.whispersystems.textsecuregcm.auth;
import org.whispersystems.textsecuregcm.util.NoStackTraceException;
public class RecoveryPasswordVerificationFailedException extends NoStackTraceException {
}
@@ -0,0 +1,18 @@
package org.whispersystems.textsecuregcm.auth;
import org.whispersystems.textsecuregcm.entities.RegistrationLockFailure;
import org.whispersystems.textsecuregcm.util.NoStackTraceException;
public class RegistrationLockFailureException extends NoStackTraceException {
private final RegistrationLockFailure failure;
public RegistrationLockFailureException(final RegistrationLockFailure failure) {
super();
this.failure = failure;
}
public RegistrationLockFailure getFailure() {
return failure;
}
}
@@ -12,8 +12,6 @@ import io.micrometer.core.instrument.DistributionSummary;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.core.Response;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
@@ -22,7 +20,6 @@ import org.apache.commons.lang3.StringUtils;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.entities.PhoneVerificationRequest;
import org.whispersystems.textsecuregcm.entities.RegistrationLockFailure;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.push.NotPushRegisteredException;
@@ -30,7 +27,7 @@ import org.whispersystems.textsecuregcm.push.PushNotificationManager;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
import org.whispersystems.textsecuregcm.storage.PhoneNumberRecoveryPasswordsManager;
public class RegistrationLockVerificationManager {
public enum Flow {
@@ -56,20 +53,20 @@ public class RegistrationLockVerificationManager {
private final DisconnectionRequestManager disconnectionRequestManager;
private final ExternalServiceCredentialsGenerator svr2CredentialGenerator;
private final RateLimiters rateLimiters;
private final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager;
private final PhoneNumberRecoveryPasswordsManager phoneNumberRecoveryPasswordsManager;
private final PushNotificationManager pushNotificationManager;
public RegistrationLockVerificationManager(
final AccountsManager accounts,
final DisconnectionRequestManager disconnectionRequestManager,
final ExternalServiceCredentialsGenerator svr2CredentialGenerator,
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager,
final PhoneNumberRecoveryPasswordsManager phoneNumberRecoveryPasswordsManager,
final PushNotificationManager pushNotificationManager,
final RateLimiters rateLimiters) {
this.accounts = accounts;
this.disconnectionRequestManager = disconnectionRequestManager;
this.svr2CredentialGenerator = svr2CredentialGenerator;
this.registrationRecoveryPasswordsManager = registrationRecoveryPasswordsManager;
this.phoneNumberRecoveryPasswordsManager = phoneNumberRecoveryPasswordsManager;
this.pushNotificationManager = pushNotificationManager;
this.rateLimiters = rateLimiters;
}
@@ -80,13 +77,16 @@ public class RegistrationLockVerificationManager {
* @param account
* @param clientRegistrationLock
* @throws RateLimitExceededException
* @throws WebApplicationException
* @throws RegistrationLockFailureException
*/
public void verifyRegistrationLock(final Account account, @Nullable final String clientRegistrationLock,
final String userAgent,
@Nullable final String userAgent,
final Flow flow,
final PhoneVerificationRequest.VerificationType phoneVerificationType
) throws RateLimitExceededException, WebApplicationException {
) throws RateLimitExceededException, RegistrationLockFailureException {
final String phoneNumber = account.getNumberOptional()
.orElseThrow(() -> new IllegalArgumentException("account does not have a phone number"));
final Tags expiredTags = Tags.of(UserAgentTagUtil.getPlatformTag(userAgent),
Tag.of(REGISTRATION_LOCK_VERIFICATION_FLOW_TAG_NAME, flow.name()),
@@ -108,10 +108,9 @@ public class RegistrationLockVerificationManager {
}
if (StringUtils.isNotEmpty(clientRegistrationLock)) {
rateLimiters.getPinLimiter().validate(account.getNumber());
rateLimiters.getPinLimiter().validate(phoneNumber);
}
final String phoneNumber = account.getNumber();
final boolean registrationLockMatches = existingRegistrationLock.verify(clientRegistrationLock);
final boolean alreadyLocked = account.hasLockedCredentials();
@@ -125,7 +124,6 @@ public class RegistrationLockVerificationManager {
final DistributionSummary registrationLockIdleDays = DistributionSummary
.builder(name(RegistrationLockVerificationManager.class, "registrationLockIdleDays"))
.tags(additionalTags)
.publishPercentiles(0.75, 0.95, 0.99, 0.999)
.distributionStatisticExpiry(Duration.ofHours(2))
.register(Metrics.globalRegistry);
@@ -153,11 +151,12 @@ public class RegistrationLockVerificationManager {
// This allows users to re-register via registration recovery password
// instead of always being forced to fall back to SMS verification.
if (!phoneVerificationType.equals(PhoneVerificationRequest.VerificationType.RECOVERY_PASSWORD) || clientRegistrationLock != null) {
registrationRecoveryPasswordsManager.remove(updatedAccount.getIdentifier(IdentityType.PNI));
phoneNumberRecoveryPasswordsManager.remove(updatedAccount.getPhoneNumberIdentifierOptional()
.orElseThrow(() -> new AssertionError("Account with a phone number did not have a phone number identifier")));
}
final List<Byte> deviceIds = updatedAccount.getDevices().stream().map(Device::getId).toList();
disconnectionRequestManager.requestDisconnection(updatedAccount.getUuid(), deviceIds);
disconnectionRequestManager.requestDisconnection(updatedAccount.getAccountIdentifier(), deviceIds);
try {
// Send a push notification that prompts the client to attempt login and fail due to locked credentials
@@ -166,11 +165,10 @@ public class RegistrationLockVerificationManager {
Metrics.counter(CHALLENGED_DEVICE_NOT_PUSH_REGISTERED_COUNTER_NAME).increment();
}
throw new WebApplicationException(Response.status(FAILURE_HTTP_STATUS)
.entity(new RegistrationLockFailure(
throw new RegistrationLockFailureException(
new RegistrationLockFailure(
existingRegistrationLock.getTimeRemaining().toMillis(),
svr2FailureCredentials(existingRegistrationLock, updatedAccount)))
.build());
svr2FailureCredentials(existingRegistrationLock, updatedAccount)));
}
rateLimiters.getPinLimiter().clear(phoneNumber);
@@ -180,7 +178,7 @@ public class RegistrationLockVerificationManager {
if (!existingRegistrationLock.needsFailureCredentials()) {
return null;
}
return svr2CredentialGenerator.generateForUuid(account.getUuid());
return svr2CredentialGenerator.generateForUuid(account.getAccountIdentifier());
}
}
@@ -6,20 +6,12 @@ package org.whispersystems.textsecuregcm.auth;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.HexFormat;
import org.signal.libsignal.protocol.kdf.HKDF;
public record SaltedTokenHash(String hash, String salt) {
public enum Version {
V1,
V2,
}
public static final Version CURRENT_VERSION = Version.V2;
private static final String V2_PREFIX = "2.";
private static final byte[] AUTH_TOKEN_HKDF_INFO = "authtoken".getBytes(StandardCharsets.UTF_8);
@@ -31,21 +23,13 @@ public record SaltedTokenHash(String hash, String salt) {
public static SaltedTokenHash generateFor(final String token) {
final String salt = generateSalt();
final String hash = calculateV2Hash(salt, token);
final String hash = calculateHash(salt, token);
return new SaltedTokenHash(hash, salt);
}
public Version getVersion() {
return hash.startsWith(V2_PREFIX) ? Version.V2 : Version.V1;
}
public boolean verify(final String token) {
final String theirValue = switch (getVersion()) {
case V1 -> calculateV1Hash(salt, token);
case V2 -> calculateV2Hash(salt, token);
};
return MessageDigest.isEqual(
theirValue.getBytes(StandardCharsets.UTF_8),
calculateHash(salt, token).getBytes(StandardCharsets.UTF_8),
hash.getBytes(StandardCharsets.UTF_8));
}
@@ -55,16 +39,7 @@ public record SaltedTokenHash(String hash, String salt) {
return HexFormat.of().formatHex(salt);
}
private static String calculateV1Hash(final String salt, final String token) {
try {
return HexFormat.of()
.formatHex(MessageDigest.getInstance("SHA1").digest((salt + token).getBytes(StandardCharsets.UTF_8)));
} catch (final NoSuchAlgorithmException e) {
throw new AssertionError(e);
}
}
private static String calculateV2Hash(final String salt, final String token) {
private static String calculateHash(final String salt, final String token) {
final byte[] secret = HKDF.deriveSecrets(
token.getBytes(StandardCharsets.UTF_8), // key
salt.getBytes(StandardCharsets.UTF_8), // salt
@@ -0,0 +1,6 @@
package org.whispersystems.textsecuregcm.auth;
import org.whispersystems.textsecuregcm.util.NoStackTraceException;
public class UnverifiedRegistrationSessionException extends NoStackTraceException {
}
@@ -6,8 +6,8 @@
package org.whispersystems.textsecuregcm.auth.grpc;
import io.grpc.Context;
import io.grpc.Status;
import javax.annotation.Nullable;
import org.whispersystems.textsecuregcm.grpc.GrpcExceptions;
import org.whispersystems.textsecuregcm.storage.Device;
/**
@@ -18,13 +18,11 @@ public class AuthenticationUtil {
static final Context.Key<AuthenticatedDevice> CONTEXT_AUTHENTICATED_DEVICE = Context.key("authenticated-device");
/**
* Returns the account/device authenticated in the current gRPC context or throws an "unauthenticated" exception if
* no authenticated account/device is available.
* Returns the account/device authenticated in the current gRPC context. Should only be called from a service run with
* the {@link RequireAuthenticationInterceptor}.
*
* @return the account/device identifier authenticated in the current gRPC context
*
* @throws io.grpc.StatusRuntimeException with a status of {@code UNAUTHENTICATED} if no authenticated account/device
* could be retrieved from the current gRPC context
* @throws IllegalStateException if no authenticated account/device could be retrieved from the current gRPC context
*/
public static AuthenticatedDevice requireAuthenticatedDevice() {
@Nullable final AuthenticatedDevice authenticatedDevice = CONTEXT_AUTHENTICATED_DEVICE.get();
@@ -33,27 +31,25 @@ public class AuthenticationUtil {
return authenticatedDevice;
}
throw Status.UNAUTHENTICATED.asRuntimeException();
throw new IllegalStateException(
"Configuration issue: service expects an authenticated device, but none was found. Request should have failed from an interceptor");
}
/**
* Returns the account/device authenticated in the current gRPC context or throws an "unauthenticated" exception if
* no authenticated account/device is available or "permission denied" if the authenticated device is not the primary
* device for the account.
* Returns the account/device authenticated in the current gRPC context or "invalid argument" if the authenticated
* device is not the primary device for the account.
*
* @return the account/device identifier authenticated in the current gRPC context
*
* @throws io.grpc.StatusRuntimeException with a status of {@code UNAUTHENTICATED} if no authenticated account/device
* could be retrieved from the current gRPC context or a status of {@code PERMISSION_DENIED} if the authenticated
* device is not the primary device for the authenticated account
* @throws io.grpc.StatusRuntimeException with a status of {@code INVALID_ARGUMENT} if the authenticated device is not
* the primary device for the authenticated account
* @throws IllegalStateException if no authenticated account/device could be retrieved from the current gRPC
* context
*/
public static AuthenticatedDevice requireAuthenticatedPrimaryDevice() {
final AuthenticatedDevice authenticatedDevice = requireAuthenticatedDevice();
if (authenticatedDevice.deviceId() != Device.PRIMARY_ID) {
throw Status.PERMISSION_DENIED.asRuntimeException();
throw GrpcExceptions.badAuthentication("RPC requires a primary device");
}
return authenticatedDevice;
}
}
@@ -8,7 +8,8 @@ import io.grpc.Metadata;
import io.grpc.ServerCall;
import io.grpc.ServerCallHandler;
import io.grpc.ServerInterceptor;
import io.grpc.Status;
import org.whispersystems.textsecuregcm.grpc.GrpcExceptions;
import org.whispersystems.textsecuregcm.grpc.ServerInterceptorUtil;
/**
* A "prohibit authentication" interceptor ensures that requests to endpoints that should be invoked anonymously do not
@@ -20,10 +21,10 @@ public class ProhibitAuthenticationInterceptor implements ServerInterceptor {
@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(final ServerCall<ReqT, RespT> call,
final Metadata headers, final ServerCallHandler<ReqT, RespT> next) {
final String authHeaderString = headers.get(Metadata.Key.of(RequireAuthenticationInterceptor.AUTHORIZATION_HEADER, Metadata.ASCII_STRING_MARSHALLER));
final String authHeaderString = headers.get(RequireAuthenticationInterceptor.AUTHORIZATION_METADATA_KEY);
if (authHeaderString != null) {
call.close(Status.UNAUTHENTICATED.withDescription("authorization header forbidden"), new Metadata());
return new ServerCall.Listener<>() {};
return ServerInterceptorUtil.closeWithStatusException(call,
GrpcExceptions.badAuthentication("The service forbids requests with an authentication header"));
}
return next.startCall(call, headers);
}
@@ -11,9 +11,9 @@ import io.grpc.Metadata;
import io.grpc.ServerCall;
import io.grpc.ServerCallHandler;
import io.grpc.ServerInterceptor;
import io.grpc.Status;
import java.util.Optional;
import org.whispersystems.textsecuregcm.auth.AccountAuthenticator;
import org.whispersystems.textsecuregcm.grpc.GrpcExceptions;
import org.whispersystems.textsecuregcm.grpc.ServerInterceptorUtil;
import org.whispersystems.textsecuregcm.util.HeaderUtils;
@@ -25,7 +25,8 @@ import org.whispersystems.textsecuregcm.util.HeaderUtils;
*/
public class RequireAuthenticationInterceptor implements ServerInterceptor {
static final String AUTHORIZATION_HEADER = "authorization";
public static final Metadata.Key<String> AUTHORIZATION_METADATA_KEY =
Metadata.Key.of("authorization", Metadata.ASCII_STRING_MARSHALLER);
private final AccountAuthenticator authenticator;
@@ -36,25 +37,24 @@ public class RequireAuthenticationInterceptor implements ServerInterceptor {
@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(final ServerCall<ReqT, RespT> call,
final Metadata headers, final ServerCallHandler<ReqT, RespT> next) {
final String authHeaderString = headers.get(
Metadata.Key.of(AUTHORIZATION_HEADER, Metadata.ASCII_STRING_MARSHALLER));
final String authHeaderString = headers.get(AUTHORIZATION_METADATA_KEY);
if (authHeaderString == null) {
return ServerInterceptorUtil.closeWithStatus(call,
Status.UNAUTHENTICATED.withDescription("missing authorization header"));
return ServerInterceptorUtil.closeWithStatusException(call,
GrpcExceptions.invalidCredentials("missing authorization header"));
}
final Optional<BasicCredentials> basicCredentials = HeaderUtils.basicCredentialsFromAuthHeader(authHeaderString);
if (basicCredentials.isEmpty()) {
return ServerInterceptorUtil.closeWithStatus(call,
Status.UNAUTHENTICATED.withDescription("malformed authorization header"));
return ServerInterceptorUtil.closeWithStatusException(call,
GrpcExceptions.invalidCredentials("malformed authorization header"));
}
final Optional<org.whispersystems.textsecuregcm.auth.AuthenticatedDevice> authenticated =
authenticator.authenticate(basicCredentials.get());
if (authenticated.isEmpty()) {
return ServerInterceptorUtil.closeWithStatus(call,
Status.UNAUTHENTICATED.withDescription("invalid credentials"));
return ServerInterceptorUtil.closeWithStatusException(call,
GrpcExceptions.invalidCredentials("invalid credentials"));
}
final AuthenticatedDevice authenticatedDevice = new AuthenticatedDevice(
@@ -5,7 +5,8 @@
package org.whispersystems.textsecuregcm.backup;
import io.grpc.Status;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.security.MessageDigest;
import java.time.Clock;
import java.time.Duration;
@@ -13,7 +14,9 @@ import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
@@ -40,7 +43,6 @@ import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.RedeemedReceiptsManager;
import org.whispersystems.textsecuregcm.util.Util;
/**
* Issues ZK backup auth credentials for authenticated accounts
@@ -57,7 +59,6 @@ public class BackupAuthManager {
private static final Logger logger = LoggerFactory.getLogger(BackupAuthManager.class);
final static Duration MAX_REDEMPTION_DURATION = Duration.ofDays(7);
final static String BACKUP_MEDIA_EXPERIMENT_NAME = "backupMedia";
private final ExperimentEnrollmentManager experimentEnrollmentManager;
@@ -94,22 +95,20 @@ public class BackupAuthManager {
* message backups
* @param mediaBackupCredentialRequest A request containing the blinded backup-id the client will use to upload
* media backups
* @return A future that completes when the credentialRequest has been stored
* @throws RateLimitExceededException If too many backup-ids have been committed
*/
public CompletableFuture<Void> commitBackupId(
public void commitBackupId(
final Account account,
final Device device,
final Optional<BackupAuthCredentialRequest> messagesBackupCredentialRequest,
final Optional<BackupAuthCredentialRequest> mediaBackupCredentialRequest) {
final Optional<BackupAuthCredentialRequest> mediaBackupCredentialRequest)
throws RateLimitExceededException, BackupPermissionException, BackupInvalidArgumentException {
if (!device.isPrimary()) {
throw Status.PERMISSION_DENIED.withDescription("Only primary device can set backup-id").asRuntimeException();
throw new BackupPermissionException("Only primary device can set backup-id");
}
if (messagesBackupCredentialRequest.isEmpty() && mediaBackupCredentialRequest.isEmpty()) {
throw Status.INVALID_ARGUMENT
.withDescription("Must set at least one of message/media credential requests")
.asRuntimeException();
throw new BackupInvalidArgumentException("Must set at least one of message/media credential requests");
}
final byte[] storedMessageCredentialRequest = account.getBackupCredentialRequest(BackupCredentialType.MESSAGES)
@@ -133,42 +132,33 @@ public class BackupAuthManager {
if (!requiresMessageRotation && !requiresMediaRotation) {
// No need to update or enforce rate limits, this is the credential that the user has already
// committed to.
return CompletableFuture.completedFuture(null);
return;
}
CompletableFuture<Void> rateLimitFuture = CompletableFuture.completedFuture(null);
if (requiresMessageRotation) {
rateLimitFuture = rateLimitFuture.thenCombine(
rateLimiters.forDescriptor(RateLimiters.For.SET_BACKUP_ID).validateAsync(account.getUuid()),
(_, _) -> null);
rateLimiters.forDescriptor(RateLimiters.For.SET_BACKUP_ID).validate(account.getAccountIdentifier());
}
if (requiresMediaRotation && hasActiveVoucher(account)) {
rateLimitFuture = rateLimitFuture.thenCombine(
rateLimiters.forDescriptor(RateLimiters.For.SET_PAID_MEDIA_BACKUP_ID).validateAsync(account.getUuid()),
(_, _) -> null);
rateLimiters.forDescriptor(RateLimiters.For.SET_PAID_MEDIA_BACKUP_ID).validate(account.getAccountIdentifier());
}
return rateLimitFuture.thenCompose(ignored -> this.accountsManager
.updateAsync(account, a ->
a.setBackupCredentialRequests(targetMessageCredentialRequest, targetMediaCredentialRequest))
.thenRun(Util.NOOP))
.toCompletableFuture();
this.accountsManager.update(account, a ->
a.setBackupCredentialRequests(targetMessageCredentialRequest, targetMediaCredentialRequest));
}
public record BackupIdRotationLimit(boolean hasPermitsRemaining, Duration nextPermitAvailable) {}
public CompletionStage<BackupIdRotationLimit> checkBackupIdRotationLimit(final Account account) {
public BackupIdRotationLimit checkBackupIdRotationLimit(final Account account) {
final RateLimiter messagesLimiter = rateLimiters.forDescriptor(RateLimiters.For.SET_BACKUP_ID);
final RateLimiter mediaLimiter = rateLimiters.forDescriptor(RateLimiters.For.SET_PAID_MEDIA_BACKUP_ID);
final boolean isPaid = hasActiveVoucher(account);
final CompletionStage<Boolean> hasSetMessagesPermits =
messagesLimiter.hasAvailablePermitsAsync(account.getUuid(), 1);
messagesLimiter.hasAvailablePermitsAsync(account.getAccountIdentifier(), 1);
final CompletionStage<Boolean> hasSetMediaPermits = isPaid
? mediaLimiter.hasAvailablePermitsAsync(account.getUuid(), 1)
? mediaLimiter.hasAvailablePermitsAsync(account.getAccountIdentifier(), 1)
: CompletableFuture.completedFuture(true);
return hasSetMessagesPermits.thenCombine(hasSetMediaPermits, (hasMessage, hasMedia) -> {
@@ -180,7 +170,7 @@ public class BackupAuthManager {
isPaid ? mediaLimiter.config().permitRegenerationDuration() : Duration.ZERO));
return new BackupIdRotationLimit(false, timeToNextPermit);
}
});
}).toCompletableFuture().join();
}
public record Credential(BackupAuthCredentialResponse credential, Instant redemptionTime) {}
@@ -195,51 +185,53 @@ public class BackupAuthManager {
* voucher's expiration will include paid backup access. If the BackupVoucher exists but is already expired, this
* method will also remove the expired voucher from the account.
*
* @param account The account to create the credentials for
* @param credentialType The type of backup credentials to create
* @param originalAccount The account to create the credentials for
* @param redemptionRange The time range to return credentials for
* @return Credentials and the day on which they may be redeemed
*/
public CompletableFuture<List<Credential>> getBackupAuthCredentials(
final Account account,
final BackupCredentialType credentialType,
final RedemptionRange redemptionRange) {
public Map<BackupCredentialType, List<Credential>> getBackupAuthCredentials(
final Account originalAccount,
final RedemptionRange redemptionRange) throws BackupNotFoundException {
// If the account has an expired payment, clear it before continuing
if (hasExpiredVoucher(account)) {
return accountsManager.updateAsync(account, a -> {
final Account account;
if (hasExpiredVoucher(originalAccount)) {
account = accountsManager.update(originalAccount, a -> {
// Re-check in case we raced with an update
if (hasExpiredVoucher(a)) {
a.setBackupVoucher(null);
}
}).thenCompose(updated -> getBackupAuthCredentials(updated, credentialType, redemptionRange));
});
} else {
account = originalAccount;
}
// fetch the blinded backup-id the account should have previously committed to
final byte[] committedBytes = account.getBackupCredentialRequest(credentialType)
.orElseThrow(() -> Status.NOT_FOUND.withDescription("No blinded backup-id has been added to the account").asRuntimeException());
final Map<BackupCredentialType, List<Credential>> credentials = new HashMap<>();
for (BackupCredentialType credentialType : BackupCredentialType.values()) {
// fetch the blinded backup-id the account should have previously committed to
final byte[] committedBytes = account.getBackupCredentialRequest(credentialType)
.orElseThrow(() -> new BackupNotFoundException("No blinded backup-id has been added to the account"));
try {
final BackupLevel defaultBackupLevel = configuredBackupLevel(account);
try {
final BackupLevel defaultBackupLevel = configuredBackupLevel(account);
// create a credential for every day in the requested period
final BackupAuthCredentialRequest credentialReq = new BackupAuthCredentialRequest(committedBytes);
return CompletableFuture.completedFuture(StreamSupport.stream(redemptionRange.spliterator(), false)
.map(redemptionTime -> {
// Check if the account has a voucher that's good for a certain receiptLevel at redemption time, otherwise
// use the default receipt level
final BackupLevel backupLevel = storedBackupLevel(account, redemptionTime).orElse(defaultBackupLevel);
return new Credential(
credentialReq.issueCredential(redemptionTime, backupLevel, credentialType, serverSecretParams),
redemptionTime);
})
.toList());
} catch (InvalidInputException e) {
throw Status.INTERNAL
.withDescription("Could not deserialize stored request credential")
.withCause(e)
.asRuntimeException();
// create a credential for every day in the requested period
final BackupAuthCredentialRequest credentialReq = new BackupAuthCredentialRequest(committedBytes);
final List<Credential> credentialList = StreamSupport.stream(redemptionRange.spliterator(), false)
.map(redemptionTime -> {
// Check if the account has a voucher that's good for a certain receiptLevel at redemption time, otherwise
// use the default receipt level
final BackupLevel backupLevel = storedBackupLevel(account, redemptionTime).orElse(defaultBackupLevel);
return new Credential(
credentialReq.issueCredential(redemptionTime, backupLevel, credentialType, serverSecretParams),
redemptionTime);
})
.toList();
credentials.put(credentialType, credentialList);
} catch (InvalidInputException e) {
throw new UncheckedIOException(new IOException("Could not deserialize stored request credential", e));
}
}
return credentials;
}
/**
@@ -247,48 +239,38 @@ public class BackupAuthManager {
*
* @param account The account to enable backups on
* @param receiptCredentialPresentation A ZK receipt presentation proving payment
* @return A future that completes successfully when the account has been updated
*/
public CompletableFuture<Void> redeemReceipt(
public void redeemReceipt(
final Account account,
final ReceiptCredentialPresentation receiptCredentialPresentation) {
final ReceiptCredentialPresentation receiptCredentialPresentation)
throws BackupBadReceiptException, BackupInvalidArgumentException, BackupMissingIdCommitmentException {
try {
serverZkReceiptOperations.verifyReceiptCredentialPresentation(receiptCredentialPresentation);
} catch (VerificationFailedException e) {
throw Status.INVALID_ARGUMENT
.withDescription("receipt credential presentation verification failed")
.asRuntimeException();
throw new BackupBadReceiptException("receipt credential presentation verification failed");
}
final ReceiptSerial receiptSerial = receiptCredentialPresentation.getReceiptSerial();
final Instant receiptExpiration = Instant.ofEpochSecond(receiptCredentialPresentation.getReceiptExpirationTime());
if (clock.instant().isAfter(receiptExpiration)) {
throw Status.INVALID_ARGUMENT.withDescription("receipt is already expired").asRuntimeException();
throw new BackupBadReceiptException("receipt is already expired");
}
final long receiptLevel = receiptCredentialPresentation.getReceiptLevel();
if (BackupLevelUtil.fromReceiptLevel(receiptLevel) != BackupLevel.PAID) {
throw Status.INVALID_ARGUMENT
.withDescription("server does not recognize the requested receipt level")
.asRuntimeException();
throw new BackupInvalidArgumentException("server does not recognize the requested receipt level");
}
if (account.getBackupCredentialRequest(BackupCredentialType.MEDIA).isEmpty()) {
throw Status.ABORTED
.withDescription("account must have a backup-id commitment")
.asRuntimeException();
throw new BackupMissingIdCommitmentException();
}
return redeemedReceiptsManager
.put(receiptSerial, receiptExpiration.getEpochSecond(), receiptLevel, account.getUuid())
.thenCompose(receiptAllowed -> {
if (!receiptAllowed) {
throw Status.INVALID_ARGUMENT
.withDescription("receipt serial is already redeemed")
.asRuntimeException();
}
return extendBackupVoucher(account, new Account.BackupVoucher(receiptLevel, receiptExpiration));
});
boolean receiptAllowed = redeemedReceiptsManager
.put(receiptSerial, receiptExpiration.getEpochSecond(), receiptLevel, account.getAccountIdentifier());
if (!receiptAllowed) {
throw new BackupBadReceiptException("receipt serial is already redeemed");
}
extendBackupVoucher(account, new Account.BackupVoucher(receiptLevel, receiptExpiration));
}
/**
@@ -296,19 +278,17 @@ public class BackupAuthManager {
*
* @param account The account to update
* @param backupVoucher The backup voucher to apply to this account
* @return A future that completes once the account has been updated to have at least the level and expiration
* in the provided voucher.
*/
public CompletableFuture<Void> extendBackupVoucher(final Account account, final Account.BackupVoucher backupVoucher) {
return accountsManager.updateAsync(account, a -> {
public void extendBackupVoucher(final Account account, final Account.BackupVoucher backupVoucher) {
accountsManager.update(account, a -> {
// Receipt credential expirations must be day aligned. Make sure any manually set backupVoucher is also day
// aligned
final Account.BackupVoucher newPayment = new Account.BackupVoucher(
final Account.BackupVoucher newPayment = new Account.BackupVoucher(
backupVoucher.receiptLevel(),
backupVoucher.expiration().truncatedTo(ChronoUnit.DAYS));
final Account.BackupVoucher existingPayment = a.getBackupVoucher();
a.setBackupVoucher(merge(existingPayment, newPayment));
}).thenRun(Util.NOOP);
});
}
private static Account.BackupVoucher merge(@Nullable final Account.BackupVoucher prev,
@@ -362,7 +342,7 @@ public class BackupAuthManager {
* BackupVoucher.
*/
private BackupLevel configuredBackupLevel(final Account account) {
return this.experimentEnrollmentManager.isEnrolled(account.getUuid(), BACKUP_MEDIA_EXPERIMENT_NAME)
return this.experimentEnrollmentManager.isEnrolled(account.getAccountIdentifier(), BACKUP_MEDIA_EXPERIMENT_NAME)
? BackupLevel.PAID
: BackupLevel.FREE;
}
@@ -0,0 +1,12 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.backup;
public class BackupBadReceiptException extends BackupException {
public BackupBadReceiptException(String message) {
super(message);
}
}
@@ -0,0 +1,16 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.backup;
public class BackupException extends Exception {
public BackupException() {
super();
}
public BackupException(String message) {
super(message);
}
}
@@ -0,0 +1,12 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.backup;
public class BackupFailedZkAuthenticationException extends BackupException {
public BackupFailedZkAuthenticationException(String message) {
super(message);
}
}
@@ -0,0 +1,11 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.backup;
public class BackupInvalidArgumentException extends BackupException {
public BackupInvalidArgumentException(final String message) {
super(message);
}
}
@@ -6,8 +6,6 @@
package org.whispersystems.textsecuregcm.backup;
import com.google.common.annotations.VisibleForTesting;
import io.dropwizard.util.DataSize;
import io.grpc.Status;
import io.micrometer.core.instrument.DistributionSummary;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
@@ -25,6 +23,7 @@ import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.function.Function;
import javax.annotation.Nullable;
import org.apache.commons.lang3.StringUtils;
import org.signal.libsignal.protocol.ecc.ECKeyPair;
import org.signal.libsignal.protocol.ecc.ECPublicKey;
@@ -36,18 +35,17 @@ import org.signal.libsignal.zkgroup.backups.BackupLevel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.attachments.AttachmentGenerator;
import org.whispersystems.textsecuregcm.attachments.AttachmentUtil;
import org.whispersystems.textsecuregcm.attachments.TusAttachmentGenerator;
import org.whispersystems.textsecuregcm.auth.AuthenticatedBackupUser;
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicBackupConfiguration;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.configuration.BackupConfiguration;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecoveryClient;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.util.AsyncTimerUtil;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import org.whispersystems.textsecuregcm.util.Pair;
import org.whispersystems.textsecuregcm.util.ua.UnrecognizedUserAgentException;
@@ -56,13 +54,12 @@ import org.whispersystems.textsecuregcm.util.ua.UserAgentUtil;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Scheduler;
import javax.annotation.Nullable;
public class BackupManager {
static final String MESSAGE_BACKUP_NAME = "messageBackup";
public static final long MAX_MESSAGE_BACKUP_OBJECT_SIZE = DataSize.mebibytes(101).toBytes();
public static final long MAX_MEDIA_OBJECT_SIZE = DataSize.mebibytes(101).toBytes();
private static final int DEFAULT_LIST_MEDIA_LIMIT = 1000;
private static final String ZK_AUTHN_COUNTER_NAME = MetricsUtil.name(BackupManager.class, "authentication");
private static final String ZK_AUTHZ_FAILURE_COUNTER_NAME = MetricsUtil.name(BackupManager.class,
@@ -92,7 +89,7 @@ public class BackupManager {
private final ExternalServiceCredentialsGenerator secureValueRecoveryBCredentialsGenerator;
private final SecureValueRecoveryClient secureValueRecoveryBClient;
private final Clock clock;
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
private final BackupConfiguration backupConfiguration;
public BackupManager(
final BackupsDb backupsDb,
@@ -104,7 +101,7 @@ public class BackupManager {
final ExternalServiceCredentialsGenerator secureValueRecoveryBCredentialsGenerator,
final SecureValueRecoveryClient secureValueRecoveryBClient,
final Clock clock,
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
final BackupConfiguration backupConfiguration) {
this.backupsDb = backupsDb;
this.serverSecretParams = serverSecretParams;
this.rateLimiters = rateLimiters;
@@ -114,7 +111,7 @@ public class BackupManager {
this.secureValueRecoveryBClient = secureValueRecoveryBClient;
this.clock = clock;
this.secureValueRecoveryBCredentialsGenerator = secureValueRecoveryBCredentialsGenerator;
this.dynamicConfigurationManager = dynamicConfigurationManager;
this.backupConfiguration = backupConfiguration;
}
@@ -127,11 +124,12 @@ public class BackupManager {
* @param presentation a ZK credential presentation that encodes the backupId
* @param signature the signature of the presentation
* @param publicKey the public key of a key-pair that the presentation must be signed with
* @throws BackupFailedZkAuthenticationException If the provided presentation or signature were invalid
*/
public CompletableFuture<Void> setPublicKey(
public void setPublicKey(
final BackupAuthCredentialPresentation presentation,
final byte[] signature,
final ECPublicKey publicKey) {
final ECPublicKey publicKey) throws BackupFailedZkAuthenticationException {
// Note: this is a special case where we can't validate the presentation signature against the stored public key
// because we are currently setting it. We check against the provided public key, but we must also verify that
@@ -139,16 +137,16 @@ public class BackupManager {
final Pair<BackupCredentialType, BackupLevel> credentialTypeAndBackupLevel =
verifyPresentation(presentation).verifySignature(signature, publicKey);
return backupsDb.setPublicKey(presentation.getBackupId(), credentialTypeAndBackupLevel.second(), publicKey)
.exceptionally(ExceptionUtils.exceptionallyHandler(PublicKeyConflictException.class, ex -> {
ExceptionUtils.unwrapSupply(
BackupPublicKeyConflictException.class,
() -> backupsDb.setPublicKey(presentation.getBackupId(), credentialTypeAndBackupLevel.second(), publicKey).join(),
_ -> {
Metrics.counter(ZK_AUTHN_COUNTER_NAME,
SUCCESS_TAG_NAME, String.valueOf(false),
FAILURE_REASON_TAG_NAME, "public_key_conflict")
.increment();
throw Status.UNAUTHENTICATED
.withDescription("public key does not match existing public key for the backup-id")
.asRuntimeException();
}));
return new BackupFailedZkAuthenticationException("The provided public key did not match the stored public key");
});
}
/**
@@ -157,70 +155,68 @@ public class BackupManager {
* If successful, this also updates the TTL of the backup.
*
* @param backupUser an already ZK authenticated backup user
* @param uploadSize the maximum size of a message backup that can be uploaded with the returned form
* @return the upload form
* @throws BackupPermissionException if the credential does not have the correct level
* @throws BackupWrongCredentialTypeException if the credential does not have the messages type
*/
public CompletableFuture<BackupUploadDescriptor> createMessageBackupUploadDescriptor(
final AuthenticatedBackupUser backupUser) {
public BackupUploadDescriptor createMessageBackupUploadDescriptor(
final AuthenticatedBackupUser backupUser,
final long uploadSize) throws BackupPermissionException, BackupWrongCredentialTypeException {
checkBackupLevel(backupUser, BackupLevel.FREE);
checkBackupCredentialType(backupUser, BackupCredentialType.MESSAGES);
// this could race with concurrent updates, but the only effect would be last-writer-wins on the timestamp
return backupsDb
.addMessageBackup(backupUser)
.thenApply(_ ->
cdn3BackupCredentialGenerator.generateUpload(cdnMessageBackupName(backupUser)));
backupsDb.addMessageBackup(backupUser).join();
return cdn3BackupCredentialGenerator.generateUpload(cdnMessageBackupName(backupUser), uploadSize);
}
public CompletableFuture<BackupUploadDescriptor> createTemporaryAttachmentUploadDescriptor(
final AuthenticatedBackupUser backupUser) {
public BackupUploadDescriptor createTemporaryAttachmentUploadDescriptor(
final AuthenticatedBackupUser backupUser,
final long uploadSize)
throws RateLimitExceededException, BackupPermissionException, BackupWrongCredentialTypeException {
checkBackupLevel(backupUser, BackupLevel.PAID);
checkBackupCredentialType(backupUser, BackupCredentialType.MEDIA);
return rateLimiters.forDescriptor(RateLimiters.For.BACKUP_ATTACHMENT)
.validateAsync(rateLimitKey(backupUser)).thenApply(ignored -> {
final byte[] bytes = new byte[15];
secureRandom.nextBytes(bytes);
final String attachmentKey = Base64.getUrlEncoder().encodeToString(bytes);
final AttachmentGenerator.Descriptor descriptor = tusAttachmentGenerator.generateAttachment(attachmentKey);
return new BackupUploadDescriptor(3, attachmentKey, descriptor.headers(), descriptor.signedUploadLocation());
}).toCompletableFuture();
rateLimiters.forDescriptor(RateLimiters.For.BACKUP_ATTACHMENT).validate(rateLimitKey(backupUser));
final String attachmentKey = AttachmentUtil.generateAttachmentKey(secureRandom);
final AttachmentGenerator.Descriptor descriptor =
tusAttachmentGenerator.generateAttachment(attachmentKey, uploadSize);
return new BackupUploadDescriptor(3, attachmentKey, descriptor.headers(), descriptor.signedUploadLocation());
}
/**
* Update the last update timestamps for the backupId in the presentation
*
* @param backupUser an already ZK authenticated backup user
* @throws BackupPermissionException if the credential does not have the correct level
*/
public CompletableFuture<Void> ttlRefresh(final AuthenticatedBackupUser backupUser) {
public void ttlRefresh(final AuthenticatedBackupUser backupUser) throws BackupPermissionException {
checkBackupLevel(backupUser, BackupLevel.FREE);
// update message backup TTL
return backupsDb.ttlRefresh(backupUser).thenAccept(storedBackupAttributes -> {
if (backupUser.credentialType() == BackupCredentialType.MEDIA) {
final long maxTotalMediaSize =
dynamicConfigurationManager.getConfiguration().getBackupConfiguration().maxTotalMediaSize();
final StoredBackupAttributes storedBackupAttributes = backupsDb.ttlRefresh(backupUser).join();
if (backupUser.credentialType() == BackupCredentialType.MEDIA) {
final long maxTotalMediaSize = backupConfiguration.maxTotalMediaSize();
// Report that the backup is out of quota if it cannot store a max size media object
final boolean quotaExhausted = storedBackupAttributes.bytesUsed() >=
(maxTotalMediaSize - BackupManager.MAX_MEDIA_OBJECT_SIZE);
// Report that the backup is out of quota if it is within 100MiB of the limit
final boolean quotaExhausted = storedBackupAttributes.bytesUsed() >=
(maxTotalMediaSize - 1024 * 1024 * 100);
final Tags tags = Tags.of(
UserAgentTagUtil.getPlatformTag(backupUser.userAgent()),
Tag.of("type", backupUser.credentialType().name()),
Tag.of("tier", backupUser.backupLevel().name()),
Tag.of("quotaExhausted", String.valueOf(quotaExhausted)));
final Tags tags = Tags.of(
UserAgentTagUtil.getPlatformTag(backupUser.userAgent()),
Tag.of("type", backupUser.credentialType().name()),
Tag.of("tier", backupUser.backupLevel().name()),
Tag.of("quotaExhausted", String.valueOf(quotaExhausted)));
DistributionSummary.builder(NUM_OBJECTS_SUMMARY_NAME)
.tags(tags)
.publishPercentileHistogram()
.register(Metrics.globalRegistry)
.record(storedBackupAttributes.numObjects());
DistributionSummary.builder(BYTES_USED_SUMMARY_NAME)
.tags(tags)
.publishPercentileHistogram()
.register(Metrics.globalRegistry)
.record(storedBackupAttributes.bytesUsed());
}
});
DistributionSummary.builder(NUM_OBJECTS_SUMMARY_NAME)
.tags(tags)
.register(Metrics.globalRegistry)
.record(storedBackupAttributes.numObjects());
DistributionSummary.builder(BYTES_USED_SUMMARY_NAME)
.tags(tags)
.register(Metrics.globalRegistry)
.record(storedBackupAttributes.bytesUsed());
}
}
public record BackupInfo(int cdn, String backupSubdir, String mediaSubdir, String messageBackupKey,
@@ -231,16 +227,20 @@ public class BackupManager {
*
* @param backupUser an already ZK authenticated backup user
* @return Information about the existing backup
* @throws BackupPermissionException if the credential does not have the correct level
* @throws BackupFailedZkAuthenticationException if the provided backupuser does not exist
*/
public CompletableFuture<BackupInfo> backupInfo(final AuthenticatedBackupUser backupUser) {
public BackupInfo backupInfo(final AuthenticatedBackupUser backupUser) throws BackupPermissionException, BackupFailedZkAuthenticationException {
checkBackupLevel(backupUser, BackupLevel.FREE);
return backupsDb.describeBackup(backupUser)
.thenApply(backupDescription -> new BackupInfo(
backupDescription.cdn(),
backupUser.backupDir(),
backupUser.mediaDir(),
MESSAGE_BACKUP_NAME,
backupDescription.mediaUsedSpace()));
final BackupsDb.BackupDescription backupDescription = ExceptionUtils.unwrapSupply(
BackupFailedZkAuthenticationException.class,
() -> backupsDb.describeBackup(backupUser).join());
return new BackupInfo(
backupDescription.cdn(),
backupUser.backupDir(),
backupUser.mediaDir(),
MESSAGE_BACKUP_NAME,
backupDescription.mediaUsedSpace());
}
/**
@@ -255,46 +255,40 @@ public class BackupManager {
* @return A Flux that emits the locations of the double-encrypted objects on the backup cdn, or includes an error
* detailing why the object could not be copied.
*/
public Flux<CopyResult> copyToBackup(final AuthenticatedBackupUser backupUser, List<CopyParameters> toCopy) {
checkBackupLevel(backupUser, BackupLevel.PAID);
checkBackupCredentialType(backupUser, BackupCredentialType.MEDIA);
public Flux<CopyResult> copyToBackup(final CopyQuota copyQuota) {
final AuthenticatedBackupUser backupUser = copyQuota.backupUser();
final DynamicBackupConfiguration backupConfiguration =
dynamicConfigurationManager.getConfiguration().getBackupConfiguration();
return Flux.concat(
return Mono.fromFuture(() -> allowedCopies(backupUser, toCopy))
.flatMapMany(quotaResult -> Flux.concat(
// Perform copies for requests that fit in our quota, first updating the usage. If the copy fails, our
// estimated quota usage may not be exact since we update usage first. We make a best-effort attempt
// to undo the usage update if we know that the copied failed for sure.
Flux.fromIterable(copyQuota.requestsToCopy())
// Perform copies for requests that fit in our quota, first updating the usage. If the copy fails, our
// estimated quota usage may not be exact since we update usage first. We make a best-effort attempt
// to undo the usage update if we know that the copied failed for sure.
Flux.fromIterable(quotaResult.requestsToCopy())
// Update the usage in reasonable chunk sizes to bound how out of sync our claimed and actual usage gets
.buffer(backupConfiguration.usageCheckpointCount())
.concatMap(copyParameters -> {
final long quotaToConsume = copyParameters.stream()
.mapToLong(CopyParameters::destinationObjectSize)
.sum();
return Mono
.fromFuture(backupsDb.trackMedia(backupUser, copyParameters.size(), quotaToConsume))
.thenMany(Flux.fromIterable(copyParameters));
})
// Update the usage in reasonable chunk sizes to bound how out of sync our claimed and actual usage gets
.buffer(backupConfiguration.usageCheckpointCount())
.concatMap(copyParameters -> {
final long quotaToConsume = copyParameters.stream()
.mapToLong(CopyParameters::destinationObjectSize)
.sum();
return Mono
.fromFuture(backupsDb.trackMedia(backupUser, copyParameters.size(), quotaToConsume))
.thenMany(Flux.fromIterable(copyParameters));
})
// Actually perform the copies now that we've updated the quota
.flatMapSequential(copyParams -> copyToBackup(backupUser, copyParams)
.flatMap(copyResult -> switch (copyResult.outcome()) {
case SUCCESS -> Mono.just(copyResult);
case SOURCE_WRONG_LENGTH, SOURCE_NOT_FOUND, OUT_OF_QUOTA -> Mono
.fromFuture(this.backupsDb.trackMedia(backupUser, -1, -copyParams.destinationObjectSize()))
.thenReturn(copyResult);
}),
backupConfiguration.copyConcurrency(), 1),
// Actually perform the copies now that we've updated the quota
.flatMapSequential(copyParams -> copyToBackup(backupUser, copyParams)
.flatMap(copyResult -> switch (copyResult.outcome()) {
case SUCCESS -> Mono.just(copyResult);
case SOURCE_WRONG_LENGTH, SOURCE_NOT_FOUND, OUT_OF_QUOTA -> Mono
.fromFuture(this.backupsDb.trackMedia(backupUser, -1, -copyParams.destinationObjectSize()))
.thenReturn(copyResult);
}),
backupConfiguration.copyConcurrency(), 1),
// There wasn't enough quota remaining to perform these copies
Flux.fromIterable(quotaResult.requestsToReject())
.map(arg -> new CopyResult(CopyResult.Outcome.OUT_OF_QUOTA, arg.destinationMediaId(), null))
));
// There wasn't enough quota remaining to perform these copies
Flux.fromIterable(copyQuota.requestsToReject())
.map(arg -> new CopyResult(CopyResult.Outcome.OUT_OF_QUOTA, arg.destinationMediaId(), null)));
}
private Mono<CopyResult> copyToBackup(final AuthenticatedBackupUser backupUser, final CopyParameters copyParameters) {
@@ -317,64 +311,66 @@ public class BackupManager {
Mono.just(CopyResult.fromCopyError(throwable, copyParameters.destinationMediaId()).orElseThrow()));
}
private record QuotaResult(List<CopyParameters> requestsToCopy, List<CopyParameters> requestsToReject) {}
public record CopyQuota(AuthenticatedBackupUser backupUser, List<CopyParameters> requestsToCopy, List<CopyParameters> requestsToReject) {
private static CopyQuota create(AuthenticatedBackupUser backupUser, final List<CopyParameters> toCopy, long remainingQuota) {
// Figure out how many of the requested objects fit in the remaining quota
final int index = indexWhereTotalExceeds(toCopy, CopyParameters::destinationObjectSize, remainingQuota);
return new CopyQuota(backupUser, toCopy.subList(0, index), toCopy.subList(index, toCopy.size()));
}
}
/**
* Determine which copy requests can be performed with the user's remaining quota. This does not update the quota.
*
* @param backupUser The user quota to check against
* @param toCopy The proposed copy requests
* @return list of QuotaResult indicating which requests fit into the remaining quota and which requests should be
* @return QuotaResult indicating which requests fit into the remaining quota and which requests should be
* rejected with {@link CopyResult.Outcome#OUT_OF_QUOTA}
* @throws BackupInvalidArgumentException if toCopy contains an invalid copy request
* @throws BackupPermissionException if the credential does not have the correct level
* @throws BackupWrongCredentialTypeException if the credential does not have the media type
*/
private CompletableFuture<QuotaResult> allowedCopies(
public CopyQuota getCopyQuota(
final AuthenticatedBackupUser backupUser,
final List<CopyParameters> toCopy) {
final long totalBytesAdded = toCopy.stream()
.mapToLong(copyParameters -> {
if (copyParameters.sourceLength() > MAX_MEDIA_OBJECT_SIZE || copyParameters.sourceLength() < 0) {
throw Status.INVALID_ARGUMENT
.withDescription("Invalid sourceObject size")
.asRuntimeException();
}
return copyParameters.destinationObjectSize();
})
.sum();
final List<CopyParameters> toCopy,
final long maximumSourceObjectSize)
throws BackupWrongCredentialTypeException, BackupPermissionException, BackupInvalidArgumentException {
checkBackupLevel(backupUser, BackupLevel.PAID);
checkBackupCredentialType(backupUser, BackupCredentialType.MEDIA);
for (CopyParameters copyParameters : toCopy) {
if (copyParameters.sourceLength() > maximumSourceObjectSize || copyParameters.sourceLength() < 0) {
throw new BackupInvalidArgumentException("Invalid sourceObject size");
}
}
final long totalBytesAdded = toCopy.stream().mapToLong(CopyParameters::destinationObjectSize).sum();
final DynamicBackupConfiguration backupConfiguration =
dynamicConfigurationManager.getConfiguration().getBackupConfiguration();
final Duration maxQuotaStaleness = backupConfiguration.maxQuotaStaleness();
final long maxTotalMediaSize = backupConfiguration.maxTotalMediaSize();
return backupsDb.getMediaUsage(backupUser)
.thenComposeAsync(info -> {
long remainingQuota = maxTotalMediaSize - info.usageInfo().bytesUsed();
final boolean canStore = remainingQuota >= totalBytesAdded;
if (canStore || info.lastRecalculationTime().isAfter(clock.instant().minus(maxQuotaStaleness))) {
return CompletableFuture.completedFuture(remainingQuota);
}
final BackupsDb.TimestampedUsageInfo info = backupsDb.getMediaUsage(backupUser).join();
long estimatedRemainingQuota = maxTotalMediaSize - info.usageInfo().bytesUsed();
final boolean canStore = estimatedRemainingQuota >= totalBytesAdded;
if (canStore || info.lastRecalculationTime().isAfter(clock.instant().minus(maxQuotaStaleness))) {
return CopyQuota.create(backupUser, toCopy, estimatedRemainingQuota);
}
// The user is out of quota, and we have not recently recalculated the user's usage. Double check by doing a
// hard recalculation before actually forbidding the user from storing additional media.
return this.remoteStorageManager.calculateBytesUsed(cdnMediaDirectory(backupUser))
.thenCompose(usage -> backupsDb
.setMediaUsage(backupUser, usage)
.thenApply(ignored -> usage))
.whenComplete((newUsage, throwable) -> {
boolean usageChanged = throwable == null && !newUsage.equals(info.usageInfo());
Metrics.counter(USAGE_RECALCULATION_COUNTER_NAME, Tags.of(
UserAgentTagUtil.getPlatformTag(backupUser.userAgent()),
Tag.of("usageChanged", String.valueOf(usageChanged))))
.increment();
})
.thenApply(newUsage -> maxTotalMediaSize - newUsage.bytesUsed());
})
.thenApply(remainingQuota -> {
// Figure out how many of the requested objects fit in the remaining quota
final int index = indexWhereTotalExceeds(toCopy, CopyParameters::destinationObjectSize,
remainingQuota);
return new QuotaResult(toCopy.subList(0, index), toCopy.subList(index, toCopy.size()));
});
// The user is out of quota, and we have not recently recalculated the user's usage. Double check by doing a
// hard recalculation before actually forbidding the user from storing additional media.
boolean usageChanged = false;
try {
final UsageInfo usage =
this.remoteStorageManager.calculateBytesUsed(cdnMediaDirectory(backupUser)).toCompletableFuture().join();
backupsDb.setMediaUsage(backupUser, usage).join();
usageChanged = !usage.equals(info.usageInfo());
final long remainingQuota = maxTotalMediaSize - usage.bytesUsed();
return CopyQuota.create(backupUser, toCopy, remainingQuota);
} finally {
Metrics.counter(USAGE_RECALCULATION_COUNTER_NAME, Tags.of(
UserAgentTagUtil.getPlatformTag(backupUser.userAgent()),
Tag.of("usageChanged", String.valueOf(usageChanged))))
.increment();
}
}
public record RecalculationResult(UsageInfo oldUsage, UsageInfo newUsage) {}
@@ -415,11 +411,14 @@ public class BackupManager {
* @param backupUser an already ZK authenticated backup user
* @param cdnNumber the cdn number to get backup credentials for
* @return A map of headers to include with CDN requests
* @throws BackupPermissionException if the credential does not have the correct level
* @throws BackupInvalidArgumentException if the provided cdnNumber is invalid
*/
public Map<String, String> generateReadAuth(final AuthenticatedBackupUser backupUser, final int cdnNumber) {
public Map<String, String> generateReadAuth(final AuthenticatedBackupUser backupUser, final int cdnNumber)
throws BackupInvalidArgumentException, BackupPermissionException {
checkBackupLevel(backupUser, BackupLevel.FREE);
if (cdnNumber != 3) {
throw Status.INVALID_ARGUMENT.withDescription("unknown cdn").asRuntimeException();
throw new BackupInvalidArgumentException("unknown cdn");
}
return cdn3BackupCredentialGenerator.readHeaders(backupUser.backupDir());
}
@@ -429,8 +428,11 @@ public class BackupManager {
*
* @param backupUser an already ZK authenticated backup user
* @return the credential that may be used with SVRB
* @throws BackupPermissionException if the credential does not have the correct level
* @throws BackupWrongCredentialTypeException if the credential does not have the messages type
*/
public ExternalServiceCredentials generateSvrbAuth(final AuthenticatedBackupUser backupUser) {
public ExternalServiceCredentials generateSvrbAuth(final AuthenticatedBackupUser backupUser)
throws BackupPermissionException, BackupWrongCredentialTypeException {
checkBackupLevel(backupUser, BackupLevel.FREE);
// Clients may only use SVRB with their messages backup-id
checkBackupCredentialType(backupUser, BackupCredentialType.MESSAGES);
@@ -458,64 +460,65 @@ public class BackupManager {
*
* @param backupUser An already ZK authenticated backup user
* @param cursor A cursor returned by a previous call that can be used to resume listing
* @param limit The maximum number of list results to return
* @param limit The maximum number of list results to return, or empty to use
* {@link #DEFAULT_LIST_MEDIA_LIMIT}
* @return A {@link ListMediaResult}
* @throws BackupPermissionException if the credential does not have the correct level
*/
public CompletionStage<ListMediaResult> list(
public ListMediaResult list(
final AuthenticatedBackupUser backupUser,
final Optional<String> cursor,
final int limit) {
final Optional<Integer> limit) throws BackupPermissionException {
checkBackupLevel(backupUser, BackupLevel.FREE);
return remoteStorageManager.list(cdnMediaDirectory(backupUser), cursor, limit)
.thenApply(result ->
new ListMediaResult(
result
.objects()
.stream()
.map(entry -> new StorageDescriptorWithLength(
remoteStorageManager.cdnNumber(),
decodeMediaIdFromCdn(entry.key()),
entry.length()
))
.toList(),
result.cursor()
));
final RemoteStorageManager.ListResult result = remoteStorageManager
.list(cdnMediaDirectory(backupUser), cursor, limit.orElse(DEFAULT_LIST_MEDIA_LIMIT))
.toCompletableFuture().join();
return new ListMediaResult(result
.objects()
.stream()
.map(entry -> new StorageDescriptorWithLength(
remoteStorageManager.cdnNumber(),
decodeMediaIdFromCdn(entry.key()),
entry.length()
))
.toList(),
result.cursor());
}
public CompletableFuture<Void> deleteEntireBackup(final AuthenticatedBackupUser backupUser) {
public void deleteEntireBackup(final AuthenticatedBackupUser backupUser) throws BackupPermissionException {
checkBackupLevel(backupUser, BackupLevel.FREE);
final int deletionConcurrency =
dynamicConfigurationManager.getConfiguration().getBackupConfiguration().deletionConcurrency();
final int deletionConcurrency = backupConfiguration.deletionConcurrency();
// Clients only include SVRB data with their messages backup-id
final CompletableFuture<Void> svrbRemoval = switch(backupUser.credentialType()) {
case BackupCredentialType.MESSAGES -> secureValueRecoveryBClient.removeData(svrbIdentifier(backupUser));
case BackupCredentialType.MEDIA -> CompletableFuture.completedFuture(null);
};
return svrbRemoval.thenCompose(_ -> backupsDb
// Try to swap out the backupDir for the user
.scheduleBackupDeletion(backupUser)
if (backupUser.credentialType() == BackupCredentialType.MESSAGES) {
secureValueRecoveryBClient.removeData(svrbIdentifier(backupUser)).join();
}
try {
// Try to swap out the backupDir for the user
backupsDb.scheduleBackupDeletion(backupUser).join();
} catch (Exception e) {
final Throwable unwrapped = ExceptionUtils.unwrap(e);
if (unwrapped instanceof BackupsDb.PendingDeletionException) {
// If there was already a pending swap, try to delete the cdn objects directly
.exceptionallyCompose(ExceptionUtils.exceptionallyHandler(BackupsDb.PendingDeletionException.class, e ->
AsyncTimerUtil.record(SYNCHRONOUS_DELETE_TIMER, () ->
deletePrefix(backupUser.backupDir(), deletionConcurrency)))));
SYNCHRONOUS_DELETE_TIMER.record(() -> deletePrefix(backupUser.backupDir(), deletionConcurrency).join());
} else {
throw e;
}
}
}
public Flux<StorageDescriptor> deleteMedia(final AuthenticatedBackupUser backupUser,
final List<StorageDescriptor> storageDescriptors) {
final List<StorageDescriptor> storageDescriptors)
throws BackupPermissionException, BackupWrongCredentialTypeException {
checkBackupLevel(backupUser, BackupLevel.FREE);
checkBackupCredentialType(backupUser, BackupCredentialType.MEDIA);
// Check for a cdn we don't know how to process
if (storageDescriptors.stream().anyMatch(sd -> sd.cdn() != remoteStorageManager.cdnNumber())) {
throw Status.INVALID_ARGUMENT
.withDescription("unsupported media cdn provided")
.asRuntimeException();
return Flux.error(new BackupInvalidArgumentException("unsupported media cdn provided"));
}
final DynamicBackupConfiguration backupConfiguration =
dynamicConfigurationManager.getConfiguration().getBackupConfiguration();
return Flux.usingWhen(
@@ -614,42 +617,40 @@ public class BackupManager {
* @param presentation A {@link BackupAuthCredentialPresentation}
* @param signature An XEd25519 signature of the presentation bytes
* @return On authentication success, the authenticated backup-id and backup-tier encoded in the presentation
* @throws BackupFailedZkAuthenticationException If the provided presentation or signature were invalid
*/
public CompletableFuture<AuthenticatedBackupUser> authenticateBackupUser(
public AuthenticatedBackupUser authenticateBackupUser(
final BackupAuthCredentialPresentation presentation,
final byte[] signature,
final String userAgentString) {
final String userAgentString) throws BackupFailedZkAuthenticationException {
final PresentationSignatureVerifier signatureVerifier = verifyPresentation(presentation);
return backupsDb
.retrieveAuthenticationData(presentation.getBackupId())
.thenApply(optionalAuthenticationData -> {
final UserAgent userAgent = parseUserAgent(userAgentString);
final BackupsDb.AuthenticationData authenticationData = optionalAuthenticationData
.orElseGet(() -> {
Metrics.counter(ZK_AUTHN_COUNTER_NAME, Tags.of(
Tag.of(SUCCESS_TAG_NAME, String.valueOf(false)),
Tag.of(FAILURE_REASON_TAG_NAME, "missing_public_key"),
UserAgentTagUtil.getPlatformTag(userAgent)))
.increment();
// There was no stored public key, use a bunk public key so that validation will fail
return new BackupsDb.AuthenticationData(INVALID_PUBLIC_KEY, null, null);
});
final Pair<BackupCredentialType, BackupLevel> credentialTypeAndBackupLevel =
signatureVerifier.verifySignature(signature, authenticationData.publicKey());
return new AuthenticatedBackupUser(
presentation.getBackupId(),
credentialTypeAndBackupLevel.first(),
credentialTypeAndBackupLevel.second(),
authenticationData.backupDir(),
authenticationData.mediaDir(),
userAgent);
})
.thenApply(result -> {
Metrics.counter(ZK_AUTHN_COUNTER_NAME, SUCCESS_TAG_NAME, String.valueOf(true)).increment();
return result;
final Optional<BackupsDb.AuthenticationData> optionalAuthenticationData =
backupsDb.retrieveAuthenticationData(presentation.getBackupId()).join();
final UserAgent userAgent = parseUserAgent(userAgentString);
final BackupsDb.AuthenticationData authenticationData = optionalAuthenticationData
.orElseGet(() -> {
Metrics.counter(ZK_AUTHN_COUNTER_NAME, Tags.of(
Tag.of(SUCCESS_TAG_NAME, String.valueOf(false)),
Tag.of(FAILURE_REASON_TAG_NAME, "missing_public_key"),
UserAgentTagUtil.getPlatformTag(userAgent)))
.increment();
// There was no stored public key, use a bunk public key so that validation will fail
return new BackupsDb.AuthenticationData(INVALID_PUBLIC_KEY, null, null);
});
final Pair<BackupCredentialType, BackupLevel> credentialTypeAndBackupLevel =
signatureVerifier.verifySignature(signature, authenticationData.publicKey());
Metrics.counter(ZK_AUTHN_COUNTER_NAME, SUCCESS_TAG_NAME, String.valueOf(true)).increment();
return new AuthenticatedBackupUser(
presentation.getBackupId(),
credentialTypeAndBackupLevel.first(),
credentialTypeAndBackupLevel.second(),
authenticationData.backupDir(),
authenticationData.mediaDir(),
userAgent);
}
/**
@@ -701,7 +702,6 @@ public class BackupManager {
* List and delete all files associated with a prefix
*
* @param prefixToDelete The prefix to expire.
* @return A stage that completes when all objects with the given prefix have been deleted
*/
private CompletableFuture<Void> deletePrefix(final String prefixToDelete, int concurrentDeletes) {
if (prefixToDelete.length() != BackupsDb.BACKUP_DIRECTORY_PATH_LENGTH
@@ -723,7 +723,6 @@ public class BackupManager {
concurrentDeletes)
.count()
.doOnSuccess(itemsRemoved -> DistributionSummary.builder(DELETE_COUNT_DISTRIBUTION_NAME)
.publishPercentileHistogram(true)
.register(Metrics.globalRegistry)
.record(itemsRemoved))
.then()
@@ -732,7 +731,7 @@ public class BackupManager {
interface PresentationSignatureVerifier {
Pair<BackupCredentialType, BackupLevel> verifySignature(byte[] signature, ECPublicKey publicKey);
Pair<BackupCredentialType, BackupLevel> verifySignature(byte[] signature, ECPublicKey publicKey) throws BackupFailedZkAuthenticationException;
}
/**
@@ -741,7 +740,8 @@ public class BackupManager {
* @param presentation A ZK credential presentation that encodes the backupId and the receipt level of the requester
* @return A function that can be used to verify a signature provided with the presentation
*/
private PresentationSignatureVerifier verifyPresentation(final BackupAuthCredentialPresentation presentation) {
private PresentationSignatureVerifier verifyPresentation(final BackupAuthCredentialPresentation presentation)
throws BackupFailedZkAuthenticationException {
try {
presentation.verify(clock.instant(), serverSecretParams);
} catch (VerificationFailedException e) {
@@ -749,10 +749,7 @@ public class BackupManager {
SUCCESS_TAG_NAME, String.valueOf(false),
FAILURE_REASON_TAG_NAME, "presentation_verification")
.increment();
throw Status.UNAUTHENTICATED
.withDescription("backup auth credential presentation verification failed")
.withCause(e)
.asRuntimeException();
throw new BackupFailedZkAuthenticationException("backup auth credential presentation verification failed");
}
return (signature, publicKey) -> {
if (!publicKey.verifySignature(presentation.serialize(), signature)) {
@@ -760,9 +757,7 @@ public class BackupManager {
SUCCESS_TAG_NAME, String.valueOf(false),
FAILURE_REASON_TAG_NAME, "signature_validation")
.increment();
throw Status.UNAUTHENTICATED
.withDescription("backup auth credential presentation signature verification failed")
.asRuntimeException();
throw new BackupFailedZkAuthenticationException("backup auth credential presentation signature verification failed");
}
return new Pair<>(presentation.getType(), presentation.getBackupLevel());
};
@@ -773,19 +768,18 @@ public class BackupManager {
*
* @param backupUser The backup user to check
* @param backupLevel The authorization level to verify the backupUser has access to
* @throws {@link Status#PERMISSION_DENIED} error if the backup user is not authorized to access {@code backupLevel}
* @throws BackupPermissionException if the backupUser is not authorized to access {@code backupLevel}
*/
@VisibleForTesting
static void checkBackupLevel(final AuthenticatedBackupUser backupUser, final BackupLevel backupLevel) {
static void checkBackupLevel(final AuthenticatedBackupUser backupUser, final BackupLevel backupLevel)
throws BackupPermissionException {
if (backupUser.backupLevel().compareTo(backupLevel) < 0) {
Metrics.counter(ZK_AUTHZ_FAILURE_COUNTER_NAME, Tags.of(
UserAgentTagUtil.getPlatformTag(backupUser.userAgent()),
Tag.of(FAILURE_REASON_TAG_NAME, "level")))
.increment();
throw Status.PERMISSION_DENIED
.withDescription("credential does not support the requested operation")
.asRuntimeException();
throw new BackupPermissionException("credential does not support the requested operation");
}
}
@@ -794,19 +788,17 @@ public class BackupManager {
*
* @param backupUser The backup user to check
* @param credentialType The credential type to require
* @throws {@link Status#UNAUTHENTICATED} error if the backup user is not authenticated with the given
* @throws BackupWrongCredentialTypeException error if the backup user is not authenticated with the given
* {@code credentialType}
*/
@VisibleForTesting
static void checkBackupCredentialType(final AuthenticatedBackupUser backupUser, final BackupCredentialType credentialType) {
static void checkBackupCredentialType(final AuthenticatedBackupUser backupUser, final BackupCredentialType credentialType) throws BackupWrongCredentialTypeException {
if (backupUser.credentialType() != credentialType) {
Metrics.counter(ZK_AUTHZ_FAILURE_COUNTER_NAME,
FAILURE_REASON_TAG_NAME, "credential_type")
.increment();
throw Status.UNAUTHENTICATED
.withDescription("wrong credential type for the requested operation")
.asRuntimeException();
throw new BackupWrongCredentialTypeException("wrong credential type for the requested operation");
}
}
@@ -0,0 +1,11 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.backup;
public class BackupMissingIdCommitmentException extends BackupException {
public BackupMissingIdCommitmentException() {
super();
}
}
@@ -0,0 +1,12 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.backup;
public class BackupNotFoundException extends BackupException {
public BackupNotFoundException(final String message) {
super(message);
}
}
@@ -0,0 +1,11 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.backup;
public class BackupPermissionException extends BackupException {
public BackupPermissionException(String message) {
super(message);
}
}
@@ -0,0 +1,8 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.backup;
public class BackupPublicKeyConflictException extends BackupException {
}
@@ -0,0 +1,11 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.backup;
public class BackupWrongCredentialTypeException extends BackupException {
public BackupWrongCredentialTypeException(String message) {
super(message);
}
}
@@ -4,8 +4,8 @@
*/
package org.whispersystems.textsecuregcm.backup;
import io.grpc.Status;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
@@ -22,18 +22,12 @@ import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.function.Predicate;
import io.micrometer.core.instrument.DistributionSummary;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import org.signal.libsignal.protocol.InvalidKeyException;
import org.signal.libsignal.protocol.ecc.ECPublicKey;
import org.signal.libsignal.zkgroup.backups.BackupLevel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.auth.AuthenticatedBackupUser;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.util.AttributeValues;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import org.whispersystems.textsecuregcm.util.Util;
@@ -133,7 +127,7 @@ public class BackupsDb {
* @param authenticatedBackupLevel The backup level
* @param publicKey The public key to associate with the backup id
* @return A stage that completes when the public key has been set. If the backup-id already has a set public key that
* does not match, the stage will be completed exceptionally with a {@link PublicKeyConflictException}
* does not match, the stage will be completed exceptionally with a {@link BackupPublicKeyConflictException}
*/
CompletableFuture<Void> setPublicKey(
final byte[] authenticatedBackupId,
@@ -152,7 +146,7 @@ public class BackupsDb {
.build())
.exceptionally(ExceptionUtils.marshal(ConditionalCheckFailedException.class, e ->
// There was already a row for this backup-id and it contained a different publicKey
new PublicKeyConflictException()))
new BackupPublicKeyConflictException()))
.thenRun(Util.NOOP);
}
@@ -190,9 +184,7 @@ public class BackupsDb {
private static String getDirName(final Map<String, AttributeValue> item, final String attr) {
return AttributeValues.get(item, attr).map(AttributeValue::s).orElseThrow(() -> {
logger.error("Backups with public keys should have directory names");
return Status.INTERNAL
.withDescription("Backups with public keys must have directory names")
.asRuntimeException();
throw new UncheckedIOException(new IOException("Backups with public keys must have directory names"));
});
}
@@ -208,10 +200,7 @@ public class BackupsDb {
return new ECPublicKey(publicKeyBytes);
} catch (InvalidKeyException e) {
logger.error("Invalid publicKey {}", HexFormat.of().formatHex(publicKeyBytes), e);
throw Status.INTERNAL
.withCause(e)
.withDescription("Could not deserialize stored public key")
.asRuntimeException();
throw new UncheckedIOException(new IOException("Could not deserialize stored public key"));
}
}
@@ -330,6 +319,7 @@ public class BackupsDb {
* @param backupUser an already authorized backup user
* @return A {@link BackupDescription} containing the cdn of the message backup and the total number of media space
* bytes used by the backup user.
* @throws BackupNotFoundException If the provided backupUser's backup-id does not exist
*/
CompletableFuture<BackupDescription> describeBackup(final AuthenticatedBackupUser backupUser) {
return dynamoClient.getItem(GetItemRequest.builder()
@@ -341,7 +331,9 @@ public class BackupsDb {
.build())
.thenApply(response -> {
if (!response.hasItem()) {
throw Status.NOT_FOUND.withDescription("Backup ID not found").asRuntimeException();
// At this point, the user has already authenticated against this backup record, so we must have raced
// with a deletion. Just throw the same error we would have thrown if authentication had failed
throw ExceptionUtils.wrap(new BackupFailedZkAuthenticationException("Backup ID not found"));
}
// If the client hasn't already uploaded a backup, return the cdn we would return if they did create one
final int cdn = AttributeValues.getInt(response.item(), ATTR_CDN, BACKUP_CDN);
@@ -7,8 +7,7 @@ package org.whispersystems.textsecuregcm.backup;
import org.apache.http.HttpHeaders;
import org.whispersystems.textsecuregcm.attachments.TusConfiguration;
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
import org.whispersystems.textsecuregcm.auth.JwtGenerator;
import org.whispersystems.textsecuregcm.util.HeaderUtils;
import java.nio.charset.StandardCharsets;
@@ -17,47 +16,29 @@ import java.util.Base64;
import java.util.Map;
public class Cdn3BackupCredentialGenerator {
public static final String CDN_PATH = "backups";
public static final int BACKUP_CDN = 3;
private static String READ_PERMISSION = "read";
private static String WRITE_PERMISSION = "write";
private static String PERMISSION_SEPARATOR = "$";
// Write entities will be of the form 'write$backups/<string>
private static final String WRITE_ENTITY_PREFIX = String.format("%s%s%s/", WRITE_PERMISSION, PERMISSION_SEPARATOR,
CDN_PATH);
// Read entities will be of the form 'read$backups/<string>
private static final String READ_ENTITY_PREFIX = String.format("%s%s%s/", READ_PERMISSION, PERMISSION_SEPARATOR,
CDN_PATH);
private final ExternalServiceCredentialsGenerator credentialsGenerator;
private final String tusUri;
private final JwtGenerator jwtGenerator;
public Cdn3BackupCredentialGenerator(final TusConfiguration cfg) {
this.tusUri = cfg.uploadUri();
this.credentialsGenerator = credentialsGenerator(Clock.systemUTC(), cfg);
this.jwtGenerator = new JwtGenerator(cfg.userAuthenticationTokenSharedSecret().value(), Clock.systemUTC());
}
private static ExternalServiceCredentialsGenerator credentialsGenerator(final Clock clock,
final TusConfiguration cfg) {
return ExternalServiceCredentialsGenerator
.builder(cfg.userAuthenticationTokenSharedSecret())
.prependUsername(false)
.withClock(clock)
.build();
}
public BackupUploadDescriptor generateUpload(final String key) {
public BackupUploadDescriptor generateUpload(final String key, final long uploadSize) {
if (key.isBlank()) {
throw new IllegalArgumentException("Upload descriptors must have non-empty keys");
}
final String entity = WRITE_ENTITY_PREFIX + key;
final ExternalServiceCredentials credentials = credentialsGenerator.generateFor(entity);
final String token = jwtGenerator.generateJwt(CDN_PATH, key, builder -> builder
.withClaim(JwtGenerator.MAX_LENGTH_CLAIM_KEY, uploadSize)
.withClaim(JwtGenerator.SCOPE_CLAIM_KEY, "write"));
final String b64Key = Base64.getEncoder().encodeToString(key.getBytes(StandardCharsets.UTF_8));
final Map<String, String> headers = Map.of(
HttpHeaders.AUTHORIZATION, HeaderUtils.basicAuthHeader(credentials),
HttpHeaders.AUTHORIZATION, HeaderUtils.bearerAuthHeader(token),
"Upload-Metadata", String.format("filename %s", b64Key));
return new BackupUploadDescriptor(
@@ -71,8 +52,9 @@ public class Cdn3BackupCredentialGenerator {
if (hashedBackupId.isBlank()) {
throw new IllegalArgumentException("Backup subdir name must be non-empty");
}
final ExternalServiceCredentials credentials = credentialsGenerator.generateFor(
READ_ENTITY_PREFIX + hashedBackupId);
return Map.of(HttpHeaders.AUTHORIZATION, HeaderUtils.basicAuthHeader(credentials));
final String token = jwtGenerator.generateJwt(CDN_PATH, hashedBackupId, builder -> builder
.withClaim(JwtGenerator.SCOPE_CLAIM_KEY, "read"));
return Map.of(HttpHeaders.AUTHORIZATION, HeaderUtils.bearerAuthHeader(token));
}
}
@@ -42,6 +42,7 @@ public class Cdn3RemoteStorageManager implements RemoteStorageManager {
private final String clientId;
private final String clientSecret;
private final Map<Integer, String> sourceSchemes;
private final Duration usageRequestTimeout;
static final String CLIENT_ID_HEADER = "CF-Access-Client-Id";
static final String CLIENT_SECRET_HEADER = "CF-Access-Client-Secret";
@@ -75,6 +76,7 @@ public class Cdn3RemoteStorageManager implements RemoteStorageManager {
.withNumClients(configuration.numHttpClients())
.build();
this.sourceSchemes = configuration.sourceSchemes();
this.usageRequestTimeout = configuration.usageRequestTimeout();
}
@Override
@@ -86,7 +88,7 @@ public class Cdn3RemoteStorageManager implements RemoteStorageManager {
public CompletionStage<Void> copy(
final int sourceCdn,
final String sourceKey,
final int expectedSourceLength,
final long expectedSourceLength,
final MediaEncryptionParameters encryptionParameters,
final String destinationKey) {
final String sourceScheme = this.sourceSchemes.get(sourceCdn);
@@ -132,10 +134,10 @@ public class Cdn3RemoteStorageManager implements RemoteStorageManager {
*/
record Cdn3CopyRequest(
String encryptionKey, String hmacKey,
SourceDescriptor source, int expectedSourceLength,
SourceDescriptor source, long expectedSourceLength,
String dst) {
Cdn3CopyRequest(MediaEncryptionParameters parameters, SourceDescriptor source, int expectedSourceLength,
Cdn3CopyRequest(MediaEncryptionParameters parameters, SourceDescriptor source, long expectedSourceLength,
String dst) {
this(Base64.getEncoder().encodeToString(parameters.aesEncryptionKey().getEncoded()),
Base64.getEncoder().encodeToString(parameters.hmacSHA256Key().getEncoded()),
@@ -231,6 +233,7 @@ public class Cdn3RemoteStorageManager implements RemoteStorageManager {
HttpUtils.queryParamString(Map.of("prefix", prefix).entrySet()))))
.header(CLIENT_ID_HEADER, clientId)
.header(CLIENT_SECRET_HEADER, clientSecret)
.timeout(usageRequestTimeout)
.build();
return this.storageManagerHttpClient.sendAsync(request, HttpResponse.BodyHandlers.ofInputStream())
.thenApply(response -> {
@@ -4,6 +4,8 @@
*/
package org.whispersystems.textsecuregcm.backup;
import com.google.common.annotations.VisibleForTesting;
/**
* Descriptor for a single copy-and-encrypt operation
*
@@ -16,7 +18,7 @@ package org.whispersystems.textsecuregcm.backup;
public record CopyParameters(
int sourceCdn,
String sourceKey,
int sourceLength,
long sourceLength,
MediaEncryptionParameters encryptionParameters,
byte[] destinationMediaId) {
@@ -24,6 +26,26 @@ public record CopyParameters(
* @return The size of the double-encrypted destination object after it is copied
*/
long destinationObjectSize() {
return encryptionParameters().outputSize(sourceLength());
return destinationObjectSize(sourceLength());
}
/// Calculates the size of a ciphertext for a media object stored as part of a backup
///
/// @param inputSize the size, in bytes, of the plaintext media object
///
/// @return the size, in bytes, of the ciphertext of a media object with the given `inputSize`
@VisibleForTesting
static long destinationObjectSize(final long inputSize) {
if (inputSize < 0) {
throw new IllegalArgumentException("Size must be non-negative, but was " + inputSize);
}
// AES-256 has 16-byte block size, and always adds a block if the plaintext is a multiple of the block size
final long numBlocks = Math.addExact(inputSize, 16L) / 16;
final long cipherTextLength = Math.multiplyExact(numBlocks, 16);
// 16-byte IV will be generated and prepended to the ciphertext.
// IV + AES-256 encrypted data + HmacSHA256
return Math.addExact(cipherTextLength, 16L + 32);
}
}
@@ -11,12 +11,4 @@ public record MediaEncryptionParameters(
new SecretKeySpec(encryptionKey, "AES"),
new SecretKeySpec(macKey, "HmacSHA256"));
}
public int outputSize(final int inputSize) {
// AES-256 has 16-byte block size, and always adds a block if the plaintext is a multiple of the block size
final int numBlocks = (inputSize + 16) / 16;
// 16-byte IV will be generated and prepended to the ciphertext
// IV + AES-256 encrypted data + HmacSHA256
return 16 + (numBlocks * 16) + 32;
}
}
@@ -1,6 +0,0 @@
package org.whispersystems.textsecuregcm.backup;
import java.io.IOException;
public class PublicKeyConflictException extends IOException {
}
@@ -35,7 +35,7 @@ public interface RemoteStorageManager {
CompletionStage<Void> copy(
int sourceCdn,
String sourceKey,
int expectedSourceLength,
long expectedSourceLength,
MediaEncryptionParameters encryptionParameters,
String dstKey);
@@ -10,5 +10,8 @@ import java.util.Locale;
import org.whispersystems.textsecuregcm.entities.Badge;
public interface BadgeTranslator {
Locale resolveLocale(List<Locale> acceptableLanguages);
Badge translate(List<Locale> acceptableLanguages, String badgeId);
}
@@ -7,7 +7,6 @@ package org.whispersystems.textsecuregcm.badges;
import com.google.common.annotations.VisibleForTesting;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
@@ -31,7 +30,6 @@ public class ConfiguredProfileBadgeConverter implements ProfileBadgeConverter, B
private final Clock clock;
private final Map<String, BadgeConfiguration> knownBadges;
private final List<String> badgeIdsEnabledForAll;
private final HeaderControlledResourceBundleLookup headerControlledResourceBundleLookup;
public ConfiguredProfileBadgeConverter(
@@ -41,10 +39,14 @@ public class ConfiguredProfileBadgeConverter implements ProfileBadgeConverter, B
this.clock = clock;
this.knownBadges = badgesConfiguration.getBadges().stream()
.collect(Collectors.toMap(BadgeConfiguration::getId, Function.identity()));
this.badgeIdsEnabledForAll = badgesConfiguration.getBadgeIdsEnabledForAll();
this.headerControlledResourceBundleLookup = headerControlledResourceBundleLookup;
}
@Override
public Locale resolveLocale(final List<Locale> acceptableLanguages) {
return headerControlledResourceBundleLookup.getResourceBundle(BASE_NAME, acceptableLanguages).getLocale();
}
@Override
public Badge translate(final List<Locale> acceptableLanguages, final String badgeId) {
final ResourceBundle resourceBundle = headerControlledResourceBundleLookup.getResourceBundle(BASE_NAME,
@@ -63,12 +65,27 @@ public class ConfiguredProfileBadgeConverter implements ProfileBadgeConverter, B
false);
}
@Override
public List<String> visibleBadgeIds(final List<AccountBadge> accountBadges) {
if (accountBadges.isEmpty()) {
return List.of();
}
final Instant now = clock.instant();
return accountBadges.stream()
.filter(accountBadge -> accountBadge.visible()
&& now.isBefore(accountBadge.expiration())
&& knownBadges.containsKey(accountBadge.id()))
.map(AccountBadge::id)
.toList();
}
@Override
public List<Badge> convert(
final List<Locale> acceptableLanguages,
final List<AccountBadge> accountBadges,
final boolean isSelf) {
if (accountBadges.isEmpty() && badgeIdsEnabledForAll.isEmpty()) {
if (accountBadges.isEmpty()) {
return List.of();
}
@@ -94,20 +111,6 @@ public class ConfiguredProfileBadgeConverter implements ProfileBadgeConverter, B
accountBadge.visible());
})
.collect(Collectors.toCollection(ArrayList::new));
badges.addAll(badgeIdsEnabledForAll.stream().filter(knownBadges::containsKey).map(id -> {
BadgeConfiguration configuration = knownBadges.get(id);
return newBadge(
isSelf,
id,
configuration.getCategory(),
resourceBundle.getString(id + "_name"),
resourceBundle.getString(id + "_description"),
configuration.getSprites(),
configuration.getSvg(),
configuration.getSvgs(),
now.plus(Duration.ofDays(1)),
true);
}).collect(Collectors.toList()));
return badges;
}
@@ -12,6 +12,12 @@ import org.whispersystems.textsecuregcm.storage.AccountBadge;
public interface ProfileBadgeConverter {
/// Determine displayable badge ids for an account's badges
///
/// @param badges The full list of badges on an account
/// @return The list of badge-ids that should appear on this account's profile to other users
List<String> visibleBadgeIds(final List<AccountBadge> badges);
/**
* Converts the {@link AccountBadge}s for an account into the objects
* that can be returned on a profile fetch.
@@ -93,6 +93,9 @@ public class AssessmentResult {
return this.actualScore;
}
public int getNormalizedIntScore() {
return normalizedIntScore(this.actualScore);
}
/**
* Map a captcha score in [0.0, 1.0] to a low cardinality discrete space in [0, 100] suitable for use in metrics
@@ -16,6 +16,7 @@ import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.function.Function;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -52,20 +53,20 @@ public class CaptchaChecker {
* @param userAgent User-Agent of the solver
* @return An {@link AssessmentResult} indicating whether the solution should be accepted, and a score that can be
* used for metrics
* @throws IOException if there is an error validating the captcha with the underlying service
* @throws BadRequestException if input is not in the expected format
* @throws IOException if there is an error validating the captcha with the underlying service
* @throws InvalidCaptchaArgumentException if input is not in the expected format
*/
public AssessmentResult verify(
final Optional<UUID> maybeAci,
final Action expectedAction,
final String input,
final String ip,
final String userAgent) throws IOException {
@Nullable final String userAgent) throws IOException, InvalidCaptchaArgumentException {
final String[] parts = input.split("\\" + SEPARATOR, 4);
// we allow missing actions, if we're missing 1 part, assume it's the action
if (parts.length < 4) {
throw new BadRequestException("too few parts");
throw new InvalidCaptchaArgumentException("too few parts");
}
final String prefix = parts[0];
@@ -78,30 +79,30 @@ public class CaptchaChecker {
// This is a "short" solution that points to the actual solution. We need to fetch the
// full solution before proceeding
provider = prefix.substring(0, prefix.length() - SHORT_SUFFIX.length());
token = shortCodeExpander.retrieve(token).orElseThrow(() -> new BadRequestException("invalid shortcode"));
token = shortCodeExpander.retrieve(token).orElseThrow(() -> new InvalidCaptchaArgumentException("invalid shortcode"));
}
final CaptchaClient client = this.captchaClientSupplier.apply(provider);
if (client == null) {
throw new BadRequestException("invalid captcha scheme");
throw new InvalidCaptchaArgumentException("invalid captcha scheme");
}
final Action parsedAction = Action.parse(action)
.orElseThrow(() -> {
Metrics.counter(INVALID_ACTION_COUNTER_NAME, "action", action).increment();
return new BadRequestException("invalid captcha action");
Metrics.counter(INVALID_ACTION_COUNTER_NAME).increment();
return new InvalidCaptchaArgumentException("invalid captcha action");
});
if (!parsedAction.equals(expectedAction)) {
Metrics.counter(INVALID_ACTION_COUNTER_NAME, "action", action).increment();
throw new BadRequestException("invalid captcha action");
throw new InvalidCaptchaArgumentException("invalid captcha action");
}
final Set<String> allowedSiteKeys = client.validSiteKeys(parsedAction);
if (!allowedSiteKeys.contains(siteKey)) {
logger.debug("invalid site-key {}, action={}, token={}", siteKey, action, token);
logger.debug("invalid site-key {}, action={}", siteKey, action);
Metrics.counter(INVALID_SITEKEY_COUNTER_NAME, "action", action).increment();
throw new BadRequestException("invalid captcha site-key");
throw new InvalidCaptchaArgumentException("invalid captcha site-key");
}
final AssessmentResult result = client.verify(maybeAci, siteKey, parsedAction, token, ip, userAgent);
@@ -5,6 +5,7 @@
package org.whispersystems.textsecuregcm.captcha;
import javax.annotation.Nullable;
import java.io.IOException;
import java.util.Optional;
import java.util.Set;
@@ -42,7 +43,7 @@ public interface CaptchaClient {
final Action action,
final String token,
final String ip,
final String userAgent) throws IOException;
@Nullable final String userAgent) throws IOException;
static CaptchaClient noop() {
return new CaptchaClient() {
@@ -58,7 +59,7 @@ public interface CaptchaClient {
@Override
public AssessmentResult verify(final Optional<UUID> maybeAci, final String siteKey, final Action action, final String token, final String ip,
final String userAgent) throws IOException {
@Nullable final String userAgent) throws IOException {
return AssessmentResult.alwaysValid();
}
};
@@ -0,0 +1,15 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.captcha;
/**
* Indicates that a captcha solution was malformed
*/
public class InvalidCaptchaArgumentException extends Exception {
public InvalidCaptchaArgumentException(String message) {
super(message);
}
}
@@ -19,7 +19,7 @@ public class RegistrationCaptchaManager {
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
public Optional<AssessmentResult> assessCaptcha(final Optional<UUID> aci, final Optional<String> captcha, final String sourceHost, final String userAgent)
throws IOException {
throws IOException, InvalidCaptchaArgumentException{
return captcha.isPresent()
? Optional.of(captchaChecker.verify(aci, Action.REGISTRATION, captcha.get(), sourceHost, userAgent))
: Optional.empty();
@@ -12,6 +12,7 @@ import jakarta.validation.constraints.NotNull;
import java.util.List;
import java.util.Map;
import org.whispersystems.textsecuregcm.configuration.secrets.SecretString;
import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel;
import javax.annotation.Nullable;
/**
@@ -38,7 +39,7 @@ public record AppleAppStoreConfiguration(
@NotBlank String keyId,
@NotNull SecretString encodedKey,
@NotBlank String subscriptionGroupId,
@NotNull Map<String, Long> productIdToLevel,
@NotNull Map<String, ReceiptLevel> productIdToLevel,
@NotNull List<@NotBlank String> appleRootCerts,
@Nullable String retryConfigurationName) {
}
@@ -0,0 +1,12 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration;
import jakarta.validation.constraints.Positive;
public record AttachmentsConfiguration(
@Positive long maxAttachmentUploadSizeInBytes,
@Positive long maxMessageBackupUploadSizeInBytes) {
}
@@ -3,7 +3,7 @@
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration.dynamic;
package org.whispersystems.textsecuregcm.configuration;
import io.dropwizard.util.DataSize;
import jakarta.validation.constraints.NotNull;
@@ -17,14 +17,14 @@ import java.time.Duration;
* @param maxQuotaStaleness The maximum age of a quota estimate that can be used to enforce a quota limit
* @param maxTotalMediaSize The number of media bytes a paid-tier user may store
*/
public record DynamicBackupConfiguration(
public record BackupConfiguration(
@NotNull Integer deletionConcurrency,
@NotNull Integer copyConcurrency,
@NotNull Integer usageCheckpointCount,
@NotNull Duration maxQuotaStaleness,
@NotNull Long maxTotalMediaSize) {
public DynamicBackupConfiguration {
public BackupConfiguration {
if (deletionConcurrency == null) {
deletionConcurrency = 10;
}
@@ -42,7 +42,7 @@ public record DynamicBackupConfiguration(
}
}
public DynamicBackupConfiguration() {
public BackupConfiguration() {
this(null, null, null, null, null);
}
}
@@ -13,6 +13,7 @@ import com.fasterxml.jackson.annotation.Nulls;
import io.dropwizard.validation.ValidationMethod;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel;
import java.util.List;
import java.util.Map;
import java.util.Objects;
@@ -21,16 +22,13 @@ import java.util.stream.Collectors;
public class BadgesConfiguration {
private final List<BadgeConfiguration> badges;
private final List<String> badgeIdsEnabledForAll;
private final Map<Long, String> receiptLevels;
private final Map<ReceiptLevel, String> receiptLevels;
@JsonCreator
public BadgesConfiguration(
@JsonProperty("badges") @JsonSetter(nulls = Nulls.AS_EMPTY) final List<BadgeConfiguration> badges,
@JsonProperty("badgeIdsEnabledForAll") @JsonSetter(nulls = Nulls.AS_EMPTY) final List<String> badgeIdsEnabledForAll,
@JsonProperty("receiptLevels") @JsonSetter(nulls = Nulls.AS_EMPTY) final Map<Long, String> receiptLevels) {
@JsonProperty("receiptLevels") @JsonSetter(nulls = Nulls.AS_EMPTY) final Map<ReceiptLevel, String> receiptLevels) {
this.badges = Objects.requireNonNull(badges);
this.badgeIdsEnabledForAll = Objects.requireNonNull(badgeIdsEnabledForAll);
this.receiptLevels = Objects.requireNonNull(receiptLevels);
}
@@ -42,13 +40,7 @@ public class BadgesConfiguration {
@Valid
@NotNull
public List<String> getBadgeIdsEnabledForAll() {
return badgeIdsEnabledForAll;
}
@Valid
@NotNull
public Map<Long, String> getReceiptLevels() {
public Map<ReceiptLevel, String> getReceiptLevels() {
return receiptLevels;
}
@@ -2,6 +2,7 @@ package org.whispersystems.textsecuregcm.configuration;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import java.time.Duration;
import java.util.Collections;
import java.util.Map;
import org.whispersystems.textsecuregcm.configuration.secrets.SecretString;
@@ -21,6 +22,8 @@ import javax.annotation.Nullable;
* client; if `null`, uses the global default configuration
* @param retryConfigurationName The name of a retry configuration for the storage-manager http client; if
* `null`, uses the global default configuration
* @param usageRequestTimeout The per-attempt request timeout for usage requests to the storage-manager; if
* `null`, defaults to 5 minutes
*/
public record Cdn3StorageManagerConfiguration(
@NotNull String baseUri,
@@ -29,7 +32,8 @@ public record Cdn3StorageManagerConfiguration(
@NotNull Map<Integer, String> sourceSchemes,
@NotNull Integer numHttpClients,
@Nullable String circuitBreakerConfigurationName,
@Nullable String retryConfigurationName) {
@Nullable String retryConfigurationName,
@NotNull Duration usageRequestTimeout) {
public Cdn3StorageManagerConfiguration {
if (numHttpClients == null) {
@@ -38,5 +42,8 @@ public record Cdn3StorageManagerConfiguration(
if (sourceSchemes == null) {
sourceSchemes = Collections.emptyMap();
}
if (usageRequestTimeout == null) {
usageRequestTimeout = Duration.ofMinutes(5);
}
}
}
@@ -0,0 +1,11 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration;
import java.time.Duration;
public record ChangeNumberConfiguration(Duration postRegistrationWaitingPeriod) {
}
@@ -10,6 +10,5 @@ import java.time.Duration;
* Configuration for Device Check operations
*
* @param backupRedemptionDuration How long to grant backup access for redemptions via device check
* @param backupRedemptionLevel What backup level to grant redemptions via device check
*/
public record DeviceCheckConfiguration(Duration backupRedemptionDuration, long backupRedemptionLevel) {}
public record DeviceCheckConfiguration(Duration backupRedemptionDuration) {}
@@ -49,22 +49,24 @@ public class DynamoDbTables {
private final AccountsTableConfiguration accounts;
private final Table appleDeviceChecks;
private final Table changeNumberWaitingPeriods;
private final Table appleDeviceCheckPublicKeys;
private final Table backups;
private final Table clientPublicKeys;
private final Table clientReleases;
private final Table deletedAccounts;
private final Table deletedAccountsLock;
private final TableWithExpiration donationPermits;
private final IssuedReceiptsTableConfiguration issuedReceipts;
private final Table ecKeys;
private final Table ecSignedPreKeys;
private final Table kemKeys;
private final Table kemLastResortKeys;
private final Table pagedKemKeys;
private final TableWithExpiration messages;
private final TableWithExpiration onetimeDonations;
private final Table phoneNumberIdentifiers;
private final Table profileAvatars;
private final Table profiles;
private final Table profilesV2;
private final Table pushChallenge;
private final Table pushNotificationExperimentSamples;
private final TableWithExpiration redeemedReceipts;
@@ -78,22 +80,24 @@ public class DynamoDbTables {
public DynamoDbTables(
@JsonProperty("accounts") final AccountsTableConfiguration accounts,
@JsonProperty("appleDeviceChecks") final Table appleDeviceChecks,
@JsonProperty("changeNumberWaitingPeriods") final Table changeNumberWaitingPeriods,
@JsonProperty("appleDeviceCheckPublicKeys") final Table appleDeviceCheckPublicKeys,
@JsonProperty("backups") final Table backups,
@JsonProperty("clientPublicKeys") final Table clientPublicKeys,
@JsonProperty("clientReleases") final Table clientReleases,
@JsonProperty("deletedAccounts") final Table deletedAccounts,
@JsonProperty("deletedAccountsLock") final Table deletedAccountsLock,
@JsonProperty("donationPermits") final TableWithExpiration donationPermits,
@JsonProperty("issuedReceipts") final IssuedReceiptsTableConfiguration issuedReceipts,
@JsonProperty("ecKeys") final Table ecKeys,
@JsonProperty("ecSignedPreKeys") final Table ecSignedPreKeys,
@JsonProperty("pqKeys") final Table kemKeys,
@JsonProperty("pqLastResortKeys") final Table kemLastResortKeys,
@JsonProperty("pagedPqKeys") final Table pagedKemKeys,
@JsonProperty("messages") final TableWithExpiration messages,
@JsonProperty("onetimeDonations") final TableWithExpiration onetimeDonations,
@JsonProperty("phoneNumberIdentifiers") final Table phoneNumberIdentifiers,
@JsonProperty("profileAvatars") final Table profileAvatars,
@JsonProperty("profiles") final Table profiles,
@JsonProperty("profilesV2") final Table profilesV2,
@JsonProperty("pushChallenge") final Table pushChallenge,
@JsonProperty("pushNotificationExperimentSamples") final Table pushNotificationExperimentSamples,
@JsonProperty("redeemedReceipts") final TableWithExpiration redeemedReceipts,
@@ -106,22 +110,24 @@ public class DynamoDbTables {
this.accounts = accounts;
this.appleDeviceChecks = appleDeviceChecks;
this.changeNumberWaitingPeriods = changeNumberWaitingPeriods;
this.appleDeviceCheckPublicKeys = appleDeviceCheckPublicKeys;
this.backups = backups;
this.clientPublicKeys = clientPublicKeys;
this.clientReleases = clientReleases;
this.deletedAccounts = deletedAccounts;
this.deletedAccountsLock = deletedAccountsLock;
this.donationPermits = donationPermits;
this.issuedReceipts = issuedReceipts;
this.ecKeys = ecKeys;
this.ecSignedPreKeys = ecSignedPreKeys;
this.kemKeys = kemKeys;
this.pagedKemKeys = pagedKemKeys;
this.kemLastResortKeys = kemLastResortKeys;
this.messages = messages;
this.onetimeDonations = onetimeDonations;
this.phoneNumberIdentifiers = phoneNumberIdentifiers;
this.profileAvatars = profileAvatars;
this.profiles = profiles;
this.profilesV2 = profilesV2;
this.pushChallenge = pushChallenge;
this.pushNotificationExperimentSamples = pushNotificationExperimentSamples;
this.redeemedReceipts = redeemedReceipts;
@@ -145,6 +151,12 @@ public class DynamoDbTables {
return appleDeviceChecks;
}
@NotNull
@Valid
public Table getChangeNumberWaitingPeriods() {
return changeNumberWaitingPeriods;
}
@NotNull
@Valid
public Table getAppleDeviceCheckPublicKeys() {
@@ -157,12 +169,6 @@ public class DynamoDbTables {
return backups;
}
@NotNull
@Valid
public Table getClientPublicKeys() {
return clientPublicKeys;
}
@NotNull
@Valid
public Table getClientReleases() {
@@ -181,6 +187,12 @@ public class DynamoDbTables {
return deletedAccountsLock;
}
@NotNull
@Valid
public TableWithExpiration getDonationPermits() {
return donationPermits;
}
@NotNull
@Valid
public IssuedReceiptsTableConfiguration getIssuedReceipts() {
@@ -199,12 +211,6 @@ public class DynamoDbTables {
return ecSignedPreKeys;
}
@NotNull
@Valid
public Table getKemKeys() {
return kemKeys;
}
@NotNull
@Valid
public Table getPagedKemKeys() {
@@ -237,10 +243,22 @@ public class DynamoDbTables {
@NotNull
@Valid
public Table getProfiles() {
public Table getProfileAvatars() {
return profileAvatars;
}
@NotNull
@Valid
public Table getProfilesV1() {
return profiles;
}
@NotNull
@Valid
public Table getProfilesV2() {
return profilesV2;
}
@NotNull
@Valid
public Table getPushChallenge() {
@@ -0,0 +1,65 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration;
import com.apple.foundationdb.Database;
import com.apple.foundationdb.FDB;
import com.fasterxml.jackson.annotation.JsonTypeName;
import jakarta.validation.constraints.NotBlank;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
@JsonTypeName("default")
public record FoundationDbClusterConfiguration(@NotBlank String clusterFileUrl) implements FoundationDbDatabaseFactory {
@Override
public Database build(final FDB fdb) throws IOException {
final URI clusterFileUri = URI.create(clusterFileUrl());
final File clusterFile = switch (clusterFileUri.getScheme()) {
case "file" -> new File(clusterFileUri);
case "http", "https" -> {
try (final HttpClient clusterFileClient = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_1_1)
.connectTimeout(Duration.ofSeconds(10))
.build()) {
final HttpResponse<String> response = clusterFileClient.send(HttpRequest.newBuilder()
.uri(URI.create(clusterFileUrl()))
.timeout(Duration.ofSeconds(10))
.GET()
.build(), HttpResponse.BodyHandlers.ofString());
if (response.statusCode() != 200) {
throw new IOException("Could not load cluster file (status " + response.statusCode() + ")");
}
final File tempClusterFile = File.createTempFile("fdb.cluster-", "");
tempClusterFile.deleteOnExit();
try (final FileWriter fileWriter = new FileWriter(tempClusterFile)) {
fileWriter.write(response.body());
}
yield tempClusterFile;
} catch (final InterruptedException e) {
throw new IOException("Interrupted while waiting for cluster file response", e);
}
}
default -> throw new IllegalArgumentException("Unrecognized cluster file URI scheme: " + clusterFileUri.getScheme());
};
return fdb.open(clusterFile.getAbsolutePath());
}
}
@@ -0,0 +1,18 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration;
import com.apple.foundationdb.Database;
import com.apple.foundationdb.FDB;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import io.dropwizard.jackson.Discoverable;
import java.io.IOException;
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type", defaultImpl = FoundationDbClusterConfiguration.class)
public interface FoundationDbDatabaseFactory extends Discoverable {
Database build(final FDB fdb) throws IOException;
}
@@ -0,0 +1,75 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration;
import jakarta.validation.Valid;
import jakarta.validation.constraints.AssertTrue;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.PositiveOrZero;
import jakarta.validation.constraints.Size;
import java.time.Duration;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import org.whispersystems.textsecuregcm.configuration.secrets.SecretBytes;
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStore;
/// @param transactionTimeout the time limit for a transaction, which may [contain multiple tries](https://forums.foundationdb.org/t/defaults-for-transaction-timeouts-and-retries/315/2).
/// Note that this is independent of the FoundationDB server’s transaction hard limit of 5 seconds.
/// @param transactionRetryLimit the maximum number of retries permitted _within_ a transaction
/// @param batchPriorityTransactionTimeout the maximum time for a batch priority transaction. Should be greater than or equal to {@link transactionTimeout}
/// @param batchPriorityTransactionRetryLimit the maximum number of retries permitted _within_ a batch priority transaction
public record FoundationDbMessagesConfiguration(@NotEmpty Map<String, @Valid FoundationDbDatabaseFactory> clusters,
@NotEmpty Map<@PositiveOrZero @Max(FoundationDbMessageStore.MAX_EPOCHS - 1) Integer, @Size(min = 1, max = FoundationDbMessageStore.MAX_SHARDS - 1) List<String>> epochs,
@PositiveOrZero @Max(FoundationDbMessageStore.MAX_EPOCHS - 1) int activeEpoch,
@NotEmpty Map<@PositiveOrZero @Max(63) Integer, SecretBytes> versionstampCipherKeys,
@PositiveOrZero @Max(63) int currentVersionstampCipherKey,
@PositiveOrZero @Max(1_000_000) long maxWatchesPerClient,
@NotNull Duration transactionTimeout,
@PositiveOrZero long transactionRetryLimit,
@NotNull Duration batchPriorityTransactionTimeout,
@PositiveOrZero long batchPriorityTransactionRetryLimit) {
public static final long DEFAULT_MAX_WATCHES_PER_CLIENT = 10_000;
public static final Duration DEFAULT_TRANSACTION_TIMEOUT = Duration.ofSeconds(1);
public static final long DEFAULT_TRANSACTION_RETRY_LIMIT = 3;
@AssertTrue
boolean isEveryEpochClusterConfigured() {
for (final List<String> clustersInEpoch : epochs().values()) {
for (final String cluster : clustersInEpoch) {
if (!clusters.containsKey(cluster)) {
return false;
}
}
}
return true;
}
@AssertTrue
boolean isEveryEpochFreeOfDuplicates() {
for (final List<String> clustersInEpoch : epochs().values()) {
if (new HashSet<>(clustersInEpoch).size() != clustersInEpoch.size()) {
return false;
}
}
return true;
}
@AssertTrue
boolean isActiveEpochConfigured() {
return epochs().containsKey(activeEpoch());
}
@AssertTrue
boolean isCurrentVersionstampCipherKeyConfigured() {
return versionstampCipherKeys().containsKey(currentVersionstampCipherKey());
}
}
@@ -14,7 +14,6 @@ import org.whispersystems.textsecuregcm.configuration.secrets.SecretString;
public record GcpAttachmentsConfiguration(@NotBlank String domain,
@NotBlank String email,
@Min(1) int maxSizeInBytes,
String pathPrefix,
@NotNull SecretString rsaSigningKey) {
@SuppressWarnings("unused")
@@ -9,6 +9,7 @@ import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import java.util.Map;
import org.whispersystems.textsecuregcm.configuration.secrets.SecretString;
import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel;
/**
* @param credentialsJson Service account credentials for Play Billing API
@@ -18,7 +19,7 @@ import org.whispersystems.textsecuregcm.configuration.secrets.SecretString;
* signal subscription level
*/
public record GooglePlayBillingConfiguration(
@NotNull SecretString credentialsJson,
@NotBlank String credentialsJson,
@NotNull String packageName,
@NotBlank String applicationName,
@NotNull Map<String, Long> productIdToLevel) {}
@NotNull Map<String, ReceiptLevel> productIdToLevel) {}
@@ -5,11 +5,33 @@
package org.whispersystems.textsecuregcm.configuration;
import jakarta.validation.constraints.NotNull;
import java.time.Duration;
/// Configuration for the gRPC Server
///
/// @param bindAddress The host to bind the omnibus server to
/// @param port The port to bind the omnibus server to
/// @param websocketAddress The address of a listening websocket server for handling legacy requests
/// @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
public record GrpcConfiguration(
@NotNull String bindAddress,
@NotNull Integer port,
@NotNull String websocketAddress,
@NotNull Integer websocketPort,
@NotNull Duration idleTimeout,
boolean h2c) {
public record GrpcConfiguration(@NotNull String bindAddress, @NotNull Integer port) {
public GrpcConfiguration {
if (bindAddress == null || bindAddress.isEmpty()) {
bindAddress = "localhost";
}
if (websocketAddress == null || websocketAddress.isEmpty()) {
websocketAddress = "localhost";
}
if (idleTimeout == null) {
idleTimeout = Duration.ofMinutes(5);
}
}
}
@@ -0,0 +1,15 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration;
import org.whispersystems.textsecuregcm.configuration.secrets.SecretString;
import javax.annotation.Nullable;
public record HlrLookupConfiguration(SecretString apiKey,
SecretString apiSecret,
@Nullable String circuitBreakerConfigurationName,
@Nullable String retryConfigurationName) {
}
@@ -7,29 +7,25 @@ package org.whispersystems.textsecuregcm.configuration;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.NotEmpty;
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
import org.whispersystems.textsecuregcm.util.EnumMapUtil;
import java.time.Duration;
import java.util.EnumMap;
import java.util.Map;
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
import org.whispersystems.textsecuregcm.util.EnumMapUtil;
public class IssuedReceiptsTableConfiguration extends DynamoDbTables.TableWithExpiration {
public class IssuedReceiptsTableConfiguration extends DynamoDbTables.Table {
private final byte[] generator;
/**
* The maximum number of issued receipts the issued receipt manager should issue for a particular itemId
*/
private final EnumMap<PaymentProvider, Integer> maxIssuedReceiptsPerPaymentId;
/// The maximum number of receipts that may be issued for a single subscription payment.
private final EnumMap<PaymentProvider, Integer> maxReceiptsPerSubscriptionPayment;
public IssuedReceiptsTableConfiguration(
@JsonProperty("tableName") final String tableName,
@JsonProperty("expiration") final Duration expiration,
@JsonProperty("generator") final byte[] generator,
@JsonProperty("maxIssuedReceiptsPerPaymentId") final Map<PaymentProvider, Integer> maxIssuedReceiptsPerPaymentId) {
super(tableName, expiration);
@JsonProperty("maxReceiptsPerSubscriptionPayment") final Map<PaymentProvider, Integer> maxReceiptsPerSubscriptionPayment) {
super(tableName);
this.generator = generator;
this.maxIssuedReceiptsPerPaymentId = EnumMapUtil.toCompleteEnumMap(PaymentProvider.class, maxIssuedReceiptsPerPaymentId);
this.maxReceiptsPerSubscriptionPayment = EnumMapUtil.toCompleteEnumMap(PaymentProvider.class, maxReceiptsPerSubscriptionPayment);
}
@NotEmpty
@@ -37,7 +33,7 @@ public class IssuedReceiptsTableConfiguration extends DynamoDbTables.TableWithEx
return generator;
}
public EnumMap<PaymentProvider, Integer> getmaxIssuedReceiptsPerPaymentId() {
return maxIssuedReceiptsPerPaymentId;
public EnumMap<PaymentProvider, Integer> getMaxReceiptsPerSubscriptionPayment() {
return maxReceiptsPerSubscriptionPayment;
}
}
@@ -0,0 +1,18 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Positive;
import java.time.Duration;
/// Configuration for one-time Signal Login purchases
///
/// @param playProductId the Google Play Billing productId clients should purchase to obtain a Signal Login
/// @param appStoreProductId the App Store productId clients should purchase to obtain a Signal Login
public record LoginPurchaseConfiguration(
@NotEmpty String playProductId,
@NotEmpty String appStoreProductId) {}
@@ -1,30 +0,0 @@
/*
* Copyright 2013-2020 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
public class MaxDeviceConfiguration {
@JsonProperty
@NotEmpty
private String number;
@JsonProperty
@NotNull
private int count;
public String getNumber() {
return number;
}
public int getCount() {
return count;
}
}
@@ -7,16 +7,19 @@ package org.whispersystems.textsecuregcm.configuration;
import com.fasterxml.jackson.annotation.JsonTypeName;
import jakarta.validation.constraints.NotBlank;
import java.net.URI;
import java.time.Duration;
import java.util.concurrent.ScheduledExecutorService;
import org.whispersystems.textsecuregcm.s3.S3ObjectMonitor;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import javax.annotation.Nullable;
@JsonTypeName("default")
public record MonitoredS3ObjectConfiguration(
@NotBlank String s3Region,
@NotBlank String s3Bucket,
@NotBlank String objectKey,
@Nullable URI endpointOverride,
Long maxSize,
Duration refreshInterval) implements S3ObjectMonitorFactory {
@@ -36,6 +39,10 @@ public record MonitoredS3ObjectConfiguration(
public S3ObjectMonitor build(final AwsCredentialsProvider awsCredentialsProvider,
final ScheduledExecutorService refreshExecutorService) {
if (endpointOverride != null && !endpointOverride.toString().isEmpty()) {
return new S3ObjectMonitor(awsCredentialsProvider, endpointOverride, s3Region, s3Bucket, objectKey,
maxSize, refreshExecutorService, refreshInterval);
}
return new S3ObjectMonitor(awsCredentialsProvider, s3Region, s3Bucket, objectKey, maxSize, refreshExecutorService,
refreshInterval);
}
@@ -24,10 +24,9 @@ public record OneTimeDonationConfiguration(@Valid ExpiringLevelConfiguration boo
/**
* @param badge the numeric donation level ID
* @param level the badge ID associated with the level
* @param expiration the duration after which the level expires
*/
public record ExpiringLevelConfiguration(@NotEmpty String badge, @Positive long level, Duration expiration) {
public record ExpiringLevelConfiguration(@NotEmpty String badge, Duration expiration) {
}
}
@@ -15,6 +15,5 @@ import java.util.concurrent.ScheduledExecutorService;
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type", defaultImpl = RegistrationServiceConfiguration.class)
public interface RegistrationServiceClientFactory extends Discoverable {
RegistrationServiceClient build(Environment environment, Executor callbackExecutor,
ScheduledExecutorService identityRefreshExecutor);
RegistrationServiceClient build(Environment environment, ScheduledExecutorService identityRefreshExecutor);
}
@@ -5,7 +5,6 @@ import io.dropwizard.core.setup.Environment;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import java.io.IOException;
import java.util.concurrent.Executor;
import java.util.concurrent.ScheduledExecutorService;
import org.whispersystems.textsecuregcm.configuration.secrets.SecretBytes;
import org.whispersystems.textsecuregcm.registration.IdentityTokenCallCredentials;
@@ -21,16 +20,16 @@ public record RegistrationServiceConfiguration(@NotBlank String host,
RegistrationServiceClientFactory {
@Override
public RegistrationServiceClient build(final Environment environment, final Executor callbackExecutor,
public RegistrationServiceClient build(final Environment environment,
final ScheduledExecutorService identityRefreshExecutor) {
try {
final IdentityTokenCallCredentials callCredentials = IdentityTokenCallCredentials.fromCredentialConfig(
credentialConfigurationJson, identityTokenAudience, identityRefreshExecutor);
environment.lifecycle().manage(callCredentials);
return new RegistrationServiceClient(host, port, callCredentials, registrationCaCertificate, collationKeySalt.value(),
identityRefreshExecutor);
return new RegistrationServiceClient(host, port, callCredentials, registrationCaCertificate, collationKeySalt.value());
} catch (IOException e) {
throw new RuntimeException(e);
}
@@ -7,6 +7,9 @@ package org.whispersystems.textsecuregcm.configuration;
import jakarta.validation.constraints.NotNull;
import org.whispersystems.textsecuregcm.configuration.secrets.SecretString;
import javax.annotation.Nullable;
public record TlsKeyStoreConfiguration(@NotNull SecretString password) {
public record TlsKeyStoreConfiguration(
@Nullable String path,
@NotNull SecretString password) {
}
@@ -14,7 +14,8 @@ import org.whispersystems.textsecuregcm.util.ExactlySize;
public record UnidentifiedDeliveryConfiguration(@NotNull @NotEmpty byte[] certificate,
@ExactlySize(32) SecretBytes privateKey,
int expiresDays) {
int expiresDays,
boolean embedSigner) {
public ECPrivateKey ecPrivateKey() throws InvalidKeyException {
return new ECPrivateKey(privateKey.value());
}
@@ -0,0 +1,24 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration.dynamic;
import jakarta.validation.constraints.NotNull;
import java.time.Duration;
public record DynamicCarrierDataLookupConfiguration(boolean enabled, @NotNull Duration maxCacheAge) {
public static Duration DEFAULT_MAX_CACHE_AGE = Duration.ofDays(7);
public DynamicCarrierDataLookupConfiguration() {
this(false, DEFAULT_MAX_CACHE_AGE);
}
public DynamicCarrierDataLookupConfiguration {
if (maxCacheAge == null) {
maxCacheAge = DEFAULT_MAX_CACHE_AGE;
}
}
}
Loaded 100 of 748 files, more files were not shown because too many files have changed in this diff. Show more