Compare commits

...
Author SHA1 Message Date
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
192 changed files with 8951 additions and 3201 deletions

No files matched your search

+1 -1
View File
@@ -24,7 +24,7 @@ jobs:
distribution: 'temurin'
java-version-file: .java-version
cache: 'maven'
- uses: aws-actions/configure-aws-credentials@8df5847569e6427dd6c4fb1cf565c83acfa8afa7 # v6.0.0
- uses: aws-actions/configure-aws-credentials@ec61189d14ec14c8efccab744f656cffd0e33f37 # v6.1.0
name: Configure AWS credentials from Test account
with:
role-to-assume: ${{ vars.AWS_ROLE }}
+1 -1
View File
@@ -1 +1 @@
temurin-24
temurin-25
+2 -2
View File
@@ -14,7 +14,7 @@
# 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
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.14/apache-maven-3.9.14-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.3.4/maven-wrapper-3.3.4.jar
distributionSha256Sum=0d7125e8c91097b36edb990ea5934e6c68b4440eef4ea96510a0f6815e7eeadb
distributionSha256Sum=55fadd669532a3205d5db95f490bf13971d8b0843526f407f29db0e61f074ab3
wrapperSha256Sum=4e2fbf6554bc8a4702cdfdd3bef464f423393d784ddbb037216320ce55d5e4e1
@@ -14,7 +14,6 @@ import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import org.signal.libsignal.protocol.IdentityKey;
@@ -130,9 +129,9 @@ public class TestUser {
public AccountAttributes accountAttributes() {
return new AccountAttributes(true, registrationId, pniRegistrationId, "".getBytes(StandardCharsets.UTF_8), "", true,
DeviceCapability.CAPABILITIES_REQUIRED_FOR_REGISTRATION)
.withUnidentifiedAccessKey(unidentifiedAccessKey)
.withRecoveryPassword(registrationPassword);
DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES)
.setUnidentifiedAccessKey(unidentifiedAccessKey)
.setRecoveryPassword(registrationPassword);
}
public void setAciUuid(final UUID aciUuid) {
+44 -39
View File
@@ -45,8 +45,8 @@
</modules>
<properties>
<aws.sdk2.version>2.41.11</aws.sdk2.version>
<braintree.version>3.47.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.21.0</commons-io.version>
<dropwizard.version>4.0.16</dropwizard.version>
@@ -57,47 +57,47 @@
<foundationdb.version>7.3.62</foundationdb.version>
<foundationdb.api-version>730</foundationdb.api-version>
<foundationdb.client-library-sha256>bfed237b787fae3cde1222676e6bfbb0d218fc27bf9e903397a7a7aa96fb2d33</foundationdb.client-library-sha256>
<google-cloud-libraries.version>26.74.0</google-cloud-libraries.version>
<grpc.version>1.73.0</grpc.version> <!-- should be kept in sync with the value from Google libraries-bom -->
<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.21.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.3.0</kotlin.version>
<logback.version>1.5.25</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.32</logback.version>
<logback-access-common.version>2.0.12</logback-access-common.version>
<lettuce.version>6.8.2.RELEASE</lettuce.version>
<libphonenumber.version>9.0.21</libphonenumber.version>
<logstash.logback.version>8.1</logstash.logback.version>
<log4j-bom.version>2.25.3</log4j-bom.version>
<log4j-bom.version>2.25.4</log4j-bom.version>
<luajava.version>3.5.0</luajava.version>
<micrometer.version>1.16.2</micrometer.version>
<micrometer.version>1.16.4</micrometer.version>
<netty.version>4.1.127.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>
<reactor-bom.version>2025.0.2</reactor-bom.version> <!-- 3.8.2, 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.2.0</simple-grpc.version>
<slf4j.version>2.0.17</slf4j.version>
<stripe.version>31.2.0</stripe.version>
<swagger.version>2.2.42</swagger.version>
<testcontainers.version>2.0.3</testcontainers.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>
<dynamodb.image>amazon/dynamodb-local:3.3.0@sha256:d89f8fcc6b1a39cb35976c248ed42a28c66ae00dc043099210f5571e42648ab4</dynamodb.image>
<localstack.image>localstack/localstack:4.13@sha256:46302bcb91a7e8008e6394be8afafdbfa40fb77a54d4046a38be35992042d5de</localstack.image>
<redis.image>redis:7.4-alpine@sha256:af1d0fc3f63b02b13ff7906c9baf7c5b390b8881ca08119cd570677fe2f60b55</redis.image>
<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>
<!-- eclipse-temurin:25.0.2_10-jre-noble (note: always use the multi-arch manifest *LIST* here) -->
<docker.image.sha256>d2975fcad8dc9ac2180c0c278c8ae7b3443d36cb80845cb0811c20d9463f5fee</docker.image.sha256>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
@@ -167,14 +167,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>
@@ -251,12 +251,12 @@
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.3.5</version>
<version>1.3.6</version>
</dependency>
<dependency>
<groupId>org.ow2.asm</groupId>
<artifactId>asm</artifactId>
<version>9.8</version>
<version>9.9.1</version>
<scope>test</scope>
</dependency>
<dependency>
@@ -370,6 +370,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>
@@ -417,7 +422,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>
@@ -425,27 +430,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>
@@ -455,7 +460,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>
@@ -501,16 +506,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>
@@ -523,7 +528,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>
<!--
@@ -543,7 +548,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>
@@ -564,7 +569,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>
@@ -573,7 +578,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 -2
View File
@@ -125,6 +125,8 @@ dynamoDbTables:
tableName: Example_PhoneNumberIdentifiers
profiles:
tableName: Example_Profiles
profilesV2:
tableName: Example_ProfilesV2
pushChallenge:
tableName: Example_PushChallenge
pushNotificationExperimentSamples:
@@ -231,17 +233,19 @@ 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
tus:
uploadUri: https://example.org/upload
userAuthenticationTokenSharedSecret: secret://tus.userAuthenticationTokenSharedSecret
maxSizeInBytes: 1024
apn: # Apple Push Notifications configuration
sandbox: true
+4 -1
View File
@@ -555,7 +555,7 @@
<dependency>
<groupId>com.squareup.okio</groupId>
<artifactId>okio-jvm</artifactId>
<version>3.15.0</version>
<version>3.16.4</version>
</dependency>
</dependencies>
@@ -696,6 +696,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>
@@ -10,14 +10,12 @@ 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.BadgesConfiguration;
import org.whispersystems.textsecuregcm.configuration.BraintreeConfiguration;
@@ -31,7 +29,6 @@ import org.whispersystems.textsecuregcm.configuration.DeviceCheckConfiguration;
import org.whispersystems.textsecuregcm.configuration.DirectoryV2Configuration;
import org.whispersystems.textsecuregcm.configuration.DynamoDbClientFactory;
import org.whispersystems.textsecuregcm.configuration.DynamoDbTables;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicGrpcAllowListConfiguration;
import org.whispersystems.textsecuregcm.configuration.ExternalRequestFilterConfiguration;
import org.whispersystems.textsecuregcm.configuration.FaultTolerantRedisClientFactory;
import org.whispersystems.textsecuregcm.configuration.FaultTolerantRedisClusterFactory;
@@ -44,7 +41,6 @@ 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.MessageByteLimitCardinalityEstimatorConfiguration;
import org.whispersystems.textsecuregcm.configuration.MessageCacheConfiguration;
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration;
@@ -122,6 +118,11 @@ public class WhisperServerConfiguration extends Configuration {
@JsonProperty
private DynamoDbTables dynamoDbTables;
@NotNull
@Valid
@JsonProperty
private AttachmentsConfiguration attachments;
@NotNull
@Valid
@JsonProperty
@@ -182,11 +183,6 @@ public class WhisperServerConfiguration extends Configuration {
@JsonProperty
private MessageCacheConfiguration messageCache;
@Valid
@NotNull
@JsonProperty
private List<MaxDeviceConfiguration> maxDevices = new LinkedList<>();
@Valid
@NotNull
@JsonProperty
@@ -349,11 +345,6 @@ public class WhisperServerConfiguration extends Configuration {
@JsonProperty
private GrpcConfiguration grpc;
@NotNull
@Valid
@JsonProperty
private DynamicGrpcAllowListConfiguration grpcAllowList = new DynamicGrpcAllowListConfiguration();
@Valid
@NotNull
@JsonProperty
@@ -412,6 +403,10 @@ public class WhisperServerConfiguration extends Configuration {
return webSocket;
}
public AttachmentsConfiguration getAttachments() {
return attachments;
}
public GcpAttachmentsConfiguration getGcpAttachmentsConfiguration() {
return gcpAttachments;
}
@@ -476,17 +471,6 @@ 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;
}
@@ -595,10 +579,6 @@ public class WhisperServerConfiguration extends Configuration {
return grpc;
}
public DynamicGrpcAllowListConfiguration getGrpcAllowList() {
return grpcAllowList;
}
public S3ObjectMonitorFactory getAsnTableConfiguration() {
return asnTable;
}
@@ -610,4 +590,5 @@ public class WhisperServerConfiguration extends Configuration {
public HlrLookupConfiguration getHlrLookupConfiguration() {
return hlrLookup;
}
}
@@ -159,6 +159,8 @@ import org.whispersystems.textsecuregcm.grpc.MessagesAnonymousGrpcService;
import org.whispersystems.textsecuregcm.grpc.MessagesGrpcService;
import org.whispersystems.textsecuregcm.grpc.MetricServerInterceptor;
import org.whispersystems.textsecuregcm.grpc.PaymentsGrpcService;
import org.whispersystems.textsecuregcm.grpc.ProfileAnonymousGrpcService;
import org.whispersystems.textsecuregcm.grpc.ProfileGrpcService;
import org.whispersystems.textsecuregcm.grpc.RequestAttributesInterceptor;
import org.whispersystems.textsecuregcm.grpc.ValidatingInterceptor;
import org.whispersystems.textsecuregcm.grpc.net.ManagedGrpcServer;
@@ -238,6 +240,7 @@ import org.whispersystems.textsecuregcm.storage.PersistentTimer;
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
import org.whispersystems.textsecuregcm.storage.Profiles;
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
import org.whispersystems.textsecuregcm.storage.ProfilesV2;
import org.whispersystems.textsecuregcm.storage.PushChallengeDynamoDb;
import org.whispersystems.textsecuregcm.storage.RedeemedReceiptsManager;
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswords;
@@ -469,8 +472,9 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
config.getDynamoDbTables().getClientReleases().getTableName());
PhoneNumberIdentifiers phoneNumberIdentifiers = new PhoneNumberIdentifiers(dynamoDbAsyncClient,
config.getDynamoDbTables().getPhoneNumberIdentifiers().getTableName());
Profiles profiles = new Profiles(dynamoDbClient, dynamoDbAsyncClient,
config.getDynamoDbTables().getProfiles().getTableName());
Profiles profilesV1 = new Profiles(dynamoDbClient, dynamoDbAsyncClient,
config.getDynamoDbTables().getProfilesV1().getTableName());
ProfilesV2 profiles = new ProfilesV2(dynamoDbClient, dynamoDbAsyncClient, config.getDynamoDbTables().getProfilesV2().getTableName());
S3AsyncClient asyncKeysS3Client = S3AsyncClient.builder()
.credentialsProvider(awsCredentialsProvider)
@@ -678,7 +682,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
storageServiceExecutor, retryExecutor, config.getSecureStorageServiceConfiguration());
DisconnectionRequestManager disconnectionRequestManager = new DisconnectionRequestManager(pubsubClient,
disconnectionRequestListenerExecutor, retryExecutor);
ProfilesManager profilesManager = new ProfilesManager(profiles, cacheCluster, retryExecutor, asyncCdnS3Client,
ProfilesManager profilesManager = new ProfilesManager(profilesV1, profiles, cacheCluster, retryExecutor, asyncCdnS3Client,
config.getCdnConfiguration().bucket());
MessagesCache messagesCache = new MessagesCache(messagesCluster, messageDeliveryScheduler,
messageDeletionAsyncExecutor, retryExecutor, clock, experimentEnrollmentManager);
@@ -739,7 +743,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
final AccountAuthenticator accountAuthenticator = new AccountAuthenticator(accountsManager);
final MessageSender messageSender = new MessageSender(messagesManager, pushNotificationManager);
final MessageSender messageSender = new MessageSender(messagesManager, pushNotificationManager, dynamicConfigurationManager);
final ReceiptSender receiptSender = new ReceiptSender(accountsManager, messageSender, receiptSenderExecutor);
final CloudflareTurnCredentialsManager cloudflareTurnCredentialsManager = new CloudflareTurnCredentialsManager(
config.getTurnConfiguration().cloudflare().apiToken().value(),
@@ -754,8 +758,9 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
cloudflareTurnHttpExecutor,
config.getTurnConfiguration().cloudflare().retryConfigurationName(),
cloudflareTurnRetryExecutor,
cloudflareDnsResolver
);
cloudflareDnsResolver,
dynamicConfigurationManager,
experimentEnrollmentManager);
final CardinalityEstimator messageByteLimitCardinalityEstimator = new CardinalityEstimator(
rateLimitersCluster,
@@ -765,8 +770,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
PushChallengeManager pushChallengeManager = new PushChallengeManager(pushNotificationManager,
pushChallengeDynamoDb);
ChangeNumberManager changeNumberManager = new ChangeNumberManager(messageSender, accountsManager, Clock.systemUTC());
HttpClient currencyClient = HttpClient.newBuilder().version(HttpClient.Version.HTTP_2).connectTimeout(Duration.ofSeconds(10)).build();
FixerClient fixerClient = config.getPaymentsServiceConfiguration().externalClients()
.buildFixerClient(currencyClient);
@@ -822,7 +825,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
final GcsAttachmentGenerator gcsAttachmentGenerator = new GcsAttachmentGenerator(
config.getGcpAttachmentsConfiguration().domain(),
config.getGcpAttachmentsConfiguration().email(),
config.getGcpAttachmentsConfiguration().maxSizeInBytes(),
config.getGcpAttachmentsConfiguration().pathPrefix(),
config.getGcpAttachmentsConfiguration().rsaSigningKey().value());
@@ -947,7 +949,9 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
log.info("Registered spam filter: {}", filter.getClass().getName());
});
final RemoteDeprecationFilter remoteDeprecationFilter = new RemoteDeprecationFilter(dynamicConfigurationManager);
final RemoteDeprecationFilter remoteDeprecationFilter =
new RemoteDeprecationFilter(accountsManager, accountAuthenticator, dynamicConfigurationManager);
final MetricServerInterceptor metricServerInterceptor = new MetricServerInterceptor(Metrics.globalRegistry, clientReleaseManager);
final ErrorMappingInterceptor errorMappingInterceptor = new ErrorMappingInterceptor();
@@ -968,10 +972,12 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new AccountsGrpcService(accountsManager, rateLimiters, usernameHashZkProofVerifier, registrationRecoveryPasswordsManager),
ExternalServiceCredentialsGrpcService.createForAllExternalServices(config, rateLimiters),
new KeysGrpcService(accountsManager, keysManager, rateLimiters),
new ProfileGrpcService(clock, accountsManager, profilesManager, dynamicConfigurationManager, config.getBadges(), profileCdnPolicyGenerator, profileCdnPolicySigner, profileBadgeConverter, rateLimiters),
new MessagesGrpcService(accountsManager, rateLimiters, messageSender, messageByteLimitCardinalityEstimator, spamChecker, Clock.systemUTC()),
new BackupsGrpcService(accountsManager, backupAuthManager, backupMetrics),
new DevicesGrpcService(accountsManager),
new AttachmentsGrpcService(experimentEnrollmentManager, rateLimiters, gcsAttachmentGenerator, tusAttachmentGenerator))
new AttachmentsGrpcService(experimentEnrollmentManager, rateLimiters,
gcsAttachmentGenerator, tusAttachmentGenerator, config.getAttachments().maxAttachmentUploadSizeInBytes()))
.map(bindableService -> ServerInterceptors.intercept(bindableService,
// Note: interceptors run in the reverse order they are added; the remote deprecation filter
// depends on the user-agent context so it has to come first here!
@@ -988,9 +994,10 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new AccountsAnonymousGrpcService(accountsManager, rateLimiters),
new CallQualitySurveyGrpcService(callQualitySurveyManager, rateLimiters),
new KeysAnonymousGrpcService(accountsManager, keysManager, zkSecretParams, Clock.systemUTC()),
new ProfileAnonymousGrpcService(accountsManager, profilesManager, profileBadgeConverter, zkSecretParams),
new PaymentsGrpcService(currencyManager),
new MessagesAnonymousGrpcService(accountsManager, rateLimiters, messageSender, groupSendTokenUtil, messageByteLimitCardinalityEstimator, spamChecker, Clock.systemUTC()),
new BackupsAnonymousGrpcService(backupManager, backupMetrics),
new BackupsAnonymousGrpcService(backupManager, backupMetrics, config.getAttachments().maxAttachmentUploadSizeInBytes(), config.getAttachments().maxMessageBackupUploadSizeInBytes()),
ExternalServiceCredentialsAnonymousGrpcService.create(accountsManager, config))
.map(bindableService -> ServerInterceptors.intercept(bindableService,
// Note: interceptors run in the reverse order they are added; the remote deprecation filter
@@ -1087,14 +1094,17 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
final PhoneVerificationTokenManager phoneVerificationTokenManager = new PhoneVerificationTokenManager(
phoneNumberIdentifiers, registrationServiceClient, registrationRecoveryPasswordsManager, registrationRecoveryChecker);
final ChangeNumberManager changeNumberManager = new ChangeNumberManager(messageSender, accountsManager,
phoneVerificationTokenManager, registrationLockVerificationManager, rateLimiters, Clock.systemUTC());
final List<Object> commonControllers = Lists.newArrayList(
new AccountController(accountsManager, rateLimiters, registrationRecoveryPasswordsManager,
usernameHashZkProofVerifier),
new AccountControllerV2(accountsManager, changeNumberManager, phoneVerificationTokenManager,
registrationLockVerificationManager, rateLimiters),
new AccountControllerV2(accountsManager, changeNumberManager),
new AttachmentControllerV4(rateLimiters, gcsAttachmentGenerator, tusAttachmentGenerator,
experimentEnrollmentManager),
new ArchiveController(accountsManager, backupAuthManager, backupManager, backupMetrics),
experimentEnrollmentManager, config.getAttachments().maxAttachmentUploadSizeInBytes()),
new ArchiveController(accountsManager, backupAuthManager, backupManager, backupMetrics, config.getAttachments().maxAttachmentUploadSizeInBytes(), config.getAttachments().maxMessageBackupUploadSizeInBytes()),
new CallRoutingControllerV2(rateLimiters, cloudflareTurnCredentialsManager),
new CallLinkController(rateLimiters, callingGenericZkSecretParams),
new CallQualitySurveyController(callQualitySurveyManager),
@@ -1102,7 +1112,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
config.getDeliveryCertificate().ecPrivateKey(), config.getDeliveryCertificate().expiresDays(), config.getDeliveryCertificate().embedSigner()),
zkAuthOperations, callingGenericZkSecretParams, clock),
new ChallengeController(accountsManager, rateLimitChallengeManager, challengeConstraintChecker),
new DeviceController(accountsManager, rateLimiters, persistentTimer, config.getMaxDevices()),
new DeviceController(accountsManager, rateLimiters, persistentTimer),
new DeviceCheckController(clock, accountsManager, backupAuthManager, appleDeviceCheckManager, rateLimiters,
config.getDeviceCheck().backupRedemptionLevel(),
config.getDeviceCheck().backupRedemptionDuration()),
@@ -1122,7 +1132,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
zkSecretParams, zkProfileOperations, batchIdentityCheckExecutor),
new ProvisioningController(rateLimiters, provisioningManager),
new RegistrationController(accountsManager, phoneVerificationTokenManager, registrationLockVerificationManager,
rateLimiters),
rateLimiters, registrationFraudChecker),
new RemoteConfigController(remoteConfigsManager, config.getRemoteConfigConfiguration().globalConfig(), clock),
new SecureStorageController(storageCredentialsGenerator),
new SecureValueRecovery2Controller(svr2CredentialsGenerator, accountsManager),
@@ -10,8 +10,6 @@ public interface AttachmentGenerator {
record Descriptor(Map<String, String> headers, String signedUploadLocation) {}
Descriptor generateAttachment(final String key);
long maxUploadSizeInBytes();
Descriptor generateAttachment(final String key, final long uploadLength);
}
@@ -22,28 +22,21 @@ public class GcsAttachmentGenerator implements AttachmentGenerator {
@Nonnull
private final CanonicalRequestSigner canonicalRequestSigner;
private final int maxSizeInBytes;
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.maxSizeInBytes = maxSizeInBytes;
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));
}
@Override
public long maxUploadSizeInBytes() {
return this.maxSizeInBytes;
}
private String getSignedUploadLocation(@Nonnull CanonicalRequest canonicalRequest) {
return "https://" + canonicalRequest.getDomain() + canonicalRequest.getResourcePath()
+ '?' + canonicalRequest.getCanonicalQuery()
@@ -19,18 +19,16 @@ public class TusAttachmentGenerator implements AttachmentGenerator {
private final JwtGenerator jwtGenerator;
private final String tusUri;
private final long maxUploadSize;
public TusAttachmentGenerator(final TusConfiguration cfg) {
this.tusUri = cfg.uploadUri();
this.jwtGenerator = new JwtGenerator(cfg.userAuthenticationTokenSharedSecret().value(), Clock.systemUTC());
this.maxUploadSize = cfg.maxSizeInBytes();
}
@Override
public Descriptor generateAttachment(final String 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, maxUploadSize));
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(
@@ -39,9 +37,4 @@ public class TusAttachmentGenerator implements AttachmentGenerator {
);
return new Descriptor(headers, tusUri + "/" + ATTACHMENTS);
}
@Override
public long maxUploadSizeInBytes() {
return maxUploadSize;
}
}
@@ -12,6 +12,4 @@ import org.whispersystems.textsecuregcm.util.ExactlySize;
public record TusConfiguration(
@ExactlySize(32) SecretBytes userAuthenticationTokenSharedSecret,
@NotEmpty String uploadUri,
@Positive long maxSizeInBytes
){}
@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;
@@ -36,9 +35,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,14 +100,7 @@ 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
}
final Account authenticatedAccount = updateLastSeen(account.get(), device.get());
return Optional.of(new AuthenticatedDevice(authenticatedAccount.getIdentifier(IdentityType.ACI),
device.get().getId(),
Instant.ofEpochMilli(authenticatedAccount.getPrimaryDevice().getLastSeen())));
@@ -153,7 +142,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.getIdentifier(IdentityType.ACI), 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);
}
@@ -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
);
}
}
@@ -27,6 +27,7 @@ import org.whispersystems.textsecuregcm.registration.RegistrationServiceClient;
import org.whispersystems.textsecuregcm.spam.RegistrationRecoveryChecker;
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
import javax.annotation.Nullable;
public class PhoneVerificationTokenManager {
@@ -56,8 +57,10 @@ public class PhoneVerificationTokenManager {
*
* @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
* the session ID as invalid
@@ -65,13 +68,22 @@ public class PhoneVerificationTokenManager {
* @throws ForbiddenException if the recovery password is not valid
* @throws InterruptedException if verification did not complete before a timeout
*/
public PhoneVerificationRequest.VerificationType verify(final ContainerRequestContext requestContext, final String number, final PhoneVerificationRequest request)
throws InterruptedException {
public PhoneVerificationRequest.VerificationType verify(final ContainerRequestContext requestContext,
final String number,
@Nullable final byte[] sessionId,
@Nullable final byte[] recoveryPassword) throws InterruptedException {
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(requestContext, number, recoveryPassword);
}
return verificationType;
@@ -108,14 +120,19 @@ public class PhoneVerificationTokenManager {
}
}
private void verifyByRecoveryPassword(final ContainerRequestContext requestContext, final String number, final byte[] recoveryPassword)
throws InterruptedException {
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");
}
try {
final boolean verified = registrationRecoveryPasswordsManager.verify(phoneNumberIdentifiers.getPhoneNumberIdentifier(number).join(), recoveryPassword)
final boolean verified = phoneNumberIdentifiers.getPhoneNumberIdentifier(number)
.thenCompose(phoneNumberIdentifier -> registrationRecoveryPasswordsManager.verify(phoneNumberIdentifier, recoveryPassword))
.get(VERIFICATION_TIMEOUT_SECONDS, TimeUnit.SECONDS);
if (!verified) {
throw new ForbiddenException("recoveryPassword couldn't be verified");
}
@@ -123,5 +140,4 @@ public class PhoneVerificationTokenManager {
throw new ServerErrorException(Response.Status.SERVICE_UNAVAILABLE);
}
}
}
@@ -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
@@ -8,7 +8,6 @@ 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;
@@ -22,7 +21,7 @@ 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) {
return ServerInterceptorUtil.closeWithStatusException(call,
GrpcExceptions.badAuthentication("The service forbids requests with an authentication header"));
@@ -11,7 +11,6 @@ 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;
@@ -26,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;
@@ -37,8 +37,7 @@ 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.closeWithStatusException(call,
@@ -284,7 +284,7 @@ public class BackupAuthManager {
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();
@@ -155,28 +155,33 @@ 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 BackupUploadDescriptor createMessageBackupUploadDescriptor(
final AuthenticatedBackupUser backupUser) throws BackupPermissionException, BackupWrongCredentialTypeException {
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
backupsDb.addMessageBackup(backupUser).join();
return cdn3BackupCredentialGenerator.generateUpload(cdnMessageBackupName(backupUser));
return cdn3BackupCredentialGenerator.generateUpload(cdnMessageBackupName(backupUser), uploadSize);
}
public 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);
rateLimiters.forDescriptor(RateLimiters.For.BACKUP_ATTACHMENT).validate(rateLimitKey(backupUser));
final String attachmentKey = AttachmentUtil.generateAttachmentKey(secureRandom);
final AttachmentGenerator.Descriptor descriptor = tusAttachmentGenerator.generateAttachment(attachmentKey);
final AttachmentGenerator.Descriptor descriptor =
tusAttachmentGenerator.generateAttachment(attachmentKey, uploadSize);
return new BackupUploadDescriptor(3, attachmentKey, descriptor.headers(), descriptor.signedUploadLocation());
}
@@ -194,9 +199,9 @@ public class BackupManager {
final long maxTotalMediaSize =
dynamicConfigurationManager.getConfiguration().getBackupConfiguration().maxTotalMediaSize();
// Report that the backup is out of quota if it cannot store a max size media object
// Report that the backup is out of quota if it is within 100MiB of the limit
final boolean quotaExhausted = storedBackupAttributes.bytesUsed() >=
(maxTotalMediaSize - tusAttachmentGenerator.maxUploadSizeInBytes());
(maxTotalMediaSize - 1024 * 1024 * 100);
final Tags tags = Tags.of(
UserAgentTagUtil.getPlatformTag(backupUser.userAgent()),
@@ -329,13 +334,14 @@ public class BackupManager {
*/
public CopyQuota getCopyQuota(
final AuthenticatedBackupUser backupUser,
final List<CopyParameters> toCopy)
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() > tusAttachmentGenerator.maxUploadSizeInBytes() || copyParameters.sourceLength() < 0) {
if (copyParameters.sourceLength() > maximumSourceObjectSize || copyParameters.sourceLength() < 0) {
throw new BackupInvalidArgumentException("Invalid sourceObject size");
}
}
@@ -729,10 +735,6 @@ public class BackupManager {
.toFuture();
}
public long maxMessageBackupUploadSize() {
return tusAttachmentGenerator.maxUploadSizeInBytes();
}
interface PresentationSignatureVerifier {
Pair<BackupCredentialType, BackupLevel> verifySignature(byte[] signature, ECPublicKey publicKey) throws BackupFailedZkAuthenticationException;
@@ -21,21 +21,19 @@ public class Cdn3BackupCredentialGenerator {
private final String tusUri;
private final JwtGenerator jwtGenerator;
private final long maxUploadSize;
public Cdn3BackupCredentialGenerator(final TusConfiguration cfg) {
this.tusUri = cfg.uploadUri();
this.jwtGenerator = new JwtGenerator(cfg.userAuthenticationTokenSharedSecret().value(), Clock.systemUTC());
this.maxUploadSize = cfg.maxSizeInBytes();
}
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 token = jwtGenerator.generateJwt(CDN_PATH, key, builder -> builder
.withClaim(JwtGenerator.MAX_LENGTH_CLAIM_KEY, maxUploadSize)
.withClaim(JwtGenerator.MAX_LENGTH_CLAIM_KEY, uploadSize)
.withClaim(JwtGenerator.SCOPE_CLAIM_KEY, "write"));
final String b64Key = Base64.getEncoder().encodeToString(key.getBytes(StandardCharsets.UTF_8));
@@ -4,6 +4,8 @@
*/
package org.whispersystems.textsecuregcm.backup;
import com.google.common.annotations.VisibleForTesting;
/**
* Descriptor for a single copy-and-encrypt operation
*
@@ -24,6 +26,25 @@ 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 int inputSize) {
if (inputSize < 0) {
throw new IllegalArgumentException("Size must be non-negative, but was " + inputSize);
}
// AES-256 has 16-byte block size, and always adds a block if the plaintext is a multiple of the block size
final long numBlocks = ((long) inputSize + 16) / 16;
// 16-byte IV will be generated and prepended to the ciphertext
// IV + AES-256 encrypted data + HmacSHA256
return 16 + (numBlocks * 16) + 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;
}
}
@@ -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
@@ -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) {
}
@@ -64,6 +64,7 @@ public class DynamoDbTables {
private final TableWithExpiration onetimeDonations;
private final Table phoneNumberIdentifiers;
private final Table profiles;
private final Table profilesV2;
private final Table pushChallenge;
private final Table pushNotificationExperimentSamples;
private final TableWithExpiration redeemedReceipts;
@@ -92,6 +93,7 @@ public class DynamoDbTables {
@JsonProperty("onetimeDonations") final TableWithExpiration onetimeDonations,
@JsonProperty("phoneNumberIdentifiers") final Table phoneNumberIdentifiers,
@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,
@@ -119,6 +121,7 @@ public class DynamoDbTables {
this.onetimeDonations = onetimeDonations;
this.phoneNumberIdentifiers = phoneNumberIdentifiers;
this.profiles = profiles;
this.profilesV2 = profilesV2;
this.pushChallenge = pushChallenge;
this.pushNotificationExperimentSamples = pushNotificationExperimentSamples;
this.redeemedReceipts = redeemedReceipts;
@@ -228,10 +231,16 @@ public class DynamoDbTables {
@NotNull
@Valid
public Table getProfiles() {
public Table getProfilesV1() {
return profiles;
}
@NotNull
@Valid
public Table getProfilesV2() {
return profilesV2;
}
@NotNull
@Valid
public Table getPushChallenge() {
@@ -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")
@@ -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;
}
}
@@ -30,7 +30,7 @@ public class DynamicConfiguration {
@JsonProperty
@Valid
private DynamicRemoteDeprecationConfiguration remoteDeprecation = new DynamicRemoteDeprecationConfiguration();
private DynamicRemoteDeprecationConfiguration remoteDeprecation = DynamicRemoteDeprecationConfiguration.DEFAULT;
@JsonProperty
@Valid
@@ -44,6 +44,10 @@ public class DynamicConfiguration {
@Valid
DynamicMessagePersisterConfiguration messagePersister = new DynamicMessagePersisterConfiguration();
@JsonProperty
@Valid
DynamicMessageDeliveryConfiguration messageDelivery = new DynamicMessageDeliveryConfiguration();
@JsonProperty
@Valid
DynamicRegistrationConfiguration registrationConfiguration = new DynamicRegistrationConfiguration(false);
@@ -76,6 +80,10 @@ public class DynamicConfiguration {
@Valid
private DynamicGrpcAllowListConfiguration grpcAllowList = new DynamicGrpcAllowListConfiguration();
@JsonProperty
@Valid
private DynamicTurnConfiguration turn = new DynamicTurnConfiguration();
public Optional<DynamicExperimentEnrollmentConfiguration> getExperimentEnrollmentConfiguration(
final String experimentName) {
return Optional.ofNullable(experiments.get(experimentName));
@@ -106,6 +114,10 @@ public class DynamicConfiguration {
return messagePersister;
}
public DynamicMessageDeliveryConfiguration getMessageDeliveryConfiguration() {
return messageDelivery;
}
public DynamicRegistrationConfiguration getRegistrationConfiguration() {
return registrationConfiguration;
}
@@ -137,4 +149,8 @@ public class DynamicConfiguration {
public DynamicGrpcAllowListConfiguration getGrpcAllowList() {
return grpcAllowList;
}
public DynamicTurnConfiguration getTurnConfiguration() {
return turn;
}
}
@@ -0,0 +1,18 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration.dynamic;
import com.fasterxml.jackson.annotation.JsonProperty;
public class DynamicMessageDeliveryConfiguration {
@JsonProperty
private boolean readOnly = false;
public boolean isReadOnly() {
return readOnly;
}
}
@@ -5,74 +5,52 @@
package org.whispersystems.textsecuregcm.configuration.dynamic;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.annotations.VisibleForTesting;
import com.vdurmont.semver4j.Semver;
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
import jakarta.validation.constraints.NotNull;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
public class DynamicRemoteDeprecationConfiguration {
public record DynamicRemoteDeprecationConfiguration(
@NotNull Map<ClientPlatform, Semver> minimumVersions,
@NotNull Map<ClientPlatform, Semver> versionsPendingDeprecation,
@NotNull Map<ClientPlatform, Set<Semver>> blockedVersions,
@NotNull Map<ClientPlatform, Set<Semver>> versionsPendingBlock,
@NotNull Boolean spqrEnforcementPending,
@NotNull Boolean requireSpqr) {
@JsonProperty
private Map<ClientPlatform, Semver> minimumVersions = Collections.emptyMap();
public static DynamicRemoteDeprecationConfiguration DEFAULT = new DynamicRemoteDeprecationConfiguration(
Collections.emptyMap(),
Collections.emptyMap(),
Collections.emptyMap(),
Collections.emptyMap(),
false,
false);
@JsonProperty
private Map<ClientPlatform, Semver> versionsPendingDeprecation = Collections.emptyMap();
@JsonProperty
private Map<ClientPlatform, Set<Semver>> blockedVersions = Collections.emptyMap();
@JsonProperty
private Map<ClientPlatform, Set<Semver>> versionsPendingBlock = Collections.emptyMap();
@JsonProperty
private boolean unrecognizedUserAgentAllowed = true;
@VisibleForTesting
public void setMinimumVersions(final Map<ClientPlatform, Semver> minimumVersions) {
this.minimumVersions = minimumVersions;
public DynamicRemoteDeprecationConfiguration {
if (minimumVersions == null) {
minimumVersions = DEFAULT.minimumVersions();
}
public Map<ClientPlatform, Semver> getMinimumVersions() {
return minimumVersions;
if (versionsPendingDeprecation == null) {
versionsPendingDeprecation = DEFAULT.versionsPendingDeprecation();
}
@VisibleForTesting
public void setVersionsPendingDeprecation(final Map<ClientPlatform, Semver> versionsPendingDeprecation) {
this.versionsPendingDeprecation = versionsPendingDeprecation;
if (blockedVersions == null) {
blockedVersions = DEFAULT.blockedVersions();
}
public Map<ClientPlatform, Semver> getVersionsPendingDeprecation() {
return versionsPendingDeprecation;
if (versionsPendingBlock == null) {
versionsPendingBlock = DEFAULT.versionsPendingBlock();
}
@VisibleForTesting
public void setUnrecognizedUserAgentAllowed(final boolean allowUnrecognizedUserAgents) {
this.unrecognizedUserAgentAllowed = allowUnrecognizedUserAgents;
if (spqrEnforcementPending == null) {
spqrEnforcementPending = DEFAULT.spqrEnforcementPending();
}
public boolean isUnrecognizedUserAgentAllowed() {
return unrecognizedUserAgentAllowed;
}
@VisibleForTesting
public void setBlockedVersions(final Map<ClientPlatform, Set<Semver>> blockedVersions) {
this.blockedVersions = blockedVersions;
}
public Map<ClientPlatform, Set<Semver>> getBlockedVersions() {
return blockedVersions;
}
@VisibleForTesting
public void setVersionsPendingBlock(final Map<ClientPlatform, Set<Semver>> versionsPendingBlock) {
this.versionsPendingBlock = versionsPendingBlock;
}
public Map<ClientPlatform, Set<Semver>> getVersionsPendingBlock() {
return versionsPendingBlock;
if (requireSpqr == null) {
requireSpqr = DEFAULT.requireSpqr();
}
}
}
@@ -0,0 +1,45 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration.dynamic;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import javax.annotation.Nullable;
import java.util.Collections;
import java.util.List;
public class DynamicTurnConfiguration {
@JsonProperty
@NotNull
@Valid
private List<@NotBlank String> urls = Collections.emptyList();
@JsonProperty
@NotNull
@Valid
private List<@NotBlank String> urlsWithIps = Collections.emptyList();
@JsonProperty
@Nullable
private String hostname = null;
public DynamicTurnConfiguration() {}
public List<String> getUrls() {
return urls;
}
public List<String> getUrlsWithIps() {
return urlsWithIps;
}
public @Nullable String getHostname() {
return hostname;
}
}
@@ -108,33 +108,26 @@ public class AccountController {
public void setGcmRegistrationId(@Auth AuthenticatedDevice auth,
@NotNull @Valid GcmRegistrationId registrationId) {
final Account account = accounts.getByAccountIdentifier(auth.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
final String currentGcmId = accounts.getByAccountIdentifier(auth.accountIdentifier())
.flatMap(account -> account.getDevice(auth.deviceId()))
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED))
.getGcmId();
final Device device = account.getDevice(auth.deviceId())
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
if (Objects.equals(device.getGcmId(), registrationId.gcmRegistrationId())) {
if (Objects.equals(currentGcmId, registrationId.gcmRegistrationId())) {
return;
}
accounts.updateDevice(account, device.getId(), d -> {
d.setApnId(null);
d.setGcmId(registrationId.gcmRegistrationId());
d.setFetchesMessages(false);
accounts.updateDevice(auth.accountIdentifier(), auth.deviceId(), device -> {
device.setApnId(null);
device.setGcmId(registrationId.gcmRegistrationId());
device.setFetchesMessages(false);
});
}
@DELETE
@Path("/gcm/")
public void deleteGcmRegistrationId(@Auth AuthenticatedDevice auth) {
final Account account = accounts.getByAccountIdentifier(auth.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
final Device device = account.getDevice(auth.deviceId())
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
accounts.updateDevice(account, device.getId(), d -> {
accounts.updateDevice(auth.accountIdentifier(), auth.deviceId(), d -> {
d.setGcmId(null);
d.setFetchesMessages(false);
d.setUserAgent("OWA");
@@ -148,15 +141,9 @@ public class AccountController {
public void setApnRegistrationId(@Auth AuthenticatedDevice auth,
@NotNull @Valid ApnRegistrationId registrationId) {
final Account account = accounts.getByAccountIdentifier(auth.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
final Device device = account.getDevice(auth.deviceId())
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
// Unlike FCM tokens, we need current "last updated" timestamps for APNs tokens and so update device records
// unconditionally
accounts.updateDevice(account, device.getId(), d -> {
accounts.updateDevice(auth.accountIdentifier(), auth.deviceId(), d -> {
d.setApnId(registrationId.apnRegistrationId());
d.setGcmId(null);
d.setFetchesMessages(false);
@@ -166,20 +153,10 @@ public class AccountController {
@DELETE
@Path("/apn/")
public void deleteApnRegistrationId(@Auth AuthenticatedDevice auth) {
final Account account = accounts.getByAccountIdentifier(auth.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
final Device device = account.getDevice(auth.deviceId())
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
accounts.updateDevice(account, device.getId(), d -> {
accounts.updateDevice(auth.accountIdentifier(), auth.deviceId(), d -> {
d.setApnId(null);
d.setFetchesMessages(false);
if (d.getId() == 1) {
d.setUserAgent("OWI");
} else {
d.setUserAgent("OWP");
}
d.setUserAgent(d.isPrimary() ? "OWI" : "OWP");
});
}
@@ -189,20 +166,14 @@ public class AccountController {
public void setRegistrationLock(@Auth AuthenticatedDevice auth, @NotNull @Valid RegistrationLock accountLock) {
final SaltedTokenHash credentials = SaltedTokenHash.generateFor(accountLock.registrationLock());
final Account account = accounts.getByAccountIdentifier(auth.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
accounts.update(account,
accounts.update(auth.accountIdentifier(),
a -> a.setRegistrationLock(credentials.hash(), credentials.salt()));
}
@DELETE
@Path("/registration_lock")
public void removeRegistrationLock(@Auth AuthenticatedDevice auth) {
final Account account = accounts.getByAccountIdentifier(auth.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
accounts.update(account, a -> a.setRegistrationLock(null, null));
accounts.update(auth.accountIdentifier(), a -> a.setRegistrationLock(null, null));
}
@PUT
@@ -240,7 +211,7 @@ public class AccountController {
throw new ForbiddenException();
}
accounts.updateDevice(account, targetDeviceId, d -> d.setName(deviceName.deviceName()));
accounts.updateDevice(account.getIdentifier(IdentityType.ACI), targetDeviceId, d -> d.setName(deviceName.deviceName()));
}
@PUT
@@ -252,10 +223,8 @@ public class AccountController {
@HeaderParam(HttpHeaders.USER_AGENT) String userAgent,
@HeaderParam(HeaderUtils.X_SIGNAL_AGENT) String signalAgent,
@NotNull @Valid AccountAttributes attributes) {
final Account account = accounts.getByAccountIdentifier(auth.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
final Account updatedAccount = accounts.update(account, a -> {
final Account updatedAccount = accounts.update(auth.accountIdentifier(), a -> {
a.getDevice(auth.deviceId()).ifPresent(d -> {
d.setFetchesMessages(attributes.getFetchesMessages());
d.setName(attributes.getName());
@@ -306,10 +275,7 @@ public class AccountController {
@ApiResponse(responseCode = "204", description = "Username successfully deleted.", useReturnTypeSchema = true)
@ApiResponse(responseCode = "401", description = "Account authentication check failed.")
public void deleteUsernameHash(@Auth final AuthenticatedDevice auth) {
final Account account = accounts.getByAccountIdentifier(auth.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
accounts.clearUsernameHash(account);
accounts.clearUsernameHash(auth.accountIdentifier());
}
@PUT
@@ -332,9 +298,6 @@ public class AccountController {
@Auth final AuthenticatedDevice auth,
@NotNull @Valid final ReserveUsernameHashRequest usernameRequest) throws RateLimitExceededException {
final Account account = accounts.getByAccountIdentifier(auth.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
rateLimiters.getUsernameReserveLimiter().validate(auth.accountIdentifier());
for (final byte[] hash : usernameRequest.usernameHashes()) {
@@ -345,7 +308,7 @@ public class AccountController {
try {
final AccountsManager.UsernameReservation reservation =
accounts.reserveUsernameHash(account, usernameRequest.usernameHashes());
accounts.reserveUsernameHash(auth.accountIdentifier(), usernameRequest.usernameHashes());
return new ReserveUsernameHashResponse(reservation.reservedUsernameHash());
} catch (final UsernameHashNotAvailableException e) {
@@ -374,20 +337,17 @@ public class AccountController {
@Auth final AuthenticatedDevice auth,
@NotNull @Valid final ConfirmUsernameHashRequest confirmRequest) throws RateLimitExceededException {
final Account account = accounts.getByAccountIdentifier(auth.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
try {
usernameHashZkProofVerifier.verifyProof(confirmRequest.zkProof(), confirmRequest.usernameHash());
} catch (final BaseUsernameException e) {
throw new WebApplicationException(Response.status(422).build());
}
rateLimiters.getUsernameSetLimiter().validate(account.getUuid());
rateLimiters.getUsernameSetLimiter().validate(auth.accountIdentifier());
try {
final Account updatedAccount = accounts.confirmReservedUsernameHash(
account,
auth.accountIdentifier(),
confirmRequest.usernameHash(),
confirmRequest.encryptedUsername());
@@ -474,7 +434,7 @@ public class AccountController {
} else {
usernameLinkHandle = UUID.randomUUID();
}
updateUsernameLink(account, usernameLinkHandle, encryptedUsername.usernameLinkEncryptedValue());
updateUsernameLink(account.getIdentifier(IdentityType.ACI), usernameLinkHandle, encryptedUsername.usernameLinkEncryptedValue());
return new UsernameLinkHandle(usernameLinkHandle);
}
@@ -494,10 +454,7 @@ public class AccountController {
// check ratelimiter for username link operations
rateLimiters.forDescriptor(RateLimiters.For.USERNAME_LINK_OPERATION).validate(auth.accountIdentifier());
final Account account = accounts.getByAccountIdentifier(auth.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
clearUsernameLink(account);
clearUsernameLink(auth.accountIdentifier());
}
@GET
@@ -559,24 +516,21 @@ public class AccountController {
@DELETE
@Path("/me")
public void deleteAccount(@Auth AuthenticatedDevice auth) {
final Account account = accounts.getByAccountIdentifier(auth.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
accounts.delete(account, AccountsManager.DeletionReason.USER_REQUEST);
accounts.delete(auth.accountIdentifier(), AccountsManager.DeletionReason.USER_REQUEST);
}
private void clearUsernameLink(final Account account) {
updateUsernameLink(account, null, null);
private void clearUsernameLink(final UUID accountIdentifier) {
updateUsernameLink(accountIdentifier, null, null);
}
private void updateUsernameLink(
final Account account,
final UUID accountIdentifier,
@Nullable final UUID usernameLinkHandle,
@Nullable final byte[] encryptedUsername) {
if ((encryptedUsername == null) ^ (usernameLinkHandle == null)) {
throw new IllegalStateException("Both or neither arguments must be null");
}
accounts.update(account, a -> a.setUsernameLinkDetails(usernameLinkHandle, encryptedUsername));
accounts.update(accountIdentifier, a -> a.setUsernameLinkDetails(usernameLinkHandle, encryptedUsername));
}
private void requireNotAuthenticated(final Optional<AuthenticatedDevice> authenticatedAccount) {
@@ -5,13 +5,8 @@
package org.whispersystems.textsecuregcm.controllers;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import com.google.common.net.HttpHeaders;
import io.dropwizard.auth.Auth;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.headers.Header;
import io.swagger.v3.oas.annotations.media.Content;
@@ -27,28 +22,24 @@ import jakarta.ws.rs.HeaderParam;
import jakarta.ws.rs.PUT;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.ServiceUnavailableException;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import java.time.Instant;
import java.util.Optional;
import java.util.UUID;
import org.apache.commons.lang3.StringUtils;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.ChangesPhoneNumber;
import org.whispersystems.textsecuregcm.auth.PhoneVerificationTokenManager;
import org.whispersystems.textsecuregcm.auth.RegistrationLockVerificationManager;
import org.whispersystems.textsecuregcm.entities.AccountDataReportResponse;
import org.whispersystems.textsecuregcm.entities.AccountIdentityResponse;
import org.whispersystems.textsecuregcm.entities.ChangeNumberRequest;
import org.whispersystems.textsecuregcm.entities.MismatchedDevicesResponse;
import org.whispersystems.textsecuregcm.entities.PhoneNumberDiscoverabilityRequest;
import org.whispersystems.textsecuregcm.entities.PhoneVerificationRequest;
import org.whispersystems.textsecuregcm.entities.RegistrationLockFailure;
import org.whispersystems.textsecuregcm.entities.StaleDevicesResponse;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.push.MessageTooLargeException;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
@@ -59,26 +50,14 @@ import org.whispersystems.textsecuregcm.storage.Device;
@io.swagger.v3.oas.annotations.tags.Tag(name = "Account")
public class AccountControllerV2 {
private static final String CHANGE_NUMBER_COUNTER_NAME = name(AccountControllerV2.class, "changeNumber");
private static final String VERIFICATION_TYPE_TAG_NAME = "verification";
private final AccountsManager accountsManager;
private final ChangeNumberManager changeNumberManager;
private final PhoneVerificationTokenManager phoneVerificationTokenManager;
private final RegistrationLockVerificationManager registrationLockVerificationManager;
private final RateLimiters rateLimiters;
public AccountControllerV2(final AccountsManager accountsManager,
final ChangeNumberManager changeNumberManager,
final PhoneVerificationTokenManager phoneVerificationTokenManager,
final RegistrationLockVerificationManager registrationLockVerificationManager,
final RateLimiters rateLimiters) {
final ChangeNumberManager changeNumberManager) {
this.accountsManager = accountsManager;
this.changeNumberManager = changeNumberManager;
this.phoneVerificationTokenManager = phoneVerificationTokenManager;
this.registrationLockVerificationManager = registrationLockVerificationManager;
this.rateLimiters = rateLimiters;
}
@PUT
@@ -111,45 +90,22 @@ public class AccountControllerV2 {
throw new WebApplicationException("Invalid signature", 422);
}
final String number = request.number();
final Account account = accountsManager.getByAccountIdentifier(authenticatedDevice.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
// Only verify and check reglock if there's a data change to be made...
if (!account.getNumber().equals(number)) {
rateLimiters.getRegistrationLimiter().validate(number);
final PhoneVerificationRequest.VerificationType verificationType = phoneVerificationTokenManager.verify(
requestContext, number, request);
final Optional<Account> existingAccount = accountsManager.getByE164(number);
if (existingAccount.isPresent()) {
registrationLockVerificationManager.verifyRegistrationLock(existingAccount.get(), request.registrationLock(),
userAgentString, RegistrationLockVerificationManager.Flow.CHANGE_NUMBER, verificationType);
}
Metrics.counter(CHANGE_NUMBER_COUNTER_NAME, Tags.of(UserAgentTagUtil.getPlatformTag(userAgentString),
Tag.of(VERIFICATION_TYPE_TAG_NAME, verificationType.name())))
.increment();
}
// ...but always attempt to make the change in case a client retries and needs to re-send messages
try {
final Account updatedAccount = changeNumberManager.changeNumber(
account,
authenticatedDevice.accountIdentifier(),
StringUtils.isNotBlank(request.sessionId()) ? request.decodeSessionId() : null,
request.recoveryPassword(),
request.registrationLock(),
request.number(),
request.pniIdentityKey(),
request.devicePniSignedPrekeys(),
request.devicePniPqLastResortPrekeys(),
request.deviceMessages(),
request.pniRegistrationIds(),
userAgentString);
requestContext);
return AccountIdentityResponseBuilder.fromAccount(updatedAccount);
} catch (MismatchedDevicesException e) {
} catch (final MismatchedDevicesException e) {
if (!e.getMismatchedDevices().staleDeviceIds().isEmpty()) {
throw new WebApplicationException(Response.status(410)
.type(MediaType.APPLICATION_JSON)
@@ -162,10 +118,12 @@ public class AccountControllerV2 {
e.getMismatchedDevices().extraDeviceIds()))
.build());
}
} catch (IllegalArgumentException e) {
} catch (final IllegalArgumentException e) {
throw new BadRequestException(e);
} catch (MessageTooLargeException e) {
} catch (final MessageTooLargeException e) {
throw new WebApplicationException(Response.Status.REQUEST_ENTITY_TOO_LARGE);
} catch (final MessageDeliveryNotAllowedException e) {
throw new ServiceUnavailableException();
}
}
@@ -179,10 +137,7 @@ public class AccountControllerV2 {
@Auth AuthenticatedDevice auth,
@NotNull @Valid PhoneNumberDiscoverabilityRequest phoneNumberDiscoverability) {
final Account account = accountsManager.getByAccountIdentifier(auth.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
accountsManager.update(account, a -> a.setDiscoverableByPhoneNumber(
accountsManager.update(auth.accountIdentifier(), a -> a.setDiscoverableByPhoneNumber(
phoneNumberDiscoverability.discoverableByPhoneNumber()));
}
@@ -102,17 +102,23 @@ public class ArchiveController {
private final BackupAuthManager backupAuthManager;
private final BackupManager backupManager;
private final BackupMetrics backupMetrics;
private final long maxAttachmentSize;
private final long maxMessageBackupSize;
public ArchiveController(
final AccountsManager accountsManager,
final BackupAuthManager backupAuthManager,
final BackupManager backupManager,
final BackupMetrics backupMetrics) {
final BackupMetrics backupMetrics,
final long maxAttachmentSize,
final long maxMessageBackupSize) {
this.accountsManager = accountsManager;
this.backupAuthManager = backupAuthManager;
this.backupManager = backupManager;
this.backupMetrics = backupMetrics;
this.maxAttachmentSize = maxAttachmentSize;
this.maxMessageBackupSize = maxMessageBackupSize;
}
public record SetBackupIdRequest(
@@ -566,8 +572,11 @@ public class ArchiveController {
@Path("/upload/form")
@Produces(MediaType.APPLICATION_JSON)
@Operation(
summary = "Fetch message backup upload form",
description = "Retrieve an upload form that can be used to perform a resumable upload of a message backup.")
summary = "Fetch message backup upload form", description = """
Retrieve an upload form that can be used to perform a resumable upload of a message backup.
Uploads with the returned form will be limited to a maximum size of the provided uploadLength.
""")
@ApiResponse(responseCode = "200", content = @Content(schema = @Schema(implementation = UploadDescriptorResponse.class)))
@ApiResponse(responseCode = "429", description = "Rate limited.")
@ApiResponse(responseCode = "413", description = "The provided uploadLength is larger than the maximum supported upload size. The maximum upload size is subject to change.")
@@ -596,7 +605,7 @@ public class ArchiveController {
backupManager.authenticateBackupUser(presentation.presentation, signature.signature, userAgent);
final boolean oversize = uploadLength
.map(length -> length > backupManager.maxMessageBackupUploadSize())
.map(length -> length > maxMessageBackupSize)
.orElse(false);
backupMetrics.updateMessageBackupSizeDistribution(backupUser, oversize, uploadLength);
@@ -604,7 +613,7 @@ public class ArchiveController {
throw new ClientErrorException("exceeded maximum uploadLength", Response.Status.REQUEST_ENTITY_TOO_LARGE);
}
final BackupUploadDescriptor uploadDescriptor =
backupManager.createMessageBackupUploadDescriptor(backupUser);
backupManager.createMessageBackupUploadDescriptor(backupUser, uploadLength.orElse(maxMessageBackupSize));
return new UploadDescriptorResponse(
uploadDescriptor.cdn(),
uploadDescriptor.key(),
@@ -621,32 +630,42 @@ public class ArchiveController {
Retrieve an upload form that can be used to perform a resumable upload of an attachment. After uploading, the
attachment can be copied into the backup at PUT /archives/media/.
Like the account authenticated version at /attachments, the uploaded object is only temporary.
Like the account authenticated version at /attachments, the uploaded object is only temporary. Uploads with
the returned form will be limited to a maximum size of the provided uploadLength.
""")
@ApiResponse(responseCode = "200", content = @Content(schema = @Schema(implementation = UploadDescriptorResponse.class)))
@ApiResponse(responseCode = "429", description = "Rate limited.")
@ApiResponse(responseCode = "413", description = "The provided uploadLength is larger than the maximum supported upload size. The maximum upload size is subject to change and is governed by `global.attachments.maxBytes`.")
@ApiResponseZkAuth
@ManagedAsync
public UploadDescriptorResponse uploadTemporaryAttachment(
@Auth final Optional<AuthenticatedDevice> account,
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
@Parameter(description = BackupAuthCredentialPresentationHeader.DESCRIPTION, schema = @Schema(implementation = String.class))
@NotNull
@HeaderParam(X_SIGNAL_ZK_AUTH) final ArchiveController.BackupAuthCredentialPresentationHeader presentation,
@Parameter(description = BackupAuthCredentialPresentationSignature.DESCRIPTION, schema = @Schema(implementation = String.class))
@NotNull
@HeaderParam(X_SIGNAL_ZK_AUTH_SIGNATURE) final BackupAuthCredentialPresentationSignature signature)
@HeaderParam(X_SIGNAL_ZK_AUTH_SIGNATURE) final BackupAuthCredentialPresentationSignature signature,
@Parameter(description = "The size of the temporary attachment to upload in bytes")
@QueryParam("uploadLength") final Optional<Long> uploadLength)
throws RateLimitExceededException, BackupFailedZkAuthenticationException, BackupWrongCredentialTypeException, BackupPermissionException {
if (account.isPresent()) {
throw new BadRequestException("must not use authenticated connection for anonymous operations");
}
final AuthenticatedBackupUser backupUser =
backupManager.authenticateBackupUser(presentation.presentation, signature.signature, userAgent);
final boolean oversize = uploadLength.map(length -> length > maxAttachmentSize).orElse(false);
if (oversize) {
throw new ClientErrorException("exceeded maximum uploadLength", Response.Status.REQUEST_ENTITY_TOO_LARGE);
}
final BackupUploadDescriptor uploadDescriptor =
backupManager.createTemporaryAttachmentUploadDescriptor(backupUser);
backupManager.createTemporaryAttachmentUploadDescriptor(backupUser, uploadLength.orElse(maxAttachmentSize));
return new UploadDescriptorResponse(
uploadDescriptor.cdn(),
uploadDescriptor.key(),
@@ -741,7 +760,7 @@ public class ArchiveController {
final AuthenticatedBackupUser backupUser =
backupManager.authenticateBackupUser(presentation.presentation, signature.signature, userAgent);
final BackupManager.CopyQuota copyQuota =
backupManager.getCopyQuota(backupUser, List.of(copyMediaRequest.toCopyParameters()));
backupManager.getCopyQuota(backupUser, List.of(copyMediaRequest.toCopyParameters()), maxAttachmentSize);
final CopyResult copyResult = backupManager.copyToBackup(copyQuota).next()
.blockOptional()
.orElseThrow(() -> new IllegalStateException("Non empty copy request must return result"));
@@ -844,7 +863,7 @@ public class ArchiveController {
final Stream<CopyParameters> copyParams = copyMediaRequest.items().stream().map(CopyMediaRequest::toCopyParameters);
final AuthenticatedBackupUser backupUser =
backupManager.authenticateBackupUser(presentation.presentation, signature.signature, userAgent);
final BackupManager.CopyQuota copyQuota = backupManager.getCopyQuota(backupUser, copyParams.toList());
final BackupManager.CopyQuota copyQuota = backupManager.getCopyQuota(backupUser, copyParams.toList(), maxAttachmentSize);
final List<CopyMediaBatchResponse.Entry> copyResults = backupManager.copyToBackup(copyQuota)
.doOnNext(result -> backupMetrics.updateCopyCounter(result, UserAgentTagUtil.getPlatformTag(userAgent)))
.map(CopyMediaBatchResponse.Entry::fromCopyResult)
@@ -7,17 +7,25 @@ package org.whispersystems.textsecuregcm.controllers;
import io.dropwizard.auth.Auth;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.headers.Header;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Positive;
import jakarta.ws.rs.ClientErrorException;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import java.security.SecureRandom;
import java.util.Map;
import java.util.Optional;
import javax.annotation.Nonnull;
import org.whispersystems.textsecuregcm.attachments.AttachmentGenerator;
import org.whispersystems.textsecuregcm.attachments.AttachmentUtil;
import org.whispersystems.textsecuregcm.attachments.GcsAttachmentGenerator;
import org.whispersystems.textsecuregcm.attachments.TusAttachmentGenerator;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
@@ -25,7 +33,6 @@ import org.whispersystems.textsecuregcm.entities.AttachmentDescriptorV3;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.limits.RateLimiter;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.attachments.AttachmentUtil;
/**
@@ -37,7 +44,9 @@ import org.whispersystems.textsecuregcm.attachments.AttachmentUtil;
public class AttachmentControllerV4 {
private final ExperimentEnrollmentManager experimentEnrollmentManager;
private final RateLimiter rateLimiter;
private final RateLimiter countRateLimiter;
private final RateLimiter bytesRateLimiter;
private final long maxUploadLength;
private final Map<Integer, AttachmentGenerator> attachmentGenerators;
@@ -48,9 +57,12 @@ public class AttachmentControllerV4 {
final RateLimiters rateLimiters,
final GcsAttachmentGenerator gcsAttachmentGenerator,
final TusAttachmentGenerator tusAttachmentGenerator,
final ExperimentEnrollmentManager experimentEnrollmentManager) {
this.rateLimiter = rateLimiters.getAttachmentLimiter();
final ExperimentEnrollmentManager experimentEnrollmentManager,
final long maxUploadLength) {
this.countRateLimiter = rateLimiters.getAttachmentLimiter();
this.bytesRateLimiter = rateLimiters.getAttachmentBytesLimiter();
this.experimentEnrollmentManager = experimentEnrollmentManager;
this.maxUploadLength = maxUploadLength;
this.secureRandom = new SecureRandom();
this.attachmentGenerators = Map.of(
2, gcsAttachmentGenerator,
@@ -66,19 +78,43 @@ public class AttachmentControllerV4 {
description = """
Retrieve an upload form that can be used to perform a resumable upload. The response will include a cdn number
indicating what protocol should be used to perform the upload.
Uploads with the returned form will be limited to a maximum size of the provided uploadLength.
"""
)
@ApiResponse(responseCode = "200", description = "Success, response body includes upload form", useReturnTypeSchema = true)
@ApiResponse(responseCode = "400", description = "The provided uploadLength was not valid")
@ApiResponse(responseCode = "413", description = "The provided uploadLength is larger than the maximum supported upload size. The maximum upload size is subject to change and is governed by `global.attachments.maxBytes`.")
@ApiResponse(responseCode = "429", description = "Too many attempts", headers = @Header(
name = "Retry-After",
description = "If present, an positive integer indicating the number of seconds before a subsequent attempt could succeed"))
public AttachmentDescriptorV3 getAttachmentUploadForm(@Auth AuthenticatedDevice auth)
public AttachmentDescriptorV3 getAttachmentUploadForm(
@Auth AuthenticatedDevice auth,
@Parameter(description = "The size of the attachment to upload in bytes")
@QueryParam("uploadLength") final @Valid Optional<@Positive Long> maybeUploadLength)
throws RateLimitExceededException {
rateLimiter.validate(auth.accountIdentifier());
final long uploadLength = maybeUploadLength.orElse(maxUploadLength);
if (uploadLength > maxUploadLength) {
throw new ClientErrorException("exceeded maximum uploadLength", Response.Status.REQUEST_ENTITY_TOO_LARGE);
}
countRateLimiter.validate(auth.accountIdentifier());
if (maybeUploadLength.isPresent()) {
// Ideally we'd check these two rate limits transactionally and only update them if both permits were acquired.
// However, just undoing the first modification if the second one fails is close enough for our purposes
try {
bytesRateLimiter.validate(auth.accountIdentifier(), maybeUploadLength.get());
} catch (RateLimitExceededException e) {
countRateLimiter.restorePermits(auth.accountIdentifier(), 1);
throw e;
}
}
final String key = AttachmentUtil.generateAttachmentKey(secureRandom);
final boolean useCdn3 = this.experimentEnrollmentManager.isEnrolled(auth.accountIdentifier(), AttachmentUtil.CDN3_EXPERIMENT_NAME);
int cdn = useCdn3 ? 3 : 2;
final AttachmentGenerator.Descriptor descriptor = this.attachmentGenerators.get(cdn).generateAttachment(key);
final AttachmentGenerator.Descriptor descriptor = this.attachmentGenerators.get(cdn).generateAttachment(key, uploadLength);
return new AttachmentDescriptorV3(cdn, key, descriptor.headers(), descriptor.signedUploadLocation());
}
@@ -60,7 +60,7 @@ public class CallRoutingControllerV2 {
rateLimiters.getCallEndpointLimiter().validate(auth.accountIdentifier());
try {
return new GetCallingRelaysResponse(List.of(cloudflareTurnCredentialsManager.retrieveFromCloudflare()));
return new GetCallingRelaysResponse(List.of(cloudflareTurnCredentialsManager.retrieveFromCloudflare(auth.accountIdentifier())));
} catch (final Exception e) {
CLOUDFLARE_TURN_ERROR_COUNTER.increment();
throw e;
@@ -50,8 +50,8 @@ import javax.annotation.Nullable;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.BasicAuthorizationHeader;
import org.whispersystems.textsecuregcm.auth.ChangesLinkedDevices;
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
import org.whispersystems.textsecuregcm.entities.DeviceActivationRequest;
import org.whispersystems.textsecuregcm.entities.DeviceAttributes;
import org.whispersystems.textsecuregcm.entities.DeviceInfo;
import org.whispersystems.textsecuregcm.entities.DeviceInfoList;
import org.whispersystems.textsecuregcm.entities.LinkDeviceRequest;
@@ -93,7 +93,6 @@ public class DeviceController {
private final AccountsManager accounts;
private final RateLimiters rateLimiters;
private final PersistentTimer persistentTimer;
private final Map<String, Integer> maxDeviceConfiguration;
private final EnumMap<ClientPlatform, AtomicInteger> linkedDeviceListenersByPlatform;
private final AtomicInteger linkedDeviceListenersForUnrecognizedPlatforms;
@@ -117,13 +116,11 @@ public class DeviceController {
public DeviceController(final AccountsManager accounts,
final RateLimiters rateLimiters,
final PersistentTimer persistentTimer,
final Map<String, Integer> maxDeviceConfiguration) {
final PersistentTimer persistentTimer) {
this.accounts = accounts;
this.rateLimiters = rateLimiters;
this.persistentTimer = persistentTimer;
this.maxDeviceConfiguration = maxDeviceConfiguration;
linkedDeviceListenersByPlatform =
EnumMapUtil.toEnumMap(ClientPlatform.class, clientPlatform -> buildGauge(clientPlatform.name().toLowerCase()));
@@ -162,10 +159,7 @@ public class DeviceController {
throw new ForbiddenException();
}
final Account account = accounts.getByAccountIdentifier(auth.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
accounts.removeDevice(account, deviceId);
accounts.removeDevice(auth.accountIdentifier(), deviceId);
}
/**
@@ -204,14 +198,8 @@ public class DeviceController {
rateLimiters.getAllocateDeviceLimiter().validate(account.getUuid());
int maxDeviceLimit = MAX_DEVICES;
if (maxDeviceConfiguration.containsKey(account.getNumber())) {
maxDeviceLimit = maxDeviceConfiguration.get(account.getNumber());
}
if (account.getDevices().size() >= maxDeviceLimit) {
throw new DeviceLimitExceededException(account.getDevices().size(), maxDeviceLimit);
if (account.getDevices().size() >= MAX_DEVICES) {
throw new DeviceLimitExceededException(account.getDevices().size(), MAX_DEVICES);
}
if (auth.deviceId() != Device.PRIMARY_ID) {
@@ -250,7 +238,7 @@ public class DeviceController {
.orElseThrow(ForbiddenException::new);
final DeviceActivationRequest deviceActivationRequest = linkDeviceRequest.deviceActivationRequest();
final AccountAttributes accountAttributes = linkDeviceRequest.accountAttributes();
final DeviceAttributes deviceAttributes = linkDeviceRequest.deviceAttributes();
rateLimiters.getVerifyDeviceLimiter().validate(account.getUuid());
@@ -268,13 +256,11 @@ public class DeviceController {
throw new WebApplicationException(Response.status(422).build());
}
final int maxDeviceLimit = maxDeviceConfiguration.getOrDefault(account.getNumber(), MAX_DEVICES);
if (account.getDevices().size() >= maxDeviceLimit) {
throw new DeviceLimitExceededException(account.getDevices().size(), maxDeviceLimit);
if (account.getDevices().size() >= MAX_DEVICES) {
throw new DeviceLimitExceededException(account.getDevices().size(), MAX_DEVICES);
}
final Set<DeviceCapability> capabilities = accountAttributes.getCapabilities();
final Set<DeviceCapability> capabilities = deviceAttributes.capabilities();
if (capabilities == null) {
throw new WebApplicationException(Response.status(422, "Missing device capabilities").build());
@@ -293,20 +279,21 @@ public class DeviceController {
}
try {
final Pair<Account, Device> accountAndDevice = accounts.addDevice(account, new DeviceSpec(accountAttributes.getName(),
authorizationHeader.getPassword(),
signalAgent,
capabilities,
accountAttributes.getRegistrationId(),
accountAttributes.getPhoneNumberIdentityRegistrationId(),
accountAttributes.getFetchesMessages(),
deviceActivationRequest.apnToken(),
deviceActivationRequest.gcmToken(),
deviceActivationRequest.aciSignedPreKey(),
deviceActivationRequest.pniSignedPreKey(),
deviceActivationRequest.aciPqLastResortPreKey(),
deviceActivationRequest.pniPqLastResortPreKey()),
linkDeviceRequest.verificationCode());
final Pair<Account, Device> accountAndDevice = accounts.addDevice(account.getIdentifier(IdentityType.ACI),
new DeviceSpec(deviceAttributes.name(),
authorizationHeader.getPassword(),
signalAgent,
capabilities,
deviceAttributes.registrationId(),
deviceAttributes.phoneNumberIdentityRegistrationId(),
deviceAttributes.fetchesMessages(),
deviceActivationRequest.apnToken(),
deviceActivationRequest.gcmToken(),
deviceActivationRequest.aciSignedPreKey(),
deviceActivationRequest.pniSignedPreKey(),
deviceActivationRequest.aciPqLastResortPreKey(),
deviceActivationRequest.pniPqLastResortPreKey()),
linkDeviceRequest.verificationCode());
return new LinkDeviceResponse(
accountAndDevice.first().getIdentifier(IdentityType.ACI),
@@ -395,19 +382,16 @@ public class DeviceController {
@PUT
@Produces(MediaType.APPLICATION_JSON)
@Path("/capabilities")
public void setCapabilities(@Auth final AuthenticatedDevice auth,
@NotNull
final Map<String, Boolean> capabilities) {
final Account account = accounts.getByAccountIdentifier(auth.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
accounts.updateDevice(account, auth.deviceId(),
public void setCapabilities(@Auth final AuthenticatedDevice auth, @NotNull final Map<String, Boolean> capabilities) {
accounts.updateDevice(auth.accountIdentifier(), auth.deviceId(),
d -> d.setCapabilities(DeviceCapabilityAdapter.mapToSet(capabilities)));
}
private static boolean isCapabilityDowngrade(final Account account, final Set<DeviceCapability> capabilities) {
if (!capabilities.containsAll(DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES)) {
return true;
}
final Set<DeviceCapability> requiredCapabilities = Arrays.stream(DeviceCapability.values())
// `ALWAYS_CAPABLE` capabilities are always assumed to be present, so we don't require callers to specify them
.filter(capability -> capability.getAccountCapabilityMode() != DeviceCapability.AccountCapabilityMode.ALWAYS_CAPABLE)
@@ -15,16 +15,12 @@ import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.Response.Status;
import java.time.Clock;
import java.time.Instant;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.function.Function;
import javax.annotation.Nonnull;
import org.glassfish.jersey.server.ManagedAsync;
import org.signal.libsignal.zkgroup.InvalidInputException;
@@ -35,7 +31,6 @@ import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.configuration.BadgesConfiguration;
import org.whispersystems.textsecuregcm.entities.RedeemReceiptRequest;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountBadge;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.RedeemedReceiptsManager;
@@ -121,9 +116,6 @@ public class DonationController {
.build();
}
final Account account = accountsManager.getByAccountIdentifier(auth.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
final boolean receiptMatched = redeemedReceiptsManager.put(
receiptSerial, receiptExpiration.getEpochSecond(), receiptLevel, auth.accountIdentifier()).join();
if (!receiptMatched) {
@@ -133,7 +125,7 @@ public class DonationController {
.build();
}
accountsManager.update(account, a -> {
accountsManager.update(auth.accountIdentifier(), a -> {
a.addBadge(clock, new AccountBadge(badgeId, receiptExpiration, request.isVisible()));
if (request.isPrimary()) {
a.makeBadgePrimaryIfExists(clock, badgeId);
@@ -398,34 +398,38 @@ public class KeysController {
}
private List<Device> parseDeviceId(String deviceId, Account account) {
return parseDeviceId(deviceId)
.map(id -> account.getDevice(id).map(List::of).orElse(List.of()))
.orElseGet(account::getDevices);
}
private Optional<Byte> parseDeviceId(final String deviceId) {
if (deviceId.equals("*")) {
return account.getDevices();
return Optional.empty();
}
try {
byte id = Byte.parseByte(deviceId);
return account.getDevice(id).map(List::of).orElse(List.of());
return Optional.of(Byte.parseByte(deviceId));
} catch (NumberFormatException e) {
throw new WebApplicationException(Response.status(422).build());
}
}
private String getPreKeysLimiterKey(
final Account account,
final AuthenticatedDevice authenticatedDevice,
final ServiceIdentifier targetIdentifier,
final Account targetAccount,
final String targetDeviceId) {
final String targetRegistrationId = targetDeviceId.equals("*")
? "*"
: String.valueOf(
parseDeviceId(targetDeviceId, targetAccount).getFirst().getRegistrationId(targetIdentifier.identityType()));
return String.format("%s.%s__%s.%s.%s",
final Optional<Byte> parsedTargetDeviceId = parseDeviceId(targetDeviceId);
final Optional<Integer> targetRegistrationId = parsedTargetDeviceId
.flatMap(targetAccount::getDevice)
.map(device -> device.getRegistrationId(targetIdentifier.identityType()));
return RateLimitKeys.preKeyLimiterKey(
account.getUuid(),
authenticatedDevice.deviceId(),
targetIdentifier.uuid(),
targetDeviceId,
targetRegistrationId
);
targetIdentifier,
parsedTargetDeviceId, targetRegistrationId);
}
}
@@ -33,6 +33,7 @@ import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.ServiceUnavailableException;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.core.Context;
@@ -471,6 +472,8 @@ public class MessageController {
}
} catch (final MessageTooLargeException e) {
throw new WebApplicationException(Status.REQUEST_ENTITY_TOO_LARGE);
} catch (final MessageDeliveryNotAllowedException e) {
throw new ServiceUnavailableException();
}
}
@@ -724,6 +727,8 @@ public class MessageController {
.type(MediaType.APPLICATION_JSON)
.entity(accountStaleDevices)
.build());
} catch (final MessageDeliveryNotAllowedException e) {
throw new ServiceUnavailableException();
}
}
@@ -0,0 +1,11 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.controllers;
import org.whispersystems.textsecuregcm.util.NoStackTraceException;
public class MessageDeliveryNotAllowedException extends NoStackTraceException {
}
@@ -58,8 +58,8 @@ import org.whispersystems.textsecuregcm.storage.IssuedReceiptsManager;
import org.whispersystems.textsecuregcm.storage.OneTimeDonationsManager;
import org.whispersystems.textsecuregcm.subscriptions.BraintreeManager;
import org.whispersystems.textsecuregcm.subscriptions.ChargeFailure;
import org.whispersystems.textsecuregcm.subscriptions.PayPalDonationsTranslator;
import org.whispersystems.textsecuregcm.subscriptions.CustomerAwareSubscriptionPaymentProcessor;
import org.whispersystems.textsecuregcm.subscriptions.PayPalDonationsTranslator;
import org.whispersystems.textsecuregcm.subscriptions.PaymentDetails;
import org.whispersystems.textsecuregcm.subscriptions.PaymentMethod;
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
@@ -118,17 +118,18 @@ public class OneTimeDonationController {
public static class CreateBoostRequest {
@Schema(required = true, maxLength = 3, minLength = 3)
@Schema(maxLength = 3, minLength = 3)
@NotEmpty
@ExactlySize(3)
public String currency;
@Schema(required = true, minimum = "1", description = "The amount to pay in the [currency's minor unit](https://docs.stripe.com/currencies#minor-units)")
@Schema(minimum = "1", description = "The amount to pay in the [currency's minor unit](https://docs.stripe.com/currencies#minor-units)", requiredMode = Schema.RequiredMode.REQUIRED)
@Min(1)
public long amount;
@Schema(description = "The level for the boost payment. Assumed to be the boost level if missing")
public Long level;
@Schema(description = "The level for the boost payment", defaultValue = "1", minimum = "1", requiredMode = Schema.RequiredMode.REQUIRED)
@Min(1)
public long level = 1;
@Schema(description = "The payment method", defaultValue = "CARD")
public PaymentMethod paymentMethod = PaymentMethod.CARD;
@@ -160,12 +161,6 @@ public class OneTimeDonationController {
properties = {
@StringToClassMapItem(key = "error", value = String.class)
})))
@ApiResponse(responseCode = "409", description = "Provided level does not match the currency/amount combination",
content = @Content(schema = @Schema(
type = "object",
properties = {
@StringToClassMapItem(key = "error", value = String.class)
})))
public CompletableFuture<Response> createBoostPaymentIntent(
@Auth Optional<AuthenticatedDevice> authenticatedAccount,
@NotNull @Valid CreateBoostRequest request,
@@ -175,45 +170,37 @@ public class OneTimeDonationController {
throw new ForbiddenException("must not use authenticated connection for one-time donation operations");
}
return CompletableFuture.runAsync(() -> {
if (request.level == null) {
request.level = oneTimeDonationConfiguration.boost().level();
}
BigDecimal amount = BigDecimal.valueOf(request.amount);
if (request.level == oneTimeDonationConfiguration.gift().level()) {
BigDecimal amountConfigured = oneTimeDonationConfiguration.currencies()
.get(request.currency.toLowerCase(Locale.ROOT)).gift();
if (amountConfigured == null ||
SubscriptionCurrencyUtil.convertConfiguredAmountToStripeAmount(request.currency, amountConfigured)
.compareTo(amount) != 0) {
throw new WebApplicationException(
Response.status(Response.Status.CONFLICT).entity(Map.of("error", "level_amount_mismatch")).build());
}
}
validateRequestCurrencyAmount(request, amount, stripeManager);
})
.thenCompose(unused -> stripeManager.createPaymentIntent(request.currency, request.amount, request.level,
return CompletableFuture.runAsync(() ->
validateRequestCurrencyAmount(request, BigDecimal.valueOf(request.amount), stripeManager))
.thenCompose(_ -> stripeManager.createPaymentIntent(request.currency, request.amount, request.level,
getClientPlatform(userAgent)))
.thenApply(paymentIntent -> Response.ok(new CreateBoostResponse(paymentIntent.getClientSecret())).build());
}
/**
* Validates that the currency is supported by the {@code manager} and {@code request.paymentMethod} and that the
* amount meets minimum and maximum constraints.
* Validates that the request level is valid, the currency is supported by the {@code manager} and {@code request.paymentMethod},
* and that the amount meets minimum and maximum constraints.
*
* @throws BadRequestException indicates validation failed. Inspect {@code response.error} for details
*/
private void validateRequestCurrencyAmount(CreateBoostRequest request, BigDecimal amount,
CustomerAwareSubscriptionPaymentProcessor manager) {
private void validateRequestCurrencyAmount(final CreateBoostRequest request, final BigDecimal amount,
final CustomerAwareSubscriptionPaymentProcessor manager) {
if (!(request.level == oneTimeDonationConfiguration.gift().level()
|| request.level == oneTimeDonationConfiguration.boost().level())) {
throw new BadRequestException(
Response.status(Response.Status.BAD_REQUEST).entity(Map.of("error", "invalid_level")).build());
}
if (!manager.getSupportedCurrenciesForPaymentMethod(request.paymentMethod)
.contains(request.currency.toLowerCase(Locale.ROOT))) {
throw new BadRequestException(Response.status(Response.Status.BAD_REQUEST)
.entity(Map.of("error", "unsupported_currency")).build());
}
BigDecimal minCurrencyAmountMajorUnits = oneTimeDonationConfiguration.currencies()
final BigDecimal minCurrencyAmountMajorUnits = oneTimeDonationConfiguration.currencies()
.get(request.currency.toLowerCase(Locale.ROOT)).minimum();
BigDecimal minCurrencyAmountMinorUnits = SubscriptionCurrencyUtil.convertConfiguredAmountToApiAmount(
final BigDecimal minCurrencyAmountMinorUnits = SubscriptionCurrencyUtil.convertConfiguredAmountToApiAmount(
request.currency,
minCurrencyAmountMajorUnits);
if (minCurrencyAmountMinorUnits.compareTo(amount) > 0) {
@@ -255,21 +242,15 @@ public class OneTimeDonationController {
public CompletableFuture<Response> createPayPalBoost(
@Auth Optional<AuthenticatedDevice> authenticatedAccount,
@NotNull @Valid CreatePayPalBoostRequest request,
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
@Context ContainerRequestContext containerRequestContext) {
if (authenticatedAccount.isPresent()) {
throw new ForbiddenException("must not use authenticated connection for one-time donation operations");
}
return CompletableFuture.runAsync(() -> {
if (request.level == null) {
request.level = oneTimeDonationConfiguration.boost().level();
}
validateRequestCurrencyAmount(request, BigDecimal.valueOf(request.amount), braintreeManager);
})
.thenCompose(unused -> {
return CompletableFuture.runAsync(() ->
validateRequestCurrencyAmount(request, BigDecimal.valueOf(request.amount), braintreeManager))
.thenCompose(_ -> {
final List<Locale> acceptableLanguages =
HeaderUtils.getAcceptableLanguagesForRequest(containerRequestContext);
@@ -300,6 +281,10 @@ public class OneTimeDonationController {
public String paymentId; // PAYID-…
@NotEmpty
public String paymentToken; // EC-…
public ConfirmPayPalBoostRequest() {
super.paymentMethod = PaymentMethod.PAYPAL;
}
}
record ConfirmPayPalBoostResponse(String paymentId) {}
@@ -317,12 +302,9 @@ public class OneTimeDonationController {
throw new ForbiddenException("must not use authenticated connection for one-time donation operations");
}
return CompletableFuture.runAsync(() -> {
if (request.level == null) {
request.level = oneTimeDonationConfiguration.boost().level();
}
})
.thenCompose(unused -> braintreeManager.captureOneTimePayment(request.payerId, request.paymentId,
return CompletableFuture.runAsync(() ->
validateRequestCurrencyAmount(request, BigDecimal.valueOf(request.amount), braintreeManager))
.thenCompose(_ -> braintreeManager.captureOneTimePayment(request.payerId, request.paymentId,
request.paymentToken, request.currency, request.amount, request.level, getClientPlatform(userAgent)))
.thenCompose(
chargeSuccessDetails -> oneTimeDonationsManager.putPaidAt(chargeSuccessDetails.paymentId(), Instant.now()))
@@ -412,7 +394,7 @@ public class OneTimeDonationController {
final long finalLevel = level;
return issuedReceiptsManager.recordIssuance(paymentDetails.id(), request.processor,
receiptCredentialRequest, clock.instant())
.thenCompose(unused -> oneTimeDonationsManager.getPaidAt(paymentDetails.id(), paymentDetails.created()))
.thenCompose(_ -> oneTimeDonationsManager.getPaidAt(paymentDetails.id(), paymentDetails.created()))
.thenApply(paidAt -> {
Instant expiration = paidAt
.plus(levelExpiration)
@@ -62,6 +62,8 @@ import org.signal.libsignal.zkgroup.VerificationFailedException;
import org.signal.libsignal.zkgroup.groupsend.GroupSendDerivedKeyPair;
import org.signal.libsignal.zkgroup.groupsend.GroupSendFullToken;
import org.signal.libsignal.zkgroup.profiles.ExpiringProfileKeyCredentialResponse;
import org.signal.libsignal.zkgroup.profiles.ProfileKeyCommitment;
import org.signal.libsignal.zkgroup.profiles.ProfileKeyCredentialRequest;
import org.signal.libsignal.zkgroup.profiles.ServerZkProfileOperations;
import org.whispersystems.textsecuregcm.auth.Anonymous;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
@@ -83,6 +85,7 @@ import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.limits.RateLimitedByIp;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.s3.PolicySigner;
@@ -93,7 +96,7 @@ import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
import org.whispersystems.textsecuregcm.storage.VersionedProfile;
import org.whispersystems.textsecuregcm.storage.VersionedProfileV1;
import org.whispersystems.textsecuregcm.util.HeaderUtils;
import org.whispersystems.textsecuregcm.util.Pair;
import org.whispersystems.textsecuregcm.util.ProfileHelper;
@@ -171,33 +174,28 @@ public class ProfileController {
final Account account = accountsManager.getByAccountIdentifier(auth.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
final Optional<VersionedProfile> currentProfile =
profilesManager.get(auth.accountIdentifier(), request.version());
if (account.hasCapability(DeviceCapability.PROFILES_V2)) {
return Response.status(Response.Status.PRECONDITION_FAILED).build();
}
final Optional<VersionedProfileV1> currentProfile =
profilesManager.getV1(auth.accountIdentifier(), request.version());
if (request.paymentAddress() != null && request.paymentAddress().length != 0) {
final boolean hasDisallowedPrefix =
dynamicConfigurationManager.getConfiguration().getPaymentsConfiguration().getDisallowedPrefixes().stream()
.anyMatch(prefix -> account.getNumber().startsWith(prefix));
if (hasDisallowedPrefix && currentProfile.map(VersionedProfile::paymentAddress).isEmpty()) {
if (hasDisallowedPrefix && currentProfile.map(VersionedProfileV1::paymentAddress).isEmpty()) {
return Response.status(Response.Status.FORBIDDEN).build();
}
}
Optional<String> currentAvatar = Optional.empty();
if (currentProfile.isPresent() && currentProfile.get().avatar() != null && currentProfile.get().avatar()
.startsWith("profiles/")) {
currentAvatar = Optional.of(currentProfile.get().avatar());
}
final Optional<String> currentAvatar = ProfileHelper.getCurrentAvatar(currentProfile);
final String avatar = ProfileHelper.getAvatar(request.getAvatarChange(), currentAvatar);
final String avatar = switch (request.getAvatarChange()) {
case UNCHANGED -> currentAvatar.orElse(null);
case CLEAR -> null;
case UPDATE -> ProfileHelper.generateAvatarObjectName();
};
profilesManager.set(auth.accountIdentifier(),
new VersionedProfile(
profilesManager.setV1(auth.accountIdentifier(),
new VersionedProfileV1(
request.version(),
request.name(),
avatar,
@@ -211,7 +209,7 @@ public class ProfileController {
currentAvatar.ifPresent(profilesManager::deleteAvatar);
}
accountsManager.update(account, a -> {
accountsManager.update(account.getIdentifier(IdentityType.ACI), a -> {
final List<AccountBadge> updatedBadges = request.badges()
.map(badges -> ProfileHelper.mergeBadgeIdsWithExistingAccountBadges(clock, badgeConfigurationMap, badges, a.getBadges()))
@@ -364,6 +362,7 @@ public class ProfileController {
@Path("/identity_check/batch")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@RateLimitedByIp(RateLimiters.For.BATCH_IDENTITY_CHECK)
@Operation(
summary = "Batch identity key check",
description = "Checks identity key fingerprints for multiple accounts. Returns accounts where the fingerprint does not match. Should not be authenticated.")
@@ -372,7 +371,8 @@ public class ProfileController {
description = "Batch check completed successfully. Response may contain accounts with mismatched fingerprints.",
content = @Content(schema = @Schema(implementation = BatchIdentityCheckResponse.class)))
@ApiResponse(responseCode = "400", description = "Invalid request format or validation failed.")
public CompletableFuture<BatchIdentityCheckResponse> runBatchIdentityCheck(@NotNull @Valid BatchIdentityCheckRequest request) {
@ApiResponse(responseCode = "429", description = "Rate limit exceeded.")
public CompletableFuture<BatchIdentityCheckResponse> runBatchIdentityCheck(@NotNull @Valid final BatchIdentityCheckRequest request) {
return CompletableFuture.supplyAsync(() -> {
List<BatchIdentityCheckResponse.Element> responseElements = Collections.synchronizedList(new ArrayList<>());
@@ -434,18 +434,26 @@ public class ProfileController {
final boolean isSelf,
final ContainerRequestContext containerRequestContext) {
final ExpiringProfileKeyCredentialResponse expiringProfileKeyCredentialResponse = profilesManager.get(account.getUuid(), version)
.map(profile -> {
final ExpiringProfileKeyCredentialResponse profileKeyCredentialResponse;
try {
profileKeyCredentialResponse = ProfileHelper.getExpiringProfileKeyCredential(HexFormat.of().parseHex(encodedCredentialRequest),
profile, new ServiceId.Aci(account.getUuid()), zkProfileOperations);
} catch (VerificationFailedException | InvalidInputException e) {
throw new BadRequestException(e);
}
return profileKeyCredentialResponse;
})
.orElse(null);
final ExpiringProfileKeyCredentialResponse expiringProfileKeyCredentialResponse;
if (account.getCurrentProfileVersion().map(version::equals).orElse(false)) {
expiringProfileKeyCredentialResponse = profilesManager.getV1(account.getUuid(), version)
.map(profile -> {
final ExpiringProfileKeyCredentialResponse profileKeyCredentialResponse;
try {
profileKeyCredentialResponse = ProfileHelper.getExpiringProfileKeyCredential(
new ProfileKeyCredentialRequest(HexFormat.of().parseHex(encodedCredentialRequest)),
new ProfileKeyCommitment(profile.commitment()), new ServiceId.Aci(account.getUuid()),
zkProfileOperations);
} catch (VerificationFailedException | InvalidInputException e) {
throw new BadRequestException(e);
}
return profileKeyCredentialResponse;
})
.orElse(null);
} else {
expiringProfileKeyCredentialResponse = null;
}
return new ExpiringProfileKeyCredentialProfileResponse(
buildVersionedProfileResponse(account, version, isSelf, true, containerRequestContext),
@@ -458,7 +466,7 @@ public class ProfileController {
final boolean hasCredentialRequest,
final ContainerRequestContext containerRequestContext) {
final Optional<VersionedProfile> maybeProfile = profilesManager.get(account.getUuid(), version);
final Optional<VersionedProfileV1> maybeProfile = profilesManager.getV1(account.getUuid(), version);
if (maybeProfile.isEmpty()) {
// this can happen if an account re-registers, which includes some device-transfer scenarios
@@ -471,17 +479,17 @@ public class ProfileController {
.increment();
}
final byte[] name = maybeProfile.map(VersionedProfile::name).orElse(null);
final byte[] about = maybeProfile.map(VersionedProfile::about).orElse(null);
final byte[] aboutEmoji = maybeProfile.map(VersionedProfile::aboutEmoji).orElse(null);
final String avatar = maybeProfile.map(VersionedProfile::avatar).orElse(null);
final byte[] phoneNumberSharing = maybeProfile.map(VersionedProfile::phoneNumberSharing).orElse(null);
final byte[] name = maybeProfile.map(VersionedProfileV1::name).orElse(null);
final byte[] about = maybeProfile.map(VersionedProfileV1::about).orElse(null);
final byte[] aboutEmoji = maybeProfile.map(VersionedProfileV1::aboutEmoji).orElse(null);
final String avatar = maybeProfile.map(VersionedProfileV1::avatar).orElse(null);
final byte[] phoneNumberSharing = maybeProfile.map(VersionedProfileV1::phoneNumberSharing).orElse(null);
// Allow requests where either the version matches the latest version on Account or the latest version on Account
// is empty to read the payment address.
final byte[] paymentAddress = maybeProfile
.filter(p -> account.getCurrentProfileVersion().map(v -> v.equals(version)).orElse(true))
.map(VersionedProfile::paymentAddress)
.filter(p -> account.getCurrentProfileVersion().map(v -> v.equals(p.version())).orElse(true))
.map(VersionedProfileV1::paymentAddress)
.orElse(null);
return new VersionedProfileResponse(
@@ -0,0 +1,35 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.controllers;
import java.util.Optional;
import java.util.UUID;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
/// Helper methods to centrally define rate-limit key formats used in multiple places
public class RateLimitKeys {
/// Key for rate-limiting a device's pre-keys
///
/// @param sourceAci the account identifier of the authenticated device fetching the pre-keys
/// @param sourceDeviceId the deviceId of the authenticated device fetching pre-keys
/// @param targetIdentifier the [ServiceIdentifier] of the target account
/// @param targetDeviceId the deviceId of the target device, empty if fetching all device pre-keys
/// @param targetRegistrationId the registrationId of the target device, empty if fetching all device pre-keys
/// @return the rate-limit key
public static String preKeyLimiterKey(
final UUID sourceAci,
final byte sourceDeviceId,
final ServiceIdentifier targetIdentifier,
final Optional<Byte> targetDeviceId,
final Optional<Integer> targetRegistrationId) {
return String.format("%s.%s__%s.%s.%s",
sourceAci,
sourceDeviceId,
targetIdentifier.uuid(),
targetDeviceId.map(String::valueOf).orElse("*"),
targetRegistrationId.map(String::valueOf).orElse("*"));
}
}
@@ -34,6 +34,9 @@ import java.time.Instant;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Optional;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.auth.BasicAuthorizationHeader;
import org.whispersystems.textsecuregcm.auth.PhoneVerificationTokenManager;
import org.whispersystems.textsecuregcm.auth.RegistrationLockVerificationManager;
@@ -44,6 +47,7 @@ import org.whispersystems.textsecuregcm.entities.RegistrationLockFailure;
import org.whispersystems.textsecuregcm.entities.RegistrationRequest;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.spam.RegistrationFraudChecker;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
@@ -69,16 +73,21 @@ public class RegistrationController {
private final PhoneVerificationTokenManager phoneVerificationTokenManager;
private final RegistrationLockVerificationManager registrationLockVerificationManager;
private final RateLimiters rateLimiters;
private final RegistrationFraudChecker registrationFraudChecker;
private static final Logger logger = LoggerFactory.getLogger(RegistrationController.class);
public RegistrationController(final AccountsManager accounts,
final PhoneVerificationTokenManager phoneVerificationTokenManager,
final RegistrationLockVerificationManager registrationLockVerificationManager,
final RateLimiters rateLimiters) {
final RateLimiters rateLimiters,
final RegistrationFraudChecker registrationFraudChecker) {
this.accounts = accounts;
this.phoneVerificationTokenManager = phoneVerificationTokenManager;
this.registrationLockVerificationManager = registrationLockVerificationManager;
this.rateLimiters = rateLimiters;
this.registrationFraudChecker = registrationFraudChecker;
}
@POST
@@ -118,17 +127,27 @@ public class RegistrationController {
if (!(registrationRequest.accountAttributes().getCapabilities() != null
? registrationRequest.accountAttributes().getCapabilities()
: Collections.<DeviceCapability>emptySet()).containsAll(DeviceCapability.CAPABILITIES_REQUIRED_FOR_REGISTRATION)) {
: Collections.<DeviceCapability>emptySet()).containsAll(DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES)) {
throw new WebApplicationException("Missing required device capability", 499);
}
rateLimiters.getRegistrationLimiter().validate(number);
final PhoneVerificationRequest.VerificationType verificationType = phoneVerificationTokenManager.verify(
requestContext, number, registrationRequest);
final PhoneVerificationRequest.VerificationType verificationType =
phoneVerificationTokenManager.verify(requestContext,
number,
StringUtils.isNotBlank(registrationRequest.sessionId()) ? registrationRequest.decodeSessionId() : null,
registrationRequest.recoveryPassword());
final Optional<Account> existingAccount = accounts.getByE164(number);
// There can be at most one existing account for a set of numbers in the same equivalence class, so it's sufficient
// to find the first one.
final Optional<Account> existingAccount = Util.getAlternateForms(number)
.stream()
.map(accounts::getByE164)
.filter(Optional::isPresent)
.map(Optional::get)
.findFirst();
existingAccount.ifPresent(account -> {
final Instant accountLastSeen = Instant.ofEpochMilli(account.getLastSeen());
@@ -169,6 +188,14 @@ public class RegistrationController {
registrationRequest.deviceActivationRequest().pniPqLastResortPreKey()),
userAgent);
if (verificationType == PhoneVerificationRequest.VerificationType.SESSION) {
try {
registrationFraudChecker.handleVerificationCompleted(registrationRequest.sessionId(), account);
} catch (final Exception e) {
logger.warn("Failed to notify fraud checker of completed verification session", e);
}
}
Metrics.counter(ACCOUNT_CREATED_COUNTER_NAME, Tags.of(UserAgentTagUtil.getPlatformTag(userAgent),
Tag.of(COUNTRY_CODE_TAG_NAME, Util.getCountryCode(number)),
Tag.of(REGION_CODE_TAG_NAME, Util.getRegion(number)),
@@ -77,6 +77,7 @@ import org.whispersystems.textsecuregcm.entities.VerificationSessionResponse;
import org.whispersystems.textsecuregcm.filters.RemoteAddressFilter;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.mappers.RegistrationServiceSenderExceptionMapper;
import org.whispersystems.textsecuregcm.metrics.CaptchaMetrics;
import org.whispersystems.textsecuregcm.metrics.DevicePlatformUtil;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.push.PushNotification;
@@ -492,6 +493,11 @@ public class VerificationController {
Tag.of(SCORE_TAG_NAME, assessmentResult.getScoreString())))
.increment();
CaptchaMetrics.measureCaptchaOutcome(assessmentResult.getNormalizedIntScore(),
assessmentResult.isValid(captchaScoreThreshold),
Util.getRegion(registrationServiceSession.number()),
"verification");
} catch (final IOException e) {
logger.error("error assessing captcha during registration verification", e);
throw new ServerErrorException(Response.Status.SERVICE_UNAVAILABLE, e);
@@ -782,6 +788,10 @@ public class VerificationController {
boolean existingRRP = false;
if (resultSession.verified()) {
// Since there is a valid verification session we invalidate the other possible verification mechanism,
// the RRP. It's possible the client will not actually be able to register (e.g. failed reglock challenge), and
// so we will have removed the RRP unnecessarily. The impact of this is low, since the owner of the RRP
// can always just fallback to session-based verification.
existingRRP = registrationRecoveryPasswordsManager.remove(phoneNumberIdentifiers.getPhoneNumberIdentifier(registrationServiceSession.number()).join()).join();
}
@@ -854,7 +864,11 @@ public class VerificationController {
.orElseThrow(NotFoundException::new);
if (registrationServiceSession.verified()) {
registrationRecoveryPasswordsManager.remove(phoneNumberIdentifiers.getPhoneNumberIdentifier(registrationServiceSession.number()).join());
// Since there is a valid verification session we invalidate the other possible verification mechanism,
// the RRP. It's possible the client will not actually be able to register (e.g. failed reglock challenge), and
// so we will have removed the RRP unnecessarily. The impact of this is low, since the owner of the RRP
// can always just fallback to session-based verification.
registrationRecoveryPasswordsManager.remove(phoneNumberIdentifiers.getPhoneNumberIdentifier(registrationServiceSession.number()).join()).join();
}
return registrationServiceSession;
@@ -4,40 +4,26 @@
*/
package org.whispersystems.textsecuregcm.entities;
import static org.whispersystems.textsecuregcm.util.RegistrationIdValidator.validRegistrationId;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonUnwrapped;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.google.common.annotations.VisibleForTesting;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.Valid;
import jakarta.validation.constraints.AssertTrue;
import jakarta.validation.constraints.Size;
import java.util.Optional;
import java.util.Set;
import javax.annotation.Nullable;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
import org.whispersystems.textsecuregcm.util.DeviceCapabilityAdapter;
import org.whispersystems.textsecuregcm.util.ExactlySize;
public class AccountAttributes {
@JsonProperty
private boolean fetchesMessages;
@JsonProperty
private int registrationId;
@JsonProperty("pniRegistrationId")
private int phoneNumberIdentityRegistrationId;
@JsonProperty
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
@Size(max = 225)
private byte[] name;
@JsonUnwrapped
@Valid
private DeviceAttributes deviceAttributes;
@JsonProperty
@ExactlySize({0, 64})
@@ -50,12 +36,6 @@ public class AccountAttributes {
@JsonProperty
private boolean unrestrictedUnidentifiedAccess;
@JsonProperty
@JsonSerialize(using = DeviceCapabilityAdapter.Serializer.class)
@JsonDeserialize(using = DeviceCapabilityAdapter.Deserializer.class)
@Nullable
private Set<DeviceCapability> capabilities;
@JsonProperty
private boolean discoverableByPhoneNumber = true;
@@ -77,29 +57,26 @@ public class AccountAttributes {
final String registrationLock,
final boolean discoverableByPhoneNumber,
final Set<DeviceCapability> capabilities) {
this.fetchesMessages = fetchesMessages;
this.registrationId = registrationId;
this.phoneNumberIdentityRegistrationId = phoneNumberIdentifierRegistrationId;
this.name = name;
this.deviceAttributes = new DeviceAttributes(fetchesMessages, registrationId, phoneNumberIdentifierRegistrationId, name, capabilities);
this.registrationLock = registrationLock;
this.discoverableByPhoneNumber = discoverableByPhoneNumber;
this.capabilities = capabilities;
}
public boolean getFetchesMessages() {
return fetchesMessages;
return deviceAttributes.fetchesMessages();
}
public int getRegistrationId() {
return registrationId;
return deviceAttributes.registrationId();
}
public int getPhoneNumberIdentityRegistrationId() {
return phoneNumberIdentityRegistrationId;
return deviceAttributes.phoneNumberIdentityRegistrationId();
}
public byte[] getName() {
return name;
return deviceAttributes.name();
}
public String getRegistrationLock() {
@@ -116,7 +93,7 @@ public class AccountAttributes {
@Nullable
public Set<DeviceCapability> getCapabilities() {
return capabilities;
return deviceAttributes.capabilities();
}
public boolean isDiscoverableByPhoneNumber() {
@@ -128,20 +105,33 @@ public class AccountAttributes {
}
@VisibleForTesting
public AccountAttributes withUnidentifiedAccessKey(final byte[] unidentifiedAccessKey) {
public AccountAttributes setUnidentifiedAccessKey(final byte[] unidentifiedAccessKey) {
this.unidentifiedAccessKey = unidentifiedAccessKey;
return this;
}
@VisibleForTesting
public AccountAttributes withRecoveryPassword(final byte[] recoveryPassword) {
public AccountAttributes setRecoveryPassword(final byte[] recoveryPassword) {
this.recoveryPassword = recoveryPassword;
return this;
}
@VisibleForTesting
public AccountAttributes setDeviceAttributes(final DeviceAttributes deviceAttributes) {
this.deviceAttributes = deviceAttributes;
return this;
}
@VisibleForTesting
public AccountAttributes setUnrestrictedUnidentifiedAccess(final boolean unrestrictedUnidentifiedAccess) {
this.unrestrictedUnidentifiedAccess = unrestrictedUnidentifiedAccess;
return this;
}
@AssertTrue
@Schema(hidden = true)
public boolean isEachRegistrationIdValid() {
return validRegistrationId(registrationId) && validRegistrationId(phoneNumberIdentityRegistrationId);
public boolean isUnrestrictedUakValid() {
return unrestrictedUnidentifiedAccess || (unidentifiedAccessKey != null && unidentifiedAccessKey.length == 16);
}
}
@@ -0,0 +1,46 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.entities;
import static org.whispersystems.textsecuregcm.util.RegistrationIdValidator.validRegistrationId;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.AssertTrue;
import jakarta.validation.constraints.Size;
import java.util.Set;
import javax.annotation.Nullable;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
import org.whispersystems.textsecuregcm.util.DeviceCapabilityAdapter;
public record DeviceAttributes(
boolean fetchesMessages,
int registrationId,
@JsonProperty("pniRegistrationId") int phoneNumberIdentityRegistrationId,
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
@Size(max = 225)
byte[] name,
@JsonSerialize(using = DeviceCapabilityAdapter.Serializer.class)
@JsonDeserialize(using = DeviceCapabilityAdapter.Deserializer.class)
@Nullable
Set<DeviceCapability> capabilities) {
@AssertTrue
@Schema(hidden = true)
public boolean isEachRegistrationIdValid() {
return validRegistrationId(registrationId) && validRegistrationId(phoneNumberIdentityRegistrationId);
}
}
@@ -19,7 +19,7 @@ public class ExpiringProfileKeyCredentialProfileResponse {
@JsonUnwrapped
private VersionedProfileResponse versionedProfileResponse;
@Schema(description = "Expiring profile key credential response. Null if profile version was not found")
@Schema(description = "Expiring profile key credential response. Null if profile version was not found or if the profile version is not current")
@JsonProperty
@JsonSerialize(using = ExpiringProfileKeyCredentialResponseAdapter.Serializing.class)
@JsonDeserialize(using = ExpiringProfileKeyCredentialResponseAdapter.Deserializing.class)
@@ -14,6 +14,7 @@ import io.swagger.v3.oas.annotations.media.Schema;
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 java.util.List;
@@ -21,6 +22,7 @@ import java.util.Objects;
import org.whispersystems.textsecuregcm.controllers.MessageController;
public record IncomingMessageList(@NotNull
@NotEmpty
@Valid
List<@NotNull @Valid IncomingMessage> messages,
@@ -19,7 +19,8 @@ public record LinkDeviceRequest(@Schema(requiredMode = Schema.RequiredMode.REQUI
@NotNull
@Valid
AccountAttributes accountAttributes,
@JsonProperty("accountAttributes")
DeviceAttributes deviceAttributes,
@NotNull
@Valid
@@ -30,7 +31,7 @@ public record LinkDeviceRequest(@Schema(requiredMode = Schema.RequiredMode.REQUI
@JsonCreator
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
public LinkDeviceRequest(@JsonProperty("verificationCode") String verificationCode,
@JsonProperty("accountAttributes") AccountAttributes accountAttributes,
@JsonProperty("accountAttributes") DeviceAttributes deviceAttributes,
@JsonProperty("aciSignedPreKey") @NotNull @Valid ECSignedPreKey aciSignedPreKey,
@JsonProperty("pniSignedPreKey") @NotNull @Valid ECSignedPreKey pniSignedPreKey,
@JsonProperty("aciPqLastResortPreKey") @NotNull @Valid KEMSignedPreKey aciPqLastResortPreKey,
@@ -38,14 +39,14 @@ public record LinkDeviceRequest(@Schema(requiredMode = Schema.RequiredMode.REQUI
@JsonProperty("apnToken") Optional<@Valid ApnRegistrationId> apnToken,
@JsonProperty("gcmToken") Optional<@Valid GcmRegistrationId> gcmToken) {
this(verificationCode, accountAttributes,
this(verificationCode, deviceAttributes,
new DeviceActivationRequest(aciSignedPreKey, pniSignedPreKey, aciPqLastResortPreKey, pniPqLastResortPreKey, apnToken, gcmToken));
}
@AssertTrue
@Schema(hidden = true)
public boolean isExactlyOneMessageDeliveryChannel() {
if (accountAttributes != null && accountAttributes.getFetchesMessages()) {
if (deviceAttributes != null && deviceAttributes.fetchesMessages()) {
return deviceActivationRequest().apnToken().isEmpty() && deviceActivationRequest().gcmToken().isEmpty();
} else {
return deviceActivationRequest().apnToken().isPresent() ^ deviceActivationRequest().gcmToken().isPresent();
@@ -7,6 +7,7 @@ package org.whispersystems.textsecuregcm.filters;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.net.HttpHeaders;
import com.vdurmont.semver4j.Semver;
import io.grpc.Metadata;
@@ -23,14 +24,21 @@ import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import javax.annotation.Nullable;
import org.whispersystems.textsecuregcm.auth.AccountAuthenticator;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.grpc.RequireAuthenticationInterceptor;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicRemoteDeprecationConfiguration;
import org.whispersystems.textsecuregcm.grpc.GrpcExceptions;
import org.whispersystems.textsecuregcm.grpc.RequestAttributesUtil;
import org.whispersystems.textsecuregcm.grpc.ServerInterceptorUtil;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.util.HeaderUtils;
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
import org.whispersystems.textsecuregcm.util.ua.UnrecognizedUserAgentException;
import org.whispersystems.textsecuregcm.util.ua.UserAgent;
@@ -44,6 +52,8 @@ import org.whispersystems.textsecuregcm.util.ua.UserAgentUtil;
*/
public class RemoteDeprecationFilter implements Filter, ServerInterceptor {
private final AccountsManager accountsManager;
private final AccountAuthenticator accountAuthenticator;
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
private static final String DEPRECATED_CLIENT_COUNTER_NAME = name(RemoteDeprecationFilter.class, "deprecated");
@@ -52,9 +62,14 @@ public class RemoteDeprecationFilter implements Filter, ServerInterceptor {
private static final String REASON_TAG_NAME = "reason";
private static final String EXPIRED_CLIENT_REASON = "expired";
private static final String BLOCKED_CLIENT_REASON = "blocked";
private static final String UNRECOGNIZED_UA_REASON = "unrecognized_user_agent";
private static final String SPQR_NOT_SUPPORTED_REASON = "spqr";
public RemoteDeprecationFilter(final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
public RemoteDeprecationFilter(final AccountsManager accountsManager,
final AccountAuthenticator accountAuthenticator,
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
this.accountsManager = accountsManager;
this.accountAuthenticator = accountAuthenticator;
this.dynamicConfigurationManager = dynamicConfigurationManager;
}
@@ -69,7 +84,7 @@ public class RemoteDeprecationFilter implements Filter, ServerInterceptor {
userAgent = null;
}
if (shouldBlock(userAgent)) {
if (shouldBlock(userAgent, ((HttpServletRequest) request).getHeader(HttpHeaders.AUTHORIZATION))) {
((HttpServletResponse) response).sendError(499);
} else {
chain.doFilter(request, response);
@@ -91,32 +106,41 @@ public class RemoteDeprecationFilter implements Filter, ServerInterceptor {
}
}).orElse(null);
if (shouldBlock(userAgent)) {
if (shouldBlock(userAgent, headers.get(RequireAuthenticationInterceptor.AUTHORIZATION_METADATA_KEY))) {
return ServerInterceptorUtil.closeWithStatusException(call, GrpcExceptions.upgradeRequired());
} else {
return next.startCall(call, headers);
}
}
private boolean shouldBlock(@Nullable final UserAgent userAgent) {
@VisibleForTesting
boolean shouldBlock(@Nullable final UserAgent userAgent, @Nullable final String authHeader) {
final DynamicRemoteDeprecationConfiguration configuration = dynamicConfigurationManager
.getConfiguration().getRemoteDeprecationConfiguration();
final Map<ClientPlatform, Semver> minimumVersionsByPlatform = configuration.getMinimumVersions();
final Map<ClientPlatform, Semver> minimumVersionsByPlatform = configuration.minimumVersions();
final Map<ClientPlatform, Semver> versionsPendingDeprecationByPlatform = configuration
.getVersionsPendingDeprecation();
final Map<ClientPlatform, Set<Semver>> blockedVersionsByPlatform = configuration.getBlockedVersions();
final Map<ClientPlatform, Set<Semver>> versionsPendingBlockByPlatform = configuration.getVersionsPendingBlock();
boolean shouldBlock = false;
.versionsPendingDeprecation();
final Map<ClientPlatform, Set<Semver>> blockedVersionsByPlatform = configuration.blockedVersions();
final Map<ClientPlatform, Set<Semver>> versionsPendingBlockByPlatform = configuration.versionsPendingBlock();
if (userAgent == null) {
if (configuration.isUnrecognizedUserAgentAllowed()) {
return false;
// In first-party clients, we can enforce SPQR presence via minimum client version. For third-party clients, we
// need to do a more expensive check for the actual capability.
if ((configuration.spqrEnforcementPending() || configuration.requireSpqr()) && isMissingSpqrCapability(authHeader)) {
if (configuration.requireSpqr()) {
recordDeprecation(null, SPQR_NOT_SUPPORTED_REASON);
return true;
}
recordPendingDeprecation(null, SPQR_NOT_SUPPORTED_REASON);
}
recordDeprecation(null, UNRECOGNIZED_UA_REASON);
return true;
return false;
}
boolean shouldBlock = false;
if (blockedVersionsByPlatform.containsKey(userAgent.platform())) {
if (blockedVersionsByPlatform.get(userAgent.platform()).contains(userAgent.version())) {
recordDeprecation(userAgent, BLOCKED_CLIENT_REASON);
@@ -146,15 +170,37 @@ public class RemoteDeprecationFilter implements Filter, ServerInterceptor {
return shouldBlock;
}
private void recordDeprecation(final UserAgent userAgent, final String reason) {
/// Tests whether the device identified by the given authentication header (if any) is definitively missing the SPQR
/// capability.
///
/// @return `true` if the authenticated device is definitively missing the SPQR capability or `false` if the
/// capability is present, no credentials are presented, or if authentication failed for any reason
@VisibleForTesting
boolean isMissingSpqrCapability(@Nullable final String authHeader) {
if (authHeader == null) {
return false;
}
final Optional<AuthenticatedDevice> maybeAuthenticatedDevice =
HeaderUtils.basicCredentialsFromAuthHeader(authHeader)
.flatMap(accountAuthenticator::authenticate);
return maybeAuthenticatedDevice
.flatMap(authenticatedDevice -> accountsManager.getByAccountIdentifier(authenticatedDevice.accountIdentifier()))
.flatMap(account -> account.getDevice(maybeAuthenticatedDevice.get().deviceId()))
.map(device -> !device.hasCapability(DeviceCapability.SPARSE_POST_QUANTUM_RATCHET))
.orElse(false);
}
private void recordDeprecation(@Nullable final UserAgent userAgent, final String reason) {
Metrics.counter(DEPRECATED_CLIENT_COUNTER_NAME,
PLATFORM_TAG, userAgent != null ? userAgent.platform().name().toLowerCase() : "unrecognized",
REASON_TAG_NAME, reason).increment();
}
private void recordPendingDeprecation(final UserAgent userAgent, final String reason) {
private void recordPendingDeprecation(@Nullable final UserAgent userAgent, final String reason) {
Metrics.counter(PENDING_DEPRECATION_COUNTER_NAME,
PLATFORM_TAG, userAgent.platform().name().toLowerCase(),
PLATFORM_TAG, userAgent != null ? userAgent.platform().name().toLowerCase() : "unrecognized",
REASON_TAG_NAME, reason).increment();
}
}
@@ -27,9 +27,9 @@ public class CanonicalRequest {
@Nonnull
private final String domain;
private final int maxSizeInBytes;
private final long maxSizeInBytes;
public CanonicalRequest(@Nonnull String canonicalRequest, @Nonnull String resourcePath, @Nonnull String canonicalQuery, @Nonnull String activeDatetime, @Nonnull String credentialScope, @Nonnull String domain, int maxSizeInBytes) {
public CanonicalRequest(@Nonnull String canonicalRequest, @Nonnull String resourcePath, @Nonnull String canonicalQuery, @Nonnull String activeDatetime, @Nonnull String credentialScope, @Nonnull String domain, long maxSizeInBytes) {
this.canonicalRequest = canonicalRequest;
this.resourcePath = resourcePath;
this.canonicalQuery = canonicalQuery;
@@ -69,7 +69,7 @@ public class CanonicalRequest {
return domain;
}
public int getMaxSizeInBytes() {
public long getMaxSizeInBytes() {
return maxSizeInBytes;
}
}
@@ -26,19 +26,16 @@ public class CanonicalRequestGenerator {
@Nonnull
private final String email;
private final int maxSizeBytes;
@Nonnull
private final String pathPrefix;
public CanonicalRequestGenerator(@Nonnull String domain, @Nonnull String email, int maxSizeBytes, @Nonnull String pathPrefix) {
public CanonicalRequestGenerator(@Nonnull String domain, @Nonnull String email, @Nonnull String pathPrefix) {
this.domain = domain;
this.email = email;
this.maxSizeBytes = maxSizeBytes;
this.pathPrefix = pathPrefix;
}
public CanonicalRequest createFor(@Nonnull final String key, @Nonnull final ZonedDateTime now) {
public CanonicalRequest createFor(@Nonnull final String key, @Nonnull final ZonedDateTime now, final long uploadLength) {
final StringBuilder result = new StringBuilder("POST\n");
final StringBuilder resourcePathBuilder = new StringBuilder();
@@ -58,7 +55,7 @@ public class CanonicalRequestGenerator {
result.append(canonicalQuery).append('\n');
result.append("host:").append(domain).append('\n');
result.append("x-goog-content-length-range:1,").append(maxSizeBytes).append('\n');
result.append("x-goog-content-length-range:1,").append(uploadLength).append('\n');
result.append("x-goog-resumable:start\n");
result.append('\n');
@@ -66,7 +63,7 @@ public class CanonicalRequestGenerator {
result.append("UNSIGNED-PAYLOAD");
return new CanonicalRequest(result.toString(), resourcePath, canonicalQuery, activeDatetime, makeCredentialScope(now), domain, maxSizeBytes);
return new CanonicalRequest(result.toString(), resourcePath, canonicalQuery, activeDatetime, makeCredentialScope(now), domain, uploadLength);
}
private String makeCredentialScope(@Nonnull ZonedDateTime now) {
@@ -7,6 +7,7 @@ package org.whispersystems.textsecuregcm.grpc;
import com.google.protobuf.ByteString;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HexFormat;
import java.util.List;
import java.util.UUID;
@@ -34,6 +35,8 @@ import org.signal.chat.account.SetRegistrationRecoveryPasswordRequest;
import org.signal.chat.account.SetRegistrationRecoveryPasswordResponse;
import org.signal.chat.account.SetUsernameLinkRequest;
import org.signal.chat.account.SetUsernameLinkResponse;
import org.signal.chat.account.SetZkCredentialKeyRequest;
import org.signal.chat.account.SetZkCredentialKeyResponse;
import org.signal.chat.account.SimpleAccountsGrpc;
import org.signal.chat.account.UsernameNotAvailable;
import org.signal.chat.common.AccountIdentifiers;
@@ -94,8 +97,8 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
@Override
public DeleteAccountResponse deleteAccount(final DeleteAccountRequest request) {
accountsManager.delete(getAuthenticatedAccount(AuthenticationUtil.requireAuthenticatedPrimaryDevice()),
AccountsManager.DeletionReason.USER_REQUEST);
accountsManager.delete(AuthenticationUtil.requireAuthenticatedPrimaryDevice().accountIdentifier(),
AccountsManager.DeletionReason.USER_REQUEST);
return DeleteAccountResponse.getDefaultInstance();
}
@@ -107,7 +110,7 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
final SaltedTokenHash credentials =
SaltedTokenHash.generateFor(HexFormat.of().withLowerCase().formatHex(request.getRegistrationLock().toByteArray()));
accountsManager.update(getAuthenticatedAccount(AuthenticationUtil.requireAuthenticatedPrimaryDevice()),
accountsManager.update(AuthenticationUtil.requireAuthenticatedPrimaryDevice().accountIdentifier(),
account -> account.setRegistrationLock(credentials.hash(), credentials.salt()));
return SetRegistrationLockResponse.getDefaultInstance();
@@ -115,7 +118,7 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
@Override
public ClearRegistrationLockResponse clearRegistrationLock(final ClearRegistrationLockRequest request) {
accountsManager.update(getAuthenticatedAccount(AuthenticationUtil.requireAuthenticatedPrimaryDevice()),
accountsManager.update(AuthenticationUtil.requireAuthenticatedPrimaryDevice().accountIdentifier(),
account -> account.setRegistrationLock(null, null));
return ClearRegistrationLockResponse.getDefaultInstance();
@@ -139,11 +142,9 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
rateLimiters.getUsernameReserveLimiter().validate(authenticatedDevice.accountIdentifier());
final Account account = getAuthenticatedAccount();
try {
final AccountsManager.UsernameReservation usernameReservation =
accountsManager.reserveUsernameHash(account, usernameHashes);
accountsManager.reserveUsernameHash(authenticatedDevice.accountIdentifier(), usernameHashes);
return ReserveUsernameHashResponse.newBuilder()
.setUsernameHash(ByteString.copyFrom(usernameReservation.reservedUsernameHash()))
@@ -169,7 +170,7 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
rateLimiters.getUsernameSetLimiter().validate(authenticatedDevice.accountIdentifier());
try {
final Account updatedAccount = accountsManager.confirmReservedUsernameHash(getAuthenticatedAccount(),
final Account updatedAccount = accountsManager.confirmReservedUsernameHash(authenticatedDevice.accountIdentifier(),
request.getUsernameHash().toByteArray(),
request.getUsernameCiphertext().toByteArray());
@@ -193,7 +194,7 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
@Override
public DeleteUsernameHashResponse deleteUsernameHash(final DeleteUsernameHashRequest request) {
accountsManager.clearUsernameHash(getAuthenticatedAccount());
accountsManager.clearUsernameHash(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier());
return DeleteUsernameHashResponse.getDefaultInstance();
}
@@ -217,7 +218,8 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
? account.getUsernameLinkHandle()
: UUID.randomUUID();
accountsManager.update(account, a -> a.setUsernameLinkDetails(linkHandle, request.getUsernameCiphertext().toByteArray()));
accountsManager.update(account.getIdentifier(IdentityType.ACI),
a -> a.setUsernameLinkDetails(linkHandle, request.getUsernameCiphertext().toByteArray()));
return responseBuilder.setUsernameLinkHandle(UUIDUtil.toByteString(linkHandle)).build();
}
@@ -229,7 +231,7 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
rateLimiters.getUsernameLinkOperationLimiter().validate(authenticatedDevice.accountIdentifier());
accountsManager.update(getAuthenticatedAccount(), a -> a.setUsernameLinkDetails(null, null));
accountsManager.update(authenticatedDevice.accountIdentifier(), a -> a.setUsernameLinkDetails(null, null));
return DeleteUsernameLinkResponse.getDefaultInstance();
}
@@ -242,7 +244,7 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH, request.getUnidentifiedAccessKey().size()));
}
accountsManager.update(getAuthenticatedAccount(), account -> {
accountsManager.update(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier(), account -> {
account.setUnrestrictedUnidentifiedAccess(request.getAllowUnrestrictedUnidentifiedAccess());
account.setUnidentifiedAccessKey(request.getAllowUnrestrictedUnidentifiedAccess() ? null : request.getUnidentifiedAccessKey().toByteArray());
});
@@ -252,7 +254,7 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
@Override
public SetDiscoverableByPhoneNumberResponse setDiscoverableByPhoneNumber(final SetDiscoverableByPhoneNumberRequest request) {
accountsManager.update(getAuthenticatedAccount(),
accountsManager.update(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier(),
account -> account.setDiscoverableByPhoneNumber(request.getDiscoverableByPhoneNumber()));
return SetDiscoverableByPhoneNumberResponse.getDefaultInstance();
@@ -267,6 +269,24 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
return SetRegistrationRecoveryPasswordResponse.getDefaultInstance();
}
@Override
public SetZkCredentialKeyResponse setZkCredentialKey(final SetZkCredentialKeyRequest request) throws RateLimitExceededException {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
final Account authenticatedAccount = getAuthenticatedAccount();
final byte[] zkCredentialKey = request.getPublicKey().toByteArray();
if (Arrays.equals(authenticatedAccount.getZkCredentialKey(), zkCredentialKey)) {
return SetZkCredentialKeyResponse.getDefaultInstance();
}
rateLimiters.getSetZkCredentialKeyLimiter().validate(authenticatedDevice.accountIdentifier());
accountsManager.update(authenticatedDevice.accountIdentifier(), account -> account.setZkCredentialKey(zkCredentialKey));
return SetZkCredentialKeyResponse.getDefaultInstance();
}
private Account getAuthenticatedAccount() {
return getAuthenticatedAccount(AuthenticationUtil.requireAuthenticatedDevice());
}
@@ -11,7 +11,9 @@ import org.signal.chat.attachments.GetUploadFormRequest;
import org.signal.chat.attachments.GetUploadFormResponse;
import org.signal.chat.attachments.SimpleAttachmentsGrpc;
import org.signal.chat.common.UploadForm;
import org.signal.chat.errors.FailedPrecondition;
import org.whispersystems.textsecuregcm.attachments.AttachmentGenerator;
import org.whispersystems.textsecuregcm.attachments.AttachmentUtil;
import org.whispersystems.textsecuregcm.attachments.GcsAttachmentGenerator;
import org.whispersystems.textsecuregcm.attachments.TusAttachmentGenerator;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
@@ -20,12 +22,13 @@ import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.limits.RateLimiter;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.attachments.AttachmentUtil;
public class AttachmentsGrpcService extends SimpleAttachmentsGrpc.AttachmentsImplBase {
private final ExperimentEnrollmentManager experimentEnrollmentManager;
private final RateLimiter rateLimiter;
private final RateLimiter countRateLimiter;
private final RateLimiter bytesRateLimiter;
private final long maxUploadLength;
private final Map<Integer, AttachmentGenerator> attachmentGenerators;
private final SecureRandom secureRandom;
@@ -33,9 +36,12 @@ public class AttachmentsGrpcService extends SimpleAttachmentsGrpc.AttachmentsImp
final ExperimentEnrollmentManager experimentEnrollmentManager,
final RateLimiters rateLimiters,
final GcsAttachmentGenerator gcsAttachmentGenerator,
final TusAttachmentGenerator tusAttachmentGenerator) {
final TusAttachmentGenerator tusAttachmentGenerator,
final long maxUploadLength) {
this.experimentEnrollmentManager = experimentEnrollmentManager;
this.rateLimiter = rateLimiters.getAttachmentLimiter();
this.countRateLimiter = rateLimiters.getAttachmentLimiter();
this.bytesRateLimiter = rateLimiters.getAttachmentBytesLimiter();
this.maxUploadLength = maxUploadLength;
this.secureRandom = new SecureRandom();
this.attachmentGenerators = Map.of(
2, gcsAttachmentGenerator,
@@ -44,13 +50,29 @@ public class AttachmentsGrpcService extends SimpleAttachmentsGrpc.AttachmentsImp
@Override
public GetUploadFormResponse getUploadForm(final GetUploadFormRequest request) throws RateLimitExceededException {
if (request.getUploadLength() > maxUploadLength) {
return GetUploadFormResponse.newBuilder()
.setExceedsMaxUploadLength(FailedPrecondition.getDefaultInstance())
.build();
}
final AuthenticatedDevice auth = AuthenticationUtil.requireAuthenticatedDevice();
rateLimiter.validate(auth.accountIdentifier());
countRateLimiter.validate(auth.accountIdentifier());
try {
// Ideally we'd check these two rate limits transactionally and only update them if both permits were acquired.
// However, just undoing the first modification if the second one fails is close enough for our purposes
bytesRateLimiter.validate(auth.accountIdentifier(), request.getUploadLength());
} catch (RateLimitExceededException e) {
countRateLimiter.restorePermits(auth.accountIdentifier(), 1);
throw e;
}
final String key = AttachmentUtil.generateAttachmentKey(secureRandom);
final boolean useCdn3 = this.experimentEnrollmentManager.isEnrolled(auth.accountIdentifier(),
AttachmentUtil.CDN3_EXPERIMENT_NAME);
final int cdn = useCdn3 ? 3 : 2;
final AttachmentGenerator.Descriptor descriptor = this.attachmentGenerators.get(cdn).generateAttachment(key);
final AttachmentGenerator.Descriptor descriptor =
this.attachmentGenerators.get(cdn).generateAttachment(key, request.getUploadLength());
return GetUploadFormResponse.newBuilder().setUploadForm(UploadForm.newBuilder()
.setCdn(cdn)
.setKey(key)
@@ -9,7 +9,7 @@ import io.grpc.Status;
import org.whispersystems.textsecuregcm.entities.AvatarChange;
public class AvatarChangeUtil {
public static AvatarChange fromGrpcAvatarChange(final org.signal.chat.profile.SetProfileRequest.AvatarChange avatarChangeType) {
public static AvatarChange fromGrpcAvatarChange(final org.signal.chat.profile.SetProfileV1Request.AvatarChange avatarChangeType) {
return switch (avatarChangeType) {
case AVATAR_CHANGE_UNCHANGED -> AvatarChange.AVATAR_CHANGE_UNCHANGED;
case AVATAR_CHANGE_CLEAR -> AvatarChange.AVATAR_CHANGE_CLEAR;
@@ -32,6 +32,7 @@ import org.signal.chat.backup.SetPublicKeyRequest;
import org.signal.chat.backup.SetPublicKeyResponse;
import org.signal.chat.backup.SignedPresentation;
import org.signal.chat.backup.SimpleBackupsAnonymousGrpc;
import org.signal.chat.common.UploadForm;
import org.signal.chat.errors.FailedPrecondition;
import org.signal.chat.errors.FailedZkAuthentication;
import org.signal.libsignal.protocol.InvalidKeyException;
@@ -60,10 +61,14 @@ public class BackupsAnonymousGrpcService extends SimpleBackupsAnonymousGrpc.Back
private final BackupManager backupManager;
private final BackupMetrics backupMetrics;
private final long maxAttachmentSize;
private final long maxMessageBackupSize;
public BackupsAnonymousGrpcService(final BackupManager backupManager, final BackupMetrics backupMetrics) {
public BackupsAnonymousGrpcService(final BackupManager backupManager, final BackupMetrics backupMetrics, final long maxAttachmentSize, final long maxMessageBackupSize) {
this.backupManager = backupManager;
this.backupMetrics = backupMetrics;
this.maxAttachmentSize = maxAttachmentSize;
this.maxMessageBackupSize = maxMessageBackupSize;
}
@Override
@@ -154,16 +159,19 @@ public class BackupsAnonymousGrpcService extends SimpleBackupsAnonymousGrpc.Back
}
@Override
public SetPublicKeyResponse setPublicKey(final SetPublicKeyRequest request)
throws BackupFailedZkAuthenticationException {
public SetPublicKeyResponse setPublicKey(final SetPublicKeyRequest request) {
final ECPublicKey publicKey = deserialize(ECPublicKey::new, request.getPublicKey().toByteArray());
final BackupAuthCredentialPresentation presentation = deserialize(
BackupAuthCredentialPresentation::new,
request.getSignedPresentation().getPresentation().toByteArray());
final byte[] signature = request.getSignedPresentation().getPresentationSignature().toByteArray();
backupManager.setPublicKey(presentation, signature, publicKey);
return SetPublicKeyResponse.newBuilder().setSuccess(Empty.getDefaultInstance()).build();
try {
backupManager.setPublicKey(presentation, signature, publicKey);
return SetPublicKeyResponse.newBuilder().setSuccess(Empty.getDefaultInstance()).build();
} catch (BackupFailedZkAuthenticationException e) {
return SetPublicKeyResponse.newBuilder().setFailedAuthentication(FailedZkAuthentication.getDefaultInstance()).build();
}
}
@@ -178,35 +186,32 @@ public class BackupsAnonymousGrpcService extends SimpleBackupsAnonymousGrpc.Back
.setFailedAuthentication(FailedZkAuthentication.newBuilder().setDescription(e.getMessage()).build())
.build();
}
final GetUploadFormResponse.Builder builder = GetUploadFormResponse.newBuilder();
switch (request.getUploadTypeCase()) {
final long uploadLength = request.getUploadLength();
final boolean oversize = switch (request.getUploadTypeCase()) {
case MEDIA -> uploadLength > maxAttachmentSize;
case MESSAGES -> {
final long uploadLength = request.getMessages().getUploadLength();
final boolean oversize = uploadLength > backupManager.maxMessageBackupUploadSize();
backupMetrics.updateMessageBackupSizeDistribution(backupUser, oversize, Optional.of(uploadLength));
if (oversize) {
builder.setExceedsMaxUploadLength(FailedPrecondition.getDefaultInstance());
} else {
final BackupUploadDescriptor uploadDescriptor = backupManager.createMessageBackupUploadDescriptor(backupUser);
builder.setUploadForm(builder.getUploadFormBuilder()
.setCdn(uploadDescriptor.cdn())
.setKey(uploadDescriptor.key())
.setSignedUploadLocation(uploadDescriptor.signedUploadLocation())
.putAllHeaders(uploadDescriptor.headers())).build();
}
backupMetrics.updateMessageBackupSizeDistribution(backupUser, uploadLength > maxMessageBackupSize, Optional.of(uploadLength));
yield uploadLength > maxMessageBackupSize;
}
case MEDIA -> {
final BackupUploadDescriptor uploadDescriptor = backupManager.createTemporaryAttachmentUploadDescriptor(
backupUser);
builder.setUploadForm(builder.getUploadFormBuilder()
case UPLOADTYPE_NOT_SET -> throw GrpcExceptions.fieldViolation("upload_type", "Must set upload_type");
};
if (oversize) {
return GetUploadFormResponse.newBuilder().setExceedsMaxUploadLength(FailedPrecondition.getDefaultInstance()).build();
}
final BackupUploadDescriptor uploadDescriptor = switch (request.getUploadTypeCase()) {
case MESSAGES -> backupManager.createMessageBackupUploadDescriptor(backupUser, uploadLength);
case MEDIA -> backupManager.createTemporaryAttachmentUploadDescriptor(backupUser, uploadLength);
case UPLOADTYPE_NOT_SET -> throw GrpcExceptions.fieldViolation("upload_type", "Must set upload_type");
};
return GetUploadFormResponse.newBuilder()
.setUploadForm(UploadForm.newBuilder()
.setCdn(uploadDescriptor.cdn())
.setKey(uploadDescriptor.key())
.setSignedUploadLocation(uploadDescriptor.signedUploadLocation())
.putAllHeaders(uploadDescriptor.headers())).build();
}
case UPLOADTYPE_NOT_SET -> throw GrpcExceptions.fieldViolation("upload_type", "Must set upload_type");
}
return builder.build();
.putAllHeaders(uploadDescriptor.headers()))
.build();
}
@Override
@@ -221,7 +226,7 @@ public class BackupsAnonymousGrpcService extends SimpleBackupsAnonymousGrpc.Back
// uint32 in proto, make sure it fits in a signed int
fromUnsignedExact(item.getObjectLength()),
new MediaEncryptionParameters(item.getEncryptionKey().toByteArray(), item.getHmacKey().toByteArray()),
item.getMediaId().toByteArray())).toList());
item.getMediaId().toByteArray())).toList(), maxAttachmentSize);
} catch (BackupFailedZkAuthenticationException e) {
return JdkFlowAdapter.publisherToFlowPublisher(Mono.just(CopyMediaResponse
.newBuilder()
@@ -18,6 +18,7 @@ public class DeviceCapabilityUtil {
case DEVICE_CAPABILITY_TRANSFER -> DeviceCapability.TRANSFER;
case DEVICE_CAPABILITY_ATTACHMENT_BACKFILL -> DeviceCapability.ATTACHMENT_BACKFILL;
case DEVICE_CAPABILITY_SPARSE_POST_QUANTUM_RATCHET -> DeviceCapability.SPARSE_POST_QUANTUM_RATCHET;
case DEVICE_CAPABILITY_PROFILES_V2 -> DeviceCapability.PROFILES_V2;
case DEVICE_CAPABILITY_UNSPECIFIED, UNRECOGNIZED ->
throw GrpcExceptions.invalidArguments("unrecognized device capability");
};
@@ -29,6 +30,7 @@ public class DeviceCapabilityUtil {
case TRANSFER -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_TRANSFER;
case ATTACHMENT_BACKFILL -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_ATTACHMENT_BACKFILL;
case SPARSE_POST_QUANTUM_RATCHET -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_SPARSE_POST_QUANTUM_RATCHET;
case PROFILES_V2 -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_PROFILES_V2;
};
}
}
@@ -80,9 +80,7 @@ public class DevicesGrpcService extends SimpleDevicesGrpc.DevicesImplBase {
throw GrpcExceptions.badAuthentication("linked devices cannot remove devices other than themselves");
}
final byte deviceId = DeviceIdUtil.validate(request.getId());
accountsManager.removeDevice(getAuthenticatedAccount(), deviceId);
accountsManager.removeDevice(authenticatedDevice.accountIdentifier(), DeviceIdUtil.validate(request.getId()));
return RemoveDeviceResponse.getDefaultInstance();
}
@@ -106,7 +104,7 @@ public class DevicesGrpcService extends SimpleDevicesGrpc.DevicesImplBase {
return SetDeviceNameResponse.newBuilder().setTargetDeviceNotFound(NotFound.getDefaultInstance()).build();
}
accountsManager.updateDevice(account, deviceId, device -> device.setName(request.getName().toByteArray()));
accountsManager.updateDevice(account.getIdentifier(IdentityType.ACI), deviceId, device -> device.setName(request.getName().toByteArray()));
return SetDeviceNameResponse.newBuilder().setSuccess(Empty.getDefaultInstance()).build();
}
@@ -141,7 +139,7 @@ public class DevicesGrpcService extends SimpleDevicesGrpc.DevicesImplBase {
.orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials"));
if (!Objects.equals(device.getApnId(), apnsToken) || !Objects.equals(device.getGcmId(), fcmToken)) {
accountsManager.updateDevice(account, authenticatedDevice.deviceId(), d -> {
accountsManager.updateDevice(account.getIdentifier(IdentityType.ACI), authenticatedDevice.deviceId(), d -> {
d.setApnId(apnsToken);
d.setGcmId(fcmToken);
d.setFetchesMessages(false);
@@ -154,9 +152,8 @@ public class DevicesGrpcService extends SimpleDevicesGrpc.DevicesImplBase {
@Override
public ClearPushTokenResponse clearPushToken(final ClearPushTokenRequest request) {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
final Account account = getAuthenticatedAccount();
accountsManager.updateDevice(account, authenticatedDevice.deviceId(), device -> {
accountsManager.updateDevice(authenticatedDevice.accountIdentifier(), authenticatedDevice.deviceId(), device -> {
if (StringUtils.isNotBlank(device.getApnId())) {
device.setUserAgent(device.isPrimary() ? "OWI" : "OWP");
} else if (StringUtils.isNotBlank(device.getGcmId())) {
@@ -179,7 +176,7 @@ public class DevicesGrpcService extends SimpleDevicesGrpc.DevicesImplBase {
.map(DeviceCapabilityUtil::fromGrpcDeviceCapability)
.collect(Collectors.toSet());
accountsManager.updateDevice(getAuthenticatedAccount(), authenticatedDevice.deviceId(),
accountsManager.updateDevice(authenticatedDevice.accountIdentifier(), authenticatedDevice.deviceId(),
device -> device.setCapabilities(capabilities));
return SetCapabilitiesResponse.getDefaultInstance();
@@ -158,6 +158,10 @@ public class GrpcExceptions {
return StatusProto.toStatusRuntimeException(builder.build());
}
public static StatusRuntimeException unavailable() {
return unavailable(null);
}
/// There was an internal error processing the RPC. The client should retry the request with exponential backoff.
///
/// @return A [StatusRuntimeException] encoding the error
@@ -7,6 +7,7 @@ package org.whispersystems.textsecuregcm.grpc;
import io.grpc.StatusRuntimeException;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.function.BiFunction;
@@ -31,6 +32,7 @@ import org.signal.libsignal.protocol.kem.KEMPublicKey;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.controllers.RateLimitKeys;
import org.whispersystems.textsecuregcm.entities.ECPreKey;
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
@@ -96,18 +98,28 @@ public class KeysGrpcService extends SimpleKeysGrpc.KeysImplBase {
final ServiceIdentifier targetIdentifier =
ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getTargetIdentifier());
final Optional<Account> maybeTargetAccount = accountsManager.getByServiceIdentifier(targetIdentifier);
final byte deviceId = request.hasDeviceId()
? DeviceIdUtil.validate(request.getDeviceId())
: KeysGrpcHelper.ALL_DEVICES;
final String rateLimitKey = authenticatedDevice.accountIdentifier() + "." +
authenticatedDevice.deviceId() + "__" +
targetIdentifier.uuid() + "." +
deviceId;
final Optional<Integer> targetRegistrationId = maybeTargetAccount
.filter(_ -> request.hasDeviceId())
.flatMap(targetAccount -> targetAccount.getDevice(deviceId))
.map(device -> device.getRegistrationId(targetIdentifier.identityType()));
final String rateLimitKey = RateLimitKeys.preKeyLimiterKey(
authenticatedDevice.accountIdentifier(),
authenticatedDevice.deviceId(),
targetIdentifier,
Optional.ofNullable(request.hasDeviceId() ? deviceId : null),
targetRegistrationId);
rateLimiters.getPreKeysLimiter().validate(rateLimitKey);
return accountsManager.getByServiceIdentifier(targetIdentifier)
return maybeTargetAccount
.flatMap(targetAccount -> KeysGrpcHelper.getPreKeys(targetAccount, targetIdentifier, deviceId, keysManager))
.map(accountPreKeyBundles -> GetPreKeysResponse.newBuilder()
.setPreKeys(accountPreKeyBundles)
@@ -11,6 +11,7 @@ import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import com.google.protobuf.Empty;
import io.grpc.Status;
import org.signal.chat.errors.FailedUnidentifiedAuthorization;
import org.signal.chat.errors.NotFound;
import org.signal.chat.messages.IndividualRecipientMessageBundle;
@@ -28,6 +29,7 @@ import org.signal.libsignal.protocol.InvalidMessageException;
import org.signal.libsignal.protocol.InvalidVersionException;
import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
import org.whispersystems.textsecuregcm.controllers.MessageDeliveryNotAllowedException;
import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
import org.whispersystems.textsecuregcm.controllers.MultiRecipientMismatchedDevicesException;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
@@ -229,6 +231,8 @@ public class MessagesAnonymousGrpcService extends SimpleMessagesAnonymousGrpc.Me
.build();
} catch (final MessageTooLargeException e) {
throw GrpcExceptions.invalidArguments("message too large");
} catch (final MessageDeliveryNotAllowedException e) {
throw GrpcExceptions.unavailable();
}
}
@@ -295,14 +299,16 @@ public class MessagesAnonymousGrpcService extends SimpleMessagesAnonymousGrpc.Me
MessageUtil.resolveRecipients(accountsManager, multiRecipientMessage);
try {
messageSender.sendMultiRecipientMessage(multiRecipientMessage,
resolvedRecipients,
timestamp,
story,
ephemeral,
urgent,
RequestAttributesUtil.getUserAgent().orElse(null))
.join();
if (!resolvedRecipients.isEmpty()) {
messageSender.sendMultiRecipientMessage(multiRecipientMessage,
resolvedRecipients,
timestamp,
story,
ephemeral,
urgent,
RequestAttributesUtil.getUserAgent().orElse(null))
.join();
}
final MultiRecipientSuccess.Builder responseBuilder = MultiRecipientSuccess.newBuilder();
@@ -323,6 +329,8 @@ public class MessagesAnonymousGrpcService extends SimpleMessagesAnonymousGrpc.Me
return SendMultiRecipientMessageResponse.newBuilder()
.setMismatchedDevices(mismatchedDevicesBuilder)
.build();
} catch (final MessageDeliveryNotAllowedException e) {
throw GrpcExceptions.unavailable();
}
}
@@ -5,21 +5,24 @@
package org.whispersystems.textsecuregcm.grpc;
import static org.whispersystems.textsecuregcm.grpc.MessagesGrpcHelper.buildMismatchedDevices;
import com.google.protobuf.ByteString;
import com.google.protobuf.Empty;
import java.time.Clock;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import com.google.protobuf.Empty;
import org.signal.chat.errors.NotFound;
import org.signal.chat.messages.SendMessageType;
import org.signal.chat.messages.IndividualRecipientMessageBundle;
import org.signal.chat.messages.SendAuthenticatedSenderMessageRequest;
import org.signal.chat.messages.SendMessageAuthenticatedSenderResponse;
import org.signal.chat.messages.SendMessageType;
import org.signal.chat.messages.SendSyncMessageRequest;
import org.signal.chat.messages.SimpleMessagesGrpc;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
import org.whispersystems.textsecuregcm.controllers.MessageDeliveryNotAllowedException;
import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
@@ -36,8 +39,6 @@ import org.whispersystems.textsecuregcm.spam.SpamChecker;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import static org.whispersystems.textsecuregcm.grpc.MessagesGrpcHelper.buildMismatchedDevices;
public class MessagesGrpcService extends SimpleMessagesGrpc.MessagesImplBase {
private final AccountsManager accountsManager;
@@ -192,6 +193,8 @@ public class MessagesGrpcService extends SimpleMessagesGrpc.MessagesImplBase {
.build();
} catch (final MessageTooLargeException e) {
throw GrpcExceptions.invalidArguments("message too large");
} catch (final MessageDeliveryNotAllowedException e) {
throw GrpcExceptions.unavailable();
}
}
@@ -7,6 +7,7 @@ package org.whispersystems.textsecuregcm.grpc;
import com.google.common.annotations.VisibleForTesting;
import com.google.protobuf.Descriptors;
import com.google.protobuf.GeneratedMessage;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.Message;
import com.google.rpc.ErrorInfo;
@@ -26,6 +27,7 @@ import io.micrometer.core.instrument.Timer;
import java.io.UncheckedIOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import javax.annotation.Nullable;
@@ -46,15 +48,19 @@ public class MetricServerInterceptor implements ServerInterceptor {
private static final String TAG_REASON = "reason";
@VisibleForTesting
static final String DEFAULT_SUCCESS_REASON = "success";
static final String DEFAULT_SUCCESS_REASON = "SUCCESS";
@VisibleForTesting
static final String DEFAULT_ERROR_REASON = "n/a";
static final String DEFAULT_ERROR_REASON = "N/A";
@VisibleForTesting
static final String REQUEST_MESSAGE_COUNTER_NAME = MetricsUtil.name(MetricServerInterceptor.class, "requestMessage");
@VisibleForTesting
static final String REQUEST_BYTES_COUNTER_NAME = MetricsUtil.name(MetricServerInterceptor.class, "requestBytes");
@VisibleForTesting
static final String RESPONSE_COUNTER_NAME = MetricsUtil.name(MetricServerInterceptor.class, "responseMessage");
@VisibleForTesting
static final String RESPONSE_BYTES_COUNTER_NAME = MetricsUtil.name(MetricServerInterceptor.class, "responseBytes");
@VisibleForTesting
static final String RPC_COUNTER_NAME = MetricsUtil.name(MetricServerInterceptor.class, "rpc");
@VisibleForTesting
static final String DURATION_TIMER_NAME = MetricsUtil.name(MetricServerInterceptor.class, "processingDuration");
@@ -99,12 +105,14 @@ public class MetricServerInterceptor implements ServerInterceptor {
private class MetricServerCall<ReqT, RespT> extends ForwardingServerCall.SimpleForwardingServerCall<ReqT, RespT> {
private final Counter responseMessageCounter;
private final Counter responseBytesCounter;
private final Tags tags;
private @Nullable String reason = null;
MetricServerCall(final ServerCall<ReqT, RespT> delegate, final Tags tags) {
super(delegate);
this.responseMessageCounter = meterRegistry.counter(RESPONSE_COUNTER_NAME, tags);
this.responseBytesCounter = meterRegistry.counter(RESPONSE_BYTES_COUNTER_NAME, tags);
this.tags = tags;
}
@@ -117,7 +125,7 @@ public class MetricServerInterceptor implements ServerInterceptor {
}
Tags responseTags = tags.and(Tag.of(TAG_STATUS_CODE, status.getCode().name()));
if (reason != null) {
responseTags = responseTags.and(TAG_REASON, reason);
responseTags = responseTags.and(TAG_REASON, reason.toUpperCase(Locale.ROOT));
}
meterRegistry.counter(RPC_COUNTER_NAME, responseTags).increment();
super.close(status, responseHeaders);
@@ -126,6 +134,11 @@ public class MetricServerInterceptor implements ServerInterceptor {
@Override
public void sendMessage(final RespT responseMessage) {
this.responseMessageCounter.increment();
if (responseMessage instanceof GeneratedMessage generatedMessage) {
this.responseBytesCounter.increment(generatedMessage.getSerializedSize());
}
// Extract the annotated reason (if any) from the message
final String messageReason = MetricServerCall.reason(responseMessage);
@@ -171,12 +184,14 @@ public class MetricServerInterceptor implements ServerInterceptor {
private class MetricServerCallListener<ReqT> extends ForwardingServerCallListener.SimpleForwardingServerCallListener<ReqT> {
private final Counter requestCounter;
private final Counter requestBytesCounter;
private final Timer responseTimer;
private final Timer.Sample sample;
MetricServerCallListener(final ServerCall.Listener<ReqT> delegate, final Tags tags) {
super(delegate);
this.requestCounter = meterRegistry.counter(REQUEST_MESSAGE_COUNTER_NAME, tags);
this.requestBytesCounter = meterRegistry.counter(REQUEST_BYTES_COUNTER_NAME, tags);
this.responseTimer = meterRegistry.timer(DURATION_TIMER_NAME, tags);
this.sample = Timer.start(meterRegistry);
}
@@ -184,6 +199,11 @@ public class MetricServerInterceptor implements ServerInterceptor {
@Override
public void onMessage(final ReqT requestMessage) {
this.requestCounter.increment();
if (requestMessage instanceof GeneratedMessage generatedMessage) {
this.requestBytesCounter.increment(generatedMessage.getSerializedSize());
}
super.onMessage(requestMessage);
}
@@ -5,16 +5,18 @@
package org.whispersystems.textsecuregcm.grpc;
import io.grpc.Status;
import io.grpc.StatusException;
import java.time.Clock;
import java.util.Optional;
import com.google.common.annotations.VisibleForTesting;
import org.signal.chat.errors.FailedUnidentifiedAuthorization;
import org.signal.chat.errors.NotFound;
import org.signal.chat.profile.CredentialType;
import org.signal.chat.profile.GetExpiringProfileKeyCredentialAnonymousRequest;
import org.signal.chat.profile.GetExpiringProfileKeyCredentialResponse;
import org.signal.chat.profile.GetExpiringProfileKeyCredentialAnonymousResponse;
import org.signal.chat.profile.GetUnversionedProfileAnonymousRequest;
import org.signal.chat.profile.GetUnversionedProfileResponse;
import org.signal.chat.profile.GetUnversionedProfileAnonymousResponse;
import org.signal.chat.profile.GetVersionedProfileAnonymousRequest;
import org.signal.chat.profile.GetVersionedProfileResponse;
import org.signal.chat.profile.GetVersionedProfileAnonymousResponse;
import org.signal.chat.profile.SimpleProfileAnonymousGrpc;
import org.signal.libsignal.zkgroup.ServerSecretParams;
import org.signal.libsignal.zkgroup.profiles.ServerZkProfileOperations;
@@ -38,77 +40,116 @@ public class ProfileAnonymousGrpcService extends SimpleProfileAnonymousGrpc.Prof
final ProfilesManager profilesManager,
final ProfileBadgeConverter profileBadgeConverter,
final ServerSecretParams serverSecretParams) {
this(accountsManager,
profilesManager,
profileBadgeConverter,
new ServerZkProfileOperations(serverSecretParams),
new GroupSendTokenUtil(serverSecretParams, Clock.systemUTC()));
}
@VisibleForTesting
ProfileAnonymousGrpcService(final AccountsManager accountsManager,
final ProfilesManager profilesManager,
final ProfileBadgeConverter profileBadgeConverter,
final ServerZkProfileOperations zkProfileOperations,
final GroupSendTokenUtil groupSendTokenUtil) {
this.accountsManager = accountsManager;
this.profilesManager = profilesManager;
this.profileBadgeConverter = profileBadgeConverter;
this.zkProfileOperations = new ServerZkProfileOperations(serverSecretParams);
this.groupSendTokenUtil = new GroupSendTokenUtil(serverSecretParams, Clock.systemUTC());
this.zkProfileOperations = zkProfileOperations;
this.groupSendTokenUtil = groupSendTokenUtil;
}
@Override
public GetUnversionedProfileResponse getUnversionedProfile(final GetUnversionedProfileAnonymousRequest request) throws StatusException {
public GetUnversionedProfileAnonymousResponse getUnversionedProfile(final GetUnversionedProfileAnonymousRequest request) {
final ServiceIdentifier targetIdentifier =
ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getRequest().getServiceIdentifier());
// Callers must be authenticated to request unversioned profiles by PNI
if (targetIdentifier.identityType() == IdentityType.PNI) {
throw Status.UNAUTHENTICATED.asException();
throw GrpcExceptions.invalidArguments("aci service identifier type required");
}
final Account account = switch (request.getAuthenticationCase()) {
case GROUP_SEND_TOKEN -> {
if (!groupSendTokenUtil.checkGroupSendToken(request.getGroupSendToken(), targetIdentifier)) {
throw Status.UNAUTHENTICATED.asException();
}
yield accountsManager.getByServiceIdentifier(targetIdentifier)
.orElseThrow(Status.NOT_FOUND::asException);
}
final Optional<Account> targetAccount = accountsManager.getByServiceIdentifier(targetIdentifier);
final boolean authorized = switch (request.getAuthenticationCase()) {
case GROUP_SEND_TOKEN -> groupSendTokenUtil.checkGroupSendToken(request.getGroupSendToken(), targetIdentifier);
case UNIDENTIFIED_ACCESS_KEY ->
getTargetAccountAndValidateUnidentifiedAccess(targetIdentifier, request.getUnidentifiedAccessKey().toByteArray());
default -> throw Status.INVALID_ARGUMENT.asException();
targetAccount.map(a -> UnidentifiedAccessUtil.checkUnidentifiedAccess(a, request.getUnidentifiedAccessKey().toByteArray()))
.orElse(false);
default -> throw GrpcExceptions.constraintViolation("invalid authentication");
};
return ProfileGrpcHelper.buildUnversionedProfileResponse(targetIdentifier,
null,
account,
profileBadgeConverter);
if (!authorized) {
return GetUnversionedProfileAnonymousResponse.newBuilder()
.setFailedUnidentifiedAuthorization(FailedUnidentifiedAuthorization.getDefaultInstance())
.build();
}
return targetAccount.map(account ->
GetUnversionedProfileAnonymousResponse.newBuilder()
.setResult(ProfileGrpcHelper.buildUnversionedProfileResult(targetIdentifier,
null,
account,
profileBadgeConverter))
.build())
.orElseGet(() -> GetUnversionedProfileAnonymousResponse.newBuilder()
.setNotFound(NotFound.getDefaultInstance())
.build());
}
@Override
public GetVersionedProfileResponse getVersionedProfile(final GetVersionedProfileAnonymousRequest request) throws StatusException {
public GetVersionedProfileAnonymousResponse getVersionedProfile(final GetVersionedProfileAnonymousRequest request) {
final ServiceIdentifier targetIdentifier = ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getRequest().getAccountIdentifier());
if (targetIdentifier.identityType() != IdentityType.ACI) {
throw Status.INVALID_ARGUMENT.withDescription("Expected ACI service identifier").asException();
}
final Optional<Account> targetAccount = getTargetAccountAndValidateUnidentifiedAccess(targetIdentifier, request.getUnidentifiedAccessKey().toByteArray());
final Account targetAccount = getTargetAccountAndValidateUnidentifiedAccess(targetIdentifier, request.getUnidentifiedAccessKey().toByteArray());
return ProfileGrpcHelper.getVersionedProfile(targetAccount, profilesManager, request.getRequest().getVersion());
return targetAccount.flatMap(account ->
ProfileGrpcHelper.getVersionedProfile(account,
profilesManager,
request.getRequest().getVersion().toByteArray(),
request.getRequest().getDataEtag().toByteArray(),
request.getRequest().getPaymentAddressEtag().toByteArray()))
.map(result ->
GetVersionedProfileAnonymousResponse.newBuilder()
.setResult(result)
.build())
.orElseGet(() ->
GetVersionedProfileAnonymousResponse.newBuilder()
.setNotFound(NotFound.getDefaultInstance())
.build());
}
@Override
public GetExpiringProfileKeyCredentialResponse getExpiringProfileKeyCredential(
final GetExpiringProfileKeyCredentialAnonymousRequest request) throws StatusException {
public GetExpiringProfileKeyCredentialAnonymousResponse getExpiringProfileKeyCredential(
final GetExpiringProfileKeyCredentialAnonymousRequest request) {
final ServiceIdentifier targetIdentifier = ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getRequest().getAccountIdentifier());
if (targetIdentifier.identityType() != IdentityType.ACI) {
throw Status.INVALID_ARGUMENT.withDescription("Expected ACI service identifier").asException();
}
if (request.getRequest().getCredentialType() != CredentialType.CREDENTIAL_TYPE_EXPIRING_PROFILE_KEY) {
throw Status.INVALID_ARGUMENT.withDescription("Expected expiring profile key credential type").asException();
throw GrpcExceptions.constraintViolation("invalid credential type");
}
final Account account = getTargetAccountAndValidateUnidentifiedAccess(
final Optional<Account> maybeAccount = getTargetAccountAndValidateUnidentifiedAccess(
targetIdentifier, request.getUnidentifiedAccessKey().toByteArray());
return ProfileGrpcHelper.getExpiringProfileKeyCredentialResponse(account.getUuid(),
request.getRequest().getVersion(), request.getRequest().getCredentialRequest().toByteArray(), profilesManager, zkProfileOperations);
return maybeAccount.map(account ->
ProfileGrpcHelper.getExpiringProfileKeyCredentialResult(account,
request.getRequest().getVersion().toByteArray(), request.getRequest().getCredentialRequest().toByteArray(),
profilesManager, zkProfileOperations)
.map(result -> GetExpiringProfileKeyCredentialAnonymousResponse.newBuilder()
.setResult(result)
.build())
.orElseGet(() -> GetExpiringProfileKeyCredentialAnonymousResponse.newBuilder()
.setNotFound(NotFound.getDefaultInstance())
.build())).orElseGet(() -> GetExpiringProfileKeyCredentialAnonymousResponse.newBuilder()
.setNotFound(NotFound.getDefaultInstance())
.build());
}
private Account getTargetAccountAndValidateUnidentifiedAccess(final ServiceIdentifier targetIdentifier, final byte[] unidentifiedAccessKey) throws StatusException {
private Optional<Account> getTargetAccountAndValidateUnidentifiedAccess(final ServiceIdentifier targetIdentifier, final byte[] unidentifiedAccessKey) {
return accountsManager.getByServiceIdentifier(targetIdentifier)
.filter(targetAccount -> UnidentifiedAccessUtil.checkUnidentifiedAccess(targetAccount, unidentifiedAccessKey))
.orElseThrow(Status.UNAUTHENTICATED::asException);
.filter(targetAccount -> UnidentifiedAccessUtil.checkUnidentifiedAccess(targetAccount, unidentifiedAccessKey));
}
}
@@ -7,21 +7,27 @@ package org.whispersystems.textsecuregcm.grpc;
import com.google.common.annotations.VisibleForTesting;
import com.google.protobuf.ByteString;
import io.grpc.Status;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HexFormat;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import io.grpc.StatusException;
import org.signal.chat.profile.Badge;
import org.signal.chat.profile.BadgeSvg;
import org.signal.chat.profile.GetExpiringProfileKeyCredentialResponse;
import org.signal.chat.profile.GetUnversionedProfileResponse;
import org.signal.chat.profile.GetVersionedProfileResponse;
import org.signal.chat.profile.DataEtag;
import org.signal.chat.profile.GetExpiringProfileKeyCredentialResult;
import org.signal.chat.profile.GetUnversionedProfileResult;
import org.signal.chat.profile.GetVersionedProfileResult;
import org.signal.chat.profile.GetVersionedProfileV1Response;
import org.signal.libsignal.protocol.ServiceId;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.VerificationFailedException;
import org.signal.libsignal.zkgroup.profiles.ExpiringProfileKeyCredentialResponse;
import org.signal.libsignal.zkgroup.profiles.ProfileKeyCommitment;
import org.signal.libsignal.zkgroup.profiles.ProfileKeyCredentialRequest;
import org.signal.libsignal.zkgroup.profiles.ServerZkProfileOperations;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessChecksum;
import org.whispersystems.textsecuregcm.badges.ProfileBadgeConverter;
@@ -30,32 +36,88 @@ import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
import org.whispersystems.textsecuregcm.storage.VersionedProfile;
import org.whispersystems.textsecuregcm.storage.VersionedProfileV1;
import org.whispersystems.textsecuregcm.util.ProfileHelper;
public class ProfileGrpcHelper {
static GetVersionedProfileResponse getVersionedProfile(final Account account,
static Optional<GetVersionedProfileResult> getVersionedProfile(final Account account,
final ProfilesManager profilesManager,
final String requestVersion) throws StatusException {
final byte[] requestVersion,
final byte[] requestDataEtag,
final byte[] requestPaymentAddressEtag) {
final VersionedProfile profile = profilesManager.get(account.getUuid(), requestVersion)
.orElseThrow(Status.NOT_FOUND.withDescription("Profile version not found")::asException);
final GetVersionedProfileResponse.Builder responseBuilder = GetVersionedProfileResponse.newBuilder();
responseBuilder
.setName(ByteString.copyFrom(profile.name()))
.setAbout(ByteString.copyFrom(profile.about()))
.setAboutEmoji(ByteString.copyFrom(profile.aboutEmoji()))
.setAvatar(profile.avatar())
.setPhoneNumberSharing(ByteString.copyFrom(profile.phoneNumberSharing()));
// Allow requests where either the version matches the latest version on Account or the latest version on Account
// is empty to read the payment address.
if (account.getCurrentProfileVersion().map(v -> v.equals(requestVersion)).orElse(true)) {
responseBuilder.setPaymentAddress(ByteString.copyFrom(profile.paymentAddress()));
final Optional<VersionedProfile> profile;
if (account.hasCapability(DeviceCapability.PROFILES_V2)) {
profile = profilesManager.get(account.getUuid(), requestVersion);
} else {
profile = Optional.empty();
}
return responseBuilder.build();
final Optional<VersionedProfileV1> v1Profile;
if (profile.isEmpty()) {
v1Profile = profilesManager.getV1(account.getUuid(), HexFormat.of().formatHex(requestVersion));
} else {
v1Profile = Optional.empty();
}
if (profile.isEmpty() && v1Profile.isEmpty()) {
return Optional.empty();
}
final GetVersionedProfileResult.Builder responseBuilder = GetVersionedProfileResult.newBuilder();
profile.ifPresent(p -> {
if (requestDataEtag.length > 0 && Arrays.equals(requestDataEtag, p.dataHash())) {
responseBuilder.setDataEtagMatched(true);
} else {
responseBuilder.setDataEtag(DataEtag.newBuilder()
.setData(ByteString.copyFrom(p.data()))
.setEtag(ByteString.copyFrom(p.dataHash()))
.build());
}
});
v1Profile.ifPresent(p -> {
final GetVersionedProfileV1Response.Builder v1ResponseBuilder = GetVersionedProfileV1Response.newBuilder();
v1ResponseBuilder
.setName(ByteString.copyFrom(p.name()))
.setAbout(ByteString.copyFrom(p.about()))
.setAboutEmoji(ByteString.copyFrom(p.aboutEmoji()))
.setPhoneNumberSharing(ByteString.copyFrom(p.phoneNumberSharing()));
if (p.avatar() != null) {
v1ResponseBuilder.setAvatar(p.avatar());
}
responseBuilder.setV1Response(v1ResponseBuilder);
});
// Include payment address if the version matches the latest version on Account or the latest version on Account
// is empty
if (account.getCurrentProfileVersion().map(v -> v.equals(HexFormat.of().formatHex(requestVersion))).orElse(true)) {
final Optional<byte []> paymentAddress = profile.map(VersionedProfile::paymentAddress).or(() -> v1Profile.map(VersionedProfileV1::paymentAddress));
if (paymentAddress.isPresent()) {
final boolean paymentAddressETagMatches = requestPaymentAddressEtag.length > 0 &&
profile.map(VersionedProfile::paymentAddressHash)
.map(h -> Arrays.equals(requestPaymentAddressEtag, h))
.orElse(false);
if (paymentAddressETagMatches) {
responseBuilder.setPaymentAddressEtagMatched(true);
} else {
responseBuilder.setPaymentAddressDataEtag(DataEtag.newBuilder()
.setData(ByteString.copyFrom(paymentAddress.get()))
.setEtag(ByteString.copyFrom(
profile.map(VersionedProfile::paymentAddressHash).orElseGet(() -> hash(paymentAddress.get()))))
.build());
}
}
}
return Optional.of(responseBuilder.build());
}
@VisibleForTesting
@@ -95,54 +157,79 @@ public class ProfileGrpcHelper {
return grpcBadgeSvgs;
}
static GetUnversionedProfileResponse buildUnversionedProfileResponse(
static GetUnversionedProfileResult buildUnversionedProfileResult(
final ServiceIdentifier targetIdentifier,
final UUID requesterUuid,
final Account targetAccount,
final ProfileBadgeConverter profileBadgeConverter) {
final GetUnversionedProfileResponse.Builder responseBuilder = GetUnversionedProfileResponse.newBuilder()
final GetUnversionedProfileResult.Builder resultBuilder = GetUnversionedProfileResult.newBuilder()
.setIdentityKey(ByteString.copyFrom(targetAccount.getIdentityKey(targetIdentifier.identityType()).serialize()))
.addAllCapabilities(buildAccountCapabilities(targetAccount));
switch (targetIdentifier.identityType()) {
case ACI -> {
responseBuilder.setUnrestrictedUnidentifiedAccess(targetAccount.isUnrestrictedUnidentifiedAccess())
.addAllBadges(buildBadges(profileBadgeConverter.convert(
RequestAttributesUtil.getAvailableAcceptedLocales(),
resultBuilder.setUnrestrictedUnidentifiedAccess(targetAccount.isUnrestrictedUnidentifiedAccess())
.addAllBadges(
buildBadges(profileBadgeConverter.convert(RequestAttributesUtil.getAvailableAcceptedLocales(),
targetAccount.getBadges(),
ProfileHelper.isSelfProfileRequest(requesterUuid, targetIdentifier))));
targetAccount.getUnidentifiedAccessKey()
.map(UnidentifiedAccessChecksum::generateFor)
.map(ByteString::copyFrom)
.ifPresent(responseBuilder::setUnidentifiedAccess);
.ifPresent(resultBuilder::setUnidentifiedAccess);
}
case PNI -> responseBuilder.setUnrestrictedUnidentifiedAccess(false);
case PNI -> resultBuilder.setUnrestrictedUnidentifiedAccess(false);
}
return responseBuilder.build();
return resultBuilder.build();
}
static GetExpiringProfileKeyCredentialResponse getExpiringProfileKeyCredentialResponse(
final UUID targetUuid,
final String version,
static Optional<GetExpiringProfileKeyCredentialResult> getExpiringProfileKeyCredentialResult(
final Account account,
final byte[] version,
final byte[] encodedCredentialRequest,
final ProfilesManager profilesManager,
final ServerZkProfileOperations zkProfileOperations) throws StatusException {
final ServerZkProfileOperations zkProfileOperations) {
final VersionedProfile profile = profilesManager.get(targetUuid, version)
.orElseThrow(Status.NOT_FOUND.withDescription("Profile version not found")::asException);
final ExpiringProfileKeyCredentialResponse profileKeyCredentialResponse;
try {
profileKeyCredentialResponse = ProfileHelper.getExpiringProfileKeyCredential(encodedCredentialRequest,
profile, new ServiceId.Aci(targetUuid), zkProfileOperations);
} catch (VerificationFailedException | InvalidInputException e) {
throw Status.INVALID_ARGUMENT.withCause(e).asException();
final Optional<VersionedProfile> versionedProfile;
if (account.hasCapability(DeviceCapability.PROFILES_V2)) {
versionedProfile = profilesManager.get(account.getUuid(), version);
} else {
versionedProfile = Optional.empty();
}
return GetExpiringProfileKeyCredentialResponse.newBuilder()
.setProfileKeyCredential(ByteString.copyFrom(profileKeyCredentialResponse.serialize()))
.build();
return versionedProfile.map(VersionedProfile::commitment)
.or(() -> profilesManager.getV1(account.getUuid(), HexFormat.of().formatHex(version)).map(VersionedProfileV1::commitment))
.map(commitment -> {
final ExpiringProfileKeyCredentialResponse profileKeyCredentialResponse;
try {
profileKeyCredentialResponse = ProfileHelper.getExpiringProfileKeyCredential(new ProfileKeyCredentialRequest(encodedCredentialRequest),
new ProfileKeyCommitment(commitment), new ServiceId.Aci(account.getUuid()), zkProfileOperations);
} catch (VerificationFailedException | InvalidInputException e) {
throw GrpcExceptions.constraintViolation("invalid credential request");
}
return GetExpiringProfileKeyCredentialResult.newBuilder()
.setProfileKeyCredential(ByteString.copyFrom(profileKeyCredentialResponse.serialize()))
.build();
});
}
/**
* Computes the SHA-256 hash of the given data.
* <p>
* Only needed during the v1 -> v2 migration. See also: VersionedProfile#hash(byte[])
*/
@VisibleForTesting
public static byte[] hash(final byte[] data) {
final MessageDigest sha256;
try {
sha256 = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
throw new AssertionError(e);
}
return sha256.digest(data);
}
}
@@ -6,29 +6,29 @@
package org.whispersystems.textsecuregcm.grpc;
import com.google.protobuf.ByteString;
import io.grpc.Status;
import java.time.Clock;
import java.time.ZonedDateTime;
import java.util.HexFormat;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.function.Function;
import java.util.stream.Collectors;
import io.grpc.StatusException;
import org.signal.chat.profile.CredentialType;
import org.signal.chat.profile.GetExpiringProfileKeyCredentialRequest;
import org.signal.chat.profile.GetExpiringProfileKeyCredentialResponse;
import org.signal.chat.errors.FailedPrecondition;
import org.signal.chat.errors.NotFound;
import org.signal.chat.profile.GetUnversionedProfileRequest;
import org.signal.chat.profile.GetUnversionedProfileResponse;
import org.signal.chat.profile.GetVersionedProfileRequest;
import org.signal.chat.profile.GetVersionedProfileResponse;
import org.signal.chat.profile.PaymentsForbiddenInRegion;
import org.signal.chat.profile.ProfileAvatarUploadAttributes;
import org.signal.chat.profile.ProfilesV2CapabilityRequired;
import org.signal.chat.profile.SetProfileRequest;
import org.signal.chat.profile.SetProfileRequest.AvatarChange;
import org.signal.chat.profile.SetProfileResponse;
import org.signal.chat.profile.SetProfileResult;
import org.signal.chat.profile.SetProfileV1Request.AvatarChange;
import org.signal.chat.profile.SimpleProfileGrpc;
import org.signal.libsignal.zkgroup.profiles.ServerZkProfileOperations;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
import org.whispersystems.textsecuregcm.badges.ProfileBadgeConverter;
@@ -44,9 +44,12 @@ import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountBadge;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
import org.whispersystems.textsecuregcm.storage.VersionedProfile;
import org.whispersystems.textsecuregcm.storage.VersionedProfileV1;
import org.whispersystems.textsecuregcm.storage.WriteConflictException;
import org.whispersystems.textsecuregcm.util.Pair;
import org.whispersystems.textsecuregcm.util.ProfileHelper;
@@ -61,7 +64,6 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
private final PolicySigner policySigner;
private final ProfileBadgeConverter profileBadgeConverter;
private final RateLimiters rateLimiters;
private final ServerZkProfileOperations zkProfileOperations;
private record AvatarData(Optional<String> currentAvatar,
Optional<String> finalAvatar,
@@ -76,8 +78,7 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
final PostPolicyGenerator policyGenerator,
final PolicySigner policySigner,
final ProfileBadgeConverter profileBadgeConverter,
final RateLimiters rateLimiters,
final ServerZkProfileOperations zkProfileOperations) {
final RateLimiters rateLimiters) {
this.clock = clock;
this.accountsManager = accountsManager;
this.profilesManager = profilesManager;
@@ -88,33 +89,52 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
this.policySigner = policySigner;
this.profileBadgeConverter = profileBadgeConverter;
this.rateLimiters = rateLimiters;
this.zkProfileOperations = zkProfileOperations;
}
@Override
public SetProfileResponse setProfile(final SetProfileRequest request) throws StatusException {
validateRequest(request);
public SetProfileResponse setProfile(final SetProfileRequest request) {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
final Account account = accountsManager.getByAccountIdentifier(
authenticatedDevice.accountIdentifier()).orElseThrow(Status.UNAUTHENTICATED::asException);
final Optional<VersionedProfile> maybeProfile = profilesManager.get(
authenticatedDevice.accountIdentifier(), request.getVersion());
final Account account = accountsManager.getByAccountIdentifier(authenticatedDevice.accountIdentifier())
.orElseThrow(() -> GrpcExceptions.invalidArguments("Account not found"));
if (!request.getPaymentAddress().isEmpty()) {
final boolean hasDisallowedPrefix =
dynamicConfigurationManager.getConfiguration().getPaymentsConfiguration().getDisallowedPrefixes().stream()
.anyMatch(prefix -> account.getNumber().startsWith(prefix));
if (hasDisallowedPrefix && maybeProfile.map(VersionedProfile::paymentAddress).isEmpty()) {
throw Status.PERMISSION_DENIED.asException();
}
if (!account.hasCapability(DeviceCapability.PROFILES_V2)) {
return SetProfileResponse.newBuilder()
.setProfilesV2CapabilityRequired(ProfilesV2CapabilityRequired.getDefaultInstance())
.build();
}
final Optional<String> currentAvatar = maybeProfile.map(VersionedProfile::avatar)
validateRequest(request);
final String expectedCurrentVersionHex = HexFormat.of().formatHex(request.getExpectedCurrentVersion().toByteArray());
final boolean currentVersionMatchesExpected = account.getCurrentProfileVersion().isEmpty()
? request.getExpectedCurrentVersion().isEmpty()
: account.getCurrentProfileVersion().get().equals(expectedCurrentVersionHex);
if (!currentVersionMatchesExpected) {
return SetProfileResponse.newBuilder().setWriteConflict(FailedPrecondition.newBuilder()
.setDescription("current and expected profile versions must match")
.build()).build();
}
final byte[] version = request.getVersion().toByteArray();
final Optional<VersionedProfile> maybeProfile = profilesManager.get(authenticatedDevice.accountIdentifier(),
version);
final Optional<VersionedProfileV1> maybeV1Profile = profilesManager.getV1(
authenticatedDevice.accountIdentifier(), HexFormat.of().formatHex(version));
if (!request.getPaymentAddress().isEmpty() && ProfileHelper.isPaymentAddressUpdateForbidden(account, maybeProfile, maybeV1Profile, dynamicConfigurationManager)) {
return SetProfileResponse.newBuilder()
.setPaymentsForbiddenInRegion(PaymentsForbiddenInRegion.getDefaultInstance())
.build();
}
final Optional<String> currentAvatar = maybeV1Profile.map(VersionedProfileV1::avatar)
.filter(avatar -> avatar.startsWith("profiles/"));
final AvatarData avatarData = switch (AvatarChangeUtil.fromGrpcAvatarChange(request.getAvatarChange())) {
final AvatarData avatarData = switch (AvatarChangeUtil.fromGrpcAvatarChange(request.getV1Request().getAvatarChange())) {
case AVATAR_CHANGE_UNCHANGED -> new AvatarData(currentAvatar, currentAvatar, Optional.empty());
case AVATAR_CHANGE_CLEAR -> new AvatarData(currentAvatar, Optional.empty(), Optional.empty());
case AVATAR_CHANGE_UPDATE -> {
@@ -124,120 +144,128 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
}
};
profilesManager.set(account.getUuid(),
new VersionedProfile(
request.getVersion(),
request.getName().toByteArray(),
avatarData.finalAvatar().orElse(null),
request.getAboutEmoji().toByteArray(),
request.getAbout().toByteArray(),
request.getPaymentAddress().toByteArray(),
request.getPhoneNumberSharing().toByteArray(),
request.getCommitment().toByteArray()));
final byte[] commitment = !request.getCommitment().isEmpty()
? request.getCommitment().toByteArray()
: maybeProfile.orElseThrow(IllegalStateException::new).commitment();
accountsManager.update(account, a -> {
final VersionedProfileV1 v1Profile = new VersionedProfileV1(
HexFormat.of().formatHex(version),
request.getV1Request().getName().toByteArray(),
avatarData.finalAvatar().orElse(null),
request.getV1Request().getAboutEmoji().toByteArray(),
request.getV1Request().getAbout().toByteArray(),
request.getPaymentAddress().toByteArray(),
request.getV1Request().getPhoneNumberSharing().toByteArray(),
commitment);
final List<AccountBadge> updatedBadges = Optional.of(request.getBadgeIdsList())
.map(badges -> ProfileHelper.mergeBadgeIdsWithExistingAccountBadges(clock, badgeConfigurationMap, badges,
a.getBadges()))
.orElseGet(a::getBadges);
final VersionedProfile profile = new VersionedProfile(version,
request.getData().toByteArray(),
request.getPaymentAddress().isEmpty() ? null : request.getPaymentAddress().toByteArray(),
commitment
);
a.setBadges(clock, updatedBadges);
a.setCurrentProfileVersion(request.getVersion());
});
try {
profilesManager.set(account.getIdentifier(IdentityType.ACI), v1Profile, profile,
request.getExpectedCurrentDataHash().isEmpty() ? null : request.getExpectedCurrentDataHash().toByteArray());
if (request.getAvatarChange() != AvatarChange.AVATAR_CHANGE_UNCHANGED && avatarData.currentAvatar().isPresent()) {
} catch (WriteConflictException _) {
return SetProfileResponse.newBuilder()
.setWriteConflict(FailedPrecondition.newBuilder()
.setDescription("current and expected data hash mismatch")
.build())
.build();
}
try {
accountsManager.updateCurrentProfileVersion(account.getIdentifier(IdentityType.ACI), version, expectedCurrentVersionHex, a -> {
final List<AccountBadge> updatedBadges = Optional.of(request.getBadgeIdsList())
.map(badges -> ProfileHelper.mergeBadgeIdsWithExistingAccountBadges(clock, badgeConfigurationMap, badges,
a.getBadges()))
.orElseGet(a::getBadges);
a.setBadges(clock, updatedBadges);
});
} catch (final WriteConflictException _) {
return SetProfileResponse.newBuilder()
.setWriteConflict(FailedPrecondition.newBuilder()
.setDescription("current and expected version mismatch")
.build())
.build();
}
if (request.getV1Request().getAvatarChange() != AvatarChange.AVATAR_CHANGE_UNCHANGED && avatarData.currentAvatar().isPresent()) {
profilesManager.deleteAvatar(avatarData.currentAvatar().get());
}
return avatarData.uploadAttributes()
.map(avatarUploadAttributes -> SetProfileResponse.newBuilder().setAttributes(avatarUploadAttributes).build())
.orElse(SetProfileResponse.newBuilder().build());
.map(avatarUploadAttributes -> SetProfileResponse.newBuilder()
.setResult(SetProfileResult.newBuilder()
.setV1AvatarUploadForm(avatarUploadAttributes).build())
.build())
.orElse(SetProfileResponse.newBuilder()
.setResult(SetProfileResult.getDefaultInstance())
.build());
}
@Override
public GetUnversionedProfileResponse getUnversionedProfile(final GetUnversionedProfileRequest request) throws StatusException, RateLimitExceededException {
public GetUnversionedProfileResponse getUnversionedProfile(final GetUnversionedProfileRequest request) throws RateLimitExceededException {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
final ServiceIdentifier targetIdentifier =
ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getServiceIdentifier());
final Account targetAccount = validateRateLimitAndGetAccount(authenticatedDevice.accountIdentifier(), targetIdentifier);
final Optional<Account> maybeAccount = validateRateLimitAndGetAccount(authenticatedDevice.accountIdentifier(), targetIdentifier);
return ProfileGrpcHelper.buildUnversionedProfileResponse(targetIdentifier,
return maybeAccount.map(account -> GetUnversionedProfileResponse.newBuilder()
.setResult(ProfileGrpcHelper.buildUnversionedProfileResult(targetIdentifier,
authenticatedDevice.accountIdentifier(),
targetAccount,
profileBadgeConverter);
account,
profileBadgeConverter))
.build()).orElseGet(() -> GetUnversionedProfileResponse.newBuilder()
.setNotFound(NotFound.getDefaultInstance())
.build());
}
@Override
public GetVersionedProfileResponse getVersionedProfile(final GetVersionedProfileRequest request) throws StatusException, RateLimitExceededException {
public GetVersionedProfileResponse getVersionedProfile(final GetVersionedProfileRequest request) throws RateLimitExceededException {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
final ServiceIdentifier targetIdentifier =
ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getAccountIdentifier());
if (targetIdentifier.identityType() != IdentityType.ACI) {
throw Status.INVALID_ARGUMENT.withDescription("Expected ACI service identifier").asException();
}
final Optional<Account> maybeAccount = validateRateLimitAndGetAccount(authenticatedDevice.accountIdentifier(), targetIdentifier);
final Account account = validateRateLimitAndGetAccount(authenticatedDevice.accountIdentifier(), targetIdentifier);
return ProfileGrpcHelper.getVersionedProfile(account, profilesManager, request.getVersion());
return maybeAccount.map(account ->
ProfileGrpcHelper.getVersionedProfile(account, profilesManager,
request.getVersion().toByteArray(),
request.getDataEtag().toByteArray(),
request.getPaymentAddressEtag().toByteArray())
.map(result ->
GetVersionedProfileResponse.newBuilder()
.setResult(result)
.build())
.orElseGet(() -> GetVersionedProfileResponse.newBuilder()
.setNotFound(NotFound.getDefaultInstance())
.build())).orElseGet(() -> GetVersionedProfileResponse.newBuilder()
.setNotFound(NotFound.getDefaultInstance())
.build());
}
@Override
public GetExpiringProfileKeyCredentialResponse getExpiringProfileKeyCredential(
final GetExpiringProfileKeyCredentialRequest request) throws StatusException, RateLimitExceededException {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
final ServiceIdentifier targetIdentifier = ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getAccountIdentifier());
if (targetIdentifier.identityType() != IdentityType.ACI) {
throw Status.INVALID_ARGUMENT.withDescription("Expected ACI service identifier").asException();
}
if (request.getCredentialType() != CredentialType.CREDENTIAL_TYPE_EXPIRING_PROFILE_KEY) {
throw Status.INVALID_ARGUMENT.withDescription("Expected expiring profile key credential type").asException();
}
final Account targetAccount = validateRateLimitAndGetAccount(authenticatedDevice.accountIdentifier(), targetIdentifier);
return ProfileGrpcHelper.getExpiringProfileKeyCredentialResponse(targetAccount.getUuid(),
request.getVersion(), request.getCredentialRequest().toByteArray(), profilesManager, zkProfileOperations);
}
private Account validateRateLimitAndGetAccount(final UUID requesterUuid,
final ServiceIdentifier targetIdentifier) throws RateLimitExceededException, StatusException {
private Optional<Account> validateRateLimitAndGetAccount(final UUID requesterUuid,
final ServiceIdentifier targetIdentifier) throws RateLimitExceededException {
rateLimiters.getProfileLimiter().validate(requesterUuid);
return accountsManager.getByServiceIdentifier(targetIdentifier).orElseThrow(Status.NOT_FOUND::asException);
return accountsManager.getByServiceIdentifier(targetIdentifier);
}
private void validateRequest(final SetProfileRequest request) throws StatusException {
if (request.getVersion().isEmpty()) {
throw Status.INVALID_ARGUMENT.withDescription("Missing version").asException();
private void validateRequest(final SetProfileRequest request) {
if (request.getExpectedCurrentDataHash().isEmpty() && request.getCommitment().isEmpty()) {
throw GrpcExceptions.constraintViolation("At least one of expected current data hash and commitment is required");
}
// v1 -> v2 migration
if (request.getCommitment().isEmpty()) {
throw Status.INVALID_ARGUMENT.withDescription("Missing profile commitment").asException();
throw GrpcExceptions.constraintViolation("Request must include commitment during migration");
}
checkByteStringLength(request.getName(), "Invalid name length", List.of(81, 285));
checkByteStringLength(request.getAboutEmoji(), "Invalid about emoji length", List.of(0, 60));
checkByteStringLength(request.getAbout(), "Invalid about length", List.of(0, 156, 282, 540));
checkByteStringLength(request.getPaymentAddress(), "Invalid mobile coin address length", List.of(0, 582));
}
private static void checkByteStringLength(final ByteString byteString, final String errorMessage,
final List<Integer> allowedLengths) throws StatusException {
final int byteStringLength = byteString.toByteArray().length;
for (int allowedLength : allowedLengths) {
if (byteStringLength == allowedLength) {
return;
}
}
throw Status.INVALID_ARGUMENT.withDescription(errorMessage).asException();
}
private ProfileAvatarUploadAttributes generateAvatarUploadForm(final String objectName) {
@@ -17,6 +17,7 @@ import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.grpc.validators.Base64UrlFieldValidator;
import org.whispersystems.textsecuregcm.grpc.validators.E164FieldValidator;
import org.whispersystems.textsecuregcm.grpc.validators.EnumSpecifiedFieldValidator;
import org.whispersystems.textsecuregcm.grpc.validators.ExactlySizeFieldValidator;
@@ -25,6 +26,7 @@ import org.whispersystems.textsecuregcm.grpc.validators.FieldValidator;
import org.whispersystems.textsecuregcm.grpc.validators.NonEmptyFieldValidator;
import org.whispersystems.textsecuregcm.grpc.validators.PresentFieldValidator;
import org.whispersystems.textsecuregcm.grpc.validators.RangeFieldValidator;
import org.whispersystems.textsecuregcm.grpc.validators.ServiceIdentifierIdentityTypeValidator;
import org.whispersystems.textsecuregcm.grpc.validators.SizeFieldValidator;
public class ValidatingInterceptor implements ServerInterceptor {
@@ -37,7 +39,9 @@ public class ValidatingInterceptor implements ServerInterceptor {
"org.signal.chat.require.e164", new E164FieldValidator(),
"org.signal.chat.require.exactlySize", new ExactlySizeFieldValidator(),
"org.signal.chat.require.range", new RangeFieldValidator(),
"org.signal.chat.require.size", new SizeFieldValidator()
"org.signal.chat.require.size", new SizeFieldValidator(),
"org.signal.chat.require.base64url", new Base64UrlFieldValidator(),
"org.signal.chat.require.identityType", new ServiceIdentifierIdentityTypeValidator()
);
@Override
@@ -62,9 +66,6 @@ public class ValidatingInterceptor implements ServerInterceptor {
try {
validateMessage(message);
super.onMessage(message);
} catch (final StatusRuntimeException e) {
call.close(e.getStatus(), e.getTrailers());
forwardCalls = false;
} catch (RuntimeException runtimeException) {
final StatusRuntimeException grpcException = switch (runtimeException) {
case StatusRuntimeException e -> e;
@@ -0,0 +1,39 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc.validators;
import com.google.protobuf.Descriptors;
import org.whispersystems.textsecuregcm.util.ImpossiblePhoneNumberException;
import org.whispersystems.textsecuregcm.util.NonNormalizedPhoneNumberException;
import org.whispersystems.textsecuregcm.util.Util;
import java.util.Base64;
import java.util.Objects;
import java.util.Set;
/// Validate that a string field is a valid base64 url string (padded or unpadded)
public class Base64UrlFieldValidator extends BaseFieldValidator<Boolean> {
public Base64UrlFieldValidator() {
super("base64url", Set.of(Descriptors.FieldDescriptor.Type.STRING), MissingOptionalAction.SUCCEED, false);
}
@Override
protected Boolean resolveExtensionValue(final Object extensionValue) throws FieldValidationException {
return requireFlagExtension(extensionValue);
}
@Override
protected void validateStringValue(
final Boolean extensionValue,
final String fieldValue) throws FieldValidationException {
try {
Base64.getUrlDecoder().decode(fieldValue);
} catch (IllegalArgumentException e) {
throw new FieldValidationException("value is not valid base64 url");
}
}
}
@@ -0,0 +1,52 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc.validators;
import com.google.protobuf.Descriptors;
import com.google.protobuf.Message;
import java.util.Objects;
import java.util.Set;
import org.signal.chat.common.IdentityType;
import org.signal.chat.common.ServiceIdentifier;
public class ServiceIdentifierIdentityTypeValidator extends BaseFieldValidator<IdentityType> {
public ServiceIdentifierIdentityTypeValidator() {
super("identityType", Set.of(Descriptors.FieldDescriptor.Type.MESSAGE), MissingOptionalAction.SUCCEED, false);
}
@Override
protected IdentityType resolveExtensionValue(final Object extensionValue) throws FieldValidationException {
if (extensionValue instanceof Descriptors.EnumValueDescriptor d) {
if (d.getType().equals(org.signal.chat.require.IdentityType.getDescriptor())) {
return switch (Objects.requireNonNull(org.signal.chat.require.IdentityType.forNumber(d.getNumber()))) {
case IDENTITY_TYPE_ACI -> IdentityType.IDENTITY_TYPE_ACI;
case IDENTITY_TYPE_PNI -> IdentityType.IDENTITY_TYPE_PNI;
default -> throw new IllegalArgumentException("unsupported value: " + d.getName());
};
}
}
throw new IllegalArgumentException("value must be org.signal.chat.require.IdentityType");
}
@Override
protected void validateMessageValue(final IdentityType extensionValue, final Message msg) throws FieldValidationException {
if (msg == null) {
return;
}
if (msg instanceof ServiceIdentifier i) {
if (i.getIdentityType() == extensionValue) {
return;
}
throw new FieldValidationException("identity type must be " + extensionValue.getValueDescriptor().getName());
}
throw new IllegalArgumentException("field must be " + ServiceIdentifier.class.getName());
}
}
@@ -14,8 +14,10 @@ import java.io.IOException;
import java.util.List;
import java.util.Optional;
import org.whispersystems.textsecuregcm.captcha.Action;
import org.whispersystems.textsecuregcm.captcha.AssessmentResult;
import org.whispersystems.textsecuregcm.captcha.CaptchaChecker;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.metrics.CaptchaMetrics;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.push.NotPushRegisteredException;
import org.whispersystems.textsecuregcm.spam.ChallengeType;
@@ -61,13 +63,18 @@ public class RateLimitChallengeManager {
}
}
public boolean answerCaptchaChallenge(final Account account, final String captcha, final String mostRecentProxyIp,
final String userAgent, final Optional<Float> scoreThreshold)
throws RateLimitExceededException, IOException {
public boolean answerCaptchaChallenge(final Account account,
final String captcha,
final String mostRecentProxyIp,
final String userAgent,
final Optional<Float> scoreThreshold) throws RateLimitExceededException, IOException {
rateLimiters.getCaptchaChallengeAttemptLimiter().validate(account.getUuid());
final boolean challengeSuccess = captchaChecker.verify(Optional.of(account.getUuid()), Action.CHALLENGE, captcha, mostRecentProxyIp, userAgent).isValid(scoreThreshold);
final AssessmentResult assessmentResult =
captchaChecker.verify(Optional.of(account.getUuid()), Action.CHALLENGE, captcha, mostRecentProxyIp, userAgent);
final boolean challengeSuccess = assessmentResult.isValid(scoreThreshold);
final Tags tags = Tags.of(
Tag.of(SOURCE_COUNTRY_TAG_NAME, Util.getCountryCode(account.getNumber())),
@@ -77,6 +84,13 @@ public class RateLimitChallengeManager {
Metrics.counter(CAPTCHA_ATTEMPT_COUNTER_NAME, tags).increment();
CaptchaMetrics.measureCaptchaOutcome(assessmentResult.getNormalizedIntScore(),
challengeSuccess,
Util.getRegion(account.getNumber()),
// Note: currently all challenges are for message-sending, but if we add more use cases, we'll need to make the
// accept a context from callers rather than hard-coding it here
"sendMessage");
if (challengeSuccess) {
rateLimiters.getCaptchaChallengeSuccessLimiter().validate(account.getUuid());
resetRateLimits(account, ChallengeType.CAPTCHA);
@@ -8,7 +8,6 @@ package org.whispersystems.textsecuregcm.limits;
import java.util.UUID;
import java.util.concurrent.CompletionStage;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import reactor.core.publisher.Mono;
public interface RateLimiter {
@@ -78,4 +77,27 @@ public interface RateLimiter {
default CompletionStage<Void> clearAsync(final UUID accountUuid) {
return clearAsync(accountUuid.toString());
}
/// Restore `permitsToRestore` permits to the pool. If the RateLimiter has a maximum bucket size, it is respected even
/// if `permitsToRestore` would exceed the maximum bucket size.
///
/// @param key The key to restore permits for.
/// @param permitsToRestore The number of permits to restore
/// @implNote The default implementation of this method assumes permits can be restored by calling `validate` with a
/// negative permit count. If the `validate` implementation does not support this, the implementor must provide a
/// custom implementation of [this#restorePermits].
default void restorePermits(final String key, int permitsToRestore) {
if (permitsToRestore < 0) {
throw new IllegalArgumentException("permits to restore must be non-negative");
}
try {
validate(key, -1 * permitsToRestore);
} catch (RateLimitExceededException e) {
throw new IllegalStateException("Out of permits when trying to restore permits", e);
}
}
default void restorePermits(final UUID accountUuid, int permitsToRestore) {
restorePermits(accountUuid.toString(), permitsToRestore);
}
}
@@ -8,6 +8,7 @@ import com.google.common.annotations.VisibleForTesting;
import java.time.Clock;
import java.time.Duration;
import java.util.concurrent.ScheduledExecutorService;
import io.dropwizard.util.DataSize;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
@@ -19,6 +20,7 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
BACKUP_AUTH_CHECK("backupAuthCheck", new RateLimiterConfig(100, Duration.ofMinutes(15), true)),
PIN("pin", new RateLimiterConfig(10, Duration.ofDays(1), false)),
ATTACHMENT("attachmentCreate", new RateLimiterConfig(50, Duration.ofMillis(1200), true)),
ATTACHMENT_BYTES("attachmentCreateBytes", new RateLimiterConfig(DataSize.gigabytes(1).toBytes(), Duration.ofNanos(1000), true)),
BACKUP_ATTACHMENT("backupAttachmentCreate", new RateLimiterConfig(10_000, Duration.ofSeconds(1), true)),
PRE_KEYS("prekeys", new RateLimiterConfig(6, Duration.ofMinutes(10), false)),
MESSAGES("messages", new RateLimiterConfig(60, Duration.ofSeconds(1), true)),
@@ -34,6 +36,7 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
USERNAME_LINK_LOOKUP_PER_IP("usernameLinkLookupPerIp", new RateLimiterConfig(100, Duration.ofSeconds(15), true)),
CHECK_ACCOUNT_EXISTENCE("checkAccountExistence", new RateLimiterConfig(1000, Duration.ofSeconds(4), true)),
REGISTRATION("registration", new RateLimiterConfig(6, Duration.ofSeconds(30), false)),
SET_ZK_CREDENTIAL_KEY("setZkCredentialKey", new RateLimiterConfig(5, Duration.ofDays(7), false)),
VERIFICATION_PUSH_CHALLENGE("verificationPushChallenge", new RateLimiterConfig(5, Duration.ofSeconds(30), false)),
VERIFICATION_CAPTCHA("verificationCaptcha", new RateLimiterConfig(10, Duration.ofSeconds(30), false)),
RATE_LIMIT_RESET("rateLimitReset", new RateLimiterConfig(2, Duration.ofHours(12), false)),
@@ -56,7 +59,8 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
RECORD_DEVICE_TRANSFER_REQUEST("recordDeviceTransferRequest", new RateLimiterConfig(10, Duration.ofMillis(100), true)),
WAIT_FOR_DEVICE_TRANSFER_REQUEST("waitForDeviceTransferRequest", new RateLimiterConfig(10, Duration.ofMillis(100), true)),
DEVICE_CHECK_CHALLENGE("deviceCheckChallenge", new RateLimiterConfig(10, Duration.ofMinutes(1), false)),
SUBMIT_CALL_QUALITY_SURVEY("submitCallQualitySurvey", new RateLimiterConfig(100, Duration.ofMinutes(1), true))
SUBMIT_CALL_QUALITY_SURVEY("submitCallQualitySurvey", new RateLimiterConfig(100, Duration.ofMinutes(1), true)),
BATCH_IDENTITY_CHECK("batchIdentityCheck", new RateLimiterConfig(100, Duration.ofMinutes(1), true)),
;
private final String id;
@@ -103,8 +107,8 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
return forDescriptor(For.VERIFY_DEVICE);
}
public RateLimiter getMessagesLimiter() {
return forDescriptor(For.MESSAGES);
public RateLimiter getSetZkCredentialKeyLimiter() {
return forDescriptor(For.SET_ZK_CREDENTIAL_KEY);
}
public RateLimiter getPreKeysLimiter() {
@@ -115,6 +119,10 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
return forDescriptor(For.ATTACHMENT);
}
public RateLimiter getAttachmentBytesLimiter() {
return forDescriptor(For.ATTACHMENT_BYTES);
}
public RateLimiter getPinLimiter() {
return forDescriptor(For.PIN);
}
@@ -155,6 +163,10 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
return forDescriptor(For.REGISTRATION);
}
public RateLimiter getMessagesLimiter() {
return forDescriptor(For.MESSAGES);
}
public RateLimiter getRateLimitResetLimiter() {
return forDescriptor(For.RATE_LIMIT_RESET);
}
@@ -226,4 +238,8 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
public RateLimiter getSubmitCallQualitySurveyLimiter() {
return forDescriptor(For.SUBMIT_CALL_QUALITY_SURVEY);
}
public RateLimiter getBatchIdentityCheckLimiter() {
return forDescriptor(For.BATCH_IDENTITY_CHECK);
}
}
@@ -0,0 +1,31 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.metrics;
import io.micrometer.core.instrument.DistributionSummary;
import io.micrometer.core.instrument.Metrics;
public class CaptchaMetrics {
private static final String CAPTCHA_OUTCOME_DISTRIBUTION_NAME = MetricsUtil.name(CaptchaMetrics.class, "outcome");
private CaptchaMetrics() {}
public static void measureCaptchaOutcome(final int score,
final boolean success,
final String region,
final String context) {
DistributionSummary.builder(CAPTCHA_OUTCOME_DISTRIBUTION_NAME)
.tags("success", String.valueOf(success),
"regionCode", region,
"context", context)
.minimumExpectedValue(1.0d)
.maximumExpectedValue(100.0d)
.register(Metrics.globalRegistry)
.record(Math.max(1, score));
}
}
@@ -18,9 +18,11 @@ import jakarta.ws.rs.container.ContainerResponseFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import java.util.Set;
import javax.annotation.Nullable;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.HttpChannel;
import org.eclipse.jetty.server.Request;
@@ -49,6 +51,9 @@ import org.whispersystems.textsecuregcm.util.ua.UserAgentUtil;
public class MetricsHttpChannelListener implements HttpChannel.Listener, Container.Listener, LifeCycle.Listener,
ContainerResponseFilter {
private static final Set<String> EXPECTED_HTTP_METHODS =
Set.of("GET", "HEAD", "POST", "PUT", "DELETE", "CONNECT", "OPTIONS", "TRACE", "PATCH");
private static final Logger logger = LoggerFactory.getLogger(MetricsHttpChannelListener.class);
private record RequestInfo(String path, String method, int statusCode, @Nullable String userAgent) {
@@ -201,14 +206,21 @@ public class MetricsHttpChannelListener implements HttpChannel.Listener, Contain
.filter(servletPaths::contains)
.orElse("unknown")
);
final String method = Optional.ofNullable(request.getMethod()).orElse("unknown");
// Response cannot be null, but its status might not always reflect an actual response status, since it gets
// initialized to 200
final int status = request.getResponse().getStatus();
@Nullable final String userAgent = request.getHeader(HttpHeaders.USER_AGENT);
return new RequestInfo(path, method, status, userAgent);
return new RequestInfo(path, normalizeMethod(request.getMethod()), status, userAgent);
}
static String normalizeMethod(@Nullable final String method) {
if (StringUtils.isBlank(method)) {
return "unknown";
}
return EXPECTED_HTTP_METHODS.contains(method.toUpperCase(Locale.ROOT)) ? method : "unknown";
}
}
@@ -107,7 +107,7 @@ public class MetricsRequestEventListener implements RequestEventListener {
final List<Tag> tags = new ArrayList<>();
tags.add(Tag.of(PATH_TAG, UriInfoUtil.getPathTemplate(event.getUriInfo())));
tags.add(Tag.of(METHOD_TAG, event.getContainerRequest().getMethod()));
tags.add(Tag.of(METHOD_TAG, MetricsHttpChannelListener.normalizeMethod(event.getContainerRequest().getMethod())));
tags.add(Tag.of(STATUS_CODE_TAG, String.valueOf(Optional
.ofNullable(event.getContainerResponse())
.map(ContainerResponse::getStatus)
@@ -26,6 +26,8 @@ import javax.annotation.Nullable;
import kotlin.Pair;
import org.apache.commons.lang3.StringUtils;
import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.controllers.MessageDeliveryNotAllowedException;
import org.whispersystems.textsecuregcm.controllers.MismatchedDevices;
import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
import org.whispersystems.textsecuregcm.controllers.MultiRecipientMismatchedDevicesException;
@@ -36,6 +38,7 @@ import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.spam.MessageDeliveryListener;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.storage.MessagesManager;
import org.whispersystems.textsecuregcm.util.Util;
@@ -54,6 +57,7 @@ public class MessageSender {
private final MessagesManager messagesManager;
private final PushNotificationManager pushNotificationManager;
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
private final List<MessageDeliveryListener> messageDeliveryListeners = new ArrayList<>();
@@ -80,9 +84,12 @@ public class MessageSender {
@VisibleForTesting
static final byte NO_EXCLUDED_DEVICE_ID = -1;
public MessageSender(final MessagesManager messagesManager, final PushNotificationManager pushNotificationManager) {
public MessageSender(final MessagesManager messagesManager,
final PushNotificationManager pushNotificationManager,
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
this.messagesManager = messagesManager;
this.pushNotificationManager = pushNotificationManager;
this.dynamicConfigurationManager = dynamicConfigurationManager;
}
public void addMessageDeliveryListener(final MessageDeliveryListener messageDeliveryListener) {
@@ -112,7 +119,12 @@ public class MessageSender {
final Map<Byte, Envelope> messagesByDeviceId,
final Map<Byte, Integer> registrationIdsByDeviceId,
@SuppressWarnings("OptionalUsedAsFieldOrParameterType") final Optional<Byte> syncMessageSenderDeviceId,
@Nullable final String userAgent) throws MismatchedDevicesException, MessageTooLargeException {
@Nullable final String userAgent)
throws MismatchedDevicesException, MessageTooLargeException, MessageDeliveryNotAllowedException {
if (dynamicConfigurationManager.getConfiguration().getMessageDeliveryConfiguration().isReadOnly()) {
throw new MessageDeliveryNotAllowedException();
}
final Tag platformTag = UserAgentTagUtil.getPlatformTag(userAgent);
@@ -189,7 +201,12 @@ public class MessageSender {
final boolean isStory,
final boolean isEphemeral,
final boolean isUrgent,
@Nullable final String userAgent) throws MultiRecipientMismatchedDevicesException, MessageTooLargeException {
@Nullable final String userAgent)
throws MultiRecipientMismatchedDevicesException, MessageTooLargeException, MessageDeliveryNotAllowedException {
if (dynamicConfigurationManager.getConfiguration().getMessageDeliveryConfiguration().isReadOnly()) {
throw new MessageDeliveryNotAllowedException();
}
final Tag platformTag = UserAgentTagUtil.getPlatformTag(userAgent);
@@ -304,8 +321,11 @@ public class MessageSender {
}
if (messagesByDeviceId.isEmpty()) {
if (syncMessageSenderDeviceId.isEmpty()) {
throw new IllegalArgumentException("Messages must not be empty for non-sync messages");
}
Metrics.counter(EMPTY_MESSAGE_LIST_COUNTER_NAME,
Tags.of(SYNC_MESSAGE_TAG_NAME, String.valueOf(syncMessageSenderDeviceId.isPresent())).and(platformTag)).increment();
Tags.of(SYNC_MESSAGE_TAG_NAME, String.valueOf(true)).and(platformTag)).increment();
}
final byte excludedDeviceId;
@@ -17,6 +17,7 @@ import java.util.function.BiConsumer;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
@@ -195,7 +196,7 @@ public class PushNotificationManager {
// updating an uninstalled feedback timestamp though.
accountsManager.getByAccountIdentifier(account.getUuid()).ifPresent(rereadAccount ->
rereadAccount.getDevice(device.getId()).ifPresent(rereadDevice ->
accountsManager.updateDevice(rereadAccount, device.getId(), d -> {
accountsManager.updateDevice(rereadAccount.getIdentifier(IdentityType.ACI), device.getId(), d -> {
// Don't clear the token if it's already changed
if (originalToken.equals(getPushToken(d, tokenType))) {
switch (tokenType) {
@@ -8,6 +8,7 @@ import jakarta.ws.rs.container.ContainerRequestContext;
import java.util.Optional;
import org.whispersystems.textsecuregcm.entities.UpdateVerificationSessionRequest;
import org.whispersystems.textsecuregcm.registration.VerificationSession;
import org.whispersystems.textsecuregcm.storage.Account;
public interface RegistrationFraudChecker {
@@ -47,6 +48,14 @@ public interface RegistrationFraudChecker {
final VerificationSession verificationSession,
final String e164);
/**
* Handles a completed verification session resulting in a registration.
*
* @param verificationSessionId The ID of the verification session that resulted in a completed registration
* @param createdAccount The account created at the end of the verification session
*/
void handleVerificationCompleted(final String verificationSessionId, final Account createdAccount);
static RegistrationFraudChecker noop() {
return new RegistrationFraudChecker() {
@@ -64,6 +73,10 @@ public interface RegistrationFraudChecker {
return VerificationCheck.DEFAULT;
}
@Override
public void handleVerificationCompleted(final String verificationSessionId, final Account createdAccount) {
}
};
}
}
@@ -92,6 +92,7 @@ public class Account {
private String registrationLockSalt;
@JsonProperty("uak")
@Nullable
private byte[] unidentifiedAccessKey;
@JsonProperty("uua")
@@ -112,6 +113,10 @@ public class Account {
@Nullable
private BackupVoucher backupVoucher;
@JsonProperty("zck")
@Nullable
private byte[] zkCredentialKey;
@JsonProperty
private int version;
@@ -428,7 +433,9 @@ public class Account {
public Optional<byte[]> getUnidentifiedAccessKey() {
requireNotStale();
return Optional.ofNullable(unidentifiedAccessKey);
return Optional.ofNullable((unidentifiedAccessKey == null || unidentifiedAccessKey.length == 0)
? null
: unidentifiedAccessKey);
}
public void setUnidentifiedAccessKey(final byte[] unidentifiedAccessKey) {
@@ -536,6 +543,15 @@ public class Account {
this.usernameHolds = usernameHolds;
}
@Nullable
public byte[] getZkCredentialKey() {
return zkCredentialKey;
}
public void setZkCredentialKey(@Nullable final byte[] zkCredentialKey) {
this.zkCredentialKey = zkCredentialKey;
}
public void markStale() {
stale = true;
}
@@ -6,6 +6,7 @@ package org.whispersystems.textsecuregcm.storage;
import static java.util.Objects.requireNonNull;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import static org.whispersystems.textsecuregcm.util.Util.getAlternateForms;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectWriter;
@@ -325,6 +326,9 @@ public class Accounts {
// Carry over the existing backup voucher to the new account
accountToCreate.setBackupVoucher(existingAccount.getBackupVoucher());
// Carry over the existing ZK credential key to the new account
accountToCreate.setZkCredentialKey(existingAccount.getZkCredentialKey());
final List<TransactWriteItem> writeItems = new ArrayList<>();
// If we're reclaiming an account that already has a username, we'd like to give the re-registering client
@@ -371,7 +375,28 @@ public class Accounts {
.build())
.build());
}
writeItems.add(UpdateAccountSpec.forAccount(accountsTableName, accountToCreate).transactItem());
// Phone number canonicalization means that a user can use a different phone number in the same equivalence class
// to reclaim the account.
if (!existingAccount.getNumber().equals(accountToCreate.getNumber())) {
if (getAlternateForms(existingAccount.getNumber()).contains(accountToCreate.getNumber())) {
final AttributeValue uuidAttr = AttributeValues.fromUUID(existingAccount.getUuid());
final AttributeValue numberAttr = AttributeValues.fromString(accountToCreate.getNumber());
final TransactWriteItem phoneNumberConstraintPut = buildConstraintTablePutIfAbsent(
phoneNumberConstraintTableName, uuidAttr, ATTR_ACCOUNT_E164, numberAttr);
writeItems.add(buildDelete(phoneNumberConstraintTableName, ATTR_ACCOUNT_E164, existingAccount.getNumber()));
writeItems.add(phoneNumberConstraintPut);
} else {
log.error("Reclaiming account with a non-equivalent phone number. Old account {}:{}:{}, new account {}:{}:{}",
existingAccount.getUuid(), existingAccount.getNumber(), existingAccount.getPhoneNumberIdentifier(),
accountToCreate.getUuid(), accountToCreate.getNumber(), accountToCreate.getPhoneNumberIdentifier());
throw new IllegalArgumentException("reclaimed accounts must have equivalent phone numbers");
}
}
final int updateAccountItemIndex = writeItems.size();
writeItems.add(UpdateAccountSpec.forReclaimedAccount(accountsTableName, accountToCreate, existingAccount.getNumber()).transactItem());
writeItems.addAll(additionalWriteItems);
return dynamoDbAsyncClient.transactWriteItems(TransactWriteItemsRequest.builder().transactItems(writeItems).build())
@@ -382,6 +407,16 @@ public class Accounts {
.exceptionally(throwable -> {
final Throwable unwrapped = ExceptionUtils.unwrap(throwable);
if (unwrapped instanceof TransactionCanceledException te) {
if (Accounts.conditionalCheckFailed(te.cancellationReasons().get(updateAccountItemIndex))) {
final Map<String, AttributeValue> item = te.cancellationReasons().get(updateAccountItemIndex).item();
final String existingNumber = AttributeValues.getString(item, Accounts.ATTR_ACCOUNT_E164, null);
if (!existingAccount.getNumber().equals(existingNumber)) {
log.error("Failed to update account due to unexpected existing phone number. Account {}. Expected {}, got {}",
existingAccount.getUuid(), existingAccount.getNumber(), existingNumber);
throw new UnexpectedExistingPhoneNumberException();
}
}
if (te.cancellationReasons().stream().anyMatch(Accounts::conditionalCheckFailed)) {
throw new ContestedOptimisticLockException();
}
@@ -889,6 +924,37 @@ public class Accounts {
}
}
record UpdateExpression (List<String> setClauses, List<String> addClauses, List<String> removeClauses) {
public String toExpressionString() {
final StringBuilder updateExpressionBuilder = new StringBuilder();
if (!setClauses.isEmpty()) {
updateExpressionBuilder.append("SET ");
updateExpressionBuilder.append(String.join(", ", setClauses));
}
if (!removeClauses.isEmpty()) {
if (!updateExpressionBuilder.isEmpty()) {
updateExpressionBuilder.append(" ");
}
updateExpressionBuilder.append("REMOVE ");
updateExpressionBuilder.append(String.join(", ", removeClauses));
}
if (!addClauses.isEmpty()) {
if (!updateExpressionBuilder.isEmpty()) {
updateExpressionBuilder.append(" ");
}
updateExpressionBuilder.append("ADD ");
updateExpressionBuilder.append(String.join(", ", addClauses));
}
return updateExpressionBuilder.toString();
}
}
/**
* A ddb update that can be used as part of a transaction or single-item update statement.
*/
@@ -897,13 +963,13 @@ public class Accounts {
Map<String, AttributeValue> key,
Map<String, String> attrNames,
Map<String, AttributeValue> attrValues,
String updateExpression,
UpdateExpression updateExpression,
String conditionExpression) {
UpdateItemRequest updateItemRequest() {
return UpdateItemRequest.builder()
.tableName(tableName)
.key(key)
.updateExpression(updateExpression)
.updateExpression(updateExpression.toExpressionString())
.conditionExpression(conditionExpression)
.expressionAttributeNames(attrNames)
.expressionAttributeValues(attrValues)
@@ -914,17 +980,46 @@ public class Accounts {
return TransactWriteItem.builder().update(Update.builder()
.tableName(tableName)
.key(key)
.updateExpression(updateExpression)
.updateExpression(updateExpression.toExpressionString())
.conditionExpression(conditionExpression)
.returnValuesOnConditionCheckFailure(ReturnValuesOnConditionCheckFailure.ALL_OLD)
.expressionAttributeNames(attrNames)
.expressionAttributeValues(attrValues)
.build()).build();
}
static UpdateAccountSpec forReclaimedAccount(
final String accountTableName,
final Account account,
final String expectedExistingE164) {
final UpdateAccountSpec base = forAccount(accountTableName, account);
final Map<String, AttributeValue> attrValues = new HashMap<>(base.attrValues());
attrValues.put(":number", AttributeValues.fromString(account.getNumber()));
final UpdateExpression updateExpression = base.updateExpression();
final List<String> setClauses = new ArrayList<>(updateExpression.setClauses());
setClauses.add("#number = :number");
final MembershipExpression membershipExpression = MembershipExpression.build(getAlternateForms(expectedExistingE164));
attrValues.putAll(membershipExpression.values());
// Defensive check: we should only update the e164 to another e164 in the same equivalence class
final String conditionExpression = base.conditionExpression() + " AND #number IN %s".formatted(membershipExpression.expression());
return new UpdateAccountSpec(
base.tableName(),
base.key(),
base.attrNames(),
attrValues,
new UpdateExpression(setClauses, updateExpression.addClauses(), updateExpression.removeClauses()),
conditionExpression
);
}
static UpdateAccountSpec forAccount(
final String accountTableName,
final Account account) {
// username, e164, and pni cannot be modified through this method
final Map<String, String> attrNames = new HashMap<>(Map.of(
"#number", ATTR_ACCOUNT_E164,
"#data", ATTR_ACCOUNT_DATA,
@@ -937,19 +1032,20 @@ public class Accounts {
":version", AttributeValues.fromInt(account.getVersion()),
":version_increment", AttributeValues.fromInt(1)));
final StringBuilder updateExpressionBuilder = new StringBuilder("SET #data = :data, #cds = :cds");
final List<String> setClauses = new ArrayList<>(List.of("#data = :data", "#cds = :cds"));
if (account.getUnidentifiedAccessKey().isPresent()) {
// if it's present in the account, also set the uak
attrNames.put("#uak", ATTR_UAK);
attrValues.put(":uak", AttributeValues.fromByteArray(account.getUnidentifiedAccessKey().get()));
updateExpressionBuilder.append(", #uak = :uak");
setClauses.add("#uak = :uak");
}
if (account.getUsernameHash().isPresent()) {
// if it's present in the account, also set the username hash
attrNames.put("#usernameHash", ATTR_USERNAME_HASH);
attrValues.put(":usernameHash", AttributeValues.fromByteArray(account.getUsernameHash().get()));
updateExpressionBuilder.append(", #usernameHash = :usernameHash");
setClauses.add("#usernameHash = :usernameHash");
}
// If the account has a username/handle pair, we should add it to the top level attributes.
@@ -959,7 +1055,7 @@ public class Accounts {
if (account.getEncryptedUsername().isPresent() && account.getUsernameLinkHandle() != null) {
attrNames.put("#ul", ATTR_USERNAME_LINK_UUID);
attrValues.put(":ul", AttributeValues.fromUUID(account.getUsernameLinkHandle()));
updateExpressionBuilder.append(", #ul = :ul");
setClauses.add("#ul = :ul");
}
// Some operations may remove the usernameLink or the usernameHash (re-registration, clear username link, and
@@ -974,17 +1070,20 @@ public class Accounts {
attrNames.put("#username_hash", ATTR_USERNAME_HASH);
removes.add("#username_hash");
}
final List<String> removeClauses = new ArrayList<>();
if (!removes.isEmpty()) {
updateExpressionBuilder.append(" REMOVE %s".formatted(String.join(",", removes)));
removeClauses.add(String.join(",", removes));
}
updateExpressionBuilder.append(" ADD #version :version_increment");
final List<String> addClauses = List.of("#version :version_increment");
return new UpdateAccountSpec(
accountTableName,
Map.of(KEY_ACCOUNT_UUID, AttributeValues.fromUUID(account.getUuid())),
attrNames,
attrValues,
updateExpressionBuilder.toString(),
new UpdateExpression(setClauses, addClauses, removeClauses),
"attribute_exists(#number) AND #version = :version");
}
}
@@ -1138,6 +1237,18 @@ public class Accounts {
.build();
}
private TransactWriteItem buildConditionalDeleteAccount(final Account account) {
return TransactWriteItem.builder()
.delete(Delete.builder()
.tableName(accountsTableName)
.key(Map.of(KEY_ACCOUNT_UUID, AttributeValues.fromUUID(account.getUuid())))
.conditionExpression("#version = :version")
.expressionAttributeNames(Map.of("#version", ATTR_VERSION))
.expressionAttributeValues(Map.of(":version", AttributeValues.fromInt(account.getVersion())))
.build())
.build();
}
@Nonnull
public CompletableFuture<Optional<Account>> getByAccountIdentifierAsync(final UUID uuid) {
return AsyncTimerUtil.record(GET_BY_UUID_TIMER, () -> itemByKeyAsync(accountsTableName, KEY_ACCOUNT_UUID, AttributeValues.fromUUID(uuid))
@@ -1178,34 +1289,51 @@ public class Accounts {
public void delete(final UUID uuid, final List<TransactWriteItem> additionalWriteItems) {
final Timer.Sample sample = Timer.start();
int tries = 0;
final int maxTries = 3;
try {
final Account account;
{
final Optional<Account> maybeAccount = getByAccountIdentifier(uuid);
while (tries < maxTries) {
try {
final Account account;
{
final Optional<Account> maybeAccount = getByAccountIdentifier(uuid);
if (maybeAccount.isEmpty()) {
if (maybeAccount.isEmpty()) {
return;
}
account = maybeAccount.get();
}
final List<TransactWriteItem> transactWriteItems = new ArrayList<>(List.of(
buildConditionalDeleteAccount(account),
buildDelete(phoneNumberConstraintTableName, ATTR_ACCOUNT_E164, account.getNumber()),
buildDelete(phoneNumberIdentifierConstraintTableName, ATTR_PNI_UUID, account.getPhoneNumberIdentifier()),
buildPutDeletedAccount(uuid, account.getPhoneNumberIdentifier())
));
account.getUsernameHash().ifPresent(usernameHash -> transactWriteItems.add(
buildDelete(usernamesConstraintTableName, UsernameTable.KEY_USERNAME_HASH, usernameHash)));
transactWriteItems.addAll(additionalWriteItems);
dynamoDbClient.transactWriteItems(TransactWriteItemsRequest.builder()
.transactItems(transactWriteItems)
.build());
return;
} catch (final TransactionCanceledException e) {
final CancellationReason cancellationReason = e.cancellationReasons().get(0);
if (conditionalCheckFailed(cancellationReason) || isTransactionConflict(cancellationReason)) {
// This means that either the optimistic delete failed because something else changed the account from under us,
// or there is an ongoing transaction for the account item. Either way, retry until the max attempts.
tries++;
} else {
throw new RuntimeException("Account deletion transaction canceled", e);
}
}
account = maybeAccount.get();
}
final List<TransactWriteItem> transactWriteItems = new ArrayList<>(List.of(
buildDelete(phoneNumberConstraintTableName, ATTR_ACCOUNT_E164, account.getNumber()),
buildDelete(accountsTableName, KEY_ACCOUNT_UUID, uuid),
buildDelete(phoneNumberIdentifierConstraintTableName, ATTR_PNI_UUID, account.getPhoneNumberIdentifier()),
buildPutDeletedAccount(uuid, account.getPhoneNumberIdentifier())
));
account.getUsernameHash().ifPresent(usernameHash -> transactWriteItems.add(
buildDelete(usernamesConstraintTableName, UsernameTable.KEY_USERNAME_HASH, usernameHash)));
transactWriteItems.addAll(additionalWriteItems);
dynamoDbClient.transactWriteItems(TransactWriteItemsRequest.builder()
.transactItems(transactWriteItems)
.build());
throw new OptimisticLockRetryLimitExceededException();
} finally {
sample.stop(DELETE_TIMER);
}
@@ -1545,7 +1673,13 @@ public class Accounts {
accountIdentifier, account.getPhoneNumberIdentifier(), phoneNumberIdentifierFromAttribute);
}
account.setNumber(item.get(ATTR_ACCOUNT_E164).s(), phoneNumberIdentifierFromAttribute);
final String attributeNumber = item.get(ATTR_ACCOUNT_E164).s();
if (account.getNumber() == null || !account.getNumber().equals(attributeNumber)) {
log.error("Missing or mismatched phone numbers for account {}. From JSON: {}; from attribute: {}",
accountIdentifier, account.getNumber(), attributeNumber);
}
account.setNumber(attributeNumber, phoneNumberIdentifierFromAttribute);
account.setUuid(accountIdentifier);
account.setUsernameHash(AttributeValues.getByteArray(item, ATTR_USERNAME_HASH, null));
account.setUsernameLinkHandle(AttributeValues.getUUID(item, ATTR_USERNAME_LINK_UUID, null));
@@ -1584,4 +1718,26 @@ public class Accounts {
: phoneNumber.substring(phoneNumber.length() - 2));
return sb.toString();
}
record MembershipExpression(String expression, Map<String, AttributeValue> values) {
public static MembershipExpression build(final Collection<String> values) {
if (values.isEmpty()) {
throw new IllegalArgumentException("must have at least one value");
}
final Map<String, AttributeValue> expressionValues = new HashMap<>();
final List<String> placeholders = new ArrayList<>();
final String prefix = "val";
int i = 0;
for (final String value : values) {
String key = ":" + prefix + i;
placeholders.add(key);
expressionValues.put(key, AttributeValues.fromString(value));
i++;
}
final String expression = "(" + String.join(", ", placeholders) + ")";
return new MembershipExpression(expression, expressionValues);
}
}
}
@@ -11,7 +11,6 @@ import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import io.dropwizard.lifecycle.Managed;
import io.lettuce.core.RedisCommandTimeoutException;
import io.lettuce.core.RedisException;
@@ -38,8 +37,10 @@ import java.util.Arrays;
import java.util.Base64;
import java.util.Collection;
import java.util.HashSet;
import java.util.HexFormat;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Queue;
import java.util.Set;
@@ -64,7 +65,6 @@ import org.signal.libsignal.protocol.IdentityKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestManager;
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
import org.whispersystems.textsecuregcm.controllers.MismatchedDevices;
import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
@@ -435,11 +435,15 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
return account;
}
public Pair<Account, Device> addDevice(final Account account, final DeviceSpec deviceSpec, final String linkDeviceToken)
public Pair<Account, Device> addDevice(final UUID accountIdentifier, final DeviceSpec deviceSpec, final String linkDeviceToken)
throws LinkDeviceTokenAlreadyUsedException {
return accountLockManager.withLock(Set.of(account.getPhoneNumberIdentifier()),
() -> addDevice(account.getIdentifier(IdentityType.ACI), deviceSpec, linkDeviceToken, MAX_UPDATE_ATTEMPTS),
final UUID phoneNumberIdentifier = accounts.getByAccountIdentifier(accountIdentifier)
.map(account -> account.getIdentifier(IdentityType.PNI))
.orElseThrow(() -> new IllegalArgumentException("Account not found: " + accountIdentifier));
return accountLockManager.withLock(Set.of(phoneNumberIdentifier),
() -> addDevice(accountIdentifier, deviceSpec, linkDeviceToken, MAX_UPDATE_ATTEMPTS),
accountLockExecutor);
}
@@ -624,13 +628,18 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
*
* @return the updated Account
*/
public Account removeDevice(final Account account, final byte deviceId) {
public Account removeDevice(final UUID accountIdentifier, final byte deviceId) {
if (deviceId == Device.PRIMARY_ID) {
throw new IllegalArgumentException("Cannot remove primary device");
}
return accountLockManager.withLock(Set.of(account.getPhoneNumberIdentifier()),
() -> removeDevice(account.getIdentifier(IdentityType.ACI), deviceId, MAX_UPDATE_ATTEMPTS),
// Always fetch a fresh, non-cached copy of the account before making modifications
final UUID phoneNumberIdentifier = accounts.getByAccountIdentifier(accountIdentifier)
.map(account -> account.getIdentifier(IdentityType.PNI))
.orElseThrow(() -> new IllegalArgumentException("Account not found: " + accountIdentifier));
return accountLockManager.withLock(Set.of(phoneNumberIdentifier),
() -> removeDevice(accountIdentifier, deviceId, MAX_UPDATE_ATTEMPTS),
accountLockExecutor);
}
@@ -674,13 +683,17 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
}
}
public Account changeNumber(final Account account,
public Account changeNumber(final UUID accountIdentifier,
final String targetNumber,
final IdentityKey pniIdentityKey,
final Map<Byte, ECSignedPreKey> pniSignedPreKeys,
final Map<Byte, KEMSignedPreKey> pniPqLastResortPreKeys,
final Map<Byte, Integer> pniRegistrationIds) throws InterruptedException, MismatchedDevicesException {
// Always fetch a fresh, non-cached copy of the account before making modifications
final Account account = accounts.getByAccountIdentifier(accountIdentifier)
.orElseThrow(() -> new IllegalArgumentException("Account not found: " + accountIdentifier));
final UUID targetPhoneNumberIdentifier = phoneNumberIdentifiers.getPhoneNumberIdentifier(targetNumber).join();
try {
@@ -745,7 +758,6 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
buildPniKeyWriteItems(targetPhoneNumberIdentifier, pniSignedPreKeys, pniPqLastResortPreKeys);
return updateWithRetries(
account,
a -> {
setPniKeys(a, pniIdentityKey, pniRegistrationIds);
return true;
@@ -817,18 +829,23 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
/// Reserve a username hash so that no other accounts may take it.
///
/// The reserved hash can later be set with [#confirmReservedUsernameHash(Account, byte\[\], byte\[\])]. The
/// The reserved hash can later be set with [#confirmReservedUsernameHash(UUID, byte\[\], byte\[\])]. The
/// reservation will eventually expire, after which point confirmReservedUsernameHash may fail if another account has
/// taken the username hash.
///
/// @param account the account to update
/// @param accountIdentifier the unique identifier of the account to update
/// @param requestedUsernameHashes the list of username hashes to attempt to reserve
///
/// @return the reserved username hash
///
/// @throws UsernameHashNotAvailableException if none of the given username hashes are available
public UsernameReservation reserveUsernameHash(final Account account, final List<byte[]> requestedUsernameHashes)
public UsernameReservation reserveUsernameHash(final UUID accountIdentifier, final List<byte[]> requestedUsernameHashes)
throws UsernameHashNotAvailableException {
// Always fetch a fresh, non-cached copy of the account before making modifications
final Account account = accounts.getByAccountIdentifier(accountIdentifier)
.orElseThrow(() -> new IllegalArgumentException("Account not found: " + accountIdentifier));
if (account.getUsernameHash().filter(
oldHash -> requestedUsernameHashes.stream().anyMatch(hash -> Arrays.equals(oldHash, hash)))
.isPresent()) {
@@ -846,7 +863,6 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
redisDelete(account);
final Account updatedAccount = updateWithRetries(
account,
_ -> true,
a -> reservedUsernameHash.set(
checkAndReserveNextUsernameHash(a, new ArrayDeque<>(requestedUsernameHashes))),
@@ -875,9 +891,9 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
}
}
/// Set a username hash previously reserved with {@link #reserveUsernameHash(Account, List)}
/// Set a username hash previously reserved with {@link #reserveUsernameHash(UUID, List)}
///
/// @param account the account to update
/// @param accountIdentifier identifier of the account to update
/// @param reservedUsernameHash the previously reserved username hash
/// @param encryptedUsername the encrypted form of the previously reserved username for the username link
///
@@ -886,9 +902,13 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
/// @throws UsernameHashNotAvailableException if the reserved username hash has been taken (because the reservation
/// expired)
/// @throws UsernameReservationNotFoundException if `reservedUsernameHash` was not reserved for the account
public Account confirmReservedUsernameHash(final Account account, final byte[] reservedUsernameHash, @Nullable final byte[] encryptedUsername)
public Account confirmReservedUsernameHash(final UUID accountIdentifier, final byte[] reservedUsernameHash, @Nullable final byte[] encryptedUsername)
throws UsernameReservationNotFoundException, UsernameHashNotAvailableException {
// Always fetch a fresh, non-cached copy of the account before making modifications
final Account account = accounts.getByAccountIdentifier(accountIdentifier)
.orElseThrow(() -> new IllegalArgumentException("Account not found: " + accountIdentifier));
if (account.getUsernameHash().map(currentUsernameHash -> Arrays.equals(currentUsernameHash, reservedUsernameHash)).orElse(false)) {
// the client likely already succeeded and is retrying
return account;
@@ -902,7 +922,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
redisDelete(account);
final Account updatedAccount = updateWithRetries(account,
final Account updatedAccount = updateWithRetries(
_ -> true,
a -> accounts.confirmUsernameHash(a, reservedUsernameHash, encryptedUsername),
() -> accounts.getByAccountIdentifier(account.getUuid()).orElseThrow(),
@@ -913,13 +933,10 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
return updatedAccount;
}
public Account clearUsernameHash(final Account account) {
redisDelete(account);
final Account updatedAccount = updateWithRetries(account,
_ -> true,
public Account clearUsernameHash(final UUID accountIdentifier) {
final Account updatedAccount = updateWithRetries(_ -> true,
accounts::clearUsernameHash,
() -> accounts.getByAccountIdentifier(account.getUuid()).orElseThrow(),
() -> accounts.getByAccountIdentifier(accountIdentifier).orElseThrow(),
AccountChangeValidator.USERNAME_CHANGE_VALIDATOR);
redisDelete(updatedAccount);
@@ -927,20 +944,63 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
return updatedAccount;
}
public Account update(Account account, Consumer<Account> updater) {
return update(account, a -> {
public Account update(final Account account, final Consumer<Account> updater) {
final Account updatedAccount = update(account.getIdentifier(IdentityType.ACI), updater);
account.markStale();
return updatedAccount;
}
public Account update(final UUID accountIdentifier, final Consumer<Account> updater) {
return update(accountIdentifier, a -> {
updater.accept(a);
// assume that all updaters passed to the public method actually modify the account
return true;
});
}
/// Using a pessimistic lock, updates the current profile version to `newVersion` if `currentProfileVersion` matches
/// `expectedCurrentVersion`. The caller may provide a supplementary `Consumer<Account>` for additional updates
///
/// @throws WriteConflictException if the expected current version does not match the current version
public Account updateCurrentProfileVersion(final UUID accountIdentifier, final byte[] newVersion,
final String expectedCurrentVersion, final Consumer<Account> updater) throws WriteConflictException {
Objects.requireNonNull(expectedCurrentVersion, "expectedCurrentVersion");
// Always fetch a fresh, non-cached copy of the account before making modifications
final Account account = accounts.getByAccountIdentifier(accountIdentifier)
.orElseThrow(() -> new IllegalArgumentException("Account not found: " + accountIdentifier));
final String newVersionHex = HexFormat.of().formatHex(newVersion);
return accountLockManager.withLock(Set.of(account.getPhoneNumberIdentifier()), () -> {
final Account maybeUpdatedAccount = update(accountIdentifier, a -> {
if (!a.getCurrentProfileVersion().orElse("").equals(expectedCurrentVersion)) {
return false;
}
a.setCurrentProfileVersion(newVersionHex);
updater.accept(a);
return true;
});
if (!maybeUpdatedAccount.getCurrentProfileVersion().map(v -> v.equals(newVersionHex)).orElse(false)) {
throw new WriteConflictException();
}
return maybeUpdatedAccount;
}, accountLockExecutor);
}
/**
* Specialized version of {@link #updateDevice(Account, byte, Consumer)} that minimizes potentially contentious and
* Specialized version of {@link #updateDevice(UUID, byte, Consumer)} that minimizes potentially contentious and
* redundant updates of {@code device.lastSeen}
*/
public Account updateDeviceLastSeen(Account account, Device device, final long lastSeen) {
return update(account, a -> {
public Account updateDeviceLastSeen(UUID accountIdentifier, Device device, final long lastSeen) {
return update(accountIdentifier, a -> {
final Optional<Device> maybeDevice = a.getDevice(device.getId());
@@ -957,27 +1017,17 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
});
}
public Account updateDeviceAuthentication(final Account account, final Device device, final SaltedTokenHash credentials) {
Preconditions.checkArgument(credentials.getVersion() == SaltedTokenHash.CURRENT_VERSION);
return updateDevice(account, device.getId(), device1 -> device1.setAuthTokenHash(credentials));
}
/**
* @param account account to update
* @param accountIdentifier identifier of account to update
* @param updater must return {@code true} if the account was actually updated
*/
private Account update(Account account, Function<Account, Boolean> updater) {
private Account update(UUID accountIdentifier, Function<Account, Boolean> updater) {
return updateTimer.record(() -> {
redisDelete(account);
final UUID uuid = account.getUuid();
final Account updatedAccount = updateWithRetries(account,
updater,
final Account updatedAccount = updateWithRetries(updater,
accounts::update,
() -> accounts.getByAccountIdentifier(uuid).orElseThrow(),
() -> accounts.getByAccountIdentifier(accountIdentifier).orElseThrow(),
AccountChangeValidator.GENERAL_CHANGE_VALIDATOR);
redisSet(updatedAccount);
@@ -986,49 +1036,38 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
});
}
private <E extends Exception> Account updateWithRetries(Account account,
final Function<Account, Boolean> updater,
private <E extends Exception> Account updateWithRetries(final Function<Account, Boolean> updater,
final ThrowingConsumer<Account, E> persister,
final Supplier<Account> retriever,
final AccountChangeValidator changeValidator) throws E {
Account originalAccount = AccountUtil.cloneAccountAsNotStale(account);
if (!updater.apply(account)) {
return account;
}
final int maxTries = 10;
int tries = 0;
while (tries < maxTries) {
try {
persister.accept(account);
final Account updatedAccount = AccountUtil.cloneAccountAsNotStale(account);
account.markStale();
changeValidator.validateChange(originalAccount, updatedAccount);
return updatedAccount;
} catch (final ContestedOptimisticLockException e) {
tries++;
account = retriever.get();
originalAccount = AccountUtil.cloneAccountAsNotStale(account);
final Account account = retriever.get();
final Account originalAccount = AccountUtil.cloneAccountAsNotStale(account);
if (!updater.apply(account)) {
return account;
}
persister.accept(account);
changeValidator.validateChange(originalAccount, account);
return account;
} catch (final ContestedOptimisticLockException e) {
tries++;
}
}
throw new OptimisticLockRetryLimitExceededException();
}
public Account updateDevice(Account account, byte deviceId, Consumer<Device> deviceUpdater) {
return update(account, a -> {
public Account updateDevice(final UUID accountIdentifier, byte deviceId, Consumer<Device> deviceUpdater) {
return update(accountIdentifier, a -> {
a.getDevice(deviceId).ifPresent(deviceUpdater);
// assume that all updaters passed to the public method actually modify the device
return true;
@@ -1097,6 +1136,22 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
);
}
/// Returns a fresh, uncached copy of the identified account (the account preparing to change its number) and a fresh,
/// uncached copy of the account that holds the target phone number if such an account exists.
///
/// @param accountIdentifier the identifier for the account changing its phone number
/// @param targetNumber the new phone number for the identified account
///
/// @return a fresh, uncached copy of the identified account and a fresh, uncached copy of the account that has
/// `targetNumber` if one exists
///
/// @throws IllegalArgumentException if no account was found for `accountIdentifier`
Pair<Account, Optional<Account>> getAccountsForChangeNumber(final UUID accountIdentifier, final String targetNumber) {
return new Pair<>(accounts.getByAccountIdentifier(accountIdentifier)
.orElseThrow(() -> new IllegalArgumentException("Account not found: " + accountIdentifier)),
accounts.getByE164(targetNumber));
}
public UUID getPhoneNumberIdentifier(String e164) {
return phoneNumberIdentifiers.getPhoneNumberIdentifier(e164).join();
}
@@ -1113,9 +1168,19 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
return accounts.getAll(segments, scheduler);
}
public void delete(final Account account, final DeletionReason deletionReason) {
public void delete(final UUID accountIdentifier, final DeletionReason deletionReason) {
final Timer.Sample sample = Timer.start();
final Optional<Account> maybeAccount = accounts.getByAccountIdentifier(accountIdentifier);
if (maybeAccount.isEmpty()) {
// In most cases, failing to find an account would be an error, but in this case, it's probably a sign that we've
// already succeeded in deleting the account and this is a spurious retry.
return;
}
final Account account = maybeAccount.get();
try {
accountLockManager.withLock(Set.of(account.getPhoneNumberIdentifier()), () -> {
delete(account);
@@ -1335,21 +1400,6 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
getAccountEntityKey(account.getUuid())))));
}
private CompletableFuture<Void> redisDeleteAsync(final Account account) {
final Timer.Sample sample = Timer.start();
final String[] keysToDelete = new String[]{
getAccountMapKey(account.getPhoneNumberIdentifier().toString()),
getAccountEntityKey(account.getUuid())
};
return ResilienceUtil.getGeneralRedisRetry(RETRY_NAME).executeCompletionStage(retryExecutor,
() -> cacheCluster.withCluster(connection -> connection.async().del(keysToDelete))
.thenRun(Util.NOOP))
.toCompletableFuture()
.whenComplete((_, _) -> sample.stop(redisDeleteTimer));
}
public CompletableFuture<Optional<DeviceInfo>> waitForNewLinkedDevice(
final UUID accountIdentifier,
final Device linkingDevice,
@@ -8,47 +8,109 @@ import java.time.Clock;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.Collectors;
import com.google.common.net.HttpHeaders;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import jakarta.ws.rs.container.ContainerRequestContext;
import org.signal.libsignal.protocol.IdentityKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.auth.PhoneVerificationTokenManager;
import org.whispersystems.textsecuregcm.auth.RegistrationLockVerificationManager;
import org.whispersystems.textsecuregcm.controllers.AccountControllerV2;
import org.whispersystems.textsecuregcm.controllers.MessageDeliveryNotAllowedException;
import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
import org.whispersystems.textsecuregcm.entities.IncomingMessage;
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
import org.whispersystems.textsecuregcm.entities.PhoneVerificationRequest;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.push.MessageSender;
import org.whispersystems.textsecuregcm.push.MessageTooLargeException;
import org.whispersystems.textsecuregcm.util.Pair;
import javax.annotation.Nullable;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
public class ChangeNumberManager {
private static final Logger logger = LoggerFactory.getLogger(ChangeNumberManager.class);
private final MessageSender messageSender;
private final AccountsManager accountsManager;
private final PhoneVerificationTokenManager phoneVerificationTokenManager;
private final RegistrationLockVerificationManager registrationLockVerificationManager;
private final RateLimiters rateLimiters;
private final Clock clock;
private static final Logger logger = LoggerFactory.getLogger(ChangeNumberManager.class);
// Note that this counter name references another class deliberately in the interest of metric continuity
private static final String CHANGE_NUMBER_COUNTER_NAME = name(AccountControllerV2.class, "changeNumber");
private static final String VERIFICATION_TYPE_TAG_NAME = "verification";
public ChangeNumberManager(
final MessageSender messageSender,
final AccountsManager accountsManager,
final PhoneVerificationTokenManager phoneVerificationTokenManager,
final RegistrationLockVerificationManager registrationLockVerificationManager,
final RateLimiters rateLimiters,
final Clock clock) {
this.messageSender = messageSender;
this.accountsManager = accountsManager;
this.phoneVerificationTokenManager = phoneVerificationTokenManager;
this.registrationLockVerificationManager = registrationLockVerificationManager;
this.rateLimiters = rateLimiters;
this.clock = clock;
}
public Account changeNumber(final Account account,
public Account changeNumber(final UUID accountIdentifier,
@Nullable final byte[] sessionId,
@Nullable final byte[] recoveryPassword,
@Nullable final String registrationLock,
final String number,
final IdentityKey pniIdentityKey,
final Map<Byte, ECSignedPreKey> deviceSignedPreKeys,
final Map<Byte, KEMSignedPreKey> devicePqLastResortPreKeys,
final List<IncomingMessage> deviceMessages,
final Map<Byte, Integer> pniRegistrationIds,
final String senderUserAgent)
throws InterruptedException, MismatchedDevicesException, MessageTooLargeException {
final ContainerRequestContext containerRequestContext)
throws InterruptedException, MismatchedDevicesException, MessageTooLargeException, RateLimitExceededException, MessageDeliveryNotAllowedException {
final String senderUserAgent = containerRequestContext.getHeaderString(HttpHeaders.USER_AGENT);
final Pair<Account, Optional<Account>> accountAndMaybeExistingAccount =
accountsManager.getAccountsForChangeNumber(accountIdentifier, number);
final Account account = accountAndMaybeExistingAccount.first();
// Only verify and check reglock if there's a data change to be made...
if (!account.getNumber().equals(number)) {
rateLimiters.getRegistrationLimiter().validate(number);
final PhoneVerificationRequest.VerificationType verificationType =
phoneVerificationTokenManager.verify(containerRequestContext, number, sessionId, recoveryPassword);
final Optional<Account> existingAccount = accountAndMaybeExistingAccount.second();
if (existingAccount.isPresent()) {
registrationLockVerificationManager.verifyRegistrationLock(existingAccount.get(), registrationLock,
senderUserAgent, RegistrationLockVerificationManager.Flow.CHANGE_NUMBER, verificationType);
}
Metrics.counter(CHANGE_NUMBER_COUNTER_NAME, Tags.of(UserAgentTagUtil.getPlatformTag(senderUserAgent),
Tag.of(VERIFICATION_TYPE_TAG_NAME, verificationType.name())))
.increment();
}
// ...but always attempt to make the change in case a client retries and needs to re-send messages
final long serverTimestamp = clock.millis();
final AciServiceIdentifier serviceIdentifier = new AciServiceIdentifier(account.getIdentifier(IdentityType.ACI));
@@ -80,13 +142,13 @@ public class ChangeNumberManager {
}
final Account updatedAccount = accountsManager.changeNumber(
account, number, pniIdentityKey, deviceSignedPreKeys, devicePqLastResortPreKeys, pniRegistrationIds);
account.getIdentifier(IdentityType.ACI), number, pniIdentityKey, deviceSignedPreKeys, devicePqLastResortPreKeys, pniRegistrationIds);
try {
// Now that we've actually updated the account, populate the "updated PNI" field on all envelopes
final String updatedPniString = updatedAccount.getIdentifier(IdentityType.PNI).toString();
messagesByDeviceId.replaceAll((deviceId, envelope) ->
messagesByDeviceId.replaceAll((_, envelope) ->
envelope.toBuilder().setUpdatedPni(updatedPniString).build());
messageSender.sendMessages(updatedAccount,
@@ -6,6 +6,7 @@
package org.whispersystems.textsecuregcm.storage;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
@@ -14,7 +15,8 @@ public enum DeviceCapability {
STORAGE("storage", AccountCapabilityMode.ANY_DEVICE, false, false, false),
TRANSFER("transfer", AccountCapabilityMode.PRIMARY_DEVICE, false, false, false),
ATTACHMENT_BACKFILL("attachmentBackfill", AccountCapabilityMode.PRIMARY_DEVICE, false, true, false),
SPARSE_POST_QUANTUM_RATCHET("spqr", AccountCapabilityMode.ALL_DEVICES, true, true, true);
SPARSE_POST_QUANTUM_RATCHET("spqr", AccountCapabilityMode.ALL_DEVICES, true, true, true),
PROFILES_V2("profiles_v2", AccountCapabilityMode.ALL_DEVICES, false, true, false);
public enum AccountCapabilityMode {
/**
@@ -36,42 +38,41 @@ public enum DeviceCapability {
ALWAYS_CAPABLE,
}
public static final Set<DeviceCapability> CAPABILITIES_REQUIRED_FOR_REGISTRATION =
Arrays.stream(DeviceCapability.values())
.filter(DeviceCapability::requireForRegistration)
.collect(Collectors.toSet());
public static final Set<DeviceCapability> CAPABILITIES_REQUIRED_FOR_NEW_DEVICES =
EnumSet.copyOf(Arrays.stream(DeviceCapability.values())
.filter(DeviceCapability::requireForNewDevices)
.collect(Collectors.toSet()));
private final String name;
private final AccountCapabilityMode accountCapabilityMode;
private final boolean preventDowngrade;
private final boolean includeInProfile;
private final boolean requireForRegistration;
private final boolean requireForNewDevices;
/**
* Create a DeviceCapability
*
* @param name The name of the device capability that clients will see
* @param accountCapabilityMode How to combine the constituent device's capabilities in the account to an overall
* account capability
* @param preventDowngrade If true, don't let linked devices join that don't have a device capability if the
* overall account has the capability. Most of the time this should only be used in
* conjunction with AccountCapabilityMode.ALL_DEVICES.
* @param includeInProfile Whether to return this capability on the account's profile. If false, the capability
* is only visible to the server.
* @param requireForRegistration If true, prevent account creation if the account's initial device does not have this
* capability
* @param name The name of the device capability that clients will see
* @param accountCapabilityMode How to combine the constituent device's capabilities in the account to an overall
* account capability
* @param preventDowngrade If true, don't let linked devices join that don't have a device capability if the
* overall account has the capability. Most of the time this should only be used in
* conjunction with AccountCapabilityMode.ALL_DEVICES.
* @param includeInProfile Whether to return this capability on the account's profile. If false, the capability
* is only visible to the server.
* @param requireForNewDevices If true, prevent device creation if the new device does not have this capability
*/
DeviceCapability(final String name,
final AccountCapabilityMode accountCapabilityMode,
final boolean preventDowngrade,
final boolean includeInProfile,
final boolean requireForRegistration) {
final boolean requireForNewDevices) {
this.name = name;
this.accountCapabilityMode = accountCapabilityMode;
this.preventDowngrade = preventDowngrade;
this.includeInProfile = includeInProfile;
this.requireForRegistration = requireForRegistration;
this.requireForNewDevices = requireForNewDevices;
}
public String getName() {
@@ -90,8 +91,8 @@ public enum DeviceCapability {
return includeInProfile;
}
public boolean requireForRegistration() {
return requireForRegistration;
public boolean requireForNewDevices() {
return requireForNewDevices;
}
public static Optional<DeviceCapability> forName(final String name) {
@@ -5,7 +5,7 @@
package org.whispersystems.textsecuregcm.storage;
public class KeyIdUtil {
public static final long MAX_KEY_ID = (1L << 32) - 1;
public static final long MAX_KEY_ID = (1L << 31) - 1;
public static final long MIN_KEY_ID = 0;
private KeyIdUtil(){}
@@ -311,7 +311,7 @@ public class MessagePersister implements Managed {
} else {
logger.warn("Failed to persist queue {}::{} due to overfull queue; will unlink device", accountUuid, deviceId);
return Mono.fromRunnable(() -> accountsManager.removeDevice(account, deviceId))
return Mono.fromRunnable(() -> accountsManager.removeDevice(accountUuid, deviceId))
.subscribeOn(persistQueueScheduler)
.then(Mono.empty());
}
@@ -19,9 +19,7 @@ import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.whispersystems.textsecuregcm.util.AsyncTimerUtil;
import org.whispersystems.textsecuregcm.util.AttributeValues;
import org.whispersystems.textsecuregcm.util.Util;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
@@ -31,6 +29,8 @@ import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest;
import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
import software.amazon.awssdk.services.dynamodb.model.GetItemResponse;
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem;
import software.amazon.awssdk.services.dynamodb.model.Update;
import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;
public class Profiles {
@@ -93,7 +93,7 @@ public class Profiles {
this.tableName = tableName;
}
public void set(final UUID uuid, final VersionedProfile profile) {
public void set(final UUID uuid, final VersionedProfileV1 profile) {
SET_PROFILES_TIMER.record(() -> {
dynamoDbClient.updateItem(UpdateItemRequest.builder()
.tableName(tableName)
@@ -105,16 +105,17 @@ public class Profiles {
});
}
public CompletableFuture<Void> setAsync(final UUID uuid, final VersionedProfile profile) {
return AsyncTimerUtil.record(SET_PROFILES_TIMER, () -> dynamoDbAsyncClient.updateItem(UpdateItemRequest.builder()
/// Used to update a profile during the v2 migration.
public TransactWriteItem getTransactWriteItem(final UUID uuid, final VersionedProfileV1 profile) {
return TransactWriteItem.builder()
.update(Update.builder()
.tableName(tableName)
.key(buildPrimaryKey(uuid, profile.version()))
.updateExpression(buildUpdateExpression(profile))
.expressionAttributeNames(UPDATE_EXPRESSION_ATTRIBUTE_NAMES)
.expressionAttributeValues(buildUpdateExpressionAttributeValues(profile))
.build()
).thenRun(Util.NOOP)
).toCompletableFuture();
.build())
.build();
}
private static Map<String, AttributeValue> buildPrimaryKey(final UUID uuid, final String version) {
@@ -124,7 +125,7 @@ public class Profiles {
}
@VisibleForTesting
static String buildUpdateExpression(final VersionedProfile profile) {
static String buildUpdateExpression(final VersionedProfileV1 profile) {
final List<String> updatedAttributes = new ArrayList<>(5);
final List<String> deletedAttributes = new ArrayList<>(5);
@@ -186,7 +187,7 @@ public class Profiles {
}
@VisibleForTesting
static Map<String, AttributeValue> buildUpdateExpressionAttributeValues(final VersionedProfile profile) {
static Map<String, AttributeValue> buildUpdateExpressionAttributeValues(final VersionedProfileV1 profile) {
final Map<String, AttributeValue> expressionValues = new HashMap<>();
expressionValues.put(":commitment", AttributeValues.fromByteArray(profile.commitment()));
@@ -217,7 +218,7 @@ public class Profiles {
return expressionValues;
}
public Optional<VersionedProfile> get(final UUID uuid, final String version) {
public Optional<VersionedProfileV1> get(final UUID uuid, final String version) {
return GET_PROFILE_TIMER.record(() -> {
final GetItemResponse response = dynamoDbClient.getItem(GetItemRequest.builder()
.tableName(tableName)
@@ -229,19 +230,8 @@ public class Profiles {
});
}
public CompletableFuture<Optional<VersionedProfile>> getAsync(final UUID uuid, final String version) {
return AsyncTimerUtil.record(GET_PROFILE_TIMER, () -> dynamoDbAsyncClient.getItem(GetItemRequest.builder()
.tableName(tableName)
.key(buildPrimaryKey(uuid, version))
.consistentRead(true)
.build())
.thenApply(response ->
response.hasItem() ? Optional.of(fromItem(response.item())) : Optional.<VersionedProfile>empty())
).toCompletableFuture();
}
private static VersionedProfile fromItem(final Map<String, AttributeValue> item) {
return new VersionedProfile(
private static VersionedProfileV1 fromItem(final Map<String, AttributeValue> item) {
return new VersionedProfileV1(
AttributeValues.getString(item, ATTR_VERSION, null),
getBytes(item, ATTR_NAME),
AttributeValues.getString(item, ATTR_AVATAR, null),
@@ -11,22 +11,25 @@ import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.annotations.VisibleForTesting;
import io.lettuce.core.RedisException;
import io.lettuce.core.ScriptOutputType;
import io.micrometer.core.instrument.Metrics;
import java.io.IOException;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ScheduledExecutorService;
import java.util.function.Function;
import javax.annotation.Nullable;
import io.micrometer.core.instrument.Metrics;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import org.whispersystems.textsecuregcm.util.ResilienceUtil;
import org.whispersystems.textsecuregcm.util.SystemMapper;
import org.whispersystems.textsecuregcm.util.Util;
import reactor.core.publisher.Mono;
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.model.DeleteObjectRequest;
@@ -34,40 +37,90 @@ public class ProfilesManager {
private final Logger logger = LoggerFactory.getLogger(ProfilesManager.class);
private static final String CACHE_PREFIX = "profiles::";
private static final String CACHE_PREFIX_V1 = "profiles_v1::";
private static final String CACHE_PREFIX_V2 = "profiles_v2::";
private final Profiles profiles;
private static final byte[] EMPTY = new byte[0];
private final Profiles profilesV1;
private final ProfilesV2 profilesV2;
private final FaultTolerantRedisClusterClient cacheCluster;
private final ScheduledExecutorService retryExecutor;
private final S3AsyncClient s3Client;
private final String bucket;
private final ClusterLuaScript setLuaScript;
private final ObjectMapper mapper;
private static final String RETRY_NAME = ResilienceUtil.name(ProfilesManager.class);
private static final String DELETE_AVATAR_COUNTER_NAME = name(ProfilesManager.class, "deleteAvatar");
public ProfilesManager(final Profiles profiles,
public ProfilesManager(final Profiles profilesV1,
final ProfilesV2 profilesV2,
final FaultTolerantRedisClusterClient cacheCluster,
final ScheduledExecutorService retryExecutor,
final S3AsyncClient s3Client,
final String bucket) {
this.profiles = profiles;
final String bucket) throws IOException {
this(profilesV1, profilesV2, cacheCluster, retryExecutor, s3Client, bucket,
ClusterLuaScript.fromResource(cacheCluster, "lua/profile_set.lua", ScriptOutputType.STATUS));
}
@VisibleForTesting
ProfilesManager(final Profiles profilesV1,
final ProfilesV2 profilesV2,
final FaultTolerantRedisClusterClient cacheCluster,
final ScheduledExecutorService retryExecutor,
final S3AsyncClient s3Client,
final String bucket,
final ClusterLuaScript setLuaScript) {
this.profilesV1 = profilesV1;
this.profilesV2 = profilesV2;
this.cacheCluster = cacheCluster;
this.retryExecutor = retryExecutor;
this.s3Client = s3Client;
this.bucket = bucket;
this.setLuaScript = setLuaScript;
this.mapper = SystemMapper.jsonMapper();
}
public void set(UUID uuid, VersionedProfile versionedProfile) {
redisSet(uuid, versionedProfile);
profiles.set(uuid, versionedProfile);
public void setV1(UUID uuid, VersionedProfileV1 versionedProfile) {
redisDelete(uuid);
profilesV1.set(uuid, versionedProfile);
redisSet(uuid, null, versionedProfile);
try {
// until the PROFILES_V2 capability prevents downgrades, if a client sets a v2 profile, and then the account
// downgrades to v1, all v2 profiles are stale
assert !DeviceCapability.PROFILES_V2.preventDowngrade();
profilesV2.deleteAll(uuid);
} catch (final Exception e) {
logger.warn("Failed to delete v2 profile data: {}", uuid, e);
}
}
public CompletableFuture<Void> setAsync(UUID uuid, VersionedProfile versionedProfile) {
return profiles.setAsync(uuid, versionedProfile)
.thenCompose(ignored -> redisSetAsync(uuid, versionedProfile));
/// Transactionally sets v1 and v2 Profile data in DynamoDB.
///
/// Note: writes to the Redis cache are not transactional, and a failed DynamoDB write may leave incorrect data in Redis
public void set(UUID uuid, VersionedProfileV1 versionedProfileV1, VersionedProfile versionedProfile, @Nullable byte[] expectedCurrentDataHash) throws WriteConflictException {
final TransactWriteItem v1TransactWriteItem = profilesV1.getTransactWriteItem(uuid, versionedProfileV1);
redisDelete(uuid);
profilesV2.set(uuid,
versionedProfile.version(),
versionedProfile.data(),
versionedProfile.dataHash(),
versionedProfile.commitment(),
versionedProfile.paymentAddress(),
versionedProfile.paymentAddressHash(),
expectedCurrentDataHash,
v1TransactWriteItem);
redisSet(uuid, versionedProfile, versionedProfileV1);
}
/**
@@ -78,7 +131,7 @@ public class ProfilesManager {
*/
public CompletableFuture<Void> deleteAll(UUID uuid, final boolean includeAvatar) {
final CompletableFuture<Void> profilesAndAvatars = Mono.fromFuture(profiles.deleteAll(uuid))
final CompletableFuture<Void> profilesV1AndAvatars = Mono.fromFuture(profilesV1.deleteAll(uuid))
.flatMapIterable(Function.identity())
.flatMap(avatar ->
Mono.fromFuture(includeAvatar ? deleteAvatar(avatar) : CompletableFuture.completedFuture(null))
@@ -87,7 +140,7 @@ public class ProfilesManager {
.onErrorComplete())
.then().toFuture();
return CompletableFuture.allOf(redisDelete(uuid), profilesAndAvatars);
return CompletableFuture.allOf(redisDeleteAsync(uuid), profilesV1AndAvatars, profilesV2.deleteAll(uuid));
}
public CompletableFuture<Void> deleteAvatar(String avatar) {
@@ -110,87 +163,99 @@ public class ProfilesManager {
.thenRun(Util.NOOP);
}
public Optional<VersionedProfile> get(UUID uuid, String version) {
Optional<VersionedProfile> profile = redisGet(uuid, version);
if (profile.isEmpty()) {
profile = profiles.get(uuid, version);
public Optional<VersionedProfileV1> getV1(UUID uuid, String version) {
return redisGetV1(uuid, version).or(() -> {
final Optional<VersionedProfileV1> profile = profilesV1.get(uuid, version);
try {
profile.ifPresent(versionedProfile -> redisSet(uuid, versionedProfile));
profile.ifPresent(versionedProfile -> redisSet(uuid, null, versionedProfile));
} catch (RedisException e) {
logger.warn("Failed to cache retrieved profile", e);
}
}
return profile;
return profile;
});
}
public CompletableFuture<Optional<VersionedProfile>> getAsync(UUID uuid, String version) {
return redisGetAsync(uuid, version)
.thenCompose(maybeVersionedProfile -> maybeVersionedProfile
.map(versionedProfile -> CompletableFuture.completedFuture(maybeVersionedProfile))
.orElseGet(() -> profiles.getAsync(uuid, version)
.thenCompose(maybeVersionedProfileFromDynamo -> maybeVersionedProfileFromDynamo
.map(profile -> redisSetAsync(uuid, profile)
.exceptionally(ExceptionUtils.exceptionallyHandler(RedisException.class, e -> {
logger.warn("Failed to cache retrieved profile", e);
return null;
}))
.thenApply(ignored -> maybeVersionedProfileFromDynamo))
.orElseGet(() -> CompletableFuture.completedFuture(maybeVersionedProfileFromDynamo)))));
public Optional<VersionedProfile> get(UUID uuid, byte[] version) {
return redisGet(uuid, version).or(() -> {
final Optional<VersionedProfile> profile = profilesV2.get(uuid, version);
try {
profile.ifPresent(versionedProfile -> redisSet(uuid, versionedProfile, null));
} catch (RedisException e) {
logger.warn("Failed to cache retrieved profile", e);
}
return profile;
});
}
private void redisSet(UUID uuid, VersionedProfile profile) {
@VisibleForTesting
void redisSet(UUID uuid, @Nullable VersionedProfile v2Profile, @Nullable VersionedProfileV1 v1Profile) {
try {
final String profileJson = mapper.writeValueAsString(profile);
if (v1Profile == null && v2Profile == null) {
logger.error("Expected at least one profile");
return;
}
final byte[] v1ProfileVersion;
final byte[] v1ProfileBytes;
if (v1Profile != null) {
v1ProfileVersion = v1Profile.version().getBytes();
v1ProfileBytes = mapper.writeValueAsBytes(v1Profile);
} else {
v1ProfileVersion = EMPTY;
v1ProfileBytes = EMPTY;
}
final byte[] v2ProfileVersion;
final byte[] v2ProfileBytes;
if (v2Profile != null) {
v2ProfileVersion = v2Profile.version();
v2ProfileBytes = mapper.writeValueAsBytes(v2Profile);
} else {
v2ProfileVersion = EMPTY;
v2ProfileBytes = EMPTY;
}
setLuaScript.executeBinary(List.of(getCacheKeyV1(uuid), getCacheKeyV2(uuid)),
List.of(v1ProfileVersion, v1ProfileBytes, v2ProfileVersion, v2ProfileBytes));
cacheCluster.useCluster(connection -> connection.sync().hset(getCacheKey(uuid), profile.version(), profileJson));
} catch (JsonProcessingException e) {
throw new IllegalArgumentException(e);
}
}
private CompletableFuture<Void> redisSetAsync(UUID uuid, VersionedProfile profile) {
final String profileJson;
private Optional<VersionedProfile> redisGet(UUID uuid, byte[] version) {
try {
profileJson = mapper.writeValueAsString(profile);
} catch (JsonProcessingException e) {
throw new IllegalArgumentException(e);
}
@Nullable final byte[] json = cacheCluster.withBinaryCluster(connection -> connection.sync().hget(getCacheKeyV2(uuid), version));
return cacheCluster.withCluster(connection ->
connection.async().hset(getCacheKey(uuid), profile.version(), profileJson))
.thenRun(Util.NOOP)
.toCompletableFuture();
return parseProfileJson(json, VersionedProfile.class);
} catch (RedisException e) {
logger.warn("Redis exception", e);
return Optional.empty();
}
}
private Optional<VersionedProfile> redisGet(UUID uuid, String version) {
try {
@Nullable final String json = cacheCluster.withCluster(connection -> connection.sync().hget(getCacheKey(uuid), version));
@VisibleForTesting
static byte[] getCacheKeyV2(UUID uuid) {
return (CACHE_PREFIX_V2 + '{' + uuid.toString() + '}').getBytes();
}
return parseProfileJson(json);
private Optional<VersionedProfileV1> redisGetV1(UUID uuid, String version) {
try {
@Nullable final byte[] json = cacheCluster.withBinaryCluster(connection -> connection.sync().hget(getCacheKeyV1(uuid), version.getBytes()));
return parseProfileJson(json, VersionedProfileV1.class);
} catch (RedisException e) {
logger.warn("Failed to retrieve profile from cache", e);
return Optional.empty();
}
}
private CompletableFuture<Optional<VersionedProfile>> redisGetAsync(UUID uuid, String version) {
return cacheCluster.withCluster(connection ->
connection.async().hget(getCacheKey(uuid), version))
.thenApply(this::parseProfileJson)
.exceptionally(throwable -> {
logger.warn("Failed to read versioned profile from Redis", throwable);
return Optional.empty();
})
.toCompletableFuture();
}
private Optional<VersionedProfile> parseProfileJson(@Nullable final String maybeJson) {
private <T> Optional<T> parseProfileJson(@Nullable final byte[] maybeJson, Class<T> klass) {
try {
if (maybeJson != null) {
return Optional.of(mapper.readValue(maybeJson, VersionedProfile.class));
return Optional.of(mapper.readValue(maybeJson, klass));
}
return Optional.empty();
} catch (final IOException e) {
@@ -199,16 +264,23 @@ public class ProfilesManager {
}
}
private CompletableFuture<Void> redisDelete(UUID uuid) {
private void redisDelete(UUID uuid) {
ResilienceUtil.getGeneralRedisRetry(RETRY_NAME)
.executeRunnable(() -> cacheCluster.withBinaryCluster(
connection -> connection.sync().del(getCacheKeyV1(uuid), getCacheKeyV2(uuid))));
}
private CompletableFuture<Void> redisDeleteAsync(UUID uuid) {
return ResilienceUtil.getGeneralRedisRetry(RETRY_NAME)
.executeCompletionStage(retryExecutor,
() -> cacheCluster.withCluster(connection -> connection.async().del(getCacheKey(uuid))))
() -> cacheCluster.withBinaryCluster(connection -> connection.async().del(getCacheKeyV1(uuid), getCacheKeyV2(uuid))))
.toCompletableFuture()
.thenRun(Util.NOOP);
}
@VisibleForTesting
static String getCacheKey(UUID uuid) {
return CACHE_PREFIX + uuid.toString();
static byte[] getCacheKeyV1(UUID uuid) {
return (CACHE_PREFIX_V1 + '{' + uuid.toString() + '}').getBytes();
}
}
@@ -0,0 +1,342 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import com.google.common.annotations.VisibleForTesting;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Timer;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import javax.annotation.Nullable;
import org.whispersystems.textsecuregcm.util.AttributeValues;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.CancellationReason;
import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest;
import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
import software.amazon.awssdk.services.dynamodb.model.GetItemResponse;
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
import software.amazon.awssdk.services.dynamodb.model.ReturnValuesOnConditionCheckFailure;
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem;
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItemsRequest;
import software.amazon.awssdk.services.dynamodb.model.TransactionCanceledException;
import software.amazon.awssdk.services.dynamodb.model.Update;
public class ProfilesV2 {
private static final String CONDITIONAL_CHECK_FAILED_CODE = "ConditionalCheckFailed";
private static final String TRANSACTION_CONFLICT_CODE = "TransactionConflict";
private final DynamoDbClient dynamoDbClient;
private final DynamoDbAsyncClient dynamoDbAsyncClient;
private final String tableName;
// UUID of the account that owns this profile; hash key; byte array
@VisibleForTesting
static final String KEY_ACCOUNT_UUID = "U";
// Version of this profile; sort key; byte array
@VisibleForTesting
static final String KEY_VERSION = "V";
// Profile data (serialized ciphertext); byte array
private static final String ATTR_DATA = "D";
// SHA-256 hash of data attribute; byte array
private static final String ATTR_DATA_HASH = "DH";
// Commitment; byte array
private static final String ATTR_COMMITMENT = "C";
// Payment address; byte array
private static final String ATTR_PAYMENT_ADDRESS = "P";
// SHA-256 hash of payment address attribute; byte array
private static final String ATTR_PAYMENT_ADDRESS_HASH = "PH";
private static final Map<String, String> UPDATE_EXPRESSION_ATTRIBUTE_NAMES = Map.of(
"#data", ATTR_DATA,
"#dataHash", ATTR_DATA_HASH,
"#commitment", ATTR_COMMITMENT,
"#paymentAddress", ATTR_PAYMENT_ADDRESS,
"#paymentAddressHash", ATTR_PAYMENT_ADDRESS_HASH);
private static final Timer SET_PROFILES_TIMER = Metrics.timer(name(ProfilesV2.class, "set"));
private static final Timer GET_PROFILE_TIMER = Metrics.timer(name(ProfilesV2.class, "get"));
private static final String DELETE_PROFILES_TIMER_NAME = name(ProfilesV2.class, "delete");
private static final String WRITE_CONFLICTS_COUNTER_NAME = name(ProfilesV2.class, "writeConflicts");
private static final int COMMITMENT_LENGTH = 97;
private static final int DELETE_MAX_CONCURRENCY = 32;
public ProfilesV2(final DynamoDbClient dynamoDbClient,
final DynamoDbAsyncClient dynamoDbAsyncClient,
final String tableName) {
this.dynamoDbClient = dynamoDbClient;
this.dynamoDbAsyncClient = dynamoDbAsyncClient;
this.tableName = tableName;
}
/// Put a profile version with the given data
///
/// During the migration from v1 &rarr; v2, both updates are executed transactionally
///
/// @param uuid the account UUID
/// @param version the profile version
/// @param data serialized profile ciphertext
/// @param commitment serialized profile key commitment (required for initial write, optional for updates)
/// @param paymentAddress serialized payment address ciphertext (nullable)
/// @param expectedCurrentDataHash the expected current data hash, used for conditional update (nullable for the initial write)
/// @param profileV1TransactWriteItem transact write item for v1 profile during migration
/// @throws WriteConflictException if the expected data hash does not match the stored data hash
/// @throws IllegalArgumentException if commitment is null on initial write or commitment does not match on an update
/// @throws IllegalStateException if commitment is missing after a write
public void set(final UUID uuid,
final byte[] version,
final byte[] data,
final byte[] dataHash,
@Nullable final byte[] commitment,
@Nullable final byte[] paymentAddress,
@Nullable final byte[] paymentAddressHash,
@Nullable final byte[] expectedCurrentDataHash,
final TransactWriteItem profileV1TransactWriteItem) throws WriteConflictException {
// Commitment is required for initial write (when expectedCurrentDataHash is null)
if (expectedCurrentDataHash == null && commitment == null) {
throw new IllegalArgumentException("Commitment is required for initial write");
}
final Timer.Sample sample = Timer.start();
try {
final List<TransactWriteItem> transactWriteItems = List.of(
getTransactWriteItem(uuid, version, data, dataHash, commitment, paymentAddress, paymentAddressHash, expectedCurrentDataHash),
profileV1TransactWriteItem);
dynamoDbClient.transactWriteItems(TransactWriteItemsRequest.builder()
.transactItems(transactWriteItems)
.build());
} catch (TransactionCanceledException e) {
if (e.hasCancellationReasons()) {
// check for fields with conditional check failures
if (e.cancellationReasons().getFirst() != null
&& e.cancellationReasons().getFirst().code().equals(CONDITIONAL_CHECK_FAILED_CODE)
&& e.cancellationReasons().getFirst().hasItem()) {
final Map<String, AttributeValue> item = e.cancellationReasons().getFirst().item();
final byte[] oldCommitment = AttributeValues.getByteArray(item, ATTR_COMMITMENT, null);
if (oldCommitment != null && commitment != null && !Arrays.equals(oldCommitment, commitment)) {
throw new IllegalArgumentException("Commitment is immutable");
}
if (oldCommitment == null && commitment == null) {
throw new IllegalStateException("Commitment is absent from existing profile");
}
}
final Optional<String> cancellationCode = e.cancellationReasons().stream()
.map(CancellationReason::code)
.filter(code -> CONDITIONAL_CHECK_FAILED_CODE.equals(code) || TRANSACTION_CONFLICT_CODE.equals(code))
.findFirst();
if (cancellationCode.isPresent()) {
// any other conditional check failure is an expected data hash mismatch, which is a write conflict
Metrics.counter(WRITE_CONFLICTS_COUNTER_NAME, "code", cancellationCode.get()).increment();
throw new WriteConflictException();
}
}
throw e;
} finally {
sample.stop(SET_PROFILES_TIMER);
}
}
/// Get a [TransactWriteItem] for a profile update during the v2 migration
///
/// @param uuid the account UUID
/// @param version the profile version
/// @param data the serialized profile ciphertext
/// @param dataHash the serialized profile ciphertext hash
/// @param commitment the profile key commitment (required for initial write, optional for updates)
/// @param paymentAddress the payment address (nullable; will clear existing value for this version if null)
/// @param paymentAddressHash the payment address hash (nullable; will clear existing value for this version if null)
/// @param expectedCurrentDataHash the expected current data hash for conditional update (nullable for first write)
/// @return a [TransactWriteItem] containing the Update operation
@VisibleForTesting
TransactWriteItem getTransactWriteItem(final UUID uuid,
final byte[] version,
final byte[] data,
final byte[] dataHash,
@Nullable final byte[] commitment,
@Nullable final byte[] paymentAddress,
@Nullable final byte[] paymentAddressHash,
@Nullable final byte[] expectedCurrentDataHash) {
return TransactWriteItem.builder()
.update(Update.builder()
.tableName(tableName)
.key(buildPrimaryKey(uuid, version))
.updateExpression(buildUpdateExpression(commitment != null, paymentAddress != null))
.conditionExpression(buildConditionExpression(commitment != null, expectedCurrentDataHash != null))
.expressionAttributeNames(UPDATE_EXPRESSION_ATTRIBUTE_NAMES)
.expressionAttributeValues(buildUpdateExpressionAttributeValues(data, dataHash, commitment, paymentAddress, paymentAddressHash, expectedCurrentDataHash))
.returnValuesOnConditionCheckFailure(ReturnValuesOnConditionCheckFailure.ALL_OLD)
.build())
.build();
}
private static Map<String, AttributeValue> buildPrimaryKey(final UUID uuid, final byte[] version) {
return Map.of(
KEY_ACCOUNT_UUID, AttributeValues.fromUUID(uuid),
KEY_VERSION, AttributeValues.fromByteArray(version));
}
@VisibleForTesting
static String buildUpdateExpression(final boolean hasCommitment, final boolean hasPaymentAddress) {
final StringBuilder updateExpressionBuilder = new StringBuilder("SET #data = :data, #dataHash = :dataHash");
if (hasCommitment) {
updateExpressionBuilder.append(", #commitment = if_not_exists(#commitment, :commitment)");
}
if (hasPaymentAddress) {
updateExpressionBuilder.append(", #paymentAddress = :paymentAddress, #paymentAddressHash = :paymentAddressHash");
} else {
updateExpressionBuilder.append(" REMOVE #paymentAddress, #paymentAddressHash");
}
return updateExpressionBuilder.toString();
}
@VisibleForTesting
static String buildConditionExpression(final boolean hasCommitment, final boolean hasExpectedCurrentDataHash) {
final StringBuilder sb = new StringBuilder();
if (hasCommitment) {
sb.append("(attribute_not_exists(#commitment) OR #commitment = :commitment)");
} else {
sb.append("size(#commitment) = :commitment_length");
}
if (hasExpectedCurrentDataHash) {
// If expected hash is provided, verify it matches the stored hash
sb.append(" AND #dataHash = :expectedDataHash");
} else {
// Initial write: dataHash must not exist
sb.append(" AND attribute_not_exists(#dataHash)");
}
return sb.toString();
}
@VisibleForTesting
static Map<String, AttributeValue> buildUpdateExpressionAttributeValues(
final byte[] data,
final byte[] dataHash,
@Nullable final byte[] commitment,
@Nullable final byte[] paymentAddress,
@Nullable final byte[] paymentAddressHash,
@Nullable final byte[] expectedCurrentDataHash) {
final Map<String, AttributeValue> expressionValues = new HashMap<>();
expressionValues.put(":data", AttributeValues.fromByteArray(data));
expressionValues.put(":dataHash", AttributeValues.fromByteArray(dataHash));
if (commitment != null) {
expressionValues.put(":commitment", AttributeValues.fromByteArray(commitment));
} else {
expressionValues.put(":commitment_length", AttributeValues.fromInt(COMMITMENT_LENGTH));
}
if (paymentAddress != null) {
expressionValues.put(":paymentAddress", AttributeValues.fromByteArray(paymentAddress));
expressionValues.put(":paymentAddressHash", AttributeValues.fromByteArray(paymentAddressHash));
}
if (expectedCurrentDataHash != null) {
expressionValues.put(":expectedDataHash", AttributeValues.fromByteArray(expectedCurrentDataHash));
}
return expressionValues;
}
/// Fetch a profile version
///
/// @param uuid the account UUID
/// @param version the profile version
/// @return the VersionedProfile, if found
public Optional<VersionedProfile> get(final UUID uuid, final byte[] version) {
return GET_PROFILE_TIMER.record(() -> {
final GetItemResponse response = dynamoDbClient.getItem(GetItemRequest.builder()
.tableName(tableName)
.key(buildPrimaryKey(uuid, version))
.consistentRead(true)
.build());
return response.hasItem() ? Optional.of(fromItem(response.item())) : Optional.empty();
});
}
private static VersionedProfile fromItem(final Map<String, AttributeValue> item) {
return new VersionedProfile(
Objects.requireNonNull(AttributeValues.getByteArray(item, KEY_VERSION, null)),
Objects.requireNonNull(AttributeValues.getByteArray(item, ATTR_DATA, null)),
Objects.requireNonNull(AttributeValues.getByteArray(item, ATTR_DATA_HASH, null)),
AttributeValues.getByteArray(item, ATTR_PAYMENT_ADDRESS, null),
AttributeValues.getByteArray(item, ATTR_PAYMENT_ADDRESS_HASH, null),
Objects.requireNonNull(AttributeValues.getByteArray(item, ATTR_COMMITMENT, null)));
}
/// Deletes all profile versions for the given UUID.
///
/// @param uuid the account UUID
/// @return a CompletableFuture that completes when all versions have been deleted
public CompletableFuture<Void> deleteAll(final UUID uuid) {
final Timer.Sample sample = Timer.start();
final AttributeValue uuidAttributeValue = AttributeValues.fromUUID(uuid);
return Flux.from(dynamoDbAsyncClient.queryPaginator(QueryRequest.builder()
.tableName(tableName)
.keyConditionExpression("#uuid = :uuid")
.expressionAttributeNames(Map.of("#uuid", KEY_ACCOUNT_UUID))
.expressionAttributeValues(Map.of(":uuid", uuidAttributeValue))
.projectionExpression(KEY_VERSION)
.consistentRead(true)
.build())
.items())
.flatMap(item -> Mono.fromFuture(() -> dynamoDbAsyncClient.deleteItem(DeleteItemRequest.builder()
.tableName(tableName)
.key(Map.of(
KEY_ACCOUNT_UUID, uuidAttributeValue,
KEY_VERSION, item.get(KEY_VERSION)))
.build())), DELETE_MAX_CONCURRENCY)
.then()
.doOnSuccess(_ -> sample.stop(Metrics.timer(DELETE_PROFILES_TIMER_NAME, "outcome", "success")))
.doOnError(_ -> sample.stop(Metrics.timer(DELETE_PROFILES_TIMER_NAME, "outcome", "error")))
.toFuture();
}
}
@@ -0,0 +1,9 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage;
public class UnexpectedExistingPhoneNumberException extends RuntimeException {
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2020 Signal Messenger, LLC
* Copyright 2013 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
@@ -7,34 +7,77 @@ package org.whispersystems.textsecuregcm.storage;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.google.common.annotations.VisibleForTesting;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Objects;
import javax.annotation.Nullable;
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
import org.whispersystems.textsecuregcm.util.ByteArrayBase64WithPaddingAdapter;
public record VersionedProfile (String version,
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
byte[] name,
public record VersionedProfile(@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
byte[] version,
@Nullable
String avatar,
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
byte[] data,
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
byte[] aboutEmoji,
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
byte[] dataHash,
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
byte[] about,
@Nullable
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
byte[] paymentAddress,
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
byte[] paymentAddress,
@Nullable
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
byte[] paymentAddressHash,
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
byte[] phoneNumberSharing,
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
byte[] commitment) {
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
byte[] commitment) {}
public VersionedProfile(byte[] version, byte[] data, @Nullable byte[] paymentAddress, byte[] commitment) {
this(Objects.requireNonNull(version), Objects.requireNonNull(data), hash(Objects.requireNonNull(data)), paymentAddress, paymentAddress == null ? null : hash(paymentAddress), Objects.requireNonNull(commitment));
}
@Override
public boolean equals(final Object o) {
if (!(o instanceof final VersionedProfile that))
return false;
return Arrays.equals(data, that.data) && Arrays.equals(version, that.version) && Arrays.equals(dataHash,
that.dataHash) && Arrays.equals(commitment, that.commitment) && Arrays.equals(paymentAddress,
that.paymentAddress) && Arrays.equals(paymentAddressHash, that.paymentAddressHash);
}
@Override
public int hashCode() {
return Objects.hash(
Arrays.hashCode(version),
Arrays.hashCode(data),
Arrays.hashCode(dataHash),
Arrays.hashCode(paymentAddress),
Arrays.hashCode(paymentAddressHash),
Arrays.hashCode(commitment));
}
/**
* Computes the SHA-256 hash of the given data.
*/
@VisibleForTesting
static byte[] hash(final byte[] data) {
final MessageDigest sha256;
try {
sha256 = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
throw new AssertionError(e);
}
return sha256.digest(data);
}
}
@@ -0,0 +1,67 @@
/*
* Copyright 2013 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import javax.annotation.Nullable;
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
import org.whispersystems.textsecuregcm.util.ByteArrayBase64WithPaddingAdapter;
import java.util.Arrays;
import java.util.Objects;
public record VersionedProfileV1(String version,
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
byte[] name,
@Nullable
String avatar,
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
byte[] aboutEmoji,
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
byte[] about,
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
byte[] paymentAddress,
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
byte[] phoneNumberSharing,
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
byte[] commitment) {
@Override
public boolean equals(final Object o) {
if (!(o instanceof final VersionedProfileV1 that))
return false;
return Arrays.equals(name, that.name) && Arrays.equals(about, that.about) && Objects.equals(avatar, that.avatar)
&& Objects.equals(version, that.version) && Arrays.equals(aboutEmoji, that.aboutEmoji) && Arrays.equals(
commitment, that.commitment) && Arrays.equals(paymentAddress, that.paymentAddress) && Arrays.equals(
phoneNumberSharing, that.phoneNumberSharing);
}
@Override
public int hashCode() {
return Objects.hash(
version,
Arrays.hashCode(name),
Objects.hashCode(avatar),
Arrays.hashCode(aboutEmoji),
Arrays.hashCode(about),
Arrays.hashCode(paymentAddress),
Arrays.hashCode(phoneNumberSharing),
Arrays.hashCode(commitment));
}
}
@@ -0,0 +1,11 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage;
import org.whispersystems.textsecuregcm.util.NoStackTraceException;
public class WriteConflictException extends NoStackTraceException {
}
@@ -206,7 +206,9 @@ public class AppleDeviceCheckManager {
}
// Store the updated sign count, so we can check the next assertion (step 6)
appleDeviceChecks.updateCounter(account, keyId, appleDevice.getCounter());
if (!appleDeviceChecks.updateCounter(account, keyId, appleDevice.getCounter())) {
throw new RequestReuseException("Sign count from request less than stored sign count");
}
removeChallenge(redisChallengeKey);
}
@@ -0,0 +1,350 @@
package org.whispersystems.textsecuregcm.storage.foundationdb;
import com.apple.foundationdb.Database;
import com.apple.foundationdb.KeySelector;
import com.apple.foundationdb.StreamingMode;
import com.apple.foundationdb.Transaction;
import com.google.protobuf.InvalidProtocolBufferException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.storage.MessageStreamEntry;
import org.whispersystems.textsecuregcm.util.Pair;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
import reactor.core.publisher.Flux;
import reactor.core.publisher.FluxSink;
import javax.annotation.Nullable;
import java.io.UncheckedIOException;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.function.BiConsumer;
/// Publishes a message stream from a device queue in FoundationDB. Capable of publishing both a finite stream for
/// catching up to end-of-queue,and an infinite stream for live updates.
class FoundationDbMessagePublisher {
private final Database database;
private final MessageGuidCodec messageGuidCodec;
/// The maximum number of messages we will fetch per range query operation to avoid excessive memory consumption
private final int maxMessagesPerScan;
/// The end key at which we stop reading messages. For finite publisher, this is just past the end-of-queue key at the
/// time the publisher was created. For an infinite publisher, this is the end of subspace range.
private final KeySelector endKeyExclusive;
/// Keeps track of the key from which to start reading on the next iteration
private volatile KeySelector beginKeyCursor;
enum State {
/// Messages are likely available in the queue. Initial state.
MESSAGES_AVAILABLE,
/// We're actively fetching messages from FoundationDB.
FETCHING_MESSAGES,
/// We have read all available messages in the queue.
QUEUE_EMPTY,
/// The message available watch triggered while other stuff was going on. We record it as a state so that we can
/// fetch new messages at a more opportune time.
MESSAGE_AVAILABLE_SIGNAL_BUFFERED,
/// Waiting for the message available watch to trigger that signals new messages have arrived.
AWAITING_NEW_MESSAGES,
/// Terminal state indicating no more messages will be published. Either we have successfully published all messages
/// in the case of a finite publisher, or the subscriber has indicated that it has terminated.
TERMINATED,
/// Terminal state reached when there is an error fetching or publishing messages.
ERROR
}
enum Event {
/// Downstream subscriber requested more items.
DEMAND_REQUESTED,
/// The FoundationDB range query returned less than the batch size.
FETCHED_ALL_AVAILABLE_MESSAGES,
/// We have successfully fetched and published a message batch
PUBLISHED_MESSAGES,
/// The message available watch triggered indicating new messages have arrived.
MESSAGE_AVAILABLE_WATCH_TRIGGERED,
/// Internal self-trigger used to immediately transition to the next state.
INTERNAL_TRIGGER,
/// An error occurred during fetching from FoundationDB or publishing messages to the sink.
FETCH_OR_PUBLISH_ERROR_OCCURRED
}
/// The key that is updated whenever new messages are available in the queue. If null, it is inferred that the publisher
/// is finite and will terminate when the end-of-queue at time of publisher creation is reached. Otherwise, the publisher
/// is "infinite" and will continue to wait for new messages and publish them in a loop.
@Nullable private final byte[] messagesAvailableWatchKey;
/// Listener to watch for state machine transitions; used for testing.
private final BiConsumer<State, State> stateChangeListener;
private final Flux<MessageStreamEntry.Envelope> messagePublisher;
/// Whether the publisher is finite or infinite.
private final boolean terminateOnQueueEmpty;
/// Tracks the current state of the publisher state machine. Initial state presumes that messages are available in the queue.
private State state = State.MESSAGES_AVAILABLE;
/// Reference to the sink we publishes messages to.
private volatile FluxSink<MessageStreamEntry.Envelope> emitter;
/// Future that completes when the watch for {@link #messagesAvailableWatchKey} triggers.
private CompletableFuture<Void> watchFuture;
private static final Logger LOGGER = LoggerFactory.getLogger(FoundationDbMessagePublisher.class);
FoundationDbMessagePublisher(
final KeySelector beginKeyInclusive,
final KeySelector endKeyExclusive,
final Database database,
final MessageGuidCodec messageGuidCodec,
final int maxMessagesPerScan,
@Nullable final byte[] messagesAvailableWatchKey,
@Nullable final BiConsumer<State, State> stateChangeListener) {
this.beginKeyCursor = beginKeyInclusive;
this.endKeyExclusive = endKeyExclusive;
this.database = database;
this.messageGuidCodec = messageGuidCodec;
this.maxMessagesPerScan = maxMessagesPerScan;
this.messagesAvailableWatchKey = messagesAvailableWatchKey;
this.terminateOnQueueEmpty = messagesAvailableWatchKey == null;
this.stateChangeListener = stateChangeListener != null ? stateChangeListener : (_, _) -> {};
this.messagePublisher = Flux.create(emitter -> {
this.emitter = emitter;
emitter.onRequest(_ -> transitionStateOnEvent(Event.DEMAND_REQUESTED));
emitter.onDispose(this::onDispose);
});
}
/// Creates a [FoundationDbMessagePublisher] that publishes a stream of messages in a queue that terminates when it
/// yields the last message that was present in the queue at the time the publisher was created. This is helpful in
/// cases when callers need to "catch up" on stored messages without following fresh updates (for example, when a
/// client first connects and needs to load stored messages before receiving a "live" stream of new messages).
public static FoundationDbMessagePublisher createFinitePublisher(
final KeySelector beginKeyInclusive,
final KeySelector endKeyExclusive,
final Database database,
final MessageGuidCodec messageGuidCodec,
final int maxMessagesPerScan) {
return new FoundationDbMessagePublisher(beginKeyInclusive,
endKeyExclusive,
database,
messageGuidCodec,
maxMessagesPerScan,
null,
null);
}
/// Creates a [FoundationDbMessagePublisher] that publishes a non-terminating stream of messages from a device queue.
/// It waits for new messages and publishes them in a loop. Useful when a client has finished receiving its stored
/// messages and is now waiting for a live stream of new messages.
public static FoundationDbMessagePublisher createInfinitePublisher(
final KeySelector beginKeyInclusive,
final KeySelector endKeyExclusive,
final Database database,
final MessageGuidCodec messageGuidCodec,
final int maxMessagesPerScan,
final byte[] messagesAvailableWatchKey) {
return new FoundationDbMessagePublisher(beginKeyInclusive,
endKeyExclusive,
database,
messageGuidCodec,
maxMessagesPerScan,
messagesAvailableWatchKey,
null);
}
private synchronized void setState(final State newState, final Event event) {
LOGGER.debug("Transitioned from state {} to state {} on event {}", state, newState, event);
final State oldState = state;
state = newState;
stateChangeListener.accept(oldState, newState);
}
/// Called when an event occurs. Transitions the current state to a new state if this is a defined transition.
///
/// @param event the {@link Event} that has occurred
protected synchronized void transitionStateOnEvent(final Event event) {
assert emitter != null;
boolean knownTransition = true;
switch (state) {
case MESSAGES_AVAILABLE -> {
switch (event) {
case DEMAND_REQUESTED -> {
setState(State.FETCHING_MESSAGES, event);
emitMessages();
}
case INTERNAL_TRIGGER -> {
if (emitter.requestedFromDownstream() > 0) {
setState(State.FETCHING_MESSAGES, event);
emitMessages();
}
}
default -> knownTransition = false;
}
}
case FETCHING_MESSAGES -> {
switch (event) {
case FETCHED_ALL_AVAILABLE_MESSAGES -> setState(State.QUEUE_EMPTY, event);
case PUBLISHED_MESSAGES -> {
setState(State.MESSAGES_AVAILABLE, event);
transitionStateOnEvent(Event.INTERNAL_TRIGGER);
}
case FETCH_OR_PUBLISH_ERROR_OCCURRED -> setState(State.ERROR, event);
default -> knownTransition = false;
}
}
case QUEUE_EMPTY -> {
if (terminateOnQueueEmpty) {
switch (event) {
case PUBLISHED_MESSAGES -> {
setState(State.TERMINATED, event);
emitter.complete();
}
case FETCHED_ALL_AVAILABLE_MESSAGES -> setState(State.ERROR, event);
default -> knownTransition = false;
}
} else {
switch (event) {
case MESSAGE_AVAILABLE_WATCH_TRIGGERED -> setState(State.MESSAGE_AVAILABLE_SIGNAL_BUFFERED, event);
case PUBLISHED_MESSAGES -> setState(State.AWAITING_NEW_MESSAGES, event);
default -> knownTransition = false;
}
}
}
case MESSAGE_AVAILABLE_SIGNAL_BUFFERED -> {
switch (event) {
case PUBLISHED_MESSAGES -> {
setState(State.MESSAGES_AVAILABLE, event);
transitionStateOnEvent(Event.INTERNAL_TRIGGER);
}
default -> knownTransition = false;
}
}
case AWAITING_NEW_MESSAGES -> {
switch (event) {
case MESSAGE_AVAILABLE_WATCH_TRIGGERED -> {
setState(State.MESSAGES_AVAILABLE, event);
transitionStateOnEvent(Event.INTERNAL_TRIGGER);
}
default -> knownTransition = false;
}
}
default -> knownTransition = false;
}
if (!knownTransition) {
LOGGER.debug("Unhandled event {} on state {}", event, state);
}
}
/// Fetch messages using a range query limiting batch size to [#maxMessagesPerScan]. If the query returns fewer than
/// [#maxMessagesPerScan], emit [Event#FETCHED_ALL_AVAILABLE_MESSAGES]. In the case of an infinite publisher, also set
/// a watch for new messages. Additionally, the cursor is updated so that we begin fetching from the right key on
/// subsequent scans
///
/// @return a future of a list of [MessageStreamEntry] with a max size of [#maxMessagesPerScan]
private CompletableFuture<List<MessageStreamEntry.Envelope>> getMessagesBatch() {
return database.runAsync(transaction -> getItemsInRange(transaction, messageGuidCodec, beginKeyCursor, endKeyExclusive, maxMessagesPerScan)
.thenApply(lastKeyReadAndItems -> {
// Set our beginning key to just past the last key read so that we're ready for our next fetch
lastKeyReadAndItems.first().ifPresent(lastKeyRead -> beginKeyCursor = KeySelector.firstGreaterThan(lastKeyRead));
final List<MessageStreamEntry.Envelope> items = lastKeyReadAndItems.second();
if (items.size() < maxMessagesPerScan) {
transitionStateOnEvent(Event.FETCHED_ALL_AVAILABLE_MESSAGES);
if (!terminateOnQueueEmpty) {
setWatch(transaction);
}
}
return items;
})
);
}
/// Fetch messages in the range between `begin` and `end` limited to a batch size of `maxMessagesPerSccan`
///
/// @param transaction the FoundationDB transaction in which to perform the read query
/// @param beginInclusive the range start key (inclusive)
/// @param endExclusive the range end key (exclusive)
/// @param maxMessagesPerScan maximum number of messages to return in the fetch query
/// @return the last key read (if there were non-zero number of messages read) and the list of messages read
private static CompletableFuture<Pair<Optional<byte[]>, List<MessageStreamEntry.Envelope>>> getItemsInRange(
final Transaction transaction,
final MessageGuidCodec messageGuidCodec,
final KeySelector beginInclusive,
final KeySelector endExclusive,
final int maxMessagesPerScan) {
return transaction.getRange(beginInclusive, endExclusive, maxMessagesPerScan, false, StreamingMode.EXACT).asList()
.thenApply(keyValues -> {
final Optional<byte[]> lastKeyRead = keyValues.isEmpty()
? Optional.empty()
: Optional.of(keyValues.getLast().getKey());
final List<MessageStreamEntry.Envelope> messages = keyValues.stream()
.map(keyValue -> {
try {
return new MessageStreamEntry.Envelope(MessageProtos.Envelope.parseFrom(keyValue.getValue())
.toBuilder()
.setServerGuidBinary(UUIDUtil.toByteString(messageGuidCodec.encodeMessageGuid(FoundationDbMessageStore.getVersionstamp(keyValue.getKey()))))
.build());
} catch (final InvalidProtocolBufferException e) {
throw new UncheckedIOException(e);
}
})
.toList();
return new Pair<>(lastKeyRead, messages);
});
}
/// Fetch and publish messages. Messages are fetched in batches of [#maxMessagesPerScan] to avoid excessive memory
/// consumption. After each fetch operation, [#beginKeyCursor] is updated to the next key we need to start reading
/// from. If the fetch operation returns fewer items than the batch size, we infer that we have fetched all available
/// messages and [Event#FETCHED_ALL_AVAILABLE_MESSAGES] is sent to the state machine. See [#getMessagesBatch()]
/// for details. Additionally, after we successfully publish the batch of messages, {@link Event#PUBLISHED_MESSAGES}
/// is emitted. If there's an error while fetching or publishing, [Event#FETCH_OR_PUBLISH_ERROR_OCCURRED] is emitted
/// instead.
private void emitMessages() {
getMessagesBatch()
.thenAccept(messageStreamEntries -> {
messageStreamEntries.forEach(emitter::next);
transitionStateOnEvent(Event.PUBLISHED_MESSAGES);
})
.exceptionally(t -> {
transitionStateOnEvent(Event.FETCH_OR_PUBLISH_ERROR_OCCURRED);
emitter.error(t);
return null;
});
}
/// Get the stream of messages.
///
/// @return [Flux] of messages
public Flux<MessageStreamEntry.Envelope> getMessages() {
return this.messagePublisher;
}
private synchronized void setWatch(final Transaction transaction) {
assert messagesAvailableWatchKey != null;
// Set a watch that will be triggered when new messages arrive. When it is triggered, we attempt to fetch messages
// again (if there is demand). When we run out of messages, this method will be called again, setting another watch,
// and so on, thus achieving a "watch for new messages -> read -> publish" loop.
watchFuture = transaction.watch(messagesAvailableWatchKey);
watchFuture.thenRun(() -> transitionStateOnEvent(Event.MESSAGE_AVAILABLE_WATCH_TRIGGERED));
}
private synchronized void onDispose() {
// Unless the state machine is an already terminal state, directly set state to "terminated", since there's no point
// in evaluating the state machine when there's no live subscription.
if (state != State.TERMINATED && state != State.ERROR) {
setState(State.TERMINATED, Event.INTERNAL_TRIGGER);
}
cancelWatch();
}
/// Cancel the watch (if any). Although inactive watches are automatically timed-out, we explicitly cancel when the
/// subscription is disposed to clean up associated resources and to avoid having too many watches open at once.
private synchronized void cancelWatch() {
if (watchFuture != null) {
watchFuture.cancel(true);
}
}
}
@@ -22,6 +22,8 @@ import java.util.function.Function;
import java.util.stream.Collectors;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.MessageStream;
import org.whispersystems.textsecuregcm.util.Conversions;
/// An implementation of a message store backed by FoundationDB.
@@ -38,6 +40,7 @@ import org.whispersystems.textsecuregcm.util.Conversions;
public class FoundationDbMessageStore {
private final Database[] databases;
private final VersionstampUUIDCipher versionstampUUIDCipher;
private final Executor executor;
private final Clock clock;
@@ -58,8 +61,13 @@ public class FoundationDbMessageStore {
public record InsertResult(Optional<Versionstamp> versionstamp, boolean present) {
}
public FoundationDbMessageStore(final Database[] databases, final Executor executor, final Clock clock) {
public FoundationDbMessageStore(final Database[] databases,
final VersionstampUUIDCipher versionstampUUIDCipher,
final Executor executor,
final Clock clock) {
this.databases = databases;
this.versionstampUUIDCipher = versionstampUUIDCipher;
this.executor = executor;
this.clock = clock;
}
@@ -101,6 +109,14 @@ public class FoundationDbMessageStore {
throw new IllegalArgumentException("One or more message bundles is empty");
}
if (messagesByServiceIdentifier.values()
.stream()
.flatMap(messages -> messages.values().stream())
.anyMatch(MessageProtos.Envelope::hasServerGuid)) {
throw new IllegalArgumentException("Messages must not have pre-set server GUIDs");
}
final Map<Integer, List<Map.Entry<AciServiceIdentifier, Map<Byte, MessageProtos.Envelope>>>> messagesByShardId =
messagesByServiceIdentifier.entrySet().stream()
.collect(Collectors.groupingBy(entry -> hashAciToShardNumber(entry.getKey())));
@@ -109,8 +125,6 @@ public class FoundationDbMessageStore {
new ArrayList<>();
messagesByShardId.forEach((shardId, messagesForShard) -> {
final Database shard = databases[shardId];
int start = 0, current = 0;
int estimatedTransactionSize = 0;
@@ -121,7 +135,7 @@ public class FoundationDbMessageStore {
.sum();
if (estimatedTransactionSize > MAX_MESSAGE_CHUNK_SIZE) {
chunkFutures.add(insertChunk(shard, messagesForShard.subList(start, current)));
chunkFutures.add(insertChunk(shardId, messagesForShard.subList(start, current)));
start = current;
estimatedTransactionSize = 0;
@@ -131,7 +145,7 @@ public class FoundationDbMessageStore {
}
assert start < messagesForShard.size();
chunkFutures.add(insertChunk(shard, messagesForShard.subList(start, messagesForShard.size())));
chunkFutures.add(insertChunk(shardId, messagesForShard.subList(start, messagesForShard.size())));
});
return CompletableFuture.allOf(chunkFutures.toArray(CompletableFuture[]::new))
@@ -144,7 +158,7 @@ public class FoundationDbMessageStore {
}
private CompletableFuture<Map<AciServiceIdentifier, Map<Byte, InsertResult>>> insertChunk(
final Database database,
final int shardId,
final List<Map.Entry<AciServiceIdentifier, Map<Byte, MessageProtos.Envelope>>> messagesByAccountIdentifier) {
final Map<AciServiceIdentifier, CompletableFuture<Map<Byte, Boolean>>> insertFuturesByAci = new HashMap<>();
@@ -156,7 +170,7 @@ public class FoundationDbMessageStore {
.map(MessageProtos.Envelope::getEphemeral)
.orElseThrow(() -> new IllegalStateException("One or more bundles is empty"));
return database.runAsync(transaction -> {
return databases[shardId].runAsync(transaction -> {
messagesByAccountIdentifier.forEach(entry ->
insertFuturesByAci.put(entry.getKey(), insert(entry.getKey(), entry.getValue(), transaction)));
@@ -169,7 +183,7 @@ public class FoundationDbMessageStore {
.anyMatch(isPresent -> isPresent);
if (anyClientPresent || !ephemeral) {
return transaction.getVersionstamp()
.thenApply(versionstampBytes -> Optional.of(Versionstamp.complete(versionstampBytes)));
.thenApply(versionstampBytes -> Optional.of(Versionstamp.complete(versionstampBytes, shardId)));
}
return CompletableFuture.completedFuture(Optional.<Versionstamp>empty());
});
@@ -220,7 +234,7 @@ public class FoundationDbMessageStore {
if (isPresent || !message.getEphemeral()) {
transaction.mutate(MutationType.SET_VERSIONSTAMPED_KEY,
getDeviceQueueSubspace(aci, deviceId)
.packWithVersionstamp(Tuple.from(Versionstamp.incomplete())), message.toByteArray());
.packWithVersionstamp(Tuple.from(Versionstamp.incomplete(hashAciToShardNumber(aci)))), message.toByteArray());
}
return isPresent;
@@ -239,13 +253,30 @@ public class FoundationDbMessageStore {
if (anyClientPresent) {
transaction.mutate(MutationType.SET_VERSIONSTAMPED_VALUE, getMessagesAvailableWatchKey(aci),
Tuple.from(Versionstamp.incomplete()).packWithVersionstamp());
Tuple.from(Versionstamp.incomplete(hashAciToShardNumber(aci))).packWithVersionstamp());
}
return presenceByDeviceId;
}, executor);
}
public MessageStream getMessages(final AciServiceIdentifier aci, final Device destinationDevice) {
return getMessages(aci, destinationDevice, FoundationDbMessageStream.DEFAULT_MAX_MESSAGES_PER_SCAN);
}
@VisibleForTesting
MessageStream getMessages(final AciServiceIdentifier aci, final Device destinationDevice, final int maxMessagesPerScan) {
return new FoundationDbMessageStream(getDeviceQueueSubspace(aci, destinationDevice.getId()),
getMessagesAvailableWatchKey(aci),
getShardForAci(aci),
new MessageGuidCodec(aci.uuid(), destinationDevice.getId(), versionstampUUIDCipher),
maxMessagesPerScan);
}
static Versionstamp getVersionstamp(final byte[] messageKey) {
return Tuple.fromBytes(messageKey).getVersionstamp(4);
}
@VisibleForTesting
Database getShardForAci(final AciServiceIdentifier aci) {
return databases[hashAciToShardNumber(aci)];
@@ -258,20 +289,20 @@ public class FoundationDbMessageStore {
}
@VisibleForTesting
Subspace getDeviceQueueSubspace(final AciServiceIdentifier aci, final byte deviceId) {
static Subspace getDeviceQueueSubspace(final AciServiceIdentifier aci, final byte deviceId) {
return getDeviceSubspace(aci, deviceId).get("Q");
}
private Subspace getDeviceSubspace(final AciServiceIdentifier aci, final byte deviceId) {
private static Subspace getDeviceSubspace(final AciServiceIdentifier aci, final byte deviceId) {
return getAccountSubspace(aci).get(deviceId);
}
private Subspace getAccountSubspace(final AciServiceIdentifier aci) {
private static Subspace getAccountSubspace(final AciServiceIdentifier aci) {
return MESSAGES_SUBSPACE.get(aci.uuid());
}
@VisibleForTesting
byte[] getMessagesAvailableWatchKey(final AciServiceIdentifier aci) {
static byte[] getMessagesAvailableWatchKey(final AciServiceIdentifier aci) {
return getAccountSubspace(aci).pack("l");
}
Loaded 100 of 192 files, more files were not shown because too many files have changed in this diff. Show more