mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-12-01 04:46:47 +00:00
Compare commits
49
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e3b303e2c8 | ||
|
|
1f77698420 | ||
|
|
03b4f16ac3 | ||
|
|
01eb99d281 | ||
|
|
73d3c88ef4 | ||
|
|
5fde1d8f7b | ||
|
|
367854ea14 | ||
|
|
f46d6c566b | ||
|
|
9d4280938e | ||
|
|
b898880a0d | ||
|
|
7857f85710 | ||
|
|
635350d66a | ||
|
|
1f0bf83fef | ||
|
|
8f394663b0 | ||
|
|
55abc73cac | ||
|
|
031beed7e4 | ||
|
|
ef4c46941c | ||
|
|
ddb8c02e40 | ||
|
|
a15d5cdbb9 | ||
|
|
a0c321557f | ||
|
|
4765492415 | ||
|
|
e6aef34398 | ||
|
|
e7916302ba | ||
|
|
db00752f3d | ||
|
|
92b903c639 | ||
|
|
92fdac8d76 | ||
|
|
3bac6e5fd3 | ||
|
|
ef9df20be4 | ||
|
|
11741a5048 | ||
|
|
b2c638a635 | ||
|
|
12d7157a4e | ||
|
|
5026242122 | ||
|
|
fe39fcdb12 | ||
|
|
51af17e3b8 | ||
|
|
1389de1e0c | ||
|
|
669e955cd2 | ||
|
|
dec95043fa | ||
|
|
4be8e0bfc8 | ||
|
|
99d492c61c | ||
|
|
2d22cc4420 | ||
|
|
894ec17169 | ||
|
|
59ea29ab61 | ||
|
|
69fb42ef82 | ||
|
|
9ce8f75d76 | ||
|
|
e90c8685f8 | ||
|
|
60738acd17 | ||
|
|
f618da855f | ||
|
|
54807b22a3 | ||
|
|
bdf3e1aea1 |
No files matched your search
@@ -28,13 +28,9 @@ updates:
|
||||
versions: [">=1.6.0"]
|
||||
# https://github.com/jetty/jetty.project/issues/15657
|
||||
- dependency-name: "org.eclipse.jetty:*"
|
||||
versions: ["<=12.1.12"]
|
||||
versions: ["<=12.1.14"]
|
||||
- dependency-name: "org.eclipse.jetty.ee10:*"
|
||||
versions: ["<=12.1.12"]
|
||||
|
||||
# Temporary exclusions, pending adaptation to upstream changes
|
||||
- dependency-name: "io.lettuce:lettuce-core"
|
||||
versions: [">=7.7.0.RELEASE"]
|
||||
versions: ["<=12.1.14"]
|
||||
|
||||
# Dependency convergence sentinels, pinned to specific versions
|
||||
- dependency-name: "tools.jackson.core:jackson-databind"
|
||||
|
||||
@@ -18,7 +18,7 @@ jobs:
|
||||
# setup-java requires gpg
|
||||
sudo apt-get install -y protobuf-compiler gpg
|
||||
pip install sabledocs
|
||||
- uses: actions/setup-java@dd06d9cba3e5552c54d9f8ea23572deb30010f7c # v6.0.0
|
||||
- uses: actions/setup-java@de7274f081f381c8f8158605e0321c36c376e2e6 # v6.0.1
|
||||
with:
|
||||
distribution: 'temurin'
|
||||
java-version-file: .java-version
|
||||
|
||||
@@ -25,12 +25,12 @@ jobs:
|
||||
# setup-java requires gpg
|
||||
sudo apt update
|
||||
sudo apt install -y gpg
|
||||
- uses: actions/setup-java@dd06d9cba3e5552c54d9f8ea23572deb30010f7c # v6.0.0
|
||||
- uses: actions/setup-java@de7274f081f381c8f8158605e0321c36c376e2e6 # v6.0.1
|
||||
with:
|
||||
distribution: 'temurin'
|
||||
java-version-file: .java-version
|
||||
cache: 'maven'
|
||||
- uses: aws-actions/configure-aws-credentials@e6de054238d6b7531b4efff3b6587d9aade6a06c # v6.2.3
|
||||
- uses: aws-actions/configure-aws-credentials@e1253824e5c10ff9df46874f81ed3ec929e19cfd # v6.3.0
|
||||
name: Configure AWS credentials from Test account
|
||||
with:
|
||||
role-to-assume: ${{ vars.AWS_ROLE }}
|
||||
|
||||
@@ -50,7 +50,7 @@ jobs:
|
||||
# ca-certificates: required for AWS CRT client
|
||||
apt update && apt install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin ca-certificates
|
||||
- name: Set up JDK
|
||||
uses: actions/setup-java@dd06d9cba3e5552c54d9f8ea23572deb30010f7c # v6.0.0
|
||||
uses: actions/setup-java@de7274f081f381c8f8158605e0321c36c376e2e6 # v6.0.1
|
||||
with:
|
||||
distribution: 'temurin'
|
||||
java-version-file: .java-version
|
||||
@@ -65,7 +65,7 @@ jobs:
|
||||
run: docker exec foundationdb1 /usr/bin/fdbcli --exec 'configure new single memory'
|
||||
- name: Download and install FoundationDB client
|
||||
run: |
|
||||
./mvnw -e -B -Pexclude-spam-filter clean prepare-package -DskipTests=true
|
||||
./mvnw -e -B -Pexclude-spam-filter -pl service download:wget@install-foundationdb-client-library
|
||||
cp service/target/jib-extra/usr/lib/libfdb_c.so /usr/lib/libfdb_c.x86_64.so
|
||||
ldconfig
|
||||
- name: Build with Maven
|
||||
|
||||
@@ -235,18 +235,16 @@ public final class Operations {
|
||||
Optional.empty(),
|
||||
Optional.empty()));
|
||||
|
||||
final Pair<Integer, MfaFailureExceptionMapper.MfaFailureResponse> initialResponse = apiPost("/v1/registration", initialRequest)
|
||||
// we expect (and need) failure with status 441, which will contain the WebAuthn challenge
|
||||
final MfaFailureExceptionMapper.MfaFailureResponse mfaFailureResponse = apiPost("/v1/registration", initialRequest)
|
||||
// For a numberless account recovery, the username is the ACI
|
||||
.authorized(testUser.aciUuid().toString(), testUser.accountPassword())
|
||||
.execute(MfaFailureExceptionMapper.MfaFailureResponse.class);
|
||||
.executeExpectStatusCode(441, MfaFailureExceptionMapper.MfaFailureResponse.class);
|
||||
|
||||
// we expect (and need) failure with status 441, which will contain the WebAuthn challenge
|
||||
assert initialResponse.getLeft() == 441;
|
||||
|
||||
final MfaFailureExceptionMapper.MfaFailureResponse mfaFailureResponse = initialResponse.getRight();
|
||||
assert mfaFailureResponse.webAuthnParameters().allowedCredentialIds()
|
||||
Validate.isTrue(mfaFailureResponse.webAuthnParameters().allowedCredentialIds()
|
||||
.stream()
|
||||
.anyMatch(allowedId -> Arrays.equals(allowedId, credentialId));
|
||||
.anyMatch(allowedId -> Arrays.equals(allowedId, credentialId)),
|
||||
"Expected MFA failure to contain credentialId");
|
||||
|
||||
final PublicKeyCredential<AuthenticatorAssertionResponse, ?> credential =
|
||||
clientPlatform.get(new PublicKeyCredentialRequestOptions(
|
||||
@@ -438,9 +436,10 @@ public final class Operations {
|
||||
|
||||
private static ManagedChannel buildGrpcChannel() {
|
||||
try {
|
||||
final ByteArrayInputStream rootCert =
|
||||
new ByteArrayInputStream(CONFIG.rootCert().getBytes(StandardCharsets.UTF_8));
|
||||
final ChannelCredentials credentials = TlsChannelCredentials.newBuilder().trustManager(rootCert).build();
|
||||
final String rootCerts = String.join("\n", CONFIG.rootCerts());
|
||||
final ByteArrayInputStream rootCertInputStream =
|
||||
new ByteArrayInputStream(rootCerts.getBytes(StandardCharsets.UTF_8));
|
||||
final ChannelCredentials credentials = TlsChannelCredentials.newBuilder().trustManager(rootCertInputStream).build();
|
||||
return Grpc.newChannelBuilderForAddress(GRPC_DOMAIN, 443, credentials)
|
||||
.userAgent(USER_AGENT)
|
||||
.build();
|
||||
@@ -524,6 +523,15 @@ public final class Operations {
|
||||
response.statusCode(), expectedStatusCode, response.body());
|
||||
}
|
||||
|
||||
public <T> T executeExpectStatusCode(final int expectedStatusCode, final Class<T> expectedType) {
|
||||
final RawResponse response = executeRaw();
|
||||
Validate.isTrue(
|
||||
response.statusCode() == expectedStatusCode,
|
||||
"Unexpected response code: %d (expected %d), body: %s",
|
||||
response.statusCode(), expectedStatusCode, response.body());
|
||||
return requireNonNull(parseBody(response.body(), expectedType));
|
||||
}
|
||||
|
||||
public <T> Pair<Integer, T> execute(final Class<T> expectedType) {
|
||||
final RawResponse response = executeRaw();
|
||||
return Pair.of(response.statusCode(), parseBody(response.body(), expectedType));
|
||||
@@ -564,7 +572,7 @@ public final class Operations {
|
||||
private static FaultTolerantHttpClient buildClient() {
|
||||
try {
|
||||
return FaultTolerantHttpClient.newBuilder("integration-test", Executors.newFixedThreadPool(16))
|
||||
.withTrustedServerCertificates(CONFIG.rootCert())
|
||||
.withTrustedServerCertificates(CONFIG.rootCerts().toArray(String[]::new))
|
||||
.build();
|
||||
} catch (final CertificateException e) {
|
||||
throw new RuntimeException(e);
|
||||
@@ -573,7 +581,7 @@ public final class Operations {
|
||||
|
||||
private static WebSocketClient buildWebSocketClient() {
|
||||
try {
|
||||
final KeyStore trustStore = CertificateUtil.buildKeyStoreForPem(CONFIG.rootCert());
|
||||
final KeyStore trustStore = CertificateUtil.buildKeyStoreForPem(CONFIG.rootCerts().toArray(String[]::new));
|
||||
final SslContextFactory.Client sslContextFactory = new SslContextFactory.Client();
|
||||
sslContextFactory.setTrustStore(trustStore);
|
||||
|
||||
|
||||
@@ -7,11 +7,13 @@ package org.signal.integration.config;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import org.whispersystems.textsecuregcm.configuration.DynamoDbClientFactory;
|
||||
import java.util.List;
|
||||
|
||||
public record Config(@NotBlank String domain,
|
||||
@NotBlank String rootCert,
|
||||
@NotEmpty List<@NotBlank String> rootCerts,
|
||||
@NotNull @Valid DynamoDbClientFactory dynamoDbClient,
|
||||
@NotNull @Valid DynamoDbTables dynamoDbTables,
|
||||
@NotBlank String prescribedRegistrationNumber,
|
||||
|
||||
@@ -45,8 +45,8 @@
|
||||
</modules>
|
||||
|
||||
<properties>
|
||||
<aws.sdk2.version>2.54.7</aws.sdk2.version>
|
||||
<braintree.version>3.53.0</braintree.version>
|
||||
<aws.sdk2.version>2.55.14</aws.sdk2.version>
|
||||
<braintree.version>3.54.0</braintree.version>
|
||||
<commons-csv.version>1.14.1</commons-csv.version>
|
||||
<commons-io.version>2.22.0</commons-io.version>
|
||||
<dropwizard.version>5.0.2</dropwizard.version>
|
||||
@@ -55,42 +55,44 @@
|
||||
<foundationdb.version>7.3.76</foundationdb.version>
|
||||
<foundationdb.api-version>730</foundationdb.api-version>
|
||||
<foundationdb.client-library-sha256>af099848721d08904ff9e5d38fade0de24d92e86451ea491d9ab5ce84adcf62a</foundationdb.client-library-sha256>
|
||||
<google-cloud-libraries.version>26.87.0</google-cloud-libraries.version>
|
||||
<google-cloud-libraries.version>26.90.0</google-cloud-libraries.version>
|
||||
<grpc.version>1.76.3</grpc.version> <!-- should be kept in sync with the value from Google libraries-bom -->
|
||||
<gson.version>2.14.0</gson.version>
|
||||
<guava.version>33.7.1-jre</guava.version>
|
||||
<!-- several libraries (AWS, Google Cloud) use Apache http components transitively, and we need to align them -->
|
||||
<httpcore.version>4.4.16</httpcore.version>
|
||||
<guava.version>33.7.2-jre</guava.version>
|
||||
<!-- several libraries (AWS, Google Cloud) use Apache httpclient transitively, and we need to align them -->
|
||||
<httpclient.version>4.5.14</httpclient.version>
|
||||
<jackson.version>2.22.2</jackson.version>
|
||||
<jackson.version>2.22.3</jackson.version>
|
||||
<java-otp.version>1.0.0</java-otp.version>
|
||||
<jetty.version>12.1.9</jetty.version>
|
||||
<junit-pioneer.version>2.3.0</junit-pioneer.version>
|
||||
<jsr305.version>3.0.2</jsr305.version>
|
||||
<kotlin.version>2.4.10</kotlin.version>
|
||||
<kotlin.version>2.4.21</kotlin.version>
|
||||
<!-- dropwizard references a constant removed in 1.6. See also: dependabot.yml -->
|
||||
<logback.version>1.5.38</logback.version>
|
||||
<logback-access-common.version>2.0.15</logback-access-common.version>
|
||||
<lettuce.version>7.6.0.RELEASE</lettuce.version>
|
||||
<libphonenumber.version>9.0.38</libphonenumber.version>
|
||||
<lettuce.version>7.8.0.RELEASE</lettuce.version>
|
||||
<libphonenumber.version>9.0.41</libphonenumber.version>
|
||||
<logstash.logback.version>9.0</logstash.logback.version>
|
||||
<log4j-bom.version>2.26.1</log4j-bom.version>
|
||||
<luajava.version>4.1.0</luajava.version>
|
||||
<micrometer.version>1.17.1</micrometer.version>
|
||||
<netty.version>4.2.18.Final</netty.version>
|
||||
<netty.version>4.2.19.Final</netty.version>
|
||||
<!-- netty-bom doesn't manage the BoringSSL uber-jar; keep in sync with netty's tcnative.version -->
|
||||
<netty-tcnative.version>2.0.84.Final</netty-tcnative.version>
|
||||
<!-- Instrumentation releases target upstream opentelemetry versions and include that BOM by reference -->
|
||||
<opentelemetry-instrumentation.version>2.32.0</opentelemetry-instrumentation.version>
|
||||
<!-- must be greater than or equal to the value from Google libraries-bom, see https://protobuf.dev/support/cross-version-runtime-guarantee/ -->
|
||||
<!-- the latest 4.x should be fine https://central.sonatype.com/artifact/com.google.protobuf/protobuf-java/versions -->
|
||||
<protobuf.version>4.36.0</protobuf.version>
|
||||
<protobuf.version>4.36.2</protobuf.version>
|
||||
<pushy.version>0.15.6</pushy.version>
|
||||
<reactor-bom.version>2025.0.7</reactor-bom.version> <!-- 3.8.4, see https://github.com/reactor/reactor#bom-versioning-scheme -->
|
||||
<resilience4j.version>2.4.0</resilience4j.version>
|
||||
<semver4j.version>3.1.0</semver4j.version>
|
||||
<simple-grpc.version>0.2.1</simple-grpc.version>
|
||||
<slf4j.version>2.0.18</slf4j.version>
|
||||
<stripe.version>33.4.0</stripe.version>
|
||||
<swagger.version>2.2.54</swagger.version>
|
||||
<slf4j.version>2.0.20</slf4j.version>
|
||||
<stripe.version>33.4.2</stripe.version>
|
||||
<swagger.version>2.2.55</swagger.version>
|
||||
<testcontainers.version>2.0.5</testcontainers.version>
|
||||
<webauthn4j.version>0.31.9.RELEASE</webauthn4j.version>
|
||||
<webauthn4j.version>0.31.11.RELEASE</webauthn4j.version>
|
||||
|
||||
<!-- images to use in tests via testcontainers -->
|
||||
<dynamodb.image>amazon/dynamodb-local:3.3.1@sha256:ff89bd48ff32cd8d9be5fee8873b65b8854dc408f1afe881be6eb00247bc0dab</dynamodb.image>
|
||||
@@ -141,6 +143,11 @@
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.netty</groupId>
|
||||
<artifactId>netty-tcnative-boringssl-static</artifactId>
|
||||
<version>${netty-tcnative.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.protobuf</groupId>
|
||||
<artifactId>protobuf-bom</artifactId>
|
||||
@@ -190,17 +197,10 @@
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.opentelemetry</groupId>
|
||||
<artifactId>opentelemetry-bom</artifactId>
|
||||
<version>1.65.0</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.opentelemetry.instrumentation</groupId>
|
||||
<artifactId>opentelemetry-instrumentation-bom</artifactId>
|
||||
<version>2.31.1</version>
|
||||
<version>${opentelemetry-instrumentation.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
@@ -299,11 +299,6 @@
|
||||
<artifactId>jsr305</artifactId>
|
||||
<version>${jsr305.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.code.gson</groupId>
|
||||
<artifactId>gson</artifactId>
|
||||
<version>${gson.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
@@ -318,7 +313,7 @@
|
||||
<dependency>
|
||||
<groupId>org.signal</groupId>
|
||||
<artifactId>libsignal-server</artifactId>
|
||||
<version>0.101.2</version>
|
||||
<version>0.105.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.signal</groupId>
|
||||
@@ -332,11 +327,6 @@
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.httpcomponents</groupId>
|
||||
<artifactId>httpcore</artifactId>
|
||||
<version>${httpcore.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.httpcomponents</groupId>
|
||||
<artifactId>httpclient</artifactId>
|
||||
@@ -460,12 +450,12 @@
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>3.5.6</version>
|
||||
<version>3.6.0</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-failsafe-plugin</artifactId>
|
||||
<version>3.5.6</version>
|
||||
<version>3.6.0</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
@@ -485,12 +475,12 @@
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
<version>3.6.3</version>
|
||||
<version>3.6.4</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>properties-maven-plugin</artifactId>
|
||||
<version>1.3.0</version>
|
||||
<version>1.3.1</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</pluginManagement>
|
||||
@@ -531,7 +521,7 @@
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.15.0</version>
|
||||
<version>3.16.0</version>
|
||||
<configuration>
|
||||
<release>26</release>
|
||||
</configuration>
|
||||
@@ -594,7 +584,7 @@
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-install-plugin</artifactId>
|
||||
<version>3.1.4</version>
|
||||
<version>3.2.0</version>
|
||||
<configuration>
|
||||
<skip>true</skip>
|
||||
</configuration>
|
||||
@@ -603,7 +593,7 @@
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-deploy-plugin</artifactId>
|
||||
<version>3.1.4</version>
|
||||
<version>3.2.0</version>
|
||||
<configuration>
|
||||
<skip>true</skip>
|
||||
</configuration>
|
||||
|
||||
@@ -145,6 +145,8 @@ dynamoDbTables:
|
||||
tableName: Example_RemoteConfig
|
||||
reportMessage:
|
||||
tableName: Example_ReportMessage
|
||||
sandboxAccounts:
|
||||
tableName: Example_SandboxAccounts
|
||||
scheduledJobs:
|
||||
tableName: Example_ScheduledJobs
|
||||
expiration: P7D
|
||||
@@ -575,6 +577,7 @@ foundationDbMessages:
|
||||
|
||||
registrationWebAuthn:
|
||||
relyingPartyId: example.org
|
||||
origin: https://example.org
|
||||
origins:
|
||||
- https://example.org
|
||||
challengeTtl: PT2M
|
||||
userHandleBlindingSecret: secret://registrationWebAuthn.userHandleBlindingSecret
|
||||
+22
-15
@@ -14,13 +14,13 @@
|
||||
<apollo-api-jvm.version>3.8.6</apollo-api-jvm.version>
|
||||
<commons-compress.version>1.28.0</commons-compress.version>
|
||||
<dynamodb-lock-client.version>1.5.0</dynamodb-lock-client.version>
|
||||
<firebase-admin.version>9.10.0</firebase-admin.version>
|
||||
<libphonenumber-geocoder.version>3.38</libphonenumber-geocoder.version>
|
||||
<firebase-admin.version>9.11.0</firebase-admin.version>
|
||||
<libphonenumber-geocoder.version>3.41</libphonenumber-geocoder.version>
|
||||
<google-androidpublisher.version>v3-rev20250904-2.0.0</google-androidpublisher.version>
|
||||
<java-jwt.version>4.6.0</java-jwt.version>
|
||||
<java-jwt.version>4.6.1</java-jwt.version>
|
||||
<java-uuid-generator.version>5.2.0</java-uuid-generator.version>
|
||||
<!-- *all* opentelemetry-logback-appender versions are "alpha" despite the advanced version number -->
|
||||
<opentelemetry-logback-appender-1.0.version>2.31.1-alpha</opentelemetry-logback-appender-1.0.version>
|
||||
<opentelemetry-logback-appender-1.0.version>${opentelemetry-instrumentation.version}-alpha</opentelemetry-logback-appender-1.0.version>
|
||||
<storekit.version>5.2.0</storekit.version>
|
||||
</properties>
|
||||
|
||||
@@ -193,7 +193,7 @@
|
||||
<groupId>tools.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
<!-- update dependabot.yml when this dependency is removed -->
|
||||
<version>3.2.1</version>
|
||||
<version>3.2.3</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
@@ -240,7 +240,7 @@
|
||||
<artifactId>opentelemetry-logback-appender-1.0</artifactId>
|
||||
<version>${opentelemetry-logback-appender-1.0.version}</version>
|
||||
<exclusions>
|
||||
<!-- incubator packages aren't included in the opentelemetry BOM, and we don't use them -->
|
||||
<!-- conflicts with google-cloud-firestore; incubator packages aren't included in the opentelemetry BOM, and we don't use them -->
|
||||
<exclusion>
|
||||
<groupId>io.opentelemetry.instrumentation</groupId>
|
||||
<artifactId>opentelemetry-instrumentation-api-incubator</artifactId>
|
||||
@@ -307,7 +307,7 @@
|
||||
<version>${firebase-admin.version}</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<!-- conflicts with jackson-dataformat 2.22.1 -->
|
||||
<!-- google-cloud-storage pins 4.2.2, but jackson-dataformat-xml 2.22.x wants 4.3.0 -->
|
||||
<groupId>org.codehaus.woodstox</groupId>
|
||||
<artifactId>stax2-api</artifactId>
|
||||
</exclusion>
|
||||
@@ -315,15 +315,15 @@
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.google.code.findbugs</groupId>
|
||||
<artifactId>jsr305</artifactId>
|
||||
<!-- jackson-dataformat-xml (via firebase-admin), wants >= 4.3.0 -->
|
||||
<groupId>org.codehaus.woodstox</groupId>
|
||||
<artifactId>stax2-api</artifactId>
|
||||
<version>4.3.2</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<!-- manually resolve dependency conflict -->
|
||||
<groupId>org.codehaus.woodstox</groupId>
|
||||
<artifactId>stax2-api</artifactId>
|
||||
<version>4.3.0</version>
|
||||
<groupId>com.google.code.findbugs</groupId>
|
||||
<artifactId>jsr305</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
@@ -513,6 +513,11 @@
|
||||
<artifactId>netty-resolver-dns</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>io.netty</groupId>
|
||||
<artifactId>netty-tcnative-boringssl-static</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>io.netty</groupId>
|
||||
<artifactId>netty-transport</artifactId>
|
||||
@@ -639,6 +644,7 @@
|
||||
<version>${apollo-api-jvm.version}</version>
|
||||
|
||||
<exclusions>
|
||||
<!-- conflicts with kotlin-stdlib -->
|
||||
<exclusion>
|
||||
<groupId>org.jetbrains</groupId>
|
||||
<artifactId>annotations</artifactId>
|
||||
@@ -656,7 +662,7 @@
|
||||
<groupId>com.squareup.okio</groupId>
|
||||
<artifactId>okio-jvm</artifactId>
|
||||
<!-- update dependabot.yml when this dependency is removed -->
|
||||
<version>3.17.0</version>
|
||||
<version>3.18.1</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
@@ -795,6 +801,7 @@
|
||||
<jvmFlag>-Djdk.nio.maxCachedBufferSize=262144</jvmFlag>
|
||||
<jvmFlag>-Dlog4j2.formatMsgNoLookups=true</jvmFlag>
|
||||
<jvmFlag>-Djdk.tls.server.newSessionTicketCount=0</jvmFlag>
|
||||
<jvmFlag>-Djdk.tls.server.enableSessionTicketExtension=false</jvmFlag>
|
||||
<jvmFlag>-XX:MaxRAMPercentage=75</jvmFlag>
|
||||
<jvmFlag>-XX:+HeapDumpOnOutOfMemoryError</jvmFlag>
|
||||
<jvmFlag>-XX:HeapDumpPath=/tmp/heapdump.bin</jvmFlag>
|
||||
@@ -871,7 +878,7 @@
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>templating-maven-plugin</artifactId>
|
||||
<version>3.1.0</version>
|
||||
<version>3.1.1</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>filter-src</id>
|
||||
|
||||
@@ -219,7 +219,7 @@ import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper
|
||||
import org.whispersystems.textsecuregcm.mappers.RegistrationLockFailureExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.RegistrationServiceSenderExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.ServerRejectedExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.SubscriptionExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.PurchaseExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.metrics.BackupMetrics;
|
||||
import org.whispersystems.textsecuregcm.metrics.CallQualitySurveyManager;
|
||||
import org.whispersystems.textsecuregcm.metrics.MessageMetrics;
|
||||
@@ -287,6 +287,7 @@ import org.whispersystems.textsecuregcm.storage.RepeatedUseECSignedPreKeyStore;
|
||||
import org.whispersystems.textsecuregcm.storage.RepeatedUseKEMSignedPreKeyStore;
|
||||
import org.whispersystems.textsecuregcm.storage.ReportMessageDynamoDb;
|
||||
import org.whispersystems.textsecuregcm.storage.ReportMessageManager;
|
||||
import org.whispersystems.textsecuregcm.storage.SandboxAccounts;
|
||||
import org.whispersystems.textsecuregcm.storage.SingleUseECPreKeyStore;
|
||||
import org.whispersystems.textsecuregcm.storage.SubscriptionManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Subscriptions;
|
||||
@@ -300,15 +301,15 @@ import org.whispersystems.textsecuregcm.storage.foundationdb.FaultTolerantDataba
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStore;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDBWarmup;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.VersionstampUUIDCipher;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.AppleAppStoreClient;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.AppleAppStoreManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.BankMandateTranslator;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.BraintreeManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.GooglePlayBillingManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.LoginPurchaseManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PayPalDonationsTranslator;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.StripeManager;
|
||||
import org.whispersystems.textsecuregcm.purchases.AppleAppStoreClient;
|
||||
import org.whispersystems.textsecuregcm.purchases.AppleAppStoreManager;
|
||||
import org.whispersystems.textsecuregcm.purchases.BankMandateTranslator;
|
||||
import org.whispersystems.textsecuregcm.purchases.BraintreeManager;
|
||||
import org.whispersystems.textsecuregcm.purchases.GooglePlayBillingManager;
|
||||
import org.whispersystems.textsecuregcm.purchases.LoginPurchaseManager;
|
||||
import org.whispersystems.textsecuregcm.purchases.PayPalDonationsTranslator;
|
||||
import org.whispersystems.textsecuregcm.purchases.PaymentProvider;
|
||||
import org.whispersystems.textsecuregcm.purchases.StripeManager;
|
||||
import org.whispersystems.textsecuregcm.telephony.CarrierDataProvider;
|
||||
import org.whispersystems.textsecuregcm.telephony.hlrlookup.HlrLookupCarrierDataProvider;
|
||||
import org.whispersystems.textsecuregcm.util.BufferingInterceptor;
|
||||
@@ -342,8 +343,10 @@ import org.whispersystems.textsecuregcm.workers.RegenerateSecondaryDynamoDbTable
|
||||
import org.whispersystems.textsecuregcm.workers.RemoveExpiredAccountsCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.RemoveExpiredBackupsCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.RemoveExpiredLinkedDevicesCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.RemoveExpiredSandboxAccountsCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.RemoveExpiredUsernameHoldsCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.RemoveOrphanedPreKeyPagesCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.SandboxAccountPoolCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.ScheduledApnPushNotificationSenderServiceCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.ServerVersionCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.SetRequestLoggingEnabledTask;
|
||||
@@ -397,6 +400,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
bootstrap.addCommand(new ScheduledApnPushNotificationSenderServiceCommand());
|
||||
bootstrap.addCommand(new MessagePersisterServiceCommand());
|
||||
bootstrap.addCommand(new RemoveExpiredAccountsCommand(Clock.systemUTC()));
|
||||
bootstrap.addCommand(new RemoveExpiredSandboxAccountsCommand(Clock.systemUTC()));
|
||||
bootstrap.addCommand(new SandboxAccountPoolCommand());
|
||||
bootstrap.addCommand(new RemoveExpiredUsernameHoldsCommand(Clock.systemUTC()));
|
||||
bootstrap.addCommand(new RemoveExpiredBackupsCommand(Clock.systemUTC()));
|
||||
bootstrap.addCommand(new RemoveOrphanedPreKeyPagesCommand(Clock.systemUTC()));
|
||||
@@ -666,7 +671,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
final ScheduledExecutorService retryExecutor = ScheduledExecutorServiceBuilder.of(environment, "retry")
|
||||
.threads(16).build();
|
||||
final ScheduledExecutorService registrationIdentityTokenRefreshExecutor =
|
||||
ScheduledExecutorServiceBuilder.of(environment, "registrationIdentityTokenRefresh").threads(1).build();
|
||||
ScheduledExecutorServiceBuilder.of(environment, "registrationIdentityTokenRefresh").threads(1).build();
|
||||
final ScheduledExecutorService presenceRenewalExecutor =
|
||||
ScheduledExecutorServiceBuilder.of(environment, "presenceRenewal").threads(4).build();
|
||||
|
||||
@@ -726,11 +731,11 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
|
||||
final ManagedEventLoopGroup<NioEventLoopGroup> dnsResolutionEventLoopGroup = new ManagedEventLoopGroup<>(new NioEventLoopGroup());
|
||||
final DnsNameResolver cloudflareDnsResolver = new DnsNameResolverBuilder(dnsResolutionEventLoopGroup.getEventLoopGroup().next())
|
||||
.resolvedAddressTypes(ResolvedAddressTypes.IPV6_PREFERRED)
|
||||
.completeOncePreferredResolved(false)
|
||||
.channelType(NioDatagramChannel.class)
|
||||
.socketChannelType(NioSocketChannel.class)
|
||||
.build();
|
||||
.resolvedAddressTypes(ResolvedAddressTypes.IPV6_PREFERRED)
|
||||
.completeOncePreferredResolved(false)
|
||||
.channelType(NioDatagramChannel.class)
|
||||
.socketChannelType(NioSocketChannel.class)
|
||||
.build();
|
||||
|
||||
ExternalServiceCredentialsGenerator directoryV2CredentialsGenerator = DirectoryV2Controller.credentialsGenerator(
|
||||
config.getDirectoryV2Configuration().getDirectoryV2ClientConfiguration());
|
||||
@@ -819,14 +824,16 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
final TotpManager totpManager = new TotpManager(rateLimitersCluster, config.getRegistrationTotpConfiguration().maxValidationDelay());
|
||||
final WebAuthnCeremonyManager webAuthnCeremonyManager = new WebAuthnCeremonyManager(
|
||||
config.getRegistrationWebAuthnConfiguration().relyingPartyId(),
|
||||
config.getRegistrationWebAuthnConfiguration().origin(),
|
||||
config.getRegistrationWebAuthnConfiguration().origins(),
|
||||
config.getRegistrationWebAuthnConfiguration().challengeTtl(),
|
||||
config.getRegistrationWebAuthnConfiguration().userHandleBlindingSecret().value(),
|
||||
rateLimitersCluster);
|
||||
final SandboxAccounts sandboxAccounts = new SandboxAccounts(
|
||||
config.getDynamoDbTables().getSandboxAccounts().getTableName(), dynamoDbClient);
|
||||
final AccountsManager accountsManager = new AccountsManager(accounts, phoneNumberIdentifiers, cacheCluster,
|
||||
pubsubClient, accountLockManager, keysManager, messagesManager, profilesManager,
|
||||
changeNumberWaitingPeriodManager, secureStorageClient, secureValueRecovery2Client, disconnectionRequestManager,
|
||||
phoneNumberRecoveryPasswordsManager, messagePollExecutor,
|
||||
phoneNumberRecoveryPasswordsManager, sandboxAccounts, messagePollExecutor,
|
||||
retryExecutor, clock, config.getLinkDeviceSecretConfiguration().secret().value(),
|
||||
webAuthnCeremonyManager, totpManager);
|
||||
RemoteConfigsManager remoteConfigsManager = new RemoteConfigsManager(remoteConfigs, config.getRemoteConfigConfiguration().globalConfig());
|
||||
@@ -1173,7 +1180,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
new ProfileAnonymousGrpcService(accountsManager, profilesManager, profileBadgeConverter, profileCdnPolicyGenerator, chatGenericZkSecretParams, groupZkSecretParams, rateLimiters, clock),
|
||||
new MessagesAnonymousGrpcService(accountsManager, rateLimiters, messageSender, groupSendTokenUtil, messageByteLimitCardinalityEstimator, spamChecker, Clock.systemUTC()),
|
||||
new BackupsAnonymousGrpcService(backupManager, backupMetrics, config.getAttachments().maxAttachmentUploadSizeInBytes(), config.getAttachments().maxMessageBackupUploadSizeInBytes()),
|
||||
new CredentialsAnonymousGrpcService(accountsManager, ExternalServiceDefinitions.SVR.generatorFactory().apply(config, Clock.systemUTC())),
|
||||
new CredentialsAnonymousGrpcService(accountsManager, ExternalServiceDefinitions.SVR.generatorFactory().apply(config, Clock.systemUTC()), rateLimiters),
|
||||
new SubscriptionsGrpcService(clock, config.getSubscription(), subscriptionManager, donationPermitsManager,
|
||||
stripeManager, braintreeManager, googlePlayBillingManager, appleAppStoreManager, bankMandateTranslator),
|
||||
new OneTimeDonationsGrpcService(config.getOneTimeDonations(), stripeManager, braintreeManager,
|
||||
@@ -1218,7 +1225,9 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
grpcLocalAddress);
|
||||
@Nullable final Mapping<String, SslContext> sniMapping = config.getGrpc().h2c()
|
||||
? null
|
||||
: SniMapper.buildSniMapping(config.getTlsKeyStoreConfiguration().path(), config.getTlsKeyStoreConfiguration().password().value());
|
||||
: SniMapper.buildSniMapping(config.getTlsKeyStoreConfiguration().path(),
|
||||
config.getTlsKeyStoreConfiguration().password().value(),
|
||||
config.getGrpc().sslProvider());
|
||||
final OmnibusH2Server omnibusH2Server = new OmnibusH2Server(
|
||||
sniMapping,
|
||||
omnibusNioEventLoopGroup.getEventLoopGroup(),
|
||||
@@ -1401,7 +1410,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
new NonNormalizedPhoneNumberExceptionMapper(),
|
||||
new ObsoletePhoneNumberFormatExceptionMapper(),
|
||||
new RegistrationServiceSenderExceptionMapper(),
|
||||
new SubscriptionExceptionMapper(),
|
||||
new PurchaseExceptionMapper(),
|
||||
new BackupExceptionMapper(),
|
||||
new JsonMappingExceptionMapper(),
|
||||
new RegistrationLockFailureExceptionMapper(),
|
||||
|
||||
+4
-1
@@ -10,6 +10,7 @@ import org.whispersystems.textsecuregcm.auth.JwtGenerator;
|
||||
import org.whispersystems.textsecuregcm.util.HeaderUtils;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.util.Base64;
|
||||
import java.util.Map;
|
||||
|
||||
@@ -19,15 +20,17 @@ public class TusAttachmentGenerator implements AttachmentGenerator {
|
||||
|
||||
private final JwtGenerator jwtGenerator;
|
||||
private final String tusUri;
|
||||
private final Duration tokenExpiration;
|
||||
|
||||
public TusAttachmentGenerator(final TusConfiguration cfg) {
|
||||
this.tusUri = cfg.uploadUri();
|
||||
this.tokenExpiration = cfg.tokenExpiration();
|
||||
this.jwtGenerator = new JwtGenerator(cfg.userAuthenticationTokenSharedSecret().value(), Clock.systemUTC());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Descriptor generateAttachment(final String key, final long uploadLength) {
|
||||
final String token = jwtGenerator.generateJwt(ATTACHMENTS, key,
|
||||
final String token = jwtGenerator.generateJwt(ATTACHMENTS, key, tokenExpiration,
|
||||
builder -> builder.withClaim(JwtGenerator.MAX_LENGTH_CLAIM_KEY, uploadLength));
|
||||
final String b64Key = Base64.getEncoder().encodeToString(key.getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
|
||||
+19
-3
@@ -5,11 +5,27 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.attachments;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import jakarta.validation.constraints.Positive;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import java.time.Duration;
|
||||
import org.hibernate.validator.constraints.time.DurationMin;
|
||||
import org.whispersystems.textsecuregcm.configuration.secrets.SecretBytes;
|
||||
import org.whispersystems.textsecuregcm.util.ExactlySize;
|
||||
|
||||
public record TusConfiguration(
|
||||
@ExactlySize(32) SecretBytes userAuthenticationTokenSharedSecret,
|
||||
@NotEmpty String uploadUri){}
|
||||
@ExactlySize(32) SecretBytes userAuthenticationTokenSharedSecret,
|
||||
@NotEmpty String uploadUri,
|
||||
// The TUS server enforces its own `MAX_TOKEN_AGE`, so this must be greater than or equal to it.
|
||||
// https://github.com/signalapp/tus-server/tree/main/src/index.ts
|
||||
@NotNull @DurationMin(days = 7) Duration tokenExpiration){
|
||||
|
||||
@VisibleForTesting
|
||||
public static final Duration DEFAULT_TOKEN_EXPIRATION = Duration.ofDays(7);
|
||||
|
||||
public TusConfiguration {
|
||||
if (tokenExpiration == null) {
|
||||
tokenExpiration = DEFAULT_TOKEN_EXPIRATION;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import com.auth0.jwt.JWT;
|
||||
import com.auth0.jwt.JWTCreator;
|
||||
import com.auth0.jwt.algorithms.Algorithm;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
@@ -27,12 +28,13 @@ public class JwtGenerator {
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
public String generateJwt(final String audience, final String subject, Consumer<JWTCreator.Builder> claimCustomizer) {
|
||||
public String generateJwt(final String audience, final String subject, final Duration expiration, Consumer<JWTCreator.Builder> claimCustomizer) {
|
||||
final Instant now = clock.instant();
|
||||
JWTCreator.Builder builder = JWT.create()
|
||||
.withAudience(audience)
|
||||
.withSubject(subject)
|
||||
.withIssuedAt(now);
|
||||
.withIssuedAt(now)
|
||||
.withExpiresAt(now.plus(expiration));
|
||||
claimCustomizer.accept(builder);
|
||||
return builder.sign(algorithm);
|
||||
}
|
||||
|
||||
+8
-5
@@ -26,7 +26,10 @@ import java.security.SecureRandom;
|
||||
import java.time.Duration;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import org.whispersystems.textsecuregcm.util.HmacUtils;
|
||||
@@ -39,7 +42,7 @@ public class WebAuthnCeremonyManager {
|
||||
/// [relying party ID - WebAuthn TR](https://www.w3.org/TR/webauthn/#relying-party-identifier)
|
||||
private final String rpId;
|
||||
/// [origin - WebAuthn TR](https://www.w3.org/TR/webauthn/#dom-collectedclientdata-origin)
|
||||
private final Origin origin;
|
||||
private final Set<Origin> origins;
|
||||
private final byte[] blindingSecret;
|
||||
private final Duration challengeTtl;
|
||||
|
||||
@@ -56,10 +59,10 @@ public class WebAuthnCeremonyManager {
|
||||
|
||||
private static final SecureRandom SECURE_RANDOM = new SecureRandom();
|
||||
|
||||
public WebAuthnCeremonyManager(final String rpId, final String origin, final Duration challengeTtl, final byte[] blindingSecret,
|
||||
public WebAuthnCeremonyManager(final String rpId, final List<String> origins, final Duration challengeTtl, final byte[] blindingSecret,
|
||||
final FaultTolerantRedisClusterClient challengeStorageCluster) {
|
||||
this.rpId = rpId;
|
||||
this.origin = new Origin(origin);
|
||||
this.origins = origins.stream().map(Origin::new).collect(Collectors.toSet());
|
||||
this.challengeTtl = challengeTtl;
|
||||
this.blindingSecret = blindingSecret;
|
||||
this.challengeStorageCluster = challengeStorageCluster;
|
||||
@@ -128,7 +131,7 @@ public class WebAuthnCeremonyManager {
|
||||
// we aren't verifying any signatures for registration, so we don't need to bother saving a
|
||||
// challenge; accept whatever is supplied
|
||||
.challenge(registrationData.getCollectedClientData().getChallenge())
|
||||
.origin(origin)
|
||||
.origins(origins)
|
||||
.rpId(rpId)
|
||||
.build();
|
||||
|
||||
@@ -202,7 +205,7 @@ public class WebAuthnCeremonyManager {
|
||||
final byte[] credentialId = matchingCredential.getAttestedCredentialData().getCredentialId();
|
||||
final AuthenticationParameters authenticationParameters = new AuthenticationParameters(
|
||||
ServerProperty.builder()
|
||||
.origin(origin)
|
||||
.origins(origins)
|
||||
.rpId(rpId)
|
||||
.challenge(() -> challenge)
|
||||
.build(),
|
||||
|
||||
+9
-7
@@ -5,25 +5,27 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.backup;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.util.Base64;
|
||||
import java.util.Map;
|
||||
import org.apache.http.HttpHeaders;
|
||||
import org.whispersystems.textsecuregcm.attachments.TusConfiguration;
|
||||
import org.whispersystems.textsecuregcm.auth.JwtGenerator;
|
||||
import org.whispersystems.textsecuregcm.util.HeaderUtils;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Clock;
|
||||
import java.util.Base64;
|
||||
import java.util.Map;
|
||||
|
||||
public class Cdn3BackupCredentialGenerator {
|
||||
public static final String CDN_PATH = "backups";
|
||||
public static final int BACKUP_CDN = 3;
|
||||
|
||||
private final String tusUri;
|
||||
private final Duration tokenExpiration;
|
||||
private final JwtGenerator jwtGenerator;
|
||||
|
||||
public Cdn3BackupCredentialGenerator(final TusConfiguration cfg) {
|
||||
this.tusUri = cfg.uploadUri();
|
||||
this.tokenExpiration = cfg.tokenExpiration();
|
||||
this.jwtGenerator = new JwtGenerator(cfg.userAuthenticationTokenSharedSecret().value(), Clock.systemUTC());
|
||||
}
|
||||
|
||||
@@ -32,7 +34,7 @@ public class Cdn3BackupCredentialGenerator {
|
||||
throw new IllegalArgumentException("Upload descriptors must have non-empty keys");
|
||||
}
|
||||
|
||||
final String token = jwtGenerator.generateJwt(CDN_PATH, key, builder -> builder
|
||||
final String token = jwtGenerator.generateJwt(CDN_PATH, key, tokenExpiration, builder -> builder
|
||||
.withClaim(JwtGenerator.MAX_LENGTH_CLAIM_KEY, uploadSize)
|
||||
.withClaim(JwtGenerator.SCOPE_CLAIM_KEY, "write"));
|
||||
|
||||
@@ -53,7 +55,7 @@ public class Cdn3BackupCredentialGenerator {
|
||||
throw new IllegalArgumentException("Backup subdir name must be non-empty");
|
||||
}
|
||||
|
||||
final String token = jwtGenerator.generateJwt(CDN_PATH, hashedBackupId, builder -> builder
|
||||
final String token = jwtGenerator.generateJwt(CDN_PATH, hashedBackupId, tokenExpiration, builder -> builder
|
||||
.withClaim(JwtGenerator.SCOPE_CLAIM_KEY, "read"));
|
||||
return Map.of(HttpHeaders.AUTHORIZATION, HeaderUtils.bearerAuthHeader(token));
|
||||
}
|
||||
|
||||
@@ -98,21 +98,21 @@ public class CaptchaChecker {
|
||||
});
|
||||
|
||||
if (!parsedAction.equals(expectedAction)) {
|
||||
Metrics.counter(INVALID_ACTION_COUNTER_NAME, "action", action).increment();
|
||||
Metrics.counter(INVALID_ACTION_COUNTER_NAME, "action", parsedAction.getActionName()).increment();
|
||||
throw new InvalidCaptchaArgumentException("invalid captcha action");
|
||||
}
|
||||
|
||||
final Set<String> allowedSiteKeys = client.validSiteKeys(parsedAction);
|
||||
if (!allowedSiteKeys.contains(siteKey)) {
|
||||
logger.debug("invalid site-key {}, action={}", siteKey, action);
|
||||
Metrics.counter(INVALID_SITEKEY_COUNTER_NAME, "action", action).increment();
|
||||
logger.debug("invalid site-key {}, action={}", siteKey, parsedAction.getActionName());
|
||||
Metrics.counter(INVALID_SITEKEY_COUNTER_NAME, "action", parsedAction.getActionName()).increment();
|
||||
throw new InvalidCaptchaArgumentException("invalid captcha site-key");
|
||||
}
|
||||
|
||||
try {
|
||||
final AssessmentResult result = client.verify(maybeAci, siteKey, parsedAction, token, ip, userAgent);
|
||||
Metrics.counter(ASSESSMENTS_COUNTER_NAME,
|
||||
"action", action,
|
||||
"action", parsedAction.getActionName(),
|
||||
"score", result.getScoreString(),
|
||||
"provider", provider)
|
||||
.increment();
|
||||
|
||||
+1
-2
@@ -6,13 +6,12 @@
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import com.apple.itunes.storekit.model.Environment;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import org.whispersystems.textsecuregcm.configuration.secrets.SecretString;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel;
|
||||
import org.whispersystems.textsecuregcm.purchases.ReceiptLevel;
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
/**
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ import com.fasterxml.jackson.annotation.Nulls;
|
||||
import io.dropwizard.validation.ValidationMethod;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel;
|
||||
import org.whispersystems.textsecuregcm.purchases.ReceiptLevel;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ import java.util.Map;
|
||||
import java.util.Set;
|
||||
import javax.annotation.Nullable;
|
||||
import org.whispersystems.textsecuregcm.configuration.secrets.SecretString;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentMethod;
|
||||
import org.whispersystems.textsecuregcm.purchases.PaymentMethod;
|
||||
|
||||
/**
|
||||
* @param merchantId the Braintree merchant ID
|
||||
|
||||
+9
@@ -73,6 +73,7 @@ public class DynamoDbTables {
|
||||
private final TableWithExpiration registrationRecovery;
|
||||
private final Table remoteConfig;
|
||||
private final Table reportMessage;
|
||||
private final Table sandboxAccounts;
|
||||
private final TableWithExpiration scheduledJobs;
|
||||
private final Table subscriptions;
|
||||
private final Table verificationSessions;
|
||||
@@ -104,6 +105,7 @@ public class DynamoDbTables {
|
||||
@JsonProperty("registrationRecovery") final TableWithExpiration registrationRecovery,
|
||||
@JsonProperty("remoteConfig") final Table remoteConfig,
|
||||
@JsonProperty("reportMessage") final Table reportMessage,
|
||||
@JsonProperty("sandboxAccounts") final Table sandboxAccounts,
|
||||
@JsonProperty("scheduledJobs") final TableWithExpiration scheduledJobs,
|
||||
@JsonProperty("subscriptions") final Table subscriptions,
|
||||
@JsonProperty("verificationSessions") final Table verificationSessions) {
|
||||
@@ -134,6 +136,7 @@ public class DynamoDbTables {
|
||||
this.registrationRecovery = registrationRecovery;
|
||||
this.remoteConfig = remoteConfig;
|
||||
this.reportMessage = reportMessage;
|
||||
this.sandboxAccounts = sandboxAccounts;
|
||||
this.scheduledJobs = scheduledJobs;
|
||||
this.subscriptions = subscriptions;
|
||||
this.verificationSessions = verificationSessions;
|
||||
@@ -295,6 +298,12 @@ public class DynamoDbTables {
|
||||
return reportMessage;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
public Table getSandboxAccounts() {
|
||||
return sandboxAccounts;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
public TableWithExpiration getScheduledJobs() {
|
||||
|
||||
+1
-2
@@ -8,8 +8,7 @@ package org.whispersystems.textsecuregcm.configuration;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import java.util.Map;
|
||||
import org.whispersystems.textsecuregcm.configuration.secrets.SecretString;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel;
|
||||
import org.whispersystems.textsecuregcm.purchases.ReceiptLevel;
|
||||
|
||||
/**
|
||||
* @param credentialsJson Service account credentials for Play Billing API
|
||||
|
||||
+7
-1
@@ -4,6 +4,7 @@
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import io.netty.handler.ssl.SslProvider;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import java.time.Duration;
|
||||
|
||||
@@ -15,13 +16,15 @@ import java.time.Duration;
|
||||
/// @param websocketPort The port of a listening websocket server for handling legacy requests
|
||||
/// @param idleTimeout The duration after which an idle connection may be disconnected
|
||||
/// @param h2c If true, listen for plaintext h2c with prior-knowledge
|
||||
/// @param sslProvider The TLS implementation used to terminate TLS. Defaults to `OPENSSL`.
|
||||
public record GrpcConfiguration(
|
||||
@NotNull String bindAddress,
|
||||
@NotNull Integer port,
|
||||
@NotNull String websocketAddress,
|
||||
@NotNull Integer websocketPort,
|
||||
@NotNull Duration idleTimeout,
|
||||
boolean h2c) {
|
||||
boolean h2c,
|
||||
@NotNull SslProvider sslProvider) {
|
||||
|
||||
public GrpcConfiguration {
|
||||
if (bindAddress == null || bindAddress.isEmpty()) {
|
||||
@@ -33,5 +36,8 @@ public record GrpcConfiguration(
|
||||
if (idleTimeout == null) {
|
||||
idleTimeout = Duration.ofMinutes(5);
|
||||
}
|
||||
if (sslProvider == null) {
|
||||
sslProvider = SslProvider.OPENSSL;
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -9,7 +9,7 @@ import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import java.util.EnumMap;
|
||||
import java.util.Map;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
|
||||
import org.whispersystems.textsecuregcm.purchases.PaymentProvider;
|
||||
import org.whispersystems.textsecuregcm.util.EnumMapUtil;
|
||||
|
||||
public class IssuedReceiptsTableConfiguration extends DynamoDbTables.Table {
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ import java.util.Map;
|
||||
import java.util.Set;
|
||||
import org.whispersystems.textsecuregcm.configuration.secrets.SecretBytes;
|
||||
import org.whispersystems.textsecuregcm.configuration.secrets.SecretString;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentMethod;
|
||||
import org.whispersystems.textsecuregcm.purchases.PaymentMethod;
|
||||
|
||||
public record StripeConfiguration(@NotNull SecretString apiKey,
|
||||
@NotNull SecretBytes idempotencyKeyGenerator,
|
||||
|
||||
+1
-1
@@ -12,7 +12,7 @@ import jakarta.validation.constraints.NotEmpty;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Map;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
|
||||
import org.whispersystems.textsecuregcm.purchases.PaymentProvider;
|
||||
|
||||
public record SubscriptionPriceConfiguration(@Valid @NotEmpty Map<PaymentProvider, @NotBlank String> processorIds,
|
||||
@NotNull @DecimalMin("0.01") BigDecimal amount) {
|
||||
|
||||
+3
-1
@@ -6,14 +6,16 @@
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import org.whispersystems.textsecuregcm.configuration.secrets.SecretBytes;
|
||||
import org.whispersystems.textsecuregcm.util.ExactlySize;
|
||||
|
||||
public record WebAuthnConfiguration(
|
||||
@NotBlank String relyingPartyId,
|
||||
@NotBlank String origin,
|
||||
@NotEmpty List<@NotBlank String> origins,
|
||||
@NotNull Duration challengeTtl,
|
||||
@NotNull @ExactlySize(32) SecretBytes userHandleBlindingSecret) {
|
||||
}
|
||||
+3
-2
@@ -25,6 +25,7 @@ import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.Max;
|
||||
import jakarta.validation.constraints.Min;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Positive;
|
||||
import jakarta.validation.constraints.PositiveOrZero;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import jakarta.ws.rs.BadRequestException;
|
||||
@@ -595,7 +596,7 @@ public class ArchiveController {
|
||||
@HeaderParam(X_SIGNAL_ZK_AUTH_SIGNATURE) final BackupAuthCredentialPresentationSignature signature,
|
||||
|
||||
@Parameter(description = "The size of the message backup to upload in bytes")
|
||||
@QueryParam("uploadLength") final Optional<Long> uploadLength)
|
||||
@QueryParam("uploadLength") final Optional<@Positive Long> uploadLength)
|
||||
throws BackupFailedZkAuthenticationException, BackupWrongCredentialTypeException, BackupPermissionException {
|
||||
if (account.isPresent()) {
|
||||
throw new BadRequestException("must not use authenticated connection for anonymous operations");
|
||||
@@ -651,7 +652,7 @@ public class ArchiveController {
|
||||
@HeaderParam(X_SIGNAL_ZK_AUTH_SIGNATURE) final BackupAuthCredentialPresentationSignature signature,
|
||||
|
||||
@Parameter(description = "The size of the temporary attachment to upload in bytes")
|
||||
@QueryParam("uploadLength") final Optional<Long> uploadLength)
|
||||
@QueryParam("uploadLength") final Optional<@Positive Long> uploadLength)
|
||||
throws RateLimitExceededException, BackupFailedZkAuthenticationException, BackupWrongCredentialTypeException, BackupPermissionException {
|
||||
if (account.isPresent()) {
|
||||
throw new BadRequestException("must not use authenticated connection for anonymous operations");
|
||||
|
||||
+2
-11
@@ -72,6 +72,7 @@ import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceIdentityInfo;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceSpec;
|
||||
import org.whispersystems.textsecuregcm.storage.LinkDeviceTokenAlreadyUsedException;
|
||||
import org.whispersystems.textsecuregcm.storage.PersistentTimer;
|
||||
@@ -88,8 +89,6 @@ import org.whispersystems.textsecuregcm.util.ua.UserAgentUtil;
|
||||
@Tag(name = "Devices")
|
||||
public class DeviceController {
|
||||
|
||||
static final int MAX_DEVICES = 6;
|
||||
|
||||
private final AccountsManager accounts;
|
||||
private final RateLimiters rateLimiters;
|
||||
private final PersistentTimer persistentTimer;
|
||||
@@ -198,15 +197,11 @@ public class DeviceController {
|
||||
|
||||
rateLimiters.getAllocateDeviceLimiter().validate(account.getAccountIdentifier());
|
||||
|
||||
if (account.getDevices().size() >= MAX_DEVICES) {
|
||||
throw new DeviceLimitExceededException(account.getDevices().size(), MAX_DEVICES);
|
||||
}
|
||||
|
||||
if (auth.deviceId() != Device.PRIMARY_ID) {
|
||||
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
|
||||
}
|
||||
|
||||
final String token = accounts.generateLinkDeviceToken(account.getAccountIdentifier());
|
||||
final String token = accounts.generateLinkDeviceToken(account);
|
||||
|
||||
return new LinkDeviceToken(token, AccountsManager.getLinkDeviceTokenIdentifier(token));
|
||||
}
|
||||
@@ -271,10 +266,6 @@ public class DeviceController {
|
||||
throw new WebApplicationException(Response.status(422).build());
|
||||
}
|
||||
|
||||
if (account.getDevices().size() >= MAX_DEVICES) {
|
||||
throw new DeviceLimitExceededException(account.getDevices().size(), MAX_DEVICES);
|
||||
}
|
||||
|
||||
final Set<DeviceCapability> capabilities = deviceAttributes.capabilities();
|
||||
|
||||
if (capabilities == null) {
|
||||
|
||||
+2
-2
@@ -40,8 +40,8 @@ import org.whispersystems.textsecuregcm.storage.AccountBadge;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.DonationPermitsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.RedeemedReceiptsManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.ReceiptCredentialPresentationFactory;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel;
|
||||
import org.whispersystems.textsecuregcm.purchases.ReceiptCredentialPresentationFactory;
|
||||
import org.whispersystems.textsecuregcm.purchases.ReceiptLevel;
|
||||
|
||||
@Path("/v1/donation")
|
||||
@Tag(name = "Donations")
|
||||
|
||||
+11
-11
@@ -29,15 +29,15 @@ import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialRequest;
|
||||
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialResponse;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.mappers.SubscriptionExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.PurchaseExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.LoginPurchaseManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidArgumentsException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionNotFoundException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentRequiredException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptAlreadyRedeemedException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptRequestedForOpenPaymentException;
|
||||
import org.whispersystems.textsecuregcm.purchases.LoginPurchaseManager;
|
||||
import org.whispersystems.textsecuregcm.purchases.PaymentProvider;
|
||||
import org.whispersystems.textsecuregcm.purchases.PurchaseInvalidArgumentsException;
|
||||
import org.whispersystems.textsecuregcm.purchases.PurchaseNotFoundException;
|
||||
import org.whispersystems.textsecuregcm.purchases.PurchasePaymentRequiredException;
|
||||
import org.whispersystems.textsecuregcm.purchases.PurchaseReceiptAlreadyRedeemedException;
|
||||
import org.whispersystems.textsecuregcm.purchases.PurchaseReceiptRequestedForOpenPaymentException;
|
||||
|
||||
@Path("/v1/login-purchase")
|
||||
@io.swagger.v3.oas.annotations.tags.Tag(name = "LoginPurchase")
|
||||
@@ -91,7 +91,7 @@ public class LoginPurchaseController {
|
||||
@ApiResponse(responseCode = "402", description = "The purchase did not complete successfully. The body may include ChargeFailure details.",
|
||||
content = @Content(schema = @Schema(
|
||||
nullable = true,
|
||||
implementation = SubscriptionExceptionMapper.ChargeFailureResponse.class)))
|
||||
implementation = PurchaseExceptionMapper.ChargeFailureResponse.class)))
|
||||
@ApiResponse(responseCode = "403", description = "The request was made on an authenticated channel")
|
||||
@ApiResponse(responseCode = "404", description = "The payment provider has no purchase with the provided purchaseIdentifier")
|
||||
@ApiResponse(responseCode = "409", description = "The purchase was already redeemed for a receipt credential, but with a different receipt credential request")
|
||||
@@ -102,7 +102,7 @@ public class LoginPurchaseController {
|
||||
public Response createLoginReceiptCredential(
|
||||
@Auth final Optional<AuthenticatedDevice> authenticatedAccount,
|
||||
@NotNull @Valid final CreateLoginReceiptCredentialRequest request)
|
||||
throws IOException, SubscriptionPaymentRequiredException, SubscriptionInvalidArgumentsException, SubscriptionNotFoundException, RateLimitExceededException, SubscriptionReceiptAlreadyRedeemedException {
|
||||
throws IOException, PurchasePaymentRequiredException, PurchaseInvalidArgumentsException, PurchaseNotFoundException, RateLimitExceededException, PurchaseReceiptAlreadyRedeemedException {
|
||||
|
||||
if (!dynamicConfigurationManager.getConfiguration().getLoginPurchaseConfiguration().enabled()) {
|
||||
throw new BadRequestException("login purchases are not enabled");
|
||||
@@ -125,7 +125,7 @@ public class LoginPurchaseController {
|
||||
return Response.ok(
|
||||
new CreateLoginReceiptCredentialResponse(receiptCredentialResponse.serialize()))
|
||||
.build();
|
||||
} catch (SubscriptionReceiptRequestedForOpenPaymentException e) {
|
||||
} catch (PurchaseReceiptRequestedForOpenPaymentException e) {
|
||||
return Response.noContent().build();
|
||||
} catch (VerificationFailedException e) {
|
||||
throw new BadRequestException("receipt credential request failed verification", e);
|
||||
|
||||
+2
-2
@@ -368,8 +368,8 @@ public class MessageController {
|
||||
final String userAgent = context.getHeaderString(HttpHeaders.USER_AGENT);
|
||||
|
||||
try {
|
||||
final int totalContentLength =
|
||||
messages.messages().stream().mapToInt(message -> message.content().length).sum();
|
||||
final long totalContentLength =
|
||||
messages.messages().stream().mapToLong(message -> message.content().length).sum();
|
||||
|
||||
rateLimiters.getInboundMessageBytes().validate(destinationIdentifier.uuid(), totalContentLength);
|
||||
} catch (final RateLimitExceededException e) {
|
||||
|
||||
+28
-29
@@ -62,21 +62,23 @@ import org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimitedByIp;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.purchases.BraintreeManager;
|
||||
import org.whispersystems.textsecuregcm.purchases.ChargeFailure;
|
||||
import org.whispersystems.textsecuregcm.purchases.CustomerAwareSubscriptionPaymentProcessor;
|
||||
import org.whispersystems.textsecuregcm.purchases.PayPalDonationsTranslator;
|
||||
import org.whispersystems.textsecuregcm.purchases.PaymentDetails;
|
||||
import org.whispersystems.textsecuregcm.purchases.PaymentMethod;
|
||||
import org.whispersystems.textsecuregcm.purchases.PaymentProvider;
|
||||
import org.whispersystems.textsecuregcm.purchases.PurchaseInvalidAmountException;
|
||||
import org.whispersystems.textsecuregcm.purchases.PurchaseNotFoundException;
|
||||
import org.whispersystems.textsecuregcm.purchases.PurchasePaymentRequiredException;
|
||||
import org.whispersystems.textsecuregcm.purchases.PurchaseProcessorException;
|
||||
import org.whispersystems.textsecuregcm.purchases.PurchaseReceiptRequestedForOpenPaymentException;
|
||||
import org.whispersystems.textsecuregcm.purchases.StripeManager;
|
||||
import org.whispersystems.textsecuregcm.storage.DonationPermitsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.IssuedReceiptsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.OneTimeDonationsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.WriteConflictException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.BraintreeManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.ChargeFailure;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.CustomerAwareSubscriptionPaymentProcessor;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PayPalDonationsTranslator;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentDetails;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentMethod;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentStatus;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.StripeManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidAmountException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorException;
|
||||
import org.whispersystems.textsecuregcm.util.ExactlySize;
|
||||
import org.whispersystems.textsecuregcm.util.HeaderUtils;
|
||||
|
||||
@@ -179,7 +181,7 @@ public class OneTimeDonationController {
|
||||
@HeaderParam(HeaderUtils.DONATION_PERMIT) final Optional<DonationPermitHeader> donationPermitHeader,
|
||||
|
||||
@NotNull @Valid final CreateBoostRequest request,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent) throws SubscriptionInvalidAmountException {
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent) throws PurchaseInvalidAmountException {
|
||||
|
||||
if (authenticatedAccount.isPresent()) {
|
||||
throw new ForbiddenException("must not use authenticated connection for one-time donation operations");
|
||||
@@ -299,7 +301,7 @@ public class OneTimeDonationController {
|
||||
public ConfirmPayPalBoostResponse confirmPayPalBoost(
|
||||
@Auth final Optional<AuthenticatedDevice> authenticatedAccount,
|
||||
@NotNull @Valid final ConfirmPayPalBoostRequest request,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent) throws SubscriptionProcessorException, IOException {
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent) throws PurchaseProcessorException, IOException {
|
||||
|
||||
if (authenticatedAccount.isPresent()) {
|
||||
throw new ForbiddenException("must not use authenticated connection for one-time donation operations");
|
||||
@@ -347,27 +349,23 @@ public class OneTimeDonationController {
|
||||
throw new ForbiddenException("must not use authenticated connection for one-time donation operations");
|
||||
}
|
||||
|
||||
final Optional<PaymentDetails> maybePaymentDetails = (switch (request.processor) {
|
||||
case STRIPE -> stripeManager.claimOneTimePurchase(request.paymentIntentId);
|
||||
case BRAINTREE -> braintreeManager.claimOneTimePurchase(request.paymentIntentId);
|
||||
case GOOGLE_PLAY_BILLING -> throw new BadRequestException("cannot use play billing for one-time donations");
|
||||
case APPLE_APP_STORE -> throw new BadRequestException("cannot use app store purchases for one-time donations");
|
||||
});
|
||||
|
||||
if (maybePaymentDetails.isEmpty()) {
|
||||
final PaymentDetails paymentDetails;
|
||||
try {
|
||||
paymentDetails = (switch (request.processor) {
|
||||
case STRIPE -> stripeManager.claimOneTimePurchase(request.paymentIntentId);
|
||||
case BRAINTREE -> braintreeManager.claimOneTimePurchase(request.paymentIntentId);
|
||||
case GOOGLE_PLAY_BILLING -> throw new BadRequestException("cannot use play billing for one-time donations");
|
||||
case APPLE_APP_STORE -> throw new BadRequestException("cannot use app store purchases for one-time donations");
|
||||
});
|
||||
} catch (PurchaseNotFoundException _) {
|
||||
throw new WebApplicationException(Response.Status.NOT_FOUND);
|
||||
}
|
||||
final PaymentDetails paymentDetails = maybePaymentDetails.get();
|
||||
if (paymentDetails.status() == PaymentStatus.PROCESSING) {
|
||||
} catch (PurchaseReceiptRequestedForOpenPaymentException _) {
|
||||
return Response.noContent().build();
|
||||
}
|
||||
if (paymentDetails.status() != PaymentStatus.SUCCEEDED) {
|
||||
} catch (PurchasePaymentRequiredException e) {
|
||||
throw new WebApplicationException(Response.status(Response.Status.PAYMENT_REQUIRED)
|
||||
.entity(new CreateBoostReceiptCredentialErrorResponse(paymentDetails.chargeFailure())).build());
|
||||
.entity(new CreateBoostReceiptCredentialErrorResponse(e.getChargeFailure().orElse(null))).build());
|
||||
}
|
||||
|
||||
// The payment was successful, try to issue the receipt credential
|
||||
|
||||
final OneTimeDonationUtil.DonationLevelDetails levelDetails;
|
||||
try {
|
||||
levelDetails = OneTimeDonationUtil.getLevelDetails(paymentDetails, oneTimeDonationConfiguration);
|
||||
@@ -375,6 +373,7 @@ public class OneTimeDonationController {
|
||||
throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
|
||||
// try to issue the receipt credential
|
||||
final ReceiptCredentialRequest receiptCredentialRequest;
|
||||
try {
|
||||
receiptCredentialRequest = new ReceiptCredentialRequest(request.receiptCredentialRequest);
|
||||
|
||||
+3
-3
@@ -80,8 +80,8 @@ import org.whispersystems.textsecuregcm.storage.DeviceSpec;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.storage.PhoneNumberRecoveryPasswordsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ReceiptAlreadyRedeemedException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.ReceiptCredentialPresentationFactory;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel;
|
||||
import org.whispersystems.textsecuregcm.purchases.ReceiptCredentialPresentationFactory;
|
||||
import org.whispersystems.textsecuregcm.purchases.ReceiptLevel;
|
||||
import org.whispersystems.textsecuregcm.util.HeaderUtils;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
@@ -366,7 +366,7 @@ public class RegistrationController {
|
||||
}
|
||||
|
||||
final long receiptLevel = receiptCredentialPresentation.getReceiptLevel();
|
||||
if (receiptLevel != ReceiptLevel.LOGIN.getValue()) {
|
||||
if (receiptLevel != ReceiptLevel.LOGIN.getValue() && receiptLevel != ReceiptLevel.LOGIN_SANDBOX.getValue()) {
|
||||
throw new BadRequestException("Invalid receipt level");
|
||||
}
|
||||
|
||||
|
||||
+38
-38
@@ -72,32 +72,32 @@ import org.whispersystems.textsecuregcm.configuration.SubscriptionLevelConfigura
|
||||
import org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimitedByIp;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.mappers.SubscriptionExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.PurchaseExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.DonationPermitsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.SubscriberCredentials;
|
||||
import org.whispersystems.textsecuregcm.storage.SubscriptionManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Subscriptions;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.AppleAppStoreManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.BankMandateTranslator;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.BankTransferType;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.BraintreeManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.ChargeFailure;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.CurrencyConfiguration;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.CustomerAwareSubscriptionPaymentProcessor;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.GooglePlayBillingManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.LevelConfiguration;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentMethod;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.ProcessorCustomer;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.StripeManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidArgumentsException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidLevelException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentRequiresActionException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptRequestedForOpenPaymentException;
|
||||
import org.whispersystems.textsecuregcm.purchases.AppleAppStoreManager;
|
||||
import org.whispersystems.textsecuregcm.purchases.BankMandateTranslator;
|
||||
import org.whispersystems.textsecuregcm.purchases.BankTransferType;
|
||||
import org.whispersystems.textsecuregcm.purchases.BraintreeManager;
|
||||
import org.whispersystems.textsecuregcm.purchases.ChargeFailure;
|
||||
import org.whispersystems.textsecuregcm.purchases.CurrencyConfiguration;
|
||||
import org.whispersystems.textsecuregcm.purchases.CustomerAwareSubscriptionPaymentProcessor;
|
||||
import org.whispersystems.textsecuregcm.purchases.GooglePlayBillingManager;
|
||||
import org.whispersystems.textsecuregcm.purchases.LevelConfiguration;
|
||||
import org.whispersystems.textsecuregcm.purchases.PaymentMethod;
|
||||
import org.whispersystems.textsecuregcm.purchases.PaymentProvider;
|
||||
import org.whispersystems.textsecuregcm.purchases.ProcessorCustomer;
|
||||
import org.whispersystems.textsecuregcm.purchases.ReceiptLevel;
|
||||
import org.whispersystems.textsecuregcm.purchases.StripeManager;
|
||||
import org.whispersystems.textsecuregcm.purchases.PurchaseException;
|
||||
import org.whispersystems.textsecuregcm.purchases.PurchaseInvalidArgumentsException;
|
||||
import org.whispersystems.textsecuregcm.purchases.PurchaseInvalidLevelException;
|
||||
import org.whispersystems.textsecuregcm.purchases.PurchasePaymentRequiresActionException;
|
||||
import org.whispersystems.textsecuregcm.purchases.PurchaseReceiptRequestedForOpenPaymentException;
|
||||
import org.whispersystems.textsecuregcm.util.HeaderUtils;
|
||||
|
||||
@Path("/v1/subscription")
|
||||
@@ -197,7 +197,7 @@ public class SubscriptionController {
|
||||
@ManagedAsync
|
||||
public Response deleteSubscriber(
|
||||
@Auth Optional<AuthenticatedDevice> authenticatedAccount,
|
||||
@PathParam("subscriberId") String subscriberId) throws SubscriptionException, RateLimitExceededException {
|
||||
@PathParam("subscriberId") String subscriberId) throws PurchaseException, RateLimitExceededException {
|
||||
SubscriberCredentials subscriberCredentials =
|
||||
SubscriberCredentials.process(authenticatedAccount, subscriberId, clock);
|
||||
subscriptionManager.deleteSubscriber(subscriberCredentials);
|
||||
@@ -229,7 +229,7 @@ public class SubscriptionController {
|
||||
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) @Nullable final String userAgent,
|
||||
|
||||
@PathParam("subscriberId") String subscriberId) throws SubscriptionException {
|
||||
@PathParam("subscriberId") String subscriberId) throws PurchaseException {
|
||||
SubscriberCredentials subscriberCredentials =
|
||||
SubscriberCredentials.process(authenticatedAccount, subscriberId, clock);
|
||||
|
||||
@@ -277,7 +277,7 @@ public class SubscriptionController {
|
||||
|
||||
@PathParam("subscriberId") String subscriberId,
|
||||
@QueryParam("type") @DefaultValue("CARD") PaymentMethod paymentMethodType,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) @Nullable final String userAgentString) throws SubscriptionException {
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) @Nullable final String userAgentString) throws PurchaseException {
|
||||
|
||||
SubscriberCredentials subscriberCredentials =
|
||||
SubscriberCredentials.process(authenticatedAccount, subscriberId, clock);
|
||||
@@ -332,7 +332,7 @@ public class SubscriptionController {
|
||||
@NotNull @Valid CreatePayPalBillingAgreementRequest request,
|
||||
@Context ContainerRequestContext containerRequestContext,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) @Nullable final String userAgentString)
|
||||
throws SubscriptionException, IOException {
|
||||
throws PurchaseException, IOException {
|
||||
|
||||
final SubscriberCredentials subscriberCredentials =
|
||||
SubscriberCredentials.process(authenticatedAccount, subscriberId, clock);
|
||||
@@ -365,7 +365,7 @@ public class SubscriptionController {
|
||||
@Auth Optional<AuthenticatedDevice> authenticatedAccount,
|
||||
@PathParam("subscriberId") String subscriberId,
|
||||
@PathParam("processor") PaymentProvider processor,
|
||||
@PathParam("paymentMethodToken") @NotEmpty String paymentMethodToken) throws SubscriptionException, IOException {
|
||||
@PathParam("paymentMethodToken") @NotEmpty String paymentMethodToken) throws PurchaseException, IOException {
|
||||
SubscriberCredentials subscriberCredentials =
|
||||
SubscriberCredentials.process(authenticatedAccount, subscriberId, clock);
|
||||
|
||||
@@ -405,7 +405,7 @@ public class SubscriptionController {
|
||||
@PathParam("subscriberId") String subscriberId,
|
||||
@PathParam("level") long level,
|
||||
@PathParam("currency") String currency,
|
||||
@PathParam("idempotencyKey") String idempotencyKey) throws SubscriptionException {
|
||||
@PathParam("idempotencyKey") String idempotencyKey) throws PurchaseException {
|
||||
SubscriberCredentials subscriberCredentials =
|
||||
SubscriberCredentials.process(authenticatedAccount, subscriberId, clock);
|
||||
try {
|
||||
@@ -424,19 +424,19 @@ public class SubscriptionController {
|
||||
subscriptionManager.updateSubscriptionLevelForCustomer(subscriberCredentials, record, manager, level,
|
||||
currency, idempotencyKey, subscriptionTemplateId, this::subscriptionsAreSameType);
|
||||
return new SetSubscriptionLevelSuccessResponse(level);
|
||||
} catch (SubscriptionInvalidLevelException e) {
|
||||
} catch (PurchaseInvalidLevelException e) {
|
||||
throw new BadRequestException(Response.status(Response.Status.BAD_REQUEST)
|
||||
.entity(new SubscriptionController.SetSubscriptionLevelErrorResponse(List.of(
|
||||
new SubscriptionController.SetSubscriptionLevelErrorResponse.Error(
|
||||
SubscriptionController.SetSubscriptionLevelErrorResponse.Error.Type.UNSUPPORTED_LEVEL,
|
||||
null))))
|
||||
.build());
|
||||
} catch (SubscriptionPaymentRequiresActionException e) {
|
||||
} catch (PurchasePaymentRequiresActionException e) {
|
||||
throw new BadRequestException(Response.status(Response.Status.BAD_REQUEST)
|
||||
.entity(new SetSubscriptionLevelErrorResponse(List.of(new SetSubscriptionLevelErrorResponse.Error(
|
||||
SetSubscriptionLevelErrorResponse.Error.Type.PAYMENT_REQUIRES_ACTION, null))))
|
||||
.build());
|
||||
} catch (SubscriptionInvalidArgumentsException e) {
|
||||
} catch (PurchaseInvalidArgumentsException e) {
|
||||
throw new BadRequestException(Response.status(Response.Status.BAD_REQUEST)
|
||||
.entity(new SetSubscriptionLevelErrorResponse(List.of(new SetSubscriptionLevelErrorResponse.Error(
|
||||
SetSubscriptionLevelErrorResponse.Error.Type.INVALID_ARGUMENTS, e.getMessage()))))
|
||||
@@ -476,7 +476,7 @@ public class SubscriptionController {
|
||||
public SetSubscriptionLevelSuccessResponse setAppStoreSubscription(
|
||||
@Auth Optional<AuthenticatedDevice> authenticatedAccount,
|
||||
@PathParam("subscriberId") String subscriberId,
|
||||
@PathParam("originalTransactionId") String originalTransactionId) throws SubscriptionException, RateLimitExceededException {
|
||||
@PathParam("originalTransactionId") String originalTransactionId) throws PurchaseException, RateLimitExceededException {
|
||||
final SubscriberCredentials subscriberCredentials =
|
||||
SubscriberCredentials.process(authenticatedAccount, subscriberId, clock);
|
||||
|
||||
@@ -520,7 +520,7 @@ public class SubscriptionController {
|
||||
public SetSubscriptionLevelSuccessResponse setPlayStoreSubscription(
|
||||
@Auth Optional<AuthenticatedDevice> authenticatedAccount,
|
||||
@PathParam("subscriberId") String subscriberId,
|
||||
@PathParam("purchaseToken") String purchaseToken) throws SubscriptionException, RateLimitExceededException {
|
||||
@PathParam("purchaseToken") String purchaseToken) throws PurchaseException, RateLimitExceededException {
|
||||
final SubscriberCredentials subscriberCredentials =
|
||||
SubscriberCredentials.process(authenticatedAccount, subscriberId, clock);
|
||||
|
||||
@@ -665,7 +665,7 @@ public class SubscriptionController {
|
||||
@ManagedAsync
|
||||
public GetSubscriptionInformationResponse getSubscriptionInformation(
|
||||
@Auth Optional<AuthenticatedDevice> authenticatedAccount,
|
||||
@PathParam("subscriberId") String subscriberId) throws SubscriptionException, RateLimitExceededException {
|
||||
@PathParam("subscriberId") String subscriberId) throws PurchaseException, RateLimitExceededException {
|
||||
SubscriberCredentials subscriberCredentials =
|
||||
SubscriberCredentials.process(authenticatedAccount, subscriberId, clock);
|
||||
return subscriptionManager.getSubscriptionInformation( subscriberCredentials)
|
||||
@@ -739,7 +739,7 @@ public class SubscriptionController {
|
||||
}
|
||||
}
|
||||
""",
|
||||
implementation = SubscriptionExceptionMapper.ChargeFailureResponse.class)))
|
||||
implementation = PurchaseExceptionMapper.ChargeFailureResponse.class)))
|
||||
@ApiResponse(responseCode = "403", description = "subscriberId authentication failure OR account authentication is present")
|
||||
@ApiResponse(responseCode = "404", description = "subscriberId is not found OR malformed OR no subscription setup on the subscriber id")
|
||||
@ApiResponse(responseCode = "409", description = "latest paid receipt on subscription was already redeemed for a receipt credential but with a different receipt credential request")
|
||||
@@ -751,7 +751,7 @@ public class SubscriptionController {
|
||||
@Auth Optional<AuthenticatedDevice> authenticatedAccount,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
|
||||
@PathParam("subscriberId") String subscriberId,
|
||||
@NotNull @Valid GetReceiptCredentialRequest request) throws SubscriptionException, RateLimitExceededException {
|
||||
@NotNull @Valid GetReceiptCredentialRequest request) throws PurchaseException, RateLimitExceededException {
|
||||
SubscriberCredentials subscriberCredentials = SubscriberCredentials.process(authenticatedAccount, subscriberId, clock);
|
||||
try {
|
||||
final SubscriptionManager.ReceiptResult receiptCredential = subscriptionManager.createReceiptCredential(
|
||||
@@ -771,7 +771,7 @@ public class SubscriptionController {
|
||||
UserAgentTagUtil.getPlatformTag(userAgent)))
|
||||
.increment();
|
||||
return Response.ok(new GetReceiptCredentialResponse(receiptCredentialResponse.serialize())).build();
|
||||
} catch (SubscriptionReceiptRequestedForOpenPaymentException e) {
|
||||
} catch (PurchaseReceiptRequestedForOpenPaymentException e) {
|
||||
return Response.noContent().build();
|
||||
}
|
||||
}
|
||||
@@ -783,7 +783,7 @@ public class SubscriptionController {
|
||||
public Response setDefaultPaymentMethodForIdeal(
|
||||
@Auth Optional<AuthenticatedDevice> authenticatedAccount,
|
||||
@PathParam("subscriberId") String subscriberId,
|
||||
@PathParam("setupIntentId") @NotEmpty String setupIntentId) throws SubscriptionException, IOException {
|
||||
@PathParam("setupIntentId") @NotEmpty String setupIntentId) throws PurchaseException, IOException {
|
||||
SubscriberCredentials subscriberCredentials =
|
||||
SubscriberCredentials.process(authenticatedAccount, subscriberId, clock);
|
||||
|
||||
@@ -794,7 +794,7 @@ public class SubscriptionController {
|
||||
|
||||
private void setDefaultPaymentMethod(final CustomerAwareSubscriptionPaymentProcessor manager,
|
||||
final String paymentMethodId,
|
||||
final SubscriberCredentials requestData) throws SubscriptionException, IOException {
|
||||
final SubscriberCredentials requestData) throws PurchaseException, IOException {
|
||||
try {
|
||||
final Subscriptions.Record record = subscriptionManager.getSubscriber(requestData);
|
||||
|
||||
@@ -805,7 +805,7 @@ public class SubscriptionController {
|
||||
|
||||
manager
|
||||
.setDefaultPaymentMethodForCustomer(processorCustomer.customerId(), paymentMethodId, record.subscriptionId);
|
||||
} catch (final SubscriptionInvalidArgumentsException e) {
|
||||
} catch (final PurchaseInvalidArgumentsException e) {
|
||||
// Here, invalid arguments must mean that the client has made requests out of order, and needs to finish
|
||||
// setting up the paymentMethod first
|
||||
throw new ClientErrorException(Status.CONFLICT);
|
||||
|
||||
@@ -38,7 +38,7 @@ public class FixerClient {
|
||||
HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
if (response.statusCode() < 200 || response.statusCode() >= 300) {
|
||||
throw new FixerException("Bad response: " + response.statusCode() + " " + response.toString());
|
||||
throw new FixerException("Bad response: " + response.statusCode() + " " + response.toString().replaceAll(apiKey, "***"));
|
||||
}
|
||||
|
||||
final FixerResponse parsedResponse = SystemMapper.jsonMapper().readValue(response.body(), FixerResponse.class);
|
||||
|
||||
+3
-2
@@ -4,7 +4,8 @@
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
public record ApnRegistrationId(@NotEmpty String apnRegistrationId) {
|
||||
public record ApnRegistrationId(@NotBlank @Size(max = 1024) String apnRegistrationId) {
|
||||
}
|
||||
+3
-2
@@ -4,7 +4,8 @@
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
public record GcmRegistrationId(@NotEmpty String gcmRegistrationId) {
|
||||
public record GcmRegistrationId(@NotBlank @Size(max = 1024) String gcmRegistrationId) {
|
||||
}
|
||||
+1
-8
@@ -8,8 +8,6 @@ package org.whispersystems.textsecuregcm.filters;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.common.net.HttpHeaders;
|
||||
import com.vdurmont.semver4j.Semver;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import jakarta.ws.rs.WebApplicationException;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.ws.rs.container.ContainerRequestFilter;
|
||||
@@ -24,7 +22,6 @@ import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicRestDeprecationConfiguration.PlatformConfiguration;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
|
||||
import org.whispersystems.textsecuregcm.util.ua.UnrecognizedUserAgentException;
|
||||
@@ -34,7 +31,6 @@ import org.whispersystems.textsecuregcm.util.ua.UserAgentUtil;
|
||||
public class RestDeprecationFilter implements ContainerRequestFilter {
|
||||
|
||||
private static final String AUTHENTICATED_EXPERIMENT_NAME = "restDeprecation";
|
||||
private static final String DEPRECATED_REST_COUNTER_NAME = MetricsUtil.name(RestDeprecationFilter.class, "blockedRestRequest");
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(RestDeprecationFilter.class);
|
||||
|
||||
@@ -75,13 +71,10 @@ public class RestDeprecationFilter implements ContainerRequestFilter {
|
||||
return;
|
||||
}
|
||||
if (version.isGreaterThanOrEqualTo(config.minimumRestFreeVersion())) {
|
||||
Metrics.counter(
|
||||
DEPRECATED_REST_COUNTER_NAME, Tags.of("platform", platform.name().toLowerCase(), "version", version.toString()))
|
||||
.increment();
|
||||
throw new WebApplicationException("use websockets", 498);
|
||||
}
|
||||
} catch (final UnrecognizedUserAgentException e) {
|
||||
return; // at present we're only interested in experimenting on known clients
|
||||
// at present, we're only requiring this for known clients
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+11
-2
@@ -12,6 +12,8 @@ import org.signal.chat.credentials.SimpleCredentialsAnonymousGrpc;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsSelector;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import java.util.HashSet;
|
||||
@@ -23,18 +25,25 @@ public class CredentialsAnonymousGrpcService extends SimpleCredentialsAnonymousG
|
||||
|
||||
private final AccountsManager accountsManager;
|
||||
private final ExternalServiceCredentialsGenerator svrCredentialsGenerator;
|
||||
private final RateLimiters rateLimiters;
|
||||
|
||||
private static final long MAX_SVR_PASSWORD_AGE_SECONDS = TimeUnit.DAYS.toSeconds(30);
|
||||
|
||||
public CredentialsAnonymousGrpcService(final AccountsManager accountsManager,
|
||||
final ExternalServiceCredentialsGenerator svrCredentialsGenerator) {
|
||||
final ExternalServiceCredentialsGenerator svrCredentialsGenerator,
|
||||
final RateLimiters rateLimiters) {
|
||||
|
||||
this.svrCredentialsGenerator = svrCredentialsGenerator;
|
||||
this.accountsManager = accountsManager;
|
||||
this.rateLimiters = rateLimiters;
|
||||
}
|
||||
|
||||
@Override
|
||||
public CheckSvrCredentialsResponse checkSvrCredentials(final CheckSvrCredentialsRequest request) {
|
||||
public CheckSvrCredentialsResponse checkSvrCredentials(final CheckSvrCredentialsRequest request)
|
||||
throws RateLimitExceededException {
|
||||
|
||||
RateLimitUtil.rateLimitByRemoteAddress(rateLimiters.getBackupAuthCheckLimiter());
|
||||
|
||||
final List<String> tokens = request.getPasswordsList().stream().distinct().toList();
|
||||
final List<ExternalServiceCredentialsSelector.CredentialInfo> credentials = ExternalServiceCredentialsSelector.check(
|
||||
new HashSet<>(tokens),
|
||||
|
||||
+8
-8
@@ -4,8 +4,8 @@ import com.google.protobuf.ByteString;
|
||||
import com.google.protobuf.Empty;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import org.signal.chat.donations.CreateDonationPermitRequest;
|
||||
import org.signal.chat.donations.CreateDonationPermitResponse;
|
||||
import org.signal.chat.donations.CreateDonationPermitsRequest;
|
||||
import org.signal.chat.donations.CreateDonationPermitsResponse;
|
||||
import org.signal.chat.donations.RedeemReceiptRequest;
|
||||
import org.signal.chat.donations.RedeemReceiptResponse;
|
||||
import org.signal.chat.donations.SimpleDonationsGrpc;
|
||||
@@ -28,8 +28,8 @@ import org.whispersystems.textsecuregcm.storage.AccountBadge;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.DonationPermitsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.RedeemedReceiptsManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.ReceiptCredentialPresentationFactory;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel;
|
||||
import org.whispersystems.textsecuregcm.purchases.ReceiptCredentialPresentationFactory;
|
||||
import org.whispersystems.textsecuregcm.purchases.ReceiptLevel;
|
||||
|
||||
public class DonationsGrpcService extends SimpleDonationsGrpc.DonationsImplBase {
|
||||
|
||||
@@ -120,10 +120,10 @@ public class DonationsGrpcService extends SimpleDonationsGrpc.DonationsImplBase
|
||||
}
|
||||
|
||||
@Override
|
||||
public CreateDonationPermitResponse createDonationPermit(final CreateDonationPermitRequest request) throws Exception {
|
||||
public CreateDonationPermitsResponse createDonationPermits(final CreateDonationPermitsRequest request) throws Exception {
|
||||
final DonationPermitRequest permitRequest;
|
||||
try {
|
||||
permitRequest = new DonationPermitRequest(request.getDonationPermitRequest().toByteArray());
|
||||
permitRequest = new DonationPermitRequest(request.getDonationPermitsRequest().toByteArray());
|
||||
} catch (InvalidInputException e) {
|
||||
throw GrpcExceptions.invalidArguments("invalid permit request");
|
||||
}
|
||||
@@ -133,8 +133,8 @@ public class DonationsGrpcService extends SimpleDonationsGrpc.DonationsImplBase
|
||||
|
||||
final DonationPermitResponse permitResponse = donationPermitsManager.issue(permitRequest);
|
||||
|
||||
return CreateDonationPermitResponse.newBuilder()
|
||||
.setDonationPermitResponse(ByteString.copyFrom(permitResponse.serialize()))
|
||||
return CreateDonationPermitsResponse.newBuilder()
|
||||
.setDonationPermitsResponse(ByteString.copyFrom(permitResponse.serialize()))
|
||||
.build();
|
||||
}
|
||||
}
|
||||
+6
@@ -22,6 +22,7 @@ import org.signal.chat.keys.SimpleKeysAnonymousGrpc;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.signal.libsignal.zkgroup.ServerSecretParams;
|
||||
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
@@ -48,6 +49,11 @@ public class KeysAnonymousGrpcService extends SimpleKeysAnonymousGrpc.KeysAnonym
|
||||
final ServiceIdentifier serviceIdentifier =
|
||||
GrpcServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getRequest().getTargetIdentifier());
|
||||
|
||||
if (serviceIdentifier.identityType() == IdentityType.PNI
|
||||
&& request.getAuthorizationCase() != GetPreKeysAnonymousRequest.AuthorizationCase.GROUP_SEND_TOKEN) {
|
||||
throw GrpcExceptions.fieldViolation("authorization", "group send token is required for PNI targets");
|
||||
}
|
||||
|
||||
final byte deviceId = request.getRequest().hasDeviceId()
|
||||
? DeviceIdUtil.validate(request.getRequest().getDeviceId())
|
||||
: KeysGrpcHelper.ALL_DEVICES;
|
||||
|
||||
+13
-20
@@ -10,7 +10,6 @@ import org.signal.chat.errors.FailedPrecondition;
|
||||
import org.signal.chat.errors.NotFound;
|
||||
import org.signal.chat.purchase.CreateLoginReceiptCredentialRequest;
|
||||
import org.signal.chat.purchase.CreateLoginReceiptCredentialResponse;
|
||||
import org.signal.chat.purchase.PaymentRequired;
|
||||
import org.signal.chat.purchase.SimpleLoginPurchaseGrpc;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.VerificationFailedException;
|
||||
@@ -19,14 +18,13 @@ import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialResponse;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.LoginPurchaseManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionChargeFailurePaymentRequiredException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidArgumentsException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionNotFoundException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentRequiredException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptAlreadyRedeemedException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptRequestedForOpenPaymentException;
|
||||
import org.whispersystems.textsecuregcm.purchases.LoginPurchaseManager;
|
||||
import org.whispersystems.textsecuregcm.purchases.PaymentProvider;
|
||||
import org.whispersystems.textsecuregcm.purchases.PurchaseInvalidArgumentsException;
|
||||
import org.whispersystems.textsecuregcm.purchases.PurchaseNotFoundException;
|
||||
import org.whispersystems.textsecuregcm.purchases.PurchasePaymentRequiredException;
|
||||
import org.whispersystems.textsecuregcm.purchases.PurchaseReceiptAlreadyRedeemedException;
|
||||
import org.whispersystems.textsecuregcm.purchases.PurchaseReceiptRequestedForOpenPaymentException;
|
||||
|
||||
public class LoginPurchaseGrpcService extends SimpleLoginPurchaseGrpc.LoginPurchaseImplBase {
|
||||
|
||||
@@ -66,28 +64,23 @@ public class LoginPurchaseGrpcService extends SimpleLoginPurchaseGrpc.LoginPurch
|
||||
.setResult(CreateLoginReceiptCredentialResponse.CreateLoginReceiptCredentialResult.newBuilder()
|
||||
.setReceiptCredentialResponse(ByteString.copyFrom(receiptCredentialResponse.serialize())))
|
||||
.build();
|
||||
} catch (final SubscriptionReceiptRequestedForOpenPaymentException e) {
|
||||
} catch (final PurchaseReceiptRequestedForOpenPaymentException e) {
|
||||
return CreateLoginReceiptCredentialResponse.newBuilder()
|
||||
.setPaymentStillProcessing(FailedPrecondition.getDefaultInstance())
|
||||
.build();
|
||||
} catch (final SubscriptionChargeFailurePaymentRequiredException e) {
|
||||
} catch (final PurchasePaymentRequiredException e) {
|
||||
return CreateLoginReceiptCredentialResponse.newBuilder()
|
||||
.setPaymentRequired(PaymentRequired.newBuilder()
|
||||
.setChargeFailure(SubscriptionsUtil.toChargeFailure(e.getProcessor(), e.getChargeFailure())))
|
||||
.setPaymentRequired(SubscriptionsUtil.toPaymentRequired(e))
|
||||
.build();
|
||||
} catch (final SubscriptionPaymentRequiredException e) {
|
||||
return CreateLoginReceiptCredentialResponse.newBuilder()
|
||||
.setPaymentRequired(PaymentRequired.getDefaultInstance())
|
||||
.build();
|
||||
} catch (final SubscriptionNotFoundException e) {
|
||||
} catch (final PurchaseNotFoundException e) {
|
||||
return CreateLoginReceiptCredentialResponse.newBuilder()
|
||||
.setPaymentNotFound(NotFound.getDefaultInstance())
|
||||
.build();
|
||||
} catch (final SubscriptionReceiptAlreadyRedeemedException e) {
|
||||
} catch (final PurchaseReceiptAlreadyRedeemedException e) {
|
||||
return CreateLoginReceiptCredentialResponse.newBuilder()
|
||||
.setReceiptAlreadyIssued(FailedPrecondition.getDefaultInstance())
|
||||
.build();
|
||||
} catch (final SubscriptionInvalidArgumentsException e) {
|
||||
} catch (final PurchaseInvalidArgumentsException e) {
|
||||
throw GrpcExceptions.invalidArguments(e.errorDetail().orElse(""));
|
||||
} catch (final VerificationFailedException e) {
|
||||
throw GrpcExceptions.fieldViolation("receipt_credential_request",
|
||||
|
||||
+19
-7
@@ -10,6 +10,7 @@ import com.google.protobuf.Empty;
|
||||
import java.time.Clock;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.stream.Collectors;
|
||||
import org.signal.chat.errors.FailedUnidentifiedAuthorization;
|
||||
import org.signal.chat.errors.NotFound;
|
||||
@@ -86,14 +87,15 @@ public class MessagesAnonymousGrpcService extends SimpleMessagesAnonymousGrpc.Me
|
||||
final ServiceIdentifier destinationServiceIdentifier =
|
||||
GrpcServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getDestination());
|
||||
|
||||
if (destinationServiceIdentifier.identityType() == IdentityType.PNI
|
||||
&& request.getAuthorizationCase() != SendSealedSenderMessageRequest.AuthorizationCase.GROUP_SEND_TOKEN) {
|
||||
throw GrpcExceptions.fieldViolation("authorization", "group send token is required for PNI destinations");
|
||||
}
|
||||
|
||||
final Optional<Account> maybeDestination = accountsManager.getByServiceIdentifier(destinationServiceIdentifier);
|
||||
|
||||
final boolean authorized = switch (request.getAuthorizationCase()) {
|
||||
case UNIDENTIFIED_ACCESS_KEY -> {
|
||||
if (destinationServiceIdentifier.identityType() == IdentityType.PNI) {
|
||||
throw GrpcExceptions.fieldViolation("authorization",
|
||||
"message for PNI cannot be authenticated with an unidentified access token");
|
||||
}
|
||||
final byte[] uak = request.getUnidentifiedAccessKey().toByteArray();
|
||||
yield maybeDestination
|
||||
.map(account -> UnidentifiedAccessUtil.checkUnidentifiedAccess(account, uak))
|
||||
@@ -104,7 +106,7 @@ public class MessagesAnonymousGrpcService extends SimpleMessagesAnonymousGrpc.Me
|
||||
case GROUP_SEND_TOKEN ->
|
||||
groupSendTokenUtil.checkGroupSendToken(request.getGroupSendToken(), destinationServiceIdentifier);
|
||||
case UNRESTRICTED_ACCESS ->
|
||||
maybeDestination.map(account -> account.isUnrestrictedUnidentifiedAccess()).orElse(false);
|
||||
maybeDestination.map(Account::isUnrestrictedUnidentifiedAccess).orElse(false);
|
||||
case AUTHORIZATION_NOT_SET ->
|
||||
throw GrpcExceptions.fieldViolation("authorization", "expected authorization token not provided");
|
||||
};
|
||||
@@ -118,7 +120,7 @@ public class MessagesAnonymousGrpcService extends SimpleMessagesAnonymousGrpc.Me
|
||||
if (maybeDestination.isEmpty()) {
|
||||
return SendMessageResponse.newBuilder().setDestinationNotFound(NotFound.getDefaultInstance()).build();
|
||||
}
|
||||
|
||||
|
||||
return sendIndividualMessage(maybeDestination.get(),
|
||||
destinationServiceIdentifier,
|
||||
request.getMessages(),
|
||||
@@ -168,7 +170,7 @@ public class MessagesAnonymousGrpcService extends SimpleMessagesAnonymousGrpc.Me
|
||||
destinationServiceIdentifier);
|
||||
|
||||
spamCheckResult.response().ifPresent(grpcResponse ->
|
||||
grpcResponse.throwStatusOr(_ -> GrpcExceptions.rateLimitExceeded(null)));
|
||||
grpcResponse.throwStatusOr(_ -> GrpcExceptions.rateLimitExceeded(null)));
|
||||
|
||||
try {
|
||||
final int totalPayloadLength = messages.getMessagesMap().values().stream()
|
||||
@@ -297,6 +299,16 @@ public class MessagesAnonymousGrpcService extends SimpleMessagesAnonymousGrpc.Me
|
||||
final Map<SealedSenderMultiRecipientMessage.Recipient, Account> resolvedRecipients =
|
||||
MessageUtil.resolveRecipients(accountsManager, multiRecipientMessage);
|
||||
|
||||
if (story) {
|
||||
CompletableFuture.allOf(resolvedRecipients.values()
|
||||
.stream()
|
||||
.map(Account::getAccountIdentifier)
|
||||
.map(accountIdentifier ->
|
||||
rateLimiters.getStoriesLimiter().validateAsync(accountIdentifier).toCompletableFuture())
|
||||
.toArray(CompletableFuture[]::new))
|
||||
.join();
|
||||
}
|
||||
|
||||
try {
|
||||
if (!resolvedRecipients.isEmpty()) {
|
||||
messageSender.sendMultiRecipientMessage(multiRecipientMessage,
|
||||
|
||||
+9
-7
@@ -7,12 +7,12 @@ import java.util.Locale;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.CustomerAwareSubscriptionPaymentProcessor;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PayPalDonationsTranslator;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentDetails;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentMethod;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionCurrencyUtil;
|
||||
import org.whispersystems.textsecuregcm.purchases.CustomerAwareSubscriptionPaymentProcessor;
|
||||
import org.whispersystems.textsecuregcm.purchases.PayPalDonationsTranslator;
|
||||
import org.whispersystems.textsecuregcm.purchases.PaymentDetails;
|
||||
import org.whispersystems.textsecuregcm.purchases.PaymentMethod;
|
||||
import org.whispersystems.textsecuregcm.purchases.ReceiptLevel;
|
||||
import org.whispersystems.textsecuregcm.purchases.SubscriptionCurrencyUtil;
|
||||
|
||||
public class OneTimeDonationUtil {
|
||||
|
||||
@@ -49,6 +49,8 @@ public class OneTimeDonationUtil {
|
||||
|
||||
}
|
||||
|
||||
/// Validates a request is for a valid one-time donation level and is at least the configured minimum for the currency
|
||||
/// and payment method.
|
||||
public static OneTimeDonationRequestValidationResult validateOneTimeDonationRequest(
|
||||
final String currency,
|
||||
final long amount,
|
||||
@@ -92,7 +94,7 @@ public class OneTimeDonationUtil {
|
||||
// independently.
|
||||
final Locale locale = SubscriptionsUtil.getPayPalLocale(acceptableLocales);
|
||||
final String localizedLineItemName = payPalDonationsTranslator.translate(acceptableLocales,
|
||||
org.whispersystems.textsecuregcm.subscriptions.PayPalDonationsTranslator.ONE_TIME_DONATION_LINE_ITEM_KEY);
|
||||
org.whispersystems.textsecuregcm.purchases.PayPalDonationsTranslator.ONE_TIME_DONATION_LINE_ITEM_KEY);
|
||||
return new LocalizedPayPalDonationLineItem(locale, localizedLineItemName);
|
||||
}
|
||||
|
||||
|
||||
+30
-36
@@ -17,7 +17,6 @@ import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Optional;
|
||||
import org.signal.chat.errors.FailedPrecondition;
|
||||
import org.signal.chat.errors.FailedZkAuthentication;
|
||||
import org.signal.chat.errors.NotFound;
|
||||
@@ -31,7 +30,6 @@ import org.signal.chat.purchase.CreateBoostRequest;
|
||||
import org.signal.chat.purchase.CreateBoostResponse;
|
||||
import org.signal.chat.purchase.CreatePayPalBoostRequest;
|
||||
import org.signal.chat.purchase.CreatePayPalBoostResponse;
|
||||
import org.signal.chat.purchase.PaymentRequired;
|
||||
import org.signal.chat.purchase.SimpleOneTimeDonationsGrpc;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.VerificationFailedException;
|
||||
@@ -43,19 +41,21 @@ import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfigurati
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.purchases.BraintreeManager;
|
||||
import org.whispersystems.textsecuregcm.purchases.PayPalDonationsTranslator;
|
||||
import org.whispersystems.textsecuregcm.purchases.PaymentDetails;
|
||||
import org.whispersystems.textsecuregcm.purchases.PaymentProvider;
|
||||
import org.whispersystems.textsecuregcm.purchases.PurchaseInvalidAmountException;
|
||||
import org.whispersystems.textsecuregcm.purchases.PurchaseNotFoundException;
|
||||
import org.whispersystems.textsecuregcm.purchases.PurchasePaymentRequiredException;
|
||||
import org.whispersystems.textsecuregcm.purchases.PurchaseProcessorException;
|
||||
import org.whispersystems.textsecuregcm.purchases.PurchaseReceiptRequestedForOpenPaymentException;
|
||||
import org.whispersystems.textsecuregcm.purchases.StripeManager;
|
||||
import org.whispersystems.textsecuregcm.purchases.SubscriptionCurrencyUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.DonationPermitsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.IssuedReceiptsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.OneTimeDonationsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.WriteConflictException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.BraintreeManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PayPalDonationsTranslator;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentDetails;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentStatus;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.StripeManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionCurrencyUtil;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidAmountException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorException;
|
||||
|
||||
public class OneTimeDonationsGrpcService extends SimpleOneTimeDonationsGrpc.OneTimeDonationsImplBase {
|
||||
|
||||
@@ -115,11 +115,11 @@ public class OneTimeDonationsGrpcService extends SimpleOneTimeDonationsGrpc.OneT
|
||||
.build();
|
||||
}
|
||||
|
||||
final org.whispersystems.textsecuregcm.subscriptions.PaymentMethod paymentMethod =
|
||||
final org.whispersystems.textsecuregcm.purchases.PaymentMethod paymentMethod =
|
||||
switch (request.getPaymentMethod()) {
|
||||
case PAYMENT_METHOD_CARD -> org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.CARD;
|
||||
case PAYMENT_METHOD_SEPA_DEBIT -> org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.SEPA_DEBIT;
|
||||
case PAYMENT_METHOD_IDEAL -> org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.IDEAL;
|
||||
case PAYMENT_METHOD_CARD -> org.whispersystems.textsecuregcm.purchases.PaymentMethod.CARD;
|
||||
case PAYMENT_METHOD_SEPA_DEBIT -> org.whispersystems.textsecuregcm.purchases.PaymentMethod.SEPA_DEBIT;
|
||||
case PAYMENT_METHOD_IDEAL -> org.whispersystems.textsecuregcm.purchases.PaymentMethod.IDEAL;
|
||||
default -> throw GrpcExceptions.fieldViolation("payment_method", "Unsupported payment method");
|
||||
};
|
||||
|
||||
@@ -157,7 +157,7 @@ public class OneTimeDonationsGrpcService extends SimpleOneTimeDonationsGrpc.OneT
|
||||
request.getCurrency(), request.getAmount(), request.getLevel(),
|
||||
getClientPlatform(RequestAttributesUtil.getUserAgent().orElse(null)));
|
||||
yield CreateBoostResponse.newBuilder().setClientSecret(paymentIntent.getClientSecret()).build();
|
||||
} catch (final SubscriptionInvalidAmountException e) {
|
||||
} catch (final PurchaseInvalidAmountException e) {
|
||||
yield CreateBoostResponse.newBuilder()
|
||||
.setInvalidAmount(FailedPrecondition.newBuilder()
|
||||
.setDescription(e.getErrorCode()).build())
|
||||
@@ -175,7 +175,7 @@ public class OneTimeDonationsGrpcService extends SimpleOneTimeDonationsGrpc.OneT
|
||||
request.getCurrency(),
|
||||
request.getAmount(),
|
||||
request.getLevel(),
|
||||
org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.PAYPAL,
|
||||
org.whispersystems.textsecuregcm.purchases.PaymentMethod.PAYPAL,
|
||||
oneTimeDonationConfiguration,
|
||||
braintreeManager);
|
||||
|
||||
@@ -221,7 +221,7 @@ public class OneTimeDonationsGrpcService extends SimpleOneTimeDonationsGrpc.OneT
|
||||
request.getCurrency(),
|
||||
request.getAmount(),
|
||||
request.getLevel(),
|
||||
org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.PAYPAL,
|
||||
org.whispersystems.textsecuregcm.purchases.PaymentMethod.PAYPAL,
|
||||
oneTimeDonationConfiguration,
|
||||
braintreeManager);
|
||||
|
||||
@@ -251,7 +251,7 @@ public class OneTimeDonationsGrpcService extends SimpleOneTimeDonationsGrpc.OneT
|
||||
yield ConfirmPayPalBoostResponse.newBuilder()
|
||||
.setResult(ConfirmPayPalBoostResponse.ConfirmPayPalBoostResult.newBuilder()
|
||||
.setPaymentId(chargeSuccessDetails.paymentId()).build()).build();
|
||||
} catch (final SubscriptionProcessorException e) {
|
||||
} catch (final PurchaseProcessorException e) {
|
||||
yield ConfirmPayPalBoostResponse.newBuilder()
|
||||
.setChargeFailure(SubscriptionsUtil.toChargeFailure(e.getProcessor(), e.getChargeFailure()))
|
||||
.build();
|
||||
@@ -267,28 +267,22 @@ public class OneTimeDonationsGrpcService extends SimpleOneTimeDonationsGrpc.OneT
|
||||
final PaymentProvider processor = PaymentProvider.fromProto(request.getProcessor())
|
||||
.orElseThrow(() -> GrpcExceptions.fieldViolation("processor", "Unsupported payment processor"));
|
||||
|
||||
final Optional<PaymentDetails> maybePaymentDetails = switch (processor) {
|
||||
case STRIPE -> stripeManager.claimOneTimePurchase(request.getPaymentIntentId());
|
||||
case BRAINTREE -> braintreeManager.claimOneTimePurchase(request.getPaymentIntentId());
|
||||
default -> throw GrpcExceptions.fieldViolation("processor", "Unsupported payment processor");
|
||||
};
|
||||
|
||||
if (maybePaymentDetails.isEmpty()) {
|
||||
final PaymentDetails paymentDetails;
|
||||
try {
|
||||
paymentDetails = switch (processor) {
|
||||
case STRIPE -> stripeManager.claimOneTimePurchase(request.getPaymentIntentId());
|
||||
case BRAINTREE -> braintreeManager.claimOneTimePurchase(request.getPaymentIntentId());
|
||||
default -> throw GrpcExceptions.fieldViolation("processor", "Unsupported payment processor");
|
||||
};
|
||||
} catch (PurchaseNotFoundException _) {
|
||||
return CreateBoostReceiptCredentialResponse.newBuilder()
|
||||
.setPaymentNotFound(NotFound.getDefaultInstance()).build();
|
||||
}
|
||||
final PaymentDetails paymentDetails = maybePaymentDetails.get();
|
||||
if (paymentDetails.status() == PaymentStatus.PROCESSING) {
|
||||
} catch (PurchaseReceiptRequestedForOpenPaymentException _) {
|
||||
return CreateBoostReceiptCredentialResponse.newBuilder()
|
||||
.setPaymentStillProcessing(FailedPrecondition.getDefaultInstance()).build();
|
||||
}
|
||||
if (paymentDetails.status() != PaymentStatus.SUCCEEDED) {
|
||||
final PaymentRequired.Builder paymentRequiredBuilder = PaymentRequired.newBuilder();
|
||||
if (paymentDetails.chargeFailure() != null) {
|
||||
paymentRequiredBuilder.setChargeFailure(toChargeFailure(processor, paymentDetails.chargeFailure()));
|
||||
}
|
||||
} catch (PurchasePaymentRequiredException e) {
|
||||
return CreateBoostReceiptCredentialResponse.newBuilder()
|
||||
.setPaymentRequired(paymentRequiredBuilder).build();
|
||||
.setPaymentRequired(SubscriptionsUtil.toPaymentRequired(e)).build();
|
||||
}
|
||||
|
||||
final OneTimeDonationUtil.DonationLevelDetails levelDetails;
|
||||
|
||||
+5
-5
@@ -16,10 +16,10 @@ import org.signal.chat.purchase.SimpleProductConfigurationGrpc;
|
||||
import org.whispersystems.textsecuregcm.configuration.LoginPurchaseConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.SubscriptionConfiguration;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.CustomerAwareSubscriptionPaymentProcessor;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentMethod;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionCurrencyUtil;
|
||||
import org.whispersystems.textsecuregcm.purchases.CustomerAwareSubscriptionPaymentProcessor;
|
||||
import org.whispersystems.textsecuregcm.purchases.PaymentMethod;
|
||||
import org.whispersystems.textsecuregcm.purchases.ReceiptLevel;
|
||||
import org.whispersystems.textsecuregcm.purchases.SubscriptionCurrencyUtil;
|
||||
|
||||
public class ProductConfigurationGrpcService extends SimpleProductConfigurationGrpc.ProductConfigurationImplBase {
|
||||
private final GetConfigurationResponse configurationResponse;
|
||||
@@ -103,7 +103,7 @@ public class ProductConfigurationGrpcService extends SimpleProductConfigurationG
|
||||
|
||||
private static CurrencyConfiguration toProtoCurrencyConfiguration(
|
||||
final String currency,
|
||||
final org.whispersystems.textsecuregcm.subscriptions.CurrencyConfiguration config) {
|
||||
final org.whispersystems.textsecuregcm.purchases.CurrencyConfiguration config) {
|
||||
final CurrencyConfiguration.Builder builder = CurrencyConfiguration.newBuilder()
|
||||
.setMinimum(SubscriptionCurrencyUtil.convertPrimaryToMinorUnits(currency, config.minimum()))
|
||||
.addAllSupportedPaymentMethods(config.supportedPaymentMethods().stream()
|
||||
|
||||
+1
-3
@@ -98,9 +98,7 @@ public class RemoteConfigurationGrpcService extends SimpleRemoteConfigurationGrp
|
||||
.setEtag(etag(badges))
|
||||
.build();
|
||||
|
||||
// This could race and multiple threads could decide to build-and-cache. That's fine, they should all calculate
|
||||
// the same etag.
|
||||
localeToBadgesEtag.put(locale, taggedBadges.getEtag());
|
||||
localeToBadgesEtag.computeIfAbsent(locale, _ -> taggedBadges.getEtag());
|
||||
return GetBadgesResponse.newBuilder().setTaggedBadges(taggedBadges).build();
|
||||
}
|
||||
|
||||
|
||||
+52
-59
@@ -28,7 +28,6 @@ import org.signal.chat.purchase.GetReceiptCredentialRequest;
|
||||
import org.signal.chat.purchase.GetReceiptCredentialResponse;
|
||||
import org.signal.chat.purchase.GetSubscriptionInformationRequest;
|
||||
import org.signal.chat.purchase.GetSubscriptionInformationResponse;
|
||||
import org.signal.chat.purchase.PaymentRequired;
|
||||
import org.signal.chat.purchase.SetDefaultPaymentMethodRequest;
|
||||
import org.signal.chat.purchase.SetDefaultPaymentMethodResponse;
|
||||
import org.signal.chat.purchase.SetIapSubscriptionRequest;
|
||||
@@ -50,29 +49,28 @@ import org.whispersystems.textsecuregcm.storage.DonationPermitsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.SubscriberCredentials;
|
||||
import org.whispersystems.textsecuregcm.storage.SubscriptionManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Subscriptions;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.AppleAppStoreManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.BankMandateTranslator;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.BankTransferType;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.BraintreeManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.CustomerAwareSubscriptionPaymentProcessor;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.GooglePlayBillingManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.ProcessorCustomer;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.StripeManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriberIdCreationNotPermittedException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionChargeFailurePaymentRequiredException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionForbiddenException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInformation;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidArgumentsException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidIdempotencyKeyException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidLevelException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionNotFoundException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentRequiredException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentRequiresActionException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorConflictException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptAlreadyRedeemedException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptRequestedForOpenPaymentException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionStatus;
|
||||
import org.whispersystems.textsecuregcm.purchases.AppleAppStoreManager;
|
||||
import org.whispersystems.textsecuregcm.purchases.BankMandateTranslator;
|
||||
import org.whispersystems.textsecuregcm.purchases.BankTransferType;
|
||||
import org.whispersystems.textsecuregcm.purchases.BraintreeManager;
|
||||
import org.whispersystems.textsecuregcm.purchases.CustomerAwareSubscriptionPaymentProcessor;
|
||||
import org.whispersystems.textsecuregcm.purchases.GooglePlayBillingManager;
|
||||
import org.whispersystems.textsecuregcm.purchases.ProcessorCustomer;
|
||||
import org.whispersystems.textsecuregcm.purchases.StripeManager;
|
||||
import org.whispersystems.textsecuregcm.purchases.SubscriberIdCreationNotPermittedException;
|
||||
import org.whispersystems.textsecuregcm.purchases.PurchaseForbiddenException;
|
||||
import org.whispersystems.textsecuregcm.purchases.SubscriptionInformation;
|
||||
import org.whispersystems.textsecuregcm.purchases.PurchaseInvalidArgumentsException;
|
||||
import org.whispersystems.textsecuregcm.purchases.PurchaseInvalidIdempotencyKeyException;
|
||||
import org.whispersystems.textsecuregcm.purchases.PurchaseInvalidLevelException;
|
||||
import org.whispersystems.textsecuregcm.purchases.PurchaseNotFoundException;
|
||||
import org.whispersystems.textsecuregcm.purchases.PurchasePaymentRequiredException;
|
||||
import org.whispersystems.textsecuregcm.purchases.PurchasePaymentRequiresActionException;
|
||||
import org.whispersystems.textsecuregcm.purchases.PurchaseProcessorConflictException;
|
||||
import org.whispersystems.textsecuregcm.purchases.PurchaseProcessorException;
|
||||
import org.whispersystems.textsecuregcm.purchases.PurchaseReceiptAlreadyRedeemedException;
|
||||
import org.whispersystems.textsecuregcm.purchases.PurchaseReceiptRequestedForOpenPaymentException;
|
||||
import org.whispersystems.textsecuregcm.purchases.SubscriptionStatus;
|
||||
|
||||
public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.SubscriptionsImplBase {
|
||||
|
||||
@@ -139,7 +137,7 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
|
||||
|
||||
subscriptionManager.updateSubscriber(subscriberCredentials, creationPermitted);
|
||||
return UpdateSubscriberResponse.newBuilder().setSuccess(Empty.getDefaultInstance()).build();
|
||||
} catch (final SubscriptionForbiddenException _) {
|
||||
} catch (final PurchaseForbiddenException _) {
|
||||
throw GrpcExceptions.invalidArguments("subscriber-ids must be randomly generated");
|
||||
} catch (SubscriberIdCreationNotPermittedException _) {
|
||||
if (request.getDonationPermit().isEmpty()) {
|
||||
@@ -163,9 +161,9 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
|
||||
request.getSubscriberId().toByteArray(), clock);
|
||||
subscriptionManager.deleteSubscriber(subscriberCredentials);
|
||||
return DeleteSubscriberResponse.newBuilder().setSuccess(Empty.getDefaultInstance()).build();
|
||||
} catch (final SubscriptionNotFoundException e) {
|
||||
} catch (final PurchaseNotFoundException e) {
|
||||
return DeleteSubscriberResponse.newBuilder().setSubscriberNotFound(NotFound.newBuilder().build()).build();
|
||||
} catch (final SubscriptionInvalidArgumentsException e) {
|
||||
} catch (final PurchaseInvalidArgumentsException e) {
|
||||
return DeleteSubscriberResponse.newBuilder().setCannotCancelSubscription(
|
||||
FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
|
||||
}
|
||||
@@ -204,9 +202,9 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
|
||||
return CreatePaymentMethodResponse.newBuilder().setResult(
|
||||
CreatePaymentMethodResponse.CreatePaymentMethodResult.newBuilder().setClientSecret(token)
|
||||
.setPaymentProvider(customerAwareSubscriptionPaymentProcessor.getProvider().toProto()).build()).build();
|
||||
} catch (final SubscriptionNotFoundException | SubscriptionForbiddenException _) {
|
||||
} catch (final PurchaseNotFoundException | PurchaseForbiddenException _) {
|
||||
return CreatePaymentMethodResponse.newBuilder().setSubscriberNotFound(NotFound.newBuilder()).build();
|
||||
} catch (final SubscriptionProcessorConflictException e) {
|
||||
} catch (final PurchaseProcessorConflictException e) {
|
||||
return CreatePaymentMethodResponse.newBuilder().setSubscriptionProcessorConflict(
|
||||
FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
|
||||
}
|
||||
@@ -226,10 +224,10 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
|
||||
return CreatePayPalPaymentMethodResponse.newBuilder().setResult(
|
||||
CreatePayPalPaymentMethodResponse.CreatePayPalPaymentMethodResult.newBuilder()
|
||||
.setApprovalUrl(details.approvalUrl()).setToken(details.billingAgreementToken()).build()).build();
|
||||
} catch (final SubscriptionNotFoundException | SubscriptionForbiddenException _) {
|
||||
} catch (final PurchaseNotFoundException | PurchaseForbiddenException _) {
|
||||
return CreatePayPalPaymentMethodResponse.newBuilder().setSubscriberNotFound(NotFound.newBuilder().build())
|
||||
.build();
|
||||
} catch (final SubscriptionProcessorConflictException e) {
|
||||
} catch (final PurchaseProcessorConflictException e) {
|
||||
return CreatePayPalPaymentMethodResponse.newBuilder().setSubscriptionProcessorConflict(
|
||||
FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
|
||||
}
|
||||
@@ -267,9 +265,9 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
|
||||
.orElseGet(() -> SetDefaultPaymentMethodResponse.newBuilder()
|
||||
.setPaymentMethodNotSetUp(FailedPrecondition.newBuilder().build())
|
||||
.build());
|
||||
} catch (final SubscriptionNotFoundException | SubscriptionForbiddenException _) {
|
||||
} catch (final PurchaseNotFoundException | PurchaseForbiddenException _) {
|
||||
return SetDefaultPaymentMethodResponse.newBuilder().setSubscriberNotFound(NotFound.newBuilder().build()).build();
|
||||
} catch (final SubscriptionProcessorConflictException _) {
|
||||
} catch (final PurchaseProcessorConflictException _) {
|
||||
return SetDefaultPaymentMethodResponse.newBuilder()
|
||||
.setPaymentMethodNotSetUp(FailedPrecondition.newBuilder().build())
|
||||
.build();
|
||||
@@ -282,7 +280,7 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
|
||||
try {
|
||||
processor.setDefaultPaymentMethodForCustomer(processorCustomer.customerId(), paymentMethodId, subscriptionId);
|
||||
return SetDefaultPaymentMethodResponse.newBuilder().setSuccess(Empty.getDefaultInstance()).build();
|
||||
} catch (final SubscriptionInvalidArgumentsException e) {
|
||||
} catch (final PurchaseInvalidArgumentsException e) {
|
||||
// Here, invalid arguments must mean that the client has made requests out of order, and needs to finish
|
||||
// setting up the paymentMethod first
|
||||
return SetDefaultPaymentMethodResponse.newBuilder()
|
||||
@@ -306,7 +304,7 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
|
||||
.setPaymentMethodNotSetUp(FailedPrecondition.newBuilder().build())
|
||||
.build());
|
||||
|
||||
} catch (final SubscriptionNotFoundException | SubscriptionForbiddenException _) {
|
||||
} catch (final PurchaseNotFoundException | PurchaseForbiddenException _) {
|
||||
return SetSubscriptionLevelResponse.newBuilder().setSubscriberNotFound(NotFound.newBuilder().build()).build();
|
||||
}
|
||||
}
|
||||
@@ -343,25 +341,24 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
|
||||
subscriptionManager.updateSubscriptionLevelForCustomer(subscriberCredentials, subscriptionRecord, manager,
|
||||
request.getLevel(), request.getCurrency(), request.getIdempotencyKey(), templateId.get(),
|
||||
(l1, l2) -> SubscriptionsUtil.subscriptionsAreSameType(subscriptionConfiguration, l1, l2));
|
||||
return SetSubscriptionLevelResponse.newBuilder().setSuccess(
|
||||
SetSubscriptionLevelResponse.SetSubscriptionLevelResult.newBuilder().setLevel(request.getLevel()).build())
|
||||
return SetSubscriptionLevelResponse.newBuilder().setSuccess(Empty.getDefaultInstance())
|
||||
.build();
|
||||
} catch (final SubscriptionInvalidIdempotencyKeyException e) {
|
||||
} catch (final PurchaseInvalidIdempotencyKeyException e) {
|
||||
return SetSubscriptionLevelResponse.newBuilder()
|
||||
.setInvalidIdempotencyKey(FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build())
|
||||
.build();
|
||||
} catch (final SubscriptionProcessorException e) {
|
||||
} catch (final PurchaseProcessorException e) {
|
||||
return SetSubscriptionLevelResponse.newBuilder()
|
||||
.setChargeFailure(SubscriptionsUtil.toChargeFailure(e.getProcessor(), e.getChargeFailure())).build();
|
||||
} catch (final SubscriptionPaymentRequiresActionException e) {
|
||||
} catch (final PurchasePaymentRequiresActionException e) {
|
||||
return SetSubscriptionLevelResponse.newBuilder().setPaymentRequiresAction(FailedPrecondition.newBuilder().build())
|
||||
.build();
|
||||
} catch (final SubscriptionInvalidLevelException e) {
|
||||
} catch (final PurchaseInvalidLevelException e) {
|
||||
return SetSubscriptionLevelResponse.newBuilder()
|
||||
.setInvalidLevelTransition(FailedPrecondition.newBuilder().build()).build();
|
||||
} catch (final SubscriptionProcessorConflictException e) {
|
||||
return SetSubscriptionLevelResponse.newBuilder().setSubscriptionProcessorConflict(
|
||||
FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
|
||||
} catch (final PurchaseProcessorConflictException e) {
|
||||
// We just looked up the subscription processor from the database, a conflict is not possible
|
||||
throw new IllegalStateException(e);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -382,15 +379,15 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
|
||||
};
|
||||
return SetIapSubscriptionResponse.newBuilder()
|
||||
.setSuccess(SetIapSubscriptionResponse.SetIapSubscriptionResult.newBuilder().setLevel(level).build()).build();
|
||||
} catch (final SubscriptionNotFoundException | SubscriptionForbiddenException _) {
|
||||
} catch (final PurchaseNotFoundException | PurchaseForbiddenException _) {
|
||||
return SetIapSubscriptionResponse.newBuilder().setSubscriberNotFound(NotFound.newBuilder().build()).build();
|
||||
} catch (final SubscriptionProcessorConflictException e) {
|
||||
} catch (final PurchaseProcessorConflictException e) {
|
||||
return SetIapSubscriptionResponse.newBuilder().setSubscriptionProcessorConflict(
|
||||
FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
|
||||
} catch (final SubscriptionPaymentRequiredException e) {
|
||||
} catch (final PurchasePaymentRequiredException e) {
|
||||
return SetIapSubscriptionResponse.newBuilder().setPaymentRequired(FailedPrecondition.newBuilder().build())
|
||||
.build();
|
||||
} catch (final SubscriptionInvalidArgumentsException e) {
|
||||
} catch (final PurchaseInvalidArgumentsException e) {
|
||||
return SetIapSubscriptionResponse.newBuilder()
|
||||
.setInvalidTransaction(FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build())
|
||||
.build();
|
||||
@@ -407,7 +404,7 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
|
||||
.map(SubscriptionsGrpcService::buildSubscriptionInformationResponse).orElseGet(
|
||||
() -> GetSubscriptionInformationResponse.newBuilder().setNoSubscription(Empty.getDefaultInstance())
|
||||
.build());
|
||||
} catch (final SubscriptionNotFoundException | SubscriptionForbiddenException _) {
|
||||
} catch (final PurchaseNotFoundException | PurchaseForbiddenException _) {
|
||||
return GetSubscriptionInformationResponse.newBuilder().setSubscriberNotFound(NotFound.newBuilder().build())
|
||||
.build();
|
||||
}
|
||||
@@ -455,22 +452,18 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
|
||||
GetReceiptCredentialResponse.GetReceiptCredentialResult.newBuilder()
|
||||
.setReceiptCredentialResponse(ByteString.copyFrom(result.receiptCredentialResponse().serialize()))
|
||||
.build()).build();
|
||||
} catch (final SubscriptionReceiptRequestedForOpenPaymentException e) {
|
||||
} catch (final PurchaseReceiptRequestedForOpenPaymentException e) {
|
||||
return GetReceiptCredentialResponse.newBuilder().setNoPaidInvoice(FailedPrecondition.newBuilder().build())
|
||||
.build();
|
||||
} catch (final SubscriptionChargeFailurePaymentRequiredException e) {
|
||||
return GetReceiptCredentialResponse.newBuilder().setPaymentRequired(
|
||||
PaymentRequired.newBuilder()
|
||||
.setChargeFailure(SubscriptionsUtil.toChargeFailure(e.getProcessor(), e.getChargeFailure())).build()).build();
|
||||
} catch (final SubscriptionPaymentRequiredException e) {
|
||||
} catch (final PurchasePaymentRequiredException e) {
|
||||
return GetReceiptCredentialResponse.newBuilder()
|
||||
.setPaymentRequired(PaymentRequired.newBuilder().build()).build();
|
||||
} catch (final SubscriptionInvalidArgumentsException e) {
|
||||
.setPaymentRequired(SubscriptionsUtil.toPaymentRequired(e)).build();
|
||||
} catch (final PurchaseInvalidArgumentsException e) {
|
||||
throw GrpcExceptions.invalidArguments(e.errorDetail().orElse(""));
|
||||
} catch (final SubscriptionReceiptAlreadyRedeemedException e) {
|
||||
} catch (final PurchaseReceiptAlreadyRedeemedException e) {
|
||||
return GetReceiptCredentialResponse.newBuilder().setAlreadyRedeemed(FailedPrecondition.newBuilder().build())
|
||||
.build();
|
||||
} catch (final SubscriptionNotFoundException | SubscriptionForbiddenException _) {
|
||||
} catch (final PurchaseNotFoundException | PurchaseForbiddenException _) {
|
||||
return GetReceiptCredentialResponse.newBuilder().setSubscriberNotFound(NotFound.newBuilder().build()).build();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
import javax.annotation.Nullable;
|
||||
import org.signal.chat.purchase.PaymentRequired;
|
||||
import org.signal.libsignal.zkgroup.VerificationFailedException;
|
||||
import org.signal.libsignal.zkgroup.donation.DonationPermit;
|
||||
import org.whispersystems.textsecuregcm.badges.BadgeTranslator;
|
||||
@@ -25,13 +26,14 @@ import org.whispersystems.textsecuregcm.entities.PurchasableBadge;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.DonationPermitsManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.ChargeFailure;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.CurrencyConfiguration;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.CustomerAwareSubscriptionPaymentProcessor;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.LevelConfiguration;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentMethod;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel;
|
||||
import org.whispersystems.textsecuregcm.purchases.ChargeFailure;
|
||||
import org.whispersystems.textsecuregcm.purchases.CurrencyConfiguration;
|
||||
import org.whispersystems.textsecuregcm.purchases.CustomerAwareSubscriptionPaymentProcessor;
|
||||
import org.whispersystems.textsecuregcm.purchases.LevelConfiguration;
|
||||
import org.whispersystems.textsecuregcm.purchases.PaymentMethod;
|
||||
import org.whispersystems.textsecuregcm.purchases.PaymentProvider;
|
||||
import org.whispersystems.textsecuregcm.purchases.PurchasePaymentRequiredException;
|
||||
import org.whispersystems.textsecuregcm.purchases.ReceiptLevel;
|
||||
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
|
||||
import org.whispersystems.textsecuregcm.util.ua.UnrecognizedUserAgentException;
|
||||
import org.whispersystems.textsecuregcm.util.ua.UserAgentUtil;
|
||||
@@ -163,6 +165,12 @@ public class SubscriptionsUtil {
|
||||
.increment();
|
||||
}
|
||||
|
||||
public static PaymentRequired toPaymentRequired(final PurchasePaymentRequiredException e) {
|
||||
final PaymentRequired.Builder builder = PaymentRequired.newBuilder();
|
||||
e.getChargeFailure().ifPresent(chargeFailure -> builder.setChargeFailure(toChargeFailure(e.getProcessor(), chargeFailure)));
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
public static org.signal.chat.purchase.ChargeFailure toChargeFailure(final PaymentProvider processor,
|
||||
final ChargeFailure chargeFailure) {
|
||||
final org.signal.chat.purchase.ChargeFailure.Builder builder = org.signal.chat.purchase.ChargeFailure.newBuilder()
|
||||
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.grpc.net;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.netty.handler.ssl.OpenSsl;
|
||||
import java.net.Socket;
|
||||
import java.security.Principal;
|
||||
import java.security.PrivateKey;
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.util.Arrays;
|
||||
import java.util.Optional;
|
||||
import javax.net.ssl.ExtendedSSLSession;
|
||||
import javax.net.ssl.KeyManager;
|
||||
import javax.net.ssl.SSLEngine;
|
||||
import javax.net.ssl.X509ExtendedKeyManager;
|
||||
|
||||
/// A server key manager for netty's BoringSSL provider that uses a client's signature algorithm preferences, enabling
|
||||
/// support for ed25519.
|
||||
///
|
||||
/// This works around [netty#17690](https://github.com/netty/netty/issues/17690):
|
||||
/// netty’s engine only asks the key manager for RSA- and EC-family key types, so it never selects an Ed25519 key.
|
||||
class BoringSslServerKeyManager extends X509ExtendedKeyManager {
|
||||
|
||||
private final X509ExtendedKeyManager delegate;
|
||||
|
||||
@VisibleForTesting
|
||||
BoringSslServerKeyManager(final X509ExtendedKeyManager delegate) {
|
||||
if (!"BoringSSL".equals(OpenSsl.versionString())) {
|
||||
throw new IllegalStateException("BoringSSL required, found " + OpenSsl.versionString());
|
||||
}
|
||||
this.delegate = delegate;
|
||||
}
|
||||
|
||||
/// @throws IllegalArgumentException if `keyManagers` contains no [X509ExtendedKeyManager]
|
||||
static BoringSslServerKeyManager wrap(final KeyManager[] keyManagers) {
|
||||
return Arrays.stream(keyManagers)
|
||||
.filter(X509ExtendedKeyManager.class::isInstance)
|
||||
.map(X509ExtendedKeyManager.class::cast)
|
||||
.findFirst()
|
||||
.map(BoringSslServerKeyManager::new)
|
||||
.orElseThrow(() -> new IllegalArgumentException("No X509ExtendedKeyManager found"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public String chooseEngineServerAlias(final String keyType, final Principal[] issuers, final SSLEngine engine) {
|
||||
if (!(engine.getHandshakeSession() instanceof ExtendedSSLSession session)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Netty will only call this with EC/RSA key types (https://github.com/netty/netty/issues/17690).
|
||||
// We can safely ignore `keyType` and loop through the peer's signature algorithms to find the best matching key.
|
||||
for (final String signatureAlgorithm : session.getPeerSupportedSignatureAlgorithms()) {
|
||||
final Optional<String> maybeAlias = getJdkKeyType(signatureAlgorithm)
|
||||
.map(jdkKeyType -> delegate.chooseEngineServerAlias(jdkKeyType, issuers, engine));
|
||||
|
||||
if (maybeAlias.isPresent()) {
|
||||
return maybeAlias.get();
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// Maps a JDK signature algorithm name to the JDK key type that can produce it
|
||||
@VisibleForTesting
|
||||
static Optional<String> getJdkKeyType(final String signatureAlgorithm) {
|
||||
if (signatureAlgorithm.equals("Ed25519")) {
|
||||
return Optional.of("EdDSA");
|
||||
} else if (signatureAlgorithm.endsWith("withECDSA")) {
|
||||
return Optional.of("EC");
|
||||
} else if (signatureAlgorithm.endsWith("withRSA")) {
|
||||
return Optional.of("RSA");
|
||||
}
|
||||
|
||||
// We don't need to be exhaustive, because we require TLS 1.3 and only use a limited number of key types.
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String chooseServerAlias(final String keyType, final Principal[] issuers, final Socket socket) {
|
||||
return delegate.chooseServerAlias(keyType, issuers, socket);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String[] getServerAliases(final String keyType, final Principal[] issuers) {
|
||||
return delegate.getServerAliases(keyType, issuers);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String chooseClientAlias(final String[] keyTypes, final Principal[] issuers, final Socket socket) {
|
||||
return delegate.chooseClientAlias(keyTypes, issuers, socket);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String[] getClientAliases(final String keyType, final Principal[] issuers) {
|
||||
return delegate.getClientAliases(keyType, issuers);
|
||||
}
|
||||
|
||||
@Override
|
||||
public X509Certificate[] getCertificateChain(final String alias) {
|
||||
return delegate.getCertificateChain(alias);
|
||||
}
|
||||
|
||||
@Override
|
||||
public PrivateKey getPrivateKey(final String alias) {
|
||||
return delegate.getPrivateKey(alias);
|
||||
}
|
||||
}
|
||||
@@ -7,8 +7,10 @@ package org.whispersystems.textsecuregcm.grpc.net;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.netty.handler.ssl.ApplicationProtocolConfig;
|
||||
import io.netty.handler.ssl.ApplicationProtocolNames;
|
||||
import io.netty.handler.ssl.OpenSsl;
|
||||
import io.netty.handler.ssl.SslContext;
|
||||
import io.netty.handler.ssl.SslContextBuilder;
|
||||
import io.netty.handler.ssl.SslProvider;
|
||||
import io.netty.util.Mapping;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
@@ -49,25 +51,35 @@ public class SniMapper {
|
||||
///
|
||||
/// @param keyStorePath The path to the [KeyStore]
|
||||
/// @param keyStorePassword The password for the keyStore
|
||||
/// @param sslProvider The TLS implementation to use
|
||||
/// @return A [Mapping] that maps domains to the corresponding [SslContext] containing the certificates for that
|
||||
/// domain
|
||||
public static Mapping<String, SslContext> buildSniMapping(final String keyStorePath, final String keyStorePassword)
|
||||
throws IOException {
|
||||
public static Mapping<String, SslContext> buildSniMapping(final String keyStorePath, final String keyStorePassword,
|
||||
final SslProvider sslProvider) throws IOException {
|
||||
try (final FileInputStream fis = new FileInputStream(keyStorePath)) {
|
||||
return buildSniMapping(fis, keyStorePassword);
|
||||
return buildSniMapping(fis, keyStorePassword, sslProvider);
|
||||
}
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static Mapping<String, SslContext> buildSniMapping(final InputStream keyStore, final String keyStorePassword)
|
||||
throws IOException {
|
||||
static Mapping<String, SslContext> buildSniMapping(final InputStream keyStore, final String keyStorePassword,
|
||||
final SslProvider sslProvider) throws IOException {
|
||||
|
||||
if (sslProvider != SslProvider.JDK && sslProvider != SslProvider.OPENSSL) {
|
||||
throw new IllegalArgumentException("Unsupported SSL provider: " + sslProvider);
|
||||
}
|
||||
|
||||
if (sslProvider == SslProvider.OPENSSL) {
|
||||
OpenSsl.ensureAvailability();
|
||||
}
|
||||
|
||||
try {
|
||||
final Map<String, KeyStore> domainKeyStores = partitionByDomain(keyStore, keyStorePassword.toCharArray());
|
||||
final Map<String, SslContext> sslContextsByDomain = new HashMap<>();
|
||||
for (final Map.Entry<String, KeyStore> entry : domainKeyStores.entrySet()) {
|
||||
final KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
|
||||
kmf.init(entry.getValue(), keyStorePassword.toCharArray());
|
||||
sslContextsByDomain.put(entry.getKey(), buildSslContext(kmf));
|
||||
sslContextsByDomain.put(entry.getKey(), buildSslContext(kmf, sslProvider));
|
||||
}
|
||||
|
||||
// Netty expects the SNI mapping to always return an SslContext. Per RFC-6066 it's valid to continue the handshake
|
||||
@@ -78,15 +90,23 @@ public class SniMapper {
|
||||
.orElseThrow(() -> new IllegalArgumentException("Key store contained no certificates"))
|
||||
.getValue();
|
||||
|
||||
logger.info("Loaded TLS contexts for domains: {}", sslContextsByDomain.keySet());
|
||||
logger.info("Loaded {} TLS contexts for domains: {}", sslProvider, sslContextsByDomain.keySet());
|
||||
return hostname -> sslContextsByDomain.getOrDefault(hostname, defaultSslContext);
|
||||
} catch (NoSuchAlgorithmException | KeyStoreException | CertificateException | UnrecoverableKeyException e) {
|
||||
throw new IOException("Failed to load keystore", e);
|
||||
}
|
||||
}
|
||||
|
||||
private static SslContext buildSslContext(final KeyManagerFactory kmf) throws SSLException {
|
||||
return SslContextBuilder.forServer(kmf)
|
||||
private static SslContext buildSslContext(final KeyManagerFactory kmf, final SslProvider sslProvider)
|
||||
throws SSLException {
|
||||
|
||||
final SslContextBuilder sslContextBuilder = sslProvider == SslProvider.OPENSSL
|
||||
// work around netty's OpenSSL provider not selecting Ed25519 certificates on its own
|
||||
? SslContextBuilder.forServer(BoringSslServerKeyManager.wrap(kmf.getKeyManagers()))
|
||||
: SslContextBuilder.forServer(kmf);
|
||||
|
||||
return sslContextBuilder
|
||||
.sslProvider(sslProvider)
|
||||
.applicationProtocolConfig(new ApplicationProtocolConfig(
|
||||
ApplicationProtocolConfig.Protocol.ALPN,
|
||||
ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE,
|
||||
|
||||
@@ -128,6 +128,10 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
|
||||
return forDescriptor(For.ATTACHMENT_BYTES);
|
||||
}
|
||||
|
||||
public RateLimiter getBackupAuthCheckLimiter() {
|
||||
return forDescriptor(For.BACKUP_AUTH_CHECK);
|
||||
}
|
||||
|
||||
public RateLimiter getPinLimiter() {
|
||||
return forDescriptor(For.PIN);
|
||||
}
|
||||
|
||||
+1
-1
@@ -10,7 +10,7 @@ import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import jakarta.ws.rs.ext.ExceptionMapper;
|
||||
import jakarta.ws.rs.ext.Provider;
|
||||
import org.whispersystems.textsecuregcm.controllers.DeviceLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceLimitExceededException;
|
||||
|
||||
@Provider
|
||||
public class DeviceLimitExceededExceptionMapper implements ExceptionMapper<DeviceLimitExceededException> {
|
||||
|
||||
+24
-25
@@ -12,63 +12,62 @@ import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import jakarta.ws.rs.ext.ExceptionMapper;
|
||||
import java.util.Map;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriberIdCreationNotPermittedException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionChargeFailurePaymentRequiredException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.ChargeFailure;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionForbiddenException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidAmountException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidArgumentsException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionNotFoundException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentRequiredException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorConflictException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptAlreadyRedeemedException;
|
||||
import org.whispersystems.textsecuregcm.purchases.ChargeFailure;
|
||||
import org.whispersystems.textsecuregcm.purchases.PurchaseException;
|
||||
import org.whispersystems.textsecuregcm.purchases.PurchaseForbiddenException;
|
||||
import org.whispersystems.textsecuregcm.purchases.PurchaseInvalidAmountException;
|
||||
import org.whispersystems.textsecuregcm.purchases.PurchaseInvalidArgumentsException;
|
||||
import org.whispersystems.textsecuregcm.purchases.PurchaseNotFoundException;
|
||||
import org.whispersystems.textsecuregcm.purchases.PurchasePaymentRequiredException;
|
||||
import org.whispersystems.textsecuregcm.purchases.PurchaseProcessorConflictException;
|
||||
import org.whispersystems.textsecuregcm.purchases.PurchaseProcessorException;
|
||||
import org.whispersystems.textsecuregcm.purchases.PurchaseReceiptAlreadyRedeemedException;
|
||||
import org.whispersystems.textsecuregcm.purchases.SubscriberIdCreationNotPermittedException;
|
||||
|
||||
public class SubscriptionExceptionMapper implements ExceptionMapper<SubscriptionException> {
|
||||
public class PurchaseExceptionMapper implements ExceptionMapper<PurchaseException> {
|
||||
@VisibleForTesting
|
||||
public static final int PROCESSOR_ERROR_STATUS_CODE = 440;
|
||||
|
||||
public record ChargeFailureResponse(String processor, ChargeFailure chargeFailure) {}
|
||||
|
||||
@Override
|
||||
public Response toResponse(final SubscriptionException exception) {
|
||||
public Response toResponse(final PurchaseException exception) {
|
||||
|
||||
// Some exceptions have specific error body formats
|
||||
if (exception instanceof SubscriptionInvalidAmountException e) {
|
||||
if (exception instanceof PurchaseInvalidAmountException e) {
|
||||
return Response
|
||||
.status(Response.Status.BAD_REQUEST)
|
||||
.entity(Map.of("error", e.getErrorCode()))
|
||||
.type(MediaType.APPLICATION_JSON_TYPE)
|
||||
.build();
|
||||
}
|
||||
if (exception instanceof SubscriptionProcessorException e) {
|
||||
if (exception instanceof PurchaseProcessorException e) {
|
||||
return Response.status(PROCESSOR_ERROR_STATUS_CODE)
|
||||
.entity(new ChargeFailureResponse(e.getProcessor().name(), e.getChargeFailure()))
|
||||
.type(MediaType.APPLICATION_JSON_TYPE)
|
||||
.build();
|
||||
}
|
||||
if (exception instanceof SubscriptionChargeFailurePaymentRequiredException e) {
|
||||
if (exception instanceof PurchasePaymentRequiredException e && e.getChargeFailure().isPresent()) {
|
||||
return Response
|
||||
.status(Response.Status.PAYMENT_REQUIRED)
|
||||
.entity(new ChargeFailureResponse(e.getProcessor().name(), e.getChargeFailure()))
|
||||
.entity(new ChargeFailureResponse(e.getProcessor().name(), e.getChargeFailure().get()))
|
||||
.type(MediaType.APPLICATION_JSON_TYPE)
|
||||
.build();
|
||||
}
|
||||
|
||||
// Otherwise, we'll return a generic error message WebApplicationException, with a detailed error if one is provided
|
||||
final Response.Status status = (switch (exception) {
|
||||
case SubscriptionNotFoundException _ -> Response.Status.NOT_FOUND;
|
||||
case SubscriptionForbiddenException _ -> Response.Status.FORBIDDEN;
|
||||
case SubscriptionInvalidArgumentsException _ -> Response.Status.BAD_REQUEST;
|
||||
case SubscriptionProcessorConflictException _ -> Response.Status.CONFLICT;
|
||||
case SubscriptionPaymentRequiredException _ -> Response.Status.PAYMENT_REQUIRED;
|
||||
case SubscriptionReceiptAlreadyRedeemedException _ -> Response.Status.CONFLICT;
|
||||
case PurchaseNotFoundException _ -> Response.Status.NOT_FOUND;
|
||||
case PurchaseForbiddenException _ -> Response.Status.FORBIDDEN;
|
||||
case PurchaseInvalidArgumentsException _ -> Response.Status.BAD_REQUEST;
|
||||
case PurchaseProcessorConflictException _ -> Response.Status.CONFLICT;
|
||||
case PurchasePaymentRequiredException _ -> Response.Status.PAYMENT_REQUIRED;
|
||||
case PurchaseReceiptAlreadyRedeemedException _ -> Response.Status.CONFLICT;
|
||||
case SubscriberIdCreationNotPermittedException _ -> Response.Status.UNAUTHORIZED;
|
||||
default -> Response.Status.INTERNAL_SERVER_ERROR;
|
||||
});
|
||||
|
||||
// If the SubscriptionException came with suitable error message, include that in the response body. Otherwise,
|
||||
// If the PurchaseException came with suitable error message, include that in the response body. Otherwise,
|
||||
// don't provide any message to the WebApplicationException constructor so the response includes the default
|
||||
// HTTP error message for the status.
|
||||
final WebApplicationException wae = exception.errorDetail()
|
||||
+8
-4
@@ -2,7 +2,7 @@
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
package org.whispersystems.textsecuregcm.purchases;
|
||||
|
||||
import com.apple.itunes.storekit.client.APIError;
|
||||
import com.apple.itunes.storekit.client.APIException;
|
||||
@@ -126,15 +126,15 @@ public class AppleAppStoreClient {
|
||||
}
|
||||
|
||||
public StatusResponse getAllSubscriptions(final String originalTransactionId, final Tags errorTags)
|
||||
throws SubscriptionNotFoundException, SubscriptionInvalidArgumentsException, RateLimitExceededException {
|
||||
throws PurchaseNotFoundException, PurchaseInvalidArgumentsException, RateLimitExceededException {
|
||||
try {
|
||||
return lookupByTransactionId(originalTransactionId, errorTags,
|
||||
(env, txId) -> client(env).getAllSubscriptionStatuses(txId, EMPTY_STATUSES));
|
||||
} catch (APIException e) {
|
||||
switch (e.getApiError()) {
|
||||
case TRANSACTION_ID_NOT_FOUND, ORIGINAL_TRANSACTION_ID_NOT_FOUND, ACCOUNT_NOT_FOUND -> throw new SubscriptionNotFoundException();
|
||||
case TRANSACTION_ID_NOT_FOUND, ORIGINAL_TRANSACTION_ID_NOT_FOUND, ACCOUNT_NOT_FOUND -> throw new PurchaseNotFoundException();
|
||||
case RATE_LIMIT_EXCEEDED -> throw new RateLimitExceededException(null);
|
||||
case INVALID_ORIGINAL_TRANSACTION_ID -> throw new SubscriptionInvalidArgumentsException(e.getApiErrorMessage());
|
||||
case INVALID_ORIGINAL_TRANSACTION_ID -> throw new PurchaseInvalidArgumentsException(e.getApiErrorMessage());
|
||||
case null, default -> throw new UncheckedIOException(new IOException(e));
|
||||
}
|
||||
} catch (IOException e) {
|
||||
@@ -195,6 +195,10 @@ public class AppleAppStoreClient {
|
||||
}
|
||||
}
|
||||
|
||||
Environment getDefaultEnvironment() {
|
||||
return defaultEnvironment;
|
||||
}
|
||||
|
||||
private <T> T lookupByTransactionIdInEnvironment(final Environment env, final String transactionId, final Tags errorTags, final TransactionFinder<T> lookupFunction) throws APIException, IOException {
|
||||
try {
|
||||
return retry.executeCallable(() -> {
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
package org.whispersystems.textsecuregcm.purchases;
|
||||
|
||||
import com.apple.itunes.storekit.model.JWSRenewalInfoDecodedPayload;
|
||||
import com.apple.itunes.storekit.model.JWSTransactionDecodedPayload;
|
||||
+35
-30
@@ -3,7 +3,7 @@
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
package org.whispersystems.textsecuregcm.purchases;
|
||||
|
||||
import com.apple.itunes.storekit.model.AutoRenewStatus;
|
||||
import com.apple.itunes.storekit.model.JWSTransactionDecodedPayload;
|
||||
@@ -66,16 +66,16 @@ public class AppleAppStoreManager implements SubscriptionPaymentProcessor, OneTi
|
||||
* @param originalTransactionId The originalTransactionId associated with the subscription
|
||||
* @return the subscription level of the valid transaction.
|
||||
* @throws RateLimitExceededException If rate-limited
|
||||
* @throws SubscriptionNotFoundException If the provided originalTransactionId was not found
|
||||
* @throws SubscriptionPaymentRequiredException If the originalTransactionId exists but is in a state that does not
|
||||
* @throws PurchaseNotFoundException If the provided originalTransactionId was not found
|
||||
* @throws PurchasePaymentRequiredException If the originalTransactionId exists but is in a state that does not
|
||||
* grant the user an entitlement
|
||||
* @throws SubscriptionInvalidArgumentsException If the transaction is valid but does not contain a subscription
|
||||
* @throws PurchaseInvalidArgumentsException If the transaction is valid but does not contain a subscription
|
||||
*/
|
||||
public Long validateTransaction(final String originalTransactionId)
|
||||
throws SubscriptionInvalidArgumentsException, RateLimitExceededException, SubscriptionNotFoundException, SubscriptionPaymentRequiredException {
|
||||
throws PurchaseInvalidArgumentsException, RateLimitExceededException, PurchaseNotFoundException, PurchasePaymentRequiredException {
|
||||
final AppleAppStoreDecodedTransaction tx = lookupAndValidateTransaction(originalTransactionId, Tags.of(LOOKUP_TYPE_TAG, "validate"));
|
||||
if (!isSubscriptionActive(tx)) {
|
||||
throw new SubscriptionPaymentRequiredException();
|
||||
throw new PurchasePaymentRequiredException(getProvider());
|
||||
}
|
||||
return getLevel(tx.transaction()).getValue();
|
||||
}
|
||||
@@ -90,20 +90,20 @@ public class AppleAppStoreManager implements SubscriptionPaymentProcessor, OneTi
|
||||
*
|
||||
* @param originalTransactionId The originalTransactionId associated with the subscription
|
||||
* @throws RateLimitExceededException If rate-limited
|
||||
* @throws SubscriptionInvalidArgumentsException If the transaction is valid but does not contain a subscription, or
|
||||
* @throws PurchaseInvalidArgumentsException If the transaction is valid but does not contain a subscription, or
|
||||
* the transaction has not already been cancelled with storekit
|
||||
*/
|
||||
@Override
|
||||
public void cancelAllActiveSubscriptions(String originalTransactionId)
|
||||
throws SubscriptionInvalidArgumentsException, RateLimitExceededException {
|
||||
throws PurchaseInvalidArgumentsException, RateLimitExceededException {
|
||||
try {
|
||||
final AppleAppStoreDecodedTransaction tx = lookupSubscription(originalTransactionId, Tags.of(LOOKUP_TYPE_TAG, "cancel"));
|
||||
if (tx.signedTransaction().getStatus() != Status.EXPIRED &&
|
||||
tx.signedTransaction().getStatus() != Status.REVOKED &&
|
||||
tx.renewalInfo().getAutoRenewStatus() != AutoRenewStatus.OFF) {
|
||||
throw new SubscriptionInvalidArgumentsException("must cancel subscription with storekit before deleting");
|
||||
throw new PurchaseInvalidArgumentsException("must cancel subscription with storekit before deleting");
|
||||
}
|
||||
} catch (SubscriptionNotFoundException _) {
|
||||
} catch (PurchaseNotFoundException _) {
|
||||
// If the subscription is not found there is no need to do anything, so we can squash it
|
||||
}
|
||||
// The subscription will not auto-renew, so we can stop tracking it
|
||||
@@ -111,7 +111,7 @@ public class AppleAppStoreManager implements SubscriptionPaymentProcessor, OneTi
|
||||
|
||||
@Override
|
||||
public SubscriptionInformation getSubscriptionInformation(final String originalTransactionId)
|
||||
throws RateLimitExceededException, SubscriptionNotFoundException {
|
||||
throws RateLimitExceededException, PurchaseNotFoundException {
|
||||
final AppleAppStoreDecodedTransaction tx = lookupSubscription(originalTransactionId, Tags.of(LOOKUP_TYPE_TAG, "info"));
|
||||
final SubscriptionStatus status = switch (tx.signedTransaction().getStatus()) {
|
||||
case ACTIVE -> SubscriptionStatus.ACTIVE;
|
||||
@@ -137,10 +137,10 @@ public class AppleAppStoreManager implements SubscriptionPaymentProcessor, OneTi
|
||||
|
||||
@Override
|
||||
public ReceiptItem getReceiptItem(String originalTransactionId)
|
||||
throws RateLimitExceededException, SubscriptionNotFoundException, SubscriptionPaymentRequiredException {
|
||||
throws RateLimitExceededException, PurchaseNotFoundException, PurchasePaymentRequiredException {
|
||||
final AppleAppStoreDecodedTransaction tx = lookupSubscription(originalTransactionId, Tags.of(LOOKUP_TYPE_TAG, "receipt"));
|
||||
if (!isSubscriptionActive(tx)) {
|
||||
throw new SubscriptionPaymentRequiredException();
|
||||
throw new PurchasePaymentRequiredException(getProvider());
|
||||
}
|
||||
|
||||
// A new transactionId might be generated if you restore a subscription on a new device. webOrderLineItemId is
|
||||
@@ -154,48 +154,53 @@ public class AppleAppStoreManager implements SubscriptionPaymentProcessor, OneTi
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<PaymentDetails> claimOneTimePurchase(final String transactionId)
|
||||
throws RateLimitExceededException, SubscriptionInvalidArgumentsException {
|
||||
public PaymentDetails claimOneTimePurchase(final String transactionId)
|
||||
throws RateLimitExceededException, PurchaseInvalidArgumentsException, PurchaseNotFoundException, PurchasePaymentRequiredException {
|
||||
|
||||
final Optional<JWSTransactionDecodedPayload> maybeTransaction =
|
||||
appleAppStoreClient.lookupTransaction(transactionId, Tags.of(LOOKUP_TYPE_TAG, "one_time"));
|
||||
if (maybeTransaction.isEmpty()) {
|
||||
return Optional.empty();
|
||||
throw new PurchaseNotFoundException();
|
||||
}
|
||||
final JWSTransactionDecodedPayload transaction = maybeTransaction.get();
|
||||
|
||||
if (transaction.getType() != Type.CONSUMABLE) {
|
||||
throw new SubscriptionInvalidArgumentsException("transaction is not a consumable one-time purchase");
|
||||
throw new PurchaseInvalidArgumentsException("transaction is not a consumable one-time purchase");
|
||||
}
|
||||
|
||||
final PaymentStatus paymentStatus = transaction.getRevocationDate() == null
|
||||
? PaymentStatus.SUCCEEDED
|
||||
: PaymentStatus.FAILED;
|
||||
if (transaction.getRevocationDate() != null) {
|
||||
throw new PurchasePaymentRequiredException(getProvider());
|
||||
}
|
||||
|
||||
return Optional.of(new PaymentDetails(
|
||||
ReceiptLevel receiptLevel = getLevel(transaction);
|
||||
if (receiptLevel == ReceiptLevel.LOGIN && transaction.getEnvironment() != appleAppStoreClient.getDefaultEnvironment()) {
|
||||
// This is a special case: if we had to resort to the fallback environment to resolve this transaction, we should
|
||||
// mark the purchase to indicate it only gets a restricted entitlement.
|
||||
receiptLevel = ReceiptLevel.LOGIN_SANDBOX;
|
||||
}
|
||||
return new PaymentDetails(
|
||||
Objects.requireNonNull(transaction.getTransactionId()),
|
||||
getLevel(transaction),
|
||||
paymentStatus,
|
||||
transaction.getPurchaseDate() != null ? Instant.ofEpochMilli(transaction.getPurchaseDate()) : null,
|
||||
null));
|
||||
receiptLevel,
|
||||
Instant.ofEpochMilli(transaction.getPurchaseDate()));
|
||||
|
||||
}
|
||||
|
||||
private AppleAppStoreDecodedTransaction lookupSubscription(final String originalTransactionId, final Tags tags)
|
||||
throws RateLimitExceededException, SubscriptionNotFoundException {
|
||||
throws RateLimitExceededException, PurchaseNotFoundException {
|
||||
try {
|
||||
return lookupAndValidateTransaction(originalTransactionId, tags);
|
||||
} catch (SubscriptionInvalidArgumentsException e) {
|
||||
} catch (PurchaseInvalidArgumentsException e) {
|
||||
// Shouldn't happen because we previously validated this transactionId before storing it
|
||||
throw new UncheckedIOException(new IOException(e));
|
||||
}
|
||||
}
|
||||
|
||||
private AppleAppStoreDecodedTransaction lookupAndValidateTransaction(final String originalTransactionId, final Tags errorTags)
|
||||
throws SubscriptionInvalidArgumentsException, RateLimitExceededException, SubscriptionNotFoundException {
|
||||
throws PurchaseInvalidArgumentsException, RateLimitExceededException, PurchaseNotFoundException {
|
||||
final StatusResponse statuses = appleAppStoreClient.getAllSubscriptions(originalTransactionId, errorTags);
|
||||
final SubscriptionGroupIdentifierItem item = statuses.getData().stream()
|
||||
.filter(s -> subscriptionGroupId.equals(s.getSubscriptionGroupIdentifier())).findFirst()
|
||||
.orElseThrow(() -> new SubscriptionInvalidArgumentsException("transaction did not contain a backup subscription", null));
|
||||
.orElseThrow(() -> new PurchaseInvalidArgumentsException("transaction did not contain a backup subscription", null));
|
||||
|
||||
final List<AppleAppStoreDecodedTransaction> txs = item.getLastTransactions().stream()
|
||||
.map(txItem -> appleAppStoreClient.verifySubscription(statuses.getEnvironment(), txItem))
|
||||
@@ -207,7 +212,7 @@ public class AppleAppStoreManager implements SubscriptionPaymentProcessor, OneTi
|
||||
// Get All Subscriptions only requires that the transaction be some transaction associated with the
|
||||
// subscription. This is too flexible, since we'd like to key on the originalTransactionId in the
|
||||
// SubscriptionManager.
|
||||
throw new SubscriptionInvalidArgumentsException("transactionId did not include a paid subscription or the provided transactionId was not an originalTransactionId", null);
|
||||
throw new PurchaseInvalidArgumentsException("transactionId did not include a paid subscription or the provided transactionId was not an originalTransactionId", null);
|
||||
}
|
||||
|
||||
if (txs.size() > 1) {
|
||||
+1
-1
@@ -3,7 +3,7 @@
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
package org.whispersystems.textsecuregcm.purchases;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
+1
-1
@@ -3,7 +3,7 @@
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
package org.whispersystems.textsecuregcm.purchases;
|
||||
|
||||
public enum BankTransferType {
|
||||
SEPA_DEBIT
|
||||
+1
-1
@@ -3,7 +3,7 @@
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
package org.whispersystems.textsecuregcm.purchases;
|
||||
|
||||
import com.apollographql.apollo3.api.ApolloResponse;
|
||||
import com.apollographql.apollo3.api.Operation;
|
||||
+21
-25
@@ -3,7 +3,7 @@
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
package org.whispersystems.textsecuregcm.purchases;
|
||||
|
||||
import com.braintree.graphql.clientoperation.ChargePayPalOneTimePaymentMutation;
|
||||
import com.braintree.graphql.clientoperation.CreatePayPalBillingAgreementMutation;
|
||||
@@ -48,6 +48,7 @@ import org.whispersystems.textsecuregcm.currency.CurrencyConversionManager;
|
||||
import org.whispersystems.textsecuregcm.http.FaultTolerantHttpClient;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.PaymentTime;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.DonationsPubsub;
|
||||
import org.whispersystems.textsecuregcm.util.ExecutorUtil;
|
||||
import org.whispersystems.textsecuregcm.util.GoogleApiUtil;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
@@ -131,14 +132,10 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<PaymentDetails> claimOneTimePurchase(final String paymentId) {
|
||||
public PaymentDetails claimOneTimePurchase(final String paymentId)
|
||||
throws PurchaseNotFoundException, PurchaseReceiptRequestedForOpenPaymentException, PurchasePaymentRequiredException {
|
||||
try {
|
||||
final Transaction transaction = braintreeGateway.transaction().find(paymentId);
|
||||
ChargeFailure chargeFailure = null;
|
||||
if (!getPaymentStatus(transaction.getStatus()).equals(PaymentStatus.SUCCEEDED)) {
|
||||
chargeFailure = createChargeFailure(transaction);
|
||||
}
|
||||
|
||||
final ReceiptLevel level = Optional.ofNullable(transaction.getCustomFields())
|
||||
.map(m -> m.get(BraintreeGraphqlClient.LEVEL_METADATA_NAME))
|
||||
.map(Long::parseLong)
|
||||
@@ -146,14 +143,13 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
|
||||
.orElseThrow(() -> new IllegalStateException(
|
||||
"failed to retrieve level metadata from payment intent %s".formatted(paymentId)));
|
||||
|
||||
return Optional.of(new PaymentDetails(transaction.getGraphQLId(),
|
||||
level,
|
||||
getPaymentStatus(transaction.getStatus()),
|
||||
transaction.getCreatedAt().toInstant(),
|
||||
chargeFailure));
|
||||
|
||||
return switch (getPaymentStatus(transaction.getStatus())) {
|
||||
case SUCCEEDED -> new PaymentDetails(transaction.getGraphQLId(), level, transaction.getCreatedAt().toInstant());
|
||||
case PROCESSING -> throw new PurchaseReceiptRequestedForOpenPaymentException();
|
||||
case UNKNOWN, FAILED -> throw new PurchasePaymentRequiredException(getProvider(), createChargeFailure(transaction));
|
||||
};
|
||||
} catch (final NotFoundException e) {
|
||||
return Optional.empty();
|
||||
throw new PurchaseNotFoundException();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -168,7 +164,7 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
|
||||
|
||||
public PayPalChargeSuccessDetails captureOneTimePayment(final String payerId, final String paymentId,
|
||||
final String paymentToken, final String currency, final long amount, final long level, @Nullable final ClientPlatform clientPlatform)
|
||||
throws SubscriptionProcessorException, IOException {
|
||||
throws PurchaseProcessorException, IOException {
|
||||
final TokenizePayPalOneTimePaymentMutation.TokenizePayPalOneTimePayment response = braintreeGraphqlClient.tokenizePayPalOneTimePayment(
|
||||
payerId, paymentId, paymentToken);
|
||||
final ChargePayPalOneTimePaymentMutation.ChargePaymentMethod chargeResponse = braintreeGraphqlClient.chargeOneTimePayment(
|
||||
@@ -214,7 +210,7 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
|
||||
|
||||
switch (unsuccessfulTx.getProcessorResponseCode()) {
|
||||
case GENERIC_DECLINED_PROCESSOR_CODE, PAYPAL_FUNDING_INSTRUMENT_DECLINED_PROCESSOR_CODE ->
|
||||
throw new SubscriptionProcessorException(getProvider(), createChargeFailure(unsuccessfulTx));
|
||||
throw new PurchaseProcessorException(getProvider(), createChargeFailure(unsuccessfulTx));
|
||||
|
||||
default -> {
|
||||
logger.info("PayPal charge unexpectedly failed: {}", unsuccessfulTx.getProcessorResponseCode());
|
||||
@@ -364,11 +360,11 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
|
||||
@Override
|
||||
public SubscriptionId createSubscription(final String customerId, final String planId, final long level,
|
||||
final long lastSubscriptionCreatedAt)
|
||||
throws SubscriptionProcessorConflictException, SubscriptionProcessorException {
|
||||
throws PurchaseProcessorConflictException, PurchaseProcessorException {
|
||||
|
||||
final com.braintreegateway.PaymentMethod paymentMethod = getDefaultPaymentMethod(customerId);
|
||||
if (paymentMethod == null) {
|
||||
throw new SubscriptionProcessorConflictException();
|
||||
throw new PurchaseProcessorConflictException();
|
||||
}
|
||||
|
||||
final Optional<Subscription> maybeExistingSubscription = paymentMethod.getSubscriptions().stream()
|
||||
@@ -402,7 +398,7 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
|
||||
throw Optional
|
||||
.ofNullable(result.getTarget())
|
||||
.flatMap(subscription -> subscription.getTransactions().stream().findFirst())
|
||||
.map(transaction -> new SubscriptionProcessorException(getProvider(),
|
||||
.map(transaction -> new PurchaseProcessorException(getProvider(),
|
||||
createChargeFailure(transaction)))
|
||||
.orElseThrow(() -> new BraintreeException(result.getMessage()));
|
||||
}
|
||||
@@ -418,7 +414,7 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
|
||||
@Override
|
||||
public CustomerAwareSubscriptionPaymentProcessor.SubscriptionId updateSubscription(final Object subscriptionObj,
|
||||
final String planId, final long level,
|
||||
final String idempotencyKey) throws SubscriptionProcessorConflictException, SubscriptionProcessorException {
|
||||
final String idempotencyKey) throws PurchaseProcessorConflictException, PurchaseProcessorException {
|
||||
|
||||
if (!(subscriptionObj instanceof final Subscription subscription)) {
|
||||
throw new IllegalArgumentException("invalid subscription object: " + subscriptionObj.getClass().getName());
|
||||
@@ -430,7 +426,7 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
|
||||
endSubscription(subscription);
|
||||
|
||||
final Transaction transaction = getLatestTransactionForSubscription(subscription)
|
||||
.orElseThrow(SubscriptionProcessorConflictException::new);
|
||||
.orElseThrow(PurchaseProcessorConflictException::new);
|
||||
|
||||
final Customer customer = transaction.getCustomer();
|
||||
|
||||
@@ -583,17 +579,17 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
|
||||
|
||||
@Override
|
||||
public ReceiptItem getReceiptItem(final String subscriptionId)
|
||||
throws SubscriptionReceiptRequestedForOpenPaymentException, SubscriptionChargeFailurePaymentRequiredException {
|
||||
throws PurchaseReceiptRequestedForOpenPaymentException, PurchasePaymentRequiredException {
|
||||
final Subscription subscription = getSubscription(getSubscription(subscriptionId));
|
||||
final Transaction transaction = getLatestTransactionForSubscription(subscription)
|
||||
.orElseThrow(SubscriptionReceiptRequestedForOpenPaymentException::new);
|
||||
.orElseThrow(PurchaseReceiptRequestedForOpenPaymentException::new);
|
||||
if (!getPaymentStatus(transaction.getStatus()).equals(PaymentStatus.SUCCEEDED)) {
|
||||
final SubscriptionStatus subscriptionStatus = getSubscriptionStatus(subscription.getStatus(), true);
|
||||
if (subscriptionStatus.equals(SubscriptionStatus.ACTIVE) || subscriptionStatus.equals(
|
||||
SubscriptionStatus.PAST_DUE)) {
|
||||
throw new SubscriptionReceiptRequestedForOpenPaymentException();
|
||||
throw new PurchaseReceiptRequestedForOpenPaymentException();
|
||||
}
|
||||
throw new SubscriptionChargeFailurePaymentRequiredException(getProvider(), createChargeFailure(transaction));
|
||||
throw new PurchasePaymentRequiredException(getProvider(), createChargeFailure(transaction));
|
||||
}
|
||||
|
||||
final Instant paidAt = transaction.getSubscriptionDetails().getBillingPeriodStartDate().toInstant();
|
||||
+1
-1
@@ -3,7 +3,7 @@
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
package org.whispersystems.textsecuregcm.purchases;
|
||||
|
||||
public record BraintreePlanMetadata(long level) {
|
||||
|
||||
+1
-1
@@ -3,7 +3,7 @@
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
package org.whispersystems.textsecuregcm.purchases;
|
||||
|
||||
import io.swagger.v3.oas.annotations.ExternalDocumentation;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
package org.whispersystems.textsecuregcm.purchases;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
|
||||
+15
-15
@@ -3,7 +3,7 @@
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
package org.whispersystems.textsecuregcm.purchases;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Set;
|
||||
@@ -41,12 +41,12 @@ public interface CustomerAwareSubscriptionPaymentProcessor extends SubscriptionP
|
||||
* @param paymentMethodToken a processor-specific token previously acquired at
|
||||
* {@link #createPaymentMethodSetupToken}
|
||||
* @param currentSubscriptionId (nullable) an active subscription ID, in case it needs an explicit update
|
||||
* @throws SubscriptionInvalidArgumentsException If the paymentMethodToken is invalid or the payment method has not
|
||||
* @throws PurchaseInvalidArgumentsException If the paymentMethodToken is invalid or the payment method has not
|
||||
* finished being set up
|
||||
* @throws IOException If there was an error talking to the external payment provider
|
||||
*/
|
||||
void setDefaultPaymentMethodForCustomer(String customerId, String paymentMethodToken,
|
||||
@Nullable String currentSubscriptionId) throws SubscriptionInvalidArgumentsException, IOException;
|
||||
@Nullable String currentSubscriptionId) throws PurchaseInvalidArgumentsException, IOException;
|
||||
|
||||
Object getSubscription(String subscriptionId);
|
||||
|
||||
@@ -58,13 +58,13 @@ public interface CustomerAwareSubscriptionPaymentProcessor extends SubscriptionP
|
||||
* @param level The level of the subscription
|
||||
* @param lastSubscriptionCreatedAt The timestamp of the last successfully created subscription
|
||||
* @return A subscription identifier
|
||||
* @throws SubscriptionProcessorException If there was a failure processing the charge
|
||||
* @throws SubscriptionPaymentRequiresActionException If the payment requires additional steps before charging
|
||||
* @throws SubscriptionInvalidIdempotencyKeyException If the idempotency key was reused on a modified request
|
||||
* @throws SubscriptionProcessorConflictException If there was no payment method on the customer
|
||||
* @throws PurchaseProcessorException If there was a failure processing the charge
|
||||
* @throws PurchasePaymentRequiresActionException If the payment requires additional steps before charging
|
||||
* @throws PurchaseInvalidIdempotencyKeyException If the idempotency key was reused on a modified request
|
||||
* @throws PurchaseProcessorConflictException If there was no payment method on the customer
|
||||
*/
|
||||
SubscriptionId createSubscription(String customerId, String templateId, long level, long lastSubscriptionCreatedAt)
|
||||
throws SubscriptionProcessorException, SubscriptionPaymentRequiresActionException, SubscriptionInvalidIdempotencyKeyException, SubscriptionProcessorConflictException;
|
||||
throws PurchaseProcessorException, PurchasePaymentRequiresActionException, PurchaseInvalidIdempotencyKeyException, PurchaseProcessorConflictException;
|
||||
|
||||
/**
|
||||
* Update an existing subscription on a customer
|
||||
@@ -74,15 +74,15 @@ public interface CustomerAwareSubscriptionPaymentProcessor extends SubscriptionP
|
||||
* @param level The target level of the subscription
|
||||
* @param idempotencyKey An idempotency key to prevent retries of successful requests
|
||||
* @return A subscription identifier
|
||||
* @throws SubscriptionProcessorException If there was a failure processing the charge
|
||||
* @throws SubscriptionInvalidIdempotencyKeyException If the idempotency key was reused on a modified request
|
||||
* @throws SubscriptionInvalidLevelException If the level transition is not permitted
|
||||
* @throws SubscriptionPaymentRequiresActionException If the payment requires additional steps before charging
|
||||
* @throws SubscriptionProcessorConflictException If there was no payment method on the customer
|
||||
* @throws PurchaseProcessorException If there was a failure processing the charge
|
||||
* @throws PurchaseInvalidIdempotencyKeyException If the idempotency key was reused on a modified request
|
||||
* @throws PurchaseInvalidLevelException If the level transition is not permitted
|
||||
* @throws PurchasePaymentRequiresActionException If the payment requires additional steps before charging
|
||||
* @throws PurchaseProcessorConflictException If there was no payment method on the customer
|
||||
*/
|
||||
SubscriptionId updateSubscription(Object subscription, String templateId, long level, String idempotencyKey)
|
||||
throws SubscriptionInvalidIdempotencyKeyException, SubscriptionInvalidLevelException,
|
||||
SubscriptionPaymentRequiresActionException, SubscriptionProcessorException, SubscriptionProcessorConflictException;
|
||||
throws PurchaseInvalidIdempotencyKeyException, PurchaseInvalidLevelException,
|
||||
PurchasePaymentRequiresActionException, PurchaseProcessorException, PurchaseProcessorConflictException;
|
||||
|
||||
/**
|
||||
* @param subscription
|
||||
+48
-54
@@ -3,7 +3,7 @@
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
package org.whispersystems.textsecuregcm.purchases;
|
||||
|
||||
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
|
||||
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
|
||||
@@ -132,7 +132,7 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor, O
|
||||
*
|
||||
*/
|
||||
public void acknowledgePurchase()
|
||||
throws RateLimitExceededException, SubscriptionNotFoundException {
|
||||
throws RateLimitExceededException, PurchaseNotFoundException {
|
||||
if (!requiresAck) {
|
||||
// We've already acknowledged this purchase on a previous attempt, nothing to do
|
||||
return;
|
||||
@@ -153,12 +153,12 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor, O
|
||||
* @param purchaseToken The play store billing purchaseToken that represents a subscription purchase
|
||||
* @return A {@link ValidatedToken} that can be acknowledged
|
||||
* @throws RateLimitExceededException If rate-limited by play-billing
|
||||
* @throws SubscriptionNotFoundException If the provided purchaseToken was not found in play-billing
|
||||
* @throws SubscriptionPaymentRequiredException If the purchaseToken exists but is in a state that does not grant the
|
||||
* @throws PurchaseNotFoundException If the provided purchaseToken was not found in play-billing
|
||||
* @throws PurchasePaymentRequiredException If the purchaseToken exists but is in a state that does not grant the
|
||||
* user an entitlement
|
||||
*/
|
||||
public ValidatedToken validateToken(String purchaseToken)
|
||||
throws RateLimitExceededException, SubscriptionNotFoundException, SubscriptionPaymentRequiredException {
|
||||
throws RateLimitExceededException, PurchaseNotFoundException, PurchasePaymentRequiredException {
|
||||
final SubscriptionPurchaseV2 subscription = lookupSubscription(purchaseToken);
|
||||
final SubscriptionState state = SubscriptionState
|
||||
.fromString(subscription.getSubscriptionState())
|
||||
@@ -173,7 +173,7 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor, O
|
||||
if (state != SubscriptionState.ACTIVE
|
||||
&& state != SubscriptionState.IN_GRACE_PERIOD
|
||||
&& state != SubscriptionState.CANCELED) {
|
||||
throw new SubscriptionPaymentRequiredException(
|
||||
throw new PurchasePaymentRequiredException(getProvider(),
|
||||
"Cannot acknowledge purchase for subscription in state " + subscription.getSubscriptionState());
|
||||
}
|
||||
|
||||
@@ -212,14 +212,14 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor, O
|
||||
|
||||
executeTokenOperation(pub ->
|
||||
pub.purchases().subscriptions().cancel(packageName, purchase.getProductId(), purchaseToken));
|
||||
} catch (SubscriptionNotFoundException e) {
|
||||
} catch (PurchaseNotFoundException e) {
|
||||
// If the subscription is not found there is no need to do anything, so we can squash it
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public SubscriptionInformation getSubscriptionInformation(final String purchaseToken)
|
||||
throws RateLimitExceededException, SubscriptionNotFoundException {
|
||||
throws RateLimitExceededException, PurchaseNotFoundException {
|
||||
|
||||
final SubscriptionPurchaseV2 subscription = lookupSubscription(purchaseToken);
|
||||
final SubscriptionPrice price = getSubscriptionPrice(subscription);
|
||||
@@ -275,7 +275,7 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor, O
|
||||
|
||||
@Override
|
||||
public ReceiptItem getReceiptItem(String purchaseToken)
|
||||
throws RateLimitExceededException, SubscriptionNotFoundException, SubscriptionPaymentRequiredException {
|
||||
throws RateLimitExceededException, PurchaseNotFoundException, PurchasePaymentRequiredException {
|
||||
final SubscriptionPurchaseV2 subscription = lookupSubscription(purchaseToken);
|
||||
|
||||
Metrics.counter(GET_RECEIPT_COUNTER_NAME, subscriptionTags(subscription)).increment();
|
||||
@@ -288,7 +288,7 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor, O
|
||||
// We don't need to check any state at this point, just whether the subscription is currently valid. If the
|
||||
// subscription is in a grace period, the expiration time will be dynamically extended, see
|
||||
// https://developer.android.com/google/play/billing/lifecycle/subscriptions#grace-period
|
||||
throw new SubscriptionPaymentRequiredException();
|
||||
throw new PurchasePaymentRequiredException(getProvider());
|
||||
}
|
||||
|
||||
if (requiresAcknowledgement(subscription)) {
|
||||
@@ -318,55 +318,49 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor, O
|
||||
/// will fail, it just means we've told the play store that the purchase is complete. If the client fails after the
|
||||
/// acknowledgement, they can just retry with no issue.
|
||||
@Override
|
||||
public Optional<PaymentDetails> claimOneTimePurchase(final String purchaseToken)
|
||||
throws IOException, RateLimitExceededException, SubscriptionInvalidArgumentsException {
|
||||
try {
|
||||
final ProductPurchaseV2 productPurchaseV2 = executeTokenOperation(
|
||||
public PaymentDetails claimOneTimePurchase(final String purchaseToken)
|
||||
throws IOException, RateLimitExceededException, PurchaseInvalidArgumentsException, PurchaseNotFoundException, PurchasePaymentRequiredException, PurchaseReceiptRequestedForOpenPaymentException {
|
||||
final ProductPurchaseV2 productPurchaseV2 = executeTokenOperation(
|
||||
publisher -> publisher.purchases().productsv2().getproductpurchasev2(packageName, purchaseToken));
|
||||
|
||||
final PaymentStatus paymentStatus = Optional
|
||||
.ofNullable(productPurchaseV2.getPurchaseStateContext())
|
||||
.map(PurchaseStateContext::getPurchaseState)
|
||||
.flatMap(PurchaseState::fromString)
|
||||
.map(purchaseState -> switch (purchaseState) {
|
||||
case PENDING -> PaymentStatus.PROCESSING;
|
||||
case CANCELLED -> PaymentStatus.FAILED;
|
||||
case PURCHASED -> PaymentStatus.SUCCEEDED;
|
||||
case PURCHASE_STATE_UNSPECIFIED -> PaymentStatus.UNKNOWN;
|
||||
})
|
||||
.orElse(PaymentStatus.UNKNOWN);
|
||||
final PurchaseState purchaseState = Optional
|
||||
.ofNullable(productPurchaseV2.getPurchaseStateContext())
|
||||
.map(PurchaseStateContext::getPurchaseState)
|
||||
.flatMap(PurchaseState::fromString)
|
||||
.orElse(PurchaseState.PURCHASE_STATE_UNSPECIFIED);
|
||||
|
||||
final ProductLineItem lineItem = getLineItem(productPurchaseV2);
|
||||
final String productId = lineItem.getProductId();
|
||||
final ReceiptLevel level = productIdToLevel(productId);
|
||||
|
||||
Instant purchaseTime = null;
|
||||
if (paymentStatus == PaymentStatus.SUCCEEDED) {
|
||||
purchaseTime = parseTimestamp(productPurchaseV2.getPurchaseCompletionTime())
|
||||
.orElseThrow(() -> new IOException("Invalid purchase time"));
|
||||
|
||||
final ConsumptionState consumptionState = Optional
|
||||
.ofNullable(lineItem.getProductOfferDetails())
|
||||
.map(ProductOfferDetails::getConsumptionState)
|
||||
.flatMap(ConsumptionState::fromString)
|
||||
.orElseThrow(() -> new IllegalStateException("Purchase did not contain a consumption state: " + lineItem.getProductOfferDetails()));
|
||||
|
||||
if (consumptionState == ConsumptionState.YET_TO_BE_CONSUMED) {
|
||||
// Mark this token as consumed
|
||||
executeTokenOperation(publisher ->
|
||||
publisher.purchases().products().consume(packageName, productId, purchaseToken));
|
||||
}
|
||||
switch (purchaseState) {
|
||||
case PURCHASED -> {
|
||||
}
|
||||
return Optional.of(new PaymentDetails(purchaseToken, level, paymentStatus, purchaseTime, null));
|
||||
} catch (SubscriptionNotFoundException e) {
|
||||
return Optional.empty();
|
||||
case PENDING -> throw new PurchaseReceiptRequestedForOpenPaymentException();
|
||||
case CANCELLED, PURCHASE_STATE_UNSPECIFIED -> throw new PurchasePaymentRequiredException(getProvider());
|
||||
}
|
||||
|
||||
final ProductLineItem lineItem = getLineItem(productPurchaseV2);
|
||||
final String productId = lineItem.getProductId();
|
||||
final ReceiptLevel level = productIdToLevel(productId);
|
||||
final Instant purchaseTime = parseTimestamp(productPurchaseV2.getPurchaseCompletionTime())
|
||||
.orElseThrow(() -> new IOException("Invalid purchase time"));
|
||||
|
||||
final ConsumptionState consumptionState = Optional
|
||||
.ofNullable(lineItem.getProductOfferDetails())
|
||||
.map(ProductOfferDetails::getConsumptionState)
|
||||
.flatMap(ConsumptionState::fromString)
|
||||
.orElseThrow(() -> new IllegalStateException(
|
||||
"Purchase did not contain a consumption state: " + lineItem.getProductOfferDetails()));
|
||||
|
||||
if (consumptionState == ConsumptionState.YET_TO_BE_CONSUMED) {
|
||||
// Mark this token as consumed
|
||||
executeTokenOperation(publisher ->
|
||||
publisher.purchases().products().consume(packageName, productId, purchaseToken));
|
||||
}
|
||||
return new PaymentDetails(purchaseToken, level, purchaseTime);
|
||||
}
|
||||
|
||||
private ProductLineItem getLineItem(final ProductPurchaseV2 purchase) throws SubscriptionInvalidArgumentsException {
|
||||
private ProductLineItem getLineItem(final ProductPurchaseV2 purchase) throws PurchaseInvalidArgumentsException {
|
||||
final List<ProductLineItem> lineItems = purchase.getProductLineItem();
|
||||
if (lineItems == null || lineItems.isEmpty()) {
|
||||
throw new SubscriptionInvalidArgumentsException("purchase has no line items");
|
||||
throw new PurchaseInvalidArgumentsException("purchase has no line items");
|
||||
}
|
||||
if (lineItems.size() > 1) {
|
||||
logger.warn("{} line items found for purchase {}, expected 1", lineItems.size(), purchase.getOrderId());
|
||||
@@ -381,20 +375,20 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor, O
|
||||
|
||||
/**
|
||||
* Execute a synchronous API call on a purchaseToken, mapping expected errors to the appropriate
|
||||
* {@link SubscriptionException}
|
||||
* {@link PurchaseException}
|
||||
*
|
||||
* @param apiCall An API call that operates on a purchaseToken
|
||||
* @param <R> The result of the API call
|
||||
* @return A stage that completes with the result of the API call
|
||||
*/
|
||||
private <R> R executeTokenOperation(final ApiCall<R> apiCall)
|
||||
throws RateLimitExceededException, SubscriptionNotFoundException {
|
||||
throws RateLimitExceededException, PurchaseNotFoundException {
|
||||
try {
|
||||
return apiCall.req(androidPublisher).execute();
|
||||
} catch (HttpResponseException e) {
|
||||
if (e.getStatusCode() == Response.Status.NOT_FOUND.getStatusCode()
|
||||
|| e.getStatusCode() == Response.Status.GONE.getStatusCode()) {
|
||||
throw new SubscriptionNotFoundException();
|
||||
throw new PurchaseNotFoundException();
|
||||
}
|
||||
if (e.getStatusCode() == Response.Status.TOO_MANY_REQUESTS.getStatusCode()) {
|
||||
throw new RateLimitExceededException(null);
|
||||
@@ -418,7 +412,7 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor, O
|
||||
}
|
||||
|
||||
private SubscriptionPurchaseV2 lookupSubscription(final String purchaseToken)
|
||||
throws RateLimitExceededException, SubscriptionNotFoundException {
|
||||
throws RateLimitExceededException, PurchaseNotFoundException {
|
||||
return executeTokenOperation(publisher -> publisher.purchases().subscriptionsv2().get(packageName, purchaseToken));
|
||||
}
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
package org.whispersystems.textsecuregcm.purchases;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import org.whispersystems.textsecuregcm.entities.Badge;
|
||||
+21
-25
@@ -2,15 +2,14 @@
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
package org.whispersystems.textsecuregcm.purchases;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import java.io.IOException;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import org.signal.libsignal.zkgroup.VerificationFailedException;
|
||||
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialRequest;
|
||||
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialResponse;
|
||||
@@ -29,6 +28,9 @@ public class LoginPurchaseManager {
|
||||
@VisibleForTesting
|
||||
final static Duration LOGIN_EXPIRATION = Duration.ofDays(366 * 5);
|
||||
|
||||
@VisibleForTesting
|
||||
final static Duration SANDBOX_LOGIN_EXPIRATION = Duration.ofDays(2);
|
||||
|
||||
/// Construct a LoginPurchaseManager
|
||||
///
|
||||
/// @param oneTimePaymentProcessors The processor to use for each supported [PaymentProvider]
|
||||
@@ -46,7 +48,7 @@ public class LoginPurchaseManager {
|
||||
/// Verify a completed one-time purchase and issue a receipt credential for it.
|
||||
///
|
||||
/// Repeated calls must use the same `receiptCredentialRequest`; a second request for a purchase that was already
|
||||
/// redeemed fails with [SubscriptionReceiptAlreadyRedeemedException].
|
||||
/// redeemed fails with [PurchaseReceiptAlreadyRedeemedException].
|
||||
///
|
||||
/// @param paymentProvider The provider that processed the purchase
|
||||
/// @param purchaseId The identifier for the purchase in the `paymentProvider`
|
||||
@@ -58,40 +60,34 @@ public class LoginPurchaseManager {
|
||||
final PaymentProvider paymentProvider,
|
||||
final String purchaseId,
|
||||
final ReceiptCredentialRequest receiptCredentialRequest)
|
||||
throws RateLimitExceededException, SubscriptionInvalidArgumentsException, IOException, SubscriptionNotFoundException, SubscriptionReceiptRequestedForOpenPaymentException, SubscriptionPaymentRequiredException, SubscriptionReceiptAlreadyRedeemedException, VerificationFailedException {
|
||||
throws RateLimitExceededException, PurchaseInvalidArgumentsException, IOException, PurchaseNotFoundException, PurchaseReceiptRequestedForOpenPaymentException, PurchasePaymentRequiredException, PurchaseReceiptAlreadyRedeemedException, VerificationFailedException {
|
||||
|
||||
final OneTimePaymentProcessor oneTimePaymentProcessor = oneTimePaymentProcessors.get(paymentProvider);
|
||||
if (oneTimePaymentProcessor == null) {
|
||||
throw new SubscriptionInvalidArgumentsException("unknown payment provider: " + paymentProvider);
|
||||
throw new PurchaseInvalidArgumentsException("unknown payment provider: " + paymentProvider);
|
||||
}
|
||||
|
||||
final PaymentDetails paymentDetails = oneTimePaymentProcessor
|
||||
.claimOneTimePurchase(purchaseId)
|
||||
.orElseThrow(SubscriptionNotFoundException::new);
|
||||
if (paymentDetails.status() == PaymentStatus.PROCESSING) {
|
||||
throw new SubscriptionReceiptRequestedForOpenPaymentException();
|
||||
} else if (paymentDetails.status() != PaymentStatus.SUCCEEDED) {
|
||||
throw Optional.ofNullable(paymentDetails.chargeFailure())
|
||||
.<SubscriptionPaymentRequiredException>map(
|
||||
cf -> new SubscriptionChargeFailurePaymentRequiredException(paymentProvider, cf))
|
||||
.orElseGet(SubscriptionPaymentRequiredException::new);
|
||||
} else if (paymentDetails.level() != ReceiptLevel.LOGIN) {
|
||||
throw new SubscriptionInvalidArgumentsException("purchase was for an unexpected product");
|
||||
}
|
||||
final PaymentDetails paymentDetails = oneTimePaymentProcessor.claimOneTimePurchase(purchaseId);
|
||||
final Duration expirationDuration = switch (paymentDetails.level()) {
|
||||
case LOGIN -> LOGIN_EXPIRATION;
|
||||
case LOGIN_SANDBOX -> SANDBOX_LOGIN_EXPIRATION;
|
||||
case ONE_TIME_DONATION, ONE_TIME_GIFT_DONATION, BACKUP_FREE, BACKUP_PAID, SUBSCRIPTION_LOW, SUBSCRIPTION_MEDIUM, SUBSCRIPTION_HIGH ->
|
||||
throw new PurchaseInvalidArgumentsException("purchase was for an unexpected product");
|
||||
};
|
||||
|
||||
// Calculating the expiration from the creation date works for IAP purchases. However, for other processors, the
|
||||
// creation date of the payment intent might be days before the payment actually completed. If we support non-IAP
|
||||
// processors we should attempt to get the latest date. see OneTimeDonationController/OneTimeDonationManager
|
||||
final Instant expiration = paymentDetails.created().plus(LOGIN_EXPIRATION).truncatedTo(ChronoUnit.DAYS);
|
||||
// processors we should attempt to get the latest date. see OneTimeDonationController/OneTimeDonationsManager
|
||||
final Instant expireAt = paymentDetails.created().plus(expirationDuration).truncatedTo(ChronoUnit.DAYS);
|
||||
|
||||
try {
|
||||
issuedReceiptsManager.recordOneTimeIssuance(paymentDetails.id(), paymentProvider, receiptCredentialRequest,
|
||||
expiration);
|
||||
expireAt);
|
||||
} catch (WriteConflictException _) {
|
||||
throw new SubscriptionReceiptAlreadyRedeemedException();
|
||||
throw new PurchaseReceiptAlreadyRedeemedException();
|
||||
}
|
||||
|
||||
return zkReceiptOperations.issueReceiptCredential(receiptCredentialRequest, expiration.getEpochSecond(),
|
||||
ReceiptLevel.LOGIN.getValue());
|
||||
return zkReceiptOperations.issueReceiptCredential(receiptCredentialRequest, expireAt.getEpochSecond(),
|
||||
paymentDetails.level().getValue());
|
||||
}
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.purchases;
|
||||
|
||||
import java.io.IOException;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
|
||||
public interface OneTimePaymentProcessor {
|
||||
|
||||
/// Retrieve information about a one-time purchase.
|
||||
///
|
||||
/// @param paymentIdentifier A string that identifies the payment in the payment processor
|
||||
/// @return Details about the purchase if it was successful
|
||||
///
|
||||
/// @throws PurchaseInvalidArgumentsException The purchase does not match a configured product type
|
||||
/// @throws PurchaseNotFoundException The paymentIdentifier does not identify a transaction in the processor
|
||||
/// @throws PurchasePaymentRequiredException The identified payment failed or was revoked
|
||||
/// @throws PurchaseReceiptRequestedForOpenPaymentException The identified payment is still processing
|
||||
PaymentDetails claimOneTimePurchase(final String paymentIdentifier) throws IOException, RateLimitExceededException, PurchaseInvalidArgumentsException, PurchaseNotFoundException, PurchasePaymentRequiredException, PurchaseReceiptRequestedForOpenPaymentException;
|
||||
}
|
||||
+1
-1
@@ -3,7 +3,7 @@
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
package org.whispersystems.textsecuregcm.purchases;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
@@ -0,0 +1,16 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.purchases;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
/**
|
||||
* Payment details for a successful one-time payment specified by id
|
||||
*
|
||||
* @param id The id of the payment in the payment processor
|
||||
* @param level The level identifier of purchase
|
||||
* @param created When the payment was created
|
||||
*/
|
||||
public record PaymentDetails(String id, ReceiptLevel level, Instant created) {}
|
||||
+1
-1
@@ -3,7 +3,7 @@
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
package org.whispersystems.textsecuregcm.purchases;
|
||||
|
||||
public enum PaymentMethod {
|
||||
UNKNOWN,
|
||||
+1
-1
@@ -3,7 +3,7 @@
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
package org.whispersystems.textsecuregcm.purchases;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
+2
-2
@@ -2,9 +2,9 @@
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
package org.whispersystems.textsecuregcm.purchases;
|
||||
|
||||
public enum PaymentStatus {
|
||||
enum PaymentStatus {
|
||||
SUCCEEDED,
|
||||
PROCESSING,
|
||||
FAILED,
|
||||
+1
-1
@@ -3,7 +3,7 @@
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
package org.whispersystems.textsecuregcm.purchases;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
+4
-4
@@ -2,20 +2,20 @@
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
package org.whispersystems.textsecuregcm.purchases;
|
||||
|
||||
import java.util.Optional;
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
public class SubscriptionException extends Exception {
|
||||
public class PurchaseException extends Exception {
|
||||
|
||||
private @Nullable String errorDetail;
|
||||
|
||||
public SubscriptionException(Exception cause) {
|
||||
public PurchaseException(Exception cause) {
|
||||
this(cause, null);
|
||||
}
|
||||
|
||||
SubscriptionException(Exception cause, String errorDetail) {
|
||||
PurchaseException(Exception cause, String errorDetail) {
|
||||
super(cause);
|
||||
this.errorDetail = errorDetail;
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.purchases;
|
||||
|
||||
public class PurchaseForbiddenException extends PurchaseException {
|
||||
|
||||
public PurchaseForbiddenException(final String message) {
|
||||
super(null, message);
|
||||
}
|
||||
}
|
||||
+3
-3
@@ -2,13 +2,13 @@
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
package org.whispersystems.textsecuregcm.purchases;
|
||||
|
||||
public class SubscriptionInvalidAmountException extends SubscriptionInvalidArgumentsException {
|
||||
public class PurchaseInvalidAmountException extends PurchaseInvalidArgumentsException {
|
||||
|
||||
private String errorCode;
|
||||
|
||||
public SubscriptionInvalidAmountException(String errorCode) {
|
||||
public PurchaseInvalidAmountException(String errorCode) {
|
||||
super(null, null);
|
||||
this.errorCode = errorCode;
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.purchases;
|
||||
|
||||
public class PurchaseInvalidArgumentsException extends PurchaseException {
|
||||
|
||||
public PurchaseInvalidArgumentsException(final String message, final Exception cause) {
|
||||
super(cause, message);
|
||||
}
|
||||
|
||||
public PurchaseInvalidArgumentsException(final String message) {
|
||||
this(message, null);
|
||||
}
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.purchases;
|
||||
|
||||
public class PurchaseInvalidIdempotencyKeyException extends PurchaseInvalidArgumentsException {
|
||||
|
||||
public PurchaseInvalidIdempotencyKeyException(final String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.purchases;
|
||||
|
||||
public class PurchaseInvalidLevelException extends PurchaseInvalidArgumentsException {
|
||||
|
||||
public PurchaseInvalidLevelException() {
|
||||
super(null, null);
|
||||
}
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.purchases;
|
||||
|
||||
public class PurchaseNotFoundException extends PurchaseException {
|
||||
|
||||
public PurchaseNotFoundException() {
|
||||
super(null);
|
||||
}
|
||||
|
||||
public PurchaseNotFoundException(Exception cause) {
|
||||
super(cause);
|
||||
}
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.purchases;
|
||||
|
||||
import java.util.Optional;
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
public class PurchasePaymentRequiredException extends PurchaseException {
|
||||
|
||||
private final PaymentProvider processor;
|
||||
@Nullable
|
||||
private final ChargeFailure chargeFailure;
|
||||
|
||||
public PurchasePaymentRequiredException(final PaymentProvider processor) {
|
||||
this(processor, null, null);
|
||||
}
|
||||
|
||||
public PurchasePaymentRequiredException(final PaymentProvider processor, final String message) {
|
||||
this(processor, null, message);
|
||||
}
|
||||
|
||||
public PurchasePaymentRequiredException(final PaymentProvider processor, final ChargeFailure chargeFailure) {
|
||||
this(processor, chargeFailure, null);
|
||||
}
|
||||
|
||||
private PurchasePaymentRequiredException(final PaymentProvider processor,
|
||||
@Nullable final ChargeFailure chargeFailure, @Nullable final String message) {
|
||||
super(null, message);
|
||||
this.processor = processor;
|
||||
this.chargeFailure = chargeFailure;
|
||||
}
|
||||
|
||||
public PaymentProvider getProcessor() {
|
||||
return processor;
|
||||
}
|
||||
|
||||
/// @return The reason the processor reported for the payment failure, if it reported one
|
||||
public Optional<ChargeFailure> getChargeFailure() {
|
||||
return Optional.ofNullable(chargeFailure);
|
||||
}
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.purchases;
|
||||
|
||||
public class PurchasePaymentRequiresActionException extends PurchaseInvalidArgumentsException {
|
||||
|
||||
public PurchasePaymentRequiresActionException(String message) {
|
||||
super(message, null);
|
||||
}
|
||||
|
||||
public PurchasePaymentRequiresActionException() {
|
||||
super(null, null);
|
||||
}
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.purchases;
|
||||
|
||||
public class PurchaseProcessorConflictException extends PurchaseException {
|
||||
|
||||
public PurchaseProcessorConflictException() {
|
||||
super(null, null);
|
||||
}
|
||||
|
||||
public PurchaseProcessorConflictException(final String message) {
|
||||
super(null, message);
|
||||
}
|
||||
}
|
||||
+3
-3
@@ -2,14 +2,14 @@
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
package org.whispersystems.textsecuregcm.purchases;
|
||||
|
||||
public class SubscriptionProcessorException extends SubscriptionException {
|
||||
public class PurchaseProcessorException extends PurchaseException {
|
||||
|
||||
private final PaymentProvider processor;
|
||||
private final ChargeFailure chargeFailure;
|
||||
|
||||
public SubscriptionProcessorException(final PaymentProvider processor, final ChargeFailure chargeFailure) {
|
||||
public PurchaseProcessorException(final PaymentProvider processor, final ChargeFailure chargeFailure) {
|
||||
super(null, null);
|
||||
this.processor = processor;
|
||||
this.chargeFailure = chargeFailure;
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.purchases;
|
||||
|
||||
public class PurchaseReceiptAlreadyRedeemedException extends PurchaseException {
|
||||
|
||||
public PurchaseReceiptAlreadyRedeemedException() {
|
||||
super(null, null);
|
||||
}
|
||||
|
||||
public PurchaseReceiptAlreadyRedeemedException(final String message) {
|
||||
super(null, message);
|
||||
}
|
||||
}
|
||||
+3
-3
@@ -2,14 +2,14 @@
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
package org.whispersystems.textsecuregcm.purchases;
|
||||
|
||||
/**
|
||||
* Attempted to retrieve a receipt for a subscription that hasn't yet been charged or the invoice is in the open state
|
||||
*/
|
||||
public class SubscriptionReceiptRequestedForOpenPaymentException extends SubscriptionException {
|
||||
public class PurchaseReceiptRequestedForOpenPaymentException extends PurchaseException {
|
||||
|
||||
public SubscriptionReceiptRequestedForOpenPaymentException() {
|
||||
public PurchaseReceiptRequestedForOpenPaymentException() {
|
||||
super(null, null);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
package org.whispersystems.textsecuregcm.purchases;
|
||||
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialPresentation;
|
||||
+2
-1
@@ -2,7 +2,7 @@
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
package org.whispersystems.textsecuregcm.purchases;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Optional;
|
||||
@@ -19,6 +19,7 @@ public enum ReceiptLevel {
|
||||
BACKUP_FREE(200L),
|
||||
BACKUP_PAID(201L),
|
||||
LOGIN(300L),
|
||||
LOGIN_SANDBOX(301L),
|
||||
SUBSCRIPTION_LOW(500),
|
||||
SUBSCRIPTION_MEDIUM(1000),
|
||||
SUBSCRIPTION_HIGH(2000);
|
||||
+44
-46
@@ -3,7 +3,7 @@
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
package org.whispersystems.textsecuregcm.purchases;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.common.collect.Lists;
|
||||
@@ -46,7 +46,6 @@ import com.stripe.param.SubscriptionUpdateParams.BillingCycleAnchor;
|
||||
import com.stripe.param.SubscriptionUpdateParams.ProrationBehavior;
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.math.BigDecimal;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.InvalidKeyException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
@@ -175,7 +174,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor,
|
||||
|
||||
@Override
|
||||
public void setDefaultPaymentMethodForCustomer(final String customerId, final String paymentMethodId,
|
||||
@Nullable final String currentSubscriptionId) throws SubscriptionInvalidArgumentsException {
|
||||
@Nullable final String currentSubscriptionId) throws PurchaseInvalidArgumentsException {
|
||||
final CustomerUpdateParams params = CustomerUpdateParams.builder()
|
||||
.setInvoiceSettings(InvoiceSettings.builder()
|
||||
.setDefaultPaymentMethod(paymentMethodId)
|
||||
@@ -185,7 +184,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor,
|
||||
stripeClient.v1().customers().update(customerId, params, commonOptions());
|
||||
} catch (final InvalidRequestException e) {
|
||||
// Could happen if the paymentMethodId was bunk or the client didn't actually finish setting it up
|
||||
throw new SubscriptionInvalidArgumentsException(e.getMessage());
|
||||
throw new PurchaseInvalidArgumentsException(e.getMessage());
|
||||
} catch (final StripeException e) {
|
||||
throw new UncheckedIOException(new IOException(e));
|
||||
}
|
||||
@@ -209,13 +208,13 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor,
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a payment intent. May throw a {@link SubscriptionInvalidAmountException} if stripe rejects the attempt if
|
||||
* Creates a payment intent. May throw a {@link PurchaseInvalidAmountException} if stripe rejects the attempt if
|
||||
* the amount is too large or too small
|
||||
*/
|
||||
public PaymentIntent createPaymentIntent(final String currency,
|
||||
final long amount,
|
||||
final long level,
|
||||
@Nullable final ClientPlatform clientPlatform) throws SubscriptionInvalidAmountException {
|
||||
@Nullable final ClientPlatform clientPlatform) throws PurchaseInvalidAmountException {
|
||||
|
||||
final PaymentIntentCreateParams.Builder builder = PaymentIntentCreateParams.builder()
|
||||
.setAmount(amount)
|
||||
@@ -235,25 +234,18 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor,
|
||||
? "unknown"
|
||||
: e.getCode().toLowerCase(Locale.ROOT);
|
||||
switch (errorCode) {
|
||||
case "amount_too_small", "amount_too_large" -> throw new SubscriptionInvalidAmountException(errorCode);
|
||||
case "amount_too_small", "amount_too_large" -> throw new PurchaseInvalidAmountException(errorCode);
|
||||
default -> throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<PaymentDetails> claimOneTimePurchase(final String paymentIntentId) throws IOException {
|
||||
public PaymentDetails claimOneTimePurchase(final String paymentIntentId)
|
||||
throws IOException, PurchaseNotFoundException, PurchaseReceiptRequestedForOpenPaymentException, PurchasePaymentRequiredException {
|
||||
try {
|
||||
final PaymentIntent paymentIntent = getPaymentIntent(paymentIntentId);
|
||||
|
||||
ChargeFailure chargeFailure = null;
|
||||
if (paymentIntent.getLatestChargeObject() != null) {
|
||||
final Charge charge = paymentIntent.getLatestChargeObject();
|
||||
if (charge.getFailureCode() != null || charge.getFailureMessage() != null) {
|
||||
chargeFailure = createChargeFailure(charge);
|
||||
}
|
||||
}
|
||||
|
||||
final ReceiptLevel level = Optional.ofNullable(paymentIntent.getMetadata())
|
||||
.map(m -> m.get(METADATA_KEY_LEVEL))
|
||||
.map(Long::parseLong)
|
||||
@@ -261,14 +253,23 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor,
|
||||
.orElseThrow(() -> new IllegalStateException(
|
||||
"failed to retrieve level metadata from payment intent %s".formatted(paymentIntentId)));
|
||||
|
||||
return Optional.of(new PaymentDetails(paymentIntent.getId(),
|
||||
level,
|
||||
getPaymentStatusForStatus(paymentIntent.getStatus()),
|
||||
Instant.ofEpochSecond(paymentIntent.getCreated()),
|
||||
chargeFailure));
|
||||
return switch (getPaymentStatusForStatus(paymentIntent.getStatus())) {
|
||||
case SUCCEEDED ->
|
||||
new PaymentDetails(paymentIntent.getId(), level, Instant.ofEpochSecond(paymentIntent.getCreated()));
|
||||
case PROCESSING -> throw new PurchaseReceiptRequestedForOpenPaymentException();
|
||||
case FAILED, UNKNOWN -> {
|
||||
if (paymentIntent.getLatestChargeObject() != null) {
|
||||
final Charge charge = paymentIntent.getLatestChargeObject();
|
||||
if (charge.getFailureCode() != null || charge.getFailureMessage() != null) {
|
||||
throw new PurchasePaymentRequiredException(getProvider(), createChargeFailure(charge));
|
||||
}
|
||||
}
|
||||
throw new PurchasePaymentRequiredException(getProvider());
|
||||
}
|
||||
};
|
||||
} catch (final StripeException e) {
|
||||
if (e.getStatusCode() == 404) {
|
||||
return Optional.empty();
|
||||
throw new PurchaseNotFoundException();
|
||||
} else {
|
||||
throw new IOException(e);
|
||||
}
|
||||
@@ -290,8 +291,8 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor,
|
||||
@Override
|
||||
public SubscriptionId createSubscription(final String customerId, final String priceId, final long level,
|
||||
final long lastSubscriptionCreatedAt)
|
||||
throws SubscriptionProcessorException, SubscriptionInvalidIdempotencyKeyException,
|
||||
SubscriptionPaymentRequiresActionException {
|
||||
throws PurchaseProcessorException, PurchaseInvalidIdempotencyKeyException,
|
||||
PurchasePaymentRequiresActionException {
|
||||
// this relies on Stripe's idempotency key to avoid creating more than one subscription if the client
|
||||
// retries this request
|
||||
final SubscriptionCreateParams params = SubscriptionCreateParams.builder()
|
||||
@@ -313,12 +314,12 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor,
|
||||
commonOptions(generateIdempotencyKeyForCreateSubscription(customerId, lastSubscriptionCreatedAt)));
|
||||
return new SubscriptionId(subscription.getId());
|
||||
} catch (final IdempotencyException e) {
|
||||
throw new SubscriptionInvalidIdempotencyKeyException(e.getStripeError().getMessage());
|
||||
throw new PurchaseInvalidIdempotencyKeyException(e.getStripeError().getMessage());
|
||||
} catch (final CardException e) {
|
||||
throw new SubscriptionProcessorException(getProvider(), createChargeFailureFromCardException(e));
|
||||
throw new PurchaseProcessorException(getProvider(), createChargeFailureFromCardException(e));
|
||||
} catch (final StripeException e) {
|
||||
if ("subscription_payment_intent_requires_action".equals(e.getCode())) {
|
||||
throw new SubscriptionPaymentRequiresActionException();
|
||||
throw new PurchasePaymentRequiresActionException();
|
||||
}
|
||||
throw new UncheckedIOException(new IOException(e));
|
||||
}
|
||||
@@ -326,8 +327,8 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor,
|
||||
|
||||
@Override
|
||||
public SubscriptionId updateSubscription(final Object subscriptionObj, final String priceId, final long level, final String idempotencyKey)
|
||||
throws SubscriptionInvalidIdempotencyKeyException, SubscriptionPaymentRequiresActionException,
|
||||
SubscriptionProcessorException {
|
||||
throws PurchaseInvalidIdempotencyKeyException, PurchasePaymentRequiresActionException,
|
||||
PurchaseProcessorException {
|
||||
|
||||
final Subscription subscription = getSubscription(subscriptionObj);
|
||||
|
||||
@@ -366,9 +367,9 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor,
|
||||
commonOptions(generateIdempotencyKeyForSubscriptionUpdate(subscription.getCustomer(), idempotencyKey)));
|
||||
return new SubscriptionId(subscription1.getId());
|
||||
} catch (final IdempotencyException e) {
|
||||
throw new SubscriptionInvalidIdempotencyKeyException(e.getStripeError().getMessage());
|
||||
throw new PurchaseInvalidIdempotencyKeyException(e.getStripeError().getMessage());
|
||||
} catch (final CardException e) {
|
||||
throw new SubscriptionProcessorException(getProvider(), createChargeFailureFromCardException(e));
|
||||
throw new PurchaseProcessorException(getProvider(), createChargeFailureFromCardException(e));
|
||||
} catch (final StripeException e) {
|
||||
throw new UncheckedIOException(new IOException(e));
|
||||
}
|
||||
@@ -635,37 +636,34 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor,
|
||||
|
||||
@Override
|
||||
public ReceiptItem getReceiptItem(final String subscriptionId)
|
||||
throws SubscriptionPaymentRequiredException, SubscriptionReceiptRequestedForOpenPaymentException {
|
||||
throws PurchasePaymentRequiredException, PurchaseReceiptRequestedForOpenPaymentException {
|
||||
final Invoice invoice = getSubscription(getSubscription(subscriptionId)).getLatestInvoiceObject();
|
||||
return convertInvoiceToReceipt(invoice, subscriptionId);
|
||||
}
|
||||
|
||||
private ReceiptItem convertInvoiceToReceipt(final Invoice latestSubscriptionInvoice, final String subscriptionId)
|
||||
throws SubscriptionReceiptRequestedForOpenPaymentException, SubscriptionPaymentRequiredException {
|
||||
throws PurchaseReceiptRequestedForOpenPaymentException, PurchasePaymentRequiredException {
|
||||
if (latestSubscriptionInvoice == null) {
|
||||
throw new SubscriptionReceiptRequestedForOpenPaymentException();
|
||||
throw new PurchaseReceiptRequestedForOpenPaymentException();
|
||||
}
|
||||
if ("open".equalsIgnoreCase(latestSubscriptionInvoice.getStatus()) || "draft".equalsIgnoreCase(
|
||||
latestSubscriptionInvoice.getStatus())) {
|
||||
throw new SubscriptionReceiptRequestedForOpenPaymentException();
|
||||
throw new PurchaseReceiptRequestedForOpenPaymentException();
|
||||
}
|
||||
if (!"paid".equalsIgnoreCase(latestSubscriptionInvoice.getStatus())) {
|
||||
|
||||
final Optional<InvoicePayment> latestInvoicePayment = getMostRecentInvoicePayment(latestSubscriptionInvoice);
|
||||
|
||||
final SubscriptionPaymentRequiredException exception = latestInvoicePayment.map(invoicePayment -> {
|
||||
final PurchasePaymentRequiredException exception = latestInvoicePayment.map(invoicePayment -> {
|
||||
|
||||
final Optional<Charge> maybeCharge = getChargeForInvoicePayment(invoicePayment);
|
||||
|
||||
return maybeCharge.filter(charge -> charge.getFailureCode() != null || charge.getFailureMessage() != null)
|
||||
.map(charge -> {
|
||||
// If the charge object has a failure reason we can present to the user, create a detailed exception
|
||||
return (SubscriptionPaymentRequiredException) (new SubscriptionChargeFailurePaymentRequiredException(
|
||||
getProvider(), createChargeFailure(charge)));
|
||||
})
|
||||
.orElseGet(SubscriptionPaymentRequiredException::new);
|
||||
// If the charge object has a failure reason we can present to the user, create a detailed exception
|
||||
.map(charge -> new PurchasePaymentRequiredException(getProvider(), createChargeFailure(charge)))
|
||||
.orElseGet(() -> new PurchasePaymentRequiredException(getProvider()));
|
||||
})
|
||||
.orElseGet(SubscriptionPaymentRequiredException::new);
|
||||
.orElseGet(() -> new PurchasePaymentRequiredException(getProvider()));
|
||||
|
||||
throw exception;
|
||||
}
|
||||
@@ -715,7 +713,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor,
|
||||
}
|
||||
|
||||
public String getGeneratedSepaIdFromSetupIntent(final String setupIntentId)
|
||||
throws SubscriptionNotFoundException, SubscriptionProcessorConflictException, IOException {
|
||||
throws PurchaseNotFoundException, PurchaseProcessorConflictException, IOException {
|
||||
final SetupIntentRetrieveParams params = SetupIntentRetrieveParams.builder()
|
||||
.addExpand("latest_attempt")
|
||||
.build();
|
||||
@@ -729,12 +727,12 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor,
|
||||
// This usually indicates that the client has made requests out of order, either by not confirming
|
||||
// the SetupIntent or not having the user authorize the transaction.
|
||||
logger.debug("setupIntent {} missing expected fields", setupIntentId);
|
||||
throw new SubscriptionProcessorConflictException();
|
||||
throw new PurchaseProcessorConflictException();
|
||||
}
|
||||
return setupIntent.getLatestAttemptObject().getPaymentMethodDetails().getIdeal().getGeneratedSepaDebit();
|
||||
} catch (final StripeException e) {
|
||||
if (e.getStatusCode() == 404) {
|
||||
throw new SubscriptionNotFoundException();
|
||||
throw new PurchaseNotFoundException();
|
||||
}
|
||||
logger.error("unexpected error from Stripe when retrieving setupIntent {}", setupIntentId, e);
|
||||
throw new IOException(e);
|
||||
+2
-2
@@ -3,9 +3,9 @@
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
package org.whispersystems.textsecuregcm.purchases;
|
||||
|
||||
public class SubscriberIdCreationNotPermittedException extends SubscriptionException {
|
||||
public class SubscriberIdCreationNotPermittedException extends PurchaseException {
|
||||
|
||||
public SubscriberIdCreationNotPermittedException() {
|
||||
super(null);
|
||||
+1
-1
@@ -3,7 +3,7 @@
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
package org.whispersystems.textsecuregcm.purchases;
|
||||
|
||||
import com.google.api.services.androidpublisher.model.Money;
|
||||
import java.math.BigDecimal;
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
package org.whispersystems.textsecuregcm.purchases;
|
||||
|
||||
import java.time.Instant;
|
||||
import javax.annotation.Nullable;
|
||||
+9
-9
@@ -2,7 +2,7 @@
|
||||
* Copyright 2022 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
package org.whispersystems.textsecuregcm.purchases;
|
||||
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.storage.PaymentTime;
|
||||
@@ -27,15 +27,15 @@ public interface SubscriptionPaymentProcessor {
|
||||
* @param subscriptionId A subscriptionId that potentially corresponds to a valid subscription
|
||||
* @return A {@link ReceiptItem} if the subscription is valid
|
||||
* @throws RateLimitExceededException If rate-limited
|
||||
* @throws SubscriptionNotFoundException If the provided subscriptionId could not be found with
|
||||
* @throws PurchaseNotFoundException If the provided subscriptionId could not be found with
|
||||
* the provider
|
||||
* @throws SubscriptionPaymentRequiredException If the subscription is in a state does not grant the
|
||||
* @throws PurchasePaymentRequiredException If the subscription is in a state does not grant the
|
||||
* user an entitlement
|
||||
* @throws SubscriptionReceiptRequestedForOpenPaymentException If a receipt was requested while a payment transaction
|
||||
* @throws PurchaseReceiptRequestedForOpenPaymentException If a receipt was requested while a payment transaction
|
||||
* was still open
|
||||
*/
|
||||
ReceiptItem getReceiptItem(String subscriptionId)
|
||||
throws RateLimitExceededException, SubscriptionNotFoundException, SubscriptionChargeFailurePaymentRequiredException, SubscriptionPaymentRequiredException, SubscriptionReceiptRequestedForOpenPaymentException;
|
||||
throws RateLimitExceededException, PurchaseNotFoundException, PurchasePaymentRequiredException, PurchaseReceiptRequestedForOpenPaymentException;
|
||||
|
||||
/**
|
||||
* Cancel all active subscriptions for this key within the payment processor.
|
||||
@@ -43,10 +43,10 @@ public interface SubscriptionPaymentProcessor {
|
||||
* @param key An identifier for the subscriber within the payment provider, corresponds to the customerId field in the
|
||||
* subscriptions table
|
||||
* @throws RateLimitExceededException If rate-limited
|
||||
* @throws SubscriptionInvalidArgumentsException If a precondition for cancellation was not met
|
||||
* @throws PurchaseInvalidArgumentsException If a precondition for cancellation was not met
|
||||
*/
|
||||
void cancelAllActiveSubscriptions(String key)
|
||||
throws SubscriptionInvalidArgumentsException, RateLimitExceededException;
|
||||
throws PurchaseInvalidArgumentsException, RateLimitExceededException;
|
||||
|
||||
/**
|
||||
* Retrieve subscription information from the processor
|
||||
@@ -54,8 +54,8 @@ public interface SubscriptionPaymentProcessor {
|
||||
* @param subscriptionId The identifier with the processor to retrieve information for
|
||||
* @return {@link SubscriptionInformation} from the provider
|
||||
* @throws RateLimitExceededException If rate-limited
|
||||
* @throws SubscriptionNotFoundException If the provided key was not found with the provider
|
||||
* @throws PurchaseNotFoundException If the provided key was not found with the provider
|
||||
*/
|
||||
SubscriptionInformation getSubscriptionInformation(final String subscriptionId)
|
||||
throws RateLimitExceededException, SubscriptionNotFoundException;
|
||||
throws RateLimitExceededException, PurchaseNotFoundException;
|
||||
}
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
package org.whispersystems.textsecuregcm.purchases;
|
||||
|
||||
/// @param currency The upper-case 3-character currency specifier of the price
|
||||
/// @param amount The amount in the currency's minor unit (as defined by stripe)
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
package org.whispersystems.textsecuregcm.purchases;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
+26
-5
@@ -7,6 +7,7 @@ package org.whispersystems.textsecuregcm.push;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.protobuf.ByteString;
|
||||
import com.google.protobuf.InvalidProtocolBufferException;
|
||||
import io.dropwizard.lifecycle.Managed;
|
||||
@@ -41,6 +42,8 @@ public class ProvisioningManager extends RedisPubSubAdapter<byte[], byte[]> impl
|
||||
private static final String RECEIVE_PROVISIONING_MESSAGE_COUNTER_NAME =
|
||||
name(ProvisioningManager.class, "receiveProvisioningMessage");
|
||||
|
||||
private static final String CHANNEL_PREFIX = "provisioning::";
|
||||
|
||||
private static final String RETRY_NAME = ResilienceUtil.name(ProvisioningManager.class);
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(ProvisioningManager.class);
|
||||
@@ -64,12 +67,14 @@ public class ProvisioningManager extends RedisPubSubAdapter<byte[], byte[]> impl
|
||||
|
||||
public void addListener(final String address, final Consumer<PubSubProtos.PubSubMessage> listener) {
|
||||
listenersByProvisioningAddress.put(address, listener);
|
||||
pubSubConnection.usePubSubConnection(connection -> connection.sync().subscribe(address.getBytes(StandardCharsets.UTF_8)));
|
||||
pubSubConnection.usePubSubConnection(connection -> connection.sync().subscribe(
|
||||
getPrefixedChannel(address), getUnprefixedChannel(address)));
|
||||
}
|
||||
|
||||
public void removeListener(final String address) {
|
||||
RedisOperation.unchecked(() ->
|
||||
pubSubConnection.usePubSubConnection(connection -> connection.sync().unsubscribe(address.getBytes(StandardCharsets.UTF_8))));
|
||||
pubSubConnection.usePubSubConnection(connection -> connection.sync().unsubscribe(
|
||||
getPrefixedChannel(address), getUnprefixedChannel(address))));
|
||||
|
||||
listenersByProvisioningAddress.remove(address);
|
||||
}
|
||||
@@ -82,7 +87,7 @@ public class ProvisioningManager extends RedisPubSubAdapter<byte[], byte[]> impl
|
||||
|
||||
final boolean receiverPresent = ResilienceUtil.getGeneralRedisRetry(RETRY_NAME)
|
||||
.executeSupplier(() -> pubSubClient.withBinaryConnection(connection ->
|
||||
connection.sync().publish(address.getBytes(StandardCharsets.UTF_8), pubSubMessage.toByteArray()) > 0));
|
||||
connection.sync().publish(getPrefixedChannel(address), pubSubMessage.toByteArray()) > 0));
|
||||
|
||||
Metrics.counter(SEND_PROVISIONING_MESSAGE_COUNTER_NAME, "online", String.valueOf(receiverPresent)).increment();
|
||||
|
||||
@@ -92,7 +97,7 @@ public class ProvisioningManager extends RedisPubSubAdapter<byte[], byte[]> impl
|
||||
@Override
|
||||
public void message(final byte[] channel, final byte[] message) {
|
||||
try {
|
||||
final String address = new String(channel, StandardCharsets.UTF_8);
|
||||
final String address = getAddress(channel);
|
||||
final PubSubProtos.PubSubMessage pubSubMessage = PubSubProtos.PubSubMessage.parseFrom(message);
|
||||
|
||||
if (pubSubMessage.getType() == PubSubProtos.PubSubMessage.Type.DELIVER) {
|
||||
@@ -114,6 +119,22 @@ public class ProvisioningManager extends RedisPubSubAdapter<byte[], byte[]> impl
|
||||
|
||||
@Override
|
||||
public void unsubscribed(final byte[] channel, final long count) {
|
||||
listenersByProvisioningAddress.remove(new String(channel, StandardCharsets.UTF_8));
|
||||
listenersByProvisioningAddress.remove(getAddress(channel));
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static byte[] getPrefixedChannel(final String address) {
|
||||
return (CHANNEL_PREFIX + address).getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static byte[] getUnprefixedChannel(final String address) {
|
||||
return address.getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
private static String getAddress(final byte[] channel) {
|
||||
final String channelName = new String(channel, StandardCharsets.UTF_8);
|
||||
|
||||
return channelName.startsWith(CHANNEL_PREFIX) ? channelName.substring(CHANNEL_PREFIX.length()) : channelName;
|
||||
}
|
||||
}
|
||||
+4
-4
@@ -180,15 +180,15 @@ public class RedisMessageAvailabilityManager extends RedisClusterPubSubAdapter<b
|
||||
}
|
||||
|
||||
return subscribeFuture.get()
|
||||
.thenCompose(ignored -> clusterClient.withBinaryCluster(connection -> connection.async()
|
||||
.spublish(eventChannel, CLIENT_CONNECTED_EVENT_BYTES)))
|
||||
.handle((ignored, throwable) -> {
|
||||
.thenCompose(_ -> clusterClient.withBinaryCluster(connection -> connection.async()
|
||||
.spublish(eventChannel, CLIENT_CONNECTED_EVENT_BYTES))
|
||||
.handle((_, throwable) -> {
|
||||
if (throwable != null) {
|
||||
PUBLISH_CLIENT_CONNECTION_EVENT_ERROR_COUNTER.increment();
|
||||
}
|
||||
|
||||
return null;
|
||||
});
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+54
@@ -18,6 +18,8 @@ import io.lettuce.core.cluster.ClusterTopologyRefreshOptions;
|
||||
import io.lettuce.core.cluster.RedisClusterClient;
|
||||
import io.lettuce.core.cluster.api.StatefulRedisClusterConnection;
|
||||
import io.lettuce.core.cluster.event.ClusterTopologyChangedEvent;
|
||||
import io.lettuce.core.cluster.models.partitions.Partitions;
|
||||
import io.lettuce.core.cluster.models.partitions.RedisClusterNode;
|
||||
import io.lettuce.core.cluster.pubsub.StatefulRedisClusterPubSubConnection;
|
||||
import io.lettuce.core.codec.ByteArrayCodec;
|
||||
import io.lettuce.core.resource.ClientResources;
|
||||
@@ -25,9 +27,16 @@ import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.function.BiFunction;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
import javax.annotation.Nullable;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.configuration.RedisClusterConfiguration;
|
||||
import reactor.core.scheduler.Schedulers;
|
||||
|
||||
@@ -40,6 +49,8 @@ public class FaultTolerantRedisClusterClient {
|
||||
|
||||
private final String name;
|
||||
|
||||
private final Duration upstreamConnectionTimeout;
|
||||
|
||||
private final RedisClusterClient clusterClient;
|
||||
|
||||
private final StatefulRedisClusterConnection<String, String> stringConnection;
|
||||
@@ -49,6 +60,8 @@ public class FaultTolerantRedisClusterClient {
|
||||
|
||||
private final Retry topologyChangedEventRetry;
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(FaultTolerantRedisClusterClient.class);
|
||||
|
||||
|
||||
public FaultTolerantRedisClusterClient(final String name,
|
||||
final RedisClusterConfiguration clusterConfiguration,
|
||||
@@ -69,6 +82,7 @@ public class FaultTolerantRedisClusterClient {
|
||||
@Nullable final String circuitBreakerConfigurationName) {
|
||||
|
||||
this.name = name;
|
||||
this.upstreamConnectionTimeout = commandTimeout;
|
||||
|
||||
final LettuceShardCircuitBreaker lettuceShardCircuitBreaker =
|
||||
new LettuceShardCircuitBreaker(name, circuitBreakerConfigurationName);
|
||||
@@ -98,6 +112,12 @@ public class FaultTolerantRedisClusterClient {
|
||||
this.stringConnection = clusterClient.connect();
|
||||
this.binaryConnection = clusterClient.connect(ByteArrayCodec.INSTANCE);
|
||||
|
||||
// Eagerly initialize connections. Otherwise, the first several calls will fail immediately, rather than being queued
|
||||
// while the connection is pending. See https://github.com/redis/lettuce/pull/3782.
|
||||
awaitUpstreamConnections(
|
||||
connectToAllUpstreams(stringConnection.getPartitions(), stringConnection::getConnectionAsync),
|
||||
connectToAllUpstreams(binaryConnection.getPartitions(), binaryConnection::getConnectionAsync));
|
||||
|
||||
// create a synthetic topology changed event to notify shard circuit breakers of initial upstreams
|
||||
clusterClient.getResources().eventBus().publish(
|
||||
new ClusterTopologyChangedEvent(Collections.emptyList(), clusterClient.getPartitions().getPartitions()));
|
||||
@@ -172,6 +192,9 @@ public class FaultTolerantRedisClusterClient {
|
||||
final StatefulRedisClusterPubSubConnection<String, String> pubSubConnection = clusterClient.connectPubSub();
|
||||
pubSubConnections.add(pubSubConnection);
|
||||
|
||||
awaitUpstreamConnections(
|
||||
connectToAllUpstreams(pubSubConnection.getPartitions(), pubSubConnection::getConnectionAsync));
|
||||
|
||||
return new FaultTolerantPubSubClusterConnection<>(name, pubSubConnection, topologyChangedEventRetry,
|
||||
Schedulers.newSingle(name + "-redisPubSubEvents", true));
|
||||
}
|
||||
@@ -180,7 +203,38 @@ public class FaultTolerantRedisClusterClient {
|
||||
final StatefulRedisClusterPubSubConnection<byte[], byte[]> pubSubConnection = clusterClient.connectPubSub(ByteArrayCodec.INSTANCE);
|
||||
pubSubConnections.add(pubSubConnection);
|
||||
|
||||
awaitUpstreamConnections(
|
||||
connectToAllUpstreams(pubSubConnection.getPartitions(), pubSubConnection::getConnectionAsync));
|
||||
|
||||
return new FaultTolerantPubSubClusterConnection<>(name, pubSubConnection, topologyChangedEventRetry,
|
||||
Schedulers.newSingle(name + "-redisPubSubEvents", true));
|
||||
}
|
||||
|
||||
/// Initiates connections to all upstream nodes in the cluster
|
||||
///
|
||||
/// @return a future that completes when all connection attempts have either succeeded or failed. This future will never fail.
|
||||
private CompletableFuture<Void> connectToAllUpstreams(final Partitions partitions,
|
||||
final BiFunction<String, Integer, CompletableFuture<?>> connectionFunction) {
|
||||
|
||||
return CompletableFuture.allOf(partitions.stream()
|
||||
.filter(node -> node.is(RedisClusterNode.NodeFlag.UPSTREAM))
|
||||
.map(node -> connectionFunction.apply(node.getUri().getHost(), node.getUri().getPort())
|
||||
.exceptionally(throwable -> {
|
||||
logger.warn("Failed to connect to upstream {} for {}", node.getUri(), name, throwable);
|
||||
return null;
|
||||
}))
|
||||
.toArray(CompletableFuture[]::new));
|
||||
}
|
||||
|
||||
/// Awaits the futures until {@link FaultTolerantRedisClusterClient#upstreamConnectionTimeout} is reached
|
||||
void awaitUpstreamConnections(final CompletableFuture<?>... connectionFutures) {
|
||||
try {
|
||||
CompletableFuture.allOf(connectionFutures).get(upstreamConnectionTimeout.toMillis(), TimeUnit.MILLISECONDS);
|
||||
} catch (final TimeoutException | InterruptedException e) {
|
||||
logger.warn("Upstream connection to {} timed out or interrupted; continuing", this.name, e);
|
||||
} catch (final ExecutionException e) {
|
||||
throw new IllegalStateException("Unexpected: connection attempt futures always complete successfully", e);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Loaded 100 of 204 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user