Compare commits

..
72 Commits
Author SHA1 Message Date
Jon Chambers 4ce85fdb19 Treat "check code" exceptions as false for legacy API compatibility 2023-01-25 14:39:29 -05:00
Jon Chambers 035ddc4834 Fix a mistake where we're looking for verification codes in place that hasn't been deployed yet (but will be soon!) 2023-01-25 11:43:06 -05:00
Chris Eager c2f40b8503 Remove duplicate code 2023-01-25 11:09:23 -05:00
Jon Chambers cf738a1c14 Look for registration service errors in response bodies in addition to status responses 2023-01-25 10:49:36 -05:00
erik-signal 52d40c2321 Add metrics for spam report tokens received. 2023-01-24 10:25:40 -05:00
Erik Osheim cbf12d6b46 Update to latest version of the spam module 2023-01-19 11:20:08 -05:00
erik-signal ab26a65b6a Introduce spam report tokens 2023-01-19 11:13:43 -05:00
erik-signal ee5aaf5383 Ignore files created by emacs / lsp. 2023-01-18 15:44:29 -05:00
Jon Chambers 1c1714b2c2 Clarify a counter name 2023-01-17 17:13:06 -05:00
Jon Chambers accb017ec5 Use a longer expiration window for quantile calculation 2023-01-17 17:13:06 -05:00
Chris Eager 304782d583 Use processor from SubscriptionProcessorManager for issued receipts 2023-01-17 16:12:03 -06:00
Chris Eager f361f436d8 Support PayPal for recurring donations 2023-01-17 12:20:17 -06:00
Chris Eager a34b5a6122 grpc, guava: use version from google cloud libraries-bom 2023-01-17 11:20:46 -06:00
Chris Eager f75ea18ccb Add test for GoogleCloudAdminEventLogger 2023-01-17 11:20:46 -06:00
Dimitris Apostolou 9a06c40a28 Fix typos 2023-01-13 16:05:06 -06:00
Chris Eager e6ab97dc5a Update enabled-required authenticator metrics 2023-01-13 14:05:56 -06:00
Chris Eager ba73f757e2 Update google libraries-bom to 26.1.3, firebase-admin to 9.1.1 2023-01-13 12:22:55 -06:00
Chris Eager 30f131096d Update AWS SDK v1 to 1.12.376 2023-01-13 12:17:39 -06:00
Chris Eager b8ce922f92 Update logstash-logback-encoder to 7.2 2023-01-13 12:17:39 -06:00
Chris Eager 11b62345e1 Update mockito to 4.11.0 2023-01-13 12:17:39 -06:00
Chris Eager 77289ecb51 Update micrometer to 1.10.3 2023-01-13 12:17:39 -06:00
Chris Eager dfb0b68997 Update DynamoDBLocal to 1.20.0 2023-01-13 12:17:39 -06:00
Chris Eager d545f60fc4 Update wiremock to 2.35.0 2023-01-13 12:17:39 -06:00
Chris Eager 5cda6e9d84 Update pushy to 0.15.2 2023-01-13 12:17:39 -06:00
Chris Eager 7caba89210 Update AWS SDK v2 to 2.19.8 2023-01-13 12:17:39 -06:00
Chris Eager b8967b75c6 Update dropwizard to 2.0.34 2023-01-13 12:17:39 -06:00
Chris Eager 74d9849472 Update badge strings 2023-01-13 12:08:05 -06:00
Fedor Indutny 96b753cfd0 Add an extra kb to max sticker size 2023-01-13 12:07:45 -06:00
Jon Chambers 5a89e66fc0 Convert AccountIdentityResponse to a record 2023-01-13 12:36:17 -05:00
Jon Chambers b4a143b9de Convert RegistrationLockFailure to a record 2023-01-13 12:36:02 -05:00
Jon Chambers 050035dd52 Convert ExternalServiceCredentials to a record 2023-01-13 12:36:02 -05:00
Jon Chambers 7018062606 Explicitly create registration sessions 2023-01-09 15:27:07 -05:00
Jon Chambers 9e1485de0a Assume stored verification codes will always have a session ID instead of a verification code 2023-01-09 15:27:07 -05:00
Jon Chambers 4e358b891f Retire StoredVerificationCode#twilioVerificationSid 2023-01-09 15:27:07 -05:00
Ehren Kret 4044a9df30 stop warning about lack of syntax specification during proto generation 2023-01-09 12:20:07 -06:00
Ehren Kret 5a7b675001 import cleanup on controllers package 2023-01-09 12:20:07 -06:00
Ehren Kret 3be4e4bc57 remove unused exception type 2023-01-09 12:20:07 -06:00
Chris Eager 5de51919bb Remove Subscriptions.PCI 2023-01-05 12:02:34 -06:00
Chris Eager b02b00818b Remove Subscriptions.PCI attribute 2023-01-04 11:31:46 -06:00
Chris Eager 010f88a2ad Remove Subscriptions.C attribute 2023-01-04 11:31:46 -06:00
Jon Chambers 60edf4835f Add a pni capability to UserCapabilities 2022-12-21 16:26:07 -05:00
Jon Chambers a60450d931 Convert UserCapabilities to a record 2022-12-21 16:26:07 -05:00
erik-signal d138fa45df Handle edge cases of Math.abs on integers. 2022-12-20 12:25:04 -05:00
Katherine Yen 2c2c497c12 Define reregistrationIdleDays DistributionSummary with custom expiry 2022-12-20 09:21:24 -08:00
Katherine Yen cb5d3840d9 Add paymentActivation capability 2022-12-20 09:20:42 -08:00
Fedor Indutny 9aceaa7a4d Introduce ArtController 2022-12-19 11:58:16 -08:00
Katherine Yen 636c8ba384 Add metric for distribution of account idle time at reregistration 2022-12-16 13:50:29 -08:00
Ravi Khadiwala ac78eb1425 Update to the latest version of the abusive message filter 2022-12-16 11:28:30 -06:00
Ravi Khadiwala 65ad3fe623 Add hCaptcha support 2022-12-16 11:28:30 -06:00
Sergey Skrobotov dcec90fc52 Update to the latest version of the abusive message filter 2022-12-13 13:30:47 -08:00
Chris Eager 24ac32e6e6 Add PayPalExperienceProfileInput.userAction 2022-12-13 10:03:58 -06:00
Katherine Yen 26f5ffdde3 Enable case-sensitive usernames 2022-12-13 07:59:37 -08:00
Jon Chambers a883426402 Simplify account cleaner 2022-12-06 16:21:25 -06:00
Chris Eager 2f21e930e2 Add minimum one-time donation amont to validation error map 2022-12-06 16:21:15 -06:00
Chris Eager 5fb158635c Use existing WebApplicationException entity, if available 2022-12-06 16:21:15 -06:00
Chris Eager 6f844f9ebb Update to the latest version of the abusive message filter 2022-12-06 16:20:17 -06:00
Sergey Skrobotov d88e358016 Update to the latest version of the abusive message filter 2022-12-05 10:07:40 -08:00
Sergey Skrobotov 9cf2635528 some accounts classes refactorings 2022-12-05 09:30:40 -08:00
Chris Eager d0e7579f13 Revert transaction descriptor 2022-12-01 18:52:45 -06:00
Chris Eager cda82b0ea0 Update kotlin + Apollo 2022-12-01 18:11:35 -06:00
Chris Eager 2ecbb18fe5 Add support for one-time PayPal donations 2022-12-01 18:11:35 -06:00
Chris Eager d40d2389a9 Update to Maven 3.8.6 2022-12-01 18:09:38 -06:00
Chris Eager df8fb5cab7 Move messages cache stale discard to a separate scheduler 2022-12-01 18:09:28 -06:00
katherine-signal 99ad211c01 Enforce minimum amount by currency for one time donations 2022-11-28 11:44:59 -08:00
katherine-signal fb4ed20ff5 Remove groups v2 capability
* wip removing groups v2 capabilities

* comments

* finish removing groups v2 references

* hardcode gv1migration flag on user capability, remove other references
2022-11-21 09:31:47 -08:00
Jon Chambers cb50b44d8f Allow the account cleaner to operate on multiple accounts in parallel 2022-11-18 11:15:00 -05:00
Jon Chambers ae57853ec4 Simplify deletion reason reporting 2022-11-18 11:15:00 -05:00
Jon Chambers 2881c0fd7e Allow the account cleaner to act on all accounts in a crawled chunk 2022-11-18 11:15:00 -05:00
Chris Eager 483fb0968b Use badge name in level configuration for one-time donations 2022-11-18 11:05:23 -05:00
Jon Chambers 4d37418c15 Update to the latest version of the abusive message filter 2022-11-18 10:55:15 -05:00
Jon Chambers e8ee4b50ff Retire the legacy "abusive hosts" system in favor of newer tools 2022-11-18 10:54:25 -05:00
Chris Eager 4f8aa2eee2 Mark flaky test @Disabled 2022-11-17 13:23:42 -06:00
131 changed files with 40191 additions and 2511 deletions

No files matched your search

+3
View File
@@ -26,3 +26,6 @@ deployer.log
!/service/src/main/resources/org/signal/badges/Badges_en.properties
/service/src/main/resources/org/signal/subscriptions/Subscriptions_*.properties
!/service/src/main/resources/org/signal/subscriptions/Subscriptions_en.properties
.project
.classpath
.settings
+4 -4
View File
@@ -5,14 +5,14 @@
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
#
# https://www.apache.org/licenses/LICENSE-2.0
#
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# 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.8.5/apache-maven-3.8.5-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.6/apache-maven-3.8.6-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.1/maven-wrapper-3.1.1.jar
+10 -1
View File
@@ -24,7 +24,16 @@
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib</artifactId>
<version>${kotlin.version}</version>
<exclusions>
<exclusion>
<groupId>org.jetbrains</groupId>
<!--
depends on an outdated version (13.0) for JDK 6 compatibility, but it’s safe to override
https://youtrack.jetbrains.com/issue/KT-25047
-->
<artifactId>annotations</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlinx</groupId>
@@ -0,0 +1,22 @@
/*
* Copyright 2023 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.signal.event
import com.google.cloud.logging.Logging
import org.junit.jupiter.api.Test
import org.mockito.Mockito.mock
class GoogleCloudAdminEventLoggerTest {
@Test
fun logEvent() {
val logging = mock(Logging::class.java)
val logger = GoogleCloudAdminEventLogger(logging, "my-project", "test")
val event = RemoteConfigDeleteEvent("token", "test")
logger.logEvent(event)
}
}
+34 -27
View File
@@ -42,30 +42,31 @@
</modules>
<properties>
<aws.sdk.version>1.12.287</aws.sdk.version>
<aws.sdk2.version>2.17.258</aws.sdk2.version>
<aws.sdk.version>1.12.376</aws.sdk.version>
<aws.sdk2.version>2.19.8</aws.sdk2.version>
<braintree.version>3.19.0</braintree.version>
<commons-codec.version>1.15</commons-codec.version>
<commons-csv.version>1.8</commons-csv.version>
<commons-csv.version>1.9.0</commons-csv.version>
<commons-io.version>2.9.0</commons-io.version>
<dropwizard.version>2.0.32</dropwizard.version>
<dropwizard.version>2.0.34</dropwizard.version>
<dropwizard-metrics-datadog.version>1.1.13</dropwizard-metrics-datadog.version>
<grpc.version>1.49.2</grpc.version>
<google-cloud-libraries.version>26.1.3</google-cloud-libraries.version>
<grpc.version>1.51.1</grpc.version> <!-- this should be kept in sync with the value from Google’s libraries-bom -->
<gson.version>2.9.0</gson.version>
<guava.version>30.1.1-jre</guava.version>
<jackson.version>2.13.4</jackson.version>
<jaxb.version>2.3.1</jaxb.version>
<jedis.version>2.9.0</jedis.version>
<kotlin.version>1.7.10</kotlin.version>
<kotlinx-serialization.version>1.4.0</kotlinx-serialization.version>
<kotlin.version>1.8.0</kotlin.version>
<kotlinx-serialization.version>1.4.1</kotlinx-serialization.version>
<lettuce.version>6.2.1.RELEASE</lettuce.version>
<libphonenumber.version>8.12.54</libphonenumber.version>
<logstash.logback.version>7.0.1</logstash.logback.version>
<micrometer.version>1.10.0</micrometer.version>
<mockito.version>4.7.0</mockito.version>
<logstash.logback.version>7.2</logstash.logback.version>
<micrometer.version>1.10.3</micrometer.version>
<mockito.version>4.11.0</mockito.version>
<netty.version>4.1.82.Final</netty.version>
<opentest4j.version>1.2.0</opentest4j.version>
<protobuf.version>3.21.7</protobuf.version>
<pushy.version>0.15.1</pushy.version>
<pushy.version>0.15.2</pushy.version>
<resilience4j.version>1.7.0</resilience4j.version>
<semver4j.version>3.1.0</semver4j.version>
<slf4j.version>1.7.30</slf4j.version>
@@ -95,13 +96,6 @@
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-bom</artifactId>
<version>${grpc.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- Needed for gRPC with Java 9+ -->
<dependency>
<groupId>org.apache.tomcat</groupId>
@@ -133,7 +127,7 @@
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>libraries-bom</artifactId>
<version>26.1.0</version>
<version>${google-cloud-libraries.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
@@ -158,6 +152,13 @@
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-bom</artifactId>
<version>${kotlin.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>com.eatthepath</groupId>
<artifactId>pushy</artifactId>
@@ -168,11 +169,6 @@
<artifactId>pushy-dropwizard-metrics-listener</artifactId>
<version>${pushy.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
@@ -284,6 +280,11 @@
<artifactId>stripe-java</artifactId>
<version>${stripe.version}</version>
</dependency>
<dependency>
<groupId>com.braintreepayments.gateway</groupId>
<artifactId>braintree-java</artifactId>
<version>${braintree.version}</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
@@ -320,7 +321,7 @@
<dependency>
<groupId>com.github.tomakehurst</groupId>
<artifactId>wiremock-jre8</artifactId>
<version>2.34.0</version>
<version>2.35.0</version>
<scope>test</scope>
<exclusions>
<exclusion>
@@ -349,6 +350,12 @@
<artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit-pioneer</groupId>
<artifactId>junit-pioneer</artifactId>
<version>1.9.1</version>
<scope>test</scope>
</dependency>
</dependencies>
@@ -475,7 +482,7 @@
<rules>
<dependencyConvergence/>
<requireMavenVersion>
<version>3.8.3</version>
<version>3.8.6</version>
</requireMavenVersion>
</rules>
</configuration>
+29 -1
View File
@@ -15,6 +15,25 @@ stripe:
idempotencyKeyGenerator: abcdefg12345678= # base64 for creating request idempotency hash
boostDescription: >
Example
supportedCurrencies:
- xts
# - ...
# - Nth supported currency
braintree:
merchantId: unset
publicKey: unset
privateKey: unset
environment: unset
graphqlUrl: unset
merchantAccounts:
# ISO 4217 currency code and its corresponding sub-merchant account
'xts': unset
supportedCurrencies:
- xts
# - ...
# - Nth supported currency
dynamoDbClientConfiguration:
region: us-west-2 # AWS Region
@@ -215,6 +234,9 @@ recaptcha:
projectPath: projects/example
credentialConfigurationJson: "{ }" # service account configuration for backend authentication
hCaptcha:
apiKey: unset
storageService:
uri: storage.example.com
userAuthenticationTokenSharedSecret: 00000f
@@ -297,6 +319,10 @@ paymentsService:
# list of symbols for supported currencies
- MOB
artService:
userAuthenticationTokenSharedSecret: 0000000f0000000f0000000f0000000f0000000f0000000f0000000f0000000f # hex-encoded 32-byte secret not shared with any external service, but used in ArtController
userAuthenticationTokenUserIdSecret: 00000f # hex-encoded secret to obscure user phone numbers from Sticker Creator
badges:
badges:
- id: TEST
@@ -326,7 +352,9 @@ subscription: # configuration for Stripe subscriptions
# list of ISO 4217 currency codes and amounts for the given badge level
xts:
amount: '10'
id: price_example # stripe ID
processorIds:
STRIPE: price_example # stripe Price ID
BRAINTREE: plan_example # braintree Plan ID
oneTimeDonations:
boost:
+39 -29
View File
@@ -185,34 +185,7 @@
<dependency>
<groupId>com.google.firebase</groupId>
<artifactId>firebase-admin</artifactId>
<version>9.0.0</version>
<!-- firebase-admin has conflicting versions of these artifacts in its dependency tree; for firebase-admin
9.0.0, we'll need to depend directly on com.google.api-client:google-api-client:1.35.1 and
com.google.oauth-client:google-oauth-client:1.34.1 -->
<exclusions>
<exclusion>
<groupId>com.google.api-client</groupId>
<artifactId>google-api-client</artifactId>
</exclusion>
<exclusion>
<groupId>com.google.oauth-client</groupId>
<artifactId>google-oauth-client</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.google.api-client</groupId>
<artifactId>google-api-client</artifactId>
<version>1.35.1</version>
</dependency>
<dependency>
<groupId>com.google.oauth-client</groupId>
<artifactId>google-oauth-client</artifactId>
<version>1.34.1</version>
<version>9.1.1</version>
</dependency>
<dependency>
@@ -444,7 +417,7 @@
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>DynamoDBLocal</artifactId>
<version>1.19.0</version>
<version>1.20.0</version>
<scope>test</scope>
</dependency>
@@ -457,6 +430,18 @@
<groupId>com.stripe</groupId>
<artifactId>stripe-java</artifactId>
</dependency>
<dependency>
<groupId>com.braintreepayments.gateway</groupId>
<artifactId>braintree-java</artifactId>
</dependency>
<dependency>
<groupId>com.apollographql.apollo3</groupId>
<artifactId>apollo-api-jvm</artifactId>
<version>3.7.1</version>
</dependency>
</dependencies>
<profiles>
@@ -612,6 +597,31 @@
</arguments>
</configuration>
</plugin>
<plugin>
<groupId>com.github.aoudiamoncef</groupId>
<artifactId>apollo-client-maven-plugin</artifactId>
<version>5.0.0</version>
<executions>
<execution>
<goals>
<goal>generate</goal>
</goals>
<configuration>
<services>
<braintree>
<compilationUnit>
<name>braintree</name>
<compilerParams>
<schemaPackageName>com.braintree.graphql.client</schemaPackageName>
</compilerParams>
</compilationUnit>
</braintree>
</services>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,9 @@
# https://graphql.braintreepayments.com/reference/#Mutation--chargePaymentMethod
mutation ChargePayPalOneTimePayment($input: ChargePaymentMethodInput!) {
chargePaymentMethod(input: $input) {
transaction {
id,
status
}
}
}
@@ -0,0 +1,6 @@
mutation CreatePayPalBillingAgreement($input: CreatePayPalBillingAgreementInput!) {
createPayPalBillingAgreement(input: $input) {
approvalUrl,
billingAgreementToken
}
}
@@ -0,0 +1,7 @@
# https://graphql.braintreepayments.com/reference/#Mutation--createPayPalOneTimePayment
mutation CreatePayPalOneTimePayment($input: CreatePayPalOneTimePaymentInput!) {
createPayPalOneTimePayment(input: $input) {
approvalUrl,
paymentId
}
}
@@ -0,0 +1,7 @@
mutation TokenizePayPalBillingAgreement($input: TokenizePayPalBillingAgreementInput!) {
tokenizePayPalBillingAgreement(input: $input) {
paymentMethod {
id
}
}
}
@@ -0,0 +1,8 @@
# https://graphql.braintreepayments.com/reference/#Mutation--tokenizePayPalOneTimePayment
mutation TokenizePayPalOneTimePayment($input: TokenizePayPalOneTimePaymentInput!) {
tokenizePayPalOneTimePayment(input: $input) {
paymentMethod {
id
}
}
}
@@ -0,0 +1,7 @@
mutation VaultPaymentMethod($input: VaultPaymentMethodInput!) {
vaultPaymentMethod(input: $input) {
paymentMethod {
id
}
}
}
File diff suppressed because it is too large. Load diff
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2021 Signal Messenger, LLC
* Copyright 2013 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm;
@@ -19,6 +19,7 @@ import org.whispersystems.textsecuregcm.configuration.ApnConfiguration;
import org.whispersystems.textsecuregcm.configuration.AppConfigConfiguration;
import org.whispersystems.textsecuregcm.configuration.AwsAttachmentsConfiguration;
import org.whispersystems.textsecuregcm.configuration.BadgesConfiguration;
import org.whispersystems.textsecuregcm.configuration.BraintreeConfiguration;
import org.whispersystems.textsecuregcm.configuration.CdnConfiguration;
import org.whispersystems.textsecuregcm.configuration.DatadogConfiguration;
import org.whispersystems.textsecuregcm.configuration.DirectoryConfiguration;
@@ -27,10 +28,12 @@ import org.whispersystems.textsecuregcm.configuration.DynamoDbClientConfiguratio
import org.whispersystems.textsecuregcm.configuration.DynamoDbTables;
import org.whispersystems.textsecuregcm.configuration.FcmConfiguration;
import org.whispersystems.textsecuregcm.configuration.GcpAttachmentsConfiguration;
import org.whispersystems.textsecuregcm.configuration.HCaptchaConfiguration;
import org.whispersystems.textsecuregcm.configuration.MaxDeviceConfiguration;
import org.whispersystems.textsecuregcm.configuration.MessageCacheConfiguration;
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration;
import org.whispersystems.textsecuregcm.configuration.PaymentsServiceConfiguration;
import org.whispersystems.textsecuregcm.configuration.ArtServiceConfiguration;
import org.whispersystems.textsecuregcm.configuration.RateLimitsConfiguration;
import org.whispersystems.textsecuregcm.configuration.RecaptchaConfiguration;
import org.whispersystems.textsecuregcm.configuration.RedisClusterConfiguration;
@@ -62,6 +65,11 @@ public class WhisperServerConfiguration extends Configuration {
@JsonProperty
private StripeConfiguration stripe;
@NotNull
@Valid
@JsonProperty
private BraintreeConfiguration braintree;
@NotNull
@Valid
@JsonProperty
@@ -187,6 +195,11 @@ public class WhisperServerConfiguration extends Configuration {
@JsonProperty
private RecaptchaConfiguration recaptcha;
@Valid
@NotNull
@JsonProperty
private HCaptchaConfiguration hCaptcha;
@Valid
@NotNull
@JsonProperty
@@ -202,6 +215,11 @@ public class WhisperServerConfiguration extends Configuration {
@JsonProperty
private PaymentsServiceConfiguration paymentsService;
@Valid
@NotNull
@JsonProperty
private ArtServiceConfiguration artService;
@Valid
@NotNull
@JsonProperty
@@ -259,6 +277,10 @@ public class WhisperServerConfiguration extends Configuration {
return stripe;
}
public BraintreeConfiguration getBraintree() {
return braintree;
}
public DynamoDbClientConfiguration getDynamoDbClientConfiguration() {
return dynamoDbClientConfiguration;
}
@@ -271,6 +293,10 @@ public class WhisperServerConfiguration extends Configuration {
return recaptcha;
}
public HCaptchaConfiguration getHCaptchaConfiguration() {
return hCaptcha;
}
public VoiceVerificationConfiguration getVoiceVerificationConfiguration() {
return voiceVerification;
}
@@ -385,6 +411,10 @@ public class WhisperServerConfiguration extends Configuration {
return paymentsService;
}
public ArtServiceConfiguration getArtServiceConfiguration() {
return artService;
}
public ZkConfig getZkConfig() {
return zkConfig;
}
@@ -73,6 +73,8 @@ import org.whispersystems.dispatch.DispatchManager;
import org.whispersystems.textsecuregcm.abuse.AbusiveMessageFilter;
import org.whispersystems.textsecuregcm.abuse.FilterAbusiveMessages;
import org.whispersystems.textsecuregcm.abuse.RateLimitChallengeListener;
import org.whispersystems.textsecuregcm.abuse.ReportSpamTokenHandler;
import org.whispersystems.textsecuregcm.abuse.ReportSpamTokenProvider;
import org.whispersystems.textsecuregcm.auth.AccountAuthenticator;
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
import org.whispersystems.textsecuregcm.auth.CertificateGenerator;
@@ -83,6 +85,8 @@ import org.whispersystems.textsecuregcm.auth.TurnTokenGenerator;
import org.whispersystems.textsecuregcm.auth.WebsocketRefreshApplicationEventListener;
import org.whispersystems.textsecuregcm.badges.ConfiguredProfileBadgeConverter;
import org.whispersystems.textsecuregcm.badges.ResourceBundleLevelTranslator;
import org.whispersystems.textsecuregcm.captcha.CaptchaChecker;
import org.whispersystems.textsecuregcm.captcha.HCaptchaClient;
import org.whispersystems.textsecuregcm.configuration.DirectoryServerConfiguration;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.controllers.AccountController;
@@ -104,6 +108,7 @@ import org.whispersystems.textsecuregcm.controllers.RemoteConfigController;
import org.whispersystems.textsecuregcm.controllers.SecureBackupController;
import org.whispersystems.textsecuregcm.controllers.SecureStorageController;
import org.whispersystems.textsecuregcm.controllers.StickerController;
import org.whispersystems.textsecuregcm.controllers.ArtController;
import org.whispersystems.textsecuregcm.controllers.SubscriptionController;
import org.whispersystems.textsecuregcm.controllers.VoiceVerificationController;
import org.whispersystems.textsecuregcm.currency.CoinMarketCapClient;
@@ -153,7 +158,7 @@ import org.whispersystems.textsecuregcm.push.ProvisioningManager;
import org.whispersystems.textsecuregcm.push.PushLatencyManager;
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
import org.whispersystems.textsecuregcm.push.ReceiptSender;
import org.whispersystems.textsecuregcm.recaptcha.RecaptchaClient;
import org.whispersystems.textsecuregcm.captcha.RecaptchaClient;
import org.whispersystems.textsecuregcm.redis.ConnectionEventLogger;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
import org.whispersystems.textsecuregcm.redis.ReplicatedJedisPool;
@@ -163,7 +168,6 @@ import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
import org.whispersystems.textsecuregcm.securebackup.SecureBackupClient;
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
import org.whispersystems.textsecuregcm.sqs.DirectoryQueue;
import org.whispersystems.textsecuregcm.storage.AbusiveHostRules;
import org.whispersystems.textsecuregcm.storage.AccountCleaner;
import org.whispersystems.textsecuregcm.storage.AccountDatabaseCrawler;
import org.whispersystems.textsecuregcm.storage.AccountDatabaseCrawlerCache;
@@ -201,6 +205,7 @@ import org.whispersystems.textsecuregcm.storage.ReportMessageManager;
import org.whispersystems.textsecuregcm.storage.StoredVerificationCodeManager;
import org.whispersystems.textsecuregcm.storage.SubscriptionManager;
import org.whispersystems.textsecuregcm.storage.VerificationCodeStore;
import org.whispersystems.textsecuregcm.subscriptions.BraintreeManager;
import org.whispersystems.textsecuregcm.subscriptions.StripeManager;
import org.whispersystems.textsecuregcm.util.Constants;
import org.whispersystems.textsecuregcm.util.DynamoDbFromConfig;
@@ -330,14 +335,14 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
config.getAppConfig().getConfigurationName(),
DynamicConfiguration.class);
BlockingQueue<Runnable> messageDeletionQueue = new ArrayBlockingQueue<>(10_000);
BlockingQueue<Runnable> messageDeletionQueue = new LinkedBlockingQueue<>();
Metrics.gaugeCollectionSize(name(getClass(), "messageDeletionQueueSize"), Collections.emptyList(),
messageDeletionQueue);
ExecutorService messageDeletionAsyncExecutor = environment.lifecycle()
.executorService(name(getClass(), "messageDeletionAsyncExecutor-%d")).maxThreads(16)
.workQueue(messageDeletionQueue).build();
Accounts accounts = new Accounts(dynamicConfigurationManager,
Accounts accounts = new Accounts(
dynamoDbClient,
dynamoDbAsyncClient,
config.getDynamoDbTables().getAccounts().getTableName(),
@@ -404,15 +409,17 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
ExecutorService fcmSenderExecutor = environment.lifecycle().executorService(name(getClass(), "fcmSender-%d")).maxThreads(32).minThreads(32).workQueue(fcmSenderQueue).build();
ExecutorService backupServiceExecutor = environment.lifecycle().executorService(name(getClass(), "backupService-%d")).maxThreads(1).minThreads(1).build();
ExecutorService storageServiceExecutor = environment.lifecycle().executorService(name(getClass(), "storageService-%d")).maxThreads(1).minThreads(1).build();
ExecutorService accountDeletionExecutor = environment.lifecycle().executorService(name(getClass(), "accountCleaner-%d")).maxThreads(16).minThreads(16).build();
// TODO: generally speaking this is a DynamoDB I/O executor for the accounts table; we should eventually have a general executor for speaking to the accounts table, but most of the server is still synchronous so this isn't widely useful yet
ExecutorService batchIdentityCheckExecutor = environment.lifecycle().executorService(name(getClass(), "batchIdentityCheck-%d")).minThreads(32).maxThreads(32).build();
ExecutorService multiRecipientMessageExecutor = environment.lifecycle()
.executorService(name(getClass(), "multiRecipientMessage-%d")).minThreads(64).maxThreads(64).build();
ExecutorService stripeExecutor = environment.lifecycle().executorService(name(getClass(), "stripe-%d")).
maxThreads(availableProcessors). // mostly this is IO bound so tying to number of processors is tenuous at best
minThreads(availableProcessors). // mostly this is IO bound so tying to number of processors is tenuous at best
allowCoreThreadTimeOut(true).
ExecutorService subscriptionProcessorExecutor = environment.lifecycle()
.executorService(name(getClass(), "subscriptionProcessor-%d"))
.maxThreads(availableProcessors) // mostly this is IO bound so tying to number of processors is tenuous at best
.minThreads(availableProcessors) // mostly this is IO bound so tying to number of processors is tenuous at best
.allowCoreThreadTimeOut(true).
build();
ExecutorService receiptSenderExecutor = environment.lifecycle()
.executorService(name(getClass(), "receiptSender-%d"))
@@ -435,8 +442,13 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
config.getAdminEventLoggingConfiguration().projectId(),
config.getAdminEventLoggingConfiguration().logName());
StripeManager stripeManager = new StripeManager(config.getStripe().getApiKey(), stripeExecutor,
config.getStripe().getIdempotencyKeyGenerator(), config.getStripe().getBoostDescription());
StripeManager stripeManager = new StripeManager(config.getStripe().apiKey(), subscriptionProcessorExecutor,
config.getStripe().idempotencyKeyGenerator(), config.getStripe().boostDescription(), config.getStripe()
.supportedCurrencies());
BraintreeManager braintreeManager = new BraintreeManager(config.getBraintree().merchantId(),
config.getBraintree().publicKey(), config.getBraintree().privateKey(), config.getBraintree().environment(),
config.getBraintree().supportedCurrencies(), config.getBraintree().merchantAccounts(),
config.getBraintree().graphqlUrl(), config.getBraintree().circuitBreaker(), subscriptionProcessorExecutor);
ExternalServiceCredentialGenerator directoryCredentialsGenerator = new ExternalServiceCredentialGenerator(
config.getDirectoryConfiguration().getDirectoryClientConfiguration().getUserAuthenticationTokenSharedSecret(),
@@ -456,8 +468,11 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
config.getSecureBackupServiceConfiguration().getUserAuthenticationTokenSharedSecret(), true);
ExternalServiceCredentialGenerator paymentsCredentialsGenerator = new ExternalServiceCredentialGenerator(
config.getPaymentsServiceConfiguration().getUserAuthenticationTokenSharedSecret(), true);
ExternalServiceCredentialGenerator artCredentialsGenerator = new ExternalServiceCredentialGenerator(
config.getArtServiceConfiguration().getUserAuthenticationTokenSharedSecret(),
config.getArtServiceConfiguration().getUserAuthenticationTokenUserIdSecret(),
true, false, false);
AbusiveHostRules abusiveHostRules = new AbusiveHostRules(rateLimitersCluster, dynamicConfigurationManager);
RegistrationServiceClient registrationServiceClient = new RegistrationServiceClient(config.getRegistrationServiceConfiguration().getHost(), config.getRegistrationServiceConfiguration().getPort(), config.getRegistrationServiceConfiguration().getApiKey(), config.getRegistrationServiceConfiguration().getRegistrationCaCertificate(), registrationCallbackExecutor);
SecureBackupClient secureBackupClient = new SecureBackupClient(backupCredentialsGenerator, backupServiceExecutor, config.getSecureBackupServiceConfiguration());
SecureStorageClient secureStorageClient = new SecureStorageClient(storageCredentialsGenerator, storageServiceExecutor, config.getSecureStorageServiceConfiguration());
@@ -512,13 +527,18 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
MessageSender messageSender = new MessageSender(clientPresenceManager, messagesManager, pushNotificationManager, pushLatencyManager);
ReceiptSender receiptSender = new ReceiptSender(accountsManager, messageSender, receiptSenderExecutor);
TurnTokenGenerator turnTokenGenerator = new TurnTokenGenerator(dynamicConfigurationManager);
RecaptchaClient recaptchaClient = new RecaptchaClient(
config.getRecaptchaConfiguration().getProjectPath(),
config.getRecaptchaConfiguration().getCredentialConfigurationJson(),
dynamicConfigurationManager);
HttpClient hcaptchaHttpClient = HttpClient.newBuilder().version(HttpClient.Version.HTTP_2).connectTimeout(Duration.ofSeconds(10)).build();
HCaptchaClient hCaptchaClient = new HCaptchaClient(config.getHCaptchaConfiguration().apiKey(), hcaptchaHttpClient, dynamicConfigurationManager);
CaptchaChecker captchaChecker = new CaptchaChecker(List.of(recaptchaClient, hCaptchaClient));
PushChallengeManager pushChallengeManager = new PushChallengeManager(pushNotificationManager, pushChallengeDynamoDb);
RateLimitChallengeManager rateLimitChallengeManager = new RateLimitChallengeManager(pushChallengeManager,
recaptchaClient, dynamicRateLimiters);
captchaChecker, dynamicRateLimiters);
MessagePersister messagePersister = new MessagePersister(messagesCache, messagesManager, accountsManager, dynamicConfigurationManager, Duration.ofMinutes(config.getMessageCacheConfiguration().getPersistDelayMinutes()));
ChangeNumberManager changeNumberManager = new ChangeNumberManager(messageSender, accountsManager);
@@ -554,7 +574,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new AccountDatabaseCrawlerCache(cacheCluster, AccountDatabaseCrawlerCache.ACCOUNT_CLEANER_PREFIX);
AccountDatabaseCrawler accountCleanerAccountDatabaseCrawler = new AccountDatabaseCrawler("Account cleaner crawler",
accountsManager,
accountCleanerAccountDatabaseCrawlerCache, List.of(new AccountCleaner(accountsManager)),
accountCleanerAccountDatabaseCrawlerCache, List.of(new AccountCleaner(accountsManager, accountDeletionExecutor)),
config.getAccountDatabaseCrawlerConfiguration().getChunkSize(),
config.getAccountDatabaseCrawlerConfiguration().getChunkIntervalMs()
);
@@ -653,56 +673,36 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
// these should be common, but use @Auth DisabledPermittedAccount, which isn’t supported yet on websocket
environment.jersey().register(
new AccountController(pendingAccountsManager, accountsManager, abusiveHostRules, rateLimiters,
new AccountController(pendingAccountsManager, accountsManager, rateLimiters,
registrationServiceClient, dynamicConfigurationManager, turnTokenGenerator, config.getTestDevices(),
recaptchaClient, pushNotificationManager, changeNumberManager, backupCredentialsGenerator,
captchaChecker, pushNotificationManager, changeNumberManager, backupCredentialsGenerator,
clientPresenceManager, clock));
environment.jersey().register(new KeysController(rateLimiters, keys, accountsManager));
final List<Object> commonControllers = Lists.newArrayList(
new AttachmentControllerV2(rateLimiters, config.getAwsAttachmentsConfiguration().getAccessKey(), config.getAwsAttachmentsConfiguration().getAccessSecret(), config.getAwsAttachmentsConfiguration().getRegion(), config.getAwsAttachmentsConfiguration().getBucket()),
new AttachmentControllerV3(rateLimiters, config.getGcpAttachmentsConfiguration().getDomain(), config.getGcpAttachmentsConfiguration().getEmail(), config.getGcpAttachmentsConfiguration().getMaxSizeInBytes(), config.getGcpAttachmentsConfiguration().getPathPrefix(), config.getGcpAttachmentsConfiguration().getRsaSigningKey()),
new CertificateController(new CertificateGenerator(config.getDeliveryCertificate().getCertificate(), config.getDeliveryCertificate().getPrivateKey(), config.getDeliveryCertificate().getExpiresDays()), zkAuthOperations, clock),
new ChallengeController(rateLimitChallengeManager),
new DeviceController(pendingDevicesManager, accountsManager, messagesManager, keys, rateLimiters, config.getMaxDevices()),
new DirectoryController(directoryCredentialsGenerator),
new DirectoryV2Controller(directoryV2CredentialsGenerator),
new DonationController(clock, zkReceiptOperations, redeemedReceiptsManager, accountsManager, config.getBadges(),
ReceiptCredentialPresentation::new),
new MessageController(rateLimiters, messageSender, receiptSender, accountsManager, deletedAccountsManager, messagesManager, pushNotificationManager, reportMessageManager, multiRecipientMessageExecutor),
new PaymentsController(currencyManager, paymentsCredentialsGenerator),
new ProfileController(clock, rateLimiters, accountsManager, profilesManager, dynamicConfigurationManager,
profileBadgeConverter, config.getBadges(), cdnS3Client, profileCdnPolicyGenerator, profileCdnPolicySigner,
config.getCdnConfiguration().getBucket(), zkProfileOperations, batchIdentityCheckExecutor),
new ProvisioningController(rateLimiters, provisioningManager),
new RemoteConfigController(remoteConfigsManager, adminEventLogger,
config.getRemoteConfigConfiguration().getAuthorizedTokens(),
config.getRemoteConfigConfiguration().getGlobalConfig()),
new SecureBackupController(backupCredentialsGenerator),
new SecureStorageController(storageCredentialsGenerator),
new StickerController(rateLimiters, config.getCdnConfiguration().getAccessKey(),
config.getCdnConfiguration().getAccessSecret(), config.getCdnConfiguration().getRegion(),
config.getCdnConfiguration().getBucket())
);
if (config.getSubscription() != null && config.getOneTimeDonations() != null) {
commonControllers.add(new SubscriptionController(clock, config.getSubscription(), config.getOneTimeDonations(),
subscriptionManager, stripeManager, zkReceiptOperations, issuedReceiptsManager, profileBadgeConverter,
resourceBundleLevelTranslator));
}
for (Object controller : commonControllers) {
environment.jersey().register(controller);
webSocketEnvironment.jersey().register(controller);
}
boolean registeredAbusiveMessageFilter = false;
ReportSpamTokenProvider reportSpamTokenProvider = null;
ReportSpamTokenHandler reportSpamTokenHandler = null;
for (final AbusiveMessageFilter filter : ServiceLoader.load(AbusiveMessageFilter.class)) {
if (filter.getClass().isAnnotationPresent(FilterAbusiveMessages.class)) {
try {
filter.configure(config.getAbusiveMessageFilterConfiguration().getEnvironment());
ReportSpamTokenProvider thisProvider = filter.getReportSpamTokenProvider();
if (reportSpamTokenProvider == null) {
reportSpamTokenProvider = thisProvider;
} else if (thisProvider != null) {
log.info("Multiple spam report token providers found. Using the first.");
}
ReportSpamTokenHandler thisHandler = filter.getReportSpamTokenHandler();
if (reportSpamTokenHandler == null) {
reportSpamTokenHandler = thisHandler;
} else if (thisProvider != null) {
log.info("Multiple spam report token handlers found. Using the first.");
}
environment.lifecycle().manage(filter);
environment.jersey().register(filter);
webSocketEnvironment.jersey().register(filter);
@@ -727,6 +727,52 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
log.warn("No abusive message filters installed");
}
if (reportSpamTokenProvider == null) {
reportSpamTokenProvider = ReportSpamTokenProvider.noop();
}
if (reportSpamTokenHandler == null) {
reportSpamTokenHandler = ReportSpamTokenHandler.noop();
}
final List<Object> commonControllers = Lists.newArrayList(
new ArtController(rateLimiters, artCredentialsGenerator),
new AttachmentControllerV2(rateLimiters, config.getAwsAttachmentsConfiguration().getAccessKey(), config.getAwsAttachmentsConfiguration().getAccessSecret(), config.getAwsAttachmentsConfiguration().getRegion(), config.getAwsAttachmentsConfiguration().getBucket()),
new AttachmentControllerV3(rateLimiters, config.getGcpAttachmentsConfiguration().getDomain(), config.getGcpAttachmentsConfiguration().getEmail(), config.getGcpAttachmentsConfiguration().getMaxSizeInBytes(), config.getGcpAttachmentsConfiguration().getPathPrefix(), config.getGcpAttachmentsConfiguration().getRsaSigningKey()),
new CertificateController(new CertificateGenerator(config.getDeliveryCertificate().getCertificate(), config.getDeliveryCertificate().getPrivateKey(), config.getDeliveryCertificate().getExpiresDays()), zkAuthOperations, clock),
new ChallengeController(rateLimitChallengeManager),
new DeviceController(pendingDevicesManager, accountsManager, messagesManager, keys, rateLimiters, config.getMaxDevices()),
new DirectoryController(directoryCredentialsGenerator),
new DirectoryV2Controller(directoryV2CredentialsGenerator),
new DonationController(clock, zkReceiptOperations, redeemedReceiptsManager, accountsManager, config.getBadges(),
ReceiptCredentialPresentation::new),
new MessageController(rateLimiters, messageSender, receiptSender, accountsManager, deletedAccountsManager, messagesManager, pushNotificationManager, reportMessageManager, multiRecipientMessageExecutor,
reportSpamTokenProvider, reportSpamTokenHandler),
new PaymentsController(currencyManager, paymentsCredentialsGenerator),
new ProfileController(clock, rateLimiters, accountsManager, profilesManager, dynamicConfigurationManager,
profileBadgeConverter, config.getBadges(), cdnS3Client, profileCdnPolicyGenerator, profileCdnPolicySigner,
config.getCdnConfiguration().getBucket(), zkProfileOperations, batchIdentityCheckExecutor),
new ProvisioningController(rateLimiters, provisioningManager),
new RemoteConfigController(remoteConfigsManager, adminEventLogger,
config.getRemoteConfigConfiguration().getAuthorizedTokens(),
config.getRemoteConfigConfiguration().getGlobalConfig()),
new SecureBackupController(backupCredentialsGenerator),
new SecureStorageController(storageCredentialsGenerator),
new StickerController(rateLimiters, config.getCdnConfiguration().getAccessKey(),
config.getCdnConfiguration().getAccessSecret(), config.getCdnConfiguration().getRegion(),
config.getCdnConfiguration().getBucket())
);
if (config.getSubscription() != null && config.getOneTimeDonations() != null) {
commonControllers.add(new SubscriptionController(clock, config.getSubscription(), config.getOneTimeDonations(),
subscriptionManager, stripeManager, braintreeManager, zkReceiptOperations, issuedReceiptsManager, profileBadgeConverter,
resourceBundleLevelTranslator));
}
for (Object controller : commonControllers) {
environment.jersey().register(controller);
webSocketEnvironment.jersey().register(controller);
}
WebSocketEnvironment<AuthenticatedAccount> provisioningEnvironment = new WebSocketEnvironment<>(environment,
webSocketEnvironment.getRequestLog(), 60000);
provisioningEnvironment.jersey().register(new WebsocketRefreshApplicationEventListener(accountsManager, clientPresenceManager));
@@ -30,4 +30,19 @@ public interface AbusiveMessageFilter extends ContainerRequestFilter, Managed {
* @throws IOException if the filter could not read its configuration source for any reason
*/
void configure(String environmentName) throws IOException;
/**
* Builds a spam report token provider. This will generate tokens used by the spam reporting system.
*
* @return the configured spam report token provider.
*/
ReportSpamTokenProvider getReportSpamTokenProvider();
/**
* Builds a spam report token handler. This will handle tokens received by the spam reporting system.
*
* @return the configured spam report token handler
*/
ReportSpamTokenHandler getReportSpamTokenHandler();
}
@@ -0,0 +1,47 @@
package org.whispersystems.textsecuregcm.abuse;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
/**
* Handles ReportSpamTokens during spam reports.
*/
public interface ReportSpamTokenHandler {
/**
* Handle spam reports using the given ReportSpamToken and other provided parameters.
*
* @param reportSpamToken binary data representing a spam report token.
* @return true if the token could be handled (and was), false otherwise.
*/
CompletableFuture<Boolean> handle(
Optional<String> sourceNumber,
Optional<UUID> sourceAci,
Optional<UUID> sourcePni,
UUID messageGuid,
UUID spamReporterUuid,
byte[] reportSpamToken);
/**
* Handler which does nothing.
*
* @return the handler
*/
static ReportSpamTokenHandler noop() {
return new ReportSpamTokenHandler() {
@Override
public CompletableFuture<Boolean> handle(
final Optional<String> sourceNumber,
final Optional<UUID> sourceAci,
final Optional<UUID> sourcePni,
final UUID messageGuid,
final UUID spamReporterUuid,
final byte[] reportSpamToken) {
return CompletableFuture.completedFuture(false);
}
};
}
}
@@ -0,0 +1,38 @@
package org.whispersystems.textsecuregcm.abuse;
import javax.ws.rs.container.ContainerRequestContext;
import java.util.Optional;
import java.util.function.Function;
/**
* Generates ReportSpamTokens to be used for spam reports.
*/
public interface ReportSpamTokenProvider {
/**
* Generate a new ReportSpamToken
*
* @param context the message request context
* @return either a generated token or nothing
*/
Optional<byte[]> makeReportSpamToken(ContainerRequestContext context);
/**
* Provider which generates nothing
*
* @return the provider
*/
static ReportSpamTokenProvider noop() {
return create(c -> Optional.empty());
}
/**
* Provider which generates ReportSpamTokens using the given function
*
* @param fn function from message requests to optional tokens
* @return the provider
*/
static ReportSpamTokenProvider create(Function<ContainerRequestContext, Optional<byte[]>> fn) {
return fn::apply;
}
}
@@ -7,6 +7,7 @@ package org.whispersystems.textsecuregcm.auth;
import com.google.common.annotations.VisibleForTesting;
import org.apache.commons.codec.binary.Hex;
import org.signal.libsignal.protocol.kdf.HKDF;
import org.whispersystems.textsecuregcm.util.Util;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
@@ -32,13 +33,13 @@ public class AuthenticationCredentials {
}
public AuthenticationCredentials(String authenticationToken) {
this.salt = String.valueOf(Math.abs(new SecureRandom().nextInt()));
this.salt = String.valueOf(Util.ensureNonNegativeInt(new SecureRandom().nextInt()));
this.hashedAuthenticationToken = getV2HashedValue(salt, authenticationToken);
}
@VisibleForTesting
public AuthenticationCredentials v1ForTesting(String authenticationToken) {
String salt = String.valueOf(Math.abs(new SecureRandom().nextInt()));
String salt = String.valueOf(Util.ensureNonNegativeInt(new SecureRandom().nextInt()));
return new AuthenticationCredentials(getV1HashedValue(salt, authenticationToken), salt);
}
@@ -27,9 +27,11 @@ import org.whispersystems.textsecuregcm.util.Util;
public class BaseAccountAuthenticator {
private static final String AUTHENTICATION_COUNTER_NAME = name(BaseAccountAuthenticator.class, "authentication");
private static final String ENABLED_NOT_REQUIRED_AUTHENTICATION_COUNTER_NAME = name(BaseAccountAuthenticator.class,
"enabledNotRequiredAuthentication");
private static final String AUTHENTICATION_SUCCEEDED_TAG_NAME = "succeeded";
private static final String AUTHENTICATION_FAILURE_REASON_TAG_NAME = "reason";
private static final String AUTHENTICATION_ENABLED_REQUIRED_TAG_NAME = "enabledRequired";
private static final String ENABLED_TAG_NAME = "enabled";
private static final String AUTHENTICATION_HAS_STORY_CAPABILITY = "hasStoryCapability";
private static final String STORY_ADOPTION_COUNTER_NAME = name(BaseAccountAuthenticator.class, "storyAdoption");
@@ -37,6 +39,9 @@ public class BaseAccountAuthenticator {
private static final String DAYS_SINCE_LAST_SEEN_DISTRIBUTION_NAME = name(BaseAccountAuthenticator.class, "daysSinceLastSeen");
private static final String IS_PRIMARY_DEVICE_TAG = "isPrimary";
@VisibleForTesting
static final char DEVICE_ID_SEPARATOR = '.';
private final AccountsManager accountsManager;
private final Clock clock;
@@ -54,7 +59,7 @@ public class BaseAccountAuthenticator {
final String identifier;
final long deviceId;
final int deviceIdSeparatorIndex = basicUsername.indexOf('.');
final int deviceIdSeparatorIndex = basicUsername.indexOf(DEVICE_ID_SEPARATOR);
if (deviceIdSeparatorIndex == -1) {
identifier = basicUsername;
@@ -99,15 +104,23 @@ public class BaseAccountAuthenticator {
}
if (enabledRequired) {
if (!device.get().isEnabled()) {
final boolean deviceDisabled = !device.get().isEnabled();
if (deviceDisabled) {
failureReason = "deviceDisabled";
return Optional.empty();
}
if (!account.get().isEnabled()) {
final boolean accountDisabled = !account.get().isEnabled();
if (accountDisabled) {
failureReason = "accountDisabled";
}
if (accountDisabled || deviceDisabled) {
return Optional.empty();
}
} else {
Metrics.counter(ENABLED_NOT_REQUIRED_AUTHENTICATION_COUNTER_NAME,
ENABLED_TAG_NAME, String.valueOf(device.get().isEnabled() && account.get().isEnabled()),
IS_PRIMARY_DEVICE_TAG, String.valueOf(device.get().isMaster()))
.increment();
}
AuthenticationCredentials deviceAuthenticationCredentials = device.get().getAuthenticationCredentials();
@@ -130,8 +143,7 @@ public class BaseAccountAuthenticator {
return Optional.empty();
} finally {
Tags tags = Tags.of(
AUTHENTICATION_SUCCEEDED_TAG_NAME, String.valueOf(succeeded),
AUTHENTICATION_ENABLED_REQUIRED_TAG_NAME, String.valueOf(enabledRequired));
AUTHENTICATION_SUCCEEDED_TAG_NAME, String.valueOf(succeeded));
if (StringUtils.isNotBlank(failureReason)) {
tags = tags.and(AUTHENTICATION_FAILURE_REASON_TAG_NAME, failureReason);
@@ -146,9 +158,18 @@ public class BaseAccountAuthenticator {
@VisibleForTesting
public Account updateLastSeen(Account account, Device device) {
final long lastSeenOffsetSeconds = Math.abs(account.getUuid().getLeastSignificantBits()) % ChronoUnit.DAYS.getDuration().toSeconds();
// compute a non-negative integer between 0 and 86400.
long n = Util.ensureNonNegativeLong(account.getUuid().getLeastSignificantBits());
final long lastSeenOffsetSeconds = n % ChronoUnit.DAYS.getDuration().toSeconds();
// produce a truncated timestamp which is either today at UTC midnight
// or yesterday at UTC midnight, based on per-user randomized offset used.
final long todayInMillisWithOffset = Util.todayInMillisGivenOffsetFromNow(clock, Duration.ofSeconds(lastSeenOffsetSeconds).negated());
// only update the device's last seen time when it falls behind the truncated timestamp.
// this ensure a few things:
// (1) each account will only update last-seen at most once per day
// (2) these updates will occur throughout the day rather than all occurring at UTC midnight.
if (device.getLastSeen() < todayInMillisWithOffset) {
Metrics.summary(DAYS_SINCE_LAST_SEEN_DISTRIBUTION_NAME, IS_PRIMARY_DEVICE_TAG, String.valueOf(device.isMaster()))
.record(Duration.ofMillis(todayInMillisWithOffset - device.getLastSeen()).toDays());
@@ -9,9 +9,9 @@ import com.google.common.annotations.VisibleForTesting;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.Clock;
import java.util.HexFormat;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Hex;
import org.whispersystems.textsecuregcm.util.Util;
public class ExternalServiceCredentialGenerator {
@@ -20,33 +20,50 @@ public class ExternalServiceCredentialGenerator {
private final byte[] userIdKey;
private final boolean usernameDerivation;
private final boolean prependUsername;
private final boolean truncateKey;
private final Clock clock;
public ExternalServiceCredentialGenerator(byte[] key, byte[] userIdKey) {
this(key, userIdKey, true, true);
this(key, userIdKey, true, true, true);
}
public ExternalServiceCredentialGenerator(byte[] key, boolean prependUsername) {
this(key, new byte[0], false, prependUsername);
this(key, prependUsername, true);
}
public ExternalServiceCredentialGenerator(byte[] key, boolean prependUsername, boolean truncateKey) {
this(key, new byte[0], false, prependUsername, truncateKey);
}
@VisibleForTesting
public ExternalServiceCredentialGenerator(byte[] key, byte[] userIdKey, boolean usernameDerivation) {
this(key, userIdKey, usernameDerivation, true);
this(key, userIdKey, usernameDerivation, true, true);
}
public ExternalServiceCredentialGenerator(byte[] key, byte[] userIdKey, boolean usernameDerivation,
boolean prependUsername) {
this(key, userIdKey, usernameDerivation, prependUsername, Clock.systemUTC());
this(key, userIdKey, usernameDerivation, prependUsername, true, Clock.systemUTC());
}
public ExternalServiceCredentialGenerator(byte[] key, byte[] userIdKey, boolean usernameDerivation,
boolean prependUsername, boolean truncateKey) {
this(key, userIdKey, usernameDerivation, prependUsername, truncateKey, Clock.systemUTC());
}
@VisibleForTesting
public ExternalServiceCredentialGenerator(byte[] key, byte[] userIdKey, boolean usernameDerivation,
boolean prependUsername, Clock clock) {
this(key, userIdKey, usernameDerivation, prependUsername, true, clock);
}
@VisibleForTesting
public ExternalServiceCredentialGenerator(byte[] key, byte[] userIdKey, boolean usernameDerivation,
boolean prependUsername, boolean truncateKey, Clock clock) {
this.key = key;
this.userIdKey = userIdKey;
this.usernameDerivation = usernameDerivation;
this.prependUsername = prependUsername;
this.truncateKey = truncateKey;
this.clock = clock;
}
@@ -55,14 +72,17 @@ public class ExternalServiceCredentialGenerator {
String username = getUserId(identity, mac, usernameDerivation);
long currentTimeSeconds = clock.millis() / 1000;
String prefix = username + ":" + currentTimeSeconds;
String output = Hex.encodeHexString(Util.truncate(getHmac(key, prefix.getBytes(), mac), 10));
byte[] prefixMac = getHmac(key, prefix.getBytes(), mac);
final HexFormat hex = HexFormat.of();
String output = hex.formatHex(truncateKey ? Util.truncate(prefixMac, 10) : prefixMac);
String token = (prependUsername ? prefix : currentTimeSeconds) + ":" + output;
return new ExternalServiceCredentials(username, token);
}
private String getUserId(String number, Mac mac, boolean usernameDerivation) {
if (usernameDerivation) return Hex.encodeHexString(Util.truncate(getHmac(userIdKey, number.getBytes(), mac), 10));
final HexFormat hex = HexFormat.of();
if (usernameDerivation) return hex.formatHex(Util.truncate(getHmac(userIdKey, number.getBytes(), mac), 10));
else return number;
}
@@ -6,28 +6,6 @@
package org.whispersystems.textsecuregcm.auth;
import com.fasterxml.jackson.annotation.JsonProperty;
public record ExternalServiceCredentials(String username, String password) {
public class ExternalServiceCredentials {
@JsonProperty
private String username;
@JsonProperty
private String password;
public ExternalServiceCredentials(String username, String password) {
this.username = username;
this.password = password;
}
public ExternalServiceCredentials() {}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
}
@@ -13,7 +13,6 @@ import org.whispersystems.textsecuregcm.util.Util;
public record StoredVerificationCode(String code,
long timestamp,
String pushCode,
@Nullable String twilioVerificationSid,
@Nullable byte[] sessionId) {
public static final Duration EXPIRATION = Duration.ofMinutes(10);
@@ -10,6 +10,7 @@ import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfigurati
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicTurnConfiguration;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.util.Pair;
import org.whispersystems.textsecuregcm.util.Util;
import org.whispersystems.textsecuregcm.util.WeightedRandomSelect;
import javax.crypto.Mac;
@@ -36,7 +37,7 @@ public class TurnTokenGenerator {
List<String> urls = urls(e164);
Mac mac = Mac.getInstance("HmacSHA1");
long validUntilSeconds = (System.currentTimeMillis() + TimeUnit.DAYS.toMillis(1)) / 1000;
long user = Math.abs(new SecureRandom().nextInt());
long user = Util.ensureNonNegativeInt(new SecureRandom().nextInt());
String userTime = validUntilSeconds + ":" + user;
mac.init(new SecretKeySpec(key, "HmacSHA1"));
@@ -0,0 +1,27 @@
/*
* Copyright 2022 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.captcha;
/**
* A captcha assessment
*
* @param valid whether the captcha was passed
* @param score string representation of the risk level
*/
public record AssessmentResult(boolean valid, String score) {
public static AssessmentResult invalid() {
return new AssessmentResult(false, "");
}
/**
* Map a captcha score in [0.0, 1.0] to a low cardinality discrete space in [0, 100] suitable for use in metrics
*/
static String scoreString(final float score) {
final int x = Math.round(score * 10); // [0, 10]
return Integer.toString(x * 10); // [0, 100] in increments of 10
}
}
@@ -0,0 +1,76 @@
/*
* Copyright 2022 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.captcha;
import com.google.common.annotations.VisibleForTesting;
import io.micrometer.core.instrument.Metrics;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.ws.rs.BadRequestException;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
public class CaptchaChecker {
private static final String ASSESSMENTS_COUNTER_NAME = name(RecaptchaClient.class, "assessments");
@VisibleForTesting
static final String SEPARATOR = ".";
private final Map<String, CaptchaClient> captchaClientMap;
public CaptchaChecker(final List<CaptchaClient> captchaClients) {
this.captchaClientMap = captchaClients.stream()
.collect(Collectors.toMap(CaptchaClient::scheme, Function.identity()));
}
/**
* Check if a solved captcha should be accepted
* <p>
*
* @param input expected to contain a prefix indicating the captcha scheme, sitekey, token, and action. The expected
* format is {@code version-prefix.sitekey.[action.]token}
* @param ip IP of the solver
* @return An {@link AssessmentResult} indicating whether the solution should be accepted, and a score that can be
* used for metrics
* @throws IOException if there is an error validating the captcha with the underlying service
* @throws BadRequestException if input is not in the expected format
*/
public AssessmentResult verify(final String input, final String ip) throws IOException {
/*
* For action to be optional, there is a strong assumption that the token will never contain a {@value SEPARATOR}.
* Observation suggests {@code token} is base-64 encoded. In practice, an action should always be present, but we
* don’t need to be strict.
*/
final String[] parts = input.split("\\" + SEPARATOR, 4);
// we allow missing actions, if we're missing 1 part, assume it's the action
if (parts.length < 3) {
throw new BadRequestException("too few parts");
}
int idx = 0;
final String prefix = parts[idx++];
final String siteKey = parts[idx++];
final String action = parts.length == 3 ? null : parts[idx++];
final String token = parts[idx];
final CaptchaClient client = this.captchaClientMap.get(prefix);
if (client == null) {
throw new BadRequestException("invalid captcha scheme");
}
final AssessmentResult result = client.verify(siteKey, action, token, ip);
Metrics.counter(ASSESSMENTS_COUNTER_NAME,
"action", String.valueOf(action),
"valid", String.valueOf(result.valid()),
"score", result.score(),
"provider", prefix)
.increment();
return result;
}
}
@@ -0,0 +1,33 @@
/*
* Copyright 2022 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.captcha;
import javax.annotation.Nullable;
import java.io.IOException;
public interface CaptchaClient {
/**
* @return the identifying captcha scheme that this CaptchaClient handles
*/
String scheme();
/**
* Verify a provided captcha solution
*
* @param siteKey identifying string for the captcha service
* @param action an optional action indicating the purpose of the captcha
* @param token the captcha solution that will be verified
* @param ip the ip of the captcha solve
* @return An {@link AssessmentResult} indicating whether the solution should be accepted
* @throws IOException if the underlying captcha provider returns an error
*/
AssessmentResult verify(
final String siteKey,
final @Nullable String action,
final String token,
final String ip) throws IOException;
}
@@ -0,0 +1,114 @@
/*
* Copyright 2021-2022 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.captcha;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import io.micrometer.core.instrument.Metrics;
import java.io.IOException;
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import javax.annotation.Nullable;
import javax.ws.rs.core.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicCaptchaConfiguration;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.util.SystemMapper;
public class HCaptchaClient implements CaptchaClient {
private static final Logger logger = LoggerFactory.getLogger(HCaptchaClient.class);
private static final String PREFIX = "signal-hcaptcha";
private static final String ASSESSMENT_REASON_COUNTER_NAME = name(HCaptchaClient.class, "assessmentReason");
private static final String INVALID_REASON_COUNTER_NAME = name(HCaptchaClient.class, "invalidReason");
private final String apiKey;
private final HttpClient client;
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
public HCaptchaClient(
final String apiKey,
final HttpClient client,
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
this.apiKey = apiKey;
this.client = client;
this.dynamicConfigurationManager = dynamicConfigurationManager;
}
@Override
public String scheme() {
return PREFIX;
}
@Override
public AssessmentResult verify(final String siteKey, final @Nullable String action, final String token,
final String ip)
throws IOException {
final DynamicCaptchaConfiguration config = dynamicConfigurationManager.getConfiguration().getCaptchaConfiguration();
if (!config.isAllowHCaptcha()) {
logger.warn("Received request to verify an hCaptcha, but hCaptcha is not enabled");
return AssessmentResult.invalid();
}
final String body = String.format("response=%s&secret=%s&remoteip=%s",
URLEncoder.encode(token, StandardCharsets.UTF_8),
URLEncoder.encode(this.apiKey, StandardCharsets.UTF_8),
ip);
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://hcaptcha.com/siteverify"))
.header("Content-Type", "application/x-www-form-urlencoded")
.POST(HttpRequest.BodyPublishers.ofString(body))
.build();
HttpResponse<String> response;
try {
response = this.client.send(request, HttpResponse.BodyHandlers.ofString());
} catch (InterruptedException e) {
throw new IOException(e);
}
if (response.statusCode() != Response.Status.OK.getStatusCode()) {
logger.warn("failure submitting token to hCaptcha (code={}): {}", response.statusCode(), response);
throw new IOException("hCaptcha http failure : " + response.statusCode());
}
final HCaptchaResponse hCaptchaResponse = SystemMapper.getMapper()
.readValue(response.body(), HCaptchaResponse.class);
logger.debug("received hCaptcha response: {}", hCaptchaResponse);
if (!hCaptchaResponse.success) {
for (String errorCode : hCaptchaResponse.errorCodes) {
Metrics.counter(INVALID_REASON_COUNTER_NAME,
"action", String.valueOf(action),
"reason", errorCode).increment();
}
return AssessmentResult.invalid();
}
// hcaptcha uses the inverse scheme of recaptcha (for hcaptcha, a low score is less risky)
float score = 1.0f - hCaptchaResponse.score;
if (score < 0.0f || score > 1.0f) {
logger.error("Invalid score {} from hcaptcha response {}", hCaptchaResponse.score, hCaptchaResponse);
return AssessmentResult.invalid();
}
final String scoreString = AssessmentResult.scoreString(score);
for (String reason : hCaptchaResponse.scoreReasons) {
Metrics.counter(ASSESSMENT_REASON_COUNTER_NAME,
"action", String.valueOf(action),
"reason", reason,
"score", scoreString).increment();
}
return new AssessmentResult(score >= config.getScoreFloor().floatValue(), scoreString);
}
}
@@ -0,0 +1,57 @@
/*
* Copyright 2022 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.captcha;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.time.Duration;
import java.util.Collections;
import java.util.List;
/**
* Verify response returned by hcaptcha
* <p>
* see <a href="https://docs.hcaptcha.com/#verify-the-user-response-server-side">...</a>
*/
public class HCaptchaResponse {
@JsonProperty
boolean success;
@JsonProperty(value = "challenge-ts")
Duration challengeTs;
@JsonProperty
String hostname;
@JsonProperty
boolean credit;
@JsonProperty(value = "error-codes")
List<String> errorCodes = Collections.emptyList();
@JsonProperty
float score;
@JsonProperty(value = "score-reasons")
List<String> scoreReasons = Collections.emptyList();
public HCaptchaResponse() {
}
@Override
public String toString() {
return "HCaptchaResponse{" +
"success=" + success +
", challengeTs=" + challengeTs +
", hostname='" + hostname + '\'' +
", credit=" + credit +
", errorCodes=" + errorCodes +
", score=" + score +
", scoreReasons=" + scoreReasons +
'}';
}
}
@@ -3,15 +3,15 @@
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.recaptcha;
package org.whispersystems.textsecuregcm.captcha;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.api.gax.rpc.ApiException;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.cloud.recaptchaenterprise.v1.RecaptchaEnterpriseServiceClient;
import com.google.cloud.recaptchaenterprise.v1.RecaptchaEnterpriseServiceSettings;
import com.google.common.annotations.VisibleForTesting;
import com.google.recaptchaenterprise.v1.Assessment;
import com.google.recaptchaenterprise.v1.Event;
import com.google.recaptchaenterprise.v1.RiskAnalysis;
@@ -21,22 +21,18 @@ import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
import javax.annotation.Nonnull;
import javax.ws.rs.BadRequestException;
import org.apache.commons.lang3.StringUtils;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicCaptchaConfiguration;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
public class RecaptchaClient {
public class RecaptchaClient implements CaptchaClient {
private static final Logger log = LoggerFactory.getLogger(RecaptchaClient.class);
@VisibleForTesting
static final String SEPARATOR = ".";
@VisibleForTesting
static final String V2_PREFIX = "signal-recaptcha-v2" + RecaptchaClient.SEPARATOR;
private static final String ASSESSMENTS_COUNTER_NAME = name(RecaptchaClient.class, "assessments");
private static final String V2_PREFIX = "signal-recaptcha-v2";
private static final String INVALID_REASON_COUNTER_NAME = name(RecaptchaClient.class, "invalidReason");
private static final String ASSESSMENT_REASON_COUNTER_NAME = name(RecaptchaClient.class, "assessmentReason");
@@ -61,57 +57,20 @@ public class RecaptchaClient {
}
}
/**
* Parses the sitekey, token, and action (if any) from {@code input}. The expected input format is: {@code [version
* prefix.]sitekey.[action.]token}.
* <p>
* For action to be optional, there is a strong assumption that the token will never contain a {@value SEPARATOR}.
* Observation suggests {@code token} is base-64 encoded. In practice, an action should always be present, but we
* don’t need to be strict.
*/
static String[] parseInputToken(final String input) {
String[] parts = StringUtils.removeStart(input, V2_PREFIX).split("\\" + SEPARATOR, 3);
if (parts.length == 1) {
throw new BadRequestException("too few parts");
}
if (parts.length == 2) {
// we got some parts, assume it is action that is missing
return new String[]{parts[0], null, parts[1]};
}
return parts;
@Override
public String scheme() {
return V2_PREFIX;
}
/**
* A captcha assessment
*
* @param valid whether the captcha was passed
* @param score string representation of the risk level
*/
public record AssessmentResult(boolean valid, String score) {
public static AssessmentResult invalid() {
return new AssessmentResult(false, "");
@Override
public org.whispersystems.textsecuregcm.captcha.AssessmentResult verify(final String sitekey,
final @Nullable String expectedAction,
final String token, final String ip) throws IOException {
final DynamicCaptchaConfiguration config = dynamicConfigurationManager.getConfiguration().getCaptchaConfiguration();
if (!config.isAllowRecaptcha()) {
log.warn("Received request to verify a recaptcha, but recaptcha is not enabled");
return AssessmentResult.invalid();
}
}
/*
* recaptcha enterprise scores are from [0.0, 1.0] in increments of .1
* map to [0, 100] for easier interpretation
*/
@VisibleForTesting
static String scoreString(final float score) {
return Integer.toString((int) (score * 100));
}
public AssessmentResult verify(final String input, final String ip) {
final String[] parts = parseInputToken(input);
final String sitekey = parts[0];
final String expectedAction = parts[1];
final String token = parts[2];
Event.Builder eventBuilder = Event.newBuilder()
.setSiteKey(sitekey)
@@ -123,32 +82,30 @@ public class RecaptchaClient {
}
final Event event = eventBuilder.build();
final Assessment assessment = client.createAssessment(projectPath, Assessment.newBuilder().setEvent(event).build());
Metrics.counter(ASSESSMENTS_COUNTER_NAME,
"action", String.valueOf(expectedAction),
"valid", String.valueOf(assessment.getTokenProperties().getValid()))
.increment();
final Assessment assessment;
try {
assessment = client.createAssessment(projectPath, Assessment.newBuilder().setEvent(event).build());
} catch (ApiException e) {
throw new IOException(e);
}
if (assessment.getTokenProperties().getValid()) {
final float score = assessment.getRiskAnalysis().getScore();
log.debug("assessment for {} was valid, score: {}", expectedAction, score);
for (RiskAnalysis.ClassificationReason reason : assessment.getRiskAnalysis().getReasonsList()) {
Metrics.counter(ASSESSMENT_REASON_COUNTER_NAME,
"action", String.valueOf(expectedAction),
"score", scoreString(score),
"reason", reason.name())
"action", String.valueOf(expectedAction),
"score", AssessmentResult.scoreString(score),
"reason", reason.name())
.increment();
}
return new AssessmentResult(
score >=
dynamicConfigurationManager.getConfiguration().getCaptchaConfiguration().getScoreFloor().floatValue(),
scoreString(score));
score >= config.getScoreFloor().floatValue(),
AssessmentResult.scoreString(score));
} else {
Metrics.counter(INVALID_REASON_COUNTER_NAME,
"action", String.valueOf(expectedAction),
"reason", assessment.getTokenProperties().getInvalidReason().name())
"action", String.valueOf(expectedAction),
"reason", assessment.getTokenProperties().getInvalidReason().name())
.increment();
return AssessmentResult.invalid();
}
@@ -0,0 +1,41 @@
/*
* Copyright 2022 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;
import java.time.Duration;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
public class ArtServiceConfiguration {
@NotEmpty
@JsonProperty
private String userAuthenticationTokenSharedSecret;
@NotEmpty
@JsonProperty
private String userAuthenticationTokenUserIdSecret;
@JsonProperty
@NotNull
private Duration tokenExpiration = Duration.ofDays(1);
public byte[] getUserAuthenticationTokenSharedSecret() throws DecoderException {
return Hex.decodeHex(userAuthenticationTokenSharedSecret.toCharArray());
}
public byte[] getUserAuthenticationTokenUserIdSecret() throws DecoderException {
return Hex.decodeHex(userAuthenticationTokenUserIdSecret.toCharArray());
}
public Duration getTokenExpiration() {
return tokenExpiration;
}
}
@@ -0,0 +1,44 @@
/*
* Copyright 2022 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration;
import java.util.Map;
import java.util.Set;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
/**
* @param merchantId the Braintree merchant ID
* @param publicKey the Braintree API public key
* @param privateKey the Braintree API private key
* @param environment the Braintree environment ("production" or "sandbox")
* @param supportedCurrencies the set of supported currencies
* @param graphqlUrl the Braintree GraphQL URl to use (this must match the environment)
* @param merchantAccounts merchant account within the merchant for processing individual currencies
* @param circuitBreaker configuration for the circuit breaker used by the GraphQL HTTP client
*/
public record BraintreeConfiguration(@NotBlank String merchantId,
@NotBlank String publicKey,
@NotBlank String privateKey,
@NotBlank String environment,
@NotEmpty Set<@NotBlank String> supportedCurrencies,
@NotBlank String graphqlUrl,
@NotEmpty Map<String, String> merchantAccounts,
@NotNull
@Valid
CircuitBreakerConfiguration circuitBreaker) {
public BraintreeConfiguration {
if (circuitBreaker == null) {
// It’s a little counter-intuitive, but this compact constructor allows a default value
// to be used when one isn’t specified (e.g. in YAML), allowing the field to still be
// validated as @NotNull
circuitBreaker = new CircuitBreakerConfiguration();
}
}
}
@@ -0,0 +1,11 @@
/*
* Copyright 2021-2022 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration;
import javax.validation.constraints.NotBlank;
public record HCaptchaConfiguration(@NotBlank String apiKey) {
}
@@ -20,11 +20,11 @@ import org.whispersystems.textsecuregcm.util.ExactlySize;
* @param boosts the list of suggested one-time donation amounts
*/
public record OneTimeDonationCurrencyConfiguration(
@DecimalMin("0.01") BigDecimal minimum,
@DecimalMin("0.01") BigDecimal gift,
@NotNull @DecimalMin("0.01") BigDecimal minimum,
@NotNull @DecimalMin("0.01") BigDecimal gift,
@Valid
@ExactlySize(6)
@NotNull
List<@DecimalMin("0.01") BigDecimal> boosts) {
List<@NotNull @DecimalMin("0.01") BigDecimal> boosts) {
}
@@ -56,6 +56,9 @@ public class RateLimitsConfiguration {
@JsonProperty
private RateLimitConfiguration stickerPack = new RateLimitConfiguration(50, 20 / (24.0 * 60.0));
@JsonProperty
private RateLimitConfiguration artPack = new RateLimitConfiguration(50, 20 / (24.0 * 60.0));
@JsonProperty
private RateLimitConfiguration usernameLookup = new RateLimitConfiguration(100, 100 / (24.0 * 60.0));
@@ -135,6 +138,10 @@ public class RateLimitsConfiguration {
return stickerPack;
}
public RateLimitConfiguration getArtPack() {
return artPack;
}
public RateLimitConfiguration getUsernameLookup() {
return usernameLookup;
}
@@ -5,38 +5,13 @@
package org.whispersystems.textsecuregcm.configuration;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Set;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
public class StripeConfiguration {
public record StripeConfiguration(@NotBlank String apiKey,
@NotEmpty byte[] idempotencyKeyGenerator,
@NotBlank String boostDescription,
@NotEmpty Set<@NotBlank String> supportedCurrencies) {
private final String apiKey;
private final byte[] idempotencyKeyGenerator;
private final String boostDescription;
@JsonCreator
public StripeConfiguration(
@JsonProperty("apiKey") final String apiKey,
@JsonProperty("idempotencyKeyGenerator") final byte[] idempotencyKeyGenerator,
@JsonProperty("boostDescription") final String boostDescription) {
this.apiKey = apiKey;
this.idempotencyKeyGenerator = idempotencyKeyGenerator;
this.boostDescription = boostDescription;
}
@NotEmpty
public String getApiKey() {
return apiKey;
}
@NotEmpty
public byte[] getIdempotencyKeyGenerator() {
return idempotencyKeyGenerator;
}
@NotEmpty
public String getBoostDescription() {
return boostDescription;
}
}
@@ -5,31 +5,16 @@
package org.whispersystems.textsecuregcm.configuration;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.math.BigDecimal;
import java.util.Map;
import javax.validation.Valid;
import javax.validation.constraints.DecimalMin;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessor;
public class SubscriptionPriceConfiguration {
public record SubscriptionPriceConfiguration(@Valid @NotEmpty Map<SubscriptionProcessor, @NotBlank String> processorIds,
@NotNull @DecimalMin("0.01") BigDecimal amount) {
private final String id;
private final BigDecimal amount;
@JsonCreator
public SubscriptionPriceConfiguration(
@JsonProperty("id") @NotEmpty String id,
@JsonProperty("amount") @NotNull @DecimalMin("0.01") BigDecimal amount) {
this.id = id;
this.amount = amount;
}
public String getId() {
return id;
}
public BigDecimal getAmount() {
return amount;
}
}
@@ -1,3 +1,8 @@
/*
* Copyright 2022 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration.dynamic;
import com.fasterxml.jackson.annotation.JsonProperty;
@@ -17,6 +22,12 @@ public class DynamicCaptchaConfiguration {
@NotNull
private BigDecimal scoreFloor;
@JsonProperty
private boolean allowHCaptcha = false;
@JsonProperty
private boolean allowRecaptcha = true;
@JsonProperty
@NotNull
private Set<String> signupCountryCodes = Collections.emptySet();
@@ -46,4 +57,22 @@ public class DynamicCaptchaConfiguration {
public Set<String> getSignupRegions() {
return signupRegions;
}
public boolean isAllowHCaptcha() {
return allowHCaptcha;
}
public boolean isAllowRecaptcha() {
return allowRecaptcha;
}
@VisibleForTesting
public void setAllowHCaptcha(final boolean allowHCaptcha) {
this.allowHCaptcha = allowHCaptcha;
}
@VisibleForTesting
public void setScoreFloor(final BigDecimal scoreFloor) {
this.scoreFloor = scoreFloor;
}
}
@@ -16,16 +16,20 @@ import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber;
import io.dropwizard.auth.Auth;
import io.micrometer.core.instrument.DistributionSummary;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import java.io.IOException;
import java.security.SecureRandom;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletionException;
import javax.annotation.Nullable;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
@@ -63,6 +67,8 @@ import org.whispersystems.textsecuregcm.auth.StoredRegistrationLock;
import org.whispersystems.textsecuregcm.auth.StoredVerificationCode;
import org.whispersystems.textsecuregcm.auth.TurnToken;
import org.whispersystems.textsecuregcm.auth.TurnTokenGenerator;
import org.whispersystems.textsecuregcm.captcha.AssessmentResult;
import org.whispersystems.textsecuregcm.captcha.CaptchaChecker;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicCaptchaConfiguration;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
@@ -87,11 +93,9 @@ import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
import org.whispersystems.textsecuregcm.push.PushNotification;
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
import org.whispersystems.textsecuregcm.recaptcha.RecaptchaClient;
import org.whispersystems.textsecuregcm.registration.ClientType;
import org.whispersystems.textsecuregcm.registration.MessageTransport;
import org.whispersystems.textsecuregcm.registration.RegistrationServiceClient;
import org.whispersystems.textsecuregcm.storage.AbusiveHostRules;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.ChangeNumberManager;
@@ -101,8 +105,8 @@ import org.whispersystems.textsecuregcm.storage.StoredVerificationCodeManager;
import org.whispersystems.textsecuregcm.storage.UsernameNotAvailableException;
import org.whispersystems.textsecuregcm.storage.UsernameReservationNotFoundException;
import org.whispersystems.textsecuregcm.util.Constants;
import org.whispersystems.textsecuregcm.util.Hex;
import org.whispersystems.textsecuregcm.util.HeaderUtils;
import org.whispersystems.textsecuregcm.util.Hex;
import org.whispersystems.textsecuregcm.util.ImpossiblePhoneNumberException;
import org.whispersystems.textsecuregcm.util.NonNormalizedPhoneNumberException;
import org.whispersystems.textsecuregcm.util.Optionals;
@@ -115,8 +119,6 @@ public class AccountController {
private final Logger logger = LoggerFactory.getLogger(AccountController.class);
private final MetricRegistry metricRegistry = SharedMetricRegistries.getOrCreate(Constants.METRICS_NAME);
private final Meter blockedHostMeter = metricRegistry.meter(name(AccountController.class, "blocked_host" ));
private final Meter countryFilterApplicable = metricRegistry.meter(name(AccountController.class, "country_filter_applicable"));
private final Meter countryFilteredHostMeter = metricRegistry.meter(name(AccountController.class, "country_limited_host" ));
private final Meter rateLimitedHostMeter = metricRegistry.meter(name(AccountController.class, "rate_limited_host" ));
private final Meter rateLimitedPrefixMeter = metricRegistry.meter(name(AccountController.class, "rate_limited_prefix" ));
@@ -128,6 +130,12 @@ public class AccountController {
private static final String CAPTCHA_ATTEMPT_COUNTER_NAME = name(AccountController.class, "captcha");
private static final String CHALLENGE_ISSUED_COUNTER_NAME = name(AccountController.class, "challengeIssued");
private static final DistributionSummary REREGISTRATION_IDLE_DAYS_DISTRIBUTION = DistributionSummary
.builder(name(AccountController.class, "reregistrationIdleDays"))
.publishPercentiles(0.75, 0.95, 0.99, 0.999)
.distributionStatisticExpiry(Duration.ofHours(2))
.register(Metrics.globalRegistry);
private static final String NONSTANDARD_USERNAME_COUNTER_NAME = name(AccountController.class, "nonStandardUsername");
private static final String LOCKED_ACCOUNT_COUNTER_NAME = name(AccountController.class, "lockedAccount");
@@ -150,13 +158,12 @@ public class AccountController {
private final StoredVerificationCodeManager pendingAccounts;
private final AccountsManager accounts;
private final AbusiveHostRules abusiveHostRules;
private final RateLimiters rateLimiters;
private final RegistrationServiceClient registrationServiceClient;
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
private final TurnTokenGenerator turnTokenGenerator;
private final Map<String, Integer> testDevices;
private final RecaptchaClient recaptchaClient;
private final CaptchaChecker captchaChecker;
private final PushNotificationManager pushNotificationManager;
private final ExternalServiceCredentialGenerator backupServiceCredentialGenerator;
@@ -171,13 +178,12 @@ public class AccountController {
public AccountController(
StoredVerificationCodeManager pendingAccounts,
AccountsManager accounts,
AbusiveHostRules abusiveHostRules,
RateLimiters rateLimiters,
RegistrationServiceClient registrationServiceClient,
DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
TurnTokenGenerator turnTokenGenerator,
Map<String, Integer> testDevices,
RecaptchaClient recaptchaClient,
CaptchaChecker captchaChecker,
PushNotificationManager pushNotificationManager,
ChangeNumberManager changeNumberManager,
ExternalServiceCredentialGenerator backupServiceCredentialGenerator,
@@ -186,13 +192,12 @@ public class AccountController {
) {
this.pendingAccounts = pendingAccounts;
this.accounts = accounts;
this.abusiveHostRules = abusiveHostRules;
this.rateLimiters = rateLimiters;
this.registrationServiceClient = registrationServiceClient;
this.dynamicConfigurationManager = dynamicConfigurationManager;
this.testDevices = testDevices;
this.turnTokenGenerator = turnTokenGenerator;
this.recaptchaClient = recaptchaClient;
this.captchaChecker = captchaChecker;
this.pushNotificationManager = pushNotificationManager;
this.backupServiceCredentialGenerator = backupServiceCredentialGenerator;
this.changeNumberManager = changeNumberManager;
@@ -204,19 +209,18 @@ public class AccountController {
public AccountController(
StoredVerificationCodeManager pendingAccounts,
AccountsManager accounts,
AbusiveHostRules abusiveHostRules,
RateLimiters rateLimiters,
RegistrationServiceClient registrationServiceClient,
DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
TurnTokenGenerator turnTokenGenerator,
Map<String, Integer> testDevices,
RecaptchaClient recaptchaClient,
CaptchaChecker captchaChecker,
PushNotificationManager pushNotificationManager,
ChangeNumberManager changeNumberManager,
ExternalServiceCredentialGenerator backupServiceCredentialGenerator
) {
this(pendingAccounts, accounts, abusiveHostRules, rateLimiters,
registrationServiceClient, dynamicConfigurationManager, turnTokenGenerator, testDevices, recaptchaClient,
this(pendingAccounts, accounts, rateLimiters,
registrationServiceClient, dynamicConfigurationManager, turnTokenGenerator, testDevices, captchaChecker,
pushNotificationManager, changeNumberManager,
backupServiceCredentialGenerator, null, Clock.systemUTC());
}
@@ -229,7 +233,7 @@ public class AccountController {
@PathParam("token") String pushToken,
@PathParam("number") String number,
@QueryParam("voip") @DefaultValue("true") boolean useVoip)
throws ImpossiblePhoneNumberException, NonNormalizedPhoneNumberException {
throws ImpossiblePhoneNumberException, NonNormalizedPhoneNumberException, RateLimitExceededException {
final PushNotification.TokenType tokenType = switch(pushType) {
case "apn" -> useVoip ? PushNotification.TokenType.APN_VOIP : PushNotification.TokenType.APN;
@@ -239,9 +243,18 @@ public class AccountController {
Util.requireNormalizedNumber(number);
String pushChallenge = generatePushChallenge();
StoredVerificationCode storedVerificationCode =
new StoredVerificationCode(null, clock.millis(), pushChallenge, null, null);
final Phonenumber.PhoneNumber phoneNumber;
try {
phoneNumber = PhoneNumberUtil.getInstance().parse(number, null);
} catch (final NumberParseException e) {
// This should never happen since we just verified that the number is already normalized
throw new BadRequestException("Bad phone number");
}
final String pushChallenge = generatePushChallenge();
final byte[] sessionId = createRegistrationSession(phoneNumber);
final StoredVerificationCode storedVerificationCode =
new StoredVerificationCode(null, clock.millis(), pushChallenge, sessionId);
pendingAccounts.store(number, storedVerificationCode);
pushNotificationManager.sendRegistrationChallengeNotification(pushToken, tokenType, storedVerificationCode.pushCode());
@@ -262,7 +275,7 @@ public class AccountController {
@QueryParam("client") Optional<String> client,
@QueryParam("captcha") Optional<String> captcha,
@QueryParam("challenge") Optional<String> pushChallenge)
throws RateLimitExceededException, ImpossiblePhoneNumberException, NonNormalizedPhoneNumberException {
throws RateLimitExceededException, ImpossiblePhoneNumberException, NonNormalizedPhoneNumberException, IOException {
Util.requireNormalizedNumber(number);
@@ -273,8 +286,9 @@ public class AccountController {
final String region = Util.getRegion(number);
// if there's a captcha, assess it, otherwise check if we need a captcha
final Optional<RecaptchaClient.AssessmentResult> assessmentResult = captcha
.map(captchaToken -> recaptchaClient.verify(captchaToken, sourceHost));
final Optional<AssessmentResult> assessmentResult = captcha.isPresent()
? Optional.of(captchaChecker.verify(captcha.get(), sourceHost))
: Optional.empty();
assessmentResult.ifPresent(result ->
Metrics.counter(CAPTCHA_ATTEMPT_COUNTER_NAME, Tags.of(
@@ -342,13 +356,16 @@ public class AccountController {
}
}).orElse(ClientType.UNKNOWN);
final byte[] sessionId = registrationServiceClient.sendRegistrationCode(phoneNumber,
messageTransport, clientType, acceptLanguage.orElse(null), REGISTRATION_RPC_TIMEOUT).join();
// During the transition to explicit session creation, some previously-stored records may not have a session ID;
// after the transition, we can assume that any existing record has an associated session ID.
final byte[] sessionId = maybeStoredVerificationCode.isPresent() && maybeStoredVerificationCode.get().sessionId() != null ?
maybeStoredVerificationCode.get().sessionId() : createRegistrationSession(phoneNumber);
sendVerificationCode(sessionId, messageTransport, clientType, acceptLanguage);
final StoredVerificationCode storedVerificationCode = new StoredVerificationCode(null,
clock.millis(),
maybeStoredVerificationCode.map(StoredVerificationCode::pushCode).orElse(null),
null,
sessionId);
pendingAccounts.store(number, storedVerificationCode);
@@ -384,14 +401,14 @@ public class AccountController {
// Note that successful verification depends on being able to find a stored verification code for the given number.
// We check that numbers are normalized before we store verification codes, and so don't need to re-assert
// normalization here.
final boolean codeVerified;
final Optional<StoredVerificationCode> maybeStoredVerificationCode = pendingAccounts.getCodeForNumber(number);
final boolean codeVerified = maybeStoredVerificationCode.map(storedVerificationCode ->
storedVerificationCode.sessionId() != null ?
registrationServiceClient.checkVerificationCode(storedVerificationCode.sessionId(),
verificationCode, REGISTRATION_RPC_TIMEOUT).join() :
storedVerificationCode.isValid(verificationCode))
.orElse(false);
if (maybeStoredVerificationCode.isPresent()) {
codeVerified = checkVerificationCode(maybeStoredVerificationCode.get().sessionId(), verificationCode);
} else {
codeVerified = false;
}
if (!codeVerified) {
throw new WebApplicationException(Response.status(403).build());
@@ -399,6 +416,12 @@ public class AccountController {
Optional<Account> existingAccount = accounts.getByE164(number);
existingAccount.ifPresent(account -> {
Instant accountLastSeen = Instant.ofEpochMilli(account.getLastSeen());
Duration timeSinceLastSeen = Duration.between(accountLastSeen, Instant.now());
REREGISTRATION_IDLE_DAYS_DISTRIBUTION.record(timeSinceLastSeen.toDays());
});
if (existingAccount.isPresent()) {
verifyRegistrationLock(existingAccount.get(), accountAttributes.getRegistrationLock());
}
@@ -448,10 +471,14 @@ public class AccountController {
rateLimiters.getVerifyLimiter().validate(number);
final boolean codeVerified = pendingAccounts.getCodeForNumber(number).map(storedVerificationCode ->
registrationServiceClient.checkVerificationCode(storedVerificationCode.sessionId(),
request.code(), REGISTRATION_RPC_TIMEOUT).join())
.orElse(false);
final boolean codeVerified;
final Optional<StoredVerificationCode> maybeStoredVerificationCode = pendingAccounts.getCodeForNumber(number);
if (maybeStoredVerificationCode.isPresent()) {
codeVerified = checkVerificationCode(maybeStoredVerificationCode.get().sessionId(), request.code());
} else {
codeVerified = false;
}
if (!codeVerified) {
throw new ForbiddenException();
@@ -886,26 +913,12 @@ public class AccountController {
boolean countryFiltered = captchaConfig.getSignupCountryCodes().contains(countryCode) ||
captchaConfig.getSignupRegions().contains(region);
if (abusiveHostRules.isBlocked(sourceHost)) {
blockedHostMeter.mark();
logger.info("Blocked host: {}, {}, {} ({})", transport, number, sourceHost, forwardedFor);
if (countryFiltered) {
// this host was caught in the abusiveHostRules filter, but
// would be caught by country filter as well
countryFilterApplicable.mark();
}
return true;
}
try {
rateLimiters.getSmsVoiceIpLimiter().validate(sourceHost);
} catch (RateLimitExceededException e) {
logger.info("Rate limit exceeded: {}, {}, {} ({})", transport, number, sourceHost, forwardedFor);
rateLimitedHostMeter.mark();
if (shouldAutoBlock(sourceHost)) {
logger.info("Auto-block: {}", sourceHost);
abusiveHostRules.setBlockedHost(sourceHost);
}
return true;
}
@@ -914,10 +927,7 @@ public class AccountController {
} catch (RateLimitExceededException e) {
logger.info("Prefix rate limit exceeded: {}, {}, {} ({})", transport, number, sourceHost, forwardedFor);
rateLimitedPrefixMeter.mark();
if (shouldAutoBlock(sourceHost)) {
logger.info("Auto-block: {}", sourceHost);
abusiveHostRules.setBlockedHost(sourceHost);
}
return true;
}
@@ -925,6 +935,7 @@ public class AccountController {
countryFilteredHostMeter.mark();
return true;
}
return false;
}
@@ -944,16 +955,6 @@ public class AccountController {
}
}
private boolean shouldAutoBlock(String sourceHost) {
try {
rateLimiters.getAutoBlockLimiter().validate(sourceHost);
} catch (RateLimitExceededException e) {
return true;
}
return false;
}
private String generatePushChallenge() {
SecureRandom random = new SecureRandom();
byte[] challenge = new byte[16];
@@ -961,4 +962,58 @@ public class AccountController {
return Hex.toStringCondensed(challenge);
}
private byte[] createRegistrationSession(final Phonenumber.PhoneNumber phoneNumber) throws RateLimitExceededException {
try {
return registrationServiceClient.createRegistrationSession(phoneNumber, REGISTRATION_RPC_TIMEOUT).join();
} catch (final CompletionException e) {
rethrowRateLimitException(e);
throw e;
}
}
private void sendVerificationCode(final byte[] sessionId,
final MessageTransport messageTransport,
final ClientType clientType,
final Optional<String> acceptLanguage) throws RateLimitExceededException {
try {
registrationServiceClient.sendRegistrationCode(sessionId,
messageTransport,
clientType,
acceptLanguage.orElse(null),
REGISTRATION_RPC_TIMEOUT).join();
} catch (final CompletionException e) {
rethrowRateLimitException(e);
throw e;
}
}
private boolean checkVerificationCode(final byte[] sessionId, final String verificationCode)
throws RateLimitExceededException {
try {
return registrationServiceClient.checkVerificationCode(sessionId, verificationCode, REGISTRATION_RPC_TIMEOUT).join();
} catch (final CompletionException e) {
rethrowRateLimitException(e);
// For legacy API compatibility, funnel all errors into the same return value
return false;
}
}
private void rethrowRateLimitException(final CompletionException completionException)
throws RateLimitExceededException {
Throwable cause = completionException;
while (cause instanceof CompletionException) {
cause = cause.getCause();
}
if (cause instanceof RateLimitExceededException rateLimitExceededException) {
throw rateLimitExceededException;
}
}
}
@@ -0,0 +1,41 @@
/*
* Copyright 2013-2022 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.controllers;
import com.codahale.metrics.annotation.Timed;
import io.dropwizard.auth.Auth;
import java.util.UUID;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialGenerator;
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
@Path("/v1/art")
public class ArtController {
private final ExternalServiceCredentialGenerator artServiceCredentialGenerator;
private final RateLimiters rateLimiters;
public ArtController(RateLimiters rateLimiters,
ExternalServiceCredentialGenerator artServiceCredentialGenerator) {
this.artServiceCredentialGenerator = artServiceCredentialGenerator;
this.rateLimiters = rateLimiters;
}
@Timed
@GET
@Path("/auth")
@Produces(MediaType.APPLICATION_JSON)
public ExternalServiceCredentials getAuth(@Auth AuthenticatedAccount auth)
throws RateLimitExceededException {
final UUID uuid = auth.getAccount().getUuid();
rateLimiters.getArtPackLimiter().validate(uuid);
return artServiceCredentialGenerator.generateFor(uuid.toString());
}
}
@@ -12,6 +12,7 @@ import com.google.common.net.HttpHeaders;
import io.dropwizard.auth.Auth;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tags;
import java.io.IOException;
import java.util.NoSuchElementException;
import javax.validation.Valid;
import javax.ws.rs.Consumes;
@@ -50,7 +51,7 @@ public class ChallengeController {
public Response handleChallengeResponse(@Auth final AuthenticatedAccount auth,
@Valid final AnswerChallengeRequest answerRequest,
@HeaderParam(HttpHeaders.X_FORWARDED_FOR) final String forwardedFor,
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent) throws RateLimitExceededException {
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent) throws RateLimitExceededException, IOException {
Tags tags = Tags.of(UserAgentTagUtil.getPlatformTag(userAgent));
@@ -48,8 +48,6 @@ import org.whispersystems.textsecuregcm.storage.MessagesManager;
import org.whispersystems.textsecuregcm.storage.StoredVerificationCodeManager;
import org.whispersystems.textsecuregcm.util.Util;
import org.whispersystems.textsecuregcm.util.VerificationCode;
import org.whispersystems.textsecuregcm.util.ua.UnrecognizedUserAgentException;
import org.whispersystems.textsecuregcm.util.ua.UserAgentUtil;
@Path("/v1/devices")
public class DeviceController {
@@ -135,7 +133,7 @@ public class DeviceController {
VerificationCode verificationCode = generateVerificationCode();
StoredVerificationCode storedVerificationCode =
new StoredVerificationCode(verificationCode.getVerificationCode(), System.currentTimeMillis(), null, null, null);
new StoredVerificationCode(verificationCode.getVerificationCode(), System.currentTimeMillis(), null, null);
pendingDevices.store(account.getNumber(), storedVerificationCode);
@@ -188,7 +186,7 @@ public class DeviceController {
}
final DeviceCapabilities capabilities = accountAttributes.getCapabilities();
if (capabilities != null && isCapabilityDowngrade(account.get(), capabilities, userAgent)) {
if (capabilities != null && isCapabilityDowngrade(account.get(), capabilities)) {
throw new WebApplicationException(Response.status(409).build());
}
@@ -236,7 +234,7 @@ public class DeviceController {
return new VerificationCode(randomInt);
}
private boolean isCapabilityDowngrade(Account account, DeviceCapabilities capabilities, String userAgent) {
private boolean isCapabilityDowngrade(Account account, DeviceCapabilities capabilities) {
boolean isDowngrade = false;
isDowngrade |= account.isStoriesSupported() && !capabilities.isStories();
@@ -244,35 +242,8 @@ public class DeviceController {
isDowngrade |= account.isChangeNumberSupported() && !capabilities.isChangeNumber();
isDowngrade |= account.isAnnouncementGroupSupported() && !capabilities.isAnnouncementGroup();
isDowngrade |= account.isSenderKeySupported() && !capabilities.isSenderKey();
isDowngrade |= account.isGv1MigrationSupported() && !capabilities.isGv1Migration();
isDowngrade |= account.isGiftBadgesSupported() && !capabilities.isGiftBadges();
if (account.isGroupsV2Supported()) {
try {
switch (UserAgentUtil.parseUserAgentString(userAgent).getPlatform()) {
case DESKTOP:
case ANDROID: {
if (!capabilities.isGv2_3()) {
isDowngrade = true;
}
break;
}
case IOS: {
if (!capabilities.isGv2_2() && !capabilities.isGv2_3()) {
isDowngrade = true;
}
break;
}
}
} catch (final UnrecognizedUserAgentException e) {
// If we can't parse the UA string, the client is for sure too old to support groups V2
isDowngrade = true;
}
}
return isDowngrade;
}
}
@@ -1,12 +0,0 @@
/*
* Copyright 2013-2020 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.controllers;
public class InvalidDestinationException extends Exception {
public InvalidDestinationException(String message) {
super(message);
}
}
@@ -10,17 +10,15 @@ import static com.codahale.metrics.MetricRegistry.name;
import com.codahale.metrics.annotation.Timed;
import io.dropwizard.auth.Auth;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tags;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
import io.micrometer.core.instrument.Tags;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
import org.whispersystems.textsecuregcm.util.ua.UnrecognizedUserAgentException;
import org.whispersystems.textsecuregcm.util.ua.UserAgentUtil;
import org.whispersystems.websocket.session.WebSocketSession;
import org.whispersystems.websocket.session.WebSocketSessionContext;
@@ -55,12 +55,16 @@ import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.abuse.FilterAbusiveMessages;
import org.whispersystems.textsecuregcm.abuse.ReportSpamTokenHandler;
import org.whispersystems.textsecuregcm.abuse.ReportSpamTokenProvider;
import org.whispersystems.textsecuregcm.auth.Anonymous;
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
import org.whispersystems.textsecuregcm.auth.CombinedUnidentifiedSenderAccessKeys;
@@ -78,6 +82,7 @@ import org.whispersystems.textsecuregcm.entities.OutgoingMessageEntity;
import org.whispersystems.textsecuregcm.entities.OutgoingMessageEntityList;
import org.whispersystems.textsecuregcm.entities.SendMessageResponse;
import org.whispersystems.textsecuregcm.entities.SendMultiRecipientMessageResponse;
import org.whispersystems.textsecuregcm.entities.SpamReport;
import org.whispersystems.textsecuregcm.entities.StaleDevices;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.MessageMetrics;
@@ -117,6 +122,8 @@ public class MessageController {
private final PushNotificationManager pushNotificationManager;
private final ReportMessageManager reportMessageManager;
private final ExecutorService multiRecipientMessageExecutor;
private final ReportSpamTokenProvider reportSpamTokenProvider;
private final ReportSpamTokenHandler reportSpamTokenHandler;
private static final String REJECT_OVERSIZE_MESSAGE_COUNTER = name(MessageController.class, "rejectOversizeMessage");
private static final String SENT_MESSAGE_COUNTER_NAME = name(MessageController.class, "sentMessages");
@@ -124,6 +131,7 @@ public class MessageController {
private static final String OUTGOING_MESSAGE_LIST_SIZE_BYTES_DISTRIBUTION_NAME = name(MessageController.class, "outgoingMessageListSizeBytes");
private static final String RATE_LIMITED_MESSAGE_COUNTER_NAME = name(MessageController.class, "rateLimitedMessage");
private static final String REJECT_INVALID_ENVELOPE_TYPE = name(MessageController.class, "rejectInvalidEnvelopeType");
private static final String REPORT_SPAM_TOKENS_RECEIVED_COUNTER_NAME = name(MessageController.class, "reportSpamTokensReceived");
private static final String EPHEMERAL_TAG_NAME = "ephemeral";
private static final String SENDER_TYPE_TAG_NAME = "senderType";
@@ -147,7 +155,9 @@ public class MessageController {
MessagesManager messagesManager,
PushNotificationManager pushNotificationManager,
ReportMessageManager reportMessageManager,
@Nonnull ExecutorService multiRecipientMessageExecutor) {
@Nonnull ExecutorService multiRecipientMessageExecutor,
@Nonnull ReportSpamTokenProvider reportSpamTokenProvider,
@Nonnull ReportSpamTokenHandler reportSpamTokenHandler) {
this.rateLimiters = rateLimiters;
this.messageSender = messageSender;
this.receiptSender = receiptSender;
@@ -157,6 +167,9 @@ public class MessageController {
this.pushNotificationManager = pushNotificationManager;
this.reportMessageManager = reportMessageManager;
this.multiRecipientMessageExecutor = Objects.requireNonNull(multiRecipientMessageExecutor);
this.reportSpamTokenProvider = reportSpamTokenProvider;
this.reportSpamTokenHandler = reportSpamTokenHandler;
}
@Timed
@@ -171,7 +184,9 @@ public class MessageController {
@HeaderParam(HttpHeaders.X_FORWARDED_FOR) String forwardedFor,
@PathParam("destination") UUID destinationUuid,
@QueryParam("story") boolean isStory,
@NotNull @Valid IncomingMessageList messages)
@NotNull @Valid IncomingMessageList messages,
@Context ContainerRequestContext context
)
throws RateLimitExceededException {
if (source.isEmpty() && accessKey.isEmpty() && !isStory) {
@@ -190,6 +205,13 @@ public class MessageController {
senderType = SENDER_TYPE_UNIDENTIFIED;
}
final Optional<byte[]> spamReportToken;
if (senderType.equals(SENDER_TYPE_IDENTIFIED)) {
spamReportToken = reportSpamTokenProvider.makeReportSpamToken(context);
} else {
spamReportToken = Optional.empty();
}
for (final IncomingMessage message : messages.messages()) {
int contentLength = 0;
@@ -267,7 +289,18 @@ public class MessageController {
if (destinationDevice.isPresent()) {
Metrics.counter(SENT_MESSAGE_COUNTER_NAME, tags).increment();
sendIndividualMessage(source, destination.get(), destinationDevice.get(), destinationUuid, messages.timestamp(), messages.online(), isStory, messages.urgent(), incomingMessage, userAgent);
sendIndividualMessage(
source,
destination.get(),
destinationDevice.get(),
destinationUuid,
messages.timestamp(),
messages.online(),
isStory,
messages.urgent(),
incomingMessage,
userAgent,
spamReportToken);
}
}
@@ -570,9 +603,14 @@ public class MessageController {
@Timed
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Path("/report/{source}/{messageGuid}")
public Response reportMessage(@Auth AuthenticatedAccount auth, @PathParam("source") String source,
@PathParam("messageGuid") UUID messageGuid) {
public Response reportSpamMessage(
@Auth AuthenticatedAccount auth,
@PathParam("source") String source,
@PathParam("messageGuid") UUID messageGuid,
@Nullable @Valid SpamReport spamReport
) {
final Optional<String> sourceNumber;
final Optional<UUID> sourceAci;
@@ -602,13 +640,32 @@ public class MessageController {
}
}
reportMessageManager.report(sourceNumber, sourceAci, sourcePni, messageGuid, auth.getAccount().getUuid());
UUID spamReporterUuid = auth.getAccount().getUuid();
// spam report token is optional, but if provided ensure it is valid base64.
byte[] spamReportToken = null;
if (spamReport != null) {
try {
spamReportToken = Base64.getDecoder().decode(spamReport.token());
Metrics.counter(REPORT_SPAM_TOKENS_RECEIVED_COUNTER_NAME).increment();
} catch (IllegalArgumentException e) {
logger.error("Invalid report spam token provided", e);
throw new WebApplicationException(Response.status(400).build());
}
}
// fire-and-forget: we don't want to block the response on this action.
CompletableFuture<Boolean> ignored =
reportSpamTokenHandler.handle(sourceNumber, sourceAci, sourcePni, messageGuid, spamReporterUuid, spamReportToken);
reportMessageManager.report(sourceNumber, sourceAci, sourcePni, messageGuid, spamReporterUuid);
return Response.status(Status.ACCEPTED)
.build();
}
private void sendIndividualMessage(Optional<AuthenticatedAccount> source,
private void sendIndividualMessage(
Optional<AuthenticatedAccount> source,
Account destinationAccount,
Device destinationDevice,
UUID destinationUuid,
@@ -617,18 +674,23 @@ public class MessageController {
boolean story,
boolean urgent,
IncomingMessage incomingMessage,
String userAgentString)
String userAgentString,
Optional<byte[]> spamReportToken)
throws NoSuchUserException {
try {
final Envelope envelope;
try {
envelope = incomingMessage.toEnvelope(destinationUuid,
source.map(AuthenticatedAccount::getAccount).orElse(null),
source.map(authenticatedAccount -> authenticatedAccount.getAuthenticatedDevice().getId()).orElse(null),
Account sourceAccount = source.map(AuthenticatedAccount::getAccount).orElse(null);
Long sourceDeviceId = source.map(account -> account.getAuthenticatedDevice().getId()).orElse(null);
envelope = incomingMessage.toEnvelope(
destinationUuid,
sourceAccount,
sourceDeviceId,
timestamp == 0 ? System.currentTimeMillis() : timestamp,
story,
urgent);
urgent,
spamReportToken.orElse(null));
} catch (final IllegalArgumentException e) {
logger.warn("Received bad envelope type {} from {}", incomingMessage.type(), userAgentString);
throw new BadRequestException(e);
@@ -4,9 +4,9 @@
*/
package org.whispersystems.textsecuregcm.controllers;
import javax.annotation.Nullable;
import java.time.Duration;
import java.util.Optional;
import javax.annotation.Nullable;
public class RateLimitExceededException extends Exception {
@@ -41,6 +41,7 @@ import org.whispersystems.textsecuregcm.entities.UserRemoteConfigList;
import org.whispersystems.textsecuregcm.storage.RemoteConfig;
import org.whispersystems.textsecuregcm.storage.RemoteConfigsManager;
import org.whispersystems.textsecuregcm.util.Conversions;
import org.whispersystems.textsecuregcm.util.Util;
@Path("/v1/config")
public class RemoteConfigController {
@@ -133,7 +134,7 @@ public class RemoteConfigController {
digest.update(bb.array());
byte[] hash = digest.digest(hashKey);
int bucket = (int)(Math.abs(Conversions.byteArrayToLong(hash)) % 100);
int bucket = (int)(Util.ensureNonNegativeLong(Conversions.byteArrayToLong(hash)) % 100);
return bucket < configPercentage;
}
@@ -14,11 +14,6 @@ import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.annotations.VisibleForTesting;
import com.stripe.exception.StripeException;
import com.stripe.model.Charge;
import com.stripe.model.Charge.Outcome;
import com.stripe.model.Invoice;
import com.stripe.model.InvoiceLineItem;
import com.stripe.model.Subscription;
import io.dropwizard.auth.Auth;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tags;
@@ -31,7 +26,6 @@ import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
@@ -47,6 +41,7 @@ import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.validation.Valid;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import javax.ws.rs.BadRequestException;
@@ -72,7 +67,6 @@ import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.apache.commons.lang3.StringUtils;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.VerificationFailedException;
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialRequest;
@@ -87,16 +81,17 @@ import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfigurati
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationCurrencyConfiguration;
import org.whispersystems.textsecuregcm.configuration.SubscriptionConfiguration;
import org.whispersystems.textsecuregcm.configuration.SubscriptionLevelConfiguration;
import org.whispersystems.textsecuregcm.configuration.SubscriptionPriceConfiguration;
import org.whispersystems.textsecuregcm.entities.Badge;
import org.whispersystems.textsecuregcm.entities.PurchasableBadge;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.storage.IssuedReceiptsManager;
import org.whispersystems.textsecuregcm.storage.SubscriptionManager;
import org.whispersystems.textsecuregcm.storage.SubscriptionManager.GetResult;
import org.whispersystems.textsecuregcm.subscriptions.BraintreeManager;
import org.whispersystems.textsecuregcm.subscriptions.PaymentMethod;
import org.whispersystems.textsecuregcm.subscriptions.ProcessorCustomer;
import org.whispersystems.textsecuregcm.subscriptions.StripeManager;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionCurrencyUtil;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessor;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorManager;
import org.whispersystems.textsecuregcm.util.ExactlySize;
@@ -111,13 +106,18 @@ public class SubscriptionController {
private final OneTimeDonationConfiguration oneTimeDonationConfiguration;
private final SubscriptionManager subscriptionManager;
private final StripeManager stripeManager;
private final BraintreeManager braintreeManager;
private final ServerZkReceiptOperations zkReceiptOperations;
private final IssuedReceiptsManager issuedReceiptsManager;
private final BadgeTranslator badgeTranslator;
private final LevelTranslator levelTranslator;
private final Map<String, CurrencyConfiguration> currencyConfiguration;
private static final String INVALID_ACCEPT_LANGUAGE_COUNTER_NAME = name(SubscriptionController.class, "invalidAcceptLanguage");
private static final String INVALID_ACCEPT_LANGUAGE_COUNTER_NAME = name(SubscriptionController.class,
"invalidAcceptLanguage");
private static final String RECEIPT_ISSUED_COUNTER_NAME = name(SubscriptionController.class, "receiptIssued");
private static final String PROCESSOR_TAG_NAME = "processor";
private static final String TYPE_TAG_NAME = "type";
public SubscriptionController(
@Nonnull Clock clock,
@@ -125,6 +125,7 @@ public class SubscriptionController {
@Nonnull OneTimeDonationConfiguration oneTimeDonationConfiguration,
@Nonnull SubscriptionManager subscriptionManager,
@Nonnull StripeManager stripeManager,
@Nonnull BraintreeManager braintreeManager,
@Nonnull ServerZkReceiptOperations zkReceiptOperations,
@Nonnull IssuedReceiptsManager issuedReceiptsManager,
@Nonnull BadgeTranslator badgeTranslator,
@@ -134,13 +135,14 @@ public class SubscriptionController {
this.oneTimeDonationConfiguration = Objects.requireNonNull(oneTimeDonationConfiguration);
this.subscriptionManager = Objects.requireNonNull(subscriptionManager);
this.stripeManager = Objects.requireNonNull(stripeManager);
this.braintreeManager = Objects.requireNonNull(braintreeManager);
this.zkReceiptOperations = Objects.requireNonNull(zkReceiptOperations);
this.issuedReceiptsManager = Objects.requireNonNull(issuedReceiptsManager);
this.badgeTranslator = Objects.requireNonNull(badgeTranslator);
this.levelTranslator = Objects.requireNonNull(levelTranslator);
this.currencyConfiguration = buildCurrencyConfiguration(this.oneTimeDonationConfiguration,
this.subscriptionConfiguration, List.of(stripeManager));
this.subscriptionConfiguration, List.of(stripeManager, braintreeManager));
}
private static Map<String, CurrencyConfiguration> buildCurrencyConfiguration(
@@ -164,7 +166,7 @@ public class SubscriptionController {
.filter(levelIdAndConfig -> levelIdAndConfig.getValue().getPrices().containsKey(currency))
.collect(Collectors.toMap(
levelIdAndConfig -> String.valueOf(levelIdAndConfig.getKey()),
levelIdAndConfig -> levelIdAndConfig.getValue().getPrices().get(currency).getAmount()));
levelIdAndConfig -> levelIdAndConfig.getValue().getPrices().get(currency).amount()));
final List<String> supportedPaymentMethods = Arrays.stream(PaymentMethod.values())
.filter(paymentMethod -> subscriptionProcessorManagers.stream()
@@ -194,18 +196,22 @@ public class SubscriptionController {
levels.put(String.valueOf(levelId), levelConfiguration);
});
final Badge boostBadge = badgeTranslator.translate(acceptableLanguages,
oneTimeDonationConfiguration.boost().badge());
levels.put(String.valueOf(oneTimeDonationConfiguration.boost().level()),
new LevelConfiguration(
levelTranslator.translate(acceptableLanguages, oneTimeDonationConfiguration.boost().badge()),
boostBadge.getName(),
// NB: the one-time badges are PurchasableBadge, which has a `duration` field
new PurchasableBadge(
badgeTranslator.translate(acceptableLanguages, oneTimeDonationConfiguration.boost().badge()),
boostBadge,
oneTimeDonationConfiguration.boost().expiration())));
final Badge giftBadge = badgeTranslator.translate(acceptableLanguages, oneTimeDonationConfiguration.gift().badge());
levels.put(String.valueOf(oneTimeDonationConfiguration.gift().level()),
new LevelConfiguration(
levelTranslator.translate(acceptableLanguages, oneTimeDonationConfiguration.gift().badge()),
giftBadge.getName(),
new PurchasableBadge(
badgeTranslator.translate(acceptableLanguages, oneTimeDonationConfiguration.gift().badge()),
giftBadge,
oneTimeDonationConfiguration.gift().expiration())));
return new GetSubscriptionConfigurationResponse(currencyConfiguration, levels);
@@ -225,19 +231,7 @@ public class SubscriptionController {
throw new NotFoundException();
}
return getResult.record.getProcessorCustomer()
.map(processorCustomer -> stripeManager.getCustomer(processorCustomer.customerId())
.thenCompose(customer -> {
if (customer == null) {
throw new InternalServerErrorException(
"no customer record found for id " + processorCustomer.customerId());
}
return stripeManager.listNonCanceledSubscriptions(customer);
}).thenCompose(subscriptions -> {
@SuppressWarnings("unchecked")
CompletableFuture<Subscription>[] futures = (CompletableFuture<Subscription>[]) subscriptions.stream()
.map(stripeManager::cancelSubscriptionAtEndOfCurrentPeriod).toArray(CompletableFuture[]::new);
return CompletableFuture.allOf(futures);
}))
.map(processorCustomer -> getManagerForProcessor(processorCustomer.processor()).cancelAllActiveSubscriptions(processorCustomer.customerId()))
// a missing customer ID is OK; it means the subscriber never started to add a payment method
.orElseGet(() -> CompletableFuture.completedFuture(null));
})
@@ -299,16 +293,24 @@ public class SubscriptionController {
.thenCompose(record -> {
final CompletableFuture<SubscriptionManager.Record> updatedRecordFuture =
record.getProcessorCustomer()
.map(ignored -> CompletableFuture.completedFuture(record))
.map(ProcessorCustomer::processor)
.map(processor -> {
if (processor != subscriptionProcessorManager.getProcessor()) {
throw new ClientErrorException("existing processor does not match", Status.CONFLICT);
}
return CompletableFuture.completedFuture(record);
})
.orElseGet(() -> subscriptionProcessorManager.createCustomer(requestData.subscriberUser)
.thenApply(ProcessorCustomer::customerId)
.thenCompose(customerId -> subscriptionManager.updateProcessorAndCustomerId(record,
.thenCompose(customerId -> subscriptionManager.setProcessorAndCustomerId(record,
new ProcessorCustomer(customerId, subscriptionProcessorManager.getProcessor()),
Instant.now())));
return updatedRecordFuture.thenCompose(
updatedRecord -> {
final String customerId = updatedRecord.getProcessorCustomer()
.filter(pc -> pc.processor().equals(subscriptionProcessorManager.getProcessor()))
.orElseThrow(() -> new InternalServerErrorException("record should not be missing customer"))
.customerId();
return subscriptionProcessorManager.createPaymentMethodSetupToken(customerId);
@@ -319,9 +321,75 @@ public class SubscriptionController {
.build());
}
public record CreatePayPalBillingAgreementRequest(@NotBlank String returnUrl, @NotBlank String cancelUrl) {
}
public record CreatePayPalBillingAgreementResponse(@NotBlank String approvalUrl, @NotBlank String token) {
}
@Timed
@POST
@Path("/{subscriberId}/create_payment_method/paypal")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public CompletableFuture<Response> createPayPalPaymentMethod(
@Auth Optional<AuthenticatedAccount> authenticatedAccount,
@PathParam("subscriberId") String subscriberId,
@NotNull @Valid CreatePayPalBillingAgreementRequest request,
@Context ContainerRequestContext containerRequestContext) {
RequestData requestData = RequestData.process(authenticatedAccount, subscriberId, clock);
return subscriptionManager.get(requestData.subscriberUser, requestData.hmac)
.thenApply(this::requireRecordFromGetResult)
.thenCompose(record -> {
final CompletableFuture<SubscriptionManager.Record> updatedRecordFuture =
record.getProcessorCustomer()
.map(ProcessorCustomer::processor)
.map(processor -> {
if (processor != braintreeManager.getProcessor()) {
throw new ClientErrorException("existing processor does not match", Status.CONFLICT);
}
return CompletableFuture.completedFuture(record);
})
.orElseGet(() -> braintreeManager.createCustomer(requestData.subscriberUser)
.thenApply(ProcessorCustomer::customerId)
.thenCompose(customerId -> subscriptionManager.setProcessorAndCustomerId(record,
new ProcessorCustomer(customerId, braintreeManager.getProcessor()),
Instant.now())));
return updatedRecordFuture.thenCompose(
updatedRecord -> {
final Locale locale = getAcceptableLanguagesForRequest(containerRequestContext).stream()
.filter(l -> !"*".equals(l.getLanguage()))
.findFirst()
.orElse(Locale.US);
return braintreeManager.createPayPalBillingAgreement(request.returnUrl, request.cancelUrl,
locale.toLanguageTag());
});
})
.thenApply(
billingAgreementApprovalDetails -> Response.ok(
new CreatePayPalBillingAgreementResponse(billingAgreementApprovalDetails.approvalUrl(),
billingAgreementApprovalDetails.billingAgreementToken()))
.build());
}
private SubscriptionProcessorManager getManagerForPaymentMethod(PaymentMethod paymentMethod) {
return switch (paymentMethod) {
case CARD -> stripeManager;
case PAYPAL -> braintreeManager;
};
}
private SubscriptionProcessorManager getManagerForProcessor(SubscriptionProcessor processor) {
return switch (processor) {
case STRIPE -> stripeManager;
case BRAINTREE -> braintreeManager;
};
}
@@ -330,16 +398,38 @@ public class SubscriptionController {
@Path("/{subscriberId}/default_payment_method/{paymentMethodId}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Deprecated // use /{subscriberId}/default_payment_method/{processor}/{paymentMethodId}
public CompletableFuture<Response> setDefaultPaymentMethod(
@Auth Optional<AuthenticatedAccount> authenticatedAccount,
@PathParam("subscriberId") String subscriberId,
@PathParam("paymentMethodId") @NotEmpty String paymentMethodId) {
RequestData requestData = RequestData.process(authenticatedAccount, subscriberId, clock);
return subscriptionManager.get(requestData.subscriberUser, requestData.hmac)
.thenApply(this::requireRecordFromGetResult)
.thenCompose(record -> stripeManager.setDefaultPaymentMethodForCustomer(
record.getProcessorCustomer().orElseThrow().customerId(), paymentMethodId, record.subscriptionId))
.thenApply(customer -> Response.ok().build());
}
@Timed
@POST
@Path("/{subscriberId}/default_payment_method/{processor}/{paymentMethodToken}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public CompletableFuture<Response> setDefaultPaymentMethodWithProcessor(
@Auth Optional<AuthenticatedAccount> authenticatedAccount,
@PathParam("subscriberId") String subscriberId,
@PathParam("processor") SubscriptionProcessor processor,
@PathParam("paymentMethodToken") @NotEmpty String paymentMethodToken) {
RequestData requestData = RequestData.process(authenticatedAccount, subscriberId, clock);
final SubscriptionProcessorManager manager = getManagerForProcessor(processor);
return subscriptionManager.get(requestData.subscriberUser, requestData.hmac)
.thenApply(this::requireRecordFromGetResult)
.thenCompose(record -> record.getProcessorCustomer()
.map(processorCustomer -> stripeManager.setDefaultPaymentMethodForCustomer(processorCustomer.customerId(),
paymentMethodId))
.map(processorCustomer -> manager.setDefaultPaymentMethodForCustomer(processorCustomer.customerId(),
paymentMethodToken, record.subscriptionId))
.orElseThrow(() ->
// a missing customer ID indicates the client made requests out of order,
// and needs to call create_payment_method to create a customer for the given payment method
@@ -419,76 +509,67 @@ public class SubscriptionController {
return subscriptionManager.get(requestData.subscriberUser, requestData.hmac)
.thenApply(this::requireRecordFromGetResult)
.thenCompose(record -> {
SubscriptionLevelConfiguration levelConfiguration = subscriptionConfiguration.getLevels().get(level);
if (levelConfiguration == null) {
throw new BadRequestException(Response.status(Status.BAD_REQUEST)
.entity(new SetSubscriptionLevelErrorResponse(List.of(
new SetSubscriptionLevelErrorResponse.Error(
SetSubscriptionLevelErrorResponse.Error.Type.UNSUPPORTED_LEVEL, null))))
.build());
}
SubscriptionPriceConfiguration priceConfiguration = levelConfiguration.getPrices()
.get(currency.toLowerCase(Locale.ROOT));
if (priceConfiguration == null) {
throw new BadRequestException(Response.status(Status.BAD_REQUEST)
.entity(new SetSubscriptionLevelErrorResponse(List.of(
new SetSubscriptionLevelErrorResponse.Error(
SetSubscriptionLevelErrorResponse.Error.Type.UNSUPPORTED_CURRENCY, null))))
.build());
}
if (record.subscriptionId == null) {
long lastSubscriptionCreatedAt =
record.subscriptionCreatedAt != null ? record.subscriptionCreatedAt.getEpochSecond() : 0;
final ProcessorCustomer processorCustomer = record.getProcessorCustomer()
.orElseThrow(() ->
// a missing customer ID indicates the client made requests out of order,
// and needs to call create_payment_method to create a customer for the given payment method
new ClientErrorException(Status.CONFLICT));
return record.getProcessorCustomer()
.map(processorCustomer ->
// we don't have a subscription yet so create it and then record the subscription id
//
// this relies on stripe's idempotency key to avoid creating more than one subscription if the client
// retries this request
stripeManager.createSubscription(processorCustomer.customerId(), priceConfiguration.getId(), level,
lastSubscriptionCreatedAt)
.exceptionally(e -> {
if (e.getCause() instanceof StripeException stripeException
&& stripeException.getCode().equals("subscription_payment_intent_requires_action")) {
throw new BadRequestException(Response.status(Status.BAD_REQUEST)
.entity(new SetSubscriptionLevelErrorResponse(List.of(
new SetSubscriptionLevelErrorResponse.Error(
SetSubscriptionLevelErrorResponse.Error.Type.PAYMENT_REQUIRES_ACTION, null
)
))).build());
}
if (e instanceof RuntimeException re) {
final String subscriptionTemplateId = getSubscriptionTemplateId(level, currency, processorCustomer.processor());
final SubscriptionProcessorManager manager = getManagerForProcessor(processorCustomer.processor());
return Optional.ofNullable(record.subscriptionId)
.map(subId -> {
// we already have a subscription in our records so let's check the level and change it if needed
return manager.getSubscription(subId).thenCompose(
subscription -> manager.getLevelForSubscription(subscription).thenCompose(existingLevel -> {
if (level == existingLevel) {
return CompletableFuture.completedFuture(subscription);
}
return manager.updateSubscription(
subscription, subscriptionTemplateId, level, idempotencyKey)
.thenCompose(updatedSubscription ->
subscriptionManager.subscriptionLevelChanged(requestData.subscriberUser,
requestData.now,
level, updatedSubscription.id())
.thenApply(unused -> updatedSubscription));
}));
}).orElseGet(() -> {
long lastSubscriptionCreatedAt =
record.subscriptionCreatedAt != null ? record.subscriptionCreatedAt.getEpochSecond() : 0;
// we don't have a subscription yet so create it and then record the subscription id
//
// this relies on stripe's idempotency key to avoid creating more than one subscription if the client
// retries this request
return manager.createSubscription(processorCustomer.customerId(),
subscriptionTemplateId,
level,
lastSubscriptionCreatedAt)
.exceptionally(e -> {
if (e.getCause() instanceof StripeException stripeException
&& stripeException.getCode().equals("subscription_payment_intent_requires_action")) {
throw new BadRequestException(Response.status(Status.BAD_REQUEST)
.entity(new SetSubscriptionLevelErrorResponse(List.of(
new SetSubscriptionLevelErrorResponse.Error(
SetSubscriptionLevelErrorResponse.Error.Type.PAYMENT_REQUIRES_ACTION, null
)
))).build());
}
if (e instanceof RuntimeException re) {
throw re;
}
}
throw new CompletionException(e);
})
throw new CompletionException(e);
})
.thenCompose(subscription -> subscriptionManager.subscriptionCreated(
requestData.subscriberUser, subscription.getId(), requestData.now, level)
.thenApply(unused -> subscription)))
.orElseThrow(() ->
// a missing customer ID indicates the client made requests out of order,
// and needs to call create_payment_method to create a customer for the given payment method
new ClientErrorException(Status.CONFLICT));
} else {
// we already have a subscription in our records so let's check the level and change it if needed
return stripeManager.getSubscription(record.subscriptionId).thenCompose(
subscription -> stripeManager.getLevelForSubscription(subscription).thenCompose(existingLevel -> {
if (level == existingLevel) {
return CompletableFuture.completedFuture(subscription);
}
return stripeManager.updateSubscription(
subscription, priceConfiguration.getId(), level, idempotencyKey)
.thenCompose(updatedSubscription ->
subscriptionManager.subscriptionLevelChanged(requestData.subscriberUser, requestData.now,
level)
.thenApply(unused -> updatedSubscription));
}));
}
requestData.subscriberUser, subscription.id(), requestData.now, level)
.thenApply(unused -> subscription));
});
})
.thenApply(subscription -> Response.ok(new SetSubscriptionLevelSuccessResponse(level)).build());
.thenApply(unused -> Response.ok(new SetSubscriptionLevelSuccessResponse(level)).build());
}
public static class GetLevelsResponse {
@@ -597,7 +678,7 @@ public class SubscriptionController {
badgeTranslator.translate(acceptableLanguages, entry.getValue().getBadge()),
entry.getValue().getPrices().entrySet().stream().collect(
Collectors.toMap(levelEntry -> levelEntry.getKey().toUpperCase(Locale.ROOT),
levelEntry -> levelEntry.getValue().getAmount()))))));
levelEntry -> levelEntry.getValue().amount()))))));
return Response.ok(getLevelsResponse).build();
});
}
@@ -678,11 +759,27 @@ public class SubscriptionController {
}
public static class CreateBoostRequest {
@NotEmpty @ExactlySize(3) public String currency;
@Min(1) public long amount;
@NotEmpty
@ExactlySize(3)
public String currency;
@Min(1)
public long amount;
public Long level;
}
public static class CreatePayPalBoostRequest extends CreateBoostRequest {
@NotEmpty
public String returnUrl;
@NotEmpty
public String cancelUrl;
}
record CreatePayPalBoostResponse(String approvalUrl, String paymentId) {
}
public static class CreateBoostResponse {
private final String clientSecret;
@@ -698,6 +795,9 @@ public class SubscriptionController {
}
}
/**
* Creates a Stripe PaymentIntent with the requested amount and currency
*/
@Timed
@POST
@Path("/boost/create")
@@ -708,24 +808,123 @@ public class SubscriptionController {
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 ||
stripeManager.convertConfiguredAmountToStripeAmount(request.currency, amountConfigured)
.compareTo(BigDecimal.valueOf(request.amount)) != 0) {
SubscriptionCurrencyUtil.convertConfiguredAmountToStripeAmount(request.currency, amountConfigured)
.compareTo(amount) != 0) {
throw new WebApplicationException(
Response.status(Status.CONFLICT).entity(Map.of("error", "level_amount_mismatch")).build());
}
}
validateRequestCurrencyAmount(request, amount, stripeManager);
})
.thenCompose(unused -> stripeManager.createPaymentIntent(request.currency, request.amount, request.level))
.thenApply(paymentIntent -> Response.ok(new CreateBoostResponse(paymentIntent.getClientSecret())).build());
}
/**
* Validates that the currency and amount in the request are supported by the {@code manager} and exceed the minimum
* permitted amount
*
* @throws BadRequestException indicates validation failed. Inspect {@code response.error} for details
*/
private void validateRequestCurrencyAmount(CreateBoostRequest request, BigDecimal amount,
SubscriptionProcessorManager manager) {
if (!manager.supportsCurrency(request.currency.toLowerCase(Locale.ROOT))) {
throw new BadRequestException(Response.status(Status.BAD_REQUEST)
.entity(Map.of("error", "unsupported_currency")).build());
}
BigDecimal minCurrencyAmountMajorUnits = oneTimeDonationConfiguration.currencies()
.get(request.currency.toLowerCase(Locale.ROOT)).minimum();
BigDecimal minCurrencyAmountMinorUnits = SubscriptionCurrencyUtil.convertConfiguredAmountToApiAmount(
request.currency,
minCurrencyAmountMajorUnits);
if (minCurrencyAmountMinorUnits.compareTo(amount) > 0) {
throw new BadRequestException(Response.status(Status.BAD_REQUEST)
.entity(Map.of(
"error", "amount_below_currency_minimum",
"minimum", minCurrencyAmountMajorUnits.toString())).build());
}
}
@Timed
@POST
@Path("/boost/paypal/create")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public CompletableFuture<Response> createPayPalBoost(@NotNull @Valid CreatePayPalBoostRequest request,
@Context ContainerRequestContext containerRequestContext) {
return CompletableFuture.runAsync(() -> {
if (request.level == null) {
request.level = oneTimeDonationConfiguration.boost().level();
}
validateRequestCurrencyAmount(request, BigDecimal.valueOf(request.amount), braintreeManager);
})
.thenCompose(unused -> {
final Locale locale = getAcceptableLanguagesForRequest(containerRequestContext).stream()
.filter(l -> !"*".equals(l.getLanguage()))
.findFirst()
.orElse(Locale.US);
return braintreeManager.createOneTimePayment(request.currency.toUpperCase(Locale.ROOT), request.amount,
locale.toLanguageTag(),
request.returnUrl, request.cancelUrl);
})
.thenApply(approvalDetails -> Response.ok(
new CreatePayPalBoostResponse(approvalDetails.approvalUrl(), approvalDetails.paymentId())).build());
}
public static class ConfirmPayPalBoostRequest extends CreateBoostRequest {
@NotEmpty
public String payerId;
@NotEmpty
public String paymentId; // PAYID-…
@NotEmpty
public String paymentToken; // EC-…
}
record ConfirmPayPalBoostResponse(String paymentId) {
}
@Timed
@POST
@Path("/boost/paypal/confirm")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public CompletableFuture<Response> confirmPayPalBoost(@NotNull @Valid ConfirmPayPalBoostRequest request) {
return CompletableFuture.runAsync(() -> {
if (request.level == null) {
request.level = oneTimeDonationConfiguration.boost().level();
}
})
.thenCompose(unused -> braintreeManager.captureOneTimePayment(request.payerId, request.paymentId,
request.paymentToken, request.currency, request.amount, request.level))
.thenApply(chargeSuccessDetails -> Response.ok(
new ConfirmPayPalBoostResponse(chargeSuccessDetails.paymentId())).build());
}
public static class CreateBoostReceiptCredentialsRequest {
@NotNull public String paymentIntentId;
@NotNull public byte[] receiptCredentialRequest;
/**
* a payment ID from {@link #processor}
*/
@NotNull
public String paymentIntentId;
@NotNull
public byte[] receiptCredentialRequest;
@NotNull
public SubscriptionProcessor processor = SubscriptionProcessor.STRIPE;
}
public static class CreateBoostReceiptCredentialsResponse {
@@ -749,26 +948,30 @@ public class SubscriptionController {
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public CompletableFuture<Response> createBoostReceiptCredentials(@NotNull @Valid CreateBoostReceiptCredentialsRequest request) {
return stripeManager.getPaymentIntent(request.paymentIntentId)
.thenCompose(paymentIntent -> {
if (paymentIntent == null) {
final SubscriptionProcessorManager manager = getManagerForProcessor(request.processor);
return manager.getPaymentDetails(request.paymentIntentId)
.thenCompose(paymentDetails -> {
if (paymentDetails == null) {
throw new WebApplicationException(Status.NOT_FOUND);
}
if (StringUtils.equalsIgnoreCase("processing", paymentIntent.getStatus())) {
throw new WebApplicationException(Status.NO_CONTENT);
}
if (!StringUtils.equalsIgnoreCase("succeeded", paymentIntent.getStatus())) {
throw new WebApplicationException(Status.PAYMENT_REQUIRED);
switch (paymentDetails.status()) {
case PROCESSING -> throw new WebApplicationException(Status.NO_CONTENT);
case SUCCEEDED -> {
}
default -> throw new WebApplicationException(Status.PAYMENT_REQUIRED);
}
long level = oneTimeDonationConfiguration.boost().level();
if (paymentIntent.getMetadata() != null) {
String levelMetadata = paymentIntent.getMetadata()
if (paymentDetails.customMetadata() != null) {
String levelMetadata = paymentDetails.customMetadata()
.getOrDefault("level", Long.toString(oneTimeDonationConfiguration.boost().level()));
try {
level = Long.parseLong(levelMetadata);
} catch (NumberFormatException e) {
logger.error("failed to parse level metadata ({}) on payment intent {}", levelMetadata,
paymentIntent.getId(), e);
paymentDetails.id(), e);
throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
}
}
@@ -788,9 +991,10 @@ public class SubscriptionController {
throw new BadRequestException("invalid receipt credential request", e);
}
final long finalLevel = level;
return issuedReceiptsManager.recordIssuance(paymentIntent.getId(), receiptCredentialRequest, clock.instant())
return issuedReceiptsManager.recordIssuance(paymentDetails.id(), manager.getProcessor(),
receiptCredentialRequest, clock.instant())
.thenApply(unused -> {
Instant expiration = Instant.ofEpochSecond(paymentIntent.getCreated())
Instant expiration = paymentDetails.created()
.plus(levelExpiration)
.truncatedTo(ChronoUnit.DAYS)
.plus(1, ChronoUnit.DAYS);
@@ -801,6 +1005,10 @@ public class SubscriptionController {
} catch (VerificationFailedException e) {
throw new BadRequestException("receipt credential request failed verification", e);
}
Metrics.counter(RECEIPT_ISSUED_COUNTER_NAME,
PROCESSOR_TAG_NAME, manager.getProcessor().toString(),
TYPE_TAG_NAME, "boost")
.increment();
return Response.ok(new CreateBoostReceiptCredentialsResponse(receiptCredentialResponse.serialize()))
.build();
});
@@ -819,6 +1027,7 @@ public class SubscriptionController {
private final String currency;
private final BigDecimal amount;
private final String status;
private final SubscriptionProcessor processor;
@JsonCreator
public Subscription(
@@ -829,7 +1038,8 @@ public class SubscriptionController {
@JsonProperty("cancelAtPeriodEnd") boolean cancelAtPeriodEnd,
@JsonProperty("currency") String currency,
@JsonProperty("amount") BigDecimal amount,
@JsonProperty("status") String status) {
@JsonProperty("status") String status,
@JsonProperty("processor") SubscriptionProcessor processor) {
this.level = level;
this.billingCycleAnchor = billingCycleAnchor;
this.endOfCurrentPeriod = endOfCurrentPeriod;
@@ -838,6 +1048,7 @@ public class SubscriptionController {
this.currency = currency;
this.amount = amount;
this.status = status;
this.processor = processor;
}
public long getLevel() {
@@ -871,6 +1082,10 @@ public class SubscriptionController {
public String getStatus() {
return status;
}
public SubscriptionProcessor getProcessor() {
return processor;
}
}
public static class ChargeFailure {
@@ -947,38 +1162,38 @@ public class SubscriptionController {
return subscriptionManager.get(requestData.subscriberUser, requestData.hmac)
.thenApply(this::requireRecordFromGetResult)
.thenCompose(record -> {
if (record.subscriptionId == null) {
return CompletableFuture.completedFuture(Response.ok(new GetSubscriptionInformationResponse(null, null)).build());
}
return stripeManager.getSubscription(record.subscriptionId).thenCompose(subscription ->
stripeManager.getPriceForSubscription(subscription).thenCompose(price ->
stripeManager.getLevelForPrice(price).thenApply(level -> {
GetSubscriptionInformationResponse.ChargeFailure chargeFailure = null;
if (subscription.getLatestInvoiceObject() != null && subscription.getLatestInvoiceObject().getChargeObject() != null &&
(subscription.getLatestInvoiceObject().getChargeObject().getFailureCode() != null || subscription.getLatestInvoiceObject().getChargeObject().getFailureMessage() != null)) {
Charge charge = subscription.getLatestInvoiceObject().getChargeObject();
Outcome outcome = charge.getOutcome();
chargeFailure = new GetSubscriptionInformationResponse.ChargeFailure(
charge.getFailureCode(),
charge.getFailureMessage(),
outcome != null ? outcome.getNetworkStatus() : null,
outcome != null ? outcome.getReason() : null,
outcome != null ? outcome.getType() : null);
}
return Response.ok(
new GetSubscriptionInformationResponse(
new GetSubscriptionInformationResponse.Subscription(
level,
Instant.ofEpochSecond(subscription.getBillingCycleAnchor()),
Instant.ofEpochSecond(subscription.getCurrentPeriodEnd()),
Objects.equals(subscription.getStatus(), "active"),
subscription.getCancelAtPeriodEnd(),
price.getCurrency().toUpperCase(Locale.ROOT),
price.getUnitAmountDecimal(),
subscription.getStatus()),
chargeFailure
)).build();
})));
if (record.subscriptionId == null) {
return CompletableFuture.completedFuture(Response.ok(new GetSubscriptionInformationResponse(null, null)).build());
}
final SubscriptionProcessorManager manager = getManagerForProcessor(record.getProcessorCustomer().orElseThrow().processor());
return manager.getSubscription(record.subscriptionId).thenCompose(subscription ->
manager.getSubscriptionInformation(subscription).thenApply(subscriptionInformation -> {
final GetSubscriptionInformationResponse.ChargeFailure chargeFailure = Optional.ofNullable(subscriptionInformation.chargeFailure())
.map(chargeFailure1 -> new GetSubscriptionInformationResponse.ChargeFailure(
subscriptionInformation.chargeFailure().code(),
subscriptionInformation.chargeFailure().message(),
subscriptionInformation.chargeFailure().outcomeNetworkStatus(),
subscriptionInformation.chargeFailure().outcomeReason(),
subscriptionInformation.chargeFailure().outcomeType()
))
.orElse(null);
return Response.ok(
new GetSubscriptionInformationResponse(
new GetSubscriptionInformationResponse.Subscription(
subscriptionInformation.level(),
subscriptionInformation.billingCycleAnchor(),
subscriptionInformation.endOfCurrentPeriod(),
subscriptionInformation.active(),
subscriptionInformation.cancelAtPeriodEnd(),
subscriptionInformation.price().currency(),
subscriptionInformation.price().amount(),
subscriptionInformation.status().getApiValue(),
manager.getProcessor()),
chargeFailure
)).build();
}));
});
}
@@ -1027,97 +1242,66 @@ public class SubscriptionController {
return subscriptionManager.get(requestData.subscriberUser, requestData.hmac)
.thenApply(this::requireRecordFromGetResult)
.thenCompose(record -> {
if (record.subscriptionId == null) {
return CompletableFuture.completedFuture(Response.status(Status.NOT_FOUND).build());
}
ReceiptCredentialRequest receiptCredentialRequest;
try {
receiptCredentialRequest = new ReceiptCredentialRequest(request.getReceiptCredentialRequest());
} catch (InvalidInputException e) {
throw new BadRequestException("invalid receipt credential request", e);
}
return stripeManager.getLatestInvoiceForSubscription(record.subscriptionId)
.thenCompose(invoice -> convertInvoiceToReceipt(invoice, record.subscriptionId))
.thenCompose(receipt -> issuedReceiptsManager.recordIssuance(
receipt.getInvoiceLineItemId(), receiptCredentialRequest, requestData.now)
.thenApply(unused -> receipt))
.thenApply(receipt -> {
ReceiptCredentialResponse receiptCredentialResponse;
try {
receiptCredentialResponse = zkReceiptOperations.issueReceiptCredential(
receiptCredentialRequest, receipt.getExpiration().getEpochSecond(), receipt.getLevel());
} catch (VerificationFailedException e) {
throw new BadRequestException("receipt credential request failed verification", e);
}
return Response.ok(new GetReceiptCredentialsResponse(receiptCredentialResponse.serialize())).build();
});
if (record.subscriptionId == null) {
return CompletableFuture.completedFuture(Response.status(Status.NOT_FOUND).build());
}
ReceiptCredentialRequest receiptCredentialRequest;
try {
receiptCredentialRequest = new ReceiptCredentialRequest(request.getReceiptCredentialRequest());
} catch (InvalidInputException e) {
throw new BadRequestException("invalid receipt credential request", e);
}
final SubscriptionProcessorManager manager = getManagerForProcessor(record.getProcessorCustomer().orElseThrow().processor());
return manager.getReceiptItem(record.subscriptionId)
.thenCompose(receipt -> issuedReceiptsManager.recordIssuance(
receipt.itemId(), manager.getProcessor(), receiptCredentialRequest,
requestData.now)
.thenApply(unused -> receipt))
.thenApply(receipt -> {
ReceiptCredentialResponse receiptCredentialResponse;
try {
receiptCredentialResponse = zkReceiptOperations.issueReceiptCredential(
receiptCredentialRequest,
receiptExpirationWithGracePeriod(receipt.expiration()).getEpochSecond(), receipt.level());
} catch (VerificationFailedException e) {
throw new BadRequestException("receipt credential request failed verification", e);
}
Metrics.counter(RECEIPT_ISSUED_COUNTER_NAME,
PROCESSOR_TAG_NAME, manager.getProcessor().toString(),
TYPE_TAG_NAME, "subscription")
.increment();
return Response.ok(new GetReceiptCredentialsResponse(receiptCredentialResponse.serialize()))
.build();
});
});
}
public static class Receipt {
private final Instant expiration;
private final long level;
private final String invoiceLineItemId;
public Receipt(Instant expiration, long level, String invoiceLineItemId) {
this.expiration = expiration;
this.level = level;
this.invoiceLineItemId = invoiceLineItemId;
private Instant receiptExpirationWithGracePeriod(Instant itemExpiration) {
return itemExpiration.plus(subscriptionConfiguration.getBadgeGracePeriod())
.truncatedTo(ChronoUnit.DAYS)
.plus(1, ChronoUnit.DAYS);
}
public Instant getExpiration() {
return expiration;
}
public long getLevel() {
return level;
}
public String getInvoiceLineItemId() {
return invoiceLineItemId;
}
}
private CompletableFuture<Receipt> convertInvoiceToReceipt(Invoice latestSubscriptionInvoice, String subscriptionId) {
if (latestSubscriptionInvoice == null) {
throw new WebApplicationException(Status.NO_CONTENT);
}
if (StringUtils.equalsIgnoreCase("open", latestSubscriptionInvoice.getStatus())) {
throw new WebApplicationException(Status.NO_CONTENT);
}
if (!StringUtils.equalsIgnoreCase("paid", latestSubscriptionInvoice.getStatus())) {
throw new WebApplicationException(Status.PAYMENT_REQUIRED);
}
return stripeManager.getInvoiceLineItemsForInvoice(latestSubscriptionInvoice).thenCompose(invoiceLineItems -> {
Collection<InvoiceLineItem> subscriptionLineItems = invoiceLineItems.stream()
.filter(invoiceLineItem -> Objects.equals("subscription", invoiceLineItem.getType()))
.collect(Collectors.toList());
if (subscriptionLineItems.isEmpty()) {
throw new IllegalStateException("latest subscription invoice has no subscription line items; subscriptionId="
+ subscriptionId + "; invoiceId=" + latestSubscriptionInvoice.getId());
}
if (subscriptionLineItems.size() > 1) {
throw new IllegalStateException(
"latest subscription invoice has too many subscription line items; subscriptionId=" + subscriptionId
+ "; invoiceId=" + latestSubscriptionInvoice.getId() + "; count=" + subscriptionLineItems.size());
private String getSubscriptionTemplateId(long level, String currency, SubscriptionProcessor processor) {
SubscriptionLevelConfiguration levelConfiguration = subscriptionConfiguration.getLevels().get(level);
if (levelConfiguration == null) {
throw new BadRequestException(Response.status(Status.BAD_REQUEST)
.entity(new SetSubscriptionLevelErrorResponse(List.of(
new SetSubscriptionLevelErrorResponse.Error(
SetSubscriptionLevelErrorResponse.Error.Type.UNSUPPORTED_LEVEL, null))))
.build());
}
InvoiceLineItem subscriptionLineItem = subscriptionLineItems.stream().findAny().get();
return getReceiptForSubscriptionInvoiceLineItem(subscriptionLineItem);
});
}
private CompletableFuture<Receipt> getReceiptForSubscriptionInvoiceLineItem(InvoiceLineItem subscriptionLineItem) {
return stripeManager.getProductForPrice(subscriptionLineItem.getPrice().getId()).thenApply(product -> new Receipt(
Instant.ofEpochSecond(subscriptionLineItem.getPeriod().getEnd())
.plus(subscriptionConfiguration.getBadgeGracePeriod())
.truncatedTo(ChronoUnit.DAYS)
.plus(1, ChronoUnit.DAYS),
stripeManager.getLevelForProduct(product),
subscriptionLineItem.getId()));
}
return Optional.ofNullable(levelConfiguration.getPrices()
.get(currency.toLowerCase(Locale.ROOT)))
.map(priceConfiguration -> priceConfiguration.processorIds().get(processor))
.orElseThrow(() -> new BadRequestException(Response.status(Status.BAD_REQUEST)
.entity(new SetSubscriptionLevelErrorResponse(List.of(
new SetSubscriptionLevelErrorResponse.Error(
SetSubscriptionLevelErrorResponse.Error.Type.UNSUPPORTED_CURRENCY, null))))
.build()));
}
private SubscriptionManager.Record requireRecordFromGetResult(SubscriptionManager.GetResult getResult) {
if (getResult == GetResult.PASSWORD_MISMATCH) {
@@ -5,56 +5,12 @@
package org.whispersystems.textsecuregcm.entities;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import javax.annotation.Nullable;
import java.util.UUID;
import javax.annotation.Nullable;
public class AccountIdentityResponse {
private final UUID uuid;
private final String number;
private final UUID pni;
@Nullable
private final String username;
private final boolean storageCapable;
@JsonCreator
public AccountIdentityResponse(
@JsonProperty("uuid") final UUID uuid,
@JsonProperty("number") final String number,
@JsonProperty("pni") final UUID pni,
@JsonProperty("username") @Nullable final String username,
@JsonProperty("storageCapable") final boolean storageCapable) {
this.uuid = uuid;
this.number = number;
this.pni = pni;
this.username = username;
this.storageCapable = storageCapable;
}
public UUID getUuid() {
return uuid;
}
public String getNumber() {
return number;
}
public UUID getPni() {
return pni;
}
@Nullable
public String getUsername() {
return username;
}
public boolean isStorageCapable() {
return storageCapable;
}
public record AccountIdentityResponse(UUID uuid,
String number,
UUID pni,
@Nullable String username,
boolean storageCapable) {
}
@@ -18,7 +18,8 @@ public record IncomingMessage(int type, long destinationDeviceId, int destinatio
@Nullable Long sourceDeviceId,
final long timestamp,
final boolean story,
final boolean urgent) {
final boolean urgent,
@Nullable byte[] reportSpamToken) {
final MessageProtos.Envelope.Type envelopeType = MessageProtos.Envelope.Type.forNumber(type());
@@ -36,10 +37,15 @@ public record IncomingMessage(int type, long destinationDeviceId, int destinatio
.setUrgent(urgent);
if (sourceAccount != null && sourceDeviceId != null) {
envelopeBuilder.setSourceUuid(sourceAccount.getUuid().toString())
envelopeBuilder
.setSourceUuid(sourceAccount.getUuid().toString())
.setSourceDevice(sourceDeviceId.intValue());
}
if (reportSpamToken != null) {
envelopeBuilder.setReportSpamToken(ByteString.copyFrom(reportSpamToken));
}
if (StringUtils.isNotEmpty(content())) {
envelopeBuilder.setContent(ByteString.copyFrom(Base64.getDecoder().decode(content())));
}
@@ -5,32 +5,8 @@
package org.whispersystems.textsecuregcm.entities;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
public class RegistrationLockFailure {
public record RegistrationLockFailure(long timeRemaining, ExternalServiceCredentials backupCredentials) {
@JsonProperty
private long timeRemaining;
@JsonProperty
private ExternalServiceCredentials backupCredentials;
public RegistrationLockFailure() {}
public RegistrationLockFailure(long timeRemaining, ExternalServiceCredentials backupCredentials) {
this.timeRemaining = timeRemaining;
this.backupCredentials = backupCredentials;
}
@JsonIgnore
public long getTimeRemaining() {
return timeRemaining;
}
@JsonIgnore
public ExternalServiceCredentials getBackupCredentials() {
return backupCredentials;
}
}
@@ -0,0 +1,7 @@
package org.whispersystems.textsecuregcm.entities;
import com.fasterxml.jackson.annotation.JsonProperty;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
public record SpamReport(@JsonProperty("token") @NotEmpty String token) {}
@@ -8,85 +8,30 @@ package org.whispersystems.textsecuregcm.entities;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.whispersystems.textsecuregcm.storage.Account;
public class UserCapabilities {
public record UserCapabilities(
@JsonProperty("gv1-migration") boolean gv1Migration,
boolean senderKey,
boolean announcementGroup,
boolean changeNumber,
boolean stories,
boolean giftBadges,
boolean paymentActivation,
boolean pni) {
public static UserCapabilities createForAccount(Account account) {
return new UserCapabilities(
account.isGroupsV2Supported(),
account.isGv1MigrationSupported(),
true,
account.isSenderKeySupported(),
account.isAnnouncementGroupSupported(),
account.isChangeNumberSupported(),
account.isStoriesSupported(),
account.isGiftBadgesSupported());
}
account.isGiftBadgesSupported(),
@JsonProperty
private boolean gv2;
// Hardcode payment activation flag to false until all clients support the flow
false,
@JsonProperty("gv1-migration")
private boolean gv1Migration;
@JsonProperty
private boolean senderKey;
@JsonProperty
private boolean announcementGroup;
@JsonProperty
private boolean changeNumber;
@JsonProperty
private boolean stories;
@JsonProperty
private boolean giftBadges;
public UserCapabilities() {
}
public UserCapabilities(final boolean gv2,
boolean gv1Migration,
final boolean senderKey,
final boolean announcementGroup,
final boolean changeNumber,
final boolean stories,
final boolean giftBadges) {
this.gv2 = gv2;
this.gv1Migration = gv1Migration;
this.senderKey = senderKey;
this.announcementGroup = announcementGroup;
this.changeNumber = changeNumber;
this.stories = stories;
this.giftBadges = giftBadges;
}
public boolean isGv2() {
return gv2;
}
public boolean isGv1Migration() {
return gv1Migration;
}
public boolean isSenderKey() {
return senderKey;
}
public boolean isAnnouncementGroup() {
return announcementGroup;
}
public boolean isChangeNumber() {
return changeNumber;
}
public boolean isStories() {
return stories;
}
public boolean isGiftBadges() {
return giftBadges;
// Although originally intended to indicate that clients support phone number identifiers, the scope of this
// flag has expanded to cover phone number privacy in general
account.isPniSupported());
}
}
@@ -5,22 +5,22 @@ import static com.codahale.metrics.MetricRegistry.name;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.whispersystems.textsecuregcm.abuse.RateLimitChallengeListener;
import org.whispersystems.textsecuregcm.captcha.CaptchaChecker;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.push.NotPushRegisteredException;
import org.whispersystems.textsecuregcm.recaptcha.RecaptchaClient;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.util.Util;
public class RateLimitChallengeManager {
private final PushChallengeManager pushChallengeManager;
private final RecaptchaClient recaptchaClient;
private final CaptchaChecker captchaChecker;
private final DynamicRateLimiters rateLimiters;
private final List<RateLimitChallengeListener> rateLimitChallengeListeners =
@@ -34,11 +34,11 @@ public class RateLimitChallengeManager {
public RateLimitChallengeManager(
final PushChallengeManager pushChallengeManager,
final RecaptchaClient recaptchaClient,
final CaptchaChecker captchaChecker,
final DynamicRateLimiters rateLimiters) {
this.pushChallengeManager = pushChallengeManager;
this.recaptchaClient = recaptchaClient;
this.captchaChecker = captchaChecker;
this.rateLimiters = rateLimiters;
}
@@ -58,11 +58,11 @@ public class RateLimitChallengeManager {
}
public void answerRecaptchaChallenge(final Account account, final String captcha, final String mostRecentProxyIp, final String userAgent)
throws RateLimitExceededException {
throws RateLimitExceededException, IOException {
rateLimiters.getRecaptchaChallengeAttemptLimiter().validate(account.getUuid());
final boolean challengeSuccess = recaptchaClient.verify(captcha, mostRecentProxyIp).valid();
final boolean challengeSuccess = captchaChecker.verify(captcha, mostRecentProxyIp).valid();
final Tags tags = Tags.of(
Tag.of(SOURCE_COUNTRY_TAG_NAME, Util.getCountryCode(account.getNumber())),
@@ -15,7 +15,6 @@ public class RateLimiters {
private final RateLimiter voiceDestinationDailyLimiter;
private final RateLimiter smsVoiceIpLimiter;
private final RateLimiter smsVoicePrefixLimiter;
private final RateLimiter autoBlockLimiter;
private final RateLimiter verifyLimiter;
private final RateLimiter pinLimiter;
@@ -30,6 +29,8 @@ public class RateLimiters {
private final RateLimiter profileLimiter;
private final RateLimiter stickerPackLimiter;
private final RateLimiter artPackLimiter;
private final RateLimiter usernameLookupLimiter;
private final RateLimiter usernameSetLimiter;
@@ -60,10 +61,6 @@ public class RateLimiters {
config.getSmsVoicePrefix().getBucketSize(),
config.getSmsVoicePrefix().getLeakRatePerMinute());
this.autoBlockLimiter = new RateLimiter(cacheCluster, "autoBlock",
config.getAutoBlock().getBucketSize(),
config.getAutoBlock().getLeakRatePerMinute());
this.verifyLimiter = new LockingRateLimiter(cacheCluster, "verify",
config.getVerifyNumber().getBucketSize(),
config.getVerifyNumber().getLeakRatePerMinute());
@@ -104,6 +101,10 @@ public class RateLimiters {
config.getStickerPack().getBucketSize(),
config.getStickerPack().getLeakRatePerMinute());
this.artPackLimiter = new RateLimiter(cacheCluster, "artPack",
config.getArtPack().getBucketSize(),
config.getArtPack().getLeakRatePerMinute());
this.usernameLookupLimiter = new RateLimiter(cacheCluster, "usernameLookup",
config.getUsernameLookup().getBucketSize(),
config.getUsernameLookup().getLeakRatePerMinute());
@@ -158,10 +159,6 @@ public class RateLimiters {
return smsVoicePrefixLimiter;
}
public RateLimiter getAutoBlockLimiter() {
return autoBlockLimiter;
}
public RateLimiter getVoiceDestinationLimiter() {
return voiceDestinationLimiter;
}
@@ -190,6 +187,10 @@ public class RateLimiters {
return stickerPackLimiter;
}
public RateLimiter getArtPackLimiter() {
return artPackLimiter;
}
public RateLimiter getUsernameLookupLimiter() {
return usernameLookupLimiter;
}
@@ -5,7 +5,9 @@
package org.whispersystems.textsecuregcm.mappers;
import java.util.Optional;
import java.util.concurrent.CompletionException;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
@@ -23,8 +25,25 @@ public class CompletionExceptionMapper implements ExceptionMapper<CompletionExce
final Throwable cause = exception.getCause();
if (cause != null) {
final Class type = cause.getClass();
return providers.getExceptionMapper(type).toResponse(cause);
final ExceptionMapper exceptionMapper = providers.getExceptionMapper(type);
// some exception mappers, like LoggingExceptionMapper, have side effects (e.g., logging)
// so we always build their response…
final Response exceptionMapperResponse = exceptionMapper.toResponse(cause);
final Optional<Response> webApplicationExceptionResponse;
if (cause instanceof WebApplicationException webApplicationException) {
webApplicationExceptionResponse = Optional.of(webApplicationException.getResponse());
} else {
webApplicationExceptionResponse = Optional.empty();
}
// …but if the exception was a WebApplicationException, and provides an entity, we want to keep it
return webApplicationExceptionResponse
.filter(Response::hasEntity)
.orElse(exceptionMapperResponse);
}
return Response.serverError().build();
@@ -16,15 +16,19 @@ import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.signal.registration.rpc.CheckVerificationCodeRequest;
import org.signal.registration.rpc.CheckVerificationCodeResponse;
import org.signal.registration.rpc.CreateRegistrationSessionRequest;
import org.signal.registration.rpc.RegistrationServiceGrpc;
import org.signal.registration.rpc.SendVerificationCodeRequest;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
public class RegistrationServiceClient implements Managed {
@@ -52,17 +56,37 @@ public class RegistrationServiceClient implements Managed {
this.callbackExecutor = callbackExecutor;
}
public CompletableFuture<byte[]> sendRegistrationCode(final Phonenumber.PhoneNumber phoneNumber,
public CompletableFuture<byte[]> createRegistrationSession(final Phonenumber.PhoneNumber phoneNumber, final Duration timeout) {
final long e164 = Long.parseLong(
PhoneNumberUtil.getInstance().format(phoneNumber, PhoneNumberUtil.PhoneNumberFormat.E164).substring(1));
return toCompletableFuture(stub.withDeadline(toDeadline(timeout))
.createSession(CreateRegistrationSessionRequest.newBuilder()
.setE164(e164)
.build()))
.thenApply(response -> switch (response.getResponseCase()) {
case SESSION_METADATA -> response.getSessionMetadata().getSessionId().toByteArray();
case ERROR -> {
switch (response.getError().getErrorType()) {
case CREATE_REGISTRATION_SESSION_ERROR_TYPE_RATE_LIMITED -> throw new CompletionException(new RateLimitExceededException(Duration.ofSeconds(response.getError().getRetryAfterSeconds())));
case CREATE_REGISTRATION_SESSION_ERROR_TYPE_ILLEGAL_PHONE_NUMBER -> throw new IllegalArgumentException();
default -> throw new RuntimeException("Unrecognized error type from registration service: " + response.getError().getErrorType());
}
}
case RESPONSE_NOT_SET -> throw new RuntimeException("No response from registration service");
});
}
public CompletableFuture<byte[]> sendRegistrationCode(final byte[] sessionId,
final MessageTransport messageTransport,
final ClientType clientType,
@Nullable final String acceptLanguage,
final Duration timeout) {
final long e164 = Long.parseLong(
PhoneNumberUtil.getInstance().format(phoneNumber, PhoneNumberUtil.PhoneNumberFormat.E164).substring(1));
final SendVerificationCodeRequest.Builder requestBuilder = SendVerificationCodeRequest.newBuilder()
.setE164(e164)
.setSessionId(ByteString.copyFrom(sessionId))
.setTransport(getRpcMessageTransport(messageTransport))
.setClientType(getRpcClientType(clientType));
@@ -72,7 +96,18 @@ public class RegistrationServiceClient implements Managed {
return toCompletableFuture(stub.withDeadline(toDeadline(timeout))
.sendVerificationCode(requestBuilder.build()))
.thenApply(response -> response.getSessionId().toByteArray());
.thenApply(response -> {
if (response.hasError()) {
switch (response.getError().getErrorType()) {
case SEND_VERIFICATION_CODE_ERROR_TYPE_RATE_LIMITED ->
throw new CompletionException(new RateLimitExceededException(Duration.ofSeconds(response.getError().getRetryAfterSeconds())));
default -> throw new CompletionException(new RuntimeException("Failed to send verification code: " + response.getError().getErrorType()));
}
} else {
return response.getSessionId().toByteArray();
}
});
}
public CompletableFuture<Boolean> checkVerificationCode(final byte[] sessionId,
@@ -84,7 +119,18 @@ public class RegistrationServiceClient implements Managed {
.setSessionId(ByteString.copyFrom(sessionId))
.setVerificationCode(verificationCode)
.build()))
.thenApply(CheckVerificationCodeResponse::getVerified);
.thenApply(response -> {
if (response.hasError()) {
switch (response.getError().getErrorType()) {
case CHECK_VERIFICATION_CODE_ERROR_TYPE_RATE_LIMITED ->
throw new CompletionException(new RateLimitExceededException(Duration.ofSeconds(response.getError().getRetryAfterSeconds())));
default -> throw new CompletionException(new RuntimeException("Failed to check verification code: " + response.getError().getErrorType()));
}
} else {
return response.getVerified() || response.getSessionMetadata().getVerified();
}
});
}
private static Deadline toDeadline(final Duration timeout) {
@@ -57,7 +57,7 @@ public class SecureBackupClient {
.uri(deleteUri)
.DELETE()
.header("Authorization", "Basic " + Base64.getEncoder().encodeToString(
(credentials.getUsername() + ":" + credentials.getPassword()).getBytes(StandardCharsets.UTF_8)))
(credentials.username() + ":" + credentials.password()).getBytes(StandardCharsets.UTF_8)))
.build();
return httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString()).thenApply(response -> {
@@ -58,7 +58,7 @@ public class SecureStorageClient {
.uri(deleteUri)
.DELETE()
.header("Authorization", "Basic " + Base64.getEncoder().encodeToString(
(credentials.getUsername() + ":" + credentials.getPassword()).getBytes(StandardCharsets.UTF_8)))
(credentials.username() + ":" + credentials.password()).getBytes(StandardCharsets.UTF_8)))
.build();
return httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString()).thenApply(response -> {
@@ -16,7 +16,6 @@ import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
@@ -25,20 +24,26 @@ import software.amazon.awssdk.services.dynamodb.model.BatchWriteItemRequest;
import software.amazon.awssdk.services.dynamodb.model.BatchWriteItemResponse;
import software.amazon.awssdk.services.dynamodb.model.ScanRequest;
import software.amazon.awssdk.services.dynamodb.model.WriteRequest;
import javax.annotation.Nonnull;
public abstract class AbstractDynamoDbStore {
private final DynamoDbClient dynamoDbClient;
private static final int MAX_ATTEMPTS_TO_SAVE_BATCH_WRITE = 25; // This was arbitrarily chosen and may be entirely too high.
private final Timer batchWriteItemsFirstPass = timer(name(getClass(), "batchWriteItems"), "firstAttempt", "true");
private final Timer batchWriteItemsRetryPass = timer(name(getClass(), "batchWriteItems"), "firstAttempt", "false");
private final Counter batchWriteItemsUnprocessed = counter(name(getClass(), "batchWriteItemsUnprocessed"));
public static final int DYNAMO_DB_MAX_BATCH_SIZE = 25; // This limit comes from Amazon Dynamo DB itself. It will reject batch writes larger than this.
public static final int RESULT_SET_CHUNK_SIZE = 100;
private final Logger logger = LoggerFactory.getLogger(getClass());
private static final int MAX_ATTEMPTS_TO_SAVE_BATCH_WRITE = 25; // This was arbitrarily chosen and may be entirely too high.
public static final int DYNAMO_DB_MAX_BATCH_SIZE = 25; // This limit comes from Amazon Dynamo DB itself. It will reject batch writes larger than this.
public static final int RESULT_SET_CHUNK_SIZE = 100;
private final Timer batchWriteItemsFirstPass = timer(name(getClass(), "batchWriteItems"), "firstAttempt", "true");
private final Timer batchWriteItemsRetryPass = timer(name(getClass(), "batchWriteItems"), "firstAttempt", "false");
private final Counter batchWriteItemsUnprocessed = counter(name(getClass(), "batchWriteItemsUnprocessed"));
private final DynamoDbClient dynamoDbClient;
public AbstractDynamoDbStore(final DynamoDbClient dynamoDbClient) {
this.dynamoDbClient = dynamoDbClient;
@@ -49,18 +54,15 @@ public abstract class AbstractDynamoDbStore {
}
protected void executeTableWriteItemsUntilComplete(final Map<String, List<WriteRequest>> items) {
AtomicReference<BatchWriteItemResponse> outcome = new AtomicReference<>();
batchWriteItemsFirstPass.record(
() -> outcome.set(dynamoDbClient.batchWriteItem(BatchWriteItemRequest.builder().requestItems(items).build())));
final AtomicReference<BatchWriteItemResponse> outcome = new AtomicReference<>();
writeAndStoreOutcome(items, batchWriteItemsFirstPass, outcome);
int attemptCount = 0;
while (!outcome.get().unprocessedItems().isEmpty() && attemptCount < MAX_ATTEMPTS_TO_SAVE_BATCH_WRITE) {
batchWriteItemsRetryPass.record(() -> outcome.set(dynamoDbClient.batchWriteItem(BatchWriteItemRequest.builder()
.requestItems(outcome.get().unprocessedItems())
.build())));
writeAndStoreOutcome(outcome.get().unprocessedItems(), batchWriteItemsRetryPass, outcome);
++attemptCount;
}
if (!outcome.get().unprocessedItems().isEmpty()) {
int totalItems = outcome.get().unprocessedItems().values().stream().mapToInt(List::size).sum();
final int totalItems = outcome.get().unprocessedItems().values().stream().mapToInt(List::size).sum();
logger.error(
"Attempt count ({}) reached max ({}}) before applying all batch writes to dynamo. {} unprocessed items remain.",
attemptCount, MAX_ATTEMPTS_TO_SAVE_BATCH_WRITE, totalItems);
@@ -68,19 +70,28 @@ public abstract class AbstractDynamoDbStore {
}
}
protected List<Map<String, AttributeValue>> scan(ScanRequest scanRequest, int max) {
@Nonnull
protected List<Map<String, AttributeValue>> scan(final ScanRequest scanRequest, final int max) {
return db().scanPaginator(scanRequest)
.items()
.stream()
.limit(max)
.collect(Collectors.toList());
.toList();
}
private void writeAndStoreOutcome(
final Map<String, List<WriteRequest>> items,
final Timer timer,
final AtomicReference<BatchWriteItemResponse> outcome) {
timer.record(
() -> outcome.set(dynamoDbClient.batchWriteItem(BatchWriteItemRequest.builder().requestItems(items).build()))
);
}
static <T> void writeInBatches(final Iterable<T> items, final Consumer<List<T>> action) {
final List<T> batch = new ArrayList<>(DYNAMO_DB_MAX_BATCH_SIZE);
for (T item : items) {
for (final T item : items) {
batch.add(item);
if (batch.size() == DYNAMO_DB_MAX_BATCH_SIZE) {
@@ -1,52 +0,0 @@
/*
* Copyright 2013-2020 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage;
import static com.codahale.metrics.MetricRegistry.name;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.SharedMetricRegistries;
import com.codahale.metrics.Timer;
import java.time.Duration;
import com.google.common.annotations.VisibleForTesting;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
import org.whispersystems.textsecuregcm.util.Constants;
public class AbusiveHostRules {
private static final String KEY_PREFIX = "abusive_hosts::";
private final MetricRegistry metricRegistry = SharedMetricRegistries.getOrCreate(Constants.METRICS_NAME);
private final Timer getTimer = metricRegistry.timer(name(AbusiveHostRules.class, "get"));
private final Timer insertTimer = metricRegistry.timer(name(AbusiveHostRules.class, "setBlockedHost"));
private final FaultTolerantRedisCluster redisCluster;
private final DynamicConfigurationManager<DynamicConfiguration> configurationManager;
public AbusiveHostRules(FaultTolerantRedisCluster redisCluster, final DynamicConfigurationManager<DynamicConfiguration> configurationManager) {
this.redisCluster = redisCluster;
this.configurationManager = configurationManager;
}
public boolean isBlocked(String host) {
try (Timer.Context timer = getTimer.time()) {
return this.redisCluster.withCluster(connection -> connection.sync().exists(prefix(host))) > 0;
}
}
public void setBlockedHost(String host) {
Duration expireTime = configurationManager.getConfiguration().getAbusiveHostRules().getExpirationTime();
try (Timer.Context timer = insertTimer.time()) {
this.redisCluster.useCluster(connection -> connection.sync().setex(prefix(host), expireTime.toSeconds(), "1"));
}
}
@VisibleForTesting
public static String prefix(String keyName) {
return KEY_PREFIX + keyName;
}
}
@@ -181,14 +181,6 @@ public class Account {
return devices.stream().filter(device -> device.getId() == deviceId).findFirst();
}
public boolean isGroupsV2Supported() {
requireNotStale();
return devices.stream()
.filter(Device::isEnabled)
.allMatch(Device::isGroupsV2Supported);
}
public boolean isStorageSupported() {
requireNotStale();
@@ -201,10 +193,6 @@ public class Account {
return getMasterDevice().map(Device::getCapabilities).map(Device.DeviceCapabilities::isTransfer).orElse(false);
}
public boolean isGv1MigrationSupported() {
return allEnabledDevicesHaveCapability(DeviceCapabilities::isGv1Migration);
}
public boolean isSenderKeySupported() {
return allEnabledDevicesHaveCapability(DeviceCapabilities::isSenderKey);
}
@@ -233,6 +221,10 @@ public class Account {
return allEnabledDevicesHaveCapability(DeviceCapabilities::isGiftBadges);
}
public boolean isPaymentActivationSupported() {
return allEnabledDevicesHaveCapability(DeviceCapabilities::isPaymentActivation);
}
private boolean allEnabledDevicesHaveCapability(Predicate<DeviceCapabilities> predicate) {
requireNotStale();
@@ -4,34 +4,32 @@
*/
package org.whispersystems.textsecuregcm.storage;
import com.google.common.annotations.VisibleForTesting;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Metrics;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.util.Util;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
public class AccountCleaner extends AccountDatabaseCrawlerListener {
private static final Logger log = LoggerFactory.getLogger(AccountCleaner.class);
private static final String DELETED_ACCOUNT_COUNTER_NAME = name(AccountCleaner.class, "deletedAccounts");
private static final String DELETION_REASON_TAG_NAME = "reason";
@VisibleForTesting
static final int MAX_ACCOUNT_DELETIONS_PER_CHUNK = 256;
private static final Counter DELETED_ACCOUNT_COUNTER = Metrics.counter(name(AccountCleaner.class, "deletedAccounts"));
private final AccountsManager accountsManager;
private final Executor deletionExecutor;
public AccountCleaner(AccountsManager accountsManager) {
public AccountCleaner(final AccountsManager accountsManager, final Executor deletionExecutor) {
this.accountsManager = accountsManager;
this.deletionExecutor = deletionExecutor;
}
@Override
@@ -44,43 +42,32 @@ public class AccountCleaner extends AccountDatabaseCrawlerListener {
@Override
protected void onCrawlChunk(Optional<UUID> fromUuid, List<Account> chunkAccounts) {
int accountUpdateCount = 0;
final List<CompletableFuture<Void>> deletionFutures = chunkAccounts.stream()
.filter(AccountCleaner::isExpired)
.map(account -> CompletableFuture.runAsync(() -> {
try {
accountsManager.delete(account, AccountsManager.DeletionReason.EXPIRED);
} catch (final InterruptedException e) {
throw new CompletionException(e);
}
}, deletionExecutor)
.whenComplete((ignored, throwable) -> {
if (throwable != null) {
log.warn("Failed to delete account {}", account.getUuid(), throwable);
} else {
DELETED_ACCOUNT_COUNTER.increment();
}
}))
.toList();
for (Account account : chunkAccounts) {
if (isExpired(account) || needsExplicitRemoval(account)) {
final Tag deletionReason;
if (needsExplicitRemoval(account)) {
deletionReason = Tag.of(DELETION_REASON_TAG_NAME, "newlyExpired");
} else {
deletionReason = Tag.of(DELETION_REASON_TAG_NAME, "previouslyExpired");
}
if (accountUpdateCount < MAX_ACCOUNT_DELETIONS_PER_CHUNK) {
try {
accountsManager.delete(account, AccountsManager.DeletionReason.EXPIRED);
accountUpdateCount++;
Metrics.counter(DELETED_ACCOUNT_COUNTER_NAME, Tags.of(deletionReason)).increment();
} catch (final Exception e) {
log.warn("Failed to delete account {}", account.getUuid(), e);
}
}
}
try {
CompletableFuture.allOf(deletionFutures.toArray(new CompletableFuture[0])).join();
} catch (final Exception e) {
log.debug("Failed to delete one or more accounts in chunk", e);
}
}
private boolean needsExplicitRemoval(Account account) {
return account.getMasterDevice().isPresent() &&
hasPushToken(account.getMasterDevice().get()) &&
isExpired(account);
}
private boolean hasPushToken(Device device) {
return !Util.isEmpty(device.getGcmId()) || !Util.isEmpty(device.getApnId()) || !Util.isEmpty(device.getVoipApnId()) || device.getFetchesMessages();
}
private boolean isExpired(Account account) {
private static boolean isExpired(Account account) {
return account.getLastSeen() + TimeUnit.DAYS.toMillis(365) < System.currentTimeMillis();
}
@@ -5,6 +5,7 @@
package org.whispersystems.textsecuregcm.storage;
import static com.codahale.metrics.MetricRegistry.name;
import static java.util.Objects.requireNonNull;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.annotations.VisibleForTesting;
@@ -18,7 +19,6 @@ import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@@ -29,14 +29,17 @@ import java.util.UUID;
import java.util.concurrent.CompletionException;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.TimeUnit;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.util.AttributeValues;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import org.whispersystems.textsecuregcm.util.SystemMapper;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
import org.whispersystems.textsecuregcm.util.UsernameNormalizer;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
@@ -56,8 +59,31 @@ import software.amazon.awssdk.services.dynamodb.model.Update;
import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;
import software.amazon.awssdk.utils.CompletableFutureUtils;
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
public class Accounts extends AbstractDynamoDbStore {
private static final Logger log = LoggerFactory.getLogger(Accounts.class);
private static final byte RESERVED_USERNAME_HASH_VERSION = 1;
private static final Timer CREATE_TIMER = Metrics.timer(name(Accounts.class, "create"));
private static final Timer CHANGE_NUMBER_TIMER = Metrics.timer(name(Accounts.class, "changeNumber"));
private static final Timer SET_USERNAME_TIMER = Metrics.timer(name(Accounts.class, "setUsername"));
private static final Timer RESERVE_USERNAME_TIMER = Metrics.timer(name(Accounts.class, "reserveUsername"));
private static final Timer CLEAR_USERNAME_TIMER = Metrics.timer(name(Accounts.class, "clearUsername"));
private static final Timer UPDATE_TIMER = Metrics.timer(name(Accounts.class, "update"));
private static final Timer GET_BY_NUMBER_TIMER = Metrics.timer(name(Accounts.class, "getByNumber"));
private static final Timer GET_BY_USERNAME_TIMER = Metrics.timer(name(Accounts.class, "getByUsername"));
private static final Timer GET_BY_PNI_TIMER = Metrics.timer(name(Accounts.class, "getByPni"));
private static final Timer GET_BY_UUID_TIMER = Metrics.timer(name(Accounts.class, "getByUuid"));
private static final Timer GET_ALL_FROM_START_TIMER = Metrics.timer(name(Accounts.class, "getAllFrom"));
private static final Timer GET_ALL_FROM_OFFSET_TIMER = Metrics.timer(name(Accounts.class, "getAllFromOffset"));
private static final Timer DELETE_TIMER = Metrics.timer(name(Accounts.class, "delete"));
private static final String CONDITIONAL_CHECK_FAILED = "ConditionalCheckFailed";
private static final String TRANSACTION_CONFLICT = "TransactionConflict";
// uuid, primary key
static final String KEY_ACCOUNT_UUID = "U";
// uuid, attribute on account table, primary key for PNI table
@@ -78,45 +104,32 @@ public class Accounts extends AbstractDynamoDbStore {
static final String ATTR_TTL = "TTL";
private final Clock clock;
private final DynamoDbClient client;
private final DynamoDbAsyncClient asyncClient;
private final String phoneNumberConstraintTableName;
private final String phoneNumberIdentifierConstraintTableName;
private final String usernamesConstraintTableName;
private final String accountsTableName;
private final int scanPageSize;
private static final byte RESERVED_USERNAME_HASH_VERSION = 1;
private static final Timer CREATE_TIMER = Metrics.timer(name(Accounts.class, "create"));
private static final Timer CHANGE_NUMBER_TIMER = Metrics.timer(name(Accounts.class, "changeNumber"));
private static final Timer SET_USERNAME_TIMER = Metrics.timer(name(Accounts.class, "setUsername"));
private static final Timer RESERVE_USERNAME_TIMER = Metrics.timer(name(Accounts.class, "reserveUsername"));
private static final Timer CLEAR_USERNAME_TIMER = Metrics.timer(name(Accounts.class, "clearUsername"));
private static final Timer UPDATE_TIMER = Metrics.timer(name(Accounts.class, "update"));
private static final Timer GET_BY_NUMBER_TIMER = Metrics.timer(name(Accounts.class, "getByNumber"));
private static final Timer GET_BY_USERNAME_TIMER = Metrics.timer(name(Accounts.class, "getByUsername"));
private static final Timer GET_BY_PNI_TIMER = Metrics.timer(name(Accounts.class, "getByPni"));
private static final Timer GET_BY_UUID_TIMER = Metrics.timer(name(Accounts.class, "getByUuid"));
private static final Timer GET_ALL_FROM_START_TIMER = Metrics.timer(name(Accounts.class, "getAllFrom"));
private static final Timer GET_ALL_FROM_OFFSET_TIMER = Metrics.timer(name(Accounts.class, "getAllFromOffset"));
private static final Timer DELETE_TIMER = Metrics.timer(name(Accounts.class, "delete"));
private static final Logger log = LoggerFactory.getLogger(Accounts.class);
@VisibleForTesting
public Accounts(
final Clock clock,
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
DynamoDbClient client, DynamoDbAsyncClient asyncClient,
String accountsTableName, String phoneNumberConstraintTableName,
String phoneNumberIdentifierConstraintTableName, final String usernamesConstraintTableName,
final DynamoDbClient client,
final DynamoDbAsyncClient asyncClient,
final String accountsTableName,
final String phoneNumberConstraintTableName,
final String phoneNumberIdentifierConstraintTableName,
final String usernamesConstraintTableName,
final int scanPageSize) {
super(client);
this.clock = clock;
this.client = client;
this.asyncClient = asyncClient;
this.phoneNumberConstraintTableName = phoneNumberConstraintTableName;
this.phoneNumberIdentifierConstraintTableName = phoneNumberIdentifierConstraintTableName;
@@ -125,105 +138,61 @@ public class Accounts extends AbstractDynamoDbStore {
this.scanPageSize = scanPageSize;
}
public Accounts(final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
DynamoDbClient client, DynamoDbAsyncClient asyncClient,
String accountsTableName, String phoneNumberConstraintTableName,
String phoneNumberIdentifierConstraintTableName, final String usernamesConstraintTableName,
public Accounts(
final DynamoDbClient client,
final DynamoDbAsyncClient asyncClient,
final String accountsTableName,
final String phoneNumberConstraintTableName,
final String phoneNumberIdentifierConstraintTableName,
final String usernamesConstraintTableName,
final int scanPageSize) {
this(Clock.systemUTC(), dynamicConfigurationManager, client, asyncClient, accountsTableName,
this(Clock.systemUTC(), client, asyncClient, accountsTableName,
phoneNumberConstraintTableName, phoneNumberIdentifierConstraintTableName, usernamesConstraintTableName,
scanPageSize);
}
public boolean create(Account account) {
public boolean create(final Account account) {
return CREATE_TIMER.record(() -> {
try {
TransactWriteItem phoneNumberConstraintPut = TransactWriteItem.builder()
.put(
Put.builder()
.tableName(phoneNumberConstraintTableName)
.item(Map.of(
ATTR_ACCOUNT_E164, AttributeValues.fromString(account.getNumber()),
KEY_ACCOUNT_UUID, AttributeValues.fromUUID(account.getUuid())))
.conditionExpression(
"attribute_not_exists(#number) OR (attribute_exists(#number) AND #uuid = :uuid)")
.expressionAttributeNames(
Map.of("#uuid", KEY_ACCOUNT_UUID,
"#number", ATTR_ACCOUNT_E164))
.expressionAttributeValues(
Map.of(":uuid", AttributeValues.fromUUID(account.getUuid())))
.returnValuesOnConditionCheckFailure(ReturnValuesOnConditionCheckFailure.ALL_OLD)
.build())
.build();
final AttributeValue uuidAttr = AttributeValues.fromUUID(account.getUuid());
final AttributeValue numberAttr = AttributeValues.fromString(account.getNumber());
final AttributeValue pniUuidAttr = AttributeValues.fromUUID(account.getPhoneNumberIdentifier());
TransactWriteItem phoneNumberIdentifierConstraintPut = TransactWriteItem.builder()
.put(
Put.builder()
.tableName(phoneNumberIdentifierConstraintTableName)
.item(Map.of(
ATTR_PNI_UUID, AttributeValues.fromUUID(account.getPhoneNumberIdentifier()),
KEY_ACCOUNT_UUID, AttributeValues.fromUUID(account.getUuid())))
.conditionExpression(
"attribute_not_exists(#pni) OR (attribute_exists(#pni) AND #uuid = :uuid)")
.expressionAttributeNames(
Map.of("#uuid", KEY_ACCOUNT_UUID,
"#pni", ATTR_PNI_UUID))
.expressionAttributeValues(
Map.of(":uuid", AttributeValues.fromUUID(account.getUuid())))
.returnValuesOnConditionCheckFailure(ReturnValuesOnConditionCheckFailure.ALL_OLD)
.build())
.build();
final TransactWriteItem phoneNumberConstraintPut = buildConstraintTablePutIfAbsent(
phoneNumberConstraintTableName, uuidAttr, ATTR_ACCOUNT_E164, numberAttr);
final Map<String, AttributeValue> item = new HashMap<>(Map.of(
KEY_ACCOUNT_UUID, AttributeValues.fromUUID(account.getUuid()),
ATTR_ACCOUNT_E164, AttributeValues.fromString(account.getNumber()),
ATTR_PNI_UUID, AttributeValues.fromUUID(account.getPhoneNumberIdentifier()),
ATTR_ACCOUNT_DATA, AttributeValues.fromByteArray(SystemMapper.getMapper().writeValueAsBytes(account)),
ATTR_VERSION, AttributeValues.fromInt(account.getVersion()),
ATTR_CANONICALLY_DISCOVERABLE, AttributeValues.fromBool(account.shouldBeVisibleInDirectory())));
final TransactWriteItem phoneNumberIdentifierConstraintPut = buildConstraintTablePutIfAbsent(
phoneNumberIdentifierConstraintTableName, uuidAttr, ATTR_PNI_UUID, pniUuidAttr);
// Add the UAK if it's in the account
account.getUnidentifiedAccessKey()
.map(AttributeValues::fromByteArray)
.ifPresent(uak -> item.put(ATTR_UAK, uak));
TransactWriteItem accountPut = TransactWriteItem.builder()
.put(Put.builder()
.conditionExpression("attribute_not_exists(#number) OR #number = :number")
.expressionAttributeNames(Map.of("#number", ATTR_ACCOUNT_E164))
.expressionAttributeValues(Map.of(":number", AttributeValues.fromString(account.getNumber())))
.tableName(accountsTableName)
.item(item)
.build())
.build();
final TransactWriteItem accountPut = buildAccountPut(account, uuidAttr, numberAttr, pniUuidAttr);
final TransactWriteItemsRequest request = TransactWriteItemsRequest.builder()
.transactItems(phoneNumberConstraintPut, phoneNumberIdentifierConstraintPut, accountPut)
.build();
try {
client.transactWriteItems(request);
} catch (TransactionCanceledException e) {
db().transactWriteItems(request);
} catch (final TransactionCanceledException e) {
final CancellationReason accountCancellationReason = e.cancellationReasons().get(2);
if ("ConditionalCheckFailed".equals(accountCancellationReason.code())) {
if (conditionalCheckFailed(accountCancellationReason)) {
throw new IllegalArgumentException("account identifier present with different phone number");
}
final CancellationReason phoneNumberConstraintCancellationReason = e.cancellationReasons().get(0);
final CancellationReason phoneNumberIdentifierConstraintCancellationReason = e.cancellationReasons().get(1);
if ("ConditionalCheckFailed".equals(phoneNumberConstraintCancellationReason.code()) ||
"ConditionalCheckFailed".equals(phoneNumberIdentifierConstraintCancellationReason.code())) {
if (conditionalCheckFailed(phoneNumberConstraintCancellationReason)
|| conditionalCheckFailed(phoneNumberIdentifierConstraintCancellationReason)) {
// In theory, both reasons should trip in tandem and either should give us the information we need. Even so,
// we'll be cautious here and make sure we're choosing a condition check that really failed.
final CancellationReason reason = "ConditionalCheckFailed".equals(phoneNumberConstraintCancellationReason.code()) ?
phoneNumberConstraintCancellationReason : phoneNumberIdentifierConstraintCancellationReason;
final CancellationReason reason = conditionalCheckFailed(phoneNumberConstraintCancellationReason)
? phoneNumberConstraintCancellationReason
: phoneNumberIdentifierConstraintCancellationReason;
ByteBuffer actualAccountUuid = reason.item().get(KEY_ACCOUNT_UUID).b().asByteBuffer();
final ByteBuffer actualAccountUuid = reason.item().get(KEY_ACCOUNT_UUID).b().asByteBuffer();
account.setUuid(UUIDUtil.fromByteBuffer(actualAccountUuid));
final Account existingAccount = getByAccountIdentifier(account.getUuid()).orElseThrow();
@@ -235,7 +204,7 @@ public class Accounts extends AbstractDynamoDbStore {
return false;
}
if ("TransactionConflict".equals(accountCancellationReason.code())) {
if (TRANSACTION_CONFLICT.equals(accountCancellationReason.code())) {
// this should only happen if two clients manage to make concurrent create() calls
throw new ContestedOptimisticLockException();
}
@@ -243,7 +212,7 @@ public class Accounts extends AbstractDynamoDbStore {
// this shouldn't happen
throw new RuntimeException("could not create account: " + extractCancellationReasonCodes(e));
}
} catch (JsonProcessingException e) {
} catch (final JsonProcessingException e) {
throw new IllegalArgumentException(e);
}
@@ -275,62 +244,34 @@ public class Accounts extends AbstractDynamoDbStore {
try {
final List<TransactWriteItem> writeItems = new ArrayList<>();
final AttributeValue uuidAttr = AttributeValues.fromUUID(account.getUuid());
final AttributeValue numberAttr = AttributeValues.fromString(number);
final AttributeValue pniAttr = AttributeValues.fromUUID(phoneNumberIdentifier);
writeItems.add(TransactWriteItem.builder()
.delete(Delete.builder()
.tableName(phoneNumberConstraintTableName)
.key(Map.of(ATTR_ACCOUNT_E164, AttributeValues.fromString(originalNumber)))
.build())
.build());
writeItems.add(TransactWriteItem.builder()
.put(Put.builder()
.tableName(phoneNumberConstraintTableName)
.item(Map.of(
KEY_ACCOUNT_UUID, AttributeValues.fromUUID(account.getUuid()),
ATTR_ACCOUNT_E164, AttributeValues.fromString(number)))
.conditionExpression("attribute_not_exists(#number)")
.expressionAttributeNames(Map.of("#number", ATTR_ACCOUNT_E164))
.returnValuesOnConditionCheckFailure(ReturnValuesOnConditionCheckFailure.ALL_OLD)
.build())
.build());
writeItems.add(TransactWriteItem.builder()
.delete(Delete.builder()
.tableName(phoneNumberIdentifierConstraintTableName)
.key(Map.of(ATTR_PNI_UUID, AttributeValues.fromUUID(originalPni)))
.build())
.build());
writeItems.add(TransactWriteItem.builder()
.put(Put.builder()
.tableName(phoneNumberIdentifierConstraintTableName)
.item(Map.of(
KEY_ACCOUNT_UUID, AttributeValues.fromUUID(account.getUuid()),
ATTR_PNI_UUID, AttributeValues.fromUUID(phoneNumberIdentifier)))
.conditionExpression("attribute_not_exists(#pni)")
.expressionAttributeNames(Map.of("#pni", ATTR_PNI_UUID))
.returnValuesOnConditionCheckFailure(ReturnValuesOnConditionCheckFailure.ALL_OLD)
.build())
.build());
writeItems.add(buildDelete(phoneNumberConstraintTableName, ATTR_ACCOUNT_E164, originalNumber));
writeItems.add(buildConstraintTablePut(phoneNumberConstraintTableName, uuidAttr, ATTR_ACCOUNT_E164, numberAttr));
writeItems.add(buildDelete(phoneNumberIdentifierConstraintTableName, ATTR_PNI_UUID, originalPni));
writeItems.add(buildConstraintTablePut(phoneNumberIdentifierConstraintTableName, uuidAttr, ATTR_PNI_UUID, pniAttr));
writeItems.add(
TransactWriteItem.builder()
.update(Update.builder()
.tableName(accountsTableName)
.key(Map.of(KEY_ACCOUNT_UUID, AttributeValues.fromUUID(account.getUuid())))
.updateExpression("SET #data = :data, #number = :number, #pni = :pni, #cds = :cds ADD #version :version_increment")
.conditionExpression("attribute_exists(#number) AND #version = :version")
.expressionAttributeNames(Map.of("#number", ATTR_ACCOUNT_E164,
.key(Map.of(KEY_ACCOUNT_UUID, uuidAttr))
.updateExpression(
"SET #data = :data, #number = :number, #pni = :pni, #cds = :cds ADD #version :version_increment")
.conditionExpression(
"attribute_exists(#number) AND #version = :version")
.expressionAttributeNames(Map.of(
"#number", ATTR_ACCOUNT_E164,
"#data", ATTR_ACCOUNT_DATA,
"#cds", ATTR_CANONICALLY_DISCOVERABLE,
"#pni", ATTR_PNI_UUID,
"#version", ATTR_VERSION))
.expressionAttributeValues(Map.of(
":number", numberAttr,
":data", AttributeValues.fromByteArray(SystemMapper.getMapper().writeValueAsBytes(account)),
":number", AttributeValues.fromString(number),
":pni", AttributeValues.fromUUID(phoneNumberIdentifier),
":cds", AttributeValues.fromBool(account.shouldBeVisibleInDirectory()),
":pni", pniAttr,
":version", AttributeValues.fromInt(account.getVersion()),
":version_increment", AttributeValues.fromInt(1)))
.build())
@@ -340,7 +281,7 @@ public class Accounts extends AbstractDynamoDbStore {
.transactItems(writeItems)
.build();
client.transactWriteItems(request);
db().transactWriteItems(request);
account.setVersion(account.getVersion() + 1);
succeeded = true;
@@ -354,21 +295,6 @@ public class Accounts extends AbstractDynamoDbStore {
});
}
public static byte[] reservedUsernameHash(final UUID accountId, final String reservedUsername) {
final MessageDigest sha256;
try {
sha256 = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
throw new AssertionError(e);
}
final ByteBuffer byteBuffer = ByteBuffer.allocate(32 + 1);
sha256.update(reservedUsername.getBytes(StandardCharsets.UTF_8));
sha256.update(UUIDUtil.toBytes(accountId));
byteBuffer.put(RESERVED_USERNAME_HASH_VERSION);
byteBuffer.put(sha256.digest());
return byteBuffer.array();
}
/**
* Reserve a username under a token
*
@@ -379,14 +305,13 @@ public class Accounts extends AbstractDynamoDbStore {
final String reservedUsername,
final Duration ttl) {
final long startNanos = System.nanoTime();
// if there is an existing old reservation it will be cleaned up via ttl
final Optional<byte[]> maybeOriginalReservation = account.getReservedUsernameHash();
account.setReservedUsernameHash(reservedUsernameHash(account.getUuid(), reservedUsername));
boolean succeeded = false;
long expirationTime = clock.instant().plus(ttl).getEpochSecond();
final long expirationTime = clock.instant().plus(ttl).getEpochSecond();
final UUID reservationToken = UUID.randomUUID();
try {
@@ -397,7 +322,7 @@ public class Accounts extends AbstractDynamoDbStore {
.tableName(usernamesConstraintTableName)
.item(Map.of(
KEY_ACCOUNT_UUID, AttributeValues.fromUUID(reservationToken),
ATTR_USERNAME, AttributeValues.fromString(reservedUsername),
ATTR_USERNAME, AttributeValues.fromString(UsernameNormalizer.normalize(reservedUsername)),
ATTR_TTL, AttributeValues.fromLong(expirationTime)))
.conditionExpression("attribute_not_exists(#username) OR (#ttl < :now)")
.expressionAttributeNames(Map.of("#username", ATTR_USERNAME, "#ttl", ATTR_TTL))
@@ -425,14 +350,14 @@ public class Accounts extends AbstractDynamoDbStore {
.transactItems(writeItems)
.build();
client.transactWriteItems(request);
db().transactWriteItems(request);
account.setVersion(account.getVersion() + 1);
succeeded = true;
} catch (final JsonProcessingException e) {
throw new IllegalArgumentException(e);
} catch (final TransactionCanceledException e) {
if (e.cancellationReasons().stream().map(CancellationReason::code).anyMatch("ConditionalCheckFailed"::equals)) {
if (e.cancellationReasons().stream().map(CancellationReason::code).anyMatch(CONDITIONAL_CHECK_FAILED::equals)) {
throw new ContestedOptimisticLockException();
}
throw e;
@@ -486,12 +411,13 @@ public class Accounts extends AbstractDynamoDbStore {
final List<TransactWriteItem> writeItems = new ArrayList<>();
// add the username to the constraint table, wiping out the ttl if we had already reserved the name
// Persist the normalized username in the usernamesConstraint table and the original username in the accounts table
writeItems.add(TransactWriteItem.builder()
.put(Put.builder()
.tableName(usernamesConstraintTableName)
.item(Map.of(
KEY_ACCOUNT_UUID, AttributeValues.fromUUID(account.getUuid()),
ATTR_USERNAME, AttributeValues.fromString(username)))
ATTR_USERNAME, AttributeValues.fromString(UsernameNormalizer.normalize(username))))
// it's not in the constraint table OR it's expired OR it was reserved by us
.conditionExpression("attribute_not_exists(#username) OR #ttl < :now OR #aci = :reservation ")
.expressionAttributeNames(Map.of("#username", ATTR_USERNAME, "#ttl", ATTR_TTL, "#aci", KEY_ACCOUNT_UUID))
@@ -520,25 +446,21 @@ public class Accounts extends AbstractDynamoDbStore {
.build())
.build());
maybeOriginalUsername.ifPresent(originalUsername -> writeItems.add(TransactWriteItem.builder()
.delete(Delete.builder()
.tableName(usernamesConstraintTableName)
.key(Map.of(ATTR_USERNAME, AttributeValues.fromString(originalUsername)))
.build())
.build()));
maybeOriginalUsername.ifPresent(originalUsername -> writeItems.add(
buildDelete(usernamesConstraintTableName, ATTR_USERNAME, UsernameNormalizer.normalize(originalUsername))));
final TransactWriteItemsRequest request = TransactWriteItemsRequest.builder()
.transactItems(writeItems)
.build();
client.transactWriteItems(request);
db().transactWriteItems(request);
account.setVersion(account.getVersion() + 1);
succeeded = true;
} catch (final JsonProcessingException e) {
throw new IllegalArgumentException(e);
} catch (final TransactionCanceledException e) {
if (e.cancellationReasons().stream().map(CancellationReason::code).anyMatch("ConditionalCheckFailed"::equals)) {
if (e.cancellationReasons().stream().map(CancellationReason::code).anyMatch(CONDITIONAL_CHECK_FAILED::equals)) {
throw new ContestedOptimisticLockException();
}
throw e;
@@ -551,7 +473,7 @@ public class Accounts extends AbstractDynamoDbStore {
}
}
public void clearUsername(Account account) {
public void clearUsername(final Account account) {
account.getUsername().ifPresent(username -> {
CLEAR_USERNAME_TIMER.record(() -> {
account.setUsername(null);
@@ -578,25 +500,20 @@ public class Accounts extends AbstractDynamoDbStore {
.build())
.build());
writeItems.add(TransactWriteItem.builder()
.delete(Delete.builder()
.tableName(usernamesConstraintTableName)
.key(Map.of(ATTR_USERNAME, AttributeValues.fromString(username)))
.build())
.build());
writeItems.add(buildDelete(usernamesConstraintTableName, ATTR_USERNAME, UsernameNormalizer.normalize(username)));
final TransactWriteItemsRequest request = TransactWriteItemsRequest.builder()
.transactItems(writeItems)
.build();
client.transactWriteItems(request);
db().transactWriteItems(request);
account.setVersion(account.getVersion() + 1);
succeeded = true;
} catch (final JsonProcessingException e) {
throw new IllegalArgumentException(e);
} catch (final TransactionCanceledException e) {
if ("ConditionalCheckFailed".equals(e.cancellationReasons().get(0).code())) {
if (conditionalCheckFailed(e.cancellationReasons().get(0))) {
throw new ContestedOptimisticLockException();
}
@@ -610,27 +527,18 @@ public class Accounts extends AbstractDynamoDbStore {
});
}
/**
* Extract the cause from a CompletionException
*/
private static Throwable unwrap(Throwable throwable) {
while (throwable instanceof CompletionException e && throwable.getCause() != null) {
throwable = e.getCause();
}
return throwable;
}
public CompletionStage<Void> updateAsync(Account account) {
@Nonnull
public CompletionStage<Void> updateAsync(final Account account) {
return record(UPDATE_TIMER, () -> {
final UpdateItemRequest updateItemRequest;
try {
// username, e164, and pni cannot be modified through this method
Map<String, String> attrNames = new HashMap<>(Map.of(
final Map<String, String> attrNames = new HashMap<>(Map.of(
"#number", ATTR_ACCOUNT_E164,
"#data", ATTR_ACCOUNT_DATA,
"#cds", ATTR_CANONICALLY_DISCOVERABLE,
"#version", ATTR_VERSION));
Map<String, AttributeValue> attrValues = new HashMap<>(Map.of(
final Map<String, AttributeValue> attrValues = new HashMap<>(Map.of(
":data", AttributeValues.fromByteArray(SystemMapper.getMapper().writeValueAsBytes(account)),
":cds", AttributeValues.fromBool(account.shouldBeVisibleInDirectory()),
":version", AttributeValues.fromInt(account.getVersion()),
@@ -654,7 +562,7 @@ public class Accounts extends AbstractDynamoDbStore {
.expressionAttributeNames(attrNames)
.expressionAttributeValues(attrValues)
.build();
} catch (JsonProcessingException e) {
} catch (final JsonProcessingException e) {
throw new IllegalArgumentException(e);
}
@@ -664,7 +572,7 @@ public class Accounts extends AbstractDynamoDbStore {
return (Void) null;
})
.exceptionally(throwable -> {
final Throwable unwrapped = unwrap(throwable);
final Throwable unwrapped = ExceptionUtils.unwrap(throwable);
if (unwrapped instanceof TransactionConflictException) {
throw new ContestedOptimisticLockException();
} else if (unwrapped instanceof ConditionalCheckFailedException e) {
@@ -679,12 +587,12 @@ public class Accounts extends AbstractDynamoDbStore {
});
}
public void update(Account account) throws ContestedOptimisticLockException {
public void update(final Account account) throws ContestedOptimisticLockException {
try {
this.updateAsync(account).toCompletableFuture().join();
} catch (CompletionException e) {
updateAsync(account).toCompletableFuture().join();
} catch (final CompletionException e) {
// unwrap CompletionExceptions, throw as long is it's unchecked
Throwables.throwIfUnchecked(unwrap(e));
Throwables.throwIfUnchecked(ExceptionUtils.unwrap(e));
// if we otherwise somehow got a wrapped checked exception,
// rethrow the checked exception wrapped by the original CompletionException
@@ -698,15 +606,14 @@ public class Accounts extends AbstractDynamoDbStore {
}
public boolean usernameAvailable(final Optional<UUID> reservationToken, final String username) {
final GetItemResponse response = client.getItem(GetItemRequest.builder()
.tableName(usernamesConstraintTableName)
.key(Map.of(ATTR_USERNAME, AttributeValues.fromString(username)))
.build());
if (!response.hasItem()) {
final Optional<Map<String, AttributeValue>> usernameItem = itemByKey(
usernamesConstraintTableName, ATTR_USERNAME, AttributeValues.fromString(UsernameNormalizer.normalize(username)));
if (usernameItem.isEmpty()) {
// username is free
return true;
}
final Map<String, AttributeValue> item = response.item();
final Map<String, AttributeValue> item = usernameItem.get();
if (AttributeValues.getLong(item, ATTR_TTL, Long.MAX_VALUE) < clock.instant().getEpochSecond()) {
// username was reserved, but has expired
@@ -719,112 +626,55 @@ public class Accounts extends AbstractDynamoDbStore {
.orElse(false);
}
public Optional<Account> getByE164(String number) {
return GET_BY_NUMBER_TIMER.record(() -> {
final GetItemResponse response = client.getItem(GetItemRequest.builder()
.tableName(phoneNumberConstraintTableName)
.key(Map.of(ATTR_ACCOUNT_E164, AttributeValues.fromString(number)))
.build());
return Optional.ofNullable(response.item())
.map(item -> item.get(KEY_ACCOUNT_UUID))
.map(this::accountByUuid)
.map(Accounts::fromItem);
});
}
public Optional<Account> getByUsername(final String username) {
return GET_BY_USERNAME_TIMER.record(() -> {
final GetItemResponse response = client.getItem(GetItemRequest.builder()
.tableName(usernamesConstraintTableName)
.key(Map.of(ATTR_USERNAME, AttributeValues.fromString(username)))
.build());
return Optional.ofNullable(response.item())
// ignore items with a ttl (reservations)
.filter(item -> !item.containsKey(ATTR_TTL))
.map(item -> item.get(KEY_ACCOUNT_UUID))
.map(this::accountByUuid)
.map(Accounts::fromItem);
});
@Nonnull
public Optional<Account> getByE164(final String number) {
return getByIndirectLookup(
GET_BY_NUMBER_TIMER, phoneNumberConstraintTableName, ATTR_ACCOUNT_E164, AttributeValues.fromString(number));
}
@Nonnull
public Optional<Account> getByPhoneNumberIdentifier(final UUID phoneNumberIdentifier) {
return GET_BY_PNI_TIMER.record(() -> {
final GetItemResponse response = client.getItem(GetItemRequest.builder()
.tableName(phoneNumberIdentifierConstraintTableName)
.key(Map.of(ATTR_PNI_UUID, AttributeValues.fromUUID(phoneNumberIdentifier)))
.build());
return Optional.ofNullable(response.item())
.map(item -> item.get(KEY_ACCOUNT_UUID))
.map(this::accountByUuid)
.map(Accounts::fromItem);
});
return getByIndirectLookup(
GET_BY_PNI_TIMER, phoneNumberIdentifierConstraintTableName, ATTR_PNI_UUID, AttributeValues.fromUUID(phoneNumberIdentifier));
}
private Map<String, AttributeValue> accountByUuid(AttributeValue uuid) {
GetItemResponse r = client.getItem(GetItemRequest.builder()
.tableName(accountsTableName)
.key(Map.of(KEY_ACCOUNT_UUID, uuid))
.consistentRead(true)
.build());
return r.item().isEmpty() ? null : r.item();
@Nonnull
public Optional<Account> getByUsername(final String username) {
return getByIndirectLookup(
GET_BY_USERNAME_TIMER,
usernamesConstraintTableName,
ATTR_USERNAME,
AttributeValues.fromString(UsernameNormalizer.normalize(username)),
item -> !item.containsKey(ATTR_TTL) // ignore items with a ttl (reservations)
);
}
public Optional<Account> getByAccountIdentifier(UUID uuid) {
return GET_BY_UUID_TIMER.record(() ->
Optional.ofNullable(accountByUuid(AttributeValues.fromUUID(uuid)))
.map(Accounts::fromItem));
@Nonnull
public Optional<Account> getByAccountIdentifier(final UUID uuid) {
return requireNonNull(GET_BY_UUID_TIMER.record(() ->
itemByKey(accountsTableName, KEY_ACCOUNT_UUID, AttributeValues.fromUUID(uuid))
.map(Accounts::fromItem)));
}
public void delete(UUID uuid) {
DELETE_TIMER.record(() -> {
public void delete(final UUID uuid) {
DELETE_TIMER.record(() -> getByAccountIdentifier(uuid).ifPresent(account -> {
getByAccountIdentifier(uuid).ifPresent(account -> {
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())
));
TransactWriteItem phoneNumberDelete = TransactWriteItem.builder()
.delete(Delete.builder()
.tableName(phoneNumberConstraintTableName)
.key(Map.of(ATTR_ACCOUNT_E164, AttributeValues.fromString(account.getNumber())))
.build())
.build();
account.getUsername().ifPresent(username -> transactWriteItems.add(
buildDelete(usernamesConstraintTableName, ATTR_USERNAME, UsernameNormalizer.normalize(username))));
TransactWriteItem accountDelete = TransactWriteItem.builder()
.delete(Delete.builder()
.tableName(accountsTableName)
.key(Map.of(KEY_ACCOUNT_UUID, AttributeValues.fromUUID(uuid)))
.build())
.build();
final List<TransactWriteItem> transactWriteItems = new ArrayList<>(List.of(phoneNumberDelete, accountDelete));
transactWriteItems.add(TransactWriteItem.builder()
.delete(Delete.builder()
.tableName(phoneNumberIdentifierConstraintTableName)
.key(Map.of(ATTR_PNI_UUID, AttributeValues.fromUUID(account.getPhoneNumberIdentifier())))
.build())
.build());
account.getUsername().ifPresent(username -> transactWriteItems.add(TransactWriteItem.builder()
.delete(Delete.builder()
.tableName(usernamesConstraintTableName)
.key(Map.of(ATTR_USERNAME, AttributeValues.fromString(username)))
.build())
.build()));
TransactWriteItemsRequest request = TransactWriteItemsRequest.builder()
.transactItems(transactWriteItems).build();
client.transactWriteItems(request);
});
});
final TransactWriteItemsRequest request = TransactWriteItemsRequest.builder()
.transactItems(transactWriteItems).build();
db().transactWriteItems(request);
}));
}
@Nonnull
public AccountCrawlChunk getAllFrom(final UUID from, final int maxCount) {
final ScanRequest.Builder scanRequestBuilder = ScanRequest.builder()
.limit(scanPageSize)
@@ -833,6 +683,7 @@ public class Accounts extends AbstractDynamoDbStore {
return scanForChunk(scanRequestBuilder, maxCount, GET_ALL_FROM_OFFSET_TIMER);
}
@Nonnull
public AccountCrawlChunk getAllFromStart(final int maxCount) {
final ScanRequest.Builder scanRequestBuilder = ScanRequest.builder()
.limit(scanPageSize);
@@ -840,34 +691,185 @@ public class Accounts extends AbstractDynamoDbStore {
return scanForChunk(scanRequestBuilder, maxCount, GET_ALL_FROM_START_TIMER);
}
private static <T> CompletionStage<T> record(final Timer timer, Supplier<CompletionStage<T>> toRecord) {
final Instant start = Instant.now();
return toRecord.get().whenComplete((ignoreT, ignoreE) -> timer.record(Duration.between(start, Instant.now())));
@Nonnull
private Optional<Account> getByIndirectLookup(
final Timer timer,
final String tableName,
final String keyName,
final AttributeValue keyValue) {
return getByIndirectLookup(timer, tableName, keyName, keyValue, i -> true);
}
@Nonnull
private Optional<Account> getByIndirectLookup(
final Timer timer,
final String tableName,
final String keyName,
final AttributeValue keyValue,
final Predicate<? super Map<String, AttributeValue>> predicate) {
return requireNonNull(timer.record(() -> itemByKey(tableName, keyName, keyValue)
.filter(predicate)
.map(item -> item.get(KEY_ACCOUNT_UUID))
.flatMap(uuid -> itemByKey(accountsTableName, KEY_ACCOUNT_UUID, uuid))
.map(Accounts::fromItem)));
}
@Nonnull
private Optional<Map<String, AttributeValue>> itemByKey(final String table, final String keyName, final AttributeValue keyValue) {
final GetItemResponse response = db().getItem(GetItemRequest.builder()
.tableName(table)
.key(Map.of(keyName, keyValue))
.consistentRead(true)
.build());
return Optional.ofNullable(response.item()).filter(m -> !m.isEmpty());
}
@Nonnull
private TransactWriteItem buildAccountPut(
final Account account,
final AttributeValue uuidAttr,
final AttributeValue numberAttr,
final AttributeValue pniUuidAttr) throws JsonProcessingException {
final Map<String, AttributeValue> item = new HashMap<>(Map.of(
KEY_ACCOUNT_UUID, uuidAttr,
ATTR_ACCOUNT_E164, numberAttr,
ATTR_PNI_UUID, pniUuidAttr,
ATTR_ACCOUNT_DATA, AttributeValues.fromByteArray(SystemMapper.getMapper().writeValueAsBytes(account)),
ATTR_VERSION, AttributeValues.fromInt(account.getVersion()),
ATTR_CANONICALLY_DISCOVERABLE, AttributeValues.fromBool(account.shouldBeVisibleInDirectory())));
// Add the UAK if it's in the account
account.getUnidentifiedAccessKey()
.map(AttributeValues::fromByteArray)
.ifPresent(uak -> item.put(ATTR_UAK, uak));
return TransactWriteItem.builder()
.put(Put.builder()
.conditionExpression("attribute_not_exists(#number) OR #number = :number")
.expressionAttributeNames(Map.of("#number", ATTR_ACCOUNT_E164))
.expressionAttributeValues(Map.of(":number", numberAttr))
.tableName(accountsTableName)
.item(item)
.build())
.build();
}
@Nonnull
private static TransactWriteItem buildConstraintTablePutIfAbsent(
final String tableName,
final AttributeValue uuidAttr,
final String keyName,
final AttributeValue keyValue
) {
return TransactWriteItem.builder()
.put(Put.builder()
.tableName(tableName)
.item(Map.of(
keyName, keyValue,
KEY_ACCOUNT_UUID, uuidAttr))
.conditionExpression(
"attribute_not_exists(#key) OR #uuid = :uuid")
.expressionAttributeNames(Map.of(
"#key", keyName,
"#uuid", KEY_ACCOUNT_UUID))
.expressionAttributeValues(Map.of(
":uuid", uuidAttr))
.returnValuesOnConditionCheckFailure(ReturnValuesOnConditionCheckFailure.ALL_OLD)
.build())
.build();
}
@Nonnull
private static TransactWriteItem buildConstraintTablePut(
final String tableName,
final AttributeValue uuidAttr,
final String keyName,
final AttributeValue keyValue) {
return TransactWriteItem.builder()
.put(Put.builder()
.tableName(tableName)
.item(Map.of(
keyName, keyValue,
KEY_ACCOUNT_UUID, uuidAttr))
.conditionExpression(
"attribute_not_exists(#key)")
.expressionAttributeNames(Map.of(
"#key", keyName))
.returnValuesOnConditionCheckFailure(ReturnValuesOnConditionCheckFailure.ALL_OLD)
.build())
.build();
}
@Nonnull
private static TransactWriteItem buildDelete(final String tableName, final String keyName, final String keyValue) {
return buildDelete(tableName, keyName, AttributeValues.fromString(keyValue));
}
@Nonnull
private static TransactWriteItem buildDelete(final String tableName, final String keyName, final UUID keyValue) {
return buildDelete(tableName, keyName, AttributeValues.fromUUID(keyValue));
}
@Nonnull
private static TransactWriteItem buildDelete(final String tableName, final String keyName, final AttributeValue keyValue) {
return TransactWriteItem.builder()
.delete(Delete.builder()
.tableName(tableName)
.key(Map.of(keyName, keyValue))
.build())
.build();
}
@Nonnull
private static <T> CompletionStage<T> record(final Timer timer, final Supplier<CompletionStage<T>> toRecord) {
final Timer.Sample sample = Timer.start();
return toRecord.get().whenComplete((ignoreT, ignoreE) -> sample.stop(timer));
}
@Nonnull
private AccountCrawlChunk scanForChunk(final ScanRequest.Builder scanRequestBuilder, final int maxCount, final Timer timer) {
scanRequestBuilder.tableName(accountsTableName);
final List<Map<String, AttributeValue>> items = timer.record(() -> scan(scanRequestBuilder.build(), maxCount));
final List<Map<String, AttributeValue>> items = requireNonNull(timer.record(() -> scan(scanRequestBuilder.build(), maxCount)));
final List<Account> accounts = items.stream().map(Accounts::fromItem).toList();
return new AccountCrawlChunk(accounts, accounts.size() > 0 ? accounts.get(accounts.size() - 1).getUuid() : null);
}
@Nonnull
private static String extractCancellationReasonCodes(final TransactionCanceledException exception) {
return exception.cancellationReasons().stream()
.map(CancellationReason::code)
.collect(Collectors.joining(", "));
}
@Nonnull
public static byte[] reservedUsernameHash(final UUID accountId, final String reservedUsername) {
final MessageDigest sha256;
try {
sha256 = MessageDigest.getInstance("SHA-256");
} catch (final NoSuchAlgorithmException e) {
throw new AssertionError(e);
}
final ByteBuffer byteBuffer = ByteBuffer.allocate(32 + 1);
sha256.update(UsernameNormalizer.normalize(reservedUsername).getBytes(StandardCharsets.UTF_8));
sha256.update(UUIDUtil.toBytes(accountId));
byteBuffer.put(RESERVED_USERNAME_HASH_VERSION);
byteBuffer.put(sha256.digest());
return byteBuffer.array();
}
@VisibleForTesting
static Account fromItem(Map<String, AttributeValue> item) {
if (!item.containsKey(ATTR_ACCOUNT_DATA) ||
!item.containsKey(ATTR_ACCOUNT_E164) ||
// TODO: eventually require ATTR_CANONICALLY_DISCOVERABLE
!item.containsKey(KEY_ACCOUNT_UUID)) {
@Nonnull
static Account fromItem(final Map<String, AttributeValue> item) {
// TODO: eventually require ATTR_CANONICALLY_DISCOVERABLE
if (!item.containsKey(ATTR_ACCOUNT_DATA)
|| !item.containsKey(ATTR_ACCOUNT_E164)
|| !item.containsKey(KEY_ACCOUNT_UUID)) {
throw new RuntimeException("item missing values");
}
try {
Account account = SystemMapper.getMapper().readValue(item.get(ATTR_ACCOUNT_DATA).b().asByteArray(), Account.class);
final Account account = SystemMapper.getMapper().readValue(item.get(ATTR_ACCOUNT_DATA).b().asByteArray(), Account.class);
final UUID accountIdentifier = UUIDUtil.fromByteBuffer(item.get(KEY_ACCOUNT_UUID).b().asByteBuffer());
final UUID phoneNumberIdentifierFromAttribute = AttributeValues.getUUID(item, ATTR_PNI_UUID, null);
@@ -883,12 +885,18 @@ public class Accounts extends AbstractDynamoDbStore {
account.setUuid(accountIdentifier);
account.setUsername(AttributeValues.getString(item, ATTR_USERNAME, null));
account.setVersion(Integer.parseInt(item.get(ATTR_VERSION).n()));
account.setCanonicallyDiscoverable(Optional.ofNullable(item.get(ATTR_CANONICALLY_DISCOVERABLE)).map(av -> av.bool()).orElse(false));
account.setCanonicallyDiscoverable(Optional.ofNullable(item.get(ATTR_CANONICALLY_DISCOVERABLE))
.map(AttributeValue::bool)
.orElse(false));
return account;
} catch (IOException e) {
} catch (final IOException e) {
throw new RuntimeException("Could not read stored account data", e);
}
}
private static boolean conditionalCheckFailed(final CancellationReason reason) {
return CONDITIONAL_CHECK_FAILED.equals(reason.code());
}
}
@@ -51,6 +51,7 @@ import org.whispersystems.textsecuregcm.util.Constants;
import org.whispersystems.textsecuregcm.util.DestinationDeviceValidator;
import org.whispersystems.textsecuregcm.util.SystemMapper;
import org.whispersystems.textsecuregcm.util.UsernameGenerator;
import org.whispersystems.textsecuregcm.util.UsernameNormalizer;
import org.whispersystems.textsecuregcm.util.Util;
public class AccountsManager {
@@ -391,7 +392,7 @@ public class AccountsManager {
return account;
}
final byte[] newHash = Accounts.reservedUsernameHash(account.getUuid(), reservedUsername);
final byte[] newHash = Accounts.reservedUsernameHash(account.getUuid(), UsernameNormalizer.normalize(reservedUsername));
if (!account.getReservedUsernameHash().map(oldHash -> Arrays.equals(oldHash, newHash)).orElse(false)) {
// no such reservation existed, either there was no previous call to reserveUsername
// or the reservation changed
@@ -720,8 +721,8 @@ public class AccountsManager {
clientPresenceManager.disconnectPresence(account.getUuid(), device.getId())));
}
private String getUsernameAccountMapKey(String key) {
return "UAccountMap::" + key;
private String getUsernameAccountMapKey(String username) {
return "UAccountMap::" + UsernameNormalizer.normalize(username);
}
private String getAccountMapKey(String key) {
@@ -252,39 +252,13 @@ public class Device {
return this.userAgent;
}
public boolean isGroupsV2Supported() {
final boolean groupsV2Supported;
if (this.capabilities != null) {
final boolean ios = this.apnId != null || this.voipApnId != null;
groupsV2Supported = this.capabilities.isGv2_3() || (ios && this.capabilities.isGv2_2());
} else {
groupsV2Supported = false;
}
return groupsV2Supported;
}
public static class DeviceCapabilities {
@JsonProperty
private boolean gv2;
@JsonProperty("gv2-2")
private boolean gv2_2;
@JsonProperty("gv2-3")
private boolean gv2_3;
@JsonProperty
private boolean storage;
@JsonProperty
private boolean transfer;
@JsonProperty("gv1-migration")
private boolean gv1Migration;
@JsonProperty
private boolean senderKey;
@@ -303,36 +277,24 @@ public class Device {
@JsonProperty
private boolean giftBadges;
@JsonProperty
private boolean paymentActivation;
public DeviceCapabilities() {
}
public DeviceCapabilities(boolean gv2, final boolean gv2_2, final boolean gv2_3, boolean storage, boolean transfer,
boolean gv1Migration, final boolean senderKey, final boolean announcementGroup, final boolean changeNumber,
final boolean pni, final boolean stories, final boolean giftBadges) {
this.gv2 = gv2;
this.gv2_2 = gv2_2;
this.gv2_3 = gv2_3;
public DeviceCapabilities(boolean storage, boolean transfer,
final boolean senderKey, final boolean announcementGroup, final boolean changeNumber,
final boolean pni, final boolean stories, final boolean giftBadges, final boolean paymentActivation) {
this.storage = storage;
this.transfer = transfer;
this.gv1Migration = gv1Migration;
this.senderKey = senderKey;
this.announcementGroup = announcementGroup;
this.changeNumber = changeNumber;
this.pni = pni;
this.stories = stories;
this.giftBadges = giftBadges;
}
public boolean isGv2() {
return gv2;
}
public boolean isGv2_2() {
return gv2_2;
}
public boolean isGv2_3() {
return gv2_3;
this.paymentActivation = paymentActivation;
}
public boolean isStorage() {
@@ -343,10 +305,6 @@ public class Device {
return transfer;
}
public boolean isGv1Migration() {
return gv1Migration;
}
public boolean isSenderKey() {
return senderKey;
}
@@ -370,5 +328,9 @@ public class Device {
public boolean isGiftBadges() {
return giftBadges;
}
public boolean isPaymentActivation() {
return paymentActivation;
}
}
}
@@ -26,14 +26,16 @@ import javax.crypto.spec.SecretKeySpec;
import javax.ws.rs.ClientErrorException;
import javax.ws.rs.core.Response.Status;
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialRequest;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessor;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.ConditionalCheckFailedException;
import software.amazon.awssdk.services.dynamodb.model.ReturnValue;
import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;
public class IssuedReceiptsManager {
public static final String KEY_STRIPE_ID = "A"; // S (HashKey)
public static final String KEY_PROCESSOR_ITEM_ID = "A"; // S (HashKey)
public static final String KEY_ISSUED_RECEIPT_TAG = "B"; // B
public static final String KEY_EXPIRATION = "E"; // N
@@ -54,29 +56,39 @@ public class IssuedReceiptsManager {
}
/**
* Returns a future that completes normally if either this stripe item was never issued a receipt credential
* Returns a future that completes normally if either this processor item was never issued a receipt credential
* previously OR if it was issued a receipt credential previously for the exact same receipt credential request
* enabling clients to retry in case they missed the original response.
*
* If this stripe item has already been used to issue another receipt, throws a 409 conflict web application
* exception.
*
* Stripe item is expected to refer to an invoice line item (subscriptions) or a payment intent (one-time).
* <p>
* If this item has already been used to issue another receipt, throws a 409 conflict web application exception.
* <p>
* For {@link SubscriptionProcessor#STRIPE}, item is expected to refer to an invoice line item (subscriptions) or a
* payment intent (one-time).
*/
public CompletableFuture<Void> recordIssuance(
String stripeId,
String processorItemId,
SubscriptionProcessor processor,
ReceiptCredentialRequest request,
Instant now) {
final AttributeValue key;
if (processor == SubscriptionProcessor.STRIPE) {
// As the first processor, Stripe’s IDs were not prefixed. Its item IDs have documented prefixes (`il_`, `pi_`)
// that will not collide with `SubscriptionProcessor` names
key = s(processorItemId);
} else {
key = s(processor.name() + "_" + processorItemId);
}
UpdateItemRequest updateItemRequest = UpdateItemRequest.builder()
.tableName(table)
.key(Map.of(KEY_STRIPE_ID, s(stripeId)))
.key(Map.of(KEY_PROCESSOR_ITEM_ID, key))
.conditionExpression("attribute_not_exists(#key) OR #tag = :tag")
.returnValues(ReturnValue.NONE)
.updateExpression("SET "
+ "#tag = if_not_exists(#tag, :tag), "
+ "#exp = if_not_exists(#exp, :exp)")
.expressionAttributeNames(Map.of(
"#key", KEY_STRIPE_ID,
"#key", KEY_PROCESSOR_ITEM_ID,
"#tag", KEY_ISSUED_RECEIPT_TAG,
"#exp", KEY_EXPIRATION))
.expressionAttributeValues(Map.of(
@@ -52,6 +52,7 @@ import org.whispersystems.textsecuregcm.util.Pair;
import org.whispersystems.textsecuregcm.util.RedisClusterUtil;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Scheduler;
import reactor.core.scheduler.Schedulers;
public class MessagesCache extends RedisClusterPubSubAdapter<String, String> implements Managed {
@@ -62,6 +63,8 @@ public class MessagesCache extends RedisClusterPubSubAdapter<String, String> imp
private final ExecutorService notificationExecutorService;
private final ExecutorService messageDeletionExecutorService;
// messageDeletionExecutorService wrapped into a reactor Scheduler
private final Scheduler messageDeletionScheduler;
private final ClusterLuaScript insertScript;
private final ClusterLuaScript removeByGuidScript;
@@ -108,6 +111,7 @@ public class MessagesCache extends RedisClusterPubSubAdapter<String, String> imp
this.notificationExecutorService = notificationExecutorService;
this.messageDeletionExecutorService = messageDeletionExecutorService;
this.messageDeletionScheduler = Schedulers.fromExecutorService(messageDeletionExecutorService, "messageDeletion");
this.insertScript = ClusterLuaScript.fromResource(insertCluster, "lua/insert_item.lua", ScriptOutputType.INTEGER);
this.removeByGuidScript = ClusterLuaScript.fromResource(readDeleteCluster, "lua/remove_item_by_guid.lua",
@@ -236,7 +240,7 @@ public class MessagesCache extends RedisClusterPubSubAdapter<String, String> imp
staleEphemeralMessages
.map(e -> UUID.fromString(e.getServerGuid()))
.buffer(PAGE_SIZE)
.subscribeOn(Schedulers.boundedElastic())
.subscribeOn(messageDeletionScheduler)
.subscribe(staleEphemeralMessageGuids ->
remove(destinationUuid, destinationDevice, staleEphemeralMessageGuids)
.thenAccept(removedMessages -> staleEphemeralMessagesCounter.increment(removedMessages.size())),
@@ -6,5 +6,6 @@
package org.whispersystems.textsecuregcm.storage;
public interface PubSubAddress {
public String serialize();
String serialize();
}
@@ -24,7 +24,11 @@ public class ReportMessageDynamoDb {
private final Duration ttl;
private static final String REMOVED_MESSAGE_COUNTER_NAME = name(ReportMessageDynamoDb.class, "removed");
private static final Timer REMOVED_MESSAGE_AGE_TIMER = Metrics.timer(name(ReportMessageDynamoDb.class, "removedMessageAge"));
private static final Timer REMOVED_MESSAGE_AGE_TIMER = Timer
.builder(name(ReportMessageDynamoDb.class, "removedMessageAge"))
.publishPercentiles(0.5, 0.75, 0.95, 0.99)
.distributionStatisticExpiry(Duration.ofDays(1))
.register(Metrics.globalRegistry);
public ReportMessageDynamoDb(final DynamoDbClient dynamoDB, final String tableName, final Duration ttl) {
this.db = dynamoDB;
@@ -6,7 +6,6 @@
package org.whispersystems.textsecuregcm.storage;
import static org.whispersystems.textsecuregcm.util.AttributeValues.b;
import static org.whispersystems.textsecuregcm.util.AttributeValues.m;
import static org.whispersystems.textsecuregcm.util.AttributeValues.n;
import static org.whispersystems.textsecuregcm.util.AttributeValues.s;
@@ -15,8 +14,6 @@ import com.google.common.base.Throwables;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.Instant;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
@@ -24,6 +21,8 @@ import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.ws.rs.ClientErrorException;
import javax.ws.rs.core.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.subscriptions.ProcessorCustomer;
@@ -46,11 +45,8 @@ public class SubscriptionManager {
public static final String KEY_USER = "U"; // B (Hash Key)
public static final String KEY_PASSWORD = "P"; // B
@Deprecated
public static final String KEY_CUSTOMER_ID = "C"; // S (GSI Hash Key of `c_to_u` index)
public static final String KEY_PROCESSOR_ID_CUSTOMER_ID = "PC"; // B (GSI Hash Key of `pc_to_u` index)
public static final String KEY_CREATED_AT = "R"; // N
public static final String KEY_PROCESSOR_CUSTOMER_IDS_MAP = "PCI"; // M
public static final String KEY_SUBSCRIPTION_ID = "S"; // S
public static final String KEY_SUBSCRIPTION_CREATED_AT = "T"; // N
public static final String KEY_SUBSCRIPTION_LEVEL = "L";
@@ -59,7 +55,7 @@ public class SubscriptionManager {
public static final String KEY_CANCELED_AT = "B"; // N
public static final String KEY_CURRENT_PERIOD_ENDS_AT = "D"; // N
public static final String INDEX_NAME = "c_to_u"; // Hash Key "C"
public static final String INDEX_NAME = "pc_to_u"; // Hash Key "PC"
public static class Record {
@@ -69,7 +65,7 @@ public class SubscriptionManager {
@VisibleForTesting
@Nullable
ProcessorCustomer processorCustomer;
public Map<SubscriptionProcessor, String> processorsToCustomerIds;
@Nullable
public String subscriptionId;
public Instant subscriptionCreatedAt;
public Long subscriptionLevel;
@@ -94,7 +90,6 @@ public class SubscriptionManager {
if (processorCustomerId != null) {
record.processorCustomer = new ProcessorCustomer(processorCustomerId.second(), processorCustomerId.first());
}
record.processorsToCustomerIds = getProcessorsToCustomerIds(item);
record.subscriptionId = getString(item, KEY_SUBSCRIPTION_ID);
record.subscriptionCreatedAt = getInstant(item, KEY_SUBSCRIPTION_CREATED_AT);
record.subscriptionLevel = getLong(item, KEY_SUBSCRIPTION_LEVEL);
@@ -109,18 +104,6 @@ public class SubscriptionManager {
return Optional.ofNullable(processorCustomer);
}
private static Map<SubscriptionProcessor, String> getProcessorsToCustomerIds(Map<String, AttributeValue> item) {
final AttributeValue attributeValue = item.get(KEY_PROCESSOR_CUSTOMER_IDS_MAP);
final Map<String, AttributeValue> attribute =
attributeValue == null ? Collections.emptyMap() : attributeValue.m();
final Map<SubscriptionProcessor, String> processorsToCustomerIds = new HashMap<>();
attribute.forEach((processorName, customerId) ->
processorsToCustomerIds.put(SubscriptionProcessor.valueOf(processorName), customerId.s()));
return processorsToCustomerIds;
}
/**
* Extracts the active processor and customer from a single attribute value in the given item.
* <p>
@@ -188,26 +171,27 @@ public class SubscriptionManager {
/**
* Looks in the GSI for a record with the given customer id and returns the user id.
*/
public CompletableFuture<byte[]> getSubscriberUserByStripeCustomerId(@Nonnull String customerId) {
public CompletableFuture<byte[]> getSubscriberUserByProcessorCustomer(ProcessorCustomer processorCustomer) {
QueryRequest query = QueryRequest.builder()
.tableName(table)
.indexName(INDEX_NAME)
.keyConditionExpression("#customer_id = :customer_id")
.keyConditionExpression("#processor_customer_id = :processor_customer_id")
.projectionExpression("#user")
.expressionAttributeNames(Map.of(
"#customer_id", KEY_CUSTOMER_ID,
"#processor_customer_id", KEY_PROCESSOR_ID_CUSTOMER_ID,
"#user", KEY_USER))
.expressionAttributeValues(Map.of(
":customer_id", s(Objects.requireNonNull(customerId))))
":processor_customer_id", b(processorCustomer.toDynamoBytes())))
.build();
return client.query(query).thenApply(queryResponse -> {
int count = queryResponse.count();
if (count == 0) {
return null;
} else if (count > 1) {
logger.error("expected invariant of 1-1 subscriber-customer violated for customer {}", customerId);
logger.error("expected invariant of 1-1 subscriber-customer violated for customer {} ({})",
processorCustomer.customerId(), processorCustomer.processor());
throw new IllegalStateException(
"expected invariant of 1-1 subscriber-customer violated for customer " + customerId);
"expected invariant of 1-1 subscriber-customer violated for customer " + processorCustomer);
} else {
Map<String, AttributeValue> result = queryResponse.items().get(0);
return result.get(KEY_USER).b().asByteArray();
@@ -279,21 +263,18 @@ public class SubscriptionManager {
.updateExpression("SET "
+ "#password = if_not_exists(#password, :password), "
+ "#created_at = if_not_exists(#created_at, :created_at), "
+ "#accessed_at = if_not_exists(#accessed_at, :accessed_at), "
+ "#processors_to_customer_ids = if_not_exists(#processors_to_customer_ids, :initial_empty_map)"
+ "#accessed_at = if_not_exists(#accessed_at, :accessed_at)"
)
.expressionAttributeNames(Map.of(
"#user", KEY_USER,
"#password", KEY_PASSWORD,
"#created_at", KEY_CREATED_AT,
"#accessed_at", KEY_ACCESSED_AT,
"#processors_to_customer_ids", KEY_PROCESSOR_CUSTOMER_IDS_MAP)
"#accessed_at", KEY_ACCESSED_AT)
)
.expressionAttributeValues(Map.of(
":password", b(password),
":created_at", n(createdAt.getEpochSecond()),
":accessed_at", n(createdAt.getEpochSecond()),
":initial_empty_map", m(Map.of()))
":accessed_at", n(createdAt.getEpochSecond()))
)
.build();
return client.updateItem(request).handle((updateItemResponse, throwable) -> {
@@ -310,39 +291,28 @@ public class SubscriptionManager {
}
/**
* Updates the active processor and customer ID for the given user record.
* Sets the processor and customer ID for the given user record.
*
* @return the updated user record.
* @return the user record.
*/
public CompletableFuture<Record> updateProcessorAndCustomerId(Record userRecord,
public CompletableFuture<Record> setProcessorAndCustomerId(Record userRecord,
ProcessorCustomer activeProcessorCustomer, Instant updatedAt) {
UpdateItemRequest request = UpdateItemRequest.builder()
.tableName(table)
.key(Map.of(KEY_USER, b(userRecord.user)))
.returnValues(ReturnValue.ALL_NEW)
.conditionExpression(
// there is no active processor+customer attribute
"attribute_not_exists(#processor_customer_id) " +
// or an attribute in the map with an inactive processor+customer
"AND attribute_not_exists(#processors_to_customer_ids.#processor_name)"
)
.conditionExpression("attribute_not_exists(#processor_customer_id)")
.updateExpression("SET "
+ "#customer_id = :customer_id, "
+ "#processor_customer_id = :processor_customer_id, "
+ "#processors_to_customer_ids.#processor_name = :customer_id, "
+ "#accessed_at = :accessed_at"
)
.expressionAttributeNames(Map.of(
"#accessed_at", KEY_ACCESSED_AT,
"#customer_id", KEY_CUSTOMER_ID,
"#processor_customer_id", KEY_PROCESSOR_ID_CUSTOMER_ID,
"#processor_name", activeProcessorCustomer.processor().name(),
"#processors_to_customer_ids", KEY_PROCESSOR_CUSTOMER_IDS_MAP
"#processor_customer_id", KEY_PROCESSOR_ID_CUSTOMER_ID
))
.expressionAttributeValues(Map.of(
":accessed_at", n(updatedAt.getEpochSecond()),
":customer_id", s(activeProcessorCustomer.customerId()),
":processor_customer_id", b(activeProcessorCustomer.toDynamoBytes())
)).build();
@@ -350,8 +320,7 @@ public class SubscriptionManager {
.thenApply(updateItemResponse -> Record.from(userRecord.user, updateItemResponse.attributes()))
.exceptionallyCompose(throwable -> {
if (Throwables.getRootCause(throwable) instanceof ConditionalCheckFailedException) {
return getUser(userRecord.user).thenApply(getItemResponse ->
Record.from(userRecord.user, getItemResponse.item()));
throw new ClientErrorException(Response.Status.CONFLICT);
}
Throwables.throwIfUnchecked(throwable);
throw new CompletionException(throwable);
@@ -425,7 +394,7 @@ public class SubscriptionManager {
}
public CompletableFuture<Void> subscriptionLevelChanged(
byte[] user, Instant subscriptionLevelChangedAt, long level) {
byte[] user, Instant subscriptionLevelChangedAt, long level, String subscriptionId) {
checkUserLength(user);
UpdateItemRequest request = UpdateItemRequest.builder()
@@ -434,14 +403,17 @@ public class SubscriptionManager {
.returnValues(ReturnValue.NONE)
.updateExpression("SET "
+ "#accessed_at = :accessed_at, "
+ "#subscription_id = :subscription_id, "
+ "#subscription_level = :subscription_level, "
+ "#subscription_level_changed_at = :subscription_level_changed_at")
.expressionAttributeNames(Map.of(
"#accessed_at", KEY_ACCESSED_AT,
"#subscription_id", KEY_SUBSCRIPTION_ID,
"#subscription_level", KEY_SUBSCRIPTION_LEVEL,
"#subscription_level_changed_at", KEY_SUBSCRIPTION_LEVEL_CHANGED_AT))
.expressionAttributeValues(Map.of(
":accessed_at", n(subscriptionLevelChangedAt.getEpochSecond()),
":subscription_id", s(subscriptionId),
":subscription_level", n(level),
":subscription_level_changed_at", n(subscriptionLevelChangedAt.getEpochSecond())))
.build();
@@ -0,0 +1,331 @@
/*
* Copyright 2022 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.subscriptions;
import com.apollographql.apollo3.api.ApolloResponse;
import com.apollographql.apollo3.api.Operation;
import com.apollographql.apollo3.api.Operations;
import com.apollographql.apollo3.api.Optional;
import com.apollographql.apollo3.api.json.BufferedSinkJsonWriter;
import com.braintree.graphql.client.type.ChargePaymentMethodInput;
import com.braintree.graphql.client.type.CreatePayPalBillingAgreementInput;
import com.braintree.graphql.client.type.CreatePayPalOneTimePaymentInput;
import com.braintree.graphql.client.type.CustomFieldInput;
import com.braintree.graphql.client.type.MonetaryAmountInput;
import com.braintree.graphql.client.type.PayPalBillingAgreementChargePattern;
import com.braintree.graphql.client.type.PayPalBillingAgreementExperienceProfileInput;
import com.braintree.graphql.client.type.PayPalBillingAgreementInput;
import com.braintree.graphql.client.type.PayPalExperienceProfileInput;
import com.braintree.graphql.client.type.PayPalIntent;
import com.braintree.graphql.client.type.PayPalLandingPageType;
import com.braintree.graphql.client.type.PayPalOneTimePaymentInput;
import com.braintree.graphql.client.type.PayPalProductAttributesInput;
import com.braintree.graphql.client.type.PayPalUserAction;
import com.braintree.graphql.client.type.TokenizePayPalBillingAgreementInput;
import com.braintree.graphql.client.type.TokenizePayPalOneTimePaymentInput;
import com.braintree.graphql.client.type.TransactionInput;
import com.braintree.graphql.client.type.VaultPaymentMethodInput;
import com.braintree.graphql.clientoperation.ChargePayPalOneTimePaymentMutation;
import com.braintree.graphql.clientoperation.CreatePayPalBillingAgreementMutation;
import com.braintree.graphql.clientoperation.CreatePayPalOneTimePaymentMutation;
import com.braintree.graphql.clientoperation.TokenizePayPalBillingAgreementMutation;
import com.braintree.graphql.clientoperation.TokenizePayPalOneTimePaymentMutation;
import com.braintree.graphql.clientoperation.VaultPaymentMethodMutation;
import java.math.BigDecimal;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Base64;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import javax.ws.rs.ServiceUnavailableException;
import okio.Buffer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.http.FaultTolerantHttpClient;
class BraintreeGraphqlClient {
// required header value, recommended to be the date the integration began
// https://graphql.braintreepayments.com/guides/making_api_calls/#the-braintree-version-header
private static final String BRAINTREE_VERSION = "2022-10-01";
private static final Logger logger = LoggerFactory.getLogger(BraintreeGraphqlClient.class);
private final FaultTolerantHttpClient httpClient;
private final URI graphqlUri;
private final String authorizationHeader;
BraintreeGraphqlClient(final FaultTolerantHttpClient httpClient,
final String graphqlUri,
final String publicKey,
final String privateKey) {
this.httpClient = httpClient;
try {
this.graphqlUri = new URI(graphqlUri);
} catch (URISyntaxException e) {
throw new IllegalArgumentException("Invalid URI", e);
}
// “public”/“private” key is a bit of a misnomer, but we follow the upstream nomenclature
// they are used for Basic auth similar to “client key”/“client secret” credentials
this.authorizationHeader = "Basic " + Base64.getEncoder().encodeToString((publicKey + ":" + privateKey).getBytes());
}
CompletableFuture<CreatePayPalOneTimePaymentMutation.CreatePayPalOneTimePayment> createPayPalOneTimePayment(
final BigDecimal amount, final String currency, final String returnUrl,
final String cancelUrl, final String locale) {
final CreatePayPalOneTimePaymentInput input = buildCreatePayPalOneTimePaymentInput(amount, currency, returnUrl,
cancelUrl, locale);
final CreatePayPalOneTimePaymentMutation mutation = new CreatePayPalOneTimePaymentMutation(input);
final HttpRequest request = buildRequest(mutation);
return httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(httpResponse ->
{
// IntelliJ users: type parameters error “no instance of type variable exists so that Data conforms to Data”
// is not accurate; this might be fixed in Kotlin 1.8: https://youtrack.jetbrains.com/issue/KTIJ-21905/
final CreatePayPalOneTimePaymentMutation.Data data = assertSuccessAndExtractData(httpResponse, mutation);
return data.createPayPalOneTimePayment;
});
}
private static CreatePayPalOneTimePaymentInput buildCreatePayPalOneTimePaymentInput(BigDecimal amount,
String currency, String returnUrl, String cancelUrl, String locale) {
return new CreatePayPalOneTimePaymentInput(
Optional.absent(),
Optional.absent(), // merchant account ID will be specified when charging
new MonetaryAmountInput(amount.toString(), currency), // this could potentially use a CustomScalarAdapter
cancelUrl,
Optional.absent(),
PayPalIntent.SALE,
Optional.absent(),
Optional.present(false), // offerPayLater,
Optional.absent(),
Optional.present(
new PayPalExperienceProfileInput(Optional.present("Signal"),
Optional.present(false),
Optional.present(PayPalLandingPageType.LOGIN),
Optional.present(locale),
Optional.absent(),
Optional.present(PayPalUserAction.COMMIT))),
Optional.absent(),
Optional.absent(),
returnUrl,
Optional.absent(),
Optional.absent()
);
}
CompletableFuture<TokenizePayPalOneTimePaymentMutation.TokenizePayPalOneTimePayment> tokenizePayPalOneTimePayment(
final String payerId, final String paymentId, final String paymentToken) {
final TokenizePayPalOneTimePaymentInput input = new TokenizePayPalOneTimePaymentInput(
Optional.absent(),
Optional.absent(), // merchant account ID will be specified when charging
new PayPalOneTimePaymentInput(payerId, paymentId, paymentToken)
);
final TokenizePayPalOneTimePaymentMutation mutation = new TokenizePayPalOneTimePaymentMutation(input);
final HttpRequest request = buildRequest(mutation);
return httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(httpResponse -> {
// IntelliJ users: type parameters error “no instance of type variable exists so that Data conforms to Data”
// is not accurate; this might be fixed in Kotlin 1.8: https://youtrack.jetbrains.com/issue/KTIJ-21905/
final TokenizePayPalOneTimePaymentMutation.Data data = assertSuccessAndExtractData(httpResponse, mutation);
return data.tokenizePayPalOneTimePayment;
});
}
CompletableFuture<ChargePayPalOneTimePaymentMutation.ChargePaymentMethod> chargeOneTimePayment(
final String paymentMethodId, final BigDecimal amount, final String merchantAccount, final long level) {
final List<CustomFieldInput> customFields = List.of(
new CustomFieldInput("level", Optional.present(Long.toString(level))));
final ChargePaymentMethodInput input = buildChargePaymentMethodInput(paymentMethodId, amount, merchantAccount,
customFields);
final ChargePayPalOneTimePaymentMutation mutation = new ChargePayPalOneTimePaymentMutation(input);
final HttpRequest request = buildRequest(mutation);
return httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(httpResponse -> {
// IntelliJ users: type parameters error “no instance of type variable exists so that Data conforms to Data”
// is not accurate; this might be fixed in Kotlin 1.8: https://youtrack.jetbrains.com/issue/KTIJ-21905/
final ChargePayPalOneTimePaymentMutation.Data data = assertSuccessAndExtractData(httpResponse,
mutation);
return data.chargePaymentMethod;
});
}
private static ChargePaymentMethodInput buildChargePaymentMethodInput(String paymentMethodId, BigDecimal amount,
String merchantAccount, List<CustomFieldInput> customFields) {
return new ChargePaymentMethodInput(
Optional.absent(),
paymentMethodId,
new TransactionInput(
// documented as “amount: whole number, or exactly two or three decimal places”
amount.toString(), // this could potentially use a CustomScalarAdapter
Optional.present(merchantAccount),
Optional.absent(),
Optional.absent(),
Optional.absent(),
Optional.absent(),
Optional.present(customFields),
Optional.absent(),
Optional.absent(),
Optional.absent(),
Optional.absent(),
Optional.absent(),
Optional.absent(),
Optional.absent(),
Optional.absent(),
Optional.absent(),
Optional.absent(),
Optional.absent(),
Optional.absent()
)
);
}
public CompletableFuture<CreatePayPalBillingAgreementMutation.CreatePayPalBillingAgreement> createPayPalBillingAgreement(
final String returnUrl, final String cancelUrl, final String locale) {
final CreatePayPalBillingAgreementInput input = buildCreatePayPalBillingAgreementInput(returnUrl, cancelUrl,
locale);
final CreatePayPalBillingAgreementMutation mutation = new CreatePayPalBillingAgreementMutation(input);
final HttpRequest request = buildRequest(mutation);
return httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(httpResponse -> {
// IntelliJ users: type parameters error “no instance of type variable exists so that Data conforms to Data”
// is not accurate; this might be fixed in Kotlin 1.8: https://youtrack.jetbrains.com/issue/KTIJ-21905/
final CreatePayPalBillingAgreementMutation.Data data = assertSuccessAndExtractData(httpResponse, mutation);
return data.createPayPalBillingAgreement;
});
}
private static CreatePayPalBillingAgreementInput buildCreatePayPalBillingAgreementInput(String returnUrl,
String cancelUrl, String locale) {
return new CreatePayPalBillingAgreementInput(
Optional.absent(),
Optional.absent(),
returnUrl,
cancelUrl,
Optional.absent(),
Optional.absent(),
Optional.present(false), // offerPayPalCredit
Optional.absent(),
Optional.present(
new PayPalBillingAgreementExperienceProfileInput(Optional.present("Signal"),
Optional.present(false), // collectShippingAddress
Optional.present(PayPalLandingPageType.LOGIN),
Optional.present(locale),
Optional.absent())),
Optional.absent(),
Optional.present(new PayPalProductAttributesInput(
Optional.present(PayPalBillingAgreementChargePattern.RECURRING_PREPAID)
))
);
}
public CompletableFuture<TokenizePayPalBillingAgreementMutation.TokenizePayPalBillingAgreement> tokenizePayPalBillingAgreement(
final String billingAgreementToken) {
final TokenizePayPalBillingAgreementInput input = new TokenizePayPalBillingAgreementInput(
Optional.absent(),
new PayPalBillingAgreementInput(billingAgreementToken));
final TokenizePayPalBillingAgreementMutation mutation = new TokenizePayPalBillingAgreementMutation(input);
final HttpRequest request = buildRequest(mutation);
return httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(httpResponse -> {
// IntelliJ users: type parameters error “no instance of type variable exists so that Data conforms to Data”
// is not accurate; this might be fixed in Kotlin 1.8: https://youtrack.jetbrains.com/issue/KTIJ-21905/
final TokenizePayPalBillingAgreementMutation.Data data = assertSuccessAndExtractData(httpResponse, mutation);
return data.tokenizePayPalBillingAgreement;
});
}
public CompletableFuture<VaultPaymentMethodMutation.VaultPaymentMethod> vaultPaymentMethod(final String customerId,
final String paymentMethodId) {
final VaultPaymentMethodInput input = buildVaultPaymentMethodInput(customerId, paymentMethodId);
final VaultPaymentMethodMutation mutation = new VaultPaymentMethodMutation(input);
final HttpRequest request = buildRequest(mutation);
return httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(httpResponse -> {
// IntelliJ users: type parameters error “no instance of type variable exists so that Data conforms to Data”
// is not accurate; this might be fixed in Kotlin 1.8: https://youtrack.jetbrains.com/issue/KTIJ-21905/
final VaultPaymentMethodMutation.Data data = assertSuccessAndExtractData(httpResponse, mutation);
return data.vaultPaymentMethod;
});
}
private static VaultPaymentMethodInput buildVaultPaymentMethodInput(String customerId, String paymentMethodId) {
return new VaultPaymentMethodInput(
Optional.absent(),
paymentMethodId,
Optional.absent(),
Optional.absent(),
Optional.present(customerId),
Optional.absent(),
Optional.absent()
);
}
/**
* Verifies that the HTTP response has a {@code 200} status code and the GraphQL response has no errors, otherwise
* throws a {@link ServiceUnavailableException}.
*/
private <T extends Operation<U>, U extends Operation.Data> U assertSuccessAndExtractData(
HttpResponse<String> httpResponse, T operation) {
if (httpResponse.statusCode() != 200) {
logger.warn("Received HTTP response status {} ({})", httpResponse.statusCode(),
httpResponse.headers().firstValue("paypal-debug-id").orElse("<debug id absent>"));
throw new ServiceUnavailableException();
}
ApolloResponse<U> response = Operations.parseJsonResponse(operation, httpResponse.body());
if (response.hasErrors() || response.data == null) {
//noinspection ConstantConditions
response.errors.forEach(
error -> {
final Object legacyCode = java.util.Optional.ofNullable(error.getExtensions())
.map(extensions -> extensions.get("legacyCode"))
.orElse("<none>");
logger.warn("Received GraphQL error for {}: \"{}\" (legacyCode: {})",
response.operation.name(), error.getMessage(), legacyCode);
});
throw new ServiceUnavailableException();
}
return response.data;
}
private HttpRequest buildRequest(final Operation<?> operation) {
final Buffer buffer = new Buffer();
Operations.composeJsonRequest(operation, new BufferedSinkJsonWriter(buffer));
return HttpRequest.newBuilder()
.uri(graphqlUri)
.method("POST", HttpRequest.BodyPublishers.ofString(buffer.readUtf8()))
.header("Content-Type", "application/json")
.header("Authorization", authorizationHeader)
.header("Braintree-Version", BRAINTREE_VERSION)
.build();
}
}
@@ -0,0 +1,518 @@
/*
* Copyright 2022 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.subscriptions;
import com.braintreegateway.BraintreeGateway;
import com.braintreegateway.ClientTokenRequest;
import com.braintreegateway.Customer;
import com.braintreegateway.CustomerRequest;
import com.braintreegateway.Plan;
import com.braintreegateway.ResourceCollection;
import com.braintreegateway.Result;
import com.braintreegateway.Subscription;
import com.braintreegateway.SubscriptionRequest;
import com.braintreegateway.Transaction;
import com.braintreegateway.TransactionSearchRequest;
import com.braintreegateway.exceptions.BraintreeException;
import com.braintreegateway.exceptions.NotFoundException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.math.BigDecimal;
import java.time.Instant;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.Executor;
import javax.annotation.Nullable;
import javax.ws.rs.ClientErrorException;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import org.apache.commons.codec.binary.Hex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.configuration.CircuitBreakerConfiguration;
import org.whispersystems.textsecuregcm.http.FaultTolerantHttpClient;
public class BraintreeManager implements SubscriptionProcessorManager {
private static final Logger logger = LoggerFactory.getLogger(BraintreeManager.class);
private static final String PAYPAL_PAYMENT_ALREADY_COMPLETED_PROCESSOR_CODE = "2094";
private final BraintreeGateway braintreeGateway;
private final BraintreeGraphqlClient braintreeGraphqlClient;
private final Executor executor;
private final Set<String> supportedCurrencies;
private final Map<String, String> currenciesToMerchantAccounts;
public BraintreeManager(final String braintreeMerchantId, final String braintreePublicKey,
final String braintreePrivateKey,
final String braintreeEnvironment,
final Set<String> supportedCurrencies,
final Map<String, String> currenciesToMerchantAccounts,
final String graphqlUri,
final CircuitBreakerConfiguration circuitBreakerConfiguration,
final Executor executor) {
this.braintreeGateway = new BraintreeGateway(braintreeEnvironment, braintreeMerchantId, braintreePublicKey,
braintreePrivateKey);
this.supportedCurrencies = supportedCurrencies;
this.currenciesToMerchantAccounts = currenciesToMerchantAccounts;
final FaultTolerantHttpClient httpClient = FaultTolerantHttpClient.newBuilder()
.withName("braintree-graphql")
.withCircuitBreaker(circuitBreakerConfiguration)
.withExecutor(executor)
.build();
this.braintreeGraphqlClient = new BraintreeGraphqlClient(httpClient, graphqlUri, braintreePublicKey,
braintreePrivateKey);
this.executor = executor;
}
@Override
public Set<String> getSupportedCurrencies() {
return supportedCurrencies;
}
@Override
public SubscriptionProcessor getProcessor() {
return SubscriptionProcessor.BRAINTREE;
}
@Override
public boolean supportsPaymentMethod(final PaymentMethod paymentMethod) {
return paymentMethod == PaymentMethod.PAYPAL;
}
@Override
public boolean supportsCurrency(final String currency) {
return supportedCurrencies.contains(currency.toLowerCase(Locale.ROOT));
}
@Override
public CompletableFuture<PaymentDetails> getPaymentDetails(final String paymentId) {
return CompletableFuture.supplyAsync(() -> {
try {
final Transaction transaction = braintreeGateway.transaction().find(paymentId);
return new PaymentDetails(transaction.getGraphQLId(),
transaction.getCustomFields(),
getPaymentStatus(transaction.getStatus()),
transaction.getCreatedAt().toInstant());
} catch (final NotFoundException e) {
return null;
}
}, executor);
}
public CompletableFuture<PayPalOneTimePaymentApprovalDetails> createOneTimePayment(String currency, long amount,
String locale, String returnUrl, String cancelUrl) {
return braintreeGraphqlClient.createPayPalOneTimePayment(convertApiAmountToBraintreeAmount(currency, amount),
currency.toUpperCase(Locale.ROOT), returnUrl,
cancelUrl, locale)
.thenApply(result -> new PayPalOneTimePaymentApprovalDetails((String) result.approvalUrl, result.paymentId));
}
public CompletableFuture<PayPalChargeSuccessDetails> captureOneTimePayment(String payerId, String paymentId,
String paymentToken, String currency, long amount, long level) {
return braintreeGraphqlClient.tokenizePayPalOneTimePayment(payerId, paymentId, paymentToken)
.thenCompose(response -> braintreeGraphqlClient.chargeOneTimePayment(
response.paymentMethod.id,
convertApiAmountToBraintreeAmount(currency, amount),
currenciesToMerchantAccounts.get(currency.toLowerCase(Locale.ROOT)),
level)
.thenComposeAsync(chargeResponse -> {
final PaymentStatus paymentStatus = getPaymentStatus(chargeResponse.transaction.status);
if (paymentStatus == PaymentStatus.SUCCEEDED || paymentStatus == PaymentStatus.PROCESSING) {
return CompletableFuture.completedFuture(new PayPalChargeSuccessDetails(chargeResponse.transaction.id));
}
// the GraphQL/Apollo interfaces are a tad unwieldy for this type of status checking
final Transaction unsuccessfulTx = braintreeGateway.transaction().find(chargeResponse.transaction.id);
if (PAYPAL_PAYMENT_ALREADY_COMPLETED_PROCESSOR_CODE.equals(unsuccessfulTx.getProcessorResponseCode())
|| Transaction.GatewayRejectionReason.DUPLICATE.equals(
unsuccessfulTx.getGatewayRejectionReason())) {
// the payment has already been charged - maybe a previous call timed out or was interrupted -
// in any case, check for a successful transaction with the paymentId
final ResourceCollection<Transaction> search = braintreeGateway.transaction()
.search(new TransactionSearchRequest()
.paypalPaymentId().is(paymentId)
.status().in(
Transaction.Status.SETTLED,
Transaction.Status.SETTLING,
Transaction.Status.SUBMITTED_FOR_SETTLEMENT,
Transaction.Status.SETTLEMENT_PENDING
)
);
if (search.getMaximumSize() == 0) {
return CompletableFuture.failedFuture(
new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR));
}
final Transaction successfulTx = search.getFirst();
return CompletableFuture.completedFuture(
new PayPalChargeSuccessDetails(successfulTx.getGraphQLId()));
}
logger.info("PayPal charge unexpectedly failed: {}", unsuccessfulTx.getProcessorResponseCode());
return CompletableFuture.failedFuture(
new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR));
}, executor));
}
private static PaymentStatus getPaymentStatus(Transaction.Status status) {
return switch (status) {
case SETTLEMENT_CONFIRMED, SETTLING, SUBMITTED_FOR_SETTLEMENT, SETTLED -> PaymentStatus.SUCCEEDED;
case AUTHORIZATION_EXPIRED, GATEWAY_REJECTED, PROCESSOR_DECLINED, SETTLEMENT_DECLINED, VOIDED, FAILED ->
PaymentStatus.FAILED;
default -> PaymentStatus.UNKNOWN;
};
}
private static PaymentStatus getPaymentStatus(com.braintree.graphql.client.type.PaymentStatus status) {
try {
Transaction.Status transactionStatus = Transaction.Status.valueOf(status.rawValue);
return getPaymentStatus(transactionStatus);
} catch (final Exception e) {
return PaymentStatus.UNKNOWN;
}
}
private static SubscriptionStatus getSubscriptionStatus(final Subscription.Status status) {
return switch (status) {
case ACTIVE -> SubscriptionStatus.ACTIVE;
case CANCELED, EXPIRED -> SubscriptionStatus.CANCELED;
case PAST_DUE -> SubscriptionStatus.PAST_DUE;
case PENDING -> SubscriptionStatus.INCOMPLETE;
case UNRECOGNIZED -> {
logger.error("Subscription has unrecognized status; library may need to be updated: {}", status);
yield SubscriptionStatus.UNKNOWN;
}
};
}
private BigDecimal convertApiAmountToBraintreeAmount(final String currency, final long amount) {
return switch (currency.toLowerCase(Locale.ROOT)) {
// JPY is the only supported zero-decimal currency
case "jpy" -> BigDecimal.valueOf(amount);
default -> BigDecimal.valueOf(amount).scaleByPowerOfTen(-2);
};
}
public record PayPalOneTimePaymentApprovalDetails(String approvalUrl, String paymentId) {
}
public record PayPalChargeSuccessDetails(String paymentId) {
}
private void assertResultSuccess(Result<?> result) throws CompletionException {
if (!result.isSuccess()) {
throw new CompletionException(new BraintreeException(result.getMessage()));
}
}
@Override
public CompletableFuture<ProcessorCustomer> createCustomer(final byte[] subscriberUser) {
return CompletableFuture.supplyAsync(() -> {
final CustomerRequest request = new CustomerRequest()
.customField("subscriber_user", Hex.encodeHexString(subscriberUser));
try {
return braintreeGateway.customer().create(request);
} catch (BraintreeException e) {
throw new CompletionException(e);
}
}, executor)
.thenApply(result -> {
assertResultSuccess(result);
return new ProcessorCustomer(result.getTarget().getId(), SubscriptionProcessor.BRAINTREE);
});
}
@Override
public CompletableFuture<String> createPaymentMethodSetupToken(final String customerId) {
return CompletableFuture.supplyAsync(() -> {
ClientTokenRequest request = new ClientTokenRequest()
.customerId(customerId);
return braintreeGateway.clientToken().generate(request);
}, executor);
}
@Override
public CompletableFuture<Void> setDefaultPaymentMethodForCustomer(String customerId, String billingAgreementToken,
@Nullable String currentSubscriptionId) {
final Optional<String> maybeSubscriptionId = Optional.ofNullable(currentSubscriptionId);
return braintreeGraphqlClient.tokenizePayPalBillingAgreement(billingAgreementToken)
.thenCompose(tokenizePayPalBillingAgreement ->
braintreeGraphqlClient.vaultPaymentMethod(customerId, tokenizePayPalBillingAgreement.paymentMethod.id))
.thenApplyAsync(vaultPaymentMethod -> braintreeGateway.customer()
.update(customerId, new CustomerRequest()
.defaultPaymentMethodToken(vaultPaymentMethod.paymentMethod.id)),
executor)
.thenAcceptAsync(result -> {
maybeSubscriptionId.ifPresent(
subscriptionId -> braintreeGateway.subscription()
.update(subscriptionId, new SubscriptionRequest()
.paymentMethodToken(result.getTarget().getDefaultPaymentMethod().getToken())));
}, executor);
}
@Override
public CompletableFuture<Object> getSubscription(String subscriptionId) {
return CompletableFuture.supplyAsync(() -> braintreeGateway.subscription().find(subscriptionId), executor);
}
@Override
public CompletableFuture<SubscriptionId> createSubscription(String customerId, String planId, long level,
long lastSubscriptionCreatedAt) {
return getDefaultPaymentMethod(customerId)
.thenCompose(paymentMethod -> {
if (paymentMethod == null) {
throw new ClientErrorException(Response.Status.CONFLICT);
}
final Optional<Subscription> maybeExistingSubscription = paymentMethod.getSubscriptions().stream()
.filter(sub -> sub.getStatus().equals(Subscription.Status.ACTIVE))
.filter(Subscription::neverExpires)
.findAny();
return maybeExistingSubscription.map(subscription -> findPlan(subscription.getPlanId())
.thenApply(plan -> {
if (getLevelForPlan(plan) != level) {
// if this happens, the likely cause is retrying an apparently failed request (likely some sort of timeout or network interruption)
// with a different level.
// In this case, it’s safer and easier to recover by returning this subscription, rather than
// returning an error
logger.warn("existing subscription had unexpected level");
}
return subscription;
}))
.orElseGet(() -> findPlan(planId).thenApplyAsync(plan -> {
final Result<Subscription> result = braintreeGateway.subscription().create(new SubscriptionRequest()
.planId(planId)
.paymentMethodToken(paymentMethod.getToken())
.merchantAccountId(
currenciesToMerchantAccounts.get(plan.getCurrencyIsoCode().toLowerCase(Locale.ROOT)))
.options()
.startImmediately(true)
.done()
);
assertResultSuccess(result);
return result.getTarget();
}));
}).thenApply(subscription -> new SubscriptionId(subscription.getId()));
}
private CompletableFuture<com.braintreegateway.PaymentMethod> getDefaultPaymentMethod(String customerId) {
return CompletableFuture.supplyAsync(() -> braintreeGateway.customer().find(customerId).getDefaultPaymentMethod(),
executor);
}
@Override
public CompletableFuture<SubscriptionId> updateSubscription(Object subscriptionObj, String planId, long level,
String idempotencyKey) {
if (!(subscriptionObj instanceof final Subscription subscription)) {
throw new IllegalArgumentException("invalid subscription object: " + subscriptionObj.getClass().getName());
}
// since badge redemption is untrackable by design and unrevokable, subscription changes must be immediate and
// and not prorated. Braintree subscriptions cannot change their next billing date,
// so we must end the existing one and create a new one
return cancelSubscriptionAtEndOfCurrentPeriod(subscription)
.thenCompose(ignored -> {
final Transaction transaction = getLatestTransactionForSubscription(subscription).orElseThrow(
() -> new ClientErrorException(
Response.Status.CONFLICT));
final Customer customer = transaction.getCustomer();
return createSubscription(customer.getId(), planId, level,
subscription.getCreatedAt().toInstant().getEpochSecond());
});
}
@Override
public CompletableFuture<Long> getLevelForSubscription(Object subscriptionObj) {
final Subscription subscription = getSubscription(subscriptionObj);
return findPlan(subscription.getPlanId())
.thenApply(this::getLevelForPlan);
}
private CompletableFuture<Plan> findPlan(String planId) {
return CompletableFuture.supplyAsync(() -> braintreeGateway.plan().find(planId), executor);
}
private long getLevelForPlan(final Plan plan) {
final BraintreePlanMetadata metadata;
try {
metadata = new ObjectMapper().readValue(plan.getDescription(), BraintreePlanMetadata.class);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
return metadata.level();
}
@Override
public CompletableFuture<SubscriptionInformation> getSubscriptionInformation(Object subscriptionObj) {
final Subscription subscription = getSubscription(subscriptionObj);
return CompletableFuture.supplyAsync(() -> {
final Plan plan = braintreeGateway.plan().find(subscription.getPlanId());
final long level = getLevelForPlan(plan);
final Instant anchor = subscription.getFirstBillingDate().toInstant();
final Instant endOfCurrentPeriod = subscription.getBillingPeriodEndDate().toInstant();
final Optional<Transaction> maybeTransaction = getLatestTransactionForSubscription(subscription);
final ChargeFailure chargeFailure = maybeTransaction.map(transaction -> {
if (getPaymentStatus(transaction.getStatus()).equals(PaymentStatus.SUCCEEDED)) {
return null;
}
final String code;
final String message;
if (transaction.getProcessorResponseCode() != null) {
code = transaction.getProcessorResponseCode();
message = transaction.getProcessorResponseText();
} else if (transaction.getGatewayRejectionReason() != null) {
code = "gateway";
message = transaction.getGatewayRejectionReason().toString();
} else {
code = "unknown";
message = "unknown";
}
return new ChargeFailure(
code,
message,
null,
null,
null);
}).orElse(null);
return new SubscriptionInformation(
new SubscriptionPrice(plan.getCurrencyIsoCode().toUpperCase(Locale.ROOT),
SubscriptionCurrencyUtil.convertBraintreeAmountToApiAmount(plan.getCurrencyIsoCode(), plan.getPrice())),
level,
anchor,
endOfCurrentPeriod,
Subscription.Status.ACTIVE == subscription.getStatus(),
!subscription.neverExpires(),
getSubscriptionStatus(subscription.getStatus()),
chargeFailure
);
}, executor);
}
@Override
public CompletableFuture<Void> cancelAllActiveSubscriptions(String customerId) {
return CompletableFuture.supplyAsync(() -> braintreeGateway.customer().find(customerId), executor).thenCompose(customer -> {
final List<CompletableFuture<Void>> subscriptionCancelFutures = customer.getDefaultPaymentMethod().getSubscriptions().stream()
.map(this::cancelSubscriptionAtEndOfCurrentPeriod)
.toList();
return CompletableFuture.allOf(subscriptionCancelFutures.toArray(new CompletableFuture[0]));
});
}
private CompletableFuture<Void> cancelSubscriptionAtEndOfCurrentPeriod(Subscription subscription) {
return CompletableFuture.supplyAsync(() -> {
braintreeGateway.subscription().update(subscription.getId(),
new SubscriptionRequest().numberOfBillingCycles(subscription.getCurrentBillingCycle()));
return null;
}, executor);
}
@Override
public CompletableFuture<ReceiptItem> getReceiptItem(String subscriptionId) {
return getLatestTransactionForSubscription(subscriptionId).thenApply(maybeTransaction -> maybeTransaction.map(transaction -> {
if (!getPaymentStatus(transaction.getStatus()).equals(PaymentStatus.SUCCEEDED)) {
throw new WebApplicationException(Response.Status.PAYMENT_REQUIRED);
}
final Instant expiration = transaction.getSubscriptionDetails().getBillingPeriodEndDate().toInstant();
final Plan plan = braintreeGateway.plan().find(transaction.getPlanId());
final BraintreePlanMetadata metadata;
try {
metadata = new ObjectMapper().readValue(plan.getDescription(), BraintreePlanMetadata.class);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
return new ReceiptItem(transaction.getId(), expiration, metadata.level());
}).orElseThrow(() -> new WebApplicationException(Response.Status.NO_CONTENT)));
}
private static Subscription getSubscription(Object subscriptionObj) {
if (!(subscriptionObj instanceof final Subscription subscription)) {
throw new IllegalArgumentException("Invalid subscription object: " + subscriptionObj.getClass().getName());
}
return subscription;
}
public CompletableFuture<Optional<Transaction>> getLatestTransactionForSubscription(String subscriptionId) {
return getSubscription(subscriptionId)
.thenApply(BraintreeManager::getSubscription)
.thenApply(this::getLatestTransactionForSubscription);
}
private Optional<Transaction> getLatestTransactionForSubscription(Subscription subscription) {
return subscription.getTransactions().stream()
.max(Comparator.comparing(Transaction::getCreatedAt));
}
public CompletableFuture<PayPalBillingAgreementApprovalDetails> createPayPalBillingAgreement(final String returnUrl,
final String cancelUrl, final String locale) {
return braintreeGraphqlClient.createPayPalBillingAgreement(returnUrl, cancelUrl, locale)
.thenApply(response ->
new PayPalBillingAgreementApprovalDetails((String) response.approvalUrl, response.billingAgreementToken)
);
}
public record PayPalBillingAgreementApprovalDetails(String approvalUrl, String billingAgreementToken) {
}
}
@@ -0,0 +1,10 @@
/*
* Copyright 2022 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.subscriptions;
public record BraintreePlanMetadata(long level) {
}
@@ -10,4 +10,8 @@ public enum PaymentMethod {
* A credit card or debit card, including those from Apple Pay and Google Pay
*/
CARD,
/**
* A PayPal account
*/
PAYPAL,
}
@@ -8,6 +8,7 @@ package org.whispersystems.textsecuregcm.subscriptions;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.stripe.exception.StripeException;
import com.stripe.model.Charge;
import com.stripe.model.Customer;
import com.stripe.model.Invoice;
import com.stripe.model.InvoiceLineItem;
@@ -33,7 +34,6 @@ import com.stripe.param.SubscriptionRetrieveParams;
import com.stripe.param.SubscriptionUpdateParams;
import com.stripe.param.SubscriptionUpdateParams.BillingCycleAnchor;
import com.stripe.param.SubscriptionUpdateParams.ProrationBehavior;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
@@ -42,6 +42,7 @@ import java.time.Instant;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
@@ -56,38 +57,30 @@ import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.ws.rs.InternalServerErrorException;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang3.StringUtils;
import org.whispersystems.textsecuregcm.util.Conversions;
public class StripeManager implements SubscriptionProcessorManager {
private static final String METADATA_KEY_LEVEL = "level";
// https://stripe.com/docs/currencies?presentment-currency=US
private static final Set<String> SUPPORTED_CURRENCIES = Set.of(
"aed", "afn", "all", "amd", "ang", "aoa", "ars", "aud", "awg", "azn", "bam", "bbd", "bdt", "bgn", "bif", "bmd",
"bnd", "bob", "brl", "bsd", "bwp", "bzd", "cad", "cdf", "chf", "clp", "cny", "cop", "crc", "cve", "czk", "djf",
"dkk", "dop", "dzd", "egp", "etb", "eur", "fjd", "fkp", "gbp", "gel", "gip", "gmd", "gnf", "gtq", "gyd", "hkd",
"hnl", "hrk", "htg", "huf", "idr", "ils", "inr", "isk", "jmd", "jpy", "kes", "kgs", "khr", "kmf", "krw", "kyd",
"kzt", "lak", "lbp", "lkr", "lrd", "lsl", "mad", "mdl", "mga", "mkd", "mmk", "mnt", "mop", "mro", "mur", "mvr",
"mwk", "mxn", "myr", "mzn", "nad", "ngn", "nio", "nok", "npr", "nzd", "pab", "pen", "pgk", "php", "pkr", "pln",
"pyg", "qar", "ron", "rsd", "rub", "rwf", "sar", "sbd", "scr", "sek", "sgd", "shp", "sll", "sos", "srd", "std",
"szl", "thb", "tjs", "top", "try", "ttd", "twd", "tzs", "uah", "ugx", "usd", "uyu", "uzs", "vnd", "vuv", "wst",
"xaf", "xcd", "xof", "xpf", "yer", "zar", "zmw");
private final String apiKey;
private final Executor executor;
private final byte[] idempotencyKeyGenerator;
private final String boostDescription;
private final Set<String> supportedCurrencies;
public StripeManager(
@Nonnull String apiKey,
@Nonnull Executor executor,
@Nonnull byte[] idempotencyKeyGenerator,
@Nonnull String boostDescription) {
@Nonnull String boostDescription,
@Nonnull Set<String> supportedCurrencies) {
this.apiKey = Objects.requireNonNull(apiKey);
if (Strings.isNullOrEmpty(apiKey)) {
throw new IllegalArgumentException("apiKey cannot be empty");
@@ -98,6 +91,7 @@ public class StripeManager implements SubscriptionProcessorManager {
throw new IllegalArgumentException("idempotencyKeyGenerator cannot be empty");
}
this.boostDescription = Objects.requireNonNull(boostDescription);
this.supportedCurrencies = supportedCurrencies;
}
@Override
@@ -110,6 +104,11 @@ public class StripeManager implements SubscriptionProcessorManager {
return paymentMethod == PaymentMethod.CARD;
}
@Override
public boolean supportsCurrency(final String currency) {
return supportedCurrencies.contains(currency);
}
private RequestOptions commonOptions() {
return commonOptions(null);
}
@@ -147,7 +146,9 @@ public class StripeManager implements SubscriptionProcessorManager {
}, executor);
}
public CompletableFuture<Customer> setDefaultPaymentMethodForCustomer(String customerId, String paymentMethodId) {
@Override
public CompletableFuture<Void> setDefaultPaymentMethodForCustomer(String customerId, String paymentMethodId,
@Nullable String currentSubscriptionId) {
return CompletableFuture.supplyAsync(() -> {
Customer customer = new Customer();
customer.setId(customerId);
@@ -157,7 +158,8 @@ public class StripeManager implements SubscriptionProcessorManager {
.build())
.build();
try {
return customer.update(params, commonOptions());
customer.update(params, commonOptions());
return null;
} catch (StripeException e) {
throw new CompletionException(e);
}
@@ -181,7 +183,7 @@ public class StripeManager implements SubscriptionProcessorManager {
@Override
public Set<String> getSupportedCurrencies() {
return SUPPORTED_CURRENCIES;
return supportedCurrencies;
}
/**
@@ -210,10 +212,15 @@ public class StripeManager implements SubscriptionProcessorManager {
}, executor);
}
public CompletableFuture<PaymentIntent> getPaymentIntent(String paymentIntentId) {
public CompletableFuture<PaymentDetails> getPaymentDetails(String paymentIntentId) {
return CompletableFuture.supplyAsync(() -> {
try {
return PaymentIntent.retrieve(paymentIntentId, commonOptions());
final PaymentIntent paymentIntent = PaymentIntent.retrieve(paymentIntentId, commonOptions());
return new PaymentDetails(paymentIntent.getId(),
paymentIntent.getMetadata() == null ? Collections.emptyMap() : paymentIntent.getMetadata(),
getPaymentStatusForStatus(paymentIntent.getStatus()),
Instant.ofEpochSecond(paymentIntent.getCreated()));
} catch (StripeException e) {
if (e.getStatusCode() == 404) {
return null;
@@ -224,64 +231,86 @@ public class StripeManager implements SubscriptionProcessorManager {
}, executor);
}
public CompletableFuture<Subscription> createSubscription(String customerId, String priceId, long level, long lastSubscriptionCreatedAt) {
return CompletableFuture.supplyAsync(() -> {
SubscriptionCreateParams params = SubscriptionCreateParams.builder()
.setCustomer(customerId)
.setOffSession(true)
.setPaymentBehavior(SubscriptionCreateParams.PaymentBehavior.ERROR_IF_INCOMPLETE)
.addItem(SubscriptionCreateParams.Item.builder()
.setPrice(priceId)
.build())
.putMetadata(METADATA_KEY_LEVEL, Long.toString(level))
.build();
try {
// the idempotency key intentionally excludes priceId
//
// If the client tells the server several times in a row before the initial creation of a subscription to
// create a subscription, we want to ensure only one gets created.
return Subscription.create(params, commonOptions(generateIdempotencyKeyForCreateSubscription(
customerId, lastSubscriptionCreatedAt)));
} catch (StripeException e) {
throw new CompletionException(e);
}
}, executor);
private static PaymentStatus getPaymentStatusForStatus(String status) {
return switch (status.toLowerCase(Locale.ROOT)) {
case "processing" -> PaymentStatus.PROCESSING;
case "succeeded" -> PaymentStatus.SUCCEEDED;
default -> PaymentStatus.UNKNOWN;
};
}
public CompletableFuture<Subscription> updateSubscription(
Subscription subscription, String priceId, long level, String idempotencyKey) {
return CompletableFuture.supplyAsync(() -> {
List<SubscriptionUpdateParams.Item> items = new ArrayList<>();
for (final SubscriptionItem item : subscription.getItems().autoPagingIterable(null, commonOptions())) {
items.add(SubscriptionUpdateParams.Item.builder()
.setId(item.getId())
.setDeleted(true)
.build());
}
items.add(SubscriptionUpdateParams.Item.builder()
.setPrice(priceId)
.build());
SubscriptionUpdateParams params = SubscriptionUpdateParams.builder()
.putMetadata(METADATA_KEY_LEVEL, Long.toString(level))
// since badge redemption is untrackable by design and unrevokable, subscription changes must be immediate and
// not prorated
.setProrationBehavior(ProrationBehavior.NONE)
.setBillingCycleAnchor(BillingCycleAnchor.NOW)
.setOffSession(true)
.setPaymentBehavior(SubscriptionUpdateParams.PaymentBehavior.ERROR_IF_INCOMPLETE)
.addAllItem(items)
.build();
try {
return subscription.update(params, commonOptions(generateIdempotencyKeyForSubscriptionUpdate(
subscription.getCustomer(), idempotencyKey)));
} catch (StripeException e) {
throw new CompletionException(e);
}
}, executor);
private static SubscriptionStatus getSubscriptionStatus(final String status) {
return SubscriptionStatus.forApiValue(status);
}
public CompletableFuture<Subscription> getSubscription(String subscriptionId) {
@Override
public CompletableFuture<SubscriptionId> createSubscription(String customerId, String priceId, long level,
long lastSubscriptionCreatedAt) {
return CompletableFuture.supplyAsync(() -> {
SubscriptionCreateParams params = SubscriptionCreateParams.builder()
.setCustomer(customerId)
.setOffSession(true)
.setPaymentBehavior(SubscriptionCreateParams.PaymentBehavior.ERROR_IF_INCOMPLETE)
.addItem(SubscriptionCreateParams.Item.builder()
.setPrice(priceId)
.build())
.putMetadata(METADATA_KEY_LEVEL, Long.toString(level))
.build();
try {
// the idempotency key intentionally excludes priceId
//
// If the client tells the server several times in a row before the initial creation of a subscription to
// create a subscription, we want to ensure only one gets created.
return Subscription.create(params, commonOptions(generateIdempotencyKeyForCreateSubscription(
customerId, lastSubscriptionCreatedAt)));
} catch (StripeException e) {
throw new CompletionException(e);
}
}, executor)
.thenApply(subscription -> new SubscriptionId(subscription.getId()));
}
@Override
public CompletableFuture<SubscriptionId> updateSubscription(
Object subscriptionObj, String priceId, long level, String idempotencyKey) {
if (!(subscriptionObj instanceof final Subscription subscription)) {
throw new IllegalArgumentException("invalid subscription object: " + subscriptionObj.getClass().getName());
}
return CompletableFuture.supplyAsync(() -> {
List<SubscriptionUpdateParams.Item> items = new ArrayList<>();
for (final SubscriptionItem item : subscription.getItems().autoPagingIterable(null, commonOptions())) {
items.add(SubscriptionUpdateParams.Item.builder()
.setId(item.getId())
.setDeleted(true)
.build());
}
items.add(SubscriptionUpdateParams.Item.builder()
.setPrice(priceId)
.build());
SubscriptionUpdateParams params = SubscriptionUpdateParams.builder()
.putMetadata(METADATA_KEY_LEVEL, Long.toString(level))
// since badge redemption is untrackable by design and unrevokable, subscription changes must be immediate and
// not prorated
.setProrationBehavior(ProrationBehavior.NONE)
.setBillingCycleAnchor(BillingCycleAnchor.NOW)
.setOffSession(true)
.setPaymentBehavior(SubscriptionUpdateParams.PaymentBehavior.ERROR_IF_INCOMPLETE)
.addAllItem(items)
.build();
try {
return subscription.update(params, commonOptions(generateIdempotencyKeyForSubscriptionUpdate(
subscription.getCustomer(), idempotencyKey)));
} catch (StripeException e) {
throw new CompletionException(e);
}
}, executor)
.thenApply(subscription1 -> new SubscriptionId(subscription1.getId()));
}
public CompletableFuture<Object> getSubscription(String subscriptionId) {
return CompletableFuture.supplyAsync(() -> {
SubscriptionRetrieveParams params = SubscriptionRetrieveParams.builder()
.addExpand("latest_invoice")
@@ -295,6 +324,21 @@ public class StripeManager implements SubscriptionProcessorManager {
}, executor);
}
public CompletableFuture<Void> cancelAllActiveSubscriptions(String customerId) {
return getCustomer(customerId).thenCompose(customer -> {
if (customer == null) {
throw new InternalServerErrorException(
"no customer record found for id " + customerId);
}
return listNonCanceledSubscriptions(customer);
}).thenCompose(subscriptions -> {
@SuppressWarnings("unchecked")
CompletableFuture<Subscription>[] futures = (CompletableFuture<Subscription>[]) subscriptions.stream()
.map(this::cancelSubscriptionAtEndOfCurrentPeriod).toArray(CompletableFuture[]::new);
return CompletableFuture.allOf(futures);
});
}
public CompletableFuture<Collection<Subscription>> listNonCanceledSubscriptions(Customer customer) {
return CompletableFuture.supplyAsync(() -> {
SubscriptionListParams params = SubscriptionListParams.builder()
@@ -351,11 +395,16 @@ public class StripeManager implements SubscriptionProcessorManager {
});
}
public CompletableFuture<Product> getProductForSubscription(Subscription subscription) {
private CompletableFuture<Product> getProductForSubscription(Subscription subscription) {
return getPriceForSubscription(subscription).thenCompose(price -> getProductForPrice(price.getId()));
}
public CompletableFuture<Long> getLevelForSubscription(Subscription subscription) {
@Override
public CompletableFuture<Long> getLevelForSubscription(Object subscriptionObj) {
if (!(subscriptionObj instanceof final Subscription subscription)) {
throw new IllegalArgumentException("Invalid subscription object: " + subscriptionObj.getClass().getName());
}
return getProductForSubscription(subscription).thenApply(this::getLevelForProduct);
}
@@ -393,7 +442,7 @@ public class StripeManager implements SubscriptionProcessorManager {
.build();
try {
ArrayList<Invoice> invoices = Lists.newArrayList(Invoice.list(params, commonOptions())
.autoPagingIterable(null, commonOptions()));
.autoPagingIterable(null, commonOptions()));
invoices.sort(Comparator.comparingLong(Invoice::getCreated).reversed());
return invoices;
} catch (StripeException e) {
@@ -402,6 +451,54 @@ public class StripeManager implements SubscriptionProcessorManager {
}, executor);
}
@Override
public CompletableFuture<SubscriptionInformation> getSubscriptionInformation(Object subscriptionObj) {
final Subscription subscription = getSubscription(subscriptionObj);
return getPriceForSubscription(subscription).thenCompose(price ->
getLevelForPrice(price).thenApply(level -> {
ChargeFailure chargeFailure = null;
if (subscription.getLatestInvoiceObject() != null && subscription.getLatestInvoiceObject().getChargeObject() != null &&
(subscription.getLatestInvoiceObject().getChargeObject().getFailureCode() != null || subscription.getLatestInvoiceObject().getChargeObject().getFailureMessage() != null)) {
Charge charge = subscription.getLatestInvoiceObject().getChargeObject();
Charge.Outcome outcome = charge.getOutcome();
chargeFailure = new ChargeFailure(
charge.getFailureCode(),
charge.getFailureMessage(),
outcome != null ? outcome.getNetworkStatus() : null,
outcome != null ? outcome.getReason() : null,
outcome != null ? outcome.getType() : null);
}
return new SubscriptionInformation(
new SubscriptionPrice(price.getCurrency().toUpperCase(Locale.ROOT), price.getUnitAmountDecimal()),
level,
Instant.ofEpochSecond(subscription.getBillingCycleAnchor()),
Instant.ofEpochSecond(subscription.getCurrentPeriodEnd()),
Objects.equals(subscription.getStatus(), "active"),
subscription.getCancelAtPeriodEnd(),
getSubscriptionStatus(subscription.getStatus()),
chargeFailure
);
}));
}
private Subscription getSubscription(Object subscriptionObj) {
if (!(subscriptionObj instanceof final Subscription subscription)) {
throw new IllegalArgumentException("invalid subscription object: " + subscriptionObj.getClass().getName());
}
return subscription;
}
@Override
public CompletableFuture<ReceiptItem> getReceiptItem(String subscriptionId) {
return getLatestInvoiceForSubscription(subscriptionId)
.thenCompose(invoice -> convertInvoiceToReceipt(invoice, subscriptionId));
}
public CompletableFuture<Invoice> getLatestInvoiceForSubscription(String subscriptionId) {
return CompletableFuture.supplyAsync(() -> {
SubscriptionRetrieveParams params = SubscriptionRetrieveParams.builder()
@@ -415,24 +512,48 @@ public class StripeManager implements SubscriptionProcessorManager {
}, executor);
}
private CompletableFuture<ReceiptItem> convertInvoiceToReceipt(Invoice latestSubscriptionInvoice, String subscriptionId) {
if (latestSubscriptionInvoice == null) {
throw new WebApplicationException(Status.NO_CONTENT);
}
if (StringUtils.equalsIgnoreCase("open", latestSubscriptionInvoice.getStatus())) {
throw new WebApplicationException(Status.NO_CONTENT);
}
if (!StringUtils.equalsIgnoreCase("paid", latestSubscriptionInvoice.getStatus())) {
throw new WebApplicationException(Status.PAYMENT_REQUIRED);
}
return getInvoiceLineItemsForInvoice(latestSubscriptionInvoice).thenCompose(invoiceLineItems -> {
Collection<InvoiceLineItem> subscriptionLineItems = invoiceLineItems.stream()
.filter(invoiceLineItem -> Objects.equals("subscription", invoiceLineItem.getType()))
.toList();
if (subscriptionLineItems.isEmpty()) {
throw new IllegalStateException("latest subscription invoice has no subscription line items; subscriptionId="
+ subscriptionId + "; invoiceId=" + latestSubscriptionInvoice.getId());
}
if (subscriptionLineItems.size() > 1) {
throw new IllegalStateException(
"latest subscription invoice has too many subscription line items; subscriptionId=" + subscriptionId
+ "; invoiceId=" + latestSubscriptionInvoice.getId() + "; count=" + subscriptionLineItems.size());
}
InvoiceLineItem subscriptionLineItem = subscriptionLineItems.stream().findAny().get();
return getReceiptForSubscriptionInvoiceLineItem(subscriptionLineItem);
});
}
private CompletableFuture<ReceiptItem> getReceiptForSubscriptionInvoiceLineItem(InvoiceLineItem subscriptionLineItem) {
return getProductForPrice(subscriptionLineItem.getPrice().getId()).thenApply(product -> new ReceiptItem(
subscriptionLineItem.getId(),
Instant.ofEpochSecond(subscriptionLineItem.getPeriod().getEnd()),
getLevelForProduct(product)));
}
public CompletableFuture<Collection<InvoiceLineItem>> getInvoiceLineItemsForInvoice(Invoice invoice) {
return CompletableFuture.supplyAsync(
() -> Lists.newArrayList(invoice.getLines().autoPagingIterable(null, commonOptions())), executor);
}
/**
* Takes an amount as configured; for instance USD 4.99 and turns it into an amount as Stripe expects to see it.
* Stripe appears to only support 0 and 2 decimal currencies, but also has some backwards compatibility issues with 0
* decimal currencies so this is not to any ISO standard but rather directly from Stripe's API doc page.
*/
public BigDecimal convertConfiguredAmountToStripeAmount(String currency, BigDecimal configuredAmount) {
return switch (currency.toLowerCase(Locale.ROOT)) {
// Yuck, but this list was taken from https://stripe.com/docs/currencies?presentment-currency=US
case "bif", "clp", "djf", "gnf", "jpy", "kmf", "krw", "mga", "pyg", "rwf", "vnd", "vuv", "xaf", "xof", "xpf" -> configuredAmount;
default -> configuredAmount.scaleByPowerOfTen(2);
};
}
/**
* We use a client generated idempotency key for subscription updates due to not being able to distinguish between a
* call to update to level 2, then back to level 1, then back to level 2. If this all happens within Stripe's
@@ -0,0 +1,74 @@
/*
* Copyright 2023 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.subscriptions;
import java.math.BigDecimal;
import java.util.Locale;
import java.util.Set;
/**
* Utility for scaling amounts among Stripe, Braintree, configuration, and API responses.
* <p>
* In general, the API input and output follow’s Stripe’s <a href= >specification</a> to use amounts in a currency’s
* smallest unit. The exception is configuration APIs, which return values in the currency’s primary unit. Braintree
* uses the currency’s primary unit for its input and output.
* <h2>Examples</h2>
* <table>
* <thead>
* <td>Currency, Amount</td>API</td><td>Stripe</td><td>Braintree</td>
* </thead>
* <tbody>
* <tr>
* <td>USD 4.99</td><td>499</td><td>499</td><td>4.99</td>
* </tr>
* <tr>
* <td>JPY 501</td><td>501</td><td>501</td><td>501</td>
* </tr>
* </tbody>
* </table>
*/
public class SubscriptionCurrencyUtil {
// This list was taken from https://stripe.com/docs/currencies?presentment-currency=US
// Braintree
private static final Set<String> stripeZeroDecimalCurrencies = Set.of("bif", "clp", "djf", "gnf", "jpy", "kmf", "krw",
"mga", "pyg", "rwf", "vnd", "vuv", "xaf", "xof", "xpf");
/**
* Takes an amount as configured and turns it into an amount as API clients (and Stripe) expect to see it. For
* instance, {@code USD 4.99} return {@code 499}, while {@code JPY 500} returns {@code 500}.
*
* <p>
* Stripe appears to only support zero- and two-decimal currencies, but also has some backwards compatibility issues
* with 0 decimal currencies, so this is not to any ISO standard but rather directly from Stripe's API doc page.
*/
public static BigDecimal convertConfiguredAmountToApiAmount(String currency, BigDecimal configuredAmount) {
if (stripeZeroDecimalCurrencies.contains(currency.toLowerCase(Locale.ROOT))) {
return configuredAmount;
}
return configuredAmount.scaleByPowerOfTen(2);
}
/**
* @see org.whispersystems.textsecuregcm.subscriptions.SubscriptionCurrencyUtil#convertConfiguredAmountToApiAmount(String,
* BigDecimal)
*/
public static BigDecimal convertConfiguredAmountToStripeAmount(String currency, BigDecimal configuredAmount) {
return convertConfiguredAmountToApiAmount(currency, configuredAmount);
}
/**
* Braintree’s API expects amounts in a currency’s primary unit (e.g. USD 4.99)
*
* @see org.whispersystems.textsecuregcm.subscriptions.SubscriptionCurrencyUtil#convertConfiguredAmountToApiAmount(String,
* BigDecimal)
*/
static BigDecimal convertBraintreeAmountToApiAmount(final String currency, final BigDecimal amount) {
return convertConfiguredAmountToApiAmount(currency, amount);
}
}
@@ -16,6 +16,7 @@ public enum SubscriptionProcessor {
// because provider IDs are stored, they should not be reused, and great care
// must be used if a provider is removed from the list
STRIPE(1),
BRAINTREE(2),
;
private static final Map<Integer, SubscriptionProcessor> IDS_TO_PROCESSORS = new HashMap<>();
@@ -35,7 +36,7 @@ public enum SubscriptionProcessor {
private final byte id;
SubscriptionProcessor(int id) {
if (id > 256) {
if (id > 255) {
throw new IllegalArgumentException("ID must fit in one byte: " + id);
}
@@ -5,18 +5,159 @@
package org.whispersystems.textsecuregcm.subscriptions;
import java.math.BigDecimal;
import java.time.Instant;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public interface SubscriptionProcessorManager {
SubscriptionProcessor getProcessor();
boolean supportsPaymentMethod(PaymentMethod paymentMethod);
boolean supportsCurrency(String currency);
Set<String> getSupportedCurrencies();
CompletableFuture<PaymentDetails> getPaymentDetails(String paymentId);
CompletableFuture<ProcessorCustomer> createCustomer(byte[] subscriberUser);
CompletableFuture<String> createPaymentMethodSetupToken(String customerId);
Set<String> getSupportedCurrencies();
/**
* @param customerId
* @param paymentMethodToken a processor-specific token necessary
* @param currentSubscriptionId (nullable) an active subscription ID, in case it needs an explicit update
* @return
*/
CompletableFuture<Void> setDefaultPaymentMethodForCustomer(String customerId, String paymentMethodToken,
@Nullable String currentSubscriptionId);
CompletableFuture<Object> getSubscription(String subscriptionId);
CompletableFuture<SubscriptionId> createSubscription(String customerId, String templateId, long level,
long lastSubscriptionCreatedAt);
CompletableFuture<SubscriptionId> updateSubscription(
Object subscription, String templateId, long level, String idempotencyKey);
CompletableFuture<Long> getLevelForSubscription(Object subscription);
CompletableFuture<Void> cancelAllActiveSubscriptions(String customerId);
CompletableFuture<ReceiptItem> getReceiptItem(String subscriptionId);
CompletableFuture<SubscriptionInformation> getSubscriptionInformation(Object subscription);
record PaymentDetails(String id,
Map<String, String> customMetadata,
PaymentStatus status,
Instant created) {
}
enum PaymentStatus {
SUCCEEDED,
PROCESSING,
FAILED,
UNKNOWN,
}
enum SubscriptionStatus {
/**
* The subscription is in good standing and the most recent payment was successful.
*/
ACTIVE("active"),
/**
* Payment failed when creating the subscription, or the subscription’s start date is in the future.
*/
INCOMPLETE("incomplete"),
/**
* Payment on the latest renewal either failed or wasn't attempted.
*/
PAST_DUE("past_due"),
/**
* The subscription has been canceled.
*/
CANCELED("canceled"),
/**
* The latest renewal hasn't been paid but the subscription remains in place.
*/
UNPAID("unpaid"),
/**
* The status from the downstream processor is unknown.
*/
UNKNOWN("unknown");
private final String apiValue;
SubscriptionStatus(String apiValue) {
this.apiValue = apiValue;
}
public static SubscriptionStatus forApiValue(String status) {
return switch (status) {
case "active" -> ACTIVE;
case "canceled", "incomplete_expired" -> CANCELED;
case "unpaid" -> UNPAID;
case "past_due" -> PAST_DUE;
case "incomplete" -> INCOMPLETE;
case "trialing" -> {
final Logger logger = LoggerFactory.getLogger(SubscriptionProcessorManager.class);
logger.error("Subscription has status that should never happen: {}", status);
yield UNKNOWN;
}
default -> {
final Logger logger = LoggerFactory.getLogger(SubscriptionProcessorManager.class);
logger.error("Subscription has unknown status: {}", status);
yield UNKNOWN;
}
};
}
public String getApiValue() {
return apiValue;
}
}
record SubscriptionId(String id) {
}
record SubscriptionInformation(SubscriptionPrice price, long level, Instant billingCycleAnchor,
Instant endOfCurrentPeriod, boolean active, boolean cancelAtPeriodEnd,
SubscriptionStatus status,
ChargeFailure chargeFailure) {
}
record SubscriptionPrice(String currency, BigDecimal amount) {
}
record ChargeFailure(String code, String message, @Nullable String outcomeNetworkStatus,
@Nullable String outcomeReason, @Nullable String outcomeType) {
}
record ReceiptItem(String itemId, Instant expiration, long level) {
}
}
@@ -9,6 +9,6 @@ import io.dropwizard.util.DataSize;
public class Constants {
public static final String METRICS_NAME = "textsecure";
public static final int MAXIMUM_STICKER_SIZE_BYTES = (int) DataSize.kibibytes(300).toBytes();
public static final int MAXIMUM_STICKER_SIZE_BYTES = (int) DataSize.kibibytes(300 + 1).toBytes(); // add 1 kiB for encryption overhead
public static final int MAXIMUM_STICKER_MANIFEST_SIZE_BYTES = (int) DataSize.kibibytes(10).toBytes();
}
@@ -0,0 +1,40 @@
package org.whispersystems.textsecuregcm.util;
import java.util.concurrent.CompletionException;
public final class ExceptionUtils {
private ExceptionUtils() {
// utility class
}
/**
* Extracts the cause of a {@link CompletionException}. If the given {@code throwable} is a
* {@code CompletionException}, this method will recursively iterate through its causal chain until it finds the first
* cause that is not a {@code CompletionException}. If the last {@code CompletionException} in the causal chain has a
* {@code null} cause, then this method returns the last {@code CompletionException} in the chain. If the given
* {@code throwable} is not a {@code CompletionException}, then this method returns the original {@code throwable}.
*
* @param throwable the throwable to "unwrap"
*
* @return the first entity in the given {@code throwable}'s causal chain that is not a {@code CompletionException}
*/
public static Throwable unwrap(Throwable throwable) {
while (throwable instanceof CompletionException e && throwable.getCause() != null) {
throwable = e.getCause();
}
return throwable;
}
/**
* Wraps the given {@code throwable} in a {@link CompletionException} unless the given {@code throwable} is already
* a {@code CompletionException}, in which case this method returns the original throwable.
*
* @param throwable the throwable to wrap in a {@code CompletionException}
*/
public static CompletionException wrap(final Throwable throwable) {
return throwable instanceof CompletionException completionException
? completionException
: new CompletionException(throwable);
}
}
@@ -10,20 +10,25 @@ import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import javax.annotation.Nonnull;
public class SystemMapper {
private static final ObjectMapper mapper = new ObjectMapper();
private static final ObjectMapper MAPPER = build();
static {
@Nonnull
public static ObjectMapper getMapper() {
return MAPPER;
}
@Nonnull
private static ObjectMapper build() {
final ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE);
mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
mapper.registerModule(new JavaTimeModule());
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
public static ObjectMapper getMapper() {
return mapper;
}
}
@@ -22,18 +22,17 @@ import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
public class UsernameGenerator {
/**
* Nicknames are
* Nicknames
* <list>
* <li> lowercase </li>
* <li> do not start with a number </li>
* <li> alphanumeric or underscores only </li>
* <li> minimum length 3 </li>
* <li> maximum length 32 </li>
* <li> are alphanumeric or underscores only </li>
* <li> have minimum length 3 </li>
* <li> have maximum length 32 </li>
* </list>
*
* Usernames typically consist of a nickname and an integer discriminator
*/
public static final Pattern NICKNAME_PATTERN = Pattern.compile("^[_a-z][_a-z0-9]{2,31}$");
public static final Pattern NICKNAME_PATTERN = Pattern.compile("^[_a-zA-Z][_a-zA-Z0-9]{2,31}$");
public static final String SEPARATOR = ".";
private static final Counter USERNAME_NOT_AVAILABLE_COUNTER = Metrics.counter(name(UsernameGenerator.class, "usernameNotAvailable"));
@@ -0,0 +1,10 @@
package org.whispersystems.textsecuregcm.util;
import java.util.Locale;
public final class UsernameNormalizer {
private UsernameNormalizer() {}
public static String normalize(final String username) {
return username.toLowerCase(Locale.ROOT);
}
}
@@ -191,4 +191,29 @@ public class Util {
public static Optional<String> findBestLocale(List<LanguageRange> priorityList, Collection<String> supportedLocales) {
return Optional.ofNullable(Locale.lookupTag(priorityList, supportedLocales));
}
/**
* Map ints to non-negative ints.
* <br>
* Unlike Math.abs this method handles Integer.MIN_VALUE correctly.
*
* @param n any int value
* @return an int value guaranteed to be non-negative
*/
public static int ensureNonNegativeInt(int n) {
return n == Integer.MIN_VALUE ? 0 : Math.abs(n);
}
/**
* Map longs to non-negative longs.
* <br>
* Unlike Math.abs this method handles Long.MIN_VALUE correctly.
*
* @param n any long value
* @return a long value guaranteed to be non-negative
*/
public static long ensureNonNegativeLong(long n) {
return n == Long.MIN_VALUE ? 0 : Math.abs(n);
}
}
@@ -141,7 +141,7 @@ public class AssignUsernameCommand extends EnvironmentCommand<WhisperServerConfi
VerificationCodeStore pendingAccounts = new VerificationCodeStore(dynamoDbClient,
configuration.getDynamoDbTables().getPendingAccounts().getTableName());
Accounts accounts = new Accounts(dynamicConfigurationManager,
Accounts accounts = new Accounts(
dynamoDbClient,
dynamoDbAsyncClient,
configuration.getDynamoDbTables().getAccounts().getTableName(),
@@ -143,7 +143,7 @@ public class DeleteUserCommand extends EnvironmentCommand<WhisperServerConfigura
VerificationCodeStore pendingAccounts = new VerificationCodeStore(dynamoDbClient,
configuration.getDynamoDbTables().getPendingAccounts().getTableName());
Accounts accounts = new Accounts(dynamicConfigurationManager,
Accounts accounts = new Accounts(
dynamoDbClient,
dynamoDbAsyncClient,
configuration.getDynamoDbTables().getAccounts().getTableName(),
@@ -146,7 +146,7 @@ public class SetUserDiscoverabilityCommand extends EnvironmentCommand<WhisperSer
VerificationCodeStore pendingAccounts = new VerificationCodeStore(dynamoDbClient,
configuration.getDynamoDbTables().getPendingAccounts().getTableName());
Accounts accounts = new Accounts(dynamicConfigurationManager,
Accounts accounts = new Accounts(
dynamoDbClient,
dynamoDbAsyncClient,
configuration.getDynamoDbTables().getAccounts().getTableName(),
+4 -14
View File
@@ -1,19 +1,9 @@
/**
* Copyright (C) 2014 Open Whisper Systems
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
* Copyright 2014 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
syntax = "proto2";
package textsecure;
option java_package = "org.whispersystems.textsecuregcm.storage";
@@ -6,8 +6,13 @@ package org.signal.registration.rpc;
service RegistrationService {
/**
* Sends a verification code to a destination phone number and returns the
* ID of the newly-created registration session.
* Create a new registration session for a given destination phone number.
*/
rpc create_session (CreateRegistrationSessionRequest) returns (CreateRegistrationSessionResponse) {}
/**
* Sends a verification code to a destination phone number within the context
* of a previously-created registration session.
*/
rpc send_verification_code (SendVerificationCodeRequest) returns (SendVerificationCodeResponse) {}
@@ -18,11 +23,81 @@ service RegistrationService {
rpc check_verification_code (CheckVerificationCodeRequest) returns (CheckVerificationCodeResponse) {}
}
message SendVerificationCodeRequest {
message CreateRegistrationSessionRequest {
/**
* The phone number to which to send a verification code.
* The phone number for which to create a new registration session.
*/
uint64 e164 = 1;
}
message CreateRegistrationSessionResponse {
oneof response {
/**
* Metadata for the newly-created session.
*/
RegistrationSessionMetadata session_metadata = 1;
/**
* A response explaining why a session could not be created as requested.
*/
CreateRegistrationSessionError error = 2;
}
}
message RegistrationSessionMetadata {
/**
* An opaque sequence of bytes that uniquely identifies the registration
* session associated with this registration attempt.
*/
bytes session_id = 1;
/**
* Indicates whether a valid verification code has been submitted in the scope
* of this session.
*/
bool verified = 2;
}
message CreateRegistrationSessionError {
/**
* The type of error that prevented a session from being created.
*/
CreateRegistrationSessionErrorType error_type = 1;
/**
* Indicates that this error may succeed if retried without modification after
* a delay indicated by `retry_after_seconds`. If false, callers should not
* retry the request without modification.
*/
bool may_retry = 2;
/**
* If this error may be retried,, indicates the duration in seconds from the
* present after which the request may be retried without modification. This
* value has no meaning otherwise.
*/
uint64 retry_after_seconds = 3;
}
enum CreateRegistrationSessionErrorType {
CREATE_REGISTRATION_SESSION_ERROR_TYPE_UNSPECIFIED = 0;
/**
* Indicates that a session could not be created because too many requests to
* create a session for the given phone number have been received in some
* window of time. Callers should wait and try again later.
*/
CREATE_REGISTRATION_SESSION_ERROR_TYPE_RATE_LIMITED = 1;
/**
* Indicates that the provided phone number could not be parsed.
*/
CREATE_REGISTRATION_SESSION_ERROR_TYPE_ILLEGAL_PHONE_NUMBER = 2;
}
message SendVerificationCodeRequest {
reserved 1;
/**
* The message transport to use to send a verification code to the destination
@@ -31,8 +106,8 @@ message SendVerificationCodeRequest {
MessageTransport transport = 2;
/**
* The value of the `Accept-Language` header provided by remote clients (if
* any).
* A prioritized list of languages accepted by the destination; should be
* provided in the same format as the value of an HTTP Accept-Language header.
*/
string accept_language = 3;
@@ -40,6 +115,17 @@ message SendVerificationCodeRequest {
* The type of client requesting a verification code.
*/
ClientType client_type = 4;
/**
* The ID of a session within which to send (or re-send) a verification code.
*/
bytes session_id = 5;
/**
* If provided, always attempt to use the specified sender to send
* this message.
*/
string sender_name = 6;
}
enum MessageTransport {
@@ -61,6 +147,76 @@ message SendVerificationCodeResponse {
* session associated with this registration attempt.
*/
bytes session_id = 1;
/**
* Metadata for the named session. May be absent if the session could not be
* found or has expired.
*/
RegistrationSessionMetadata session_metadata = 2;
/**
* If a code could not be sent, explains the underlying error. Will be absent
* if a code was sent successfully. Note that both an error and session
* metadata may be present in the same response because the session metadata
* may include information helpful for resolving the underlying error (i.e.
* "next attempt" times).
*/
SendVerificationCodeError error = 3;
}
message SendVerificationCodeError {
/**
* The type of error that prevented a verification code from being sent.
*/
SendVerificationCodeErrorType error_type = 1;
/**
* Indicates that this error may succeed if retried without modification after
* a delay indicated by `retry_after_seconds`. If false, callers should not
* retry the request without modification.
*/
bool may_retry = 2;
/**
* If this error may be retried,, indicates the duration in seconds from the
* present after which the request may be retried without modification. This
* value has no meaning otherwise.
*/
uint64 retry_after_seconds = 3;
}
enum SendVerificationCodeErrorType {
SEND_VERIFICATION_CODE_ERROR_TYPE_UNSPECIFIED = 0;
/**
* The sender received and understood the request to send a verification code,
* but declined to do so (i.e. due to rate limits or suspected fraud).
*/
SEND_VERIFICATION_CODE_ERROR_TYPE_SENDER_REJECTED = 1;
/**
* The sender could not process or would not accept some part of a request
* (e.g. a valid phone number that cannot receive SMS messages).
*/
SEND_VERIFICATION_CODE_ERROR_TYPE_SENDER_ILLEGAL_ARGUMENT = 2;
/**
* A verification could could not be sent via the requested channel due to
* timing/rate restrictions. The response object containing this error should
* include session metadata that indicates when the next attempt is allowed.
*/
SEND_VERIFICATION_CODE_ERROR_TYPE_RATE_LIMITED = 3;
/**
* No session was found with the given ID.
*/
SEND_VERIFICATION_CODE_ERROR_TYPE_SESSION_NOT_FOUND = 4;
/**
* A new verification could could not be sent because the session has already
* been verified.
*/
SEND_VERIFICATION_CODE_ERROR_TYPE_SESSION_ALREADY_VERIFIED = 5;
}
message CheckVerificationCodeRequest {
@@ -81,4 +237,70 @@ message CheckVerificationCodeResponse {
* matched the expected code or false otherwise.
*/
bool verified = 1;
/**
* Metadata for the named session. May be absent if the session could not be
* found or has expired.
*/
RegistrationSessionMetadata session_metadata = 2;
/**
* If a code could not be checked, explains the underlying error. Will be
* absent if no error occurred. Note that both an error and session
* metadata may be present in the same response because the session metadata
* may include information helpful for resolving the underlying error (i.e.
* "next attempt" times).
*/
CheckVerificationCodeError error = 3;
}
message CheckVerificationCodeError {
/**
* The type of error that prevented a verification code from being checked.
*/
CheckVerificationCodeErrorType error_type = 1;
/**
* Indicates that this error may succeed if retried without modification after
* a delay indicated by `retry_after_seconds`. If false, callers should not
* retry the request without modification.
*/
bool may_retry = 2;
/**
* If this error may be retried,, indicates the duration in seconds from the
* present after which the request may be retried without modification. This
* value has no meaning otherwise.
*/
uint64 retry_after_seconds = 3;
}
enum CheckVerificationCodeErrorType {
CHECK_VERIFICATION_CODE_ERROR_TYPE_UNSPECIFIED = 0;
/**
* The caller has made too many incorrect guesses within the scope of this
* session and may not make any further guesses.
*/
CHECK_VERIFICATION_CODE_ERROR_TYPE_ATTEMPTS_EXHAUSTED = 1;
/**
* The caller has attempted to submit a verification code even though no
* verification codes have been sent within the scope of this session. The
* caller must issue a "send code" request before trying again.
*/
CHECK_VERIFICATION_CODE_ERROR_TYPE_NO_CODE_SENT = 2;
/**
* The caller has made too many guesses within some period of time. Callers
* should wait for the duration prescribed in the session metadata object
* elsewhere in the response before trying again.
*/
CHECK_VERIFICATION_CODE_ERROR_TYPE_RATE_LIMITED = 3;
/**
* The session identified in this request could not be found (possibly due to
* session expiration).
*/
CHECK_VERIFICATION_CODE_ERROR_TYPE_SESSION_NOT_FOUND = 4;
}
+6 -15
View File
@@ -1,19 +1,9 @@
/**
* Copyright (C) 2013 - 2015 Open WhisperSystems
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
* Copyright 2013 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
syntax = "proto2";
package textsecure;
option java_package = "org.whispersystems.textsecuregcm.entities";
@@ -43,7 +33,8 @@ message Envelope {
optional bool urgent = 14 [default=true];
optional string updated_pni = 15;
optional bool story = 16; // indicates that the content is a story.
// next: 17
optional bytes report_spam_token = 17; // token sent when reporting spam
// next: 18
}
message ProvisioningUuid {
@@ -29,3 +29,6 @@ BOOST_description = {short_name} supported Signal with a donation. Signal is a n
GIFT_name = Signal Gift
GIFT_description = {short_name} received a gift from a Signal supporter. Signal is a nonprofit with no advertisers or investors, supported only by people like you.
GIFT2_name = Signal UFO
GIFT2_description = A friend made a donation to Signal on behalf of {short_name}. Signal is a nonprofit with no advertisers or investors, supported only by people like you.
@@ -19,7 +19,6 @@ import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import io.dropwizard.auth.basic.BasicCredentials;
import java.time.Clock;
import java.time.Instant;
import java.util.List;
import java.util.Optional;
@@ -31,7 +30,7 @@ import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.junitpioneer.jupiter.cartesian.CartesianTest;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
@@ -208,37 +207,46 @@ class BaseAccountAuthenticatorTest {
verify(accountsManager, never()).updateDeviceAuthentication(any(), any(), any());
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void testAuthenticateEnabledRequired(final boolean enabledRequired) {
@CartesianTest
void testAuthenticateEnabledRequired(
@CartesianTest.Values(booleans = {true, false}) final boolean enabledRequired,
@CartesianTest.Values(booleans = {true, false}) final boolean accountEnabled,
@CartesianTest.Values(booleans = {true, false}) final boolean deviceEnabled,
@CartesianTest.Values(booleans = {true, false}) final boolean authenticatedDeviceIsPrimary) {
final UUID uuid = UUID.randomUUID();
final long deviceId = 1;
final long deviceId = authenticatedDeviceIsPrimary ? 1 : 2;
final String password = "12345";
final Account account = mock(Account.class);
final Device device = mock(Device.class);
final Device authenticatedDevice = mock(Device.class);
final AuthenticationCredentials credentials = mock(AuthenticationCredentials.class);
clock.unpin();
when(accountsManager.getByAccountIdentifier(uuid)).thenReturn(Optional.of(account));
when(account.getUuid()).thenReturn(uuid);
when(account.getDevice(deviceId)).thenReturn(Optional.of(device));
when(account.isEnabled()).thenReturn(false);
when(device.getId()).thenReturn(deviceId);
when(device.isEnabled()).thenReturn(false);
when(device.getAuthenticationCredentials()).thenReturn(credentials);
when(account.getDevice(deviceId)).thenReturn(Optional.of(authenticatedDevice));
when(account.isEnabled()).thenReturn(accountEnabled);
when(authenticatedDevice.getId()).thenReturn(deviceId);
when(authenticatedDevice.isEnabled()).thenReturn(deviceEnabled);
when(authenticatedDevice.getAuthenticationCredentials()).thenReturn(credentials);
when(credentials.verify(password)).thenReturn(true);
when(credentials.getVersion()).thenReturn(AuthenticationCredentials.CURRENT_VERSION);
final String identifier;
if (authenticatedDeviceIsPrimary) {
identifier = uuid.toString();
} else {
identifier = uuid.toString() + BaseAccountAuthenticator.DEVICE_ID_SEPARATOR + deviceId;
}
final Optional<AuthenticatedAccount> maybeAuthenticatedAccount =
baseAccountAuthenticator.authenticate(new BasicCredentials(uuid.toString(), password), enabledRequired);
baseAccountAuthenticator.authenticate(new BasicCredentials(identifier, password), enabledRequired);
if (enabledRequired) {
if (enabledRequired && !(accountEnabled && deviceEnabled)) {
assertThat(maybeAuthenticatedAccount).isEmpty();
} else {
assertThat(maybeAuthenticatedAccount).isPresent();
assertThat(maybeAuthenticatedAccount.get().getAccount().getUuid()).isEqualTo(uuid);
assertThat(maybeAuthenticatedAccount.get().getAuthenticatedDevice()).isEqualTo(device);
assertThat(maybeAuthenticatedAccount.get().getAuthenticatedDevice()).isEqualTo(authenticatedDevice);
}
}
@@ -22,9 +22,10 @@ class StoredVerificationCodeTest {
private static Stream<Arguments> isValid() {
return Stream.of(
Arguments.of(new StoredVerificationCode("code", System.currentTimeMillis(), null, null, null), "code", true),
Arguments.of(new StoredVerificationCode("code", System.currentTimeMillis(), null, null, null), "incorrect", false),
Arguments.of(new StoredVerificationCode("", System.currentTimeMillis(), null, null, null), "", false)
Arguments.of(
new StoredVerificationCode("code", System.currentTimeMillis(), null, null), "code", true),
Arguments.of(new StoredVerificationCode("code", System.currentTimeMillis(), null, null), "incorrect", false),
Arguments.of(new StoredVerificationCode("", System.currentTimeMillis(), null, null), "", false)
);
}
}
@@ -11,7 +11,6 @@ import static org.junit.jupiter.params.provider.Arguments.arguments;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.time.Clock;
import java.time.Instant;
@@ -46,7 +45,7 @@ public class ConfiguredProfileBadgeConverterTest {
private ResourceBundle resourceBundle;
@BeforeEach
private void beforeEach() {
void beforeEach() {
resourceBundleFactory = mock(ResourceBundleFactory.class, (invocation) -> {
throw new UnsupportedOperationException();
});
@@ -0,0 +1,119 @@
/*
* Copyright 2022 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.captcha;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.whispersystems.textsecuregcm.captcha.CaptchaChecker.SEPARATOR;
import java.io.IOException;
import java.util.List;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import javax.ws.rs.BadRequestException;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
public class CaptchaCheckerTest {
private static final String SITE_KEY = "site-key";
private static final String TOKEN = "some-token";
private static final String PREFIX = "prefix";
private static final String PREFIX_A = "prefix-a";
private static final String PREFIX_B = "prefix-b";
static Stream<Arguments> parseInputToken() {
return Stream.of(
Arguments.of(
String.join(SEPARATOR, PREFIX, SITE_KEY, TOKEN),
TOKEN,
SITE_KEY,
null),
Arguments.of(
String.join(SEPARATOR, PREFIX, SITE_KEY, "an-action", TOKEN),
TOKEN,
SITE_KEY,
"an-action"),
Arguments.of(
String.join(SEPARATOR, PREFIX, SITE_KEY, "an-action", TOKEN, "something-else"),
TOKEN + SEPARATOR + "something-else",
SITE_KEY,
"an-action")
);
}
private static CaptchaClient mockClient(final String prefix) throws IOException {
final CaptchaClient captchaClient = mock(CaptchaClient.class);
when(captchaClient.scheme()).thenReturn(prefix);
when(captchaClient.verify(any(), any(), any(), any())).thenReturn(AssessmentResult.invalid());
return captchaClient;
}
@ParameterizedTest
@MethodSource
void parseInputToken(final String input, final String expectedToken, final String siteKey,
@Nullable final String expectedAction) throws IOException {
final CaptchaClient captchaClient = mockClient(PREFIX);
new CaptchaChecker(List.of(captchaClient)).verify(input, null);
verify(captchaClient, times(1)).verify(eq(siteKey), eq(expectedAction), eq(expectedToken), any());
}
@ParameterizedTest
@MethodSource
void scoreString(float score, String expected) {
assertThat(AssessmentResult.scoreString(score)).isEqualTo(expected);
}
static Stream<Arguments> scoreString() {
return Stream.of(
Arguments.of(0.3f, "30"),
Arguments.of(0.0f, "0"),
Arguments.of(0.333f, "30"),
Arguments.of(0.29f, "30"),
Arguments.of(Float.NaN, "0")
);
}
@Test
public void choose() throws IOException {
String ainput = String.join(SEPARATOR, PREFIX_A, SITE_KEY, TOKEN);
String binput = String.join(SEPARATOR, PREFIX_B, SITE_KEY, TOKEN);
final CaptchaClient a = mockClient(PREFIX_A);
final CaptchaClient b = mockClient(PREFIX_B);
new CaptchaChecker(List.of(a, b)).verify(ainput, null);
verify(a, times(1)).verify(any(), any(), any(), any());
new CaptchaChecker(List.of(a, b)).verify(binput, null);
verify(b, times(1)).verify(any(), any(), any(), any());
}
static Stream<Arguments> badToken() {
return Stream.of(
Arguments.of(String.join(SEPARATOR, "invalid", SITE_KEY, "action", TOKEN)),
Arguments.of(String.join(SEPARATOR, PREFIX, TOKEN)),
Arguments.of(String.join(SEPARATOR, SITE_KEY, PREFIX, "action", TOKEN))
);
}
@ParameterizedTest
@MethodSource
public void badToken(final String input) throws IOException {
final CaptchaClient cc = mockClient(PREFIX);
assertThrows(BadRequestException.class, () -> new CaptchaChecker(List.of(cc)).verify(input, null));
}
}
@@ -0,0 +1,117 @@
package org.whispersystems.textsecuregcm.captcha;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.http.HttpClient;
import java.net.http.HttpResponse;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicCaptchaConfiguration;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
public class HCaptchaClientTest {
private static final String SITE_KEY = "site-key";
private static final String TOKEN = "token";
static Stream<Arguments> captchaProcessed() {
return Stream.of(
Arguments.of(true, 0.6f, true),
Arguments.of(false, 0.6f, false),
Arguments.of(true, 0.4f, false),
Arguments.of(false, 0.4f, false)
);
}
@ParameterizedTest
@MethodSource
public void captchaProcessed(final boolean success, final float score, final boolean expectedResult)
throws IOException, InterruptedException {
final HttpClient client = mockResponder(200, String.format("""
{
"success": %b,
"score": %f,
"score-reasons": ["great job doing this captcha"]
}
""",
success, 1 - score)); // hCaptcha scores are inverted compared to recaptcha scores. (low score is good)
final AssessmentResult result = new HCaptchaClient("fake", client, mockConfig(true, 0.5))
.verify(SITE_KEY, "whatever", TOKEN, null);
if (!success) {
assertThat(result).isEqualTo(AssessmentResult.invalid());
} else {
assertThat(result)
.isEqualTo(new AssessmentResult(expectedResult, AssessmentResult.scoreString(score)));
}
}
@Test
public void errorResponse() throws IOException, InterruptedException {
final HttpClient httpClient = mockResponder(503, "");
final HCaptchaClient client = new HCaptchaClient("fake", httpClient, mockConfig(true, 0.5));
assertThrows(IOException.class, () -> client.verify(SITE_KEY, "whatever", TOKEN, null));
}
@Test
public void invalidScore() throws IOException, InterruptedException {
final HttpClient httpClient = mockResponder(200, """
{"success" : true, "score": 1.1}
""");
final HCaptchaClient client = new HCaptchaClient("fake", httpClient, mockConfig(true, 0.5));
assertThat(client.verify(SITE_KEY, "whatever", TOKEN, null)).isEqualTo(AssessmentResult.invalid());
}
@Test
public void badBody() throws IOException, InterruptedException {
final HttpClient httpClient = mockResponder(200, """
{"success" : true,
""");
final HCaptchaClient client = new HCaptchaClient("fake", httpClient, mockConfig(true, 0.5));
assertThrows(IOException.class, () -> client.verify(SITE_KEY, "whatever", TOKEN, null));
}
@Test
public void disabled() throws IOException {
final HCaptchaClient hc = new HCaptchaClient("fake", null, mockConfig(false, 0.5));
assertThat(hc.verify(SITE_KEY, null, TOKEN, null)).isEqualTo(AssessmentResult.invalid());
}
private static HttpClient mockResponder(final int statusCode, final String jsonBody)
throws IOException, InterruptedException {
HttpClient httpClient = mock(HttpClient.class);
@SuppressWarnings("unchecked") final HttpResponse<Object> httpResponse = mock(HttpResponse.class);
when(httpResponse.body()).thenReturn(jsonBody);
when(httpResponse.statusCode()).thenReturn(statusCode);
when(httpClient.send(any(), any())).thenReturn(httpResponse);
return httpClient;
}
private static DynamicConfigurationManager<DynamicConfiguration> mockConfig(boolean enabled, double scoreFloor) {
final DynamicCaptchaConfiguration config = new DynamicCaptchaConfiguration();
config.setAllowHCaptcha(enabled);
config.setScoreFloor(BigDecimal.valueOf(scoreFloor));
@SuppressWarnings("unchecked") final DynamicConfigurationManager<DynamicConfiguration> m = mock(
DynamicConfigurationManager.class);
final DynamicConfiguration d = mock(DynamicConfiguration.class);
when(m.getConfiguration()).thenReturn(d);
when(d.getCaptchaConfiguration()).thenReturn(config);
return m;
}
}
Loaded 100 of 131 files, more files were not shown because too many files have changed in this diff. Show more