mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-12-01 00:36:47 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
448365c7a0 | ||
|
|
515a863195 | ||
|
|
8d0e23bde1 | ||
|
|
dc8f62a4ad | ||
|
|
896e65545e | ||
|
|
cd4a4b1dcf | ||
|
|
38a0737afb | ||
|
|
4a2768b81d | ||
|
|
00e08b8402 | ||
|
|
48e8584e13 | ||
|
|
a89e30fe75 | ||
|
|
a01fcdad28 | ||
|
|
2a99529921 | ||
|
|
c934405a3e | ||
|
|
b8d922fcb7 | ||
|
|
eb499833c6 | ||
|
|
dd98f7f043 | ||
|
|
e8978ef91c | ||
|
|
669ff1cadf | ||
|
|
4ce85fdb19 | ||
|
|
035ddc4834 | ||
|
|
c2f40b8503 | ||
|
|
cf738a1c14 | ||
|
|
52d40c2321 | ||
|
|
cbf12d6b46 | ||
|
|
ab26a65b6a | ||
|
|
ee5aaf5383 | ||
|
|
1c1714b2c2 | ||
|
|
accb017ec5 | ||
|
|
304782d583 | ||
|
|
f361f436d8 | ||
|
|
a34b5a6122 | ||
|
|
f75ea18ccb | ||
|
|
9a06c40a28 | ||
|
|
e6ab97dc5a | ||
|
|
ba73f757e2 | ||
|
|
30f131096d | ||
|
|
b8ce922f92 | ||
|
|
11b62345e1 | ||
|
|
77289ecb51 | ||
|
|
dfb0b68997 | ||
|
|
d545f60fc4 | ||
|
|
5cda6e9d84 | ||
|
|
7caba89210 | ||
|
|
b8967b75c6 | ||
|
|
74d9849472 | ||
|
|
96b753cfd0 | ||
|
|
5a89e66fc0 | ||
|
|
b4a143b9de | ||
|
|
050035dd52 | ||
|
|
7018062606 | ||
|
|
9e1485de0a | ||
|
|
4e358b891f | ||
|
|
4044a9df30 | ||
|
|
5a7b675001 | ||
|
|
3be4e4bc57 | ||
|
|
5de51919bb |
No files matched your search
@@ -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
@@ -1,11 +1,11 @@
|
||||
# Note that the implementation of the abusive message filter is private; internal
|
||||
# Note that the implementation of the spam filter is private; internal
|
||||
# developers will need to override this URL with:
|
||||
#
|
||||
# ```
|
||||
# git config submodule.abusive-message-filter.url PRIVATE_URL
|
||||
# git config submodule.spam-filter.url PRIVATE_URL
|
||||
# ```
|
||||
#
|
||||
# External developers may safely ignore this submodule.
|
||||
[submodule "abusive-message-filter"]
|
||||
path = abusive-message-filter
|
||||
[submodule "spam-filter"]
|
||||
path = spam-filter
|
||||
url = REDACTED
|
||||
Submodule abusive-message-filter deleted from e65abe428d.
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,9 @@
|
||||
<id>dynamodb-local-oregon</id>
|
||||
<name>DynamoDB Local Release Repository</name>
|
||||
<url>https://s3-us-west-2.amazonaws.com/dynamodb-local/release</url>
|
||||
<snapshots>
|
||||
<enabled>false</enabled>
|
||||
</snapshots>
|
||||
</repository>
|
||||
</repositories>
|
||||
|
||||
@@ -42,31 +45,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.21</kotlin.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>
|
||||
@@ -96,13 +99,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>
|
||||
@@ -134,7 +130,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>
|
||||
@@ -176,11 +172,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>
|
||||
@@ -333,7 +324,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>
|
||||
@@ -362,27 +353,33 @@
|
||||
<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>
|
||||
|
||||
<profiles>
|
||||
<profile>
|
||||
<id>include-abusive-message-filter</id>
|
||||
<id>include-spam-filter</id>
|
||||
<activation>
|
||||
<file>
|
||||
<exists>abusive-message-filter/pom.xml</exists>
|
||||
<exists>spam-filter/pom.xml</exists>
|
||||
</file>
|
||||
</activation>
|
||||
<modules>
|
||||
<module>abusive-message-filter</module>
|
||||
<module>spam-filter</module>
|
||||
</modules>
|
||||
</profile>
|
||||
|
||||
<profile>
|
||||
<id>exclude-abusive-message-filter</id>
|
||||
<id>exclude-spam-filter</id>
|
||||
<activation>
|
||||
<file>
|
||||
<missing>abusive-message-filter/pom.xml</missing>
|
||||
<missing>spam-filter/pom.xml</missing>
|
||||
</file>
|
||||
</activation>
|
||||
</profile>
|
||||
|
||||
@@ -140,6 +140,10 @@ directoryV2:
|
||||
userAuthenticationTokenSharedSecret: abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG= # base64-encoded secret shared with CDS to generate auth tokens for Signal users
|
||||
userIdTokenSharedSecret: bbcdefghijklmnopqrstuvwxyz0123456789ABCDEFG= # base64-encoded secret shared with CDS to generate auth identity tokens for Signal users
|
||||
|
||||
svr2:
|
||||
userAuthenticationTokenSharedSecret: abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG= # base64-encoded secret shared with SVR2 to generate auth tokens for Signal users
|
||||
userIdTokenSharedSecret: bbcdefghijklmnopqrstuvwxyz0123456789ABCDEFG= # base64-encoded secret shared with SVR2 to generate auth identity tokens for Signal users
|
||||
|
||||
messageCache: # Redis server configuration for message store cache
|
||||
persistDelayMinutes: 1
|
||||
cluster:
|
||||
@@ -225,11 +229,6 @@ unidentifiedDelivery:
|
||||
privateKey: ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789AAAAAAA
|
||||
expiresDays: 7
|
||||
|
||||
voiceVerification:
|
||||
url: https://cdn-ca.signal.org/verification/
|
||||
locales:
|
||||
- en
|
||||
|
||||
recaptcha:
|
||||
projectPath: projects/example
|
||||
credentialConfigurationJson: "{ }" # service account configuration for backend authentication
|
||||
@@ -352,7 +351,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:
|
||||
|
||||
+3
-30
@@ -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>
|
||||
|
||||
@@ -473,7 +446,7 @@
|
||||
|
||||
<profiles>
|
||||
<profile>
|
||||
<id>exclude-abusive-message-filter</id>
|
||||
<id>exclude-spam-filter</id>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
mutation CreatePayPalBillingAgreement($input: CreatePayPalBillingAgreementInput!) {
|
||||
createPayPalBillingAgreement(input: $input) {
|
||||
approvalUrl,
|
||||
billingAgreementToken
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
mutation TokenizePayPalBillingAgreement($input: TokenizePayPalBillingAgreementInput!) {
|
||||
tokenizePayPalBillingAgreement(input: $input) {
|
||||
paymentMethod {
|
||||
id
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
mutation VaultPaymentMethod($input: VaultPaymentMethodInput!) {
|
||||
vaultPaymentMethod(input: $input) {
|
||||
paymentMethod {
|
||||
id
|
||||
}
|
||||
}
|
||||
}
|
||||
+14
-14
@@ -12,7 +12,7 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
import javax.validation.Valid;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import org.whispersystems.textsecuregcm.configuration.AbusiveMessageFilterConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.SpamFilterConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.AccountDatabaseCrawlerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.AdminEventLoggingConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.ApnConfiguration;
|
||||
@@ -43,12 +43,12 @@ import org.whispersystems.textsecuregcm.configuration.RemoteConfigConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.ReportMessageConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.SecureBackupServiceConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.SecureStorageServiceConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.SecureValueRecovery2Configuration;
|
||||
import org.whispersystems.textsecuregcm.configuration.StripeConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.SubscriptionConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.TestDeviceConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.UnidentifiedDeliveryConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.UsernameConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.VoiceVerificationConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.ZkConfig;
|
||||
import org.whispersystems.websocket.configuration.WebSocketConfiguration;
|
||||
|
||||
@@ -125,6 +125,11 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
@JsonProperty
|
||||
private DirectoryV2Configuration directoryV2;
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
@JsonProperty
|
||||
private SecureValueRecovery2Configuration svr2;
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
@JsonProperty
|
||||
@@ -185,11 +190,6 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
@JsonProperty
|
||||
private UnidentifiedDeliveryConfiguration unidentifiedDelivery;
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
private VoiceVerificationConfiguration voiceVerification;
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
@@ -262,7 +262,7 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
|
||||
@Valid
|
||||
@JsonProperty
|
||||
private AbusiveMessageFilterConfiguration abusiveMessageFilter;
|
||||
private SpamFilterConfiguration spamFilterConfiguration;
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@@ -297,10 +297,6 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
return hCaptcha;
|
||||
}
|
||||
|
||||
public VoiceVerificationConfiguration getVoiceVerificationConfiguration() {
|
||||
return voiceVerification;
|
||||
}
|
||||
|
||||
public WebSocketConfiguration getWebSocketConfiguration() {
|
||||
return webSocket;
|
||||
}
|
||||
@@ -329,6 +325,10 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
return directory;
|
||||
}
|
||||
|
||||
public SecureValueRecovery2Configuration getSvr2Configuration() {
|
||||
return svr2;
|
||||
}
|
||||
|
||||
public DirectoryV2Configuration getDirectoryV2Configuration() {
|
||||
return directoryV2;
|
||||
}
|
||||
@@ -443,8 +443,8 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
return reportMessage;
|
||||
}
|
||||
|
||||
public AbusiveMessageFilterConfiguration getAbusiveMessageFilterConfiguration() {
|
||||
return abusiveMessageFilter;
|
||||
public SpamFilterConfiguration getSpamFilterConfiguration() {
|
||||
return spamFilterConfiguration;
|
||||
}
|
||||
|
||||
public UsernameConfiguration getUsername() {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2013-2022 Signal Messenger, LLC
|
||||
* Copyright 2013 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm;
|
||||
@@ -70,24 +70,23 @@ import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
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.auth.AccountAuthenticator;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
|
||||
import org.whispersystems.textsecuregcm.auth.CertificateGenerator;
|
||||
import org.whispersystems.textsecuregcm.auth.DisabledPermittedAccountAuthenticator;
|
||||
import org.whispersystems.textsecuregcm.auth.DisabledPermittedAuthenticatedAccount;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialGenerator;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
|
||||
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.captcha.RecaptchaClient;
|
||||
import org.whispersystems.textsecuregcm.configuration.DirectoryServerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.controllers.AccountController;
|
||||
import org.whispersystems.textsecuregcm.controllers.ArtController;
|
||||
import org.whispersystems.textsecuregcm.controllers.AttachmentControllerV2;
|
||||
import org.whispersystems.textsecuregcm.controllers.AttachmentControllerV3;
|
||||
import org.whispersystems.textsecuregcm.controllers.CertificateController;
|
||||
@@ -105,16 +104,15 @@ import org.whispersystems.textsecuregcm.controllers.ProvisioningController;
|
||||
import org.whispersystems.textsecuregcm.controllers.RemoteConfigController;
|
||||
import org.whispersystems.textsecuregcm.controllers.SecureBackupController;
|
||||
import org.whispersystems.textsecuregcm.controllers.SecureStorageController;
|
||||
import org.whispersystems.textsecuregcm.controllers.SecureValueRecovery2Controller;
|
||||
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;
|
||||
import org.whispersystems.textsecuregcm.currency.CurrencyConversionManager;
|
||||
import org.whispersystems.textsecuregcm.currency.FixerClient;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.filters.RequestStatisticsFilter;
|
||||
import org.whispersystems.textsecuregcm.filters.RemoteDeprecationFilter;
|
||||
import org.whispersystems.textsecuregcm.filters.RequestStatisticsFilter;
|
||||
import org.whispersystems.textsecuregcm.filters.TimestampResponseFilter;
|
||||
import org.whispersystems.textsecuregcm.limits.DynamicRateLimiters;
|
||||
import org.whispersystems.textsecuregcm.limits.PushChallengeManager;
|
||||
@@ -156,7 +154,6 @@ 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.captcha.RecaptchaClient;
|
||||
import org.whispersystems.textsecuregcm.redis.ConnectionEventLogger;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
import org.whispersystems.textsecuregcm.redis.ReplicatedJedisPool;
|
||||
@@ -165,6 +162,10 @@ import org.whispersystems.textsecuregcm.s3.PolicySigner;
|
||||
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
|
||||
import org.whispersystems.textsecuregcm.securebackup.SecureBackupClient;
|
||||
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
|
||||
import org.whispersystems.textsecuregcm.spam.FilterSpam;
|
||||
import org.whispersystems.textsecuregcm.spam.RateLimitChallengeListener;
|
||||
import org.whispersystems.textsecuregcm.spam.ReportSpamTokenProvider;
|
||||
import org.whispersystems.textsecuregcm.spam.SpamFilter;
|
||||
import org.whispersystems.textsecuregcm.sqs.DirectoryQueue;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountCleaner;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountDatabaseCrawler;
|
||||
@@ -448,29 +449,25 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
config.getBraintree().supportedCurrencies(), config.getBraintree().merchantAccounts(),
|
||||
config.getBraintree().graphqlUrl(), config.getBraintree().circuitBreaker(), subscriptionProcessorExecutor);
|
||||
|
||||
ExternalServiceCredentialGenerator directoryCredentialsGenerator = new ExternalServiceCredentialGenerator(
|
||||
config.getDirectoryConfiguration().getDirectoryClientConfiguration().getUserAuthenticationTokenSharedSecret(),
|
||||
config.getDirectoryConfiguration().getDirectoryClientConfiguration().getUserAuthenticationTokenUserIdSecret());
|
||||
ExternalServiceCredentialGenerator directoryV2CredentialsGenerator = new ExternalServiceCredentialGenerator(
|
||||
config.getDirectoryV2Configuration().getDirectoryV2ClientConfiguration().getUserAuthenticationTokenSharedSecret(),
|
||||
config.getDirectoryV2Configuration().getDirectoryV2ClientConfiguration().getUserIdTokenSharedSecret(),
|
||||
true, false);
|
||||
ExternalServiceCredentialsGenerator directoryCredentialsGenerator = DirectoryController.credentialsGenerator(
|
||||
config.getDirectoryConfiguration().getDirectoryClientConfiguration());
|
||||
ExternalServiceCredentialsGenerator directoryV2CredentialsGenerator = DirectoryV2Controller.credentialsGenerator(
|
||||
config.getDirectoryV2Configuration().getDirectoryV2ClientConfiguration());
|
||||
ExternalServiceCredentialsGenerator storageCredentialsGenerator = SecureStorageController.credentialsGenerator(
|
||||
config.getSecureStorageServiceConfiguration());
|
||||
ExternalServiceCredentialsGenerator backupCredentialsGenerator = SecureBackupController.credentialsGenerator(
|
||||
config.getSecureBackupServiceConfiguration());
|
||||
ExternalServiceCredentialsGenerator paymentsCredentialsGenerator = PaymentsController.credentialsGenerator(
|
||||
config.getPaymentsServiceConfiguration());
|
||||
ExternalServiceCredentialsGenerator artCredentialsGenerator = ArtController.credentialsGenerator(
|
||||
config.getArtServiceConfiguration());
|
||||
ExternalServiceCredentialsGenerator svr2CredentialsGenerator = SecureValueRecovery2Controller.credentialsGenerator(
|
||||
config.getSvr2Configuration());
|
||||
|
||||
dynamicConfigurationManager.start();
|
||||
|
||||
ExperimentEnrollmentManager experimentEnrollmentManager = new ExperimentEnrollmentManager(dynamicConfigurationManager);
|
||||
|
||||
ExternalServiceCredentialGenerator storageCredentialsGenerator = new ExternalServiceCredentialGenerator(
|
||||
config.getSecureStorageServiceConfiguration().getUserAuthenticationTokenSharedSecret(), true);
|
||||
ExternalServiceCredentialGenerator backupCredentialsGenerator = new ExternalServiceCredentialGenerator(
|
||||
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);
|
||||
|
||||
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());
|
||||
@@ -652,8 +649,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
ImmutableSet.of(AuthenticatedAccount.class, DisabledPermittedAuthenticatedAccount.class)));
|
||||
environment.jersey().register(new WebsocketRefreshApplicationEventListener(accountsManager, clientPresenceManager));
|
||||
environment.jersey().register(new TimestampResponseFilter());
|
||||
environment.jersey().register(new VoiceVerificationController(config.getVoiceVerificationConfiguration().getUrl(),
|
||||
config.getVoiceVerificationConfiguration().getLocales()));
|
||||
|
||||
///
|
||||
WebSocketEnvironment<AuthenticatedAccount> webSocketEnvironment = new WebSocketEnvironment<>(environment,
|
||||
@@ -678,6 +673,51 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
|
||||
environment.jersey().register(new KeysController(rateLimiters, keys, accountsManager));
|
||||
|
||||
boolean registeredSpamFilter = false;
|
||||
ReportSpamTokenProvider reportSpamTokenProvider = null;
|
||||
|
||||
for (final SpamFilter filter : ServiceLoader.load(SpamFilter.class)) {
|
||||
if (filter.getClass().isAnnotationPresent(FilterSpam.class)) {
|
||||
try {
|
||||
filter.configure(config.getSpamFilterConfiguration().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.");
|
||||
}
|
||||
|
||||
filter.getReportedMessageListeners().forEach(reportMessageManager::addListener);
|
||||
|
||||
environment.lifecycle().manage(filter);
|
||||
environment.jersey().register(filter);
|
||||
webSocketEnvironment.jersey().register(filter);
|
||||
|
||||
log.info("Registered spam filter: {}", filter.getClass().getName());
|
||||
registeredSpamFilter = true;
|
||||
} catch (final Exception e) {
|
||||
log.warn("Failed to register spam filter: {}", filter.getClass().getName(), e);
|
||||
}
|
||||
} else {
|
||||
log.warn("Spam filter {} not annotated with @FilterSpam and will not be installed",
|
||||
filter.getClass().getName());
|
||||
}
|
||||
|
||||
if (filter instanceof RateLimitChallengeListener) {
|
||||
log.info("Registered rate limit challenge listener: {}", filter.getClass().getName());
|
||||
rateLimitChallengeManager.addListener((RateLimitChallengeListener) filter);
|
||||
}
|
||||
}
|
||||
|
||||
if (!registeredSpamFilter) {
|
||||
log.warn("No spam filters installed");
|
||||
}
|
||||
|
||||
if (reportSpamTokenProvider == null) {
|
||||
reportSpamTokenProvider = ReportSpamTokenProvider.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()),
|
||||
@@ -689,7 +729,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
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 MessageController(rateLimiters, messageSender, receiptSender, accountsManager, deletedAccountsManager, messagesManager, pushNotificationManager, reportMessageManager, multiRecipientMessageExecutor,
|
||||
reportSpamTokenProvider),
|
||||
new PaymentsController(currencyManager, paymentsCredentialsGenerator),
|
||||
new ProfileController(clock, rateLimiters, accountsManager, profilesManager, dynamicConfigurationManager,
|
||||
profileBadgeConverter, config.getBadges(), cdnS3Client, profileCdnPolicyGenerator, profileCdnPolicySigner,
|
||||
@@ -698,8 +739,9 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
new RemoteConfigController(remoteConfigsManager, adminEventLogger,
|
||||
config.getRemoteConfigConfiguration().getAuthorizedTokens(),
|
||||
config.getRemoteConfigConfiguration().getGlobalConfig()),
|
||||
new SecureBackupController(backupCredentialsGenerator),
|
||||
new SecureBackupController(backupCredentialsGenerator, accountsManager),
|
||||
new SecureStorageController(storageCredentialsGenerator),
|
||||
new SecureValueRecovery2Controller(svr2CredentialsGenerator),
|
||||
new StickerController(rateLimiters, config.getCdnConfiguration().getAccessKey(),
|
||||
config.getCdnConfiguration().getAccessSecret(), config.getCdnConfiguration().getRegion(),
|
||||
config.getCdnConfiguration().getBucket())
|
||||
@@ -715,37 +757,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
webSocketEnvironment.jersey().register(controller);
|
||||
}
|
||||
|
||||
boolean registeredAbusiveMessageFilter = false;
|
||||
|
||||
for (final AbusiveMessageFilter filter : ServiceLoader.load(AbusiveMessageFilter.class)) {
|
||||
if (filter.getClass().isAnnotationPresent(FilterAbusiveMessages.class)) {
|
||||
try {
|
||||
filter.configure(config.getAbusiveMessageFilterConfiguration().getEnvironment());
|
||||
|
||||
environment.lifecycle().manage(filter);
|
||||
environment.jersey().register(filter);
|
||||
webSocketEnvironment.jersey().register(filter);
|
||||
|
||||
log.info("Registered abusive message filter: {}", filter.getClass().getName());
|
||||
registeredAbusiveMessageFilter = true;
|
||||
} catch (final Exception e) {
|
||||
log.warn("Failed to register abusive message filter: {}", filter.getClass().getName(), e);
|
||||
}
|
||||
} else {
|
||||
log.warn("Abusive message filter {} not annotated with @FilterAbusiveMessages and will not be installed",
|
||||
filter.getClass().getName());
|
||||
}
|
||||
|
||||
if (filter instanceof RateLimitChallengeListener) {
|
||||
log.info("Registered rate limit challenge listener: {}", filter.getClass().getName());
|
||||
rateLimitChallengeManager.addListener((RateLimitChallengeListener) filter);
|
||||
}
|
||||
}
|
||||
|
||||
if (!registeredAbusiveMessageFilter) {
|
||||
log.warn("No abusive message filters installed");
|
||||
}
|
||||
|
||||
WebSocketEnvironment<AuthenticatedAccount> provisioningEnvironment = new WebSocketEnvironment<>(environment,
|
||||
webSocketEnvironment.getRequestLog(), 60000);
|
||||
provisioningEnvironment.jersey().register(new WebsocketRefreshApplicationEventListener(accountsManager, clientPresenceManager));
|
||||
|
||||
-33
@@ -1,33 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2021 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.abuse;
|
||||
|
||||
import io.dropwizard.lifecycle.Managed;
|
||||
import javax.ws.rs.container.ContainerRequestFilter;
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* An abusive message filter is a {@link ContainerRequestFilter} that filters requests to message-sending endpoints to
|
||||
* detect and respond to patterns of abusive behavior.
|
||||
* <p/>
|
||||
* Abusive message filters are managed components that are generally loaded dynamically via a
|
||||
* {@link java.util.ServiceLoader}. Their {@link #configure(String)} method will be called prior to be adding to the
|
||||
* server's pool of {@link Managed} objects.
|
||||
* <p/>
|
||||
* Abusive message filters must be annotated with {@link FilterAbusiveMessages}, a name binding annotation that
|
||||
* restricts the endpoints to which the filter may apply.
|
||||
*/
|
||||
public interface AbusiveMessageFilter extends ContainerRequestFilter, Managed {
|
||||
|
||||
/**
|
||||
* Configures this abusive message filter. This method will be called before the filter is added to the server's pool
|
||||
* of managed objects and before the server processes any requests.
|
||||
*
|
||||
* @param environmentName the name of the environment in which this filter is running (e.g. "staging" or "production")
|
||||
* @throws IOException if the filter could not read its configuration source for any reason
|
||||
*/
|
||||
void configure(String environmentName) throws IOException;
|
||||
}
|
||||
-86
@@ -1,86 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2020 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
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;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.SecureRandom;
|
||||
|
||||
public class AuthenticationCredentials {
|
||||
private static final String V2_PREFIX = "2.";
|
||||
|
||||
private final String hashedAuthenticationToken;
|
||||
private final String salt;
|
||||
|
||||
public enum Version {
|
||||
V1,
|
||||
V2,
|
||||
}
|
||||
|
||||
public static final Version CURRENT_VERSION = Version.V2;
|
||||
|
||||
public AuthenticationCredentials(String hashedAuthenticationToken, String salt) {
|
||||
this.hashedAuthenticationToken = hashedAuthenticationToken;
|
||||
this.salt = salt;
|
||||
}
|
||||
|
||||
public AuthenticationCredentials(String authenticationToken) {
|
||||
this.salt = String.valueOf(Util.ensureNonNegativeInt(new SecureRandom().nextInt()));
|
||||
this.hashedAuthenticationToken = getV2HashedValue(salt, authenticationToken);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
public AuthenticationCredentials v1ForTesting(String authenticationToken) {
|
||||
String salt = String.valueOf(Util.ensureNonNegativeInt(new SecureRandom().nextInt()));
|
||||
return new AuthenticationCredentials(getV1HashedValue(salt, authenticationToken), salt);
|
||||
}
|
||||
|
||||
public Version getVersion() {
|
||||
if (this.hashedAuthenticationToken.startsWith(V2_PREFIX)) {
|
||||
return Version.V2;
|
||||
}
|
||||
return Version.V1;
|
||||
}
|
||||
|
||||
public String getHashedAuthenticationToken() {
|
||||
return hashedAuthenticationToken;
|
||||
}
|
||||
|
||||
public String getSalt() {
|
||||
return salt;
|
||||
}
|
||||
|
||||
public boolean verify(String authenticationToken) {
|
||||
final String theirValue = switch (getVersion()) {
|
||||
case V1 -> getV1HashedValue(salt, authenticationToken);
|
||||
case V2 -> getV2HashedValue(salt, authenticationToken);
|
||||
};
|
||||
return MessageDigest.isEqual(theirValue.getBytes(StandardCharsets.UTF_8), this.hashedAuthenticationToken.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
private static String getV1HashedValue(String salt, String token) {
|
||||
try {
|
||||
return new String(Hex.encodeHex(MessageDigest.getInstance("SHA1").digest((salt + token).getBytes(StandardCharsets.UTF_8))));
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
}
|
||||
|
||||
private static final byte[] AUTH_TOKEN_HKDF_INFO = "authtoken".getBytes(StandardCharsets.UTF_8);
|
||||
private static String getV2HashedValue(String salt, String token) {
|
||||
byte[] secret = HKDF.deriveSecrets(
|
||||
token.getBytes(StandardCharsets.UTF_8), // key
|
||||
salt.getBytes(StandardCharsets.UTF_8), // salt
|
||||
AUTH_TOKEN_HKDF_INFO,
|
||||
32);
|
||||
return V2_PREFIX + Hex.encodeHexString(secret);
|
||||
}
|
||||
}
|
||||
+24
-12
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2013-2021 Signal Messenger, LLC
|
||||
* Copyright 2013 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
@@ -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,26 +104,34 @@ 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();
|
||||
if (deviceAuthenticationCredentials.verify(basicCredentials.getPassword())) {
|
||||
SaltedTokenHash deviceSaltedTokenHash = device.get().getAuthTokenHash();
|
||||
if (deviceSaltedTokenHash.verify(basicCredentials.getPassword())) {
|
||||
succeeded = true;
|
||||
Account authenticatedAccount = updateLastSeen(account.get(), device.get());
|
||||
if (deviceAuthenticationCredentials.getVersion() != AuthenticationCredentials.CURRENT_VERSION) {
|
||||
if (deviceSaltedTokenHash.getVersion() != SaltedTokenHash.CURRENT_VERSION) {
|
||||
authenticatedAccount = accountsManager.updateDeviceAuthentication(
|
||||
authenticatedAccount,
|
||||
device.get(),
|
||||
new AuthenticationCredentials(basicCredentials.getPassword())); // new credentials have current version
|
||||
SaltedTokenHash.generateFor(basicCredentials.getPassword())); // new credentials have current version
|
||||
}
|
||||
return Optional.of(new AuthenticatedAccount(
|
||||
new RefreshingAccountAndDeviceSupplier(authenticatedAccount, device.get().getId(), accountsManager)));
|
||||
@@ -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);
|
||||
|
||||
-106
@@ -1,106 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2021 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.auth;
|
||||
|
||||
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.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
public class ExternalServiceCredentialGenerator {
|
||||
|
||||
private final byte[] key;
|
||||
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, true);
|
||||
}
|
||||
|
||||
public ExternalServiceCredentialGenerator(byte[] key, boolean 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, true);
|
||||
}
|
||||
|
||||
public ExternalServiceCredentialGenerator(byte[] key, byte[] userIdKey, boolean usernameDerivation,
|
||||
boolean prependUsername) {
|
||||
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;
|
||||
}
|
||||
|
||||
public ExternalServiceCredentials generateFor(String identity) {
|
||||
Mac mac = getMacInstance();
|
||||
String username = getUserId(identity, mac, usernameDerivation);
|
||||
long currentTimeSeconds = clock.millis() / 1000;
|
||||
String prefix = username + ":" + currentTimeSeconds;
|
||||
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) {
|
||||
final HexFormat hex = HexFormat.of();
|
||||
if (usernameDerivation) return hex.formatHex(Util.truncate(getHmac(userIdKey, number.getBytes(), mac), 10));
|
||||
else return number;
|
||||
}
|
||||
|
||||
private Mac getMacInstance() {
|
||||
try {
|
||||
return Mac.getInstance("HmacSHA256");
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] getHmac(byte[] key, byte[] input, Mac mac) {
|
||||
try {
|
||||
mac.init(new SecretKeySpec(key, "HmacSHA256"));
|
||||
return mac.doFinal(input);
|
||||
} catch (InvalidKeyException e) {
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+1
-23
@@ -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;
|
||||
}
|
||||
}
|
||||
+207
@@ -0,0 +1,207 @@
|
||||
/*
|
||||
* Copyright 2013 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.auth;
|
||||
|
||||
import static java.util.Objects.requireNonNull;
|
||||
import static org.whispersystems.textsecuregcm.util.HmacUtils.hmac256ToHexString;
|
||||
import static org.whispersystems.textsecuregcm.util.HmacUtils.hmac256TruncatedToHexString;
|
||||
import static org.whispersystems.textsecuregcm.util.HmacUtils.hmacHexStringsEqual;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.commons.lang3.Validate;
|
||||
|
||||
public class ExternalServiceCredentialsGenerator {
|
||||
|
||||
private static final int TRUNCATE_LENGTH = 10;
|
||||
|
||||
private static final String DELIMITER = ":";
|
||||
|
||||
private final byte[] key;
|
||||
|
||||
private final byte[] userDerivationKey;
|
||||
|
||||
private final boolean prependUsername;
|
||||
|
||||
private final boolean truncateSignature;
|
||||
|
||||
private final Clock clock;
|
||||
|
||||
|
||||
public static ExternalServiceCredentialsGenerator.Builder builder(final byte[] key) {
|
||||
return new Builder(key);
|
||||
}
|
||||
|
||||
private ExternalServiceCredentialsGenerator(
|
||||
final byte[] key,
|
||||
final byte[] userDerivationKey,
|
||||
final boolean prependUsername,
|
||||
final boolean truncateSignature,
|
||||
final Clock clock) {
|
||||
this.key = requireNonNull(key);
|
||||
this.userDerivationKey = requireNonNull(userDerivationKey);
|
||||
this.prependUsername = prependUsername;
|
||||
this.truncateSignature = truncateSignature;
|
||||
this.clock = requireNonNull(clock);
|
||||
}
|
||||
|
||||
/**
|
||||
* A convenience method for the case of identity in the form of {@link UUID}.
|
||||
* @param uuid identity to generate credentials for
|
||||
* @return an instance of {@link ExternalServiceCredentials}
|
||||
*/
|
||||
public ExternalServiceCredentials generateForUuid(final UUID uuid) {
|
||||
return generateFor(uuid.toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates `ExternalServiceCredentials` for the given identity following this generator's configuration.
|
||||
* @param identity identity string to generate credentials for
|
||||
* @return an instance of {@link ExternalServiceCredentials}
|
||||
*/
|
||||
public ExternalServiceCredentials generateFor(final String identity) {
|
||||
final String username = shouldDeriveUsername()
|
||||
? hmac256TruncatedToHexString(userDerivationKey, identity, TRUNCATE_LENGTH)
|
||||
: identity;
|
||||
|
||||
final long currentTimeSeconds = currentTimeSeconds();
|
||||
|
||||
final String dataToSign = username + DELIMITER + currentTimeSeconds;
|
||||
|
||||
final String signature = truncateSignature
|
||||
? hmac256TruncatedToHexString(key, dataToSign, TRUNCATE_LENGTH)
|
||||
: hmac256ToHexString(key, dataToSign);
|
||||
|
||||
final String token = (prependUsername ? dataToSign : currentTimeSeconds) + DELIMITER + signature;
|
||||
|
||||
return new ExternalServiceCredentials(username, token);
|
||||
}
|
||||
|
||||
/**
|
||||
* In certain cases, identity (as it was passed to `generateFor` method)
|
||||
* is a part of the signature (`password`, in terms of `ExternalServiceCredentials`) string itself.
|
||||
* For such cases, this method returns the value of the identity string.
|
||||
* @param password `password` part of `ExternalServiceCredentials`
|
||||
* @return non-empty optional with an identity string value, or empty if value can't be extracted.
|
||||
*/
|
||||
public Optional<String> identityFromSignature(final String password) {
|
||||
// for some generators, identity in the clear is just not a part of the password
|
||||
if (!prependUsername || shouldDeriveUsername() || StringUtils.isBlank(password)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
// checking for the case of unexpected format
|
||||
return StringUtils.countMatches(password, DELIMITER) == 2
|
||||
? Optional.of(password.substring(0, password.indexOf(DELIMITER)))
|
||||
: Optional.empty();
|
||||
}
|
||||
|
||||
/**
|
||||
* Given an instance of {@link ExternalServiceCredentials} object, checks that the password
|
||||
* matches the username taking into accound this generator's configuration.
|
||||
* @param credentials an instance of {@link ExternalServiceCredentials}
|
||||
* @return An optional with a timestamp (seconds) of when the credentials were generated,
|
||||
* or an empty optional if the password doesn't match the username for any reason (including malformed data)
|
||||
*/
|
||||
public Optional<Long> validateAndGetTimestamp(final ExternalServiceCredentials credentials) {
|
||||
final String[] parts = requireNonNull(credentials).password().split(DELIMITER);
|
||||
final String timestampSeconds;
|
||||
final String actualSignature;
|
||||
|
||||
// making sure password format matches our expectations based on the generator configuration
|
||||
if (parts.length == 3 && prependUsername) {
|
||||
final String username = parts[0];
|
||||
// username has to match the one from `credentials`
|
||||
if (!credentials.username().equals(username)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
timestampSeconds = parts[1];
|
||||
actualSignature = parts[2];
|
||||
} else if (parts.length == 2 && !prependUsername) {
|
||||
timestampSeconds = parts[0];
|
||||
actualSignature = parts[1];
|
||||
} else {
|
||||
// unexpected password format
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
final String signedData = credentials.username() + DELIMITER + timestampSeconds;
|
||||
final String expectedSignature = truncateSignature
|
||||
? hmac256TruncatedToHexString(key, signedData, TRUNCATE_LENGTH)
|
||||
: hmac256ToHexString(key, signedData);
|
||||
|
||||
// if the signature is valid it's safe to parse the `timestampSeconds` string into Long
|
||||
return hmacHexStringsEqual(expectedSignature, actualSignature)
|
||||
? Optional.of(Long.valueOf(timestampSeconds))
|
||||
: Optional.empty();
|
||||
}
|
||||
|
||||
/**
|
||||
* Given an instance of {@link ExternalServiceCredentials} object and the max allowed age for those credentials,
|
||||
* checks if credentials are valid and not expired.
|
||||
* @param credentials an instance of {@link ExternalServiceCredentials}
|
||||
* @param maxAgeSeconds age in seconds
|
||||
* @return An optional with a timestamp (seconds) of when the credentials were generated,
|
||||
* or an empty optional if the password doesn't match the username for any reason (including malformed data)
|
||||
*/
|
||||
public Optional<Long> validateAndGetTimestamp(final ExternalServiceCredentials credentials, final long maxAgeSeconds) {
|
||||
return validateAndGetTimestamp(credentials)
|
||||
.filter(ts -> currentTimeSeconds() - ts <= maxAgeSeconds);
|
||||
}
|
||||
|
||||
private boolean shouldDeriveUsername() {
|
||||
return userDerivationKey.length > 0;
|
||||
}
|
||||
|
||||
private long currentTimeSeconds() {
|
||||
return clock.instant().getEpochSecond();
|
||||
}
|
||||
|
||||
public static class Builder {
|
||||
|
||||
private final byte[] key;
|
||||
|
||||
private byte[] userDerivationKey = new byte[0];
|
||||
|
||||
private boolean prependUsername = true;
|
||||
|
||||
private boolean truncateSignature = true;
|
||||
|
||||
private Clock clock = Clock.systemUTC();
|
||||
|
||||
|
||||
private Builder(final byte[] key) {
|
||||
this.key = requireNonNull(key);
|
||||
}
|
||||
|
||||
public Builder withUserDerivationKey(final byte[] userDerivationKey) {
|
||||
Validate.isTrue(requireNonNull(userDerivationKey).length > 0, "userDerivationKey must not be empty");
|
||||
this.userDerivationKey = userDerivationKey;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder withClock(final Clock clock) {
|
||||
this.clock = requireNonNull(clock);
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder prependUsername(final boolean prependUsername) {
|
||||
this.prependUsername = prependUsername;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder truncateSignature(final boolean truncateSignature) {
|
||||
this.truncateSignature = truncateSignature;
|
||||
return this;
|
||||
}
|
||||
|
||||
public ExternalServiceCredentialsGenerator build() {
|
||||
return new ExternalServiceCredentialsGenerator(
|
||||
key, userDerivationKey, prependUsername, truncateSignature, clock);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
/*
|
||||
* Copyright 2013 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.auth;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.SecureRandom;
|
||||
import org.apache.commons.codec.binary.Hex;
|
||||
import org.signal.libsignal.protocol.kdf.HKDF;
|
||||
|
||||
public record SaltedTokenHash(String hash, String salt) {
|
||||
|
||||
public enum Version {
|
||||
V1,
|
||||
V2,
|
||||
}
|
||||
|
||||
public static final Version CURRENT_VERSION = Version.V2;
|
||||
|
||||
private static final String V2_PREFIX = "2.";
|
||||
|
||||
private static final byte[] AUTH_TOKEN_HKDF_INFO = "authtoken".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
private static final int SALT_SIZE = 16;
|
||||
|
||||
private static final SecureRandom SECURE_RANDOM = new SecureRandom();
|
||||
|
||||
|
||||
public static SaltedTokenHash generateFor(final String token) {
|
||||
final String salt = generateSalt();
|
||||
final String hash = calculateV2Hash(salt, token);
|
||||
return new SaltedTokenHash(hash, salt);
|
||||
}
|
||||
|
||||
public Version getVersion() {
|
||||
return hash.startsWith(V2_PREFIX) ? Version.V2 : Version.V1;
|
||||
}
|
||||
|
||||
public boolean verify(final String token) {
|
||||
final String theirValue = switch (getVersion()) {
|
||||
case V1 -> calculateV1Hash(salt, token);
|
||||
case V2 -> calculateV2Hash(salt, token);
|
||||
};
|
||||
return MessageDigest.isEqual(
|
||||
theirValue.getBytes(StandardCharsets.UTF_8),
|
||||
hash.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
private static String generateSalt() {
|
||||
final byte[] salt = new byte[SALT_SIZE];
|
||||
SECURE_RANDOM.nextBytes(salt);
|
||||
return Hex.encodeHexString(salt);
|
||||
}
|
||||
|
||||
private static String calculateV1Hash(final String salt, final String token) {
|
||||
try {
|
||||
return new String(
|
||||
Hex.encodeHex(MessageDigest.getInstance("SHA1").digest((salt + token).getBytes(StandardCharsets.UTF_8))));
|
||||
} catch (final NoSuchAlgorithmException e) {
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
}
|
||||
|
||||
private static String calculateV2Hash(final String salt, final String token) {
|
||||
final byte[] secret = HKDF.deriveSecrets(
|
||||
token.getBytes(StandardCharsets.UTF_8), // key
|
||||
salt.getBytes(StandardCharsets.UTF_8), // salt
|
||||
AUTH_TOKEN_HKDF_INFO,
|
||||
32);
|
||||
return V2_PREFIX + Hex.encodeHexString(secret);
|
||||
}
|
||||
}
|
||||
+4
-5
@@ -1,16 +1,15 @@
|
||||
/*
|
||||
* Copyright 2013-2020 Signal Messenger, LLC
|
||||
* Copyright 2013 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.auth;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import javax.annotation.Nullable;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
|
||||
public class StoredRegistrationLock {
|
||||
@@ -56,7 +55,7 @@ public class StoredRegistrationLock {
|
||||
|
||||
public boolean verify(@Nullable String clientRegistrationLock) {
|
||||
if (hasLockAndSalt() && Util.nonEmpty(clientRegistrationLock)) {
|
||||
AuthenticationCredentials credentials = new AuthenticationCredentials(registrationLock.get(), registrationLockSalt.get());
|
||||
SaltedTokenHash credentials = new SaltedTokenHash(registrationLock.get(), registrationLockSalt.get());
|
||||
return credentials.verify(clientRegistrationLock);
|
||||
} else {
|
||||
return false;
|
||||
|
||||
-1
@@ -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);
|
||||
|
||||
+3
-25
@@ -1,33 +1,11 @@
|
||||
/*
|
||||
* Copyright 2013-2020 Signal Messenger, LLC
|
||||
* Copyright 2013-2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonCreator;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import org.whispersystems.textsecuregcm.util.ExactlySize;
|
||||
|
||||
public class DirectoryV2ClientConfiguration {
|
||||
|
||||
private final byte[] userAuthenticationTokenSharedSecret;
|
||||
private final byte[] userIdTokenSharedSecret;
|
||||
|
||||
@JsonCreator
|
||||
public DirectoryV2ClientConfiguration(
|
||||
@JsonProperty("userAuthenticationTokenSharedSecret") final byte[] userAuthenticationTokenSharedSecret,
|
||||
@JsonProperty("userIdTokenSharedSecret") final byte[] userIdTokenSharedSecret) {
|
||||
this.userAuthenticationTokenSharedSecret = userAuthenticationTokenSharedSecret;
|
||||
this.userIdTokenSharedSecret = userIdTokenSharedSecret;
|
||||
}
|
||||
|
||||
@ExactlySize({32})
|
||||
public byte[] getUserAuthenticationTokenSharedSecret() {
|
||||
return userAuthenticationTokenSharedSecret;
|
||||
}
|
||||
|
||||
@ExactlySize({32})
|
||||
public byte[] getUserIdTokenSharedSecret() {
|
||||
return userIdTokenSharedSecret;
|
||||
}
|
||||
public record DirectoryV2ClientConfiguration(@ExactlySize({32}) byte[] userAuthenticationTokenSharedSecret,
|
||||
@ExactlySize({32}) byte[] userIdTokenSharedSecret) {
|
||||
}
|
||||
+11
-2
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2013-2020 Signal Messenger, LLC
|
||||
* Copyright 2013 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
@@ -74,6 +74,9 @@ public class RateLimitsConfiguration {
|
||||
@JsonProperty
|
||||
private RateLimitConfiguration stories = new RateLimitConfiguration(10_000, 10_000 / (24.0 * 60.0));
|
||||
|
||||
@JsonProperty
|
||||
private RateLimitConfiguration backupAuthCheck = new RateLimitConfiguration(100, 100 / (24.0 * 60.0));
|
||||
|
||||
public RateLimitConfiguration getAutoBlock() {
|
||||
return autoBlock;
|
||||
}
|
||||
@@ -158,7 +161,13 @@ public class RateLimitsConfiguration {
|
||||
return checkAccountExistence;
|
||||
}
|
||||
|
||||
public RateLimitConfiguration getStories() { return stories; }
|
||||
public RateLimitConfiguration getStories() {
|
||||
return stories;
|
||||
}
|
||||
|
||||
public RateLimitConfiguration getBackupAuthCheck() {
|
||||
return backupAuthCheck;
|
||||
}
|
||||
|
||||
public static class RateLimitConfiguration {
|
||||
@JsonProperty
|
||||
|
||||
+16
-54
@@ -1,71 +1,33 @@
|
||||
/*
|
||||
* Copyright 2013-2020 Signal Messenger, LLC
|
||||
* Copyright 2013 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import java.util.List;
|
||||
import javax.validation.Valid;
|
||||
import javax.validation.constraints.NotBlank;
|
||||
import javax.validation.constraints.NotEmpty;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import org.apache.commons.codec.DecoderException;
|
||||
import org.apache.commons.codec.binary.Hex;
|
||||
import java.util.List;
|
||||
|
||||
public class SecureStorageServiceConfiguration {
|
||||
public record SecureStorageServiceConfiguration(@NotEmpty String userAuthenticationTokenSharedSecret,
|
||||
@NotBlank String uri,
|
||||
@NotEmpty List<@NotBlank String> storageCaCertificates,
|
||||
@Valid CircuitBreakerConfiguration circuitBreaker,
|
||||
@Valid RetryConfiguration retry) {
|
||||
|
||||
@NotEmpty
|
||||
@JsonProperty
|
||||
private String userAuthenticationTokenSharedSecret;
|
||||
public SecureStorageServiceConfiguration {
|
||||
if (circuitBreaker == null) {
|
||||
circuitBreaker = new CircuitBreakerConfiguration();
|
||||
}
|
||||
if (retry == null) {
|
||||
retry = new RetryConfiguration();
|
||||
}
|
||||
}
|
||||
|
||||
@NotBlank
|
||||
@JsonProperty
|
||||
private String uri;
|
||||
|
||||
@NotEmpty
|
||||
@JsonProperty
|
||||
private List<@NotBlank String> storageCaCertificates;
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
@JsonProperty
|
||||
private CircuitBreakerConfiguration circuitBreaker = new CircuitBreakerConfiguration();
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
@JsonProperty
|
||||
private RetryConfiguration retry = new RetryConfiguration();
|
||||
|
||||
public byte[] getUserAuthenticationTokenSharedSecret() throws DecoderException {
|
||||
public byte[] decodeUserAuthenticationTokenSharedSecret() throws DecoderException {
|
||||
return Hex.decodeHex(userAuthenticationTokenSharedSecret.toCharArray());
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
public void setUri(final String uri) {
|
||||
this.uri = uri;
|
||||
}
|
||||
|
||||
public String getUri() {
|
||||
return uri;
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
public void setStorageCaCertificates(final List<String> certificatePem) {
|
||||
this.storageCaCertificates = certificatePem;
|
||||
}
|
||||
|
||||
public List<String> getStorageCaCertificates() {
|
||||
return storageCaCertificates;
|
||||
}
|
||||
|
||||
public CircuitBreakerConfiguration getCircuitBreakerConfiguration() {
|
||||
return circuitBreaker;
|
||||
}
|
||||
|
||||
public RetryConfiguration getRetryConfiguration() {
|
||||
return retry;
|
||||
}
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
/*
|
||||
* Copyright 2013-2020 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import org.whispersystems.textsecuregcm.util.ExactlySize;
|
||||
|
||||
public record SecureValueRecovery2Configuration(
|
||||
@ExactlySize({32}) byte[] userAuthenticationTokenSharedSecret,
|
||||
@ExactlySize({32}) byte[] userIdTokenSharedSecret) {
|
||||
}
|
||||
+2
-2
@@ -9,14 +9,14 @@ import com.fasterxml.jackson.annotation.JsonCreator;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import javax.validation.constraints.NotBlank;
|
||||
|
||||
public class AbusiveMessageFilterConfiguration {
|
||||
public class SpamFilterConfiguration {
|
||||
|
||||
@JsonProperty
|
||||
@NotBlank
|
||||
private final String environment;
|
||||
|
||||
@JsonCreator
|
||||
public AbusiveMessageFilterConfiguration(@JsonProperty("environment") final String environment) {
|
||||
public SpamFilterConfiguration(@JsonProperty("environment") final String environment) {
|
||||
this.environment = environment;
|
||||
}
|
||||
|
||||
+6
-21
@@ -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;
|
||||
}
|
||||
}
|
||||
-35
@@ -1,35 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2020 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import javax.validation.Valid;
|
||||
import javax.validation.constraints.NotEmpty;
|
||||
import javax.validation.constraints.NotNull;
|
||||
|
||||
public class VoiceVerificationConfiguration {
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
@NotEmpty
|
||||
private String url;
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
@NotNull
|
||||
private List<String> locales;
|
||||
|
||||
public String getUrl() {
|
||||
return url;
|
||||
}
|
||||
|
||||
public Set<String> getLocales() {
|
||||
return new HashSet<>(locales);
|
||||
}
|
||||
}
|
||||
-14
@@ -1,14 +0,0 @@
|
||||
package org.whispersystems.textsecuregcm.configuration.dynamic;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import java.time.Duration;
|
||||
|
||||
public class DynamicAbusiveHostRulesConfiguration {
|
||||
|
||||
@JsonProperty
|
||||
private Duration expirationTime = Duration.ofDays(1);
|
||||
|
||||
public Duration getExpirationTime() {
|
||||
return expirationTime;
|
||||
}
|
||||
}
|
||||
-9
@@ -1,7 +1,6 @@
|
||||
package org.whispersystems.textsecuregcm.configuration.dynamic;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import java.util.Collections;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
@@ -48,10 +47,6 @@ public class DynamicConfiguration {
|
||||
@Valid
|
||||
private DynamicTurnConfiguration turn = new DynamicTurnConfiguration();
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
DynamicAbusiveHostRulesConfiguration abusiveHostRules = new DynamicAbusiveHostRulesConfiguration();
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
DynamicMessagePersisterConfiguration messagePersister = new DynamicMessagePersisterConfiguration();
|
||||
@@ -102,10 +97,6 @@ public class DynamicConfiguration {
|
||||
return turn;
|
||||
}
|
||||
|
||||
public DynamicAbusiveHostRulesConfiguration getAbusiveHostRules() {
|
||||
return abusiveHostRules;
|
||||
}
|
||||
|
||||
public DynamicMessagePersisterConfiguration getMessagePersisterConfiguration() {
|
||||
return messagePersister;
|
||||
}
|
||||
|
||||
+114
-37
@@ -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.controllers;
|
||||
@@ -29,6 +29,7 @@ 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;
|
||||
@@ -54,14 +55,13 @@ import javax.ws.rs.core.Response.Status;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.abuse.FilterAbusiveMessages;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticationCredentials;
|
||||
import org.whispersystems.textsecuregcm.auth.BasicAuthorizationHeader;
|
||||
import org.whispersystems.textsecuregcm.auth.ChangesDeviceEnabledState;
|
||||
import org.whispersystems.textsecuregcm.auth.DisabledPermittedAuthenticatedAccount;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialGenerator;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
|
||||
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
|
||||
import org.whispersystems.textsecuregcm.auth.StoredRegistrationLock;
|
||||
import org.whispersystems.textsecuregcm.auth.StoredVerificationCode;
|
||||
import org.whispersystems.textsecuregcm.auth.TurnToken;
|
||||
@@ -86,6 +86,7 @@ import org.whispersystems.textsecuregcm.entities.ReserveUsernameResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.StaleDevices;
|
||||
import org.whispersystems.textsecuregcm.entities.UsernameRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.UsernameResponse;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimitedByIp;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
@@ -95,6 +96,7 @@ import org.whispersystems.textsecuregcm.push.PushNotificationManager;
|
||||
import org.whispersystems.textsecuregcm.registration.ClientType;
|
||||
import org.whispersystems.textsecuregcm.registration.MessageTransport;
|
||||
import org.whispersystems.textsecuregcm.registration.RegistrationServiceClient;
|
||||
import org.whispersystems.textsecuregcm.spam.FilterSpam;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ChangeNumberManager;
|
||||
@@ -129,7 +131,7 @@ 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_NAME = DistributionSummary
|
||||
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))
|
||||
@@ -164,7 +166,7 @@ public class AccountController {
|
||||
private final Map<String, Integer> testDevices;
|
||||
private final CaptchaChecker captchaChecker;
|
||||
private final PushNotificationManager pushNotificationManager;
|
||||
private final ExternalServiceCredentialGenerator backupServiceCredentialGenerator;
|
||||
private final ExternalServiceCredentialsGenerator backupServiceCredentialsGenerator;
|
||||
|
||||
private final ChangeNumberManager changeNumberManager;
|
||||
private final Clock clock;
|
||||
@@ -185,7 +187,7 @@ public class AccountController {
|
||||
CaptchaChecker captchaChecker,
|
||||
PushNotificationManager pushNotificationManager,
|
||||
ChangeNumberManager changeNumberManager,
|
||||
ExternalServiceCredentialGenerator backupServiceCredentialGenerator,
|
||||
ExternalServiceCredentialsGenerator backupServiceCredentialsGenerator,
|
||||
ClientPresenceManager clientPresenceManager,
|
||||
Clock clock
|
||||
) {
|
||||
@@ -198,7 +200,7 @@ public class AccountController {
|
||||
this.turnTokenGenerator = turnTokenGenerator;
|
||||
this.captchaChecker = captchaChecker;
|
||||
this.pushNotificationManager = pushNotificationManager;
|
||||
this.backupServiceCredentialGenerator = backupServiceCredentialGenerator;
|
||||
this.backupServiceCredentialsGenerator = backupServiceCredentialsGenerator;
|
||||
this.changeNumberManager = changeNumberManager;
|
||||
this.clientPresenceManager = clientPresenceManager;
|
||||
this.clock = clock;
|
||||
@@ -216,12 +218,12 @@ public class AccountController {
|
||||
CaptchaChecker captchaChecker,
|
||||
PushNotificationManager pushNotificationManager,
|
||||
ChangeNumberManager changeNumberManager,
|
||||
ExternalServiceCredentialGenerator backupServiceCredentialGenerator
|
||||
ExternalServiceCredentialsGenerator backupServiceCredentialsGenerator
|
||||
) {
|
||||
this(pendingAccounts, accounts, rateLimiters,
|
||||
registrationServiceClient, dynamicConfigurationManager, turnTokenGenerator, testDevices, captchaChecker,
|
||||
pushNotificationManager, changeNumberManager,
|
||||
backupServiceCredentialGenerator, null, Clock.systemUTC());
|
||||
backupServiceCredentialsGenerator, null, Clock.systemUTC());
|
||||
}
|
||||
|
||||
@Timed
|
||||
@@ -232,7 +234,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;
|
||||
@@ -242,9 +244,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());
|
||||
@@ -255,7 +266,7 @@ public class AccountController {
|
||||
@Timed
|
||||
@GET
|
||||
@Path("/{transport}/code/{number}")
|
||||
@FilterAbusiveMessages
|
||||
@FilterSpam
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public Response createAccount(@PathParam("transport") String transport,
|
||||
@PathParam("number") String number,
|
||||
@@ -346,13 +357,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);
|
||||
@@ -388,14 +402,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());
|
||||
@@ -406,7 +420,7 @@ public class AccountController {
|
||||
existingAccount.ifPresent(account -> {
|
||||
Instant accountLastSeen = Instant.ofEpochMilli(account.getLastSeen());
|
||||
Duration timeSinceLastSeen = Duration.between(accountLastSeen, Instant.now());
|
||||
REREGISTRATION_IDLE_DAYS_DISTRIBUTION_NAME.record(timeSinceLastSeen.toDays());
|
||||
REREGISTRATION_IDLE_DAYS_DISTRIBUTION.record(timeSinceLastSeen.toDays());
|
||||
});
|
||||
|
||||
if (existingAccount.isPresent()) {
|
||||
@@ -458,10 +472,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();
|
||||
@@ -597,10 +615,10 @@ public class AccountController {
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/registration_lock")
|
||||
public void setRegistrationLock(@Auth AuthenticatedAccount auth, @NotNull @Valid RegistrationLock accountLock) {
|
||||
AuthenticationCredentials credentials = new AuthenticationCredentials(accountLock.getRegistrationLock());
|
||||
SaltedTokenHash credentials = SaltedTokenHash.generateFor(accountLock.getRegistrationLock());
|
||||
|
||||
accounts.update(auth.getAccount(),
|
||||
a -> a.setRegistrationLock(credentials.getHashedAuthenticationToken(), credentials.getSalt()));
|
||||
a -> a.setRegistrationLock(credentials.hash(), credentials.salt()));
|
||||
}
|
||||
|
||||
@Timed
|
||||
@@ -755,9 +773,9 @@ public class AccountController {
|
||||
@GET
|
||||
@Path("/username/{username}")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@RateLimitedByIp(RateLimiters.Handle.USERNAME_LOOKUP)
|
||||
public AccountIdentifierResponse lookupUsername(
|
||||
@HeaderParam(HeaderUtils.X_SIGNAL_AGENT) final String userAgent,
|
||||
@HeaderParam(HttpHeaders.X_FORWARDED_FOR) final String forwardedFor,
|
||||
@PathParam("username") final String username,
|
||||
@Context final HttpServletRequest request) throws RateLimitExceededException {
|
||||
|
||||
@@ -766,8 +784,6 @@ public class AccountController {
|
||||
throw new BadRequestException();
|
||||
}
|
||||
|
||||
rateLimitByClientIp(rateLimiters.getUsernameLookupLimiter(), forwardedFor);
|
||||
|
||||
checkUsername(username, userAgent);
|
||||
|
||||
return accounts
|
||||
@@ -779,8 +795,8 @@ public class AccountController {
|
||||
|
||||
@HEAD
|
||||
@Path("/account/{uuid}")
|
||||
@RateLimitedByIp(RateLimiters.Handle.CHECK_ACCOUNT_EXISTENCE)
|
||||
public Response accountExists(
|
||||
@HeaderParam(HttpHeaders.X_FORWARDED_FOR) final String forwardedFor,
|
||||
@PathParam("uuid") final UUID uuid,
|
||||
@Context HttpServletRequest request) throws RateLimitExceededException {
|
||||
|
||||
@@ -788,7 +804,6 @@ public class AccountController {
|
||||
if (StringUtils.isNotBlank(request.getHeader("Authorization"))) {
|
||||
throw new BadRequestException();
|
||||
}
|
||||
rateLimitByClientIp(rateLimiters.getCheckAccountExistenceLimiter(), forwardedFor);
|
||||
|
||||
final Status status = accounts.getByAccountIdentifier(uuid)
|
||||
.or(() -> accounts.getByPhoneNumberIdentifier(uuid))
|
||||
@@ -815,7 +830,7 @@ public class AccountController {
|
||||
|
||||
final StoredRegistrationLock existingRegistrationLock = existingAccount.getRegistrationLock();
|
||||
final ExternalServiceCredentials existingBackupCredentials =
|
||||
backupServiceCredentialGenerator.generateFor(existingAccount.getUuid().toString());
|
||||
backupServiceCredentialsGenerator.generateForUuid(existingAccount.getUuid());
|
||||
|
||||
if (existingRegistrationLock.requiresClientRegistrationLock()) {
|
||||
if (!Util.isEmpty(clientRegistrationLock)) {
|
||||
@@ -945,4 +960,66 @@ 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);
|
||||
|
||||
logger.debug("Failed to create session", e);
|
||||
|
||||
// Meet legacy client expectations by "swallowing" session creation exceptions and proceeding as if we had created
|
||||
// a new session. Future operations on this "session" will always fail, but that's the legacy behavior.
|
||||
return new byte[16];
|
||||
}
|
||||
}
|
||||
|
||||
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) {
|
||||
// Note that, to meet legacy client expectations, we'll ONLY rethrow rate limit exceptions. All others will be
|
||||
// swallowed silently.
|
||||
rethrowRateLimitException(e);
|
||||
|
||||
logger.debug("Failed to send verification code", 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
+21
-6
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2013-2022 Signal Messenger, LLC
|
||||
* Copyright 2013 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
@@ -12,19 +12,34 @@ import javax.ws.rs.GET;
|
||||
import javax.ws.rs.Path;
|
||||
import javax.ws.rs.Produces;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import org.apache.commons.codec.DecoderException;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialGenerator;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
|
||||
import org.whispersystems.textsecuregcm.configuration.ArtServiceConfiguration;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
|
||||
@Path("/v1/art")
|
||||
public class ArtController {
|
||||
private final ExternalServiceCredentialGenerator artServiceCredentialGenerator;
|
||||
private final ExternalServiceCredentialsGenerator artServiceCredentialsGenerator;
|
||||
private final RateLimiters rateLimiters;
|
||||
|
||||
public static ExternalServiceCredentialsGenerator credentialsGenerator(final ArtServiceConfiguration cfg) {
|
||||
try {
|
||||
return ExternalServiceCredentialsGenerator
|
||||
.builder(cfg.getUserAuthenticationTokenSharedSecret())
|
||||
.withUserDerivationKey(cfg.getUserAuthenticationTokenUserIdSecret())
|
||||
.prependUsername(false)
|
||||
.truncateSignature(false)
|
||||
.build();
|
||||
} catch (DecoderException e) {
|
||||
throw new IllegalArgumentException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public ArtController(RateLimiters rateLimiters,
|
||||
ExternalServiceCredentialGenerator artServiceCredentialGenerator) {
|
||||
this.artServiceCredentialGenerator = artServiceCredentialGenerator;
|
||||
ExternalServiceCredentialsGenerator artServiceCredentialsGenerator) {
|
||||
this.artServiceCredentialsGenerator = artServiceCredentialsGenerator;
|
||||
this.rateLimiters = rateLimiters;
|
||||
}
|
||||
|
||||
@@ -36,6 +51,6 @@ public class ArtController {
|
||||
throws RateLimitExceededException {
|
||||
final UUID uuid = auth.getAccount().getUuid();
|
||||
rateLimiters.getArtPackLimiter().validate(uuid);
|
||||
return artServiceCredentialGenerator.generateFor(uuid.toString());
|
||||
return artServiceCredentialsGenerator.generateForUuid(uuid);
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2013-2021 Signal Messenger, LLC
|
||||
* Copyright 2013 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
@@ -32,7 +32,7 @@ public class AttachmentControllerV2 {
|
||||
|
||||
public AttachmentControllerV2(RateLimiters rateLimiters, String accessKey, String accessSecret, String region,
|
||||
String bucket) {
|
||||
this.rateLimiter = rateLimiters.getAttachmentLimiter();
|
||||
this.rateLimiter = rateLimiters.getAttachmentLimiter();
|
||||
this.policyGenerator = new PostPolicyGenerator(region, bucket, accessKey);
|
||||
this.policySigner = new PolicySigner(accessSecret, region);
|
||||
}
|
||||
|
||||
+4
-6
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2013-2022 Signal Messenger, LLC
|
||||
* Copyright 2013 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
@@ -30,9 +30,9 @@ import javax.ws.rs.core.Response;
|
||||
import org.glassfish.jersey.server.ContainerRequest;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthEnablementRefreshRequirementProvider;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticationCredentials;
|
||||
import org.whispersystems.textsecuregcm.auth.BasicAuthorizationHeader;
|
||||
import org.whispersystems.textsecuregcm.auth.ChangesDeviceEnabledState;
|
||||
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
|
||||
import org.whispersystems.textsecuregcm.auth.StoredVerificationCode;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
|
||||
import org.whispersystems.textsecuregcm.entities.DeviceInfo;
|
||||
@@ -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);
|
||||
|
||||
@@ -194,7 +192,7 @@ public class DeviceController {
|
||||
|
||||
Device device = new Device();
|
||||
device.setName(accountAttributes.getName());
|
||||
device.setAuthenticationCredentials(new AuthenticationCredentials(password));
|
||||
device.setAuthTokenHash(SaltedTokenHash.generateFor(password));
|
||||
device.setFetchesMessages(accountAttributes.getFetchesMessages());
|
||||
device.setRegistrationId(accountAttributes.getRegistrationId());
|
||||
accountAttributes.getPhoneNumberIdentityRegistrationId().ifPresent(device::setPhoneNumberIdentityRegistrationId);
|
||||
|
||||
+14
-4
@@ -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.controllers;
|
||||
@@ -13,15 +13,25 @@ import javax.ws.rs.Path;
|
||||
import javax.ws.rs.Produces;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
import org.apache.commons.codec.DecoderException;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialGenerator;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
|
||||
import org.whispersystems.textsecuregcm.configuration.DirectoryClientConfiguration;
|
||||
|
||||
@Path("/v1/directory")
|
||||
public class DirectoryController {
|
||||
|
||||
private final ExternalServiceCredentialGenerator directoryServiceTokenGenerator;
|
||||
private final ExternalServiceCredentialsGenerator directoryServiceTokenGenerator;
|
||||
|
||||
public DirectoryController(ExternalServiceCredentialGenerator userTokenGenerator) {
|
||||
public static ExternalServiceCredentialsGenerator credentialsGenerator(final DirectoryClientConfiguration cfg)
|
||||
throws DecoderException {
|
||||
return ExternalServiceCredentialsGenerator
|
||||
.builder(cfg.getUserAuthenticationTokenSharedSecret())
|
||||
.withUserDerivationKey(cfg.getUserAuthenticationTokenUserIdSecret())
|
||||
.build();
|
||||
}
|
||||
|
||||
public DirectoryController(ExternalServiceCredentialsGenerator userTokenGenerator) {
|
||||
this.directoryServiceTokenGenerator = userTokenGenerator;
|
||||
}
|
||||
|
||||
|
||||
+23
-5
@@ -1,11 +1,13 @@
|
||||
/*
|
||||
* Copyright 2013-2021 Signal Messenger, LLC
|
||||
* Copyright 2013 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import com.codahale.metrics.annotation.Timed;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import java.time.Clock;
|
||||
import java.util.UUID;
|
||||
import javax.ws.rs.GET;
|
||||
import javax.ws.rs.Path;
|
||||
@@ -13,15 +15,31 @@ import javax.ws.rs.Produces;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialGenerator;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
|
||||
import org.whispersystems.textsecuregcm.configuration.DirectoryV2ClientConfiguration;
|
||||
|
||||
@Path("/v2/directory")
|
||||
public class DirectoryV2Controller {
|
||||
|
||||
private final ExternalServiceCredentialGenerator directoryServiceTokenGenerator;
|
||||
private final ExternalServiceCredentialsGenerator directoryServiceTokenGenerator;
|
||||
|
||||
public DirectoryV2Controller(ExternalServiceCredentialGenerator userTokenGenerator) {
|
||||
@VisibleForTesting
|
||||
public static ExternalServiceCredentialsGenerator credentialsGenerator(final DirectoryV2ClientConfiguration cfg,
|
||||
final Clock clock) {
|
||||
return ExternalServiceCredentialsGenerator
|
||||
.builder(cfg.userAuthenticationTokenSharedSecret())
|
||||
.withUserDerivationKey(cfg.userIdTokenSharedSecret())
|
||||
.prependUsername(false)
|
||||
.withClock(clock)
|
||||
.build();
|
||||
}
|
||||
|
||||
public static ExternalServiceCredentialsGenerator credentialsGenerator(final DirectoryV2ClientConfiguration cfg) {
|
||||
return credentialsGenerator(cfg, Clock.systemUTC());
|
||||
}
|
||||
|
||||
public DirectoryV2Controller(ExternalServiceCredentialsGenerator userTokenGenerator) {
|
||||
this.directoryServiceTokenGenerator = userTokenGenerator;
|
||||
}
|
||||
|
||||
@@ -31,7 +49,7 @@ public class DirectoryV2Controller {
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public Response getAuthToken(@Auth AuthenticatedAccount auth) {
|
||||
final UUID uuid = auth.getAccount().getUuid();
|
||||
final ExternalServiceCredentials credentials = directoryServiceTokenGenerator.generateFor(uuid.toString());
|
||||
final ExternalServiceCredentials credentials = directoryServiceTokenGenerator.generateForUuid(uuid);
|
||||
return Response.ok().entity(credentials).build();
|
||||
}
|
||||
}
|
||||
-12
@@ -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);
|
||||
}
|
||||
}
|
||||
+1
-3
@@ -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;
|
||||
|
||||
|
||||
+59
-15
@@ -55,12 +55,13 @@ 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.auth.Anonymous;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
|
||||
import org.whispersystems.textsecuregcm.auth.CombinedUnidentifiedSenderAccessKeys;
|
||||
@@ -78,6 +79,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;
|
||||
@@ -87,6 +89,8 @@ import org.whispersystems.textsecuregcm.push.MessageSender;
|
||||
import org.whispersystems.textsecuregcm.push.NotPushRegisteredException;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
|
||||
import org.whispersystems.textsecuregcm.push.ReceiptSender;
|
||||
import org.whispersystems.textsecuregcm.spam.FilterSpam;
|
||||
import org.whispersystems.textsecuregcm.spam.ReportSpamTokenProvider;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.DeletedAccountsManager;
|
||||
@@ -117,6 +121,7 @@ public class MessageController {
|
||||
private final PushNotificationManager pushNotificationManager;
|
||||
private final ReportMessageManager reportMessageManager;
|
||||
private final ExecutorService multiRecipientMessageExecutor;
|
||||
private final ReportSpamTokenProvider reportSpamTokenProvider;
|
||||
|
||||
private static final String REJECT_OVERSIZE_MESSAGE_COUNTER = name(MessageController.class, "rejectOversizeMessage");
|
||||
private static final String SENT_MESSAGE_COUNTER_NAME = name(MessageController.class, "sentMessages");
|
||||
@@ -147,7 +152,8 @@ public class MessageController {
|
||||
MessagesManager messagesManager,
|
||||
PushNotificationManager pushNotificationManager,
|
||||
ReportMessageManager reportMessageManager,
|
||||
@Nonnull ExecutorService multiRecipientMessageExecutor) {
|
||||
@Nonnull ExecutorService multiRecipientMessageExecutor,
|
||||
@Nonnull ReportSpamTokenProvider reportSpamTokenProvider) {
|
||||
this.rateLimiters = rateLimiters;
|
||||
this.messageSender = messageSender;
|
||||
this.receiptSender = receiptSender;
|
||||
@@ -157,6 +163,7 @@ public class MessageController {
|
||||
this.pushNotificationManager = pushNotificationManager;
|
||||
this.reportMessageManager = reportMessageManager;
|
||||
this.multiRecipientMessageExecutor = Objects.requireNonNull(multiRecipientMessageExecutor);
|
||||
this.reportSpamTokenProvider = reportSpamTokenProvider;
|
||||
}
|
||||
|
||||
@Timed
|
||||
@@ -164,14 +171,16 @@ public class MessageController {
|
||||
@PUT
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@FilterAbusiveMessages
|
||||
@FilterSpam
|
||||
public Response sendMessage(@Auth Optional<AuthenticatedAccount> source,
|
||||
@HeaderParam(OptionalAccess.UNIDENTIFIED) Optional<Anonymous> accessKey,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) String userAgent,
|
||||
@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 +199,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 +283,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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -322,7 +349,7 @@ public class MessageController {
|
||||
@PUT
|
||||
@Consumes(MultiRecipientMessageProvider.MEDIA_TYPE)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@FilterAbusiveMessages
|
||||
@FilterSpam
|
||||
public Response sendMultiRecipientMessage(
|
||||
@HeaderParam(OptionalAccess.UNIDENTIFIED) @Nullable CombinedUnidentifiedSenderAccessKeys accessKeys,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) String userAgent,
|
||||
@@ -570,9 +597,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 +634,20 @@ 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.
|
||||
final Optional<byte[]> maybeSpamReportToken =
|
||||
spamReport != null ? Optional.of(spamReport.token()) : Optional.empty();
|
||||
|
||||
reportMessageManager.report(sourceNumber, sourceAci, sourcePni, messageGuid, spamReporterUuid, maybeSpamReportToken);
|
||||
|
||||
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 +656,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);
|
||||
|
||||
+20
-9
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2013-2021 Signal Messenger, LLC
|
||||
* Copyright 2013 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
@@ -11,36 +11,47 @@ import javax.ws.rs.GET;
|
||||
import javax.ws.rs.Path;
|
||||
import javax.ws.rs.Produces;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import org.apache.commons.codec.DecoderException;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialGenerator;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
|
||||
import org.whispersystems.textsecuregcm.configuration.PaymentsServiceConfiguration;
|
||||
import org.whispersystems.textsecuregcm.currency.CurrencyConversionManager;
|
||||
import org.whispersystems.textsecuregcm.entities.CurrencyConversionEntityList;
|
||||
|
||||
@Path("/v1/payments")
|
||||
public class PaymentsController {
|
||||
|
||||
private final ExternalServiceCredentialGenerator paymentsServiceCredentialGenerator;
|
||||
private final CurrencyConversionManager currencyManager;
|
||||
private final ExternalServiceCredentialsGenerator paymentsServiceCredentialsGenerator;
|
||||
private final CurrencyConversionManager currencyManager;
|
||||
|
||||
public PaymentsController(CurrencyConversionManager currencyManager, ExternalServiceCredentialGenerator paymentsServiceCredentialGenerator) {
|
||||
|
||||
public static ExternalServiceCredentialsGenerator credentialsGenerator(final PaymentsServiceConfiguration cfg)
|
||||
throws DecoderException {
|
||||
return ExternalServiceCredentialsGenerator
|
||||
.builder(cfg.getUserAuthenticationTokenSharedSecret())
|
||||
.prependUsername(true)
|
||||
.build();
|
||||
}
|
||||
|
||||
public PaymentsController(final CurrencyConversionManager currencyManager, final ExternalServiceCredentialsGenerator paymentsServiceCredentialsGenerator) {
|
||||
this.currencyManager = currencyManager;
|
||||
this.paymentsServiceCredentialGenerator = paymentsServiceCredentialGenerator;
|
||||
this.paymentsServiceCredentialsGenerator = paymentsServiceCredentialsGenerator;
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Path("/auth")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public ExternalServiceCredentials getAuth(@Auth AuthenticatedAccount auth) {
|
||||
return paymentsServiceCredentialGenerator.generateFor(auth.getAccount().getUuid().toString());
|
||||
public ExternalServiceCredentials getAuth(final @Auth AuthenticatedAccount auth) {
|
||||
return paymentsServiceCredentialsGenerator.generateForUuid(auth.getAccount().getUuid());
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Path("/conversions")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public CurrencyConversionEntityList getConversions(@Auth AuthenticatedAccount auth) {
|
||||
public CurrencyConversionEntityList getConversions(final @Auth AuthenticatedAccount auth) {
|
||||
return currencyManager.getCurrencyConversions().orElseThrow();
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -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 {
|
||||
|
||||
|
||||
+128
-7
@@ -1,34 +1,155 @@
|
||||
/*
|
||||
* Copyright 2013-2021 Signal Messenger, LLC
|
||||
* Copyright 2013 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import static java.util.Objects.requireNonNull;
|
||||
|
||||
import com.codahale.metrics.annotation.Timed;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import java.time.Clock;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.Predicate;
|
||||
import javax.validation.Valid;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import javax.ws.rs.Consumes;
|
||||
import javax.ws.rs.GET;
|
||||
import javax.ws.rs.POST;
|
||||
import javax.ws.rs.Path;
|
||||
import javax.ws.rs.Produces;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import org.apache.commons.codec.DecoderException;
|
||||
import org.apache.commons.lang3.tuple.Pair;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialGenerator;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
|
||||
import org.whispersystems.textsecuregcm.configuration.SecureBackupServiceConfiguration;
|
||||
import org.whispersystems.textsecuregcm.entities.AuthCheckRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.AuthCheckResponse;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimitedByIp;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
|
||||
@Path("/v1/backup")
|
||||
public class SecureBackupController {
|
||||
|
||||
private final ExternalServiceCredentialGenerator backupServiceCredentialGenerator;
|
||||
private static final long MAX_AGE_SECONDS = TimeUnit.DAYS.toSeconds(30);
|
||||
|
||||
public SecureBackupController(ExternalServiceCredentialGenerator backupServiceCredentialGenerator) {
|
||||
this.backupServiceCredentialGenerator = backupServiceCredentialGenerator;
|
||||
private final ExternalServiceCredentialsGenerator credentialsGenerator;
|
||||
|
||||
private final AccountsManager accountsManager;
|
||||
|
||||
public static ExternalServiceCredentialsGenerator credentialsGenerator(final SecureBackupServiceConfiguration cfg) {
|
||||
return credentialsGenerator(cfg, Clock.systemUTC());
|
||||
}
|
||||
|
||||
public static ExternalServiceCredentialsGenerator credentialsGenerator(
|
||||
final SecureBackupServiceConfiguration cfg,
|
||||
final Clock clock) {
|
||||
try {
|
||||
return ExternalServiceCredentialsGenerator
|
||||
.builder(cfg.getUserAuthenticationTokenSharedSecret())
|
||||
.prependUsername(true)
|
||||
.withClock(clock)
|
||||
.build();
|
||||
} catch (final DecoderException e) {
|
||||
throw new IllegalStateException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public SecureBackupController(
|
||||
final ExternalServiceCredentialsGenerator credentialsGenerator,
|
||||
final AccountsManager accountsManager) {
|
||||
this.credentialsGenerator = requireNonNull(credentialsGenerator);
|
||||
this.accountsManager = requireNonNull(accountsManager);
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Path("/auth")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public ExternalServiceCredentials getAuth(@Auth AuthenticatedAccount auth) {
|
||||
return backupServiceCredentialGenerator.generateFor(auth.getAccount().getUuid().toString());
|
||||
public ExternalServiceCredentials getAuth(final @Auth AuthenticatedAccount auth) {
|
||||
return credentialsGenerator.generateForUuid(auth.getAccount().getUuid());
|
||||
}
|
||||
|
||||
@Timed
|
||||
@POST
|
||||
@Path("/auth/check")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@RateLimitedByIp(RateLimiters.Handle.BACKUP_AUTH_CHECK)
|
||||
public AuthCheckResponse authCheck(@NotNull @Valid final AuthCheckRequest request) {
|
||||
final Map<String, AuthCheckResponse.Result> results = new HashMap<>();
|
||||
final Map<String, Pair<UUID, Long>> tokenToUuid = new HashMap<>();
|
||||
final Map<UUID, Long> uuidToLatestTimestamp = new HashMap<>();
|
||||
|
||||
// first pass -- filter out all tokens that contain invalid credentials
|
||||
// (this could be either legit but expired or illegitimate for any reason)
|
||||
request.passwords().forEach(token -> {
|
||||
// each token is supposed to be in a "${username}:${password}" form,
|
||||
// (note that password part may also contain ':' characters)
|
||||
final String[] parts = token.split(":", 2);
|
||||
if (parts.length != 2) {
|
||||
results.put(token, AuthCheckResponse.Result.INVALID);
|
||||
return;
|
||||
}
|
||||
final ExternalServiceCredentials credentials = new ExternalServiceCredentials(parts[0], parts[1]);
|
||||
final Optional<Long> maybeTimestamp = credentialsGenerator.validateAndGetTimestamp(credentials, MAX_AGE_SECONDS);
|
||||
final Optional<UUID> maybeUuid = UUIDUtil.fromStringSafe(credentials.username());
|
||||
if (maybeTimestamp.isEmpty() || maybeUuid.isEmpty()) {
|
||||
results.put(token, AuthCheckResponse.Result.INVALID);
|
||||
return;
|
||||
}
|
||||
// now that we validated signature and token age, we will also find the latest of the tokens
|
||||
// for each username
|
||||
final Long timestamp = maybeTimestamp.get();
|
||||
final UUID uuid = maybeUuid.get();
|
||||
tokenToUuid.put(token, Pair.of(uuid, timestamp));
|
||||
final Long latestTimestamp = uuidToLatestTimestamp.getOrDefault(uuid, 0L);
|
||||
if (timestamp > latestTimestamp) {
|
||||
uuidToLatestTimestamp.put(uuid, timestamp);
|
||||
}
|
||||
});
|
||||
|
||||
// as a result of the first pass we now have some tokens that are marked invalid,
|
||||
// and for others we now know if for any username the list contains multiple tokens
|
||||
// we also know all distinct usernames from the list
|
||||
|
||||
// if it so happens that all tokens are invalid -- respond right away
|
||||
if (tokenToUuid.isEmpty()) {
|
||||
return new AuthCheckResponse(results);
|
||||
}
|
||||
|
||||
final Predicate<UUID> uuidMatches = accountsManager
|
||||
.getByE164(request.number())
|
||||
.map(account -> (Predicate<UUID>) candidateUuid -> account.getUuid().equals(candidateUuid))
|
||||
.orElse(candidateUuid -> false);
|
||||
|
||||
// second pass will let us discard tokens that have newer versions and will also let us pick the winner (if any)
|
||||
request.passwords().forEach(token -> {
|
||||
if (results.containsKey(token)) {
|
||||
// result already calculated
|
||||
return;
|
||||
}
|
||||
final Pair<UUID, Long> uuidAndTime = requireNonNull(tokenToUuid.get(token));
|
||||
final Long latestTimestamp = requireNonNull(uuidToLatestTimestamp.get(uuidAndTime.getLeft()));
|
||||
// check if a newer version available
|
||||
if (uuidAndTime.getRight() < latestTimestamp) {
|
||||
results.put(token, AuthCheckResponse.Result.INVALID);
|
||||
return;
|
||||
}
|
||||
results.put(token, uuidMatches.test(uuidAndTime.getLeft())
|
||||
? AuthCheckResponse.Result.MATCH
|
||||
: AuthCheckResponse.Result.NO_MATCH);
|
||||
});
|
||||
|
||||
return new AuthCheckResponse(results);
|
||||
}
|
||||
}
|
||||
+19
-6
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2013-2021 Signal Messenger, LLC
|
||||
* Copyright 2013 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
@@ -11,17 +11,30 @@ import javax.ws.rs.GET;
|
||||
import javax.ws.rs.Path;
|
||||
import javax.ws.rs.Produces;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import org.apache.commons.codec.DecoderException;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialGenerator;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
|
||||
import org.whispersystems.textsecuregcm.configuration.SecureStorageServiceConfiguration;
|
||||
|
||||
@Path("/v1/storage")
|
||||
public class SecureStorageController {
|
||||
|
||||
private final ExternalServiceCredentialGenerator storageServiceCredentialGenerator;
|
||||
private final ExternalServiceCredentialsGenerator storageServiceCredentialsGenerator;
|
||||
|
||||
public SecureStorageController(ExternalServiceCredentialGenerator storageServiceCredentialGenerator) {
|
||||
this.storageServiceCredentialGenerator = storageServiceCredentialGenerator;
|
||||
public static ExternalServiceCredentialsGenerator credentialsGenerator(final SecureStorageServiceConfiguration cfg) {
|
||||
try {
|
||||
return ExternalServiceCredentialsGenerator
|
||||
.builder(cfg.decodeUserAuthenticationTokenSharedSecret())
|
||||
.prependUsername(true)
|
||||
.build();
|
||||
} catch (DecoderException e) {
|
||||
throw new IllegalArgumentException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public SecureStorageController(ExternalServiceCredentialsGenerator storageServiceCredentialsGenerator) {
|
||||
this.storageServiceCredentialsGenerator = storageServiceCredentialsGenerator;
|
||||
}
|
||||
|
||||
@Timed
|
||||
@@ -29,6 +42,6 @@ public class SecureStorageController {
|
||||
@Path("/auth")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public ExternalServiceCredentials getAuth(@Auth AuthenticatedAccount auth) {
|
||||
return storageServiceCredentialGenerator.generateFor(auth.getAccount().getUuid().toString());
|
||||
return storageServiceCredentialsGenerator.generateForUuid(auth.getAccount().getUuid());
|
||||
}
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
/*
|
||||
* Copyright 2013-2021 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 javax.ws.rs.GET;
|
||||
import javax.ws.rs.Path;
|
||||
import javax.ws.rs.Produces;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import org.apache.commons.codec.DecoderException;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
|
||||
import org.whispersystems.textsecuregcm.configuration.SecureValueRecovery2Configuration;
|
||||
|
||||
@Path("/v2/backup")
|
||||
public class SecureValueRecovery2Controller {
|
||||
|
||||
public static ExternalServiceCredentialsGenerator credentialsGenerator(final SecureValueRecovery2Configuration cfg)
|
||||
throws DecoderException {
|
||||
return ExternalServiceCredentialsGenerator
|
||||
.builder(cfg.userAuthenticationTokenSharedSecret())
|
||||
.withUserDerivationKey(cfg.userIdTokenSharedSecret())
|
||||
.build();
|
||||
}
|
||||
|
||||
private final ExternalServiceCredentialsGenerator backupServiceCredentialGenerator;
|
||||
|
||||
public SecureValueRecovery2Controller(ExternalServiceCredentialsGenerator backupServiceCredentialGenerator) {
|
||||
this.backupServiceCredentialGenerator = backupServiceCredentialGenerator;
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Path("/auth")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public ExternalServiceCredentials getAuth(@Auth AuthenticatedAccount auth) {
|
||||
return backupServiceCredentialGenerator.generateFor(auth.getAccount().getUuid().toString());
|
||||
}
|
||||
}
|
||||
+259
-211
@@ -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,7 +81,6 @@ 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;
|
||||
@@ -98,6 +91,7 @@ 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;
|
||||
@@ -119,7 +113,11 @@ public class SubscriptionController {
|
||||
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,
|
||||
@@ -168,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()
|
||||
@@ -233,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));
|
||||
})
|
||||
@@ -307,7 +293,14 @@ 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.setProcessorAndCustomerId(record,
|
||||
@@ -317,6 +310,7 @@ public class SubscriptionController {
|
||||
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);
|
||||
@@ -327,6 +321,64 @@ 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;
|
||||
@@ -346,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
|
||||
@@ -435,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) {
|
||||
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));
|
||||
|
||||
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 currency,
|
||||
// and only change it if needed
|
||||
return manager.getSubscription(subId).thenCompose(
|
||||
subscription -> manager.getLevelAndCurrencyForSubscription(subscription)
|
||||
.thenCompose(existingLevelAndCurrency -> {
|
||||
if (existingLevelAndCurrency.equals(new SubscriptionProcessorManager.LevelAndCurrency(level,
|
||||
currency.toLowerCase(Locale.ROOT)))) {
|
||||
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;
|
||||
|
||||
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) {
|
||||
throw re;
|
||||
}
|
||||
|
||||
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);
|
||||
// we don't have a subscription yet so create it and then record the subscription id
|
||||
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());
|
||||
}
|
||||
return stripeManager.updateSubscription(
|
||||
subscription, priceConfiguration.getId(), level, idempotencyKey)
|
||||
.thenCompose(updatedSubscription ->
|
||||
subscriptionManager.subscriptionLevelChanged(requestData.subscriberUser, requestData.now,
|
||||
level)
|
||||
.thenApply(unused -> updatedSubscription));
|
||||
}));
|
||||
}
|
||||
if (e instanceof RuntimeException re) {
|
||||
throw re;
|
||||
}
|
||||
|
||||
throw new CompletionException(e);
|
||||
})
|
||||
.thenCompose(subscription -> subscriptionManager.subscriptionCreated(
|
||||
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 {
|
||||
@@ -613,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();
|
||||
});
|
||||
}
|
||||
@@ -730,6 +795,9 @@ public class SubscriptionController {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a Stripe PaymentIntent with the requested amount and currency
|
||||
*/
|
||||
@Timed
|
||||
@POST
|
||||
@Path("/boost/create")
|
||||
@@ -745,7 +813,7 @@ public class SubscriptionController {
|
||||
BigDecimal amountConfigured = oneTimeDonationConfiguration.currencies()
|
||||
.get(request.currency.toLowerCase(Locale.ROOT)).gift();
|
||||
if (amountConfigured == null ||
|
||||
stripeManager.convertConfiguredAmountToStripeAmount(request.currency, amountConfigured)
|
||||
SubscriptionCurrencyUtil.convertConfiguredAmountToStripeAmount(request.currency, amountConfigured)
|
||||
.compareTo(amount) != 0) {
|
||||
throw new WebApplicationException(
|
||||
Response.status(Status.CONFLICT).entity(Map.of("error", "level_amount_mismatch")).build());
|
||||
@@ -773,7 +841,8 @@ public class SubscriptionController {
|
||||
|
||||
BigDecimal minCurrencyAmountMajorUnits = oneTimeDonationConfiguration.currencies()
|
||||
.get(request.currency.toLowerCase(Locale.ROOT)).minimum();
|
||||
BigDecimal minCurrencyAmountMinorUnits = stripeManager.convertConfiguredAmountToStripeAmount(request.currency,
|
||||
BigDecimal minCurrencyAmountMinorUnits = SubscriptionCurrencyUtil.convertConfiguredAmountToApiAmount(
|
||||
request.currency,
|
||||
minCurrencyAmountMajorUnits);
|
||||
if (minCurrencyAmountMinorUnits.compareTo(amount) > 0) {
|
||||
throw new BadRequestException(Response.status(Status.BAD_REQUEST)
|
||||
@@ -936,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();
|
||||
});
|
||||
@@ -954,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(
|
||||
@@ -964,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;
|
||||
@@ -973,6 +1048,7 @@ public class SubscriptionController {
|
||||
this.currency = currency;
|
||||
this.amount = amount;
|
||||
this.status = status;
|
||||
this.processor = processor;
|
||||
}
|
||||
|
||||
public long getLevel() {
|
||||
@@ -1006,6 +1082,10 @@ public class SubscriptionController {
|
||||
public String getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public SubscriptionProcessor getProcessor() {
|
||||
return processor;
|
||||
}
|
||||
}
|
||||
|
||||
public static class ChargeFailure {
|
||||
@@ -1082,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();
|
||||
}));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1162,98 +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(), SubscriptionProcessor.STRIPE, 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) {
|
||||
|
||||
-131
@@ -1,131 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2020 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Locale.LanguageRange;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import javax.ws.rs.POST;
|
||||
import javax.ws.rs.Path;
|
||||
import javax.ws.rs.PathParam;
|
||||
import javax.ws.rs.Produces;
|
||||
import javax.ws.rs.QueryParam;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
|
||||
@Path("/v1/voice/")
|
||||
public class VoiceVerificationController {
|
||||
|
||||
private static final String PLAY_TWIML = """
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Response>
|
||||
<Play>%s</Play>
|
||||
<Play>%s</Play>
|
||||
<Play>%s</Play>
|
||||
<Play>%s</Play>
|
||||
<Play>%s</Play>
|
||||
<Play>%s</Play>
|
||||
<Play>%s</Play>
|
||||
<Pause length="1"/>
|
||||
<Play>%s</Play>
|
||||
<Play>%s</Play>
|
||||
<Play>%s</Play>
|
||||
<Play>%s</Play>
|
||||
<Play>%s</Play>
|
||||
<Play>%s</Play>
|
||||
<Play>%s</Play>
|
||||
<Pause length="1"/>
|
||||
<Play>%s</Play>
|
||||
<Play>%s</Play>
|
||||
<Play>%s</Play>
|
||||
<Play>%s</Play>
|
||||
<Play>%s</Play>
|
||||
<Play>%s</Play>
|
||||
<Play>%s</Play>
|
||||
</Response>
|
||||
""";
|
||||
|
||||
private static final String DEFAULT_LOCALE = "en-US";
|
||||
|
||||
|
||||
private final String baseUrl;
|
||||
private final Set<String> supportedLocales;
|
||||
|
||||
public VoiceVerificationController(String baseUrl, Set<String> supportedLocales) {
|
||||
this.baseUrl = baseUrl;
|
||||
this.supportedLocales = supportedLocales;
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/description/{code}")
|
||||
@Produces(MediaType.APPLICATION_XML)
|
||||
public Response getDescription(@PathParam("code") String code, @QueryParam("l") List<String> locales) {
|
||||
code = code.replaceAll("[^0-9]", "");
|
||||
|
||||
if (code.length() != 6) {
|
||||
return Response.status(400).build();
|
||||
}
|
||||
|
||||
if (locales == null) {
|
||||
locales = Collections.emptyList();
|
||||
}
|
||||
|
||||
final List<LanguageRange> priorityList;
|
||||
try {
|
||||
priorityList = locales.stream()
|
||||
.map(LanguageRange::new)
|
||||
.collect(Collectors.toList());
|
||||
} catch (final IllegalArgumentException e) {
|
||||
return Response.status(400).build();
|
||||
}
|
||||
|
||||
final String localeMatch = Util.findBestLocale(priorityList, supportedLocales).orElse(DEFAULT_LOCALE);
|
||||
|
||||
return getLocalizedDescription(code, localeMatch);
|
||||
}
|
||||
|
||||
private Response getLocalizedDescription(String code, String locale) {
|
||||
String path = constructUrlForLocale(baseUrl, locale);
|
||||
|
||||
return Response.ok()
|
||||
.entity(String.format(PLAY_TWIML,
|
||||
path + "verification.mp3",
|
||||
path + code.charAt(0) + "_middle.mp3",
|
||||
path + code.charAt(1) + "_middle.mp3",
|
||||
path + code.charAt(2) + "_middle.mp3",
|
||||
path + code.charAt(3) + "_middle.mp3",
|
||||
path + code.charAt(4) + "_middle.mp3",
|
||||
path + code.charAt(5) + "_falling.mp3",
|
||||
path + "verification.mp3",
|
||||
path + code.charAt(0) + "_middle.mp3",
|
||||
path + code.charAt(1) + "_middle.mp3",
|
||||
path + code.charAt(2) + "_middle.mp3",
|
||||
path + code.charAt(3) + "_middle.mp3",
|
||||
path + code.charAt(4) + "_middle.mp3",
|
||||
path + code.charAt(5) + "_falling.mp3",
|
||||
path + "verification.mp3",
|
||||
path + code.charAt(0) + "_middle.mp3",
|
||||
path + code.charAt(1) + "_middle.mp3",
|
||||
path + code.charAt(2) + "_middle.mp3",
|
||||
path + code.charAt(3) + "_middle.mp3",
|
||||
path + code.charAt(4) + "_middle.mp3",
|
||||
path + code.charAt(5) + "_falling.mp3"))
|
||||
.build();
|
||||
}
|
||||
|
||||
private String constructUrlForLocale(String baseUrl, String locale) {
|
||||
if (!baseUrl.endsWith("/")) {
|
||||
baseUrl += "/";
|
||||
}
|
||||
|
||||
return baseUrl + locale + "/";
|
||||
}
|
||||
|
||||
}
|
||||
+6
-50
@@ -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) {
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import java.util.List;
|
||||
import javax.validation.constraints.NotEmpty;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import javax.validation.constraints.Size;
|
||||
import org.whispersystems.textsecuregcm.util.E164;
|
||||
|
||||
public record AuthCheckRequest(@NotNull @E164 String number,
|
||||
@NotEmpty @Size(max = 10) List<String> passwords) {
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonValue;
|
||||
import java.util.Map;
|
||||
import javax.validation.constraints.NotNull;
|
||||
|
||||
public record AuthCheckResponse(@NotNull Map<String, Result> matches) {
|
||||
|
||||
public enum Result {
|
||||
MATCH("match"),
|
||||
NO_MATCH("no-match"),
|
||||
INVALID("invalid");
|
||||
|
||||
private final String clientCode;
|
||||
|
||||
Result(final String clientCode) {
|
||||
this.clientCode = clientCode;
|
||||
}
|
||||
|
||||
@JsonValue
|
||||
public String clientCode() {
|
||||
return clientCode;
|
||||
}
|
||||
}
|
||||
}
|
||||
+8
-2
@@ -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())));
|
||||
}
|
||||
|
||||
+1
-25
@@ -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,12 @@
|
||||
package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
|
||||
import javax.validation.Valid;
|
||||
import javax.validation.constraints.NotEmpty;
|
||||
|
||||
public record SpamReport(@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
|
||||
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
|
||||
@NotEmpty byte[] token) {}
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.limits;
|
||||
|
||||
import static java.util.Objects.requireNonNull;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.common.net.HttpHeaders;
|
||||
import java.io.IOException;
|
||||
import java.time.Duration;
|
||||
import java.util.Optional;
|
||||
import javax.ws.rs.ClientErrorException;
|
||||
import javax.ws.rs.container.ContainerRequestContext;
|
||||
import javax.ws.rs.container.ContainerRequestFilter;
|
||||
import javax.ws.rs.core.Response;
|
||||
import javax.ws.rs.ext.ExceptionMapper;
|
||||
import org.glassfish.jersey.server.ExtendedUriInfo;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.util.HeaderUtils;
|
||||
|
||||
public class RateLimitByIpFilter implements ContainerRequestFilter {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(RateLimitByIpFilter.class);
|
||||
|
||||
@VisibleForTesting
|
||||
static final RateLimitExceededException INVALID_HEADER_EXCEPTION = new RateLimitExceededException(Duration.ofHours(1));
|
||||
|
||||
private static final ExceptionMapper<RateLimitExceededException> EXCEPTION_MAPPER = new RateLimitExceededExceptionMapper();
|
||||
|
||||
private final RateLimiters rateLimiters;
|
||||
|
||||
|
||||
public RateLimitByIpFilter(final RateLimiters rateLimiters) {
|
||||
this.rateLimiters = requireNonNull(rateLimiters);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void filter(final ContainerRequestContext requestContext) throws IOException {
|
||||
// requestContext.getUriInfo() should always be an instance of `ExtendedUriInfo`
|
||||
// in the Jersey client
|
||||
if (!(requestContext.getUriInfo() instanceof final ExtendedUriInfo uriInfo)) {
|
||||
return;
|
||||
}
|
||||
|
||||
final RateLimitedByIp annotation = uriInfo.getMatchedResourceMethod()
|
||||
.getInvocable()
|
||||
.getHandlingMethod()
|
||||
.getAnnotation(RateLimitedByIp.class);
|
||||
|
||||
if (annotation == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
final RateLimiters.Handle handle = annotation.value();
|
||||
|
||||
try {
|
||||
final String xffHeader = requestContext.getHeaders().getFirst(HttpHeaders.X_FORWARDED_FOR);
|
||||
final Optional<String> maybeMostRecentProxy = Optional.ofNullable(xffHeader)
|
||||
.flatMap(HeaderUtils::getMostRecentProxy);
|
||||
|
||||
// checking if we failed to extract the most recent IP from the X-Forwarded-For header
|
||||
// for any reason
|
||||
if (maybeMostRecentProxy.isEmpty()) {
|
||||
// checking if annotation is configured to fail when the most recent IP is not resolved
|
||||
if (annotation.failOnUnresolvedIp()) {
|
||||
logger.error("Missing/bad X-Forwarded-For: {}", xffHeader);
|
||||
throw INVALID_HEADER_EXCEPTION;
|
||||
}
|
||||
// otherwise, allow request
|
||||
return;
|
||||
}
|
||||
|
||||
final Optional<RateLimiter> maybeRateLimiter = rateLimiters.byHandle(handle);
|
||||
if (maybeRateLimiter.isEmpty()) {
|
||||
logger.warn("RateLimiter not found for {}. Make sure it's initialized in RateLimiters class", handle);
|
||||
return;
|
||||
}
|
||||
|
||||
maybeRateLimiter.get().validate(maybeMostRecentProxy.get());
|
||||
} catch (RateLimitExceededException e) {
|
||||
final Response response = EXCEPTION_MAPPER.toResponse(e);
|
||||
throw new ClientErrorException(response);
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -9,7 +9,7 @@ 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.spam.RateLimitChallengeListener;
|
||||
import org.whispersystems.textsecuregcm.captcha.CaptchaChecker;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.limits;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
@Target(ElementType.METHOD)
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface RateLimitedByIp {
|
||||
|
||||
RateLimiters.Handle value();
|
||||
|
||||
boolean failOnUnresolvedIp() default true;
|
||||
}
|
||||
@@ -1,15 +1,41 @@
|
||||
/*
|
||||
* Copyright 2013-2020 Signal Messenger, LLC
|
||||
* Copyright 2013 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.limits;
|
||||
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
import org.apache.commons.lang3.tuple.Pair;
|
||||
import org.whispersystems.textsecuregcm.configuration.RateLimitsConfiguration;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
|
||||
public class RateLimiters {
|
||||
|
||||
public enum Handle {
|
||||
USERNAME_LOOKUP("usernameLookup"),
|
||||
CHECK_ACCOUNT_EXISTENCE("checkAccountExistence"),
|
||||
BACKUP_AUTH_CHECK;
|
||||
|
||||
private final String id;
|
||||
|
||||
|
||||
Handle(final String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
Handle() {
|
||||
this.id = name();
|
||||
}
|
||||
|
||||
public String id() {
|
||||
return id;
|
||||
}
|
||||
}
|
||||
|
||||
private final RateLimiter smsDestinationLimiter;
|
||||
private final RateLimiter voiceDestinationLimiter;
|
||||
private final RateLimiter voiceDestinationDailyLimiter;
|
||||
@@ -17,114 +43,51 @@ public class RateLimiters {
|
||||
private final RateLimiter smsVoicePrefixLimiter;
|
||||
private final RateLimiter verifyLimiter;
|
||||
private final RateLimiter pinLimiter;
|
||||
|
||||
private final RateLimiter attachmentLimiter;
|
||||
private final RateLimiter preKeysLimiter;
|
||||
private final RateLimiter messagesLimiter;
|
||||
|
||||
private final RateLimiter allocateDeviceLimiter;
|
||||
private final RateLimiter verifyDeviceLimiter;
|
||||
|
||||
private final RateLimiter turnLimiter;
|
||||
|
||||
private final RateLimiter profileLimiter;
|
||||
private final RateLimiter stickerPackLimiter;
|
||||
|
||||
private final RateLimiter artPackLimiter;
|
||||
private final RateLimiter usernameLookupLimiter;
|
||||
private final RateLimiter usernameSetLimiter;
|
||||
|
||||
private final RateLimiter usernameReserveLimiter;
|
||||
|
||||
private final RateLimiter checkAccountExistenceLimiter;
|
||||
|
||||
private final RateLimiter storiesLimiter;
|
||||
|
||||
public RateLimiters(RateLimitsConfiguration config, FaultTolerantRedisCluster cacheCluster) {
|
||||
this.smsDestinationLimiter = new RateLimiter(cacheCluster, "smsDestination",
|
||||
config.getSmsDestination().getBucketSize(),
|
||||
config.getSmsDestination().getLeakRatePerMinute());
|
||||
private final Map<String, RateLimiter> rateLimiterByHandle;
|
||||
|
||||
this.voiceDestinationLimiter = new RateLimiter(cacheCluster, "voxDestination",
|
||||
config.getVoiceDestination().getBucketSize(),
|
||||
config.getVoiceDestination().getLeakRatePerMinute());
|
||||
public RateLimiters(final RateLimitsConfiguration config, final FaultTolerantRedisCluster cacheCluster) {
|
||||
this.smsDestinationLimiter = fromConfig("smsDestination", config.getSmsDestination(), cacheCluster);
|
||||
this.voiceDestinationLimiter = fromConfig("voxDestination", config.getVoiceDestination(), cacheCluster);
|
||||
this.voiceDestinationDailyLimiter = fromConfig("voxDestinationDaily", config.getVoiceDestinationDaily(), cacheCluster);
|
||||
this.smsVoiceIpLimiter = fromConfig("smsVoiceIp", config.getSmsVoiceIp(), cacheCluster);
|
||||
this.smsVoicePrefixLimiter = fromConfig("smsVoicePrefix", config.getSmsVoicePrefix(), cacheCluster);
|
||||
this.verifyLimiter = fromConfig("verify", config.getVerifyNumber(), cacheCluster);
|
||||
this.pinLimiter = fromConfig("pin", config.getVerifyPin(), cacheCluster);
|
||||
this.attachmentLimiter = fromConfig("attachmentCreate", config.getAttachments(), cacheCluster);
|
||||
this.preKeysLimiter = fromConfig("prekeys", config.getPreKeys(), cacheCluster);
|
||||
this.messagesLimiter = fromConfig("messages", config.getMessages(), cacheCluster);
|
||||
this.allocateDeviceLimiter = fromConfig("allocateDevice", config.getAllocateDevice(), cacheCluster);
|
||||
this.verifyDeviceLimiter = fromConfig("verifyDevice", config.getVerifyDevice(), cacheCluster);
|
||||
this.turnLimiter = fromConfig("turnAllocate", config.getTurnAllocations(), cacheCluster);
|
||||
this.profileLimiter = fromConfig("profile", config.getProfile(), cacheCluster);
|
||||
this.stickerPackLimiter = fromConfig("stickerPack", config.getStickerPack(), cacheCluster);
|
||||
this.artPackLimiter = fromConfig("artPack", config.getArtPack(), cacheCluster);
|
||||
this.usernameSetLimiter = fromConfig("usernameSet", config.getUsernameSet(), cacheCluster);
|
||||
this.usernameReserveLimiter = fromConfig("usernameReserve", config.getUsernameReserve(), cacheCluster);
|
||||
this.storiesLimiter = fromConfig("stories", config.getStories(), cacheCluster);
|
||||
|
||||
this.voiceDestinationDailyLimiter = new RateLimiter(cacheCluster, "voxDestinationDaily",
|
||||
config.getVoiceDestinationDaily().getBucketSize(),
|
||||
config.getVoiceDestinationDaily().getLeakRatePerMinute());
|
||||
this.rateLimiterByHandle = Stream.of(
|
||||
fromConfig(Handle.BACKUP_AUTH_CHECK.id(), config.getBackupAuthCheck(), cacheCluster),
|
||||
fromConfig(Handle.CHECK_ACCOUNT_EXISTENCE.id(), config.getCheckAccountExistence(), cacheCluster),
|
||||
fromConfig(Handle.USERNAME_LOOKUP.id(), config.getUsernameLookup(), cacheCluster)
|
||||
).map(rl -> Pair.of(rl.name, rl)).collect(Collectors.toMap(Pair::getKey, Pair::getValue));
|
||||
}
|
||||
|
||||
this.smsVoiceIpLimiter = new RateLimiter(cacheCluster, "smsVoiceIp",
|
||||
config.getSmsVoiceIp().getBucketSize(),
|
||||
config.getSmsVoiceIp().getLeakRatePerMinute());
|
||||
|
||||
this.smsVoicePrefixLimiter = new RateLimiter(cacheCluster, "smsVoicePrefix",
|
||||
config.getSmsVoicePrefix().getBucketSize(),
|
||||
config.getSmsVoicePrefix().getLeakRatePerMinute());
|
||||
|
||||
this.verifyLimiter = new LockingRateLimiter(cacheCluster, "verify",
|
||||
config.getVerifyNumber().getBucketSize(),
|
||||
config.getVerifyNumber().getLeakRatePerMinute());
|
||||
|
||||
this.pinLimiter = new LockingRateLimiter(cacheCluster, "pin",
|
||||
config.getVerifyPin().getBucketSize(),
|
||||
config.getVerifyPin().getLeakRatePerMinute());
|
||||
|
||||
this.attachmentLimiter = new RateLimiter(cacheCluster, "attachmentCreate",
|
||||
config.getAttachments().getBucketSize(),
|
||||
config.getAttachments().getLeakRatePerMinute());
|
||||
|
||||
this.preKeysLimiter = new RateLimiter(cacheCluster, "prekeys",
|
||||
config.getPreKeys().getBucketSize(),
|
||||
config.getPreKeys().getLeakRatePerMinute());
|
||||
|
||||
this.messagesLimiter = new RateLimiter(cacheCluster, "messages",
|
||||
config.getMessages().getBucketSize(),
|
||||
config.getMessages().getLeakRatePerMinute());
|
||||
|
||||
this.allocateDeviceLimiter = new RateLimiter(cacheCluster, "allocateDevice",
|
||||
config.getAllocateDevice().getBucketSize(),
|
||||
config.getAllocateDevice().getLeakRatePerMinute());
|
||||
|
||||
this.verifyDeviceLimiter = new RateLimiter(cacheCluster, "verifyDevice",
|
||||
config.getVerifyDevice().getBucketSize(),
|
||||
config.getVerifyDevice().getLeakRatePerMinute());
|
||||
|
||||
this.turnLimiter = new RateLimiter(cacheCluster, "turnAllocate",
|
||||
config.getTurnAllocations().getBucketSize(),
|
||||
config.getTurnAllocations().getLeakRatePerMinute());
|
||||
|
||||
this.profileLimiter = new RateLimiter(cacheCluster, "profile",
|
||||
config.getProfile().getBucketSize(),
|
||||
config.getProfile().getLeakRatePerMinute());
|
||||
|
||||
this.stickerPackLimiter = new RateLimiter(cacheCluster, "stickerPack",
|
||||
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());
|
||||
|
||||
this.usernameSetLimiter = new RateLimiter(cacheCluster, "usernameSet",
|
||||
config.getUsernameSet().getBucketSize(),
|
||||
config.getUsernameSet().getLeakRatePerMinute());
|
||||
|
||||
this.usernameReserveLimiter = new RateLimiter(cacheCluster, "usernameReserve",
|
||||
config.getUsernameReserve().getBucketSize(),
|
||||
config.getUsernameReserve().getLeakRatePerMinute());
|
||||
|
||||
|
||||
this.checkAccountExistenceLimiter = new RateLimiter(cacheCluster, "checkAccountExistence",
|
||||
config.getCheckAccountExistence().getBucketSize(),
|
||||
config.getCheckAccountExistence().getLeakRatePerMinute());
|
||||
|
||||
this.storiesLimiter = new RateLimiter(cacheCluster, "stories",
|
||||
config.getStories().getBucketSize(),
|
||||
config.getStories().getLeakRatePerMinute());
|
||||
public Optional<RateLimiter> byHandle(final Handle handle) {
|
||||
return Optional.ofNullable(rateLimiterByHandle.get(handle.id()));
|
||||
}
|
||||
|
||||
public RateLimiter getAllocateDeviceLimiter() {
|
||||
@@ -192,7 +155,7 @@ public class RateLimiters {
|
||||
}
|
||||
|
||||
public RateLimiter getUsernameLookupLimiter() {
|
||||
return usernameLookupLimiter;
|
||||
return byHandle(Handle.USERNAME_LOOKUP).orElseThrow();
|
||||
}
|
||||
|
||||
public RateLimiter getUsernameSetLimiter() {
|
||||
@@ -204,8 +167,17 @@ public class RateLimiters {
|
||||
}
|
||||
|
||||
public RateLimiter getCheckAccountExistenceLimiter() {
|
||||
return checkAccountExistenceLimiter;
|
||||
return byHandle(Handle.CHECK_ACCOUNT_EXISTENCE).orElseThrow();
|
||||
}
|
||||
|
||||
public RateLimiter getStoriesLimiter() { return storiesLimiter; }
|
||||
public RateLimiter getStoriesLimiter() {
|
||||
return storiesLimiter;
|
||||
}
|
||||
|
||||
private static RateLimiter fromConfig(
|
||||
final String name,
|
||||
final RateLimitsConfiguration.RateLimitConfiguration cfg,
|
||||
final FaultTolerantRedisCluster cacheCluster) {
|
||||
return new RateLimiter(cacheCluster, name, cfg.getBucketSize(), cfg.getLeakRatePerMinute());
|
||||
}
|
||||
}
|
||||
+4
-1
@@ -9,6 +9,7 @@ import static com.codahale.metrics.MetricRegistry.name;
|
||||
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import net.logstash.logback.marker.Markers;
|
||||
import org.slf4j.Logger;
|
||||
@@ -35,7 +36,9 @@ public class ReportedMessageMetricsListener implements ReportedMessageListener {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleMessageReported(final String sourceNumber, final UUID messageGuid, final UUID reporterUuid) {
|
||||
public void handleMessageReported(final String sourceNumber, final UUID messageGuid, final UUID reporterUuid,
|
||||
final Optional<byte[]> reportSpamToken) {
|
||||
|
||||
final String sourceCountryCode = Util.getCountryCode(sourceNumber);
|
||||
|
||||
Metrics.counter(REPORTED_COUNTER_NAME, COUNTRY_CODE_TAG_NAME, sourceCountryCode).increment();
|
||||
|
||||
+53
-7
@@ -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) {
|
||||
|
||||
+12
-11
@@ -1,41 +1,43 @@
|
||||
/*
|
||||
* Copyright 2021 Signal Messenger, LLC
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.securebackup;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.util.HeaderUtils.basicAuthHeader;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.common.net.HttpHeaders;
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.cert.CertificateException;
|
||||
import java.time.Duration;
|
||||
import java.util.Base64;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Executor;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialGenerator;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
|
||||
import org.whispersystems.textsecuregcm.configuration.SecureBackupServiceConfiguration;
|
||||
import org.whispersystems.textsecuregcm.http.FaultTolerantHttpClient;
|
||||
import org.whispersystems.textsecuregcm.util.HttpUtils;
|
||||
|
||||
/**
|
||||
* A client for sending requests to Signal's secure value recovery service on behalf of authenticated users.
|
||||
*/
|
||||
public class SecureBackupClient {
|
||||
|
||||
private final ExternalServiceCredentialGenerator secureBackupCredentialGenerator;
|
||||
private final ExternalServiceCredentialsGenerator secureBackupCredentialsGenerator;
|
||||
private final URI deleteUri;
|
||||
private final FaultTolerantHttpClient httpClient;
|
||||
|
||||
@VisibleForTesting
|
||||
static final String DELETE_PATH = "/v1/backup";
|
||||
|
||||
public SecureBackupClient(final ExternalServiceCredentialGenerator secureBackupCredentialGenerator, final Executor executor, final SecureBackupServiceConfiguration configuration) throws CertificateException {
|
||||
this.secureBackupCredentialGenerator = secureBackupCredentialGenerator;
|
||||
public SecureBackupClient(final ExternalServiceCredentialsGenerator secureBackupCredentialsGenerator, final Executor executor, final SecureBackupServiceConfiguration configuration) throws CertificateException {
|
||||
this.secureBackupCredentialsGenerator = secureBackupCredentialsGenerator;
|
||||
this.deleteUri = URI.create(configuration.getUri()).resolve(DELETE_PATH);
|
||||
this.httpClient = FaultTolerantHttpClient.newBuilder()
|
||||
.withCircuitBreaker(configuration.getCircuitBreakerConfiguration())
|
||||
@@ -51,17 +53,16 @@ public class SecureBackupClient {
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> deleteBackups(final UUID accountUuid) {
|
||||
final ExternalServiceCredentials credentials = secureBackupCredentialGenerator.generateFor(accountUuid.toString());
|
||||
final ExternalServiceCredentials credentials = secureBackupCredentialsGenerator.generateForUuid(accountUuid);
|
||||
|
||||
final HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(deleteUri)
|
||||
.DELETE()
|
||||
.header("Authorization", "Basic " + Base64.getEncoder().encodeToString(
|
||||
(credentials.getUsername() + ":" + credentials.getPassword()).getBytes(StandardCharsets.UTF_8)))
|
||||
.header(HttpHeaders.AUTHORIZATION, basicAuthHeader(credentials))
|
||||
.build();
|
||||
|
||||
return httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString()).thenApply(response -> {
|
||||
if (response.statusCode() >= 200 && response.statusCode() < 300) {
|
||||
if (HttpUtils.isSuccessfulResponse(response.statusCode())) {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
+19
-19
@@ -1,68 +1,68 @@
|
||||
/*
|
||||
* Copyright 2020 Signal Messenger, LLC
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.securestorage;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialGenerator;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
|
||||
import org.whispersystems.textsecuregcm.configuration.SecureStorageServiceConfiguration;
|
||||
import org.whispersystems.textsecuregcm.http.FaultTolerantHttpClient;
|
||||
import static org.whispersystems.textsecuregcm.util.HeaderUtils.basicAuthHeader;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.common.net.HttpHeaders;
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.cert.CertificateException;
|
||||
import java.time.Duration;
|
||||
import java.util.Base64;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Executor;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
|
||||
import org.whispersystems.textsecuregcm.configuration.SecureStorageServiceConfiguration;
|
||||
import org.whispersystems.textsecuregcm.http.FaultTolerantHttpClient;
|
||||
import org.whispersystems.textsecuregcm.util.HttpUtils;
|
||||
|
||||
/**
|
||||
* A client for sending requests to Signal's secure storage service on behalf of authenticated users.
|
||||
*/
|
||||
public class SecureStorageClient {
|
||||
|
||||
private final ExternalServiceCredentialGenerator storageServiceCredentialGenerator;
|
||||
private final ExternalServiceCredentialsGenerator storageServiceCredentialsGenerator;
|
||||
private final URI deleteUri;
|
||||
private final FaultTolerantHttpClient httpClient;
|
||||
|
||||
@VisibleForTesting
|
||||
static final String DELETE_PATH = "/v1/storage";
|
||||
|
||||
public SecureStorageClient(final ExternalServiceCredentialGenerator storageServiceCredentialGenerator, final Executor executor, final SecureStorageServiceConfiguration configuration) throws CertificateException {
|
||||
this.storageServiceCredentialGenerator = storageServiceCredentialGenerator;
|
||||
this.deleteUri = URI.create(configuration.getUri()).resolve(DELETE_PATH);
|
||||
public SecureStorageClient(final ExternalServiceCredentialsGenerator storageServiceCredentialsGenerator, final Executor executor, final SecureStorageServiceConfiguration configuration) throws CertificateException {
|
||||
this.storageServiceCredentialsGenerator = storageServiceCredentialsGenerator;
|
||||
this.deleteUri = URI.create(configuration.uri()).resolve(DELETE_PATH);
|
||||
this.httpClient = FaultTolerantHttpClient.newBuilder()
|
||||
.withCircuitBreaker(configuration.getCircuitBreakerConfiguration())
|
||||
.withRetry(configuration.getRetryConfiguration())
|
||||
.withCircuitBreaker(configuration.circuitBreaker())
|
||||
.withRetry(configuration.retry())
|
||||
.withVersion(HttpClient.Version.HTTP_1_1)
|
||||
.withConnectTimeout(Duration.ofSeconds(10))
|
||||
.withRedirect(HttpClient.Redirect.NEVER)
|
||||
.withExecutor(executor)
|
||||
.withName("secure-storage")
|
||||
.withSecurityProtocol(FaultTolerantHttpClient.SECURITY_PROTOCOL_TLS_1_3)
|
||||
.withTrustedServerCertificates(configuration.getStorageCaCertificates().toArray(new String[0]))
|
||||
.withTrustedServerCertificates(configuration.storageCaCertificates().toArray(new String[0]))
|
||||
.build();
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> deleteStoredData(final UUID accountUuid) {
|
||||
final ExternalServiceCredentials credentials = storageServiceCredentialGenerator.generateFor(accountUuid.toString());
|
||||
final ExternalServiceCredentials credentials = storageServiceCredentialsGenerator.generateForUuid(accountUuid);
|
||||
|
||||
final HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(deleteUri)
|
||||
.DELETE()
|
||||
.header("Authorization", "Basic " + Base64.getEncoder().encodeToString(
|
||||
(credentials.getUsername() + ":" + credentials.getPassword()).getBytes(StandardCharsets.UTF_8)))
|
||||
.header(HttpHeaders.AUTHORIZATION, basicAuthHeader(credentials))
|
||||
.build();
|
||||
|
||||
return httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString()).thenApply(response -> {
|
||||
if (response.statusCode() >= 200 && response.statusCode() < 300) {
|
||||
if (HttpUtils.isSuccessfulResponse(response.statusCode())) {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
+3
-3
@@ -3,7 +3,7 @@
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.abuse;
|
||||
package org.whispersystems.textsecuregcm.spam;
|
||||
|
||||
import javax.ws.rs.NameBinding;
|
||||
import java.lang.annotation.ElementType;
|
||||
@@ -12,10 +12,10 @@ import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/**
|
||||
* A name-binding annotation that associates {@link AbusiveMessageFilter}s with resource methods.
|
||||
* A name-binding annotation that associates {@link SpamFilter}s with resource methods.
|
||||
*/
|
||||
@NameBinding
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target({ElementType.TYPE, ElementType.METHOD})
|
||||
public @interface FilterAbusiveMessages {
|
||||
public @interface FilterSpam {
|
||||
}
|
||||
+1
-1
@@ -3,7 +3,7 @@
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.abuse;
|
||||
package org.whispersystems.textsecuregcm.spam;
|
||||
|
||||
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
+1
-1
@@ -3,7 +3,7 @@
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.abuse;
|
||||
package org.whispersystems.textsecuregcm.spam;
|
||||
|
||||
public enum RateLimitChallengeType {
|
||||
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package org.whispersystems.textsecuregcm.spam;
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
/*
|
||||
* Copyright 2013-2021 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.spam;
|
||||
|
||||
import io.dropwizard.lifecycle.Managed;
|
||||
import org.whispersystems.textsecuregcm.storage.ReportedMessageListener;
|
||||
import javax.ws.rs.container.ContainerRequestFilter;
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* A spam filter is a {@link ContainerRequestFilter} that filters requests to message-sending endpoints to
|
||||
* detect and respond to patterns of spam.
|
||||
* <p/>
|
||||
* Spam filters are managed components that are generally loaded dynamically via a
|
||||
* {@link java.util.ServiceLoader}. Their {@link #configure(String)} method will be called prior to be adding to the
|
||||
* server's pool of {@link Managed} objects.
|
||||
* <p/>
|
||||
* Spam filters must be annotated with {@link FilterSpam}, a name binding annotation that
|
||||
* restricts the endpoints to which the filter may apply.
|
||||
*/
|
||||
public interface SpamFilter extends ContainerRequestFilter, Managed {
|
||||
|
||||
/**
|
||||
* Configures this spam filter. This method will be called before the filter is added to the server's pool
|
||||
* of managed objects and before the server processes any requests.
|
||||
*
|
||||
* @param environmentName the name of the environment in which this filter is running (e.g. "staging" or "production")
|
||||
* @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();
|
||||
|
||||
/**
|
||||
* Return any and all reported message listeners controlled by the spam filter. Listeners will be registered with the
|
||||
* {@link org.whispersystems.textsecuregcm.storage.ReportMessageManager}.
|
||||
*
|
||||
* @return a list of reported message listeners controlled by the spam filter
|
||||
*/
|
||||
List<ReportedMessageListener> getReportedMessageListeners();
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2013-2022 Signal Messenger, LLC
|
||||
* Copyright 2013 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
@@ -18,7 +18,7 @@ import java.util.function.Predicate;
|
||||
import javax.annotation.Nullable;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticationCredentials;
|
||||
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
|
||||
import org.whispersystems.textsecuregcm.auth.StoredRegistrationLock;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
|
||||
import org.whispersystems.textsecuregcm.storage.Device.DeviceCapabilities;
|
||||
@@ -390,8 +390,8 @@ public class Account {
|
||||
|
||||
public void setRegistrationLockFromAttributes(final AccountAttributes attributes) {
|
||||
if (!Util.isEmpty(attributes.getRegistrationLock())) {
|
||||
AuthenticationCredentials credentials = new AuthenticationCredentials(attributes.getRegistrationLock());
|
||||
setRegistrationLock(credentials.getHashedAuthenticationToken(), credentials.getSalt());
|
||||
SaltedTokenHash credentials = SaltedTokenHash.generateFor(attributes.getRegistrationLock());
|
||||
setRegistrationLock(credentials.hash(), credentials.salt());
|
||||
} else {
|
||||
setRegistrationLock(null, null);
|
||||
}
|
||||
@@ -485,8 +485,8 @@ public class Account {
|
||||
* of the phone number, or after 7 days the phone number holder can register a new
|
||||
* account.
|
||||
*/
|
||||
public void lockAuthenticationCredentials() {
|
||||
devices.forEach(Device::lockAuthenticationCredentials);
|
||||
public void lockAuthTokenHash() {
|
||||
devices.forEach(Device::lockAuthTokenHash);
|
||||
}
|
||||
|
||||
boolean isStale() {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2013-2022 Signal Messenger, LLC
|
||||
* Copyright 2013 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
@@ -36,7 +36,7 @@ import java.util.function.Supplier;
|
||||
import javax.annotation.Nullable;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticationCredentials;
|
||||
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
|
||||
import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
|
||||
import org.whispersystems.textsecuregcm.entities.SignedPreKey;
|
||||
@@ -169,7 +169,7 @@ public class AccountsManager {
|
||||
deletedAccountsManager.lockAndTake(number, maybeRecentlyDeletedUuid -> {
|
||||
Device device = new Device();
|
||||
device.setId(Device.MASTER_ID);
|
||||
device.setAuthenticationCredentials(new AuthenticationCredentials(password));
|
||||
device.setAuthTokenHash(SaltedTokenHash.generateFor(password));
|
||||
device.setFetchesMessages(accountAttributes.getFetchesMessages());
|
||||
device.setRegistrationId(accountAttributes.getRegistrationId());
|
||||
accountAttributes.getPhoneNumberIdentityRegistrationId().ifPresent(device::setPhoneNumberIdentityRegistrationId);
|
||||
@@ -496,12 +496,12 @@ public class AccountsManager {
|
||||
});
|
||||
}
|
||||
|
||||
public Account updateDeviceAuthentication(final Account account, final Device device, final AuthenticationCredentials credentials) {
|
||||
Preconditions.checkArgument(credentials.getVersion() == AuthenticationCredentials.CURRENT_VERSION);
|
||||
public Account updateDeviceAuthentication(final Account account, final Device device, final SaltedTokenHash credentials) {
|
||||
Preconditions.checkArgument(credentials.getVersion() == SaltedTokenHash.CURRENT_VERSION);
|
||||
return updateDevice(account, device.getId(), new Consumer<Device>() {
|
||||
@Override
|
||||
public void accept(final Device device) {
|
||||
device.setAuthenticationCredentials(credentials);
|
||||
device.setAuthTokenHash(credentials);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2013-2022 Signal Messenger, LLC
|
||||
* Copyright 2013 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
@@ -9,7 +9,7 @@ import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import java.util.OptionalInt;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import javax.annotation.Nullable;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticationCredentials;
|
||||
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
|
||||
import org.whispersystems.textsecuregcm.entities.SignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
@@ -144,9 +144,9 @@ public class Device {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public void setAuthenticationCredentials(AuthenticationCredentials credentials) {
|
||||
this.authToken = credentials.getHashedAuthenticationToken();
|
||||
this.salt = credentials.getSalt();
|
||||
public void setAuthTokenHash(SaltedTokenHash credentials) {
|
||||
this.authToken = credentials.hash();
|
||||
this.salt = credentials.salt();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -158,8 +158,8 @@ public class Device {
|
||||
* @return true if the credential was locked, false otherwise.
|
||||
*/
|
||||
public boolean hasLockedCredentials() {
|
||||
AuthenticationCredentials auth = getAuthenticationCredentials();
|
||||
return auth.getHashedAuthenticationToken().startsWith("!");
|
||||
SaltedTokenHash auth = getAuthTokenHash();
|
||||
return auth.hash().startsWith("!");
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -169,15 +169,15 @@ public class Device {
|
||||
*
|
||||
* See that method for more information.
|
||||
*/
|
||||
public void lockAuthenticationCredentials() {
|
||||
AuthenticationCredentials oldAuth = getAuthenticationCredentials();
|
||||
String token = "!" + oldAuth.getHashedAuthenticationToken();
|
||||
String salt = oldAuth.getSalt();
|
||||
setAuthenticationCredentials(new AuthenticationCredentials(token, salt));
|
||||
public void lockAuthTokenHash() {
|
||||
SaltedTokenHash oldAuth = getAuthTokenHash();
|
||||
String token = "!" + oldAuth.hash();
|
||||
String salt = oldAuth.salt();
|
||||
setAuthTokenHash(new SaltedTokenHash(token, salt));
|
||||
}
|
||||
|
||||
public AuthenticationCredentials getAuthenticationCredentials() {
|
||||
return new AuthenticationCredentials(authToken, salt);
|
||||
public SaltedTokenHash getAuthTokenHash() {
|
||||
return new SaltedTokenHash(authToken, salt);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
|
||||
+5
-1
@@ -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;
|
||||
|
||||
+19
-4
@@ -15,8 +15,10 @@ import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
|
||||
@@ -29,6 +31,10 @@ public class ReportMessageManager {
|
||||
|
||||
private final List<ReportedMessageListener> reportedMessageListeners = new ArrayList<>();
|
||||
|
||||
private static final String REPORT_MESSAGE_COUNTER_NAME = MetricsUtil.name(ReportMessageManager.class);
|
||||
private static final String FOUND_MESSAGE_TAG = "foundMessage";
|
||||
private static final String TOKEN_PRESENT_TAG = "hasReportSpamToken";
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(ReportMessageManager.class);
|
||||
|
||||
public ReportMessageManager(final ReportMessageDynamoDb reportMessageDynamoDb,
|
||||
@@ -56,12 +62,21 @@ public class ReportMessageManager {
|
||||
}
|
||||
}
|
||||
|
||||
public void report(Optional<String> sourceNumber, Optional<UUID> sourceAci, Optional<UUID> sourcePni,
|
||||
UUID messageGuid, UUID reporterUuid) {
|
||||
public void report(final Optional<String> sourceNumber,
|
||||
final Optional<UUID> sourceAci,
|
||||
final Optional<UUID> sourcePni,
|
||||
final UUID messageGuid,
|
||||
final UUID reporterUuid,
|
||||
final Optional<byte[]> reportSpamToken) {
|
||||
|
||||
final boolean found = sourceAci.map(uuid -> reportMessageDynamoDb.remove(hash(messageGuid, uuid.toString())))
|
||||
.orElse(false);
|
||||
|
||||
Metrics.counter(REPORT_MESSAGE_COUNTER_NAME,
|
||||
FOUND_MESSAGE_TAG, String.valueOf(found),
|
||||
TOKEN_PRESENT_TAG, String.valueOf(reportSpamToken.isPresent()))
|
||||
.increment();
|
||||
|
||||
if (found) {
|
||||
rateLimitCluster.useCluster(connection -> {
|
||||
sourcePni.ifPresent(pni -> {
|
||||
@@ -80,7 +95,7 @@ public class ReportMessageManager {
|
||||
sourceNumber.ifPresent(number ->
|
||||
reportedMessageListeners.forEach(listener -> {
|
||||
try {
|
||||
listener.handleMessageReported(number, messageGuid, reporterUuid);
|
||||
listener.handleMessageReported(number, messageGuid, reporterUuid, reportSpamToken);
|
||||
} catch (final Exception e) {
|
||||
logger.error("Failed to notify listener of reported message", e);
|
||||
}
|
||||
@@ -89,7 +104,7 @@ public class ReportMessageManager {
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the number of times messages from the given account have been reported by recipients as abusive. Note that
|
||||
* Returns the number of times messages from the given account have been reported by recipients as spam. Note that
|
||||
* this method makes a call to an external service, and callers should take care to memoize calls where possible and
|
||||
* avoid unnecessary calls.
|
||||
*
|
||||
|
||||
+2
-1
@@ -5,9 +5,10 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
public interface ReportedMessageListener {
|
||||
|
||||
void handleMessageReported(String sourceNumber, UUID messageGuid, UUID reporterUuid);
|
||||
void handleMessageReported(String sourceNumber, UUID messageGuid, UUID reporterUuid, Optional<byte[]> reportSpamToken);
|
||||
}
|
||||
+10
-11
@@ -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;
|
||||
|
||||
@@ -48,8 +47,6 @@ public class SubscriptionManager {
|
||||
public static final String KEY_PASSWORD = "P"; // B
|
||||
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
|
||||
@Deprecated
|
||||
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";
|
||||
@@ -68,6 +65,7 @@ public class SubscriptionManager {
|
||||
@VisibleForTesting
|
||||
@Nullable
|
||||
ProcessorCustomer processorCustomer;
|
||||
@Nullable
|
||||
public String subscriptionId;
|
||||
public Instant subscriptionCreatedAt;
|
||||
public Long subscriptionLevel;
|
||||
@@ -190,7 +188,8 @@ public class SubscriptionManager {
|
||||
if (count == 0) {
|
||||
return null;
|
||||
} else if (count > 1) {
|
||||
logger.error("expected invariant of 1-1 subscriber-customer violated for customer {}", processorCustomer);
|
||||
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 " + processorCustomer);
|
||||
} else {
|
||||
@@ -264,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) -> {
|
||||
@@ -398,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()
|
||||
@@ -407,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();
|
||||
|
||||
+98
@@ -11,19 +11,29 @@ 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;
|
||||
@@ -185,6 +195,94 @@ class BraintreeGraphqlClient {
|
||||
);
|
||||
}
|
||||
|
||||
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}.
|
||||
|
||||
+325
-11
@@ -6,19 +6,36 @@
|
||||
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.ws.rs.BadRequestException;
|
||||
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;
|
||||
@@ -97,16 +114,6 @@ public class BraintreeManager implements SubscriptionProcessorManager {
|
||||
}, executor);
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<ProcessorCustomer> createCustomer(final byte[] subscriberUser) {
|
||||
return CompletableFuture.failedFuture(new BadRequestException("Unsupported"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<String> createPaymentMethodSetupToken(final String customerId) {
|
||||
return CompletableFuture.failedFuture(new BadRequestException("Unsupported"));
|
||||
}
|
||||
|
||||
public CompletableFuture<PayPalOneTimePaymentApprovalDetails> createOneTimePayment(String currency, long amount,
|
||||
String locale, String returnUrl, String cancelUrl) {
|
||||
return braintreeGraphqlClient.createPayPalOneTimePayment(convertApiAmountToBraintreeAmount(currency, amount),
|
||||
@@ -187,6 +194,19 @@ public class BraintreeManager implements SubscriptionProcessorManager {
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
@@ -203,4 +223,298 @@ public class BraintreeManager implements SubscriptionProcessorManager {
|
||||
|
||||
}
|
||||
|
||||
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<LevelAndCurrency> getLevelAndCurrencyForSubscription(Object subscriptionObj) {
|
||||
final Subscription subscription = getSubscription(subscriptionObj);
|
||||
|
||||
return findPlan(subscription.getPlanId())
|
||||
.thenApply(
|
||||
plan -> new LevelAndCurrency(getLevelForPlan(plan), plan.getCurrencyIsoCode().toLowerCase(Locale.ROOT)));
|
||||
|
||||
}
|
||||
|
||||
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) {
|
||||
|
||||
}
|
||||
}
|
||||
+10
@@ -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) {
|
||||
|
||||
}
|
||||
+182
-72
@@ -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;
|
||||
@@ -57,10 +57,12 @@ 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 {
|
||||
@@ -144,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);
|
||||
@@ -154,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);
|
||||
}
|
||||
@@ -234,65 +239,78 @@ public class StripeManager implements SubscriptionProcessorManager {
|
||||
};
|
||||
}
|
||||
|
||||
public CompletableFuture<Subscription> createSubscription(String customerId, String priceId, long level,
|
||||
private static SubscriptionStatus getSubscriptionStatus(final String status) {
|
||||
return SubscriptionStatus.forApiValue(status);
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<SubscriptionId> createSubscription(String customerId, String priceId, long level,
|
||||
long lastSubscriptionCreatedAt) {
|
||||
// this relies on Stripe's idempotency key to avoid creating more than one subscription if the client
|
||||
// retries this request
|
||||
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);
|
||||
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()));
|
||||
}
|
||||
|
||||
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))
|
||||
@Override
|
||||
public CompletableFuture<SubscriptionId> updateSubscription(
|
||||
Object subscriptionObj, String priceId, long level, String idempotencyKey) {
|
||||
|
||||
// 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);
|
||||
final Subscription subscription = getSubscription(subscriptionObj);
|
||||
|
||||
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<Subscription> getSubscription(String subscriptionId) {
|
||||
public CompletableFuture<Object> getSubscription(String subscriptionId) {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
SubscriptionRetrieveParams params = SubscriptionRetrieveParams.builder()
|
||||
.addExpand("latest_invoice")
|
||||
@@ -306,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()
|
||||
@@ -362,12 +395,17 @@ 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) {
|
||||
return getProductForSubscription(subscription).thenApply(this::getLevelForProduct);
|
||||
@Override
|
||||
public CompletableFuture<LevelAndCurrency> getLevelAndCurrencyForSubscription(Object subscriptionObj) {
|
||||
final Subscription subscription = getSubscription(subscriptionObj);
|
||||
|
||||
return getProductForSubscription(subscription).thenApply(
|
||||
product -> new LevelAndCurrency(getLevelForProduct(product), subscription.getCurrency().toLowerCase(
|
||||
Locale.ROOT)));
|
||||
}
|
||||
|
||||
public CompletableFuture<Long> getLevelForPrice(Price price) {
|
||||
@@ -404,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) {
|
||||
@@ -413,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()
|
||||
@@ -426,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
|
||||
|
||||
+74
@@ -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);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -36,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);
|
||||
}
|
||||
|
||||
|
||||
+130
-1
@@ -5,13 +5,16 @@
|
||||
|
||||
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);
|
||||
@@ -26,6 +29,36 @@ public interface SubscriptionProcessorManager {
|
||||
|
||||
CompletableFuture<String> createPaymentMethodSetupToken(String customerId);
|
||||
|
||||
|
||||
/**
|
||||
* @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);
|
||||
|
||||
/**
|
||||
* @param subscription
|
||||
* @return the subscription’s current level and lower-case currency code
|
||||
*/
|
||||
CompletableFuture<LevelAndCurrency> getLevelAndCurrencyForSubscription(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,
|
||||
@@ -39,4 +72,100 @@ public interface SubscriptionProcessorManager {
|
||||
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) {
|
||||
|
||||
}
|
||||
|
||||
record LevelAndCurrency(long level, String currency) {
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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,56 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.util;
|
||||
|
||||
import static java.lang.annotation.ElementType.FIELD;
|
||||
import static java.lang.annotation.ElementType.METHOD;
|
||||
import static java.lang.annotation.ElementType.PARAMETER;
|
||||
import static java.lang.annotation.RetentionPolicy.RUNTIME;
|
||||
|
||||
import java.lang.annotation.Documented;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.Target;
|
||||
import java.util.Objects;
|
||||
import javax.validation.Constraint;
|
||||
import javax.validation.ConstraintValidator;
|
||||
import javax.validation.ConstraintValidatorContext;
|
||||
import javax.validation.Payload;
|
||||
|
||||
/**
|
||||
* Constraint annotation that requires annotated entity
|
||||
* to hold (or return) a string value that is a valid E164-normalized phone number.
|
||||
*/
|
||||
@Target({ FIELD, PARAMETER, METHOD })
|
||||
@Retention(RUNTIME)
|
||||
@Constraint(validatedBy = E164.Validator.class)
|
||||
@Documented
|
||||
public @interface E164 {
|
||||
|
||||
String message() default "{org.whispersystems.textsecuregcm.util.E164.message}";
|
||||
|
||||
Class<?>[] groups() default { };
|
||||
|
||||
Class<? extends Payload>[] payload() default { };
|
||||
|
||||
class Validator implements ConstraintValidator<E164, String> {
|
||||
|
||||
@Override
|
||||
public boolean isValid(final String value, final ConstraintValidatorContext context) {
|
||||
if (Objects.isNull(value)) {
|
||||
return true;
|
||||
}
|
||||
if (!value.startsWith("+")) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
Util.requireNormalizedNumber(value);
|
||||
} catch (final ImpossiblePhoneNumberException | NonNormalizedPhoneNumberException e) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -27,7 +27,7 @@ public final class ExceptionUtils {
|
||||
}
|
||||
|
||||
/**
|
||||
* Wraps the given {@code throwable} in a {@link CompletionException} unless the given {@code throwable} is alreadt
|
||||
* 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}
|
||||
|
||||
@@ -1,14 +1,19 @@
|
||||
/*
|
||||
* Copyright 2022 Signal Messenger, LLC
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.util;
|
||||
|
||||
import static java.util.Objects.requireNonNull;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Base64;
|
||||
import java.util.Optional;
|
||||
import javax.annotation.Nonnull;
|
||||
import javax.annotation.Nullable;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
|
||||
|
||||
public final class HeaderUtils {
|
||||
|
||||
@@ -22,6 +27,16 @@ public final class HeaderUtils {
|
||||
// utility class
|
||||
}
|
||||
|
||||
public static String basicAuthHeader(final ExternalServiceCredentials credentials) {
|
||||
return basicAuthHeader(credentials.username(), credentials.password());
|
||||
}
|
||||
|
||||
public static String basicAuthHeader(final String username, final String password) {
|
||||
requireNonNull(username);
|
||||
requireNonNull(password);
|
||||
return "Basic " + Base64.getEncoder().encodeToString((username + ":" + password).getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
@Nonnull
|
||||
public static String getTimestampHeader() {
|
||||
return TIMESTAMP_HEADER + ":" + System.currentTimeMillis();
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.util;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.InvalidKeyException;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.HexFormat;
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
|
||||
public final class HmacUtils {
|
||||
|
||||
private static final HexFormat HEX = HexFormat.of();
|
||||
|
||||
private static final String HMAC_SHA_256 = "HmacSHA256";
|
||||
|
||||
private static final ThreadLocal<Mac> THREAD_LOCAL_HMAC_SHA_256 = ThreadLocal.withInitial(() -> {
|
||||
try {
|
||||
return Mac.getInstance(HMAC_SHA_256);
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
});
|
||||
|
||||
public static byte[] hmac256(final byte[] key, final byte[] input) {
|
||||
try {
|
||||
final Mac mac = THREAD_LOCAL_HMAC_SHA_256.get();
|
||||
mac.init(new SecretKeySpec(key, HMAC_SHA_256));
|
||||
return mac.doFinal(input);
|
||||
} catch (final InvalidKeyException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public static byte[] hmac256(final byte[] key, final String input) {
|
||||
return hmac256(key, input.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
public static String hmac256ToHexString(final byte[] key, final byte[] input) {
|
||||
return HEX.formatHex(hmac256(key, input));
|
||||
}
|
||||
|
||||
public static String hmac256ToHexString(final byte[] key, final String input) {
|
||||
return hmac256ToHexString(key, input.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
public static byte[] hmac256Truncated(final byte[] key, final byte[] input, final int length) {
|
||||
return Util.truncate(hmac256(key, input), length);
|
||||
}
|
||||
|
||||
public static byte[] hmac256Truncated(final byte[] key, final String input, final int length) {
|
||||
return hmac256Truncated(key, input.getBytes(StandardCharsets.UTF_8), length);
|
||||
}
|
||||
|
||||
public static String hmac256TruncatedToHexString(final byte[] key, final byte[] input, final int length) {
|
||||
return HEX.formatHex(Util.truncate(hmac256(key, input), length));
|
||||
}
|
||||
|
||||
public static String hmac256TruncatedToHexString(final byte[] key, final String input, final int length) {
|
||||
return hmac256TruncatedToHexString(key, input.getBytes(StandardCharsets.UTF_8), length);
|
||||
}
|
||||
|
||||
public static boolean hmacHexStringsEqual(final String expectedAsHexString, final String actualAsHexString) {
|
||||
try {
|
||||
final byte[] aBytes = HEX.parseHex(expectedAsHexString);
|
||||
final byte[] bBytes = HEX.parseHex(actualAsHexString);
|
||||
return MessageDigest.isEqual(aBytes, bBytes);
|
||||
} catch (final IllegalArgumentException e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.util;
|
||||
|
||||
public final class HttpUtils {
|
||||
|
||||
private HttpUtils() {
|
||||
// utility class
|
||||
}
|
||||
|
||||
public static boolean isSuccessfulResponse(final int statusCode) {
|
||||
return statusCode >= 200 && statusCode < 300;
|
||||
}
|
||||
}
|
||||
@@ -7,35 +7,48 @@ package org.whispersystems.textsecuregcm.util;
|
||||
|
||||
import java.nio.BufferUnderflowException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
public class UUIDUtil {
|
||||
public final class UUIDUtil {
|
||||
|
||||
public static byte[] toBytes(final UUID uuid) {
|
||||
return toByteBuffer(uuid).array();
|
||||
}
|
||||
private UUIDUtil() {
|
||||
// utility class
|
||||
}
|
||||
|
||||
public static ByteBuffer toByteBuffer(final UUID uuid) {
|
||||
final ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[16]);
|
||||
byteBuffer.putLong(uuid.getMostSignificantBits());
|
||||
byteBuffer.putLong(uuid.getLeastSignificantBits());
|
||||
return byteBuffer.flip();
|
||||
}
|
||||
public static byte[] toBytes(final UUID uuid) {
|
||||
return toByteBuffer(uuid).array();
|
||||
}
|
||||
|
||||
public static UUID fromBytes(final byte[] bytes) {
|
||||
return fromByteBuffer(ByteBuffer.wrap(bytes));
|
||||
}
|
||||
public static ByteBuffer toByteBuffer(final UUID uuid) {
|
||||
final ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[16]);
|
||||
byteBuffer.putLong(uuid.getMostSignificantBits());
|
||||
byteBuffer.putLong(uuid.getLeastSignificantBits());
|
||||
return byteBuffer.flip();
|
||||
}
|
||||
|
||||
public static UUID fromByteBuffer(final ByteBuffer byteBuffer) {
|
||||
try {
|
||||
final long mostSigBits = byteBuffer.getLong();
|
||||
final long leastSigBits = byteBuffer.getLong();
|
||||
if (byteBuffer.hasRemaining()) {
|
||||
throw new IllegalArgumentException("unexpected byte array length; was greater than 16");
|
||||
}
|
||||
return new UUID(mostSigBits, leastSigBits);
|
||||
} catch (BufferUnderflowException e) {
|
||||
throw new IllegalArgumentException("unexpected byte array length; was less than 16");
|
||||
public static UUID fromBytes(final byte[] bytes) {
|
||||
return fromByteBuffer(ByteBuffer.wrap(bytes));
|
||||
}
|
||||
|
||||
public static UUID fromByteBuffer(final ByteBuffer byteBuffer) {
|
||||
try {
|
||||
final long mostSigBits = byteBuffer.getLong();
|
||||
final long leastSigBits = byteBuffer.getLong();
|
||||
if (byteBuffer.hasRemaining()) {
|
||||
throw new IllegalArgumentException("unexpected byte array length; was greater than 16");
|
||||
}
|
||||
return new UUID(mostSigBits, leastSigBits);
|
||||
} catch (BufferUnderflowException e) {
|
||||
throw new IllegalArgumentException("unexpected byte array length; was less than 16");
|
||||
}
|
||||
}
|
||||
|
||||
public static Optional<UUID> fromStringSafe(final String uuidString) {
|
||||
try {
|
||||
return Optional.of(UUID.fromString(uuidString));
|
||||
} catch (final IllegalArgumentException e) {
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
}
|
||||
+9
-7
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2013-2021 Signal Messenger, LLC
|
||||
* Copyright 2013 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
@@ -23,8 +23,10 @@ import java.util.concurrent.Executors;
|
||||
import net.sourceforge.argparse4j.inf.Namespace;
|
||||
import net.sourceforge.argparse4j.inf.Subparser;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialGenerator;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.controllers.SecureBackupController;
|
||||
import org.whispersystems.textsecuregcm.controllers.SecureStorageController;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
@@ -103,11 +105,11 @@ public class AssignUsernameCommand extends EnvironmentCommand<WhisperServerConfi
|
||||
ExecutorService storageServiceExecutor = environment.lifecycle()
|
||||
.executorService(name(getClass(), "storageService-%d")).maxThreads(8).minThreads(1).build();
|
||||
|
||||
ExternalServiceCredentialGenerator backupCredentialsGenerator = new ExternalServiceCredentialGenerator(
|
||||
configuration.getSecureBackupServiceConfiguration().getUserAuthenticationTokenSharedSecret(), true);
|
||||
ExternalServiceCredentialGenerator storageCredentialsGenerator = new ExternalServiceCredentialGenerator(
|
||||
configuration.getSecureStorageServiceConfiguration().getUserAuthenticationTokenSharedSecret(), true);
|
||||
|
||||
ExternalServiceCredentialsGenerator backupCredentialsGenerator = SecureBackupController.credentialsGenerator(
|
||||
configuration.getSecureBackupServiceConfiguration());
|
||||
ExternalServiceCredentialsGenerator storageCredentialsGenerator = SecureStorageController.credentialsGenerator(
|
||||
configuration.getSecureStorageServiceConfiguration());
|
||||
|
||||
DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager = new DynamicConfigurationManager<>(
|
||||
configuration.getAppConfig().getApplication(), configuration.getAppConfig().getEnvironment(),
|
||||
configuration.getAppConfig().getConfigurationName(), DynamicConfiguration.class);
|
||||
|
||||
+9
-7
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2013-2021 Signal Messenger, LLC
|
||||
* Copyright 2013 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
@@ -25,8 +25,10 @@ import net.sourceforge.argparse4j.inf.Subparser;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialGenerator;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.controllers.SecureBackupController;
|
||||
import org.whispersystems.textsecuregcm.controllers.SecureStorageController;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
@@ -105,11 +107,11 @@ public class DeleteUserCommand extends EnvironmentCommand<WhisperServerConfigura
|
||||
ExecutorService storageServiceExecutor = environment.lifecycle()
|
||||
.executorService(name(getClass(), "storageService-%d")).maxThreads(8).minThreads(1).build();
|
||||
|
||||
ExternalServiceCredentialGenerator backupCredentialsGenerator = new ExternalServiceCredentialGenerator(
|
||||
configuration.getSecureBackupServiceConfiguration().getUserAuthenticationTokenSharedSecret(), true);
|
||||
ExternalServiceCredentialGenerator storageCredentialsGenerator = new ExternalServiceCredentialGenerator(
|
||||
configuration.getSecureStorageServiceConfiguration().getUserAuthenticationTokenSharedSecret(), true);
|
||||
|
||||
ExternalServiceCredentialsGenerator backupCredentialsGenerator = SecureBackupController.credentialsGenerator(
|
||||
configuration.getSecureBackupServiceConfiguration());
|
||||
ExternalServiceCredentialsGenerator storageCredentialsGenerator = SecureStorageController.credentialsGenerator(
|
||||
configuration.getSecureStorageServiceConfiguration());
|
||||
|
||||
DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager = new DynamicConfigurationManager<>(
|
||||
configuration.getAppConfig().getApplication(), configuration.getAppConfig().getEnvironment(),
|
||||
configuration.getAppConfig().getConfigurationName(), DynamicConfiguration.class);
|
||||
|
||||
+9
-7
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2013-2021 Signal Messenger, LLC
|
||||
* Copyright 2013 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
@@ -24,8 +24,10 @@ import java.util.concurrent.Executors;
|
||||
import net.sourceforge.argparse4j.inf.Namespace;
|
||||
import net.sourceforge.argparse4j.inf.Subparser;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialGenerator;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.controllers.SecureBackupController;
|
||||
import org.whispersystems.textsecuregcm.controllers.SecureStorageController;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
@@ -108,11 +110,11 @@ public class SetUserDiscoverabilityCommand extends EnvironmentCommand<WhisperSer
|
||||
ExecutorService storageServiceExecutor = environment.lifecycle()
|
||||
.executorService(name(getClass(), "storageService-%d")).maxThreads(8).minThreads(1).build();
|
||||
|
||||
ExternalServiceCredentialGenerator backupCredentialsGenerator = new ExternalServiceCredentialGenerator(
|
||||
configuration.getSecureBackupServiceConfiguration().getUserAuthenticationTokenSharedSecret(), true);
|
||||
ExternalServiceCredentialGenerator storageCredentialsGenerator = new ExternalServiceCredentialGenerator(
|
||||
configuration.getSecureStorageServiceConfiguration().getUserAuthenticationTokenSharedSecret(), true);
|
||||
|
||||
ExternalServiceCredentialsGenerator backupCredentialsGenerator = SecureBackupController.credentialsGenerator(
|
||||
configuration.getSecureBackupServiceConfiguration());
|
||||
ExternalServiceCredentialsGenerator storageCredentialsGenerator = SecureStorageController.credentialsGenerator(
|
||||
configuration.getSecureStorageServiceConfiguration());
|
||||
|
||||
DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager = new DynamicConfigurationManager<>(
|
||||
configuration.getAppConfig().getApplication(), configuration.getAppConfig().getEnvironment(),
|
||||
configuration.getAppConfig().getConfigurationName(), DynamicConfiguration.class);
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -27,5 +27,5 @@ R_HIGH_description = {short_name} supports Signal with a monthly donation. Signa
|
||||
BOOST_name = Signal Boost
|
||||
BOOST_description = {short_name} supported Signal with a donation. Signal is a nonprofit with no advertisers or investors, supported only by people like you.
|
||||
|
||||
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.
|
||||
GIFT_name = Signal UFO
|
||||
GIFT_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.
|
||||
+41
-33
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2013-2021 Signal Messenger, LLC
|
||||
* Copyright 2013 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
@@ -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;
|
||||
@@ -156,7 +155,7 @@ class BaseAccountAuthenticatorTest {
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
final Device device = mock(Device.class);
|
||||
final AuthenticationCredentials credentials = mock(AuthenticationCredentials.class);
|
||||
final SaltedTokenHash credentials = mock(SaltedTokenHash.class);
|
||||
|
||||
clock.unpin();
|
||||
when(accountsManager.getByAccountIdentifier(uuid)).thenReturn(Optional.of(account));
|
||||
@@ -165,9 +164,9 @@ class BaseAccountAuthenticatorTest {
|
||||
when(account.isEnabled()).thenReturn(true);
|
||||
when(device.getId()).thenReturn(deviceId);
|
||||
when(device.isEnabled()).thenReturn(true);
|
||||
when(device.getAuthenticationCredentials()).thenReturn(credentials);
|
||||
when(device.getAuthTokenHash()).thenReturn(credentials);
|
||||
when(credentials.verify(password)).thenReturn(true);
|
||||
when(credentials.getVersion()).thenReturn(AuthenticationCredentials.CURRENT_VERSION);
|
||||
when(credentials.getVersion()).thenReturn(SaltedTokenHash.CURRENT_VERSION);
|
||||
|
||||
final Optional<AuthenticatedAccount> maybeAuthenticatedAccount =
|
||||
baseAccountAuthenticator.authenticate(new BasicCredentials(uuid.toString(), password), true);
|
||||
@@ -186,7 +185,7 @@ class BaseAccountAuthenticatorTest {
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
final Device device = mock(Device.class);
|
||||
final AuthenticationCredentials credentials = mock(AuthenticationCredentials.class);
|
||||
final SaltedTokenHash credentials = mock(SaltedTokenHash.class);
|
||||
|
||||
clock.unpin();
|
||||
when(accountsManager.getByAccountIdentifier(uuid)).thenReturn(Optional.of(account));
|
||||
@@ -195,9 +194,9 @@ class BaseAccountAuthenticatorTest {
|
||||
when(account.isEnabled()).thenReturn(true);
|
||||
when(device.getId()).thenReturn(deviceId);
|
||||
when(device.isEnabled()).thenReturn(true);
|
||||
when(device.getAuthenticationCredentials()).thenReturn(credentials);
|
||||
when(device.getAuthTokenHash()).thenReturn(credentials);
|
||||
when(credentials.verify(password)).thenReturn(true);
|
||||
when(credentials.getVersion()).thenReturn(AuthenticationCredentials.CURRENT_VERSION);
|
||||
when(credentials.getVersion()).thenReturn(SaltedTokenHash.CURRENT_VERSION);
|
||||
|
||||
final Optional<AuthenticatedAccount> maybeAuthenticatedAccount =
|
||||
baseAccountAuthenticator.authenticate(new BasicCredentials(uuid + "." + deviceId, password), true);
|
||||
@@ -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 AuthenticationCredentials credentials = mock(AuthenticationCredentials.class);
|
||||
final Device authenticatedDevice = mock(Device.class);
|
||||
final SaltedTokenHash credentials = mock(SaltedTokenHash.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.getAuthTokenHash()).thenReturn(credentials);
|
||||
when(credentials.verify(password)).thenReturn(true);
|
||||
when(credentials.getVersion()).thenReturn(AuthenticationCredentials.CURRENT_VERSION);
|
||||
when(credentials.getVersion()).thenReturn(SaltedTokenHash.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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -250,7 +258,7 @@ class BaseAccountAuthenticatorTest {
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
final Device device = mock(Device.class);
|
||||
final AuthenticationCredentials credentials = mock(AuthenticationCredentials.class);
|
||||
final SaltedTokenHash credentials = mock(SaltedTokenHash.class);
|
||||
|
||||
clock.unpin();
|
||||
when(accountsManager.getByAccountIdentifier(uuid)).thenReturn(Optional.of(account));
|
||||
@@ -259,9 +267,9 @@ class BaseAccountAuthenticatorTest {
|
||||
when(account.isEnabled()).thenReturn(true);
|
||||
when(device.getId()).thenReturn(deviceId);
|
||||
when(device.isEnabled()).thenReturn(true);
|
||||
when(device.getAuthenticationCredentials()).thenReturn(credentials);
|
||||
when(device.getAuthTokenHash()).thenReturn(credentials);
|
||||
when(credentials.verify(password)).thenReturn(true);
|
||||
when(credentials.getVersion()).thenReturn(AuthenticationCredentials.Version.V1);
|
||||
when(credentials.getVersion()).thenReturn(SaltedTokenHash.Version.V1);
|
||||
|
||||
final Optional<AuthenticatedAccount> maybeAuthenticatedAccount =
|
||||
baseAccountAuthenticator.authenticate(new BasicCredentials(uuid.toString(), password), true);
|
||||
@@ -287,7 +295,7 @@ class BaseAccountAuthenticatorTest {
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
final Device device = mock(Device.class);
|
||||
final AuthenticationCredentials credentials = mock(AuthenticationCredentials.class);
|
||||
final SaltedTokenHash credentials = mock(SaltedTokenHash.class);
|
||||
|
||||
clock.unpin();
|
||||
when(accountsManager.getByAccountIdentifier(uuid)).thenReturn(Optional.of(account));
|
||||
@@ -296,9 +304,9 @@ class BaseAccountAuthenticatorTest {
|
||||
when(account.isEnabled()).thenReturn(true);
|
||||
when(device.getId()).thenReturn(deviceId);
|
||||
when(device.isEnabled()).thenReturn(true);
|
||||
when(device.getAuthenticationCredentials()).thenReturn(credentials);
|
||||
when(device.getAuthTokenHash()).thenReturn(credentials);
|
||||
when(credentials.verify(password)).thenReturn(true);
|
||||
when(credentials.getVersion()).thenReturn(AuthenticationCredentials.CURRENT_VERSION);
|
||||
when(credentials.getVersion()).thenReturn(SaltedTokenHash.CURRENT_VERSION);
|
||||
|
||||
final Optional<AuthenticatedAccount> maybeAuthenticatedAccount =
|
||||
baseAccountAuthenticator.authenticate(new BasicCredentials(uuid + "." + (deviceId + 1), password), true);
|
||||
@@ -315,7 +323,7 @@ class BaseAccountAuthenticatorTest {
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
final Device device = mock(Device.class);
|
||||
final AuthenticationCredentials credentials = mock(AuthenticationCredentials.class);
|
||||
final SaltedTokenHash credentials = mock(SaltedTokenHash.class);
|
||||
|
||||
clock.unpin();
|
||||
when(accountsManager.getByAccountIdentifier(uuid)).thenReturn(Optional.of(account));
|
||||
@@ -324,9 +332,9 @@ class BaseAccountAuthenticatorTest {
|
||||
when(account.isEnabled()).thenReturn(true);
|
||||
when(device.getId()).thenReturn(deviceId);
|
||||
when(device.isEnabled()).thenReturn(true);
|
||||
when(device.getAuthenticationCredentials()).thenReturn(credentials);
|
||||
when(device.getAuthTokenHash()).thenReturn(credentials);
|
||||
when(credentials.verify(password)).thenReturn(true);
|
||||
when(credentials.getVersion()).thenReturn(AuthenticationCredentials.CURRENT_VERSION);
|
||||
when(credentials.getVersion()).thenReturn(SaltedTokenHash.CURRENT_VERSION);
|
||||
|
||||
final String incorrectPassword = password + "incorrect";
|
||||
|
||||
|
||||
+4
-3
@@ -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)
|
||||
);
|
||||
}
|
||||
}
|
||||
+1
-2
@@ -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();
|
||||
});
|
||||
|
||||
+302
-146
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2013-2021 Signal Messenger, LLC
|
||||
* Copyright 2013 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
@@ -29,7 +29,6 @@ import com.google.common.collect.ImmutableSet;
|
||||
import com.google.common.net.HttpHeaders;
|
||||
import com.google.i18n.phonenumbers.NumberParseException;
|
||||
import com.google.i18n.phonenumbers.PhoneNumberUtil;
|
||||
import com.google.i18n.phonenumbers.Phonenumber;
|
||||
import io.dropwizard.auth.PolymorphicAuthValueFactoryProvider;
|
||||
import io.dropwizard.testing.junit5.DropwizardExtensionsSupport;
|
||||
import io.dropwizard.testing.junit5.ResourceExtension;
|
||||
@@ -64,14 +63,15 @@ import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.stubbing.Answer;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticationCredentials;
|
||||
import org.whispersystems.textsecuregcm.auth.DisabledPermittedAuthenticatedAccount;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialGenerator;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
|
||||
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
|
||||
import org.whispersystems.textsecuregcm.auth.StoredRegistrationLock;
|
||||
import org.whispersystems.textsecuregcm.auth.StoredVerificationCode;
|
||||
import org.whispersystems.textsecuregcm.auth.TurnTokenGenerator;
|
||||
import org.whispersystems.textsecuregcm.captcha.AssessmentResult;
|
||||
import org.whispersystems.textsecuregcm.captcha.CaptchaChecker;
|
||||
import org.whispersystems.textsecuregcm.configuration.SecureStorageServiceConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicCaptchaConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
|
||||
@@ -89,6 +89,7 @@ import org.whispersystems.textsecuregcm.entities.ReserveUsernameResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.SignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.UsernameRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.UsernameResponse;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimitByIpFilter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.mappers.ImpossiblePhoneNumberExceptionMapper;
|
||||
@@ -112,6 +113,7 @@ import org.whispersystems.textsecuregcm.storage.UsernameReservationNotFoundExcep
|
||||
import org.whispersystems.textsecuregcm.tests.util.AccountsHelper;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
|
||||
import org.whispersystems.textsecuregcm.util.Hex;
|
||||
import org.whispersystems.textsecuregcm.util.MockUtils;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
import org.whispersystems.textsecuregcm.util.TestClock;
|
||||
|
||||
@@ -170,7 +172,13 @@ class AccountControllerTest {
|
||||
private static DynamicConfigurationManager dynamicConfigurationManager = mock(DynamicConfigurationManager.class);
|
||||
|
||||
private byte[] registration_lock_key = new byte[32];
|
||||
private static ExternalServiceCredentialGenerator storageCredentialGenerator = new ExternalServiceCredentialGenerator(new byte[32], new byte[32], false);
|
||||
|
||||
private static final SecureStorageServiceConfiguration STORAGE_CFG = MockUtils.buildMock(
|
||||
SecureStorageServiceConfiguration.class,
|
||||
cfg -> when(cfg.decodeUserAuthenticationTokenSharedSecret()).thenReturn(new byte[32]));
|
||||
|
||||
private static final ExternalServiceCredentialsGenerator STORAGE_CREDENTIAL_GENERATOR = SecureStorageController
|
||||
.credentialsGenerator(STORAGE_CFG);
|
||||
|
||||
private static final ResourceExtension resources = ResourceExtension.builder()
|
||||
.addProvider(AuthHelper.getAuthFilter())
|
||||
@@ -181,6 +189,7 @@ class AccountControllerTest {
|
||||
.addProvider(new RateLimitExceededExceptionMapper())
|
||||
.addProvider(new ImpossiblePhoneNumberExceptionMapper())
|
||||
.addProvider(new NonNormalizedPhoneNumberExceptionMapper())
|
||||
.addProvider(new RateLimitByIpFilter(rateLimiters))
|
||||
.setMapper(SystemMapper.getMapper())
|
||||
.setTestContainerFactory(new GrizzlyWebTestContainerFactory())
|
||||
.addResource(new AccountController(pendingAccountsManager,
|
||||
@@ -193,7 +202,7 @@ class AccountControllerTest {
|
||||
captchaChecker,
|
||||
pushNotificationManager,
|
||||
changeNumberManager,
|
||||
storageCredentialGenerator,
|
||||
STORAGE_CREDENTIAL_GENERATOR,
|
||||
clientPresenceManager,
|
||||
testClock))
|
||||
.build();
|
||||
@@ -204,7 +213,7 @@ class AccountControllerTest {
|
||||
clearInvocations(AuthHelper.VALID_ACCOUNT, AuthHelper.UNDISCOVERABLE_ACCOUNT);
|
||||
|
||||
new SecureRandom().nextBytes(registration_lock_key);
|
||||
AuthenticationCredentials registrationLockCredentials = new AuthenticationCredentials(Hex.toStringCondensed(registration_lock_key));
|
||||
SaltedTokenHash registrationLockCredentials = SaltedTokenHash.generateFor(Hex.toStringCondensed(registration_lock_key));
|
||||
|
||||
AccountsHelper.setupMockUpdate(accountsManager);
|
||||
|
||||
@@ -226,7 +235,7 @@ class AccountControllerTest {
|
||||
when(senderHasStorage.isStorageSupported()).thenReturn(true);
|
||||
when(senderHasStorage.getRegistrationLock()).thenReturn(new StoredRegistrationLock(Optional.empty(), Optional.empty(), System.currentTimeMillis()));
|
||||
|
||||
when(senderRegLockAccount.getRegistrationLock()).thenReturn(new StoredRegistrationLock(Optional.of(registrationLockCredentials.getHashedAuthenticationToken()), Optional.of(registrationLockCredentials.getSalt()), System.currentTimeMillis()));
|
||||
when(senderRegLockAccount.getRegistrationLock()).thenReturn(new StoredRegistrationLock(Optional.of(registrationLockCredentials.hash()), Optional.of(registrationLockCredentials.salt()), System.currentTimeMillis()));
|
||||
when(senderRegLockAccount.getLastSeen()).thenReturn(System.currentTimeMillis());
|
||||
when(senderRegLockAccount.getUuid()).thenReturn(SENDER_REG_LOCK_UUID);
|
||||
when(senderRegLockAccount.getNumber()).thenReturn(SENDER_REG_LOCK);
|
||||
@@ -235,15 +244,15 @@ class AccountControllerTest {
|
||||
when(senderTransfer.getUuid()).thenReturn(SENDER_TRANSFER_UUID);
|
||||
when(senderTransfer.getNumber()).thenReturn(SENDER_TRANSFER);
|
||||
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER)).thenReturn(Optional.of(new StoredVerificationCode("1234", System.currentTimeMillis(), "1234-push", null, null)));
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER)).thenReturn(Optional.of(new StoredVerificationCode(null, System.currentTimeMillis(), "1234-push", null)));
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_OLD)).thenReturn(Optional.empty());
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_PIN)).thenReturn(Optional.of(new StoredVerificationCode("333333", System.currentTimeMillis(), null, null, null)));
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_REG_LOCK)).thenReturn(Optional.of(new StoredVerificationCode("666666", System.currentTimeMillis(), null, null, null)));
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_OVER_PIN)).thenReturn(Optional.of(new StoredVerificationCode("444444", System.currentTimeMillis(), null, null, null)));
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_OVER_PREFIX)).thenReturn(Optional.of(new StoredVerificationCode("777777", System.currentTimeMillis(), "1234-push", null, null)));
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_PREAUTH)).thenReturn(Optional.of(new StoredVerificationCode("555555", System.currentTimeMillis(), "validchallenge", null, null)));
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_HAS_STORAGE)).thenReturn(Optional.of(new StoredVerificationCode("666666", System.currentTimeMillis(), null, null, null)));
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_TRANSFER)).thenReturn(Optional.of(new StoredVerificationCode("1234", System.currentTimeMillis(), null, null, null)));
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_PIN)).thenReturn(Optional.of(new StoredVerificationCode(null, System.currentTimeMillis(), null, null)));
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_REG_LOCK)).thenReturn(Optional.of(new StoredVerificationCode(null, System.currentTimeMillis(), null, null)));
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_OVER_PIN)).thenReturn(Optional.of(new StoredVerificationCode(null, System.currentTimeMillis(), null, null)));
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_OVER_PREFIX)).thenReturn(Optional.of(new StoredVerificationCode(null, System.currentTimeMillis(), "1234-push", null)));
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_PREAUTH)).thenReturn(Optional.of(new StoredVerificationCode(null, System.currentTimeMillis(), "validchallenge", null)));
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_HAS_STORAGE)).thenReturn(Optional.of(new StoredVerificationCode(null, System.currentTimeMillis(), null, null)));
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_TRANSFER)).thenReturn(Optional.of(new StoredVerificationCode(null, System.currentTimeMillis(), null, null)));
|
||||
|
||||
when(accountsManager.getByE164(eq(SENDER_PIN))).thenReturn(Optional.of(senderPinAccount));
|
||||
when(accountsManager.getByE164(eq(SENDER_REG_LOCK))).thenReturn(Optional.of(senderRegLockAccount));
|
||||
@@ -339,7 +348,10 @@ class AccountControllerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetFcmPreauth() throws Exception {
|
||||
void testGetFcmPreauth() throws NumberParseException {
|
||||
when(registrationServiceClient.createRegistrationSession(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(new byte[16]));
|
||||
|
||||
Response response = resources.getJerseyTest()
|
||||
.target("/v1/accounts/fcm/preauth/mytoken/+14152222222")
|
||||
.request()
|
||||
@@ -349,6 +361,9 @@ class AccountControllerTest {
|
||||
|
||||
final ArgumentCaptor<String> challengeTokenCaptor = ArgumentCaptor.forClass(String.class);
|
||||
|
||||
verify(registrationServiceClient).createRegistrationSession(
|
||||
eq(PhoneNumberUtil.getInstance().parse("+14152222222", null)), any());
|
||||
|
||||
verify(pushNotificationManager).sendRegistrationChallengeNotification(
|
||||
eq("mytoken"), eq(PushNotification.TokenType.FCM), challengeTokenCaptor.capture());
|
||||
|
||||
@@ -356,7 +371,10 @@ class AccountControllerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetFcmPreauthIvoryCoast() throws Exception {
|
||||
void testGetFcmPreauthIvoryCoast() throws NumberParseException {
|
||||
when(registrationServiceClient.createRegistrationSession(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(new byte[16]));
|
||||
|
||||
Response response = resources.getJerseyTest()
|
||||
.target("/v1/accounts/fcm/preauth/mytoken/+2250707312345")
|
||||
.request()
|
||||
@@ -366,6 +384,9 @@ class AccountControllerTest {
|
||||
|
||||
final ArgumentCaptor<String> challengeTokenCaptor = ArgumentCaptor.forClass(String.class);
|
||||
|
||||
verify(registrationServiceClient).createRegistrationSession(
|
||||
eq(PhoneNumberUtil.getInstance().parse("+2250707312345", null)), any());
|
||||
|
||||
verify(pushNotificationManager).sendRegistrationChallengeNotification(
|
||||
eq("mytoken"), eq(PushNotification.TokenType.FCM), challengeTokenCaptor.capture());
|
||||
|
||||
@@ -373,7 +394,10 @@ class AccountControllerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetApnPreauth() throws Exception {
|
||||
void testGetApnPreauth() throws NumberParseException {
|
||||
when(registrationServiceClient.createRegistrationSession(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(new byte[16]));
|
||||
|
||||
Response response = resources.getJerseyTest()
|
||||
.target("/v1/accounts/apn/preauth/mytoken/+14152222222")
|
||||
.request()
|
||||
@@ -383,6 +407,9 @@ class AccountControllerTest {
|
||||
|
||||
final ArgumentCaptor<String> challengeTokenCaptor = ArgumentCaptor.forClass(String.class);
|
||||
|
||||
verify(registrationServiceClient).createRegistrationSession(
|
||||
eq(PhoneNumberUtil.getInstance().parse("+14152222222", null)), any());
|
||||
|
||||
verify(pushNotificationManager).sendRegistrationChallengeNotification(
|
||||
eq("mytoken"), eq(PushNotification.TokenType.APN_VOIP), challengeTokenCaptor.capture());
|
||||
|
||||
@@ -390,7 +417,10 @@ class AccountControllerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetApnPreauthExplicitVoip() throws Exception {
|
||||
void testGetApnPreauthExplicitVoip() throws NumberParseException {
|
||||
when(registrationServiceClient.createRegistrationSession(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(new byte[16]));
|
||||
|
||||
Response response = resources.getJerseyTest()
|
||||
.target("/v1/accounts/apn/preauth/mytoken/+14152222222")
|
||||
.queryParam("voip", "true")
|
||||
@@ -401,6 +431,9 @@ class AccountControllerTest {
|
||||
|
||||
final ArgumentCaptor<String> challengeTokenCaptor = ArgumentCaptor.forClass(String.class);
|
||||
|
||||
verify(registrationServiceClient).createRegistrationSession(
|
||||
eq(PhoneNumberUtil.getInstance().parse("+14152222222", null)), any());
|
||||
|
||||
verify(pushNotificationManager).sendRegistrationChallengeNotification(
|
||||
eq("mytoken"), eq(PushNotification.TokenType.APN_VOIP), challengeTokenCaptor.capture());
|
||||
|
||||
@@ -408,7 +441,10 @@ class AccountControllerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetApnPreauthExplicitNoVoip() throws Exception {
|
||||
void testGetApnPreauthExplicitNoVoip() throws NumberParseException {
|
||||
when(registrationServiceClient.createRegistrationSession(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(new byte[16]));
|
||||
|
||||
Response response = resources.getJerseyTest()
|
||||
.target("/v1/accounts/apn/preauth/mytoken/+14152222222")
|
||||
.queryParam("voip", "false")
|
||||
@@ -419,6 +455,9 @@ class AccountControllerTest {
|
||||
|
||||
final ArgumentCaptor<String> challengeTokenCaptor = ArgumentCaptor.forClass(String.class);
|
||||
|
||||
verify(registrationServiceClient).createRegistrationSession(
|
||||
eq(PhoneNumberUtil.getInstance().parse("+14152222222", null)), any());
|
||||
|
||||
verify(pushNotificationManager).sendRegistrationChallengeNotification(
|
||||
eq("mytoken"), eq(PushNotification.TokenType.APN), challengeTokenCaptor.capture());
|
||||
|
||||
@@ -435,6 +474,7 @@ class AccountControllerTest {
|
||||
assertThat(response.getStatus()).isEqualTo(400);
|
||||
assertThat(response.readEntity(String.class)).isBlank();
|
||||
|
||||
verifyNoInteractions(registrationServiceClient);
|
||||
verifyNoInteractions(pushNotificationManager);
|
||||
}
|
||||
|
||||
@@ -453,14 +493,43 @@ class AccountControllerTest {
|
||||
assertThat(responseEntity.getOriginalNumber()).isEqualTo(number);
|
||||
assertThat(responseEntity.getNormalizedNumber()).isEqualTo("+447700900111");
|
||||
|
||||
verifyNoInteractions(registrationServiceClient);
|
||||
verifyNoInteractions(pushNotificationManager);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSendCode() throws NumberParseException {
|
||||
|
||||
void testSendCodeWithExistingSessionFromPreauth() {
|
||||
final byte[] sessionId = "session-id".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER))
|
||||
.thenReturn(Optional.of(new StoredVerificationCode(null, System.currentTimeMillis(), "1234-push", sessionId)));
|
||||
|
||||
when(registrationServiceClient.sendRegistrationCode(eq(sessionId), any(), any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(sessionId));
|
||||
|
||||
Response response =
|
||||
resources.getJerseyTest()
|
||||
.target(String.format("/v1/accounts/sms/code/%s", SENDER))
|
||||
.queryParam("challenge", "1234-push")
|
||||
.request()
|
||||
.header(HttpHeaders.X_FORWARDED_FOR, NICE_HOST)
|
||||
.get();
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
|
||||
verify(registrationServiceClient).sendRegistrationCode(sessionId, MessageTransport.SMS, ClientType.UNKNOWN, null, AccountController.REGISTRATION_RPC_TIMEOUT);
|
||||
verify(pendingAccountsManager).store(eq(SENDER), argThat(
|
||||
storedVerificationCode -> Arrays.equals(storedVerificationCode.sessionId(), sessionId) &&
|
||||
"1234-push".equals(storedVerificationCode.pushCode())));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSendCode() {
|
||||
final byte[] sessionId = "session-id".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
when(registrationServiceClient.createRegistrationSession(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(sessionId));
|
||||
|
||||
when(registrationServiceClient.sendRegistrationCode(any(), any(), any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(sessionId));
|
||||
|
||||
@@ -474,14 +543,30 @@ class AccountControllerTest {
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
|
||||
final Phonenumber.PhoneNumber expectedPhoneNumber = PhoneNumberUtil.getInstance().parse(SENDER, null);
|
||||
|
||||
verify(registrationServiceClient).sendRegistrationCode(expectedPhoneNumber, MessageTransport.SMS, ClientType.UNKNOWN, null, AccountController.REGISTRATION_RPC_TIMEOUT);
|
||||
verify(registrationServiceClient).sendRegistrationCode(sessionId, MessageTransport.SMS, ClientType.UNKNOWN, null, AccountController.REGISTRATION_RPC_TIMEOUT);
|
||||
verify(pendingAccountsManager).store(eq(SENDER), argThat(
|
||||
storedVerificationCode -> Arrays.equals(storedVerificationCode.sessionId(), sessionId) &&
|
||||
"1234-push".equals(storedVerificationCode.pushCode())));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSendCodeRateLimited() {
|
||||
when(registrationServiceClient.createRegistrationSession(any(), any()))
|
||||
.thenReturn(CompletableFuture.failedFuture(new RateLimitExceededException(Duration.ofMinutes(10))));
|
||||
|
||||
Response response =
|
||||
resources.getJerseyTest()
|
||||
.target(String.format("/v1/accounts/sms/code/%s", SENDER))
|
||||
.queryParam("challenge", "1234-push")
|
||||
.request()
|
||||
.header(HttpHeaders.X_FORWARDED_FOR, NICE_HOST)
|
||||
.get();
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(413);
|
||||
|
||||
verify(registrationServiceClient, never()).sendRegistrationCode(any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSendCodeImpossibleNumber() {
|
||||
final Response response =
|
||||
@@ -520,10 +605,15 @@ class AccountControllerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSendCodeVoiceNoLocale() throws NumberParseException {
|
||||
public void testSendCodeVoiceNoLocale() {
|
||||
|
||||
final byte[] sessionId = "session".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
when(registrationServiceClient.sendRegistrationCode(any(), any(), any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(new byte[16]));
|
||||
.thenReturn(CompletableFuture.completedFuture(sessionId));
|
||||
|
||||
when(registrationServiceClient.createRegistrationSession(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(sessionId));
|
||||
|
||||
Response response =
|
||||
resources.getJerseyTest()
|
||||
@@ -533,17 +623,20 @@ class AccountControllerTest {
|
||||
.header(HttpHeaders.X_FORWARDED_FOR, NICE_HOST)
|
||||
.get();
|
||||
|
||||
final Phonenumber.PhoneNumber phoneNumber = PhoneNumberUtil.getInstance().parse(SENDER, null);
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
verify(registrationServiceClient).sendRegistrationCode(phoneNumber, MessageTransport.VOICE, ClientType.UNKNOWN, null, AccountController.REGISTRATION_RPC_TIMEOUT);
|
||||
verify(registrationServiceClient).sendRegistrationCode(sessionId, MessageTransport.VOICE, ClientType.UNKNOWN, null, AccountController.REGISTRATION_RPC_TIMEOUT);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSendCodeWithValidPreauth() throws NumberParseException {
|
||||
void testSendCodeWithValidPreauth() {
|
||||
|
||||
final byte[] sessionId = "session".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
when(registrationServiceClient.sendRegistrationCode(any(), any(), any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(new byte[16]));
|
||||
.thenReturn(CompletableFuture.completedFuture(sessionId));
|
||||
|
||||
when(registrationServiceClient.createRegistrationSession(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(sessionId));
|
||||
|
||||
Response response =
|
||||
resources.getJerseyTest()
|
||||
@@ -555,9 +648,7 @@ class AccountControllerTest {
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
|
||||
final Phonenumber.PhoneNumber phoneNumber = PhoneNumberUtil.getInstance().parse(SENDER_PREAUTH, null);
|
||||
|
||||
verify(registrationServiceClient).sendRegistrationCode(phoneNumber, MessageTransport.SMS, ClientType.UNKNOWN, null, AccountController.REGISTRATION_RPC_TIMEOUT);
|
||||
verify(registrationServiceClient).sendRegistrationCode(sessionId, MessageTransport.SMS, ClientType.UNKNOWN, null, AccountController.REGISTRATION_RPC_TIMEOUT);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -590,10 +681,15 @@ class AccountControllerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSendiOSCode() throws NumberParseException {
|
||||
void testSendiOSCode() {
|
||||
|
||||
final byte[] sessionId = "session".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
when(registrationServiceClient.sendRegistrationCode(any(), any(), any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(new byte[16]));
|
||||
.thenReturn(CompletableFuture.completedFuture(sessionId));
|
||||
|
||||
when(registrationServiceClient.createRegistrationSession(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(sessionId));
|
||||
|
||||
Response response =
|
||||
resources.getJerseyTest()
|
||||
@@ -606,15 +702,18 @@ class AccountControllerTest {
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
|
||||
final Phonenumber.PhoneNumber phoneNumber = PhoneNumberUtil.getInstance().parse(SENDER, null);
|
||||
|
||||
verify(registrationServiceClient).sendRegistrationCode(phoneNumber, MessageTransport.SMS, ClientType.IOS, null, AccountController.REGISTRATION_RPC_TIMEOUT);
|
||||
verify(registrationServiceClient).sendRegistrationCode(sessionId, MessageTransport.SMS, ClientType.IOS, null, AccountController.REGISTRATION_RPC_TIMEOUT);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSendAndroidNgCode() throws NumberParseException {
|
||||
void testSendAndroidNgCode() {
|
||||
final byte[] sessionId = "session".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
when(registrationServiceClient.sendRegistrationCode(any(), any(), any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(new byte[16]));
|
||||
.thenReturn(CompletableFuture.completedFuture(sessionId));
|
||||
|
||||
when(registrationServiceClient.createRegistrationSession(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(sessionId));
|
||||
|
||||
Response response =
|
||||
resources.getJerseyTest()
|
||||
@@ -627,16 +726,19 @@ class AccountControllerTest {
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
|
||||
final Phonenumber.PhoneNumber phoneNumber = PhoneNumberUtil.getInstance().parse(SENDER, null);
|
||||
|
||||
verify(registrationServiceClient).sendRegistrationCode(phoneNumber, MessageTransport.SMS, ClientType.ANDROID_WITHOUT_FCM, null, AccountController.REGISTRATION_RPC_TIMEOUT);
|
||||
verify(registrationServiceClient).sendRegistrationCode(sessionId, MessageTransport.SMS, ClientType.ANDROID_WITHOUT_FCM, null, AccountController.REGISTRATION_RPC_TIMEOUT);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSendWithValidCaptcha() throws NumberParseException, IOException {
|
||||
|
||||
final byte[] sessionId = "session".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
when(registrationServiceClient.sendRegistrationCode(any(), any(), any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(new byte[16]));
|
||||
.thenReturn(CompletableFuture.completedFuture(sessionId));
|
||||
|
||||
when(registrationServiceClient.createRegistrationSession(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(sessionId));
|
||||
|
||||
Response response =
|
||||
resources.getJerseyTest()
|
||||
@@ -648,10 +750,8 @@ class AccountControllerTest {
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
|
||||
final Phonenumber.PhoneNumber phoneNumber = PhoneNumberUtil.getInstance().parse(SENDER, null);
|
||||
|
||||
verify(captchaChecker).verify(eq(VALID_CAPTCHA_TOKEN), eq(NICE_HOST));
|
||||
verify(registrationServiceClient).sendRegistrationCode(phoneNumber, MessageTransport.SMS, ClientType.UNKNOWN, null, AccountController.REGISTRATION_RPC_TIMEOUT);
|
||||
verify(registrationServiceClient).sendRegistrationCode(sessionId, MessageTransport.SMS, ClientType.UNKNOWN, null, AccountController.REGISTRATION_RPC_TIMEOUT);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -709,7 +809,7 @@ class AccountControllerTest {
|
||||
|
||||
final String challenge = "challenge";
|
||||
when(pendingAccountsManager.getCodeForNumber(RESTRICTED_NUMBER))
|
||||
.thenReturn(Optional.of(new StoredVerificationCode("123456", System.currentTimeMillis(), challenge, null, null)));
|
||||
.thenReturn(Optional.of(new StoredVerificationCode(null, System.currentTimeMillis(), challenge, null)));
|
||||
|
||||
Response response =
|
||||
resources.getJerseyTest()
|
||||
@@ -740,10 +840,15 @@ class AccountControllerTest {
|
||||
|
||||
final String challenge = "challenge";
|
||||
when(pendingAccountsManager.getCodeForNumber(number))
|
||||
.thenReturn(Optional.of(new StoredVerificationCode("123456", System.currentTimeMillis(), challenge, null, null)));
|
||||
.thenReturn(Optional.of(new StoredVerificationCode(null, System.currentTimeMillis(), challenge, null)));
|
||||
|
||||
final byte[] sessionId = "session".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
when(registrationServiceClient.sendRegistrationCode(any(), any(), any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(new byte[16]));
|
||||
.thenReturn(CompletableFuture.completedFuture(sessionId));
|
||||
|
||||
when(registrationServiceClient.createRegistrationSession(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(sessionId));
|
||||
|
||||
Response response =
|
||||
resources.getJerseyTest()
|
||||
@@ -755,9 +860,7 @@ class AccountControllerTest {
|
||||
|
||||
if (expectSendCode) {
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
|
||||
final Phonenumber.PhoneNumber phoneNumber = PhoneNumberUtil.getInstance().parse(number, null);
|
||||
verify(registrationServiceClient).sendRegistrationCode(phoneNumber, MessageTransport.SMS, ClientType.UNKNOWN, null, AccountController.REGISTRATION_RPC_TIMEOUT);
|
||||
verify(registrationServiceClient).sendRegistrationCode(sessionId, MessageTransport.SMS, ClientType.UNKNOWN, null, AccountController.REGISTRATION_RPC_TIMEOUT);
|
||||
} else {
|
||||
assertThat(response.getStatus()).isEqualTo(402);
|
||||
verifyNoInteractions(registrationServiceClient);
|
||||
@@ -765,13 +868,17 @@ class AccountControllerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSendRestrictedIn() throws NumberParseException {
|
||||
void testSendRestrictedIn() {
|
||||
|
||||
final String challenge = "challenge";
|
||||
final byte[] sessionId = "session".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER)).thenReturn(Optional.of(new StoredVerificationCode("123456", System.currentTimeMillis(), challenge, null, null)));
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER)).thenReturn(Optional.of(new StoredVerificationCode(null, System.currentTimeMillis(), challenge, null)));
|
||||
when(registrationServiceClient.sendRegistrationCode(any(), any(), any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(new byte[16]));
|
||||
.thenReturn(CompletableFuture.completedFuture(sessionId));
|
||||
|
||||
when(registrationServiceClient.createRegistrationSession(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(sessionId));
|
||||
|
||||
Response response =
|
||||
resources.getJerseyTest()
|
||||
@@ -783,18 +890,19 @@ class AccountControllerTest {
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
|
||||
final Phonenumber.PhoneNumber phoneNumber = PhoneNumberUtil.getInstance().parse(SENDER, null);
|
||||
|
||||
verify(registrationServiceClient).sendRegistrationCode(phoneNumber, MessageTransport.SMS, ClientType.UNKNOWN, null, AccountController.REGISTRATION_RPC_TIMEOUT);
|
||||
verify(registrationServiceClient).sendRegistrationCode(sessionId, MessageTransport.SMS, ClientType.UNKNOWN, null, AccountController.REGISTRATION_RPC_TIMEOUT);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSendCodeTestDeviceNumber() throws NumberParseException {
|
||||
void testSendCodeTestDeviceNumber() {
|
||||
final byte[] sessionId = "session-id".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
when(registrationServiceClient.sendRegistrationCode(any(), any(), any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(sessionId));
|
||||
|
||||
when(registrationServiceClient.createRegistrationSession(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(sessionId));
|
||||
|
||||
Response response =
|
||||
resources.getJerseyTest()
|
||||
.target(String.format("/v1/accounts/sms/code/%s", TEST_NUMBER))
|
||||
@@ -809,35 +917,22 @@ class AccountControllerTest {
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
|
||||
// Even though no actual SMS will be sent, we leave that decision to the registration service
|
||||
final Phonenumber.PhoneNumber phoneNumber = PhoneNumberUtil.getInstance().parse(TEST_NUMBER, null);
|
||||
verify(registrationServiceClient).sendRegistrationCode(phoneNumber, MessageTransport.SMS, ClientType.UNKNOWN, null, AccountController.REGISTRATION_RPC_TIMEOUT);
|
||||
verify(registrationServiceClient).sendRegistrationCode(sessionId, MessageTransport.SMS, ClientType.UNKNOWN, null, AccountController.REGISTRATION_RPC_TIMEOUT);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testVerifyCode() throws Exception {
|
||||
resources.getJerseyTest()
|
||||
.target(String.format("/v1/accounts/code/%s", "1234"))
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getProvisioningAuthHeader(SENDER, "bar"))
|
||||
.put(Entity.entity(new AccountAttributes(), MediaType.APPLICATION_JSON_TYPE), AccountIdentityResponse.class);
|
||||
|
||||
verify(accountsManager).create(eq(SENDER), eq("bar"), any(), any(), anyList());
|
||||
verifyNoInteractions(registrationServiceClient);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testVerifyCodeWithRegistrationService() throws Exception {
|
||||
final byte[] sessionId = "session".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER))
|
||||
.thenReturn(Optional.of(
|
||||
new StoredVerificationCode("1234", System.currentTimeMillis(), "1234-push", null, sessionId)));
|
||||
new StoredVerificationCode(null, System.currentTimeMillis(), "1234-push", sessionId)));
|
||||
|
||||
when(registrationServiceClient.checkVerificationCode(sessionId, "1234", AccountController.REGISTRATION_RPC_TIMEOUT))
|
||||
.thenReturn(CompletableFuture.completedFuture(true));
|
||||
|
||||
resources.getJerseyTest()
|
||||
.target(String.format("/v1/accounts/code/%s", "1234"))
|
||||
.target("/v1/accounts/code/1234")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getProvisioningAuthHeader(SENDER, "bar"))
|
||||
.put(Entity.entity(new AccountAttributes(), MediaType.APPLICATION_JSON_TYPE), AccountIdentityResponse.class);
|
||||
@@ -850,7 +945,7 @@ class AccountControllerTest {
|
||||
@Test
|
||||
void testVerifyCodeBadCredentials() {
|
||||
final Response response = resources.getJerseyTest()
|
||||
.target(String.format("/v1/accounts/code/%s", "1234"))
|
||||
.target("/v1/accounts/code/1234")
|
||||
.request()
|
||||
.header("Authorization", "This is not a valid authorization header")
|
||||
.put(Entity.entity(new AccountAttributes(), MediaType.APPLICATION_JSON_TYPE));
|
||||
@@ -862,7 +957,7 @@ class AccountControllerTest {
|
||||
void testVerifyCodeOld() {
|
||||
Response response =
|
||||
resources.getJerseyTest()
|
||||
.target(String.format("/v1/accounts/code/%s", "1234"))
|
||||
.target("/v1/accounts/code/1234")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getProvisioningAuthHeader(SENDER_OLD, "bar"))
|
||||
.put(Entity.entity(new AccountAttributes(false, 2222, null, null, true, null),
|
||||
@@ -875,33 +970,18 @@ class AccountControllerTest {
|
||||
|
||||
@Test
|
||||
void testVerifyBadCode() {
|
||||
Response response =
|
||||
resources.getJerseyTest()
|
||||
.target(String.format("/v1/accounts/code/%s", "1111"))
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getProvisioningAuthHeader(SENDER, "bar"))
|
||||
.put(Entity.entity(new AccountAttributes(false, 3333, null, null, true, null),
|
||||
MediaType.APPLICATION_JSON_TYPE));
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(403);
|
||||
|
||||
verifyNoInteractions(accountsManager);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testVerifyBadCodeWithRegistrationService() {
|
||||
final byte[] sessionId = "session".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER))
|
||||
.thenReturn(Optional.of(
|
||||
new StoredVerificationCode("1234", System.currentTimeMillis(), "1234-push", null, sessionId)));
|
||||
new StoredVerificationCode(null, System.currentTimeMillis(), "1234-push", sessionId)));
|
||||
|
||||
when(registrationServiceClient.checkVerificationCode(any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(false));
|
||||
|
||||
Response response =
|
||||
resources.getJerseyTest()
|
||||
.target(String.format("/v1/accounts/code/%s", "1111"))
|
||||
.target("/v1/accounts/code/1111")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getProvisioningAuthHeader(SENDER, "bar"))
|
||||
.put(Entity.entity(new AccountAttributes(false, 3333, null, null, true, null),
|
||||
@@ -915,30 +995,48 @@ class AccountControllerTest {
|
||||
|
||||
@Test
|
||||
void testVerifyRegistrationLock() throws Exception {
|
||||
final byte[] sessionId = "session".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_REG_LOCK))
|
||||
.thenReturn(Optional.of(
|
||||
new StoredVerificationCode(null, System.currentTimeMillis(), "666666-push", sessionId)));
|
||||
|
||||
when(registrationServiceClient.checkVerificationCode(sessionId, "666666", AccountController.REGISTRATION_RPC_TIMEOUT))
|
||||
.thenReturn(CompletableFuture.completedFuture(true));
|
||||
|
||||
AccountIdentityResponse result =
|
||||
resources.getJerseyTest()
|
||||
.target(String.format("/v1/accounts/code/%s", "666666"))
|
||||
.target("/v1/accounts/code/666666")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getProvisioningAuthHeader(SENDER_REG_LOCK, "bar"))
|
||||
.put(Entity.entity(new AccountAttributes(false, 3333, null, Hex.toStringCondensed(registration_lock_key), true, null),
|
||||
MediaType.APPLICATION_JSON_TYPE), AccountIdentityResponse.class);
|
||||
|
||||
assertThat(result.getUuid()).isNotNull();
|
||||
assertThat(result.uuid()).isNotNull();
|
||||
|
||||
verify(pinLimiter).validate(eq(SENDER_REG_LOCK));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testVerifyRegistrationLockSetsRegistrationLockOnNewAccount() throws Exception {
|
||||
final byte[] sessionId = "session".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_REG_LOCK))
|
||||
.thenReturn(Optional.of(
|
||||
new StoredVerificationCode(null, System.currentTimeMillis(), "666666-push", sessionId)));
|
||||
|
||||
when(registrationServiceClient.checkVerificationCode(sessionId, "666666", AccountController.REGISTRATION_RPC_TIMEOUT))
|
||||
.thenReturn(CompletableFuture.completedFuture(true));
|
||||
|
||||
AccountIdentityResponse result =
|
||||
resources.getJerseyTest()
|
||||
.target(String.format("/v1/accounts/code/%s", "666666"))
|
||||
.target("/v1/accounts/code/666666")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getProvisioningAuthHeader(SENDER_REG_LOCK, "bar"))
|
||||
.put(Entity.entity(new AccountAttributes(false, 3333, null, Hex.toStringCondensed(registration_lock_key), true, null),
|
||||
MediaType.APPLICATION_JSON_TYPE), AccountIdentityResponse.class);
|
||||
|
||||
assertThat(result.getUuid()).isNotNull();
|
||||
assertThat(result.uuid()).isNotNull();
|
||||
|
||||
verify(pinLimiter).validate(eq(SENDER_REG_LOCK));
|
||||
|
||||
@@ -954,15 +1052,24 @@ class AccountControllerTest {
|
||||
try {
|
||||
when(senderRegLockAccount.getRegistrationLock()).thenReturn(lock.forTime(System.currentTimeMillis() - TimeUnit.DAYS.toMillis(7)));
|
||||
|
||||
final byte[] sessionId = "session".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_REG_LOCK))
|
||||
.thenReturn(Optional.of(
|
||||
new StoredVerificationCode(null, System.currentTimeMillis(), "666666-push", sessionId)));
|
||||
|
||||
when(registrationServiceClient.checkVerificationCode(sessionId, "666666", AccountController.REGISTRATION_RPC_TIMEOUT))
|
||||
.thenReturn(CompletableFuture.completedFuture(true));
|
||||
|
||||
AccountIdentityResponse result =
|
||||
resources.getJerseyTest()
|
||||
.target(String.format("/v1/accounts/code/%s", "666666"))
|
||||
.target("/v1/accounts/code/666666")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getProvisioningAuthHeader(SENDER_REG_LOCK, "bar"))
|
||||
.put(Entity.entity(new AccountAttributes(false, 3333, null, null, true, null),
|
||||
MediaType.APPLICATION_JSON_TYPE), AccountIdentityResponse.class);
|
||||
|
||||
assertThat(result.getUuid()).isNotNull();
|
||||
assertThat(result.uuid()).isNotNull();
|
||||
|
||||
verifyNoInteractions(pinLimiter);
|
||||
} finally {
|
||||
@@ -972,9 +1079,18 @@ class AccountControllerTest {
|
||||
|
||||
@Test
|
||||
void testVerifyWrongRegistrationLock() throws Exception {
|
||||
final byte[] sessionId = "session".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_REG_LOCK))
|
||||
.thenReturn(Optional.of(
|
||||
new StoredVerificationCode(null, System.currentTimeMillis(), "666666-push", sessionId)));
|
||||
|
||||
when(registrationServiceClient.checkVerificationCode(sessionId, "666666", AccountController.REGISTRATION_RPC_TIMEOUT))
|
||||
.thenReturn(CompletableFuture.completedFuture(true));
|
||||
|
||||
Response response =
|
||||
resources.getJerseyTest()
|
||||
.target(String.format("/v1/accounts/code/%s", "666666"))
|
||||
.target("/v1/accounts/code/666666")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getProvisioningAuthHeader(SENDER_REG_LOCK, "bar"))
|
||||
.put(Entity.entity(new AccountAttributes(false, 3333, null,
|
||||
@@ -989,10 +1105,19 @@ class AccountControllerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testVerifyNoRegistrationLock() throws Exception {
|
||||
void testVerifyNoRegistrationLock() {
|
||||
final byte[] sessionId = "session".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_REG_LOCK))
|
||||
.thenReturn(Optional.of(
|
||||
new StoredVerificationCode(null, System.currentTimeMillis(), "666666-push", sessionId)));
|
||||
|
||||
when(registrationServiceClient.checkVerificationCode(sessionId, "666666", AccountController.REGISTRATION_RPC_TIMEOUT))
|
||||
.thenReturn(CompletableFuture.completedFuture(true));
|
||||
|
||||
Response response =
|
||||
resources.getJerseyTest()
|
||||
.target(String.format("/v1/accounts/code/%s", "666666"))
|
||||
.target("/v1/accounts/code/666666")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getProvisioningAuthHeader(SENDER_REG_LOCK, "bar"))
|
||||
.put(Entity.entity(new AccountAttributes(false, 3333, null, null, true, null),
|
||||
@@ -1001,11 +1126,11 @@ class AccountControllerTest {
|
||||
assertThat(response.getStatus()).isEqualTo(423);
|
||||
|
||||
RegistrationLockFailure failure = response.readEntity(RegistrationLockFailure.class);
|
||||
assertThat(failure.getBackupCredentials()).isNotNull();
|
||||
assertThat(failure.getBackupCredentials().getUsername()).isEqualTo(SENDER_REG_LOCK_UUID.toString());
|
||||
assertThat(failure.getBackupCredentials().getPassword()).isNotEmpty();
|
||||
assertThat(failure.getBackupCredentials().getPassword().startsWith(SENDER_REG_LOCK_UUID.toString())).isTrue();
|
||||
assertThat(failure.getTimeRemaining()).isGreaterThan(0);
|
||||
assertThat(failure.backupCredentials()).isNotNull();
|
||||
assertThat(failure.backupCredentials().username()).isEqualTo(SENDER_REG_LOCK_UUID.toString());
|
||||
assertThat(failure.backupCredentials().password()).isNotEmpty();
|
||||
assertThat(failure.backupCredentials().password().startsWith(SENDER_REG_LOCK_UUID.toString())).isTrue();
|
||||
assertThat(failure.timeRemaining()).isGreaterThan(0);
|
||||
|
||||
// verify(senderRegLockAccount).lockAuthenticationCredentials();
|
||||
// verify(clientPresenceManager, atLeastOnce()).disconnectAllPresences(eq(SENDER_REG_LOCK_UUID), any());
|
||||
@@ -1014,11 +1139,20 @@ class AccountControllerTest {
|
||||
|
||||
@Test
|
||||
void testVerifyTransferSupported() {
|
||||
final byte[] sessionId = "session".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_TRANSFER))
|
||||
.thenReturn(Optional.of(
|
||||
new StoredVerificationCode(null, System.currentTimeMillis(), "1234-push", sessionId)));
|
||||
|
||||
when(registrationServiceClient.checkVerificationCode(sessionId, "1234", AccountController.REGISTRATION_RPC_TIMEOUT))
|
||||
.thenReturn(CompletableFuture.completedFuture(true));
|
||||
|
||||
when(senderTransfer.isTransferSupported()).thenReturn(true);
|
||||
|
||||
final Response response =
|
||||
resources.getJerseyTest()
|
||||
.target(String.format("/v1/accounts/code/%s", "1234"))
|
||||
.target("/v1/accounts/code/1234")
|
||||
.queryParam("transfer", true)
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getProvisioningAuthHeader(SENDER_TRANSFER, "bar"))
|
||||
@@ -1030,11 +1164,20 @@ class AccountControllerTest {
|
||||
|
||||
@Test
|
||||
void testVerifyTransferNotSupported() {
|
||||
final byte[] sessionId = "session".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_TRANSFER))
|
||||
.thenReturn(Optional.of(
|
||||
new StoredVerificationCode(null, System.currentTimeMillis(), "1234-push", sessionId)));
|
||||
|
||||
when(registrationServiceClient.checkVerificationCode(sessionId, "1234", AccountController.REGISTRATION_RPC_TIMEOUT))
|
||||
.thenReturn(CompletableFuture.completedFuture(true));
|
||||
|
||||
when(senderTransfer.isTransferSupported()).thenReturn(false);
|
||||
|
||||
final Response response =
|
||||
resources.getJerseyTest()
|
||||
.target(String.format("/v1/accounts/code/%s", "1234"))
|
||||
.target("/v1/accounts/code/1234")
|
||||
.queryParam("transfer", true)
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getProvisioningAuthHeader(SENDER_TRANSFER, "bar"))
|
||||
@@ -1046,11 +1189,20 @@ class AccountControllerTest {
|
||||
|
||||
@Test
|
||||
void testVerifyTransferSupportedNotRequested() {
|
||||
final byte[] sessionId = "session".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_TRANSFER))
|
||||
.thenReturn(Optional.of(
|
||||
new StoredVerificationCode(null, System.currentTimeMillis(), "1234-push", sessionId)));
|
||||
|
||||
when(registrationServiceClient.checkVerificationCode(sessionId, "1234", AccountController.REGISTRATION_RPC_TIMEOUT))
|
||||
.thenReturn(CompletableFuture.completedFuture(true));
|
||||
|
||||
when(senderTransfer.isTransferSupported()).thenReturn(true);
|
||||
|
||||
final Response response =
|
||||
resources.getJerseyTest()
|
||||
.target(String.format("/v1/accounts/code/%s", "1234"))
|
||||
.target("/v1/accounts/code/1234")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getProvisioningAuthHeader(SENDER_TRANSFER, "bar"))
|
||||
.put(Entity.entity(new AccountAttributes(false, 2222, null, null, true, null),
|
||||
@@ -1066,7 +1218,7 @@ class AccountControllerTest {
|
||||
final byte[] sessionId = "session".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
when(pendingAccountsManager.getCodeForNumber(number)).thenReturn(Optional.of(
|
||||
new StoredVerificationCode(null, System.currentTimeMillis(), "push", null, sessionId)));
|
||||
new StoredVerificationCode(null, System.currentTimeMillis(), "push", sessionId)));
|
||||
|
||||
when(registrationServiceClient.checkVerificationCode(any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(true));
|
||||
@@ -1083,9 +1235,9 @@ class AccountControllerTest {
|
||||
|
||||
verify(changeNumberManager).changeNumber(eq(AuthHelper.VALID_ACCOUNT), eq(number), any(), any(), any(), any());
|
||||
|
||||
assertThat(accountIdentityResponse.getUuid()).isEqualTo(AuthHelper.VALID_UUID);
|
||||
assertThat(accountIdentityResponse.getNumber()).isEqualTo(number);
|
||||
assertThat(accountIdentityResponse.getPni()).isNotEqualTo(AuthHelper.VALID_PNI);
|
||||
assertThat(accountIdentityResponse.uuid()).isEqualTo(AuthHelper.VALID_UUID);
|
||||
assertThat(accountIdentityResponse.number()).isEqualTo(number);
|
||||
assertThat(accountIdentityResponse.pni()).isNotEqualTo(AuthHelper.VALID_PNI);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -1167,7 +1319,7 @@ class AccountControllerTest {
|
||||
final byte[] sessionId = "session-id".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
when(pendingAccountsManager.getCodeForNumber(number)).thenReturn(Optional.of(
|
||||
new StoredVerificationCode(code, System.currentTimeMillis(), "push", null, sessionId)));
|
||||
new StoredVerificationCode(code, System.currentTimeMillis(), "push", sessionId)));
|
||||
|
||||
when(registrationServiceClient.checkVerificationCode(any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(false));
|
||||
@@ -1193,7 +1345,7 @@ class AccountControllerTest {
|
||||
final byte[] sessionId = "session-id".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
when(pendingAccountsManager.getCodeForNumber(number)).thenReturn(Optional.of(
|
||||
new StoredVerificationCode(code, System.currentTimeMillis(), "push", null, sessionId)));
|
||||
new StoredVerificationCode(code, System.currentTimeMillis(), "push", sessionId)));
|
||||
|
||||
when(registrationServiceClient.checkVerificationCode(any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(true));
|
||||
@@ -1227,7 +1379,7 @@ class AccountControllerTest {
|
||||
final byte[] sessionId = "session-id".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
when(pendingAccountsManager.getCodeForNumber(number)).thenReturn(Optional.of(
|
||||
new StoredVerificationCode(code, System.currentTimeMillis(), "push", null, sessionId)));
|
||||
new StoredVerificationCode(code, System.currentTimeMillis(), "push", sessionId)));
|
||||
|
||||
when(registrationServiceClient.checkVerificationCode(any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(true));
|
||||
@@ -1266,7 +1418,7 @@ class AccountControllerTest {
|
||||
final byte[] sessionId = "session-id".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
when(pendingAccountsManager.getCodeForNumber(number)).thenReturn(Optional.of(
|
||||
new StoredVerificationCode(null, System.currentTimeMillis(), "push", null, sessionId)));
|
||||
new StoredVerificationCode(null, System.currentTimeMillis(), "push", sessionId)));
|
||||
|
||||
when(registrationServiceClient.checkVerificationCode(any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(true));
|
||||
@@ -1306,7 +1458,7 @@ class AccountControllerTest {
|
||||
final byte[] sessionId = "session-id".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
when(pendingAccountsManager.getCodeForNumber(number)).thenReturn(Optional.of(
|
||||
new StoredVerificationCode(null, System.currentTimeMillis(), "push", null, sessionId)));
|
||||
new StoredVerificationCode(null, System.currentTimeMillis(), "push", sessionId)));
|
||||
|
||||
when(registrationServiceClient.checkVerificationCode(any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(true));
|
||||
@@ -1331,7 +1483,7 @@ class AccountControllerTest {
|
||||
MediaType.APPLICATION_JSON_TYPE));
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
verify(senderRegLockAccount, never()).lockAuthenticationCredentials();
|
||||
verify(senderRegLockAccount, never()).lockAuthTokenHash();
|
||||
verify(clientPresenceManager, never()).disconnectAllPresences(eq(SENDER_REG_LOCK_UUID), any());
|
||||
verify(changeNumberManager).changeNumber(eq(AuthHelper.VALID_ACCOUNT), any(), any(), any(), any(), any());
|
||||
}
|
||||
@@ -1358,7 +1510,7 @@ class AccountControllerTest {
|
||||
when(AuthHelper.VALID_ACCOUNT.getDevice(3L)).thenReturn(Optional.of(device3));
|
||||
|
||||
when(pendingAccountsManager.getCodeForNumber(number)).thenReturn(Optional.of(
|
||||
new StoredVerificationCode(null, System.currentTimeMillis(), "push", null, sessionId)));
|
||||
new StoredVerificationCode(null, System.currentTimeMillis(), "push", sessionId)));
|
||||
|
||||
when(registrationServiceClient.checkVerificationCode(any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(true));
|
||||
@@ -1384,9 +1536,9 @@ class AccountControllerTest {
|
||||
|
||||
verify(changeNumberManager).changeNumber(eq(AuthHelper.VALID_ACCOUNT), eq(number), any(), any(), any(), any());
|
||||
|
||||
assertThat(accountIdentityResponse.getUuid()).isEqualTo(AuthHelper.VALID_UUID);
|
||||
assertThat(accountIdentityResponse.getNumber()).isEqualTo(number);
|
||||
assertThat(accountIdentityResponse.getPni()).isNotEqualTo(AuthHelper.VALID_PNI);
|
||||
assertThat(accountIdentityResponse.uuid()).isEqualTo(AuthHelper.VALID_UUID);
|
||||
assertThat(accountIdentityResponse.number()).isEqualTo(number);
|
||||
assertThat(accountIdentityResponse.pni()).isNotEqualTo(AuthHelper.VALID_PNI);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -1492,7 +1644,7 @@ class AccountControllerTest {
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.get(AccountIdentityResponse.class);
|
||||
|
||||
assertThat(response.getUuid()).isEqualTo(AuthHelper.VALID_UUID);
|
||||
assertThat(response.uuid()).isEqualTo(AuthHelper.VALID_UUID);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -1721,8 +1873,7 @@ class AccountControllerTest {
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void testSignupCaptcha(final String message, final boolean enforced, final Set<String> countryCodes, final int expectedResponseStatusCode)
|
||||
throws NumberParseException {
|
||||
void testSignupCaptcha(final String message, final boolean enforced, final Set<String> countryCodes, final int expectedResponseStatusCode) {
|
||||
DynamicConfiguration dynamicConfiguration = mock(DynamicConfiguration.class);
|
||||
when(dynamicConfigurationManager.getConfiguration())
|
||||
.thenReturn(dynamicConfiguration);
|
||||
@@ -1732,8 +1883,13 @@ class AccountControllerTest {
|
||||
when(dynamicConfiguration.getCaptchaConfiguration())
|
||||
.thenReturn(signupCaptchaConfig);
|
||||
|
||||
final byte[] sessionId = "session".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
when(registrationServiceClient.sendRegistrationCode(any(), any(), any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(new byte[16]));
|
||||
.thenReturn(CompletableFuture.completedFuture(sessionId));
|
||||
|
||||
when(registrationServiceClient.createRegistrationSession(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(sessionId));
|
||||
|
||||
Response response =
|
||||
resources.getJerseyTest()
|
||||
@@ -1745,10 +1901,8 @@ class AccountControllerTest {
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(expectedResponseStatusCode);
|
||||
|
||||
final Phonenumber.PhoneNumber phoneNumber = PhoneNumberUtil.getInstance().parse(SENDER, null);
|
||||
|
||||
verify(registrationServiceClient, 200 == expectedResponseStatusCode ? times(1) : never())
|
||||
.sendRegistrationCode(phoneNumber, MessageTransport.SMS, ClientType.UNKNOWN, null, AccountController.REGISTRATION_RPC_TIMEOUT);
|
||||
.sendRegistrationCode(sessionId, MessageTransport.SMS, ClientType.UNKNOWN, null, AccountController.REGISTRATION_RPC_TIMEOUT);
|
||||
}
|
||||
|
||||
static Stream<Arguments> testSignupCaptcha() {
|
||||
@@ -1797,13 +1951,13 @@ class AccountControllerTest {
|
||||
|
||||
@Test
|
||||
void testAccountExistsRateLimited() throws RateLimitExceededException {
|
||||
final Duration expectedRetryAfter = Duration.ofSeconds(13);
|
||||
final Account account = mock(Account.class);
|
||||
final UUID accountIdentifier = UUID.randomUUID();
|
||||
when(accountsManager.getByAccountIdentifier(accountIdentifier)).thenReturn(Optional.of(account));
|
||||
|
||||
final RateLimiter checkAccountLimiter = mock(RateLimiter.class);
|
||||
when(rateLimiters.getCheckAccountExistenceLimiter()).thenReturn(checkAccountLimiter);
|
||||
doThrow(new RateLimitExceededException(Duration.ofSeconds(13))).when(checkAccountLimiter).validate("127.0.0.1");
|
||||
MockUtils.updateRateLimiterResponseToFail(
|
||||
rateLimiters, RateLimiters.Handle.CHECK_ACCOUNT_EXISTENCE, "127.0.0.1", expectedRetryAfter);
|
||||
|
||||
final Response response = resources.getJerseyTest()
|
||||
.target(String.format("/v1/accounts/account/%s", accountIdentifier))
|
||||
@@ -1812,7 +1966,7 @@ class AccountControllerTest {
|
||||
.head();
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(413);
|
||||
assertThat(response.getHeaderString("Retry-After")).isEqualTo(String.valueOf(Duration.ofSeconds(13).toSeconds()));
|
||||
assertThat(response.getHeaderString("Retry-After")).isEqualTo(String.valueOf(expectedRetryAfter.toSeconds()));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -1866,7 +2020,9 @@ class AccountControllerTest {
|
||||
|
||||
@Test
|
||||
void testLookupUsernameRateLimited() throws RateLimitExceededException {
|
||||
doThrow(new RateLimitExceededException(Duration.ofSeconds(13))).when(usernameLookupLimiter).validate("127.0.0.1");
|
||||
final Duration expectedRetryAfter = Duration.ofSeconds(13);
|
||||
MockUtils.updateRateLimiterResponseToFail(
|
||||
rateLimiters, RateLimiters.Handle.USERNAME_LOOKUP, "127.0.0.1", expectedRetryAfter);
|
||||
final Response response = resources.getJerseyTest()
|
||||
.target("/v1/accounts/username/test.123")
|
||||
.request()
|
||||
@@ -1874,7 +2030,7 @@ class AccountControllerTest {
|
||||
.get();
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(413);
|
||||
assertThat(response.getHeaderString("Retry-After")).isEqualTo(String.valueOf(Duration.ofSeconds(13).toSeconds()));
|
||||
assertThat(response.getHeaderString("Retry-After")).isEqualTo(String.valueOf(expectedRetryAfter.toSeconds()));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@@ -1891,10 +2047,10 @@ class AccountControllerTest {
|
||||
return Stream.of(
|
||||
Arguments.of(null, null, false),
|
||||
Arguments.of("123456", null, false),
|
||||
Arguments.of(null, new StoredVerificationCode(null, 0, null, null, null), false),
|
||||
Arguments.of(null, new StoredVerificationCode(null, 0, "123456", null, null), false),
|
||||
Arguments.of("654321", new StoredVerificationCode(null, 0, "123456", null, null), false),
|
||||
Arguments.of("123456", new StoredVerificationCode(null, 0, "123456", null, null), true)
|
||||
Arguments.of(null, new StoredVerificationCode(null, 0, null, null), false),
|
||||
Arguments.of(null, new StoredVerificationCode(null, 0, "123456", null), false),
|
||||
Arguments.of("654321", new StoredVerificationCode(null, 0, "123456", null), false),
|
||||
Arguments.of("123456", new StoredVerificationCode(null, 0, "123456", null), true)
|
||||
);
|
||||
}
|
||||
}
|
||||
+67
-8
@@ -13,6 +13,7 @@ import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.argThat;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.anyBoolean;
|
||||
import static org.mockito.Mockito.anyString;
|
||||
@@ -79,6 +80,7 @@ import org.whispersystems.textsecuregcm.entities.OutgoingMessageEntity;
|
||||
import org.whispersystems.textsecuregcm.entities.OutgoingMessageEntityList;
|
||||
import org.whispersystems.textsecuregcm.entities.SendMultiRecipientMessageResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.SignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.SpamReport;
|
||||
import org.whispersystems.textsecuregcm.entities.StaleDevices;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
@@ -87,6 +89,7 @@ import org.whispersystems.textsecuregcm.providers.MultiRecipientMessageProvider;
|
||||
import org.whispersystems.textsecuregcm.push.MessageSender;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
|
||||
import org.whispersystems.textsecuregcm.push.ReceiptSender;
|
||||
import org.whispersystems.textsecuregcm.spam.ReportSpamTokenProvider;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.DeletedAccountsManager;
|
||||
@@ -124,8 +127,6 @@ class MessageControllerTest {
|
||||
private static final String INTERNATIONAL_RECIPIENT = "+61123456789";
|
||||
private static final UUID INTERNATIONAL_UUID = UUID.fromString("33333333-3333-3333-3333-333333333333");
|
||||
|
||||
private Account internationalAccount;
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static final RedisAdvancedClusterCommands<String, String> redisCommands = mock(RedisAdvancedClusterCommands.class);
|
||||
|
||||
@@ -150,7 +151,8 @@ class MessageControllerTest {
|
||||
.setTestContainerFactory(new GrizzlyWebTestContainerFactory())
|
||||
.addResource(
|
||||
new MessageController(rateLimiters, messageSender, receiptSender, accountsManager, deletedAccountsManager,
|
||||
messagesManager, pushNotificationManager, reportMessageManager, multiRecipientMessageExecutor))
|
||||
messagesManager, pushNotificationManager, reportMessageManager, multiRecipientMessageExecutor,
|
||||
ReportSpamTokenProvider.noop()))
|
||||
.build();
|
||||
|
||||
@BeforeEach
|
||||
@@ -167,7 +169,8 @@ class MessageControllerTest {
|
||||
|
||||
Account singleDeviceAccount = AccountsHelper.generateTestAccount(SINGLE_DEVICE_RECIPIENT, SINGLE_DEVICE_UUID, SINGLE_DEVICE_PNI, singleDeviceList, UNIDENTIFIED_ACCESS_BYTES);
|
||||
Account multiDeviceAccount = AccountsHelper.generateTestAccount(MULTI_DEVICE_RECIPIENT, MULTI_DEVICE_UUID, MULTI_DEVICE_PNI, multiDeviceList, UNIDENTIFIED_ACCESS_BYTES);
|
||||
internationalAccount = AccountsHelper.generateTestAccount(INTERNATIONAL_RECIPIENT, INTERNATIONAL_UUID, UUID.randomUUID(), singleDeviceList, UNIDENTIFIED_ACCESS_BYTES);
|
||||
Account internationalAccount = AccountsHelper.generateTestAccount(INTERNATIONAL_RECIPIENT, INTERNATIONAL_UUID,
|
||||
UUID.randomUUID(), singleDeviceList, UNIDENTIFIED_ACCESS_BYTES);
|
||||
|
||||
when(accountsManager.getByAccountIdentifier(eq(SINGLE_DEVICE_UUID))).thenReturn(Optional.of(singleDeviceAccount));
|
||||
when(accountsManager.getByPhoneNumberIdentifier(SINGLE_DEVICE_PNI)).thenReturn(Optional.of(singleDeviceAccount));
|
||||
@@ -198,6 +201,7 @@ class MessageControllerTest {
|
||||
messageSender,
|
||||
receiptSender,
|
||||
accountsManager,
|
||||
deletedAccountsManager,
|
||||
messagesManager,
|
||||
rateLimiters,
|
||||
rateLimiter,
|
||||
@@ -624,7 +628,7 @@ class MessageControllerTest {
|
||||
assertThat(response.getStatus(), is(equalTo(202)));
|
||||
|
||||
verify(reportMessageManager).report(Optional.of(senderNumber), Optional.of(senderAci), Optional.of(senderPni),
|
||||
messageGuid, AuthHelper.VALID_UUID);
|
||||
messageGuid, AuthHelper.VALID_UUID, Optional.empty());
|
||||
verify(deletedAccountsManager, never()).findDeletedAccountE164(any(UUID.class));
|
||||
verify(accountsManager, never()).getPhoneNumberIdentifier(anyString());
|
||||
|
||||
@@ -641,7 +645,7 @@ class MessageControllerTest {
|
||||
assertThat(response.getStatus(), is(equalTo(202)));
|
||||
|
||||
verify(reportMessageManager).report(Optional.of(senderNumber), Optional.of(senderAci), Optional.of(senderPni),
|
||||
messageGuid, AuthHelper.VALID_UUID);
|
||||
messageGuid, AuthHelper.VALID_UUID, Optional.empty());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -671,7 +675,7 @@ class MessageControllerTest {
|
||||
assertThat(response.getStatus(), is(equalTo(202)));
|
||||
|
||||
verify(reportMessageManager).report(Optional.of(senderNumber), Optional.of(senderAci), Optional.of(senderPni),
|
||||
messageGuid, AuthHelper.VALID_UUID);
|
||||
messageGuid, AuthHelper.VALID_UUID, Optional.empty());
|
||||
verify(deletedAccountsManager, never()).findDeletedAccountE164(any(UUID.class));
|
||||
verify(accountsManager, never()).getPhoneNumberIdentifier(anyString());
|
||||
|
||||
@@ -689,7 +693,62 @@ class MessageControllerTest {
|
||||
assertThat(response.getStatus(), is(equalTo(202)));
|
||||
|
||||
verify(reportMessageManager).report(Optional.of(senderNumber), Optional.of(senderAci), Optional.of(senderPni),
|
||||
messageGuid, AuthHelper.VALID_UUID);
|
||||
messageGuid, AuthHelper.VALID_UUID, Optional.empty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testReportMessageByAciWithSpamReportToken() {
|
||||
|
||||
final String senderNumber = "+12125550001";
|
||||
final UUID senderAci = UUID.randomUUID();
|
||||
final UUID senderPni = UUID.randomUUID();
|
||||
UUID messageGuid = UUID.randomUUID();
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
when(account.getUuid()).thenReturn(senderAci);
|
||||
when(account.getNumber()).thenReturn(senderNumber);
|
||||
when(account.getPhoneNumberIdentifier()).thenReturn(senderPni);
|
||||
|
||||
when(accountsManager.getByAccountIdentifier(senderAci)).thenReturn(Optional.of(account));
|
||||
when(deletedAccountsManager.findDeletedAccountE164(senderAci)).thenReturn(Optional.of(senderNumber));
|
||||
when(accountsManager.getPhoneNumberIdentifier(senderNumber)).thenReturn(senderPni);
|
||||
|
||||
Entity<SpamReport> entity = Entity.entity(new SpamReport(new byte[3]), "application/json");
|
||||
Response response =
|
||||
resources.getJerseyTest()
|
||||
.target(String.format("/v1/messages/report/%s/%s", senderAci, messageGuid))
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.post(entity);
|
||||
|
||||
assertThat(response.getStatus(), is(equalTo(202)));
|
||||
verify(reportMessageManager).report(eq(Optional.of(senderNumber)),
|
||||
eq(Optional.of(senderAci)),
|
||||
eq(Optional.of(senderPni)),
|
||||
eq(messageGuid),
|
||||
eq(AuthHelper.VALID_UUID),
|
||||
argThat(maybeBytes -> maybeBytes.map(bytes -> Arrays.equals(bytes, new byte[3])).orElse(false)));
|
||||
verify(deletedAccountsManager, never()).findDeletedAccountE164(any(UUID.class));
|
||||
verify(accountsManager, never()).getPhoneNumberIdentifier(anyString());
|
||||
when(accountsManager.getByAccountIdentifier(senderAci)).thenReturn(Optional.empty());
|
||||
|
||||
messageGuid = UUID.randomUUID();
|
||||
|
||||
entity = Entity.entity(new SpamReport(new byte[5]), "application/json");
|
||||
response =
|
||||
resources.getJerseyTest()
|
||||
.target(String.format("/v1/messages/report/%s/%s", senderAci, messageGuid))
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.post(entity);
|
||||
|
||||
assertThat(response.getStatus(), is(equalTo(202)));
|
||||
verify(reportMessageManager).report(eq(Optional.of(senderNumber)),
|
||||
eq(Optional.of(senderAci)),
|
||||
eq(Optional.of(senderPni)),
|
||||
eq(messageGuid),
|
||||
eq(AuthHelper.VALID_UUID),
|
||||
argThat(maybeBytes -> maybeBytes.map(bytes -> Arrays.equals(bytes, new byte[5])).orElse(false)));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+291
@@ -0,0 +1,291 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import io.dropwizard.testing.junit5.DropwizardExtensionsSupport;
|
||||
import io.dropwizard.testing.junit5.ResourceExtension;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import javax.ws.rs.client.Entity;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
import org.apache.commons.lang3.RandomUtils;
|
||||
import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mockito;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
|
||||
import org.whispersystems.textsecuregcm.configuration.SecureBackupServiceConfiguration;
|
||||
import org.whispersystems.textsecuregcm.entities.AuthCheckRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.AuthCheckResponse;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
|
||||
import org.whispersystems.textsecuregcm.util.MockUtils;
|
||||
import org.whispersystems.textsecuregcm.util.MutableClock;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
|
||||
@ExtendWith(DropwizardExtensionsSupport.class)
|
||||
class SecureBackupControllerTest {
|
||||
|
||||
private static final UUID USER_1 = UUID.randomUUID();
|
||||
|
||||
private static final UUID USER_2 = UUID.randomUUID();
|
||||
|
||||
private static final UUID USER_3 = UUID.randomUUID();
|
||||
|
||||
private static final String E164_VALID = "+18005550123";
|
||||
|
||||
private static final String E164_INVALID = "1(800)555-0123";
|
||||
|
||||
private static final byte[] SECRET = RandomUtils.nextBytes(32);
|
||||
|
||||
private static final SecureBackupServiceConfiguration CFG = MockUtils.buildMock(
|
||||
SecureBackupServiceConfiguration.class,
|
||||
cfg -> Mockito.when(cfg.getUserAuthenticationTokenSharedSecret()).thenReturn(SECRET)
|
||||
);
|
||||
|
||||
private static final MutableClock CLOCK = MockUtils.mutableClock(0);
|
||||
|
||||
private static final ExternalServiceCredentialsGenerator CREDENTIAL_GENERATOR =
|
||||
SecureBackupController.credentialsGenerator(CFG, CLOCK);
|
||||
|
||||
private static final AccountsManager ACCOUNTS_MANAGER = Mockito.mock(AccountsManager.class);
|
||||
|
||||
private static final SecureBackupController CONTROLLER =
|
||||
new SecureBackupController(CREDENTIAL_GENERATOR, ACCOUNTS_MANAGER);
|
||||
|
||||
private static final ResourceExtension RESOURCES = ResourceExtension.builder()
|
||||
.addProvider(AuthHelper.getAuthFilter())
|
||||
.setMapper(SystemMapper.getMapper())
|
||||
.setTestContainerFactory(new GrizzlyWebTestContainerFactory())
|
||||
.addResource(CONTROLLER)
|
||||
.build();
|
||||
|
||||
@BeforeAll
|
||||
public static void before() throws Exception {
|
||||
Mockito.when(ACCOUNTS_MANAGER.getByE164(E164_VALID)).thenReturn(Optional.of(account(USER_1)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testOneMatch() throws Exception {
|
||||
validate(Map.of(
|
||||
token(USER_1, day(1)), AuthCheckResponse.Result.MATCH,
|
||||
token(USER_2, day(1)), AuthCheckResponse.Result.NO_MATCH,
|
||||
token(USER_3, day(1)), AuthCheckResponse.Result.NO_MATCH
|
||||
), day(2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNoMatch() throws Exception {
|
||||
validate(Map.of(
|
||||
token(USER_2, day(1)), AuthCheckResponse.Result.NO_MATCH,
|
||||
token(USER_3, day(1)), AuthCheckResponse.Result.NO_MATCH
|
||||
), day(2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testEmptyInput() throws Exception {
|
||||
validate(Collections.emptyMap(), day(2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSomeInvalid() throws Exception {
|
||||
final String fakeToken = token(USER_3, day(1)).replaceAll(USER_3.toString(), USER_2.toString());
|
||||
validate(Map.of(
|
||||
token(USER_1, day(1)), AuthCheckResponse.Result.MATCH,
|
||||
token(USER_2, day(1)), AuthCheckResponse.Result.NO_MATCH,
|
||||
fakeToken, AuthCheckResponse.Result.INVALID
|
||||
), day(2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSomeExpired() throws Exception {
|
||||
validate(Map.of(
|
||||
token(USER_1, day(100)), AuthCheckResponse.Result.MATCH,
|
||||
token(USER_2, day(100)), AuthCheckResponse.Result.NO_MATCH,
|
||||
token(USER_3, day(10)), AuthCheckResponse.Result.INVALID,
|
||||
token(USER_3, day(20)), AuthCheckResponse.Result.INVALID
|
||||
), day(110));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSomeHaveNewerVersions() throws Exception {
|
||||
validate(Map.of(
|
||||
token(USER_1, day(10)), AuthCheckResponse.Result.INVALID,
|
||||
token(USER_1, day(20)), AuthCheckResponse.Result.MATCH,
|
||||
token(USER_2, day(10)), AuthCheckResponse.Result.NO_MATCH,
|
||||
token(USER_3, day(20)), AuthCheckResponse.Result.NO_MATCH,
|
||||
token(USER_3, day(10)), AuthCheckResponse.Result.INVALID
|
||||
), day(25));
|
||||
}
|
||||
|
||||
private static void validate(
|
||||
final Map<String, AuthCheckResponse.Result> expected,
|
||||
final long nowMillis) throws Exception {
|
||||
CLOCK.setTimeMillis(nowMillis);
|
||||
final AuthCheckRequest request = new AuthCheckRequest(E164_VALID, List.copyOf(expected.keySet()));
|
||||
final AuthCheckResponse response = CONTROLLER.authCheck(request);
|
||||
assertEquals(expected, response.matches());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHttpResponseCodeSuccess() throws Exception {
|
||||
final Map<String, AuthCheckResponse.Result> expected = Map.of(
|
||||
token(USER_1, day(10)), AuthCheckResponse.Result.INVALID,
|
||||
token(USER_1, day(20)), AuthCheckResponse.Result.MATCH,
|
||||
token(USER_2, day(10)), AuthCheckResponse.Result.NO_MATCH,
|
||||
token(USER_3, day(20)), AuthCheckResponse.Result.NO_MATCH,
|
||||
token(USER_3, day(10)), AuthCheckResponse.Result.INVALID
|
||||
);
|
||||
|
||||
CLOCK.setTimeMillis(day(25));
|
||||
|
||||
final AuthCheckRequest in = new AuthCheckRequest(E164_VALID, List.copyOf(expected.keySet()));
|
||||
|
||||
final Response response = RESOURCES.getJerseyTest()
|
||||
.target("/v1/backup/auth/check")
|
||||
.request()
|
||||
.post(Entity.entity(in, MediaType.APPLICATION_JSON));
|
||||
|
||||
try (response) {
|
||||
final AuthCheckResponse res = response.readEntity(AuthCheckResponse.class);
|
||||
assertEquals(200, response.getStatus());
|
||||
assertEquals(expected, res.matches());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHttpResponseCodeWhenInvalidNumber() throws Exception {
|
||||
final AuthCheckRequest in = new AuthCheckRequest(E164_INVALID, Collections.singletonList("1"));
|
||||
final Response response = RESOURCES.getJerseyTest()
|
||||
.target("/v1/backup/auth/check")
|
||||
.request()
|
||||
.post(Entity.entity(in, MediaType.APPLICATION_JSON));
|
||||
|
||||
try (response) {
|
||||
assertEquals(422, response.getStatus());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHttpResponseCodeWhenTooManyTokens() throws Exception {
|
||||
final AuthCheckRequest inOkay = new AuthCheckRequest(E164_VALID, List.of(
|
||||
"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"
|
||||
));
|
||||
final AuthCheckRequest inTooMany = new AuthCheckRequest(E164_VALID, List.of(
|
||||
"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11"
|
||||
));
|
||||
final AuthCheckRequest inNoTokens = new AuthCheckRequest(E164_VALID, Collections.emptyList());
|
||||
|
||||
final Response responseOkay = RESOURCES.getJerseyTest()
|
||||
.target("/v1/backup/auth/check")
|
||||
.request()
|
||||
.post(Entity.entity(inOkay, MediaType.APPLICATION_JSON));
|
||||
|
||||
final Response responseError1 = RESOURCES.getJerseyTest()
|
||||
.target("/v1/backup/auth/check")
|
||||
.request()
|
||||
.post(Entity.entity(inTooMany, MediaType.APPLICATION_JSON));
|
||||
|
||||
final Response responseError2 = RESOURCES.getJerseyTest()
|
||||
.target("/v1/backup/auth/check")
|
||||
.request()
|
||||
.post(Entity.entity(inNoTokens, MediaType.APPLICATION_JSON));
|
||||
|
||||
try (responseOkay; responseError1; responseError2) {
|
||||
assertEquals(200, responseOkay.getStatus());
|
||||
assertEquals(422, responseError1.getStatus());
|
||||
assertEquals(422, responseError2.getStatus());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHttpResponseCodeWhenPasswordsMissing() throws Exception {
|
||||
final Response response = RESOURCES.getJerseyTest()
|
||||
.target("/v1/backup/auth/check")
|
||||
.request()
|
||||
.post(Entity.entity("""
|
||||
{
|
||||
"number": "123"
|
||||
}
|
||||
""", MediaType.APPLICATION_JSON));
|
||||
|
||||
try (response) {
|
||||
assertEquals(422, response.getStatus());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHttpResponseCodeWhenNumberMissing() throws Exception {
|
||||
final Response response = RESOURCES.getJerseyTest()
|
||||
.target("/v1/backup/auth/check")
|
||||
.request()
|
||||
.post(Entity.entity("""
|
||||
{
|
||||
"passwords": ["aaa:bbb"]
|
||||
}
|
||||
""", MediaType.APPLICATION_JSON));
|
||||
|
||||
try (response) {
|
||||
assertEquals(422, response.getStatus());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHttpResponseCodeWhenExtraFields() throws Exception {
|
||||
final Response response = RESOURCES.getJerseyTest()
|
||||
.target("/v1/backup/auth/check")
|
||||
.request()
|
||||
.post(Entity.entity("""
|
||||
{
|
||||
"number": "+18005550123",
|
||||
"passwords": ["aaa:bbb"],
|
||||
"unexpected": "value"
|
||||
}
|
||||
""", MediaType.APPLICATION_JSON));
|
||||
|
||||
try (response) {
|
||||
assertEquals(200, response.getStatus());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHttpResponseCodeWhenNotAJson() throws Exception {
|
||||
final Response response = RESOURCES.getJerseyTest()
|
||||
.target("/v1/backup/auth/check")
|
||||
.request()
|
||||
.post(Entity.entity("random text", MediaType.APPLICATION_JSON));
|
||||
|
||||
try (response) {
|
||||
assertEquals(400, response.getStatus());
|
||||
}
|
||||
}
|
||||
|
||||
private static String token(final UUID uuid, final long timeMillis) {
|
||||
CLOCK.setTimeMillis(timeMillis);
|
||||
final ExternalServiceCredentials credentials = CREDENTIAL_GENERATOR.generateForUuid(uuid);
|
||||
return credentials.username() + ":" + credentials.password();
|
||||
}
|
||||
|
||||
private static long day(final int n) {
|
||||
return TimeUnit.DAYS.toMillis(n);
|
||||
}
|
||||
|
||||
private static Account account(final UUID uuid) {
|
||||
final Account a = new Account();
|
||||
a.setUuid(uuid);
|
||||
return a;
|
||||
}
|
||||
}
|
||||
+209
-34
@@ -12,15 +12,17 @@ import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.reset;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoMoreInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.whispersystems.textsecuregcm.util.AttributeValues.b;
|
||||
import static org.whispersystems.textsecuregcm.util.AttributeValues.n;
|
||||
import static org.whispersystems.textsecuregcm.util.AttributeValues.s;
|
||||
|
||||
import com.fasterxml.jackson.dataformat.yaml.YAMLMapper;
|
||||
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
||||
import com.stripe.exception.ApiException;
|
||||
import com.stripe.model.PaymentIntent;
|
||||
import com.stripe.model.Subscription;
|
||||
import io.dropwizard.auth.PolymorphicAuthValueFactoryProvider;
|
||||
import io.dropwizard.testing.junit5.DropwizardExtensionsSupport;
|
||||
import io.dropwizard.testing.junit5.ResourceExtension;
|
||||
@@ -38,15 +40,18 @@ import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.stream.Stream;
|
||||
import javax.ws.rs.client.Entity;
|
||||
import javax.ws.rs.core.Response;
|
||||
import org.glassfish.jersey.server.ServerProperties;
|
||||
import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
|
||||
import org.whispersystems.textsecuregcm.auth.DisabledPermittedAuthenticatedAccount;
|
||||
@@ -65,6 +70,7 @@ import org.whispersystems.textsecuregcm.subscriptions.BraintreeManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.ProcessorCustomer;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.StripeManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessor;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorManager;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
|
||||
@@ -84,18 +90,22 @@ class SubscriptionControllerTest {
|
||||
private static final OneTimeDonationConfiguration ONETIME_CONFIG = ConfigHelper.getOneTimeConfig();
|
||||
private static final SubscriptionManager SUBSCRIPTION_MANAGER = mock(SubscriptionManager.class);
|
||||
private static final StripeManager STRIPE_MANAGER = mock(StripeManager.class);
|
||||
private static final BraintreeManager BRAINTREE_MANAGER = mock(BraintreeManager.class);
|
||||
private static final PaymentIntent PAYMENT_INTENT = mock(PaymentIntent.class);
|
||||
|
||||
static {
|
||||
// this behavior is required by the SubscriptionController constructor
|
||||
List.of(STRIPE_MANAGER, BRAINTREE_MANAGER)
|
||||
.forEach(manager -> {
|
||||
when(manager.supportsPaymentMethod(any()))
|
||||
.thenCallRealMethod();
|
||||
});
|
||||
when(STRIPE_MANAGER.getSupportedCurrencies())
|
||||
.thenReturn(Set.of("usd", "jpy", "bif"));
|
||||
when(STRIPE_MANAGER.supportsPaymentMethod(any()))
|
||||
.thenCallRealMethod();
|
||||
when(BRAINTREE_MANAGER.getSupportedCurrencies())
|
||||
.thenReturn(Set.of("usd", "jpy"));
|
||||
}
|
||||
|
||||
private static final BraintreeManager BRAINTREE_MANAGER = mock(BraintreeManager.class);
|
||||
|
||||
private static final ServerZkReceiptOperations ZK_OPS = mock(ServerZkReceiptOperations.class);
|
||||
private static final IssuedReceiptsManager ISSUED_RECEIPTS_MANAGER = mock(IssuedReceiptsManager.class);
|
||||
private static final BadgeTranslator BADGE_TRANSLATOR = mock(BadgeTranslator.class);
|
||||
@@ -116,18 +126,15 @@ class SubscriptionControllerTest {
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
when(STRIPE_MANAGER.getProcessor()).thenReturn(SubscriptionProcessor.STRIPE);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
reset(CLOCK, SUBSCRIPTION_MANAGER, STRIPE_MANAGER, ZK_OPS, ISSUED_RECEIPTS_MANAGER,
|
||||
reset(CLOCK, SUBSCRIPTION_MANAGER, STRIPE_MANAGER, BRAINTREE_MANAGER, ZK_OPS, ISSUED_RECEIPTS_MANAGER,
|
||||
BADGE_TRANSLATOR, LEVEL_TRANSLATOR);
|
||||
|
||||
when(STRIPE_MANAGER.getProcessor()).thenReturn(SubscriptionProcessor.STRIPE);
|
||||
when(BRAINTREE_MANAGER.getProcessor()).thenReturn(SubscriptionProcessor.BRAINTREE);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCreateBoostPaymentIntentAmountBelowCurrencyMinimum() {
|
||||
when(STRIPE_MANAGER.convertConfiguredAmountToStripeAmount(any(), any())).thenReturn(new BigDecimal(250));
|
||||
when(STRIPE_MANAGER.supportsCurrency("usd")).thenReturn(true);
|
||||
final Response response = RESOURCE_EXTENSION.target("/v1/subscription/boost/create")
|
||||
.request()
|
||||
@@ -150,24 +157,21 @@ class SubscriptionControllerTest {
|
||||
|
||||
@Test
|
||||
void testCreateBoostPaymentIntentLevelAmountMismatch() {
|
||||
when(STRIPE_MANAGER.convertConfiguredAmountToStripeAmount(any(), any())).thenReturn(new BigDecimal(20));
|
||||
|
||||
final Response response = RESOURCE_EXTENSION.target("/v1/subscription/boost/create")
|
||||
.request()
|
||||
.post(Entity.json("""
|
||||
{
|
||||
"currency": "USD",
|
||||
"amount": 25,
|
||||
"level": 100
|
||||
}
|
||||
"""
|
||||
{
|
||||
"currency": "USD",
|
||||
"amount": 25,
|
||||
"level": 100
|
||||
}
|
||||
"""
|
||||
));
|
||||
assertThat(response.getStatus()).isEqualTo(409);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCreateBoostPaymentIntent() {
|
||||
when(STRIPE_MANAGER.convertConfiguredAmountToStripeAmount(any(), any())).thenReturn(new BigDecimal(300));
|
||||
when(STRIPE_MANAGER.createPaymentIntent(anyString(), anyLong(), anyLong()))
|
||||
.thenReturn(CompletableFuture.completedFuture(PAYMENT_INTENT));
|
||||
when(STRIPE_MANAGER.supportsCurrency("usd")).thenReturn(true);
|
||||
@@ -233,7 +237,7 @@ class SubscriptionControllerTest {
|
||||
@Test
|
||||
void success() {
|
||||
when(STRIPE_MANAGER.createSubscription(any(), any(), anyLong(), anyLong()))
|
||||
.thenReturn(CompletableFuture.completedFuture(mock(Subscription.class)));
|
||||
.thenReturn(CompletableFuture.completedFuture(mock(SubscriptionProcessorManager.SubscriptionId.class)));
|
||||
|
||||
final String level = String.valueOf(levelId);
|
||||
final String idempotencyKey = UUID.randomUUID().toString();
|
||||
@@ -435,6 +439,159 @@ class SubscriptionControllerTest {
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
void setSubscriptionLevelMissingProcessorCustomer() {
|
||||
// set up record
|
||||
final byte[] subscriberUserAndKey = new byte[32];
|
||||
Arrays.fill(subscriberUserAndKey, (byte) 1);
|
||||
final String subscriberId = Base64.getEncoder().encodeToString(subscriberUserAndKey);
|
||||
|
||||
final Map<String, AttributeValue> dynamoItem = Map.of(SubscriptionManager.KEY_PASSWORD, b(new byte[16]),
|
||||
SubscriptionManager.KEY_CREATED_AT, n(Instant.now().getEpochSecond()),
|
||||
SubscriptionManager.KEY_ACCESSED_AT, n(Instant.now().getEpochSecond())
|
||||
);
|
||||
final SubscriptionManager.Record record = SubscriptionManager.Record.from(
|
||||
Arrays.copyOfRange(subscriberUserAndKey, 0, 16), dynamoItem);
|
||||
when(SUBSCRIPTION_MANAGER.create(any(), any(), any(Instant.class)))
|
||||
.thenReturn(CompletableFuture.completedFuture(record));
|
||||
|
||||
// set up mocks
|
||||
when(CLOCK.instant()).thenReturn(Instant.now());
|
||||
when(SUBSCRIPTION_MANAGER.get(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(SubscriptionManager.GetResult.found(record)));
|
||||
|
||||
final Response response = RESOURCE_EXTENSION
|
||||
.target(String.format("/v1/subscription/%s/level/%d/%s/%s", subscriberId, 5, "usd", "abcd"))
|
||||
.request()
|
||||
.put(Entity.json(""));
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(409);
|
||||
}
|
||||
|
||||
@Test
|
||||
void setSubscriptionLevel() {
|
||||
// set up record
|
||||
final byte[] subscriberUserAndKey = new byte[32];
|
||||
Arrays.fill(subscriberUserAndKey, (byte) 1);
|
||||
final String subscriberId = Base64.getEncoder().encodeToString(subscriberUserAndKey);
|
||||
|
||||
final String customerId = "customer";
|
||||
final Map<String, AttributeValue> dynamoItem = Map.of(SubscriptionManager.KEY_PASSWORD, b(new byte[16]),
|
||||
SubscriptionManager.KEY_CREATED_AT, n(Instant.now().getEpochSecond()),
|
||||
SubscriptionManager.KEY_ACCESSED_AT, n(Instant.now().getEpochSecond()),
|
||||
SubscriptionManager.KEY_PROCESSOR_ID_CUSTOMER_ID,
|
||||
b(new ProcessorCustomer(customerId, SubscriptionProcessor.BRAINTREE).toDynamoBytes())
|
||||
);
|
||||
final SubscriptionManager.Record record = SubscriptionManager.Record.from(
|
||||
Arrays.copyOfRange(subscriberUserAndKey, 0, 16), dynamoItem);
|
||||
when(SUBSCRIPTION_MANAGER.create(any(), any(), any(Instant.class)))
|
||||
.thenReturn(CompletableFuture.completedFuture(record));
|
||||
|
||||
// set up mocks
|
||||
when(CLOCK.instant()).thenReturn(Instant.now());
|
||||
when(SUBSCRIPTION_MANAGER.get(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(SubscriptionManager.GetResult.found(record)));
|
||||
|
||||
when(BRAINTREE_MANAGER.createSubscription(any(), any(), anyLong(), anyLong()))
|
||||
.thenReturn(CompletableFuture.completedFuture(new SubscriptionProcessorManager.SubscriptionId(
|
||||
"subscription")));
|
||||
when(SUBSCRIPTION_MANAGER.subscriptionCreated(any(), any(), any(), anyLong()))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
final long level = 5;
|
||||
final Response response = RESOURCE_EXTENSION
|
||||
.target(String.format("/v1/subscription/%s/level/%d/%s/%s", subscriberId, level, "usd", "abcd"))
|
||||
.request()
|
||||
.put(Entity.json(""));
|
||||
|
||||
verify(BRAINTREE_MANAGER).createSubscription(eq(customerId), eq("M1"), eq(level), eq(0L));
|
||||
verifyNoMoreInteractions(BRAINTREE_MANAGER);
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
|
||||
assertThat(response.readEntity(SubscriptionController.SetSubscriptionLevelSuccessResponse.class))
|
||||
.extracting(SubscriptionController.SetSubscriptionLevelSuccessResponse::getLevel)
|
||||
.isEqualTo(level);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void setSubscriptionLevelExistingSubscription(final String existingCurrency, final long existingLevel,
|
||||
final String requestCurrency, final long requestLevel, final boolean expectUpdate) {
|
||||
|
||||
// set up record
|
||||
final byte[] subscriberUserAndKey = new byte[32];
|
||||
Arrays.fill(subscriberUserAndKey, (byte) 1);
|
||||
final String subscriberId = Base64.getEncoder().encodeToString(subscriberUserAndKey);
|
||||
|
||||
final String customerId = "customer";
|
||||
final String existingSubscriptionId = "existingSubscription";
|
||||
final Map<String, AttributeValue> dynamoItem = Map.of(SubscriptionManager.KEY_PASSWORD, b(new byte[16]),
|
||||
SubscriptionManager.KEY_CREATED_AT, n(Instant.now().getEpochSecond()),
|
||||
SubscriptionManager.KEY_ACCESSED_AT, n(Instant.now().getEpochSecond()),
|
||||
SubscriptionManager.KEY_PROCESSOR_ID_CUSTOMER_ID,
|
||||
b(new ProcessorCustomer(customerId, SubscriptionProcessor.BRAINTREE).toDynamoBytes()),
|
||||
SubscriptionManager.KEY_SUBSCRIPTION_ID, s(existingSubscriptionId)
|
||||
);
|
||||
final SubscriptionManager.Record record = SubscriptionManager.Record.from(
|
||||
Arrays.copyOfRange(subscriberUserAndKey, 0, 16), dynamoItem);
|
||||
when(SUBSCRIPTION_MANAGER.create(any(), any(), any(Instant.class)))
|
||||
.thenReturn(CompletableFuture.completedFuture(record));
|
||||
|
||||
// set up mocks
|
||||
when(CLOCK.instant()).thenReturn(Instant.now());
|
||||
when(SUBSCRIPTION_MANAGER.get(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(SubscriptionManager.GetResult.found(record)));
|
||||
|
||||
final Object subscriptionObj = new Object();
|
||||
when(BRAINTREE_MANAGER.getSubscription(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(subscriptionObj));
|
||||
when(BRAINTREE_MANAGER.getLevelAndCurrencyForSubscription(subscriptionObj))
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
new SubscriptionProcessorManager.LevelAndCurrency(existingLevel, existingCurrency)));
|
||||
final String updatedSubscriptionId = "updatedSubscriptionId";
|
||||
|
||||
if (expectUpdate) {
|
||||
when(BRAINTREE_MANAGER.updateSubscription(any(), any(), anyLong(), anyString()))
|
||||
.thenReturn(CompletableFuture.completedFuture(new SubscriptionProcessorManager.SubscriptionId(
|
||||
updatedSubscriptionId)));
|
||||
when(SUBSCRIPTION_MANAGER.subscriptionLevelChanged(any(), any(), anyLong(), anyString()))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
}
|
||||
|
||||
final String idempotencyKey = "abcd";
|
||||
final Response response = RESOURCE_EXTENSION
|
||||
.target(String.format("/v1/subscription/%s/level/%d/%s/%s", subscriberId, requestLevel, requestCurrency,
|
||||
idempotencyKey))
|
||||
.request()
|
||||
.put(Entity.json(""));
|
||||
|
||||
verify(BRAINTREE_MANAGER).getSubscription(any());
|
||||
verify(BRAINTREE_MANAGER).getLevelAndCurrencyForSubscription(any());
|
||||
|
||||
if (expectUpdate) {
|
||||
verify(BRAINTREE_MANAGER).updateSubscription(any(), any(), eq(requestLevel), eq(idempotencyKey));
|
||||
verify(SUBSCRIPTION_MANAGER).subscriptionLevelChanged(any(), any(), eq(requestLevel), eq(updatedSubscriptionId));
|
||||
}
|
||||
|
||||
verifyNoMoreInteractions(BRAINTREE_MANAGER);
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
|
||||
assertThat(response.readEntity(SubscriptionController.SetSubscriptionLevelSuccessResponse.class))
|
||||
.extracting(SubscriptionController.SetSubscriptionLevelSuccessResponse::getLevel)
|
||||
.isEqualTo(requestLevel);
|
||||
}
|
||||
|
||||
static Stream<Arguments> setSubscriptionLevelExistingSubscription() {
|
||||
return Stream.of(
|
||||
Arguments.of("usd", 5, "usd", 5, false),
|
||||
Arguments.of("usd", 5, "jpy", 5, true),
|
||||
Arguments.of("usd", 5, "usd", 15, true),
|
||||
Arguments.of("usd", 5, "jpy", 15, true)
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getSubscriptionConfiguration() {
|
||||
|
||||
@@ -473,7 +630,7 @@ class SubscriptionControllerTest {
|
||||
List.of(BigDecimal.valueOf(20))));
|
||||
assertThat(currency.subscription()).isEqualTo(
|
||||
Map.of("5", BigDecimal.valueOf(5), "15", BigDecimal.valueOf(15), "35", BigDecimal.valueOf(35)));
|
||||
assertThat(currency.supportedPaymentMethods()).isEqualTo(List.of("CARD"));
|
||||
assertThat(currency.supportedPaymentMethods()).isEqualTo(List.of("CARD", "PAYPAL"));
|
||||
});
|
||||
|
||||
assertThat(currencyMap).extractingByKey("jpy").satisfies(currency -> {
|
||||
@@ -487,7 +644,7 @@ class SubscriptionControllerTest {
|
||||
List.of(BigDecimal.valueOf(2000))));
|
||||
assertThat(currency.subscription()).isEqualTo(
|
||||
Map.of("5", BigDecimal.valueOf(500), "15", BigDecimal.valueOf(1500), "35", BigDecimal.valueOf(3500)));
|
||||
assertThat(currency.supportedPaymentMethods()).isEqualTo(List.of("CARD"));
|
||||
assertThat(currency.supportedPaymentMethods()).isEqualTo(List.of("CARD", "PAYPAL"));
|
||||
});
|
||||
|
||||
assertThat(currencyMap).extractingByKey("bif").satisfies(currency -> {
|
||||
@@ -669,37 +826,55 @@ class SubscriptionControllerTest {
|
||||
prices:
|
||||
usd:
|
||||
amount: '5'
|
||||
id: R1
|
||||
processorIds:
|
||||
STRIPE: R1
|
||||
BRAINTREE: M1
|
||||
jpy:
|
||||
amount: '500'
|
||||
id: Q1
|
||||
processorIds:
|
||||
STRIPE: Q1
|
||||
BRAINTREE: N1
|
||||
bif:
|
||||
amount: '5000'
|
||||
id: S1
|
||||
processorIds:
|
||||
STRIPE: S1
|
||||
BRAINTREE: O1
|
||||
15:
|
||||
badge: B2
|
||||
prices:
|
||||
usd:
|
||||
amount: '15'
|
||||
id: R2
|
||||
processorIds:
|
||||
STRIPE: R2
|
||||
BRAINTREE: M2
|
||||
jpy:
|
||||
amount: '1500'
|
||||
id: Q2
|
||||
processorIds:
|
||||
STRIPE: Q2
|
||||
BRAINTREE: N2
|
||||
bif:
|
||||
amount: '15000'
|
||||
id: S2
|
||||
processorIds:
|
||||
STRIPE: S2
|
||||
BRAINTREE: O2
|
||||
35:
|
||||
badge: B3
|
||||
prices:
|
||||
usd:
|
||||
amount: '35'
|
||||
id: R3
|
||||
processorIds:
|
||||
STRIPE: R3
|
||||
BRAINTREE: M3
|
||||
jpy:
|
||||
amount: '3500'
|
||||
id: Q3
|
||||
processorIds:
|
||||
STRIPE: Q3
|
||||
BRAINTREE: N3
|
||||
bif:
|
||||
amount: '35000'
|
||||
id: S3
|
||||
processorIds:
|
||||
STRIPE: S3
|
||||
BRAINTREE: O3
|
||||
""";
|
||||
|
||||
private static final String ONETIME_CONFIG_YAML = """
|
||||
|
||||
Loaded 100 of 129 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user