mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-11-30 16:26:47 +00:00
Compare commits
229
Commits
v20260902.0.0
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3ec51c1200 | ||
|
|
d0ef28cbfd | ||
|
|
cb8a3fb7d6 | ||
|
|
7ec705e616 | ||
|
|
9dfbb454d1 | ||
|
|
5de899da4b | ||
|
|
cbfc2720d5 | ||
|
|
0100901667 | ||
|
|
b3db95c3ea | ||
|
|
a9f87693ba | ||
|
|
b06709b63b | ||
|
|
99278dcd1f | ||
|
|
2d6eb7951a | ||
|
|
7e26b7fe0a | ||
|
|
2f955582a4 | ||
|
|
31bb5ff621 | ||
|
|
c21ad7a3aa | ||
|
|
4a48066d87 | ||
|
|
a0cdb5d3b6 | ||
|
|
3f1b678095 | ||
|
|
ffb821e344 | ||
|
|
d9bf32dd9c | ||
|
|
2fe70c89fa | ||
|
|
9d6589110e | ||
|
|
e67272033b | ||
|
|
0e7afd9f90 | ||
|
|
cbbfc3966a | ||
|
|
59f5adc934 | ||
|
|
67ab444604 | ||
|
|
5e44fbd4e9 | ||
|
|
8abb61ebe6 | ||
|
|
50634ae07e | ||
|
|
8d426b788d | ||
|
|
a57dd64196 | ||
|
|
451bbf1da9 | ||
|
|
358fb8e58a | ||
|
|
1a36eff391 | ||
|
|
cc487aa2ac | ||
|
|
21be842303 | ||
|
|
7af5bd4d2e | ||
|
|
f8e22ae674 | ||
|
|
a4a5c1bb29 | ||
|
|
2220f750dd | ||
|
|
27980ed25d | ||
|
|
ce75147186 | ||
|
|
9049a63038 | ||
|
|
d083eb0939 | ||
|
|
129cb9e765 | ||
|
|
5ed6c58c6b | ||
|
|
ecd881a280 | ||
|
|
ca7a105f15 | ||
|
|
8e37334d2a | ||
|
|
0e4ac57482 | ||
|
|
7df37fd815 | ||
|
|
db4ad89a5d | ||
|
|
56b7cdb179 | ||
|
|
b9cff94d24 | ||
|
|
685026dd39 | ||
|
|
fbb42763d9 | ||
|
|
d4467a1f6a | ||
|
|
718d5a60b1 | ||
|
|
faf9eff6e2 | ||
|
|
1a7be839cd | ||
|
|
e4c230fb75 | ||
|
|
b18e587093 | ||
|
|
f7e4f4b5db | ||
|
|
335c079f82 | ||
|
|
8edf3488f7 | ||
|
|
ad31cff2a4 | ||
|
|
9f146e6ad1 | ||
|
|
0688bdda6d | ||
|
|
9c5170d47c | ||
|
|
4c940f2a39 | ||
|
|
3f79eb32c3 | ||
|
|
1c4933e23c | ||
|
|
6e79823f74 | ||
|
|
b6e4349caa | ||
|
|
9830e147ff | ||
|
|
954be67307 | ||
|
|
1ca19fb02c | ||
|
|
48a5fa529d | ||
|
|
f9b490c24f | ||
|
|
faff0e1751 | ||
|
|
78ec09cc25 | ||
|
|
5318ef4562 | ||
|
|
746304935d | ||
|
|
4dd84f4fc8 | ||
|
|
578f96f426 | ||
|
|
94e412031a | ||
|
|
5f24e3f771 | ||
|
|
ccc22f9ac4 | ||
|
|
58938b9775 | ||
|
|
e1534d3ef3 | ||
|
|
db6f370575 | ||
|
|
7238d00f4d | ||
|
|
773081ce36 | ||
|
|
4a25ca3937 | ||
|
|
8f78fdf58b | ||
|
|
bcf3658557 | ||
|
|
4090b1fb4a | ||
|
|
d1073e00bd | ||
|
|
9333174b58 | ||
|
|
0a04be011f | ||
|
|
a3d9f7591d | ||
|
|
458eadf0a0 | ||
|
|
edfefba78f | ||
|
|
8b92313a85 | ||
|
|
9e6b142189 | ||
|
|
ff642c1ae5 | ||
|
|
b6685b5140 | ||
|
|
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 | ||
|
|
416dee5762 | ||
|
|
e4c0649cbd | ||
|
|
87ca4578b3 | ||
|
|
740116e1fd | ||
|
|
438ad9fb8f | ||
|
|
eaa5b96079 | ||
|
|
3f7012dba4 | ||
|
|
9bbd04afaa | ||
|
|
9b8502bb6e | ||
|
|
7866ad18fa | ||
|
|
4101914040 | ||
|
|
40889a1337 | ||
|
|
26426dda7f | ||
|
|
d045c45baa | ||
|
|
a409b8e044 | ||
|
|
4289d454f3 | ||
|
|
2df897ab0b | ||
|
|
4443c31ee0 | ||
|
|
acbf1d828c | ||
|
|
9379af28fd | ||
|
|
de5ae9f7e7 | ||
|
|
c171a89f03 | ||
|
|
4bc550320b | ||
|
|
361b982357 | ||
|
|
534825fb68 | ||
|
|
9e3d10a6e8 | ||
|
|
ddb4b5d5dd | ||
|
|
ca34692cbb | ||
|
|
2bffd909a5 | ||
|
|
d400e700ac | ||
|
|
755a87c74d | ||
|
|
b30fc7aa8b | ||
|
|
4f4bd431f5 | ||
|
|
79757458d6 | ||
|
|
c09aab080f | ||
|
|
580960d958 | ||
|
|
c21475e3e7 | ||
|
|
09b5289d83 | ||
|
|
f66bd0858d | ||
|
|
ce8cc80f66 | ||
|
|
66b5412103 | ||
|
|
11b6894dae | ||
|
|
02b86d67ad | ||
|
|
f55c3c22fe | ||
|
|
eb601cd51e | ||
|
|
2ee739dbe1 | ||
|
|
a15b70476d | ||
|
|
5f124cc812 | ||
|
|
ce3378354d | ||
|
|
cb02200a24 | ||
|
|
fd36a8909c | ||
|
|
78c15d2a9a | ||
|
|
5815bb8e3f | ||
|
|
d366cdbcb0 | ||
|
|
52b32ce2d4 | ||
|
|
e976c4fbb5 | ||
|
|
81f38c1db7 | ||
|
|
5221b3fb84 | ||
|
|
53bd7a5587 | ||
|
|
100ab61c82 | ||
|
|
4d48c40ce1 | ||
|
|
93ade07c57 | ||
|
|
c1d8ca3c14 | ||
|
|
38707313d7 | ||
|
|
8eb2f5cec6 | ||
|
|
a7d66cb8e6 | ||
|
|
9db804f7c0 | ||
|
|
e93395e334 | ||
|
|
c9b8645469 | ||
|
|
f92681dbae |
No files matched your search
@@ -26,18 +26,8 @@ updates:
|
||||
# https://github.com/dropwizard/dropwizard/pull/11273
|
||||
- dependency-name: "ch.qos.logback:*"
|
||||
versions: [">=1.6.0"]
|
||||
# https://github.com/jetty/jetty.project/issues/15657
|
||||
- dependency-name: "org.eclipse.jetty:*"
|
||||
versions: ["<=12.1.12"]
|
||||
- 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"]
|
||||
|
||||
# Dependency convergence sentinels, pinned to specific versions
|
||||
- dependency-name: "tools.jackson.core:jackson-databind"
|
||||
- dependency-name: "com.squareup.okio:okio-jvm"
|
||||
|
||||
groups:
|
||||
|
||||
@@ -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@d1374f8ac74474200d16ef8ecee22c7ae7a51880 # v6.3.0
|
||||
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@d1374f8ac74474200d16ef8ecee22c7ae7a51880 # v6.3.0
|
||||
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@d1374f8ac74474200d16ef8ecee22c7ae7a51880 # v6.3.0
|
||||
with:
|
||||
distribution: 'temurin'
|
||||
java-version-file: .java-version
|
||||
@@ -65,8 +65,8 @@ 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
|
||||
run: ./mvnw -e -B clean verify -DfoundationDb.serviceContainerNamePrefix=foundationdb
|
||||
run: ./mvnw -e -B -Pprepull-testcontainers-images clean verify -DfoundationDb.serviceContainerNamePrefix=foundationdb
|
||||
+1
-1
@@ -1 +1 @@
|
||||
temurin-25
|
||||
temurin-27
|
||||
@@ -36,6 +36,12 @@
|
||||
<groupId>org.eclipse.jetty.http2</groupId>
|
||||
<artifactId>jetty-http2-client-transport</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.webauthn4j</groupId>
|
||||
<artifactId>webauthn4j-test</artifactId>
|
||||
<version>${webauthn4j.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
||||
@@ -1,101 +0,0 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.signal.integration;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonGenerator;
|
||||
import com.fasterxml.jackson.core.JsonParser;
|
||||
import com.fasterxml.jackson.databind.DeserializationContext;
|
||||
import com.fasterxml.jackson.databind.JsonDeserializer;
|
||||
import com.fasterxml.jackson.databind.JsonSerializer;
|
||||
import com.fasterxml.jackson.databind.SerializerProvider;
|
||||
import java.io.IOException;
|
||||
import java.util.Base64;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.signal.libsignal.protocol.ecc.ECPublicKey;
|
||||
|
||||
public final class Codecs {
|
||||
|
||||
private Codecs() {
|
||||
// utility class
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
public interface CheckedFunction<T, R> {
|
||||
R apply(T t) throws Exception;
|
||||
}
|
||||
|
||||
public static class Base64BasedSerializer<T> extends JsonSerializer<T> {
|
||||
|
||||
private final CheckedFunction<T, byte[]> mapper;
|
||||
|
||||
public Base64BasedSerializer(final CheckedFunction<T, byte[]> mapper) {
|
||||
this.mapper = mapper;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void serialize(final T value, final JsonGenerator gen, final SerializerProvider serializers) throws IOException {
|
||||
try {
|
||||
gen.writeString(Base64.getEncoder().withoutPadding().encodeToString(mapper.apply(value)));
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static class Base64BasedDeserializer<T> extends JsonDeserializer<T> {
|
||||
|
||||
private final CheckedFunction<byte[], T> mapper;
|
||||
|
||||
public Base64BasedDeserializer(final CheckedFunction<byte[], T> mapper) {
|
||||
this.mapper = mapper;
|
||||
}
|
||||
|
||||
@Override
|
||||
public T deserialize(final JsonParser p, final DeserializationContext ctxt) throws IOException {
|
||||
try {
|
||||
return mapper.apply(Base64.getDecoder().decode(p.getValueAsString()));
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static class ByteArraySerializer extends Base64BasedSerializer<byte[]> {
|
||||
public ByteArraySerializer() {
|
||||
super(bytes -> bytes);
|
||||
}
|
||||
}
|
||||
|
||||
public static class ByteArrayDeserializer extends Base64BasedDeserializer<byte[]> {
|
||||
public ByteArrayDeserializer() {
|
||||
super(bytes -> bytes);
|
||||
}
|
||||
}
|
||||
|
||||
public static class ECPublicKeySerializer extends Base64BasedSerializer<ECPublicKey> {
|
||||
public ECPublicKeySerializer() {
|
||||
super(ECPublicKey::serialize);
|
||||
}
|
||||
}
|
||||
|
||||
public static class ECPublicKeyDeserializer extends Base64BasedDeserializer<ECPublicKey> {
|
||||
public ECPublicKeyDeserializer() {
|
||||
super(ECPublicKey::new);
|
||||
}
|
||||
}
|
||||
|
||||
public static class IdentityKeySerializer extends Base64BasedSerializer<IdentityKey> {
|
||||
public IdentityKeySerializer() {
|
||||
super(IdentityKey::serialize);
|
||||
}
|
||||
}
|
||||
|
||||
public static class IdentityKeyDeserializer extends Base64BasedDeserializer<IdentityKey> {
|
||||
public IdentityKeyDeserializer() {
|
||||
super(bytes -> new IdentityKey(bytes, 0));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,41 +8,72 @@ package org.signal.integration;
|
||||
import static java.util.Objects.requireNonNull;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.google.common.io.Resources;
|
||||
import com.google.common.net.HttpHeaders;
|
||||
import com.webauthn4j.data.AuthenticatorAssertionResponse;
|
||||
import com.webauthn4j.data.PublicKeyCredential;
|
||||
import com.webauthn4j.data.PublicKeyCredentialDescriptor;
|
||||
import com.webauthn4j.data.PublicKeyCredentialRequestOptions;
|
||||
import com.webauthn4j.data.PublicKeyCredentialType;
|
||||
import com.webauthn4j.data.UserVerificationRequirement;
|
||||
import com.webauthn4j.data.client.challenge.DefaultChallenge;
|
||||
import com.webauthn4j.test.client.ClientPlatform;
|
||||
import io.dropwizard.configuration.ConfigurationValidationException;
|
||||
import io.dropwizard.jersey.validation.Validators;
|
||||
import io.github.resilience4j.retry.Retry;
|
||||
import io.grpc.ChannelCredentials;
|
||||
import io.grpc.ClientInterceptor;
|
||||
import io.grpc.Grpc;
|
||||
import io.grpc.ManagedChannel;
|
||||
import io.grpc.Metadata;
|
||||
import io.grpc.TlsChannelCredentials;
|
||||
import io.grpc.stub.MetadataUtils;
|
||||
import jakarta.validation.ConstraintViolation;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.lang.invoke.MethodHandles;
|
||||
import java.net.URI;
|
||||
import java.net.URL;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.InvalidKeyException;
|
||||
import java.security.KeyStore;
|
||||
import java.security.SecureRandom;
|
||||
import java.security.cert.CertificateException;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import javax.annotation.Nullable;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.commons.lang3.Validate;
|
||||
import org.apache.commons.lang3.exception.ExceptionUtils;
|
||||
import org.apache.commons.lang3.tuple.Pair;
|
||||
import org.eclipse.jetty.client.HttpClient;
|
||||
import org.eclipse.jetty.client.Request;
|
||||
import org.eclipse.jetty.http2.client.HTTP2Client;
|
||||
import org.eclipse.jetty.http2.client.transport.HttpClientTransportOverHTTP2;
|
||||
import org.eclipse.jetty.io.ClientConnector;
|
||||
import org.eclipse.jetty.util.ssl.SslContextFactory;
|
||||
import org.eclipse.jetty.websocket.api.exceptions.UpgradeException;
|
||||
import org.eclipse.jetty.websocket.client.ClientUpgradeRequest;
|
||||
import org.eclipse.jetty.websocket.client.WebSocketClient;
|
||||
import org.signal.integration.config.Config;
|
||||
import org.signal.integration.config.WebAuthnConfiguration;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.signal.libsignal.protocol.ecc.ECKeyPair;
|
||||
import org.signal.libsignal.protocol.ecc.ECPublicKey;
|
||||
@@ -58,6 +89,8 @@ import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialPresentation;
|
||||
import org.signal.libsignal.zkgroup.receipts.ReceiptSerial;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.RequireAuthenticationInterceptor;
|
||||
import org.whispersystems.textsecuregcm.configuration.RetryConfiguration;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountIdentityResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.DeviceActivationRequest;
|
||||
@@ -65,11 +98,16 @@ import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.RegistrationRequest;
|
||||
import org.whispersystems.textsecuregcm.http.FaultTolerantHttpClient;
|
||||
import org.whispersystems.textsecuregcm.mappers.MfaFailureExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.TotpManager;
|
||||
import org.whispersystems.textsecuregcm.util.CertificateUtil;
|
||||
import org.whispersystems.textsecuregcm.util.HeaderUtils;
|
||||
import org.whispersystems.textsecuregcm.util.HttpUtils;
|
||||
import org.whispersystems.textsecuregcm.util.ResilienceUtil;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
import org.whispersystems.textsecuregcm.util.ThrowingSupplier;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
public final class Operations {
|
||||
|
||||
@@ -77,19 +115,37 @@ public final class Operations {
|
||||
|
||||
private static final Config CONFIG = loadConfigFromClasspath("config.yml");
|
||||
|
||||
private static final String GRPC_DOMAIN = "grpc." + CONFIG.domain();
|
||||
|
||||
private static final IntegrationTools INTEGRATION_TOOLS = IntegrationTools.create(CONFIG);
|
||||
|
||||
private static final String USER_AGENT = "integration-test";
|
||||
|
||||
private static final FaultTolerantHttpClient CLIENT = buildClient();
|
||||
|
||||
private static final FaultTolerantHttpClient NO_RETRY_CLIENT = buildNoRetryClient();
|
||||
|
||||
private static final WebSocketClient WEB_SOCKET_CLIENT = buildWebSocketClient();
|
||||
|
||||
private static final ManagedChannel GRPC_CHANNEL = buildGrpcChannel();
|
||||
|
||||
private static final Retry WEBSOCKET_CONNECT_RETRY = Retry.of("integration-test-websocket-connect",
|
||||
new RetryConfiguration().toRetryConfigBuilder()
|
||||
.retryOnException(Operations::isRetryableConnectFailure)
|
||||
.build());
|
||||
private Operations() {
|
||||
// utility class
|
||||
}
|
||||
|
||||
static boolean isRetryableConnectFailure(final Throwable e) {
|
||||
final Throwable cause = e instanceof ExecutionException ? e.getCause() : e;
|
||||
if (cause instanceof UpgradeException upgradeException) {
|
||||
return upgradeException.getResponseStatusCode() >= 500
|
||||
|| ExceptionUtils.getRootCause(upgradeException) instanceof TimeoutException;
|
||||
}
|
||||
return cause instanceof IOException;
|
||||
}
|
||||
|
||||
public record Receipt(ReceiptSerial serial, ReceiptCredential credential) {}
|
||||
|
||||
public static Receipt getPrescribedReceipt() throws InvalidInputException {
|
||||
@@ -99,6 +155,10 @@ public final class Operations {
|
||||
);
|
||||
}
|
||||
|
||||
public static WebAuthnConfiguration getWebAuthnConfiguration() {
|
||||
return CONFIG.webAuthn();
|
||||
}
|
||||
|
||||
public static TestUser registerNumberlessUser(final ReceiptCredential receiptCredential)
|
||||
throws InvalidInputException, VerificationFailedException {
|
||||
final String accountPassword = Base64.getEncoder().encodeToString(randomBytes(32));
|
||||
@@ -113,6 +173,7 @@ public final class Operations {
|
||||
null,
|
||||
receiptCredentialPresentation.serialize(),
|
||||
null,
|
||||
null,
|
||||
user.accountAttributes(),
|
||||
true,
|
||||
new IdentityKey(aciIdentityKeyPair.getPublicKey()),
|
||||
@@ -133,6 +194,133 @@ public final class Operations {
|
||||
return user;
|
||||
}
|
||||
|
||||
public static TestUser recoverNumberlessUserWithTotp(final TestUser testUser, final ThrowingSupplier<Integer, InvalidKeyException> totpSupplier) throws InvalidKeyException {
|
||||
final TestUser recoveredUser = TestUser.createNumberlessForRecovery(testUser.accountPassword(), testUser.registrationPassword());
|
||||
final ECKeyPair aciIdentityKeyPair = ECKeyPair.generate();
|
||||
final ECKeyPair pniIdentityKeyPair = ECKeyPair.generate();
|
||||
final DeviceActivationRequest deviceActivationRequest = new DeviceActivationRequest(
|
||||
generateSignedECPreKey(1, aciIdentityKeyPair),
|
||||
Optional.of(generateSignedECPreKey(2, pniIdentityKeyPair)),
|
||||
generateSignedKEMPreKey(3, aciIdentityKeyPair),
|
||||
Optional.of(generateSignedKEMPreKey(4, pniIdentityKeyPair)),
|
||||
Optional.empty(),
|
||||
Optional.empty());
|
||||
|
||||
// The server only allows one redemption of a TOTP per time-step, which we may have used up during `confirm`. Retry
|
||||
// until the next time-step.
|
||||
final Instant retryUntil = Instant.now().plus(TotpManager.TOTP.getTimeStep().plus(Duration.ofSeconds(1)));
|
||||
while (true) {
|
||||
final Pair<Integer, AccountIdentityResponse> registrationResponse = apiPost("/v1/registration",
|
||||
new RegistrationRequest(null,
|
||||
testUser.registrationPassword(),
|
||||
null,
|
||||
totpSupplier.get(),
|
||||
null,
|
||||
recoveredUser.accountAttributes(),
|
||||
true,
|
||||
new IdentityKey(aciIdentityKeyPair.getPublicKey()),
|
||||
new IdentityKey(pniIdentityKeyPair.getPublicKey()),
|
||||
deviceActivationRequest))
|
||||
// For a numberless account recovery, the username is the ACI
|
||||
.authorized(testUser.aciUuid().toString(), testUser.accountPassword())
|
||||
.execute(AccountIdentityResponse.class);
|
||||
if (registrationResponse.getLeft() == 441 && Instant.now().isBefore(retryUntil)) {
|
||||
Util.sleep(Duration.ofSeconds(1).toMillis());
|
||||
continue;
|
||||
}
|
||||
|
||||
Validate.isTrue(HttpUtils.isSuccessfulResponse(registrationResponse.getLeft()),
|
||||
"Unexpected response code: %d", registrationResponse.getLeft());
|
||||
recoveredUser.setAciUuid(registrationResponse.getRight().uuid());
|
||||
return recoveredUser;
|
||||
}
|
||||
}
|
||||
|
||||
public static TestUser recoverNumberlessUserWithWebAuthn(final TestUser testUser,
|
||||
final ClientPlatform clientPlatform,
|
||||
final byte[] credentialId,
|
||||
final String relyingPartyId) {
|
||||
final TestUser recoveredUser = TestUser.createNumberlessForRecovery(testUser.accountPassword(), testUser.registrationPassword());
|
||||
|
||||
final ECKeyPair aciIdentityKeyPair = ECKeyPair.generate();
|
||||
final ECKeyPair pniIdentityKeyPair = ECKeyPair.generate();
|
||||
final RegistrationRequest initialRequest = new RegistrationRequest(null,
|
||||
testUser.registrationPassword(),
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
recoveredUser.accountAttributes(),
|
||||
true,
|
||||
new IdentityKey(aciIdentityKeyPair.getPublicKey()),
|
||||
new IdentityKey(pniIdentityKeyPair.getPublicKey()),
|
||||
new DeviceActivationRequest(generateSignedECPreKey(1, aciIdentityKeyPair),
|
||||
Optional.of(generateSignedECPreKey(2, pniIdentityKeyPair)),
|
||||
generateSignedKEMPreKey(3, aciIdentityKeyPair),
|
||||
Optional.of(generateSignedKEMPreKey(4, pniIdentityKeyPair)),
|
||||
Optional.empty(),
|
||||
Optional.empty()));
|
||||
|
||||
// we expect (and need) failure with status 441, which will contain the WebAuthn challenge
|
||||
MfaFailureExceptionMapper.MfaFailureResponse mfaFailureResponse = apiPost("/v1/registration", initialRequest)
|
||||
// For a numberless account recovery, the username is the ACI
|
||||
.authorized(testUser.aciUuid().toString(), testUser.accountPassword())
|
||||
.executeExpectStatusCode(441, MfaFailureExceptionMapper.MfaFailureResponse.class);
|
||||
|
||||
// Retry a 441 to 3 times. It's possible we burned a challenge on a 500 that actually succeeded, but we didn't see
|
||||
// the response, so we can retry on the new challenge.
|
||||
int attempt = 0;
|
||||
while (true) {
|
||||
attempt++;
|
||||
Validate.isTrue(mfaFailureResponse.webAuthnParameters().allowedCredentialIds()
|
||||
.stream()
|
||||
.anyMatch(allowedId -> Arrays.equals(allowedId, credentialId)),
|
||||
"Expected MFA failure to contain credentialId");
|
||||
|
||||
final PublicKeyCredential<AuthenticatorAssertionResponse, ?> credential =
|
||||
clientPlatform.get(new PublicKeyCredentialRequestOptions(
|
||||
new DefaultChallenge(mfaFailureResponse.webAuthnParameters().challenge()),
|
||||
null,
|
||||
relyingPartyId,
|
||||
List.of(new PublicKeyCredentialDescriptor(PublicKeyCredentialType.PUBLIC_KEY, credentialId, null)),
|
||||
UserVerificationRequirement.DISCOURAGED,
|
||||
null));
|
||||
|
||||
final RegistrationRequest registrationRequest = new RegistrationRequest(null,
|
||||
testUser.registrationPassword(),
|
||||
null,
|
||||
null,
|
||||
webAuthnVerificationResponseJson(credential),
|
||||
recoveredUser.accountAttributes(),
|
||||
true,
|
||||
new IdentityKey(aciIdentityKeyPair.getPublicKey()),
|
||||
new IdentityKey(pniIdentityKeyPair.getPublicKey()),
|
||||
new DeviceActivationRequest(generateSignedECPreKey(1, aciIdentityKeyPair),
|
||||
Optional.of(generateSignedECPreKey(2, pniIdentityKeyPair)),
|
||||
generateSignedKEMPreKey(3, aciIdentityKeyPair),
|
||||
Optional.of(generateSignedKEMPreKey(4, pniIdentityKeyPair)),
|
||||
Optional.empty(),
|
||||
Optional.empty()));
|
||||
|
||||
final Pair<Integer, JsonNode> registrationResponse = apiPost("/v1/registration", registrationRequest)
|
||||
// For a numberless account recovery, the username is the ACI
|
||||
.authorized(testUser.aciUuid().toString(), testUser.accountPassword())
|
||||
.execute(JsonNode.class);
|
||||
|
||||
if (registrationResponse.getLeft() == 441 && attempt < 3) {
|
||||
mfaFailureResponse = SystemMapper.jsonMapper()
|
||||
.convertValue(registrationResponse.getRight(), MfaFailureExceptionMapper.MfaFailureResponse.class);
|
||||
continue;
|
||||
}
|
||||
|
||||
Validate.isTrue(HttpUtils.isSuccessfulResponse(registrationResponse.getLeft()),
|
||||
"Unexpected response code: %d, body: %s", registrationResponse.getLeft(), registrationResponse.getRight());
|
||||
recoveredUser.setAciUuid(SystemMapper.jsonMapper()
|
||||
.convertValue(registrationResponse.getRight(), AccountIdentityResponse.class).uuid());
|
||||
return recoveredUser;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static TestUser newRegisteredUser(final String number) {
|
||||
final byte[] registrationPassword = populateRandomRecoveryPassword(number);
|
||||
final String accountPassword = Base64.getEncoder().encodeToString(randomBytes(32));
|
||||
@@ -148,6 +336,7 @@ public final class Operations {
|
||||
registrationPassword,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
accountAttributes,
|
||||
true,
|
||||
new IdentityKey(aciIdentityKeyPair.getPublicKey()),
|
||||
@@ -178,7 +367,24 @@ public final class Operations {
|
||||
}
|
||||
|
||||
public static void deleteUser(final TestUser user) {
|
||||
apiDelete("/v1/accounts/me").authorized(user).executeExpectSuccess();
|
||||
final AtomicInteger attempts = new AtomicInteger();
|
||||
final Retry retry = Retry.of("integration-test-delete-user",
|
||||
new RetryConfiguration().<Integer>toRetryConfigBuilder()
|
||||
.retryOnResult(statusCode -> statusCode >= 500)
|
||||
.build());
|
||||
final int statusCode = retry.executeSupplier(() -> {
|
||||
attempts.incrementAndGet();
|
||||
return apiDelete("/v1/accounts/me")
|
||||
.authorized(user)
|
||||
// disable retries, since this endpoint is not idempotent
|
||||
.withoutRetries()
|
||||
.execute()
|
||||
.getLeft();
|
||||
});
|
||||
|
||||
// If we had to retry a 500 where the account was already deleted, we would fail authorization
|
||||
Validate.isTrue(HttpUtils.isSuccessfulResponse(statusCode) || (attempts.get() > 1 && statusCode == 401),
|
||||
"Unexpected response code: %d", statusCode);
|
||||
}
|
||||
|
||||
public static String peekVerificationSessionPushChallenge(final String sessionId) {
|
||||
@@ -239,7 +445,7 @@ public final class Operations {
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] randomBytes(int numBytes) {
|
||||
public static byte[] randomBytes(final int numBytes) {
|
||||
final byte[] bytes = new byte[numBytes];
|
||||
new SecureRandom().nextBytes(bytes);
|
||||
return bytes;
|
||||
@@ -272,6 +478,43 @@ public final class Operations {
|
||||
return URI.create("https://" + CONFIG.domain() + endpoint + query);
|
||||
}
|
||||
|
||||
public static ManagedChannel grpcChannel() {
|
||||
return GRPC_CHANNEL;
|
||||
}
|
||||
|
||||
public static ClientInterceptor authorizationInterceptor(final TestUser user, final byte deviceId) {
|
||||
final String username = "%s.%d".formatted(user.aciUuid().toString(), deviceId);
|
||||
|
||||
final Metadata metadata = new Metadata();
|
||||
metadata.put(RequireAuthenticationInterceptor.AUTHORIZATION_METADATA_KEY,
|
||||
HeaderUtils.basicAuthHeader(username, user.accountPassword()));
|
||||
|
||||
return MetadataUtils.newAttachHeadersInterceptor(metadata);
|
||||
}
|
||||
|
||||
private static ManagedChannel buildGrpcChannel() {
|
||||
try {
|
||||
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)
|
||||
.defaultServiceConfig(Map.of("methodConfig", List.of(Map.of(
|
||||
"name", List.of(Map.of()),
|
||||
"retryPolicy", Map.of(
|
||||
"maxAttempts", 3.0,
|
||||
"initialBackoff", "0.5s",
|
||||
"maxBackoff", "2s",
|
||||
"backoffMultiplier", 2.0,
|
||||
"retryableStatusCodes", List.of("UNAVAILABLE"))))))
|
||||
.enableRetry()
|
||||
.build();
|
||||
} catch (final IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public static class RequestBuilder {
|
||||
|
||||
private final HttpRequest.Builder builder;
|
||||
@@ -280,6 +523,7 @@ public final class Operations {
|
||||
|
||||
private final List<String> queryParams = new ArrayList<>();
|
||||
|
||||
private boolean retryServerErrors = true;
|
||||
|
||||
private RequestBuilder(final HttpRequest.Builder builder, final String endpoint) {
|
||||
this.builder = builder;
|
||||
@@ -317,66 +561,109 @@ public final class Operations {
|
||||
return this;
|
||||
}
|
||||
|
||||
/// Don't automatically retry 5xx responses, for requests that aren't safe to blindly retry
|
||||
public RequestBuilder withoutRetries() {
|
||||
retryServerErrors = false;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Pair<Integer, Void> execute() {
|
||||
return execute(Void.class);
|
||||
}
|
||||
|
||||
public Pair<Integer, Void> executeExpectSuccess() {
|
||||
final Pair<Integer, Void> execute = execute();
|
||||
final RawResponse response = executeRaw();
|
||||
Validate.isTrue(
|
||||
HttpUtils.isSuccessfulResponse(execute.getLeft()),
|
||||
"Unexpected response code: %d",
|
||||
execute.getLeft());
|
||||
return execute;
|
||||
HttpUtils.isSuccessfulResponse(response.statusCode()),
|
||||
"Unexpected response code: %d, body: %s",
|
||||
response.statusCode(), response.body());
|
||||
return Pair.of(response.statusCode(), null);
|
||||
}
|
||||
|
||||
public <T> T executeExpectSuccess(final Class<T> expectedType) {
|
||||
final Pair<Integer, T> execute = execute(expectedType);
|
||||
final RawResponse response = executeRaw();
|
||||
Validate.isTrue(
|
||||
HttpUtils.isSuccessfulResponse(execute.getLeft()),
|
||||
"Unexpected response code: %d : %s",
|
||||
execute.getLeft(), execute.getRight());
|
||||
return requireNonNull(execute.getRight());
|
||||
HttpUtils.isSuccessfulResponse(response.statusCode()),
|
||||
"Unexpected response code: %d, body: %s",
|
||||
response.statusCode(), response.body());
|
||||
return requireNonNull(parseBody(response.body(), expectedType));
|
||||
}
|
||||
|
||||
public void executeExpectStatusCode(final int expectedStatusCode) {
|
||||
final Pair<Integer, Void> execute = execute(Void.class);
|
||||
final RawResponse response = executeRaw();
|
||||
Validate.isTrue(
|
||||
execute.getLeft() == expectedStatusCode,
|
||||
"Unexpected response code: %d",
|
||||
execute.getLeft()
|
||||
);
|
||||
response.statusCode() == expectedStatusCode,
|
||||
"Unexpected response code: %d (expected %d), body: %s",
|
||||
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));
|
||||
}
|
||||
|
||||
private record RawResponse(int statusCode, String body) {}
|
||||
|
||||
private RawResponse executeRaw() {
|
||||
builder.uri(serverUri(endpoint, queryParams))
|
||||
.header(HttpHeaders.USER_AGENT, USER_AGENT);
|
||||
return CLIENT.sendAsync(builder.build(), HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8))
|
||||
return (retryServerErrors ? CLIENT : NO_RETRY_CLIENT)
|
||||
.sendAsync(builder.build(), HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8))
|
||||
.whenComplete((response, error) -> {
|
||||
if (error != null) {
|
||||
logger.error("request error", error);
|
||||
error.printStackTrace();
|
||||
}
|
||||
})
|
||||
.thenApply(response -> {
|
||||
try {
|
||||
final T result = expectedType.equals(Void.class)
|
||||
? null
|
||||
: SystemMapper.jsonMapper().readValue(response.body(), expectedType);
|
||||
return Pair.of(response.statusCode(), result);
|
||||
} catch (final IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
})
|
||||
.thenApply(response -> new RawResponse(response.statusCode(), response.body()))
|
||||
.join();
|
||||
}
|
||||
|
||||
@Nullable
|
||||
private static <T> T parseBody(final String body, final Class<T> expectedType) {
|
||||
if (expectedType.equals(Void.class)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
return SystemMapper.jsonMapper().readValue(body, expectedType);
|
||||
} catch (final IOException e) {
|
||||
throw new RuntimeException(
|
||||
"Could not parse response body as %s, body: %s".formatted(expectedType.getSimpleName(), body), e);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private static FaultTolerantHttpClient buildClient() {
|
||||
try {
|
||||
return FaultTolerantHttpClient.newBuilder("integration-test", Executors.newFixedThreadPool(16))
|
||||
.withTrustedServerCertificates(CONFIG.rootCert())
|
||||
final FaultTolerantHttpClient client = FaultTolerantHttpClient.newBuilder("integration-test", Executors.newFixedThreadPool(16))
|
||||
.withTrustedServerCertificates(CONFIG.rootCerts().toArray(String[]::new))
|
||||
.withRetry(null, Executors.newSingleThreadScheduledExecutor())
|
||||
.build();
|
||||
// FaultTolerantHttpClient doesn't expose its Retry; it's the only one registered in this JVM
|
||||
ResilienceUtil.getRetryRegistry().getAllRetries().forEach(retry -> retry.getEventPublisher()
|
||||
.onRetry(event -> logger.warn("Retrying {} after {} failed attempt(s)",
|
||||
event.getName(), event.getNumberOfRetryAttempts(), event.getLastThrowable())));
|
||||
return client;
|
||||
} catch (final CertificateException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private static FaultTolerantHttpClient buildNoRetryClient() {
|
||||
try {
|
||||
return FaultTolerantHttpClient.newBuilder("integration-test-no-retry", Executors.newFixedThreadPool(16))
|
||||
.withTrustedServerCertificates(CONFIG.rootCerts().toArray(String[]::new))
|
||||
.build();
|
||||
} catch (final CertificateException e) {
|
||||
throw new RuntimeException(e);
|
||||
@@ -385,7 +672,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);
|
||||
|
||||
@@ -393,7 +680,17 @@ public final class Operations {
|
||||
connector.setSslContextFactory(sslContextFactory);
|
||||
|
||||
final HTTP2Client http2Client = new HTTP2Client(connector);
|
||||
final HttpClient httpClient = new HttpClient(new HttpClientTransportOverHTTP2(http2Client));
|
||||
final HttpClient httpClient = new HttpClient(new HttpClientTransportOverHTTP2(http2Client)) {
|
||||
// There is an upstream Jetty bug where an HTTP/2 reader can race against and beat a websocket connection in
|
||||
// reading the first websocket frame. See https://github.com/jetty/jetty.project/issues/15981 for more details.
|
||||
//
|
||||
// As a workaround, register a response content listener that never reads. This stops the HTTP client's default
|
||||
// response content consumer from reading websocket frames off the upgraded HTTP/2 stream.
|
||||
@Override
|
||||
public Request newRequest(final URI uri) {
|
||||
return super.newRequest(uri).onResponseContentSource((_, _) -> {});
|
||||
}
|
||||
};
|
||||
|
||||
final WebSocketClient wsClient = new WebSocketClient(httpClient);
|
||||
wsClient.start();
|
||||
@@ -416,18 +713,21 @@ public final class Operations {
|
||||
final String path,
|
||||
final Map<String, String> headers) throws IOException {
|
||||
|
||||
final URI uri = URI.create("wss://grpc." + CONFIG.domain() + path);
|
||||
final URI uri = URI.create("wss://" + GRPC_DOMAIN + path);
|
||||
final ClientUpgradeRequest request = new ClientUpgradeRequest(uri);
|
||||
request.setTimeout(5, TimeUnit.SECONDS);
|
||||
headers.forEach(request::setHeader);
|
||||
|
||||
final WebsocketClientSession listener = new WebsocketClientSession();
|
||||
try {
|
||||
WEB_SOCKET_CLIENT.connect(listener, request).get(5, TimeUnit.SECONDS);
|
||||
return WEBSOCKET_CONNECT_RETRY.executeCallable(() -> {
|
||||
final WebsocketClientSession session = new WebsocketClientSession();
|
||||
WEB_SOCKET_CLIENT.connect(session, request).get();
|
||||
logger.info("Successfully connected to websocket on {}", uri);
|
||||
return session;
|
||||
});
|
||||
} catch (Exception e) {
|
||||
throw new IOException(e);
|
||||
}
|
||||
logger.info("Successfully connected to websocket on {}", uri);
|
||||
return listener;
|
||||
}
|
||||
|
||||
private static Config loadConfigFromClasspath(final String filename) {
|
||||
@@ -466,4 +766,34 @@ public final class Operations {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
/// Serializes an assertion into the [specification](https://www.w3.org/TR/webauthn/#dictdef-authenticationresponsejson) format.
|
||||
static String webAuthnVerificationResponseJson(final PublicKeyCredential<AuthenticatorAssertionResponse, ?> credential) {
|
||||
final AuthenticatorAssertionResponse response = credential.getResponse();
|
||||
|
||||
return """
|
||||
{
|
||||
"id": "%s",
|
||||
"rawId": "%s",
|
||||
"type": "public-key",
|
||||
"clientExtensionResults": {},
|
||||
"response": {
|
||||
"clientDataJSON": "%s",
|
||||
"authenticatorData": "%s",
|
||||
"signature": "%s",
|
||||
"userHandle": %s
|
||||
}
|
||||
}
|
||||
""".formatted(
|
||||
base64Url(credential.getRawId()),
|
||||
base64Url(credential.getRawId()),
|
||||
base64Url(response.getClientDataJSON()),
|
||||
base64Url(response.getAuthenticatorData()),
|
||||
base64Url(response.getSignature()),
|
||||
response.getUserHandle() == null ? "null" : "\"" + base64Url(response.getUserHandle()) + "\"");
|
||||
}
|
||||
|
||||
private static String base64Url(@Nullable final byte[] bytes) {
|
||||
return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
|
||||
}
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.signal.integration;
|
||||
|
||||
import jakarta.annotation.Nullable;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import org.apache.commons.lang3.tuple.Pair;
|
||||
import org.signal.libsignal.protocol.IdentityKeyPair;
|
||||
import org.signal.libsignal.protocol.ecc.ECKeyPair;
|
||||
import org.signal.libsignal.protocol.state.SignedPreKeyRecord;
|
||||
|
||||
public class TestDevice {
|
||||
|
||||
private final byte deviceId;
|
||||
|
||||
private final Map<Integer, Pair<IdentityKeyPair, SignedPreKeyRecord>> signedPreKeys = new ConcurrentHashMap<>();
|
||||
|
||||
|
||||
public static TestDevice create(
|
||||
final byte deviceId,
|
||||
final IdentityKeyPair aciIdentityKeyPair,
|
||||
@Nullable final IdentityKeyPair pniIdentityKeyPair) {
|
||||
final TestDevice device = new TestDevice(deviceId);
|
||||
device.addSignedPreKey(aciIdentityKeyPair);
|
||||
if (pniIdentityKeyPair != null) {
|
||||
device.addSignedPreKey(pniIdentityKeyPair);
|
||||
}
|
||||
return device;
|
||||
}
|
||||
|
||||
public TestDevice(final byte deviceId) {
|
||||
this.deviceId = deviceId;
|
||||
}
|
||||
|
||||
public byte deviceId() {
|
||||
return deviceId;
|
||||
}
|
||||
|
||||
public SignedPreKeyRecord latestSignedPreKey(final IdentityKeyPair identity) {
|
||||
final int id = signedPreKeys.entrySet()
|
||||
.stream()
|
||||
.filter(p -> p.getValue().getLeft().equals(identity))
|
||||
.mapToInt(Map.Entry::getKey)
|
||||
.max()
|
||||
.orElseThrow();
|
||||
return signedPreKeys.get(id).getRight();
|
||||
}
|
||||
|
||||
public SignedPreKeyRecord addSignedPreKey(final IdentityKeyPair identity) {
|
||||
final int nextId = signedPreKeys.keySet().stream().mapToInt(k -> k + 1).max().orElse(0);
|
||||
final ECKeyPair keyPair = ECKeyPair.generate();
|
||||
final byte[] signature = keyPair.getPrivateKey().calculateSignature(keyPair.getPublicKey().serialize());
|
||||
final SignedPreKeyRecord signedPreKeyRecord = new SignedPreKeyRecord(nextId, System.currentTimeMillis(), keyPair, signature);
|
||||
signedPreKeys.put(nextId, Pair.of(identity, signedPreKeyRecord));
|
||||
return signedPreKeyRecord;
|
||||
}
|
||||
}
|
||||
@@ -5,29 +5,15 @@
|
||||
|
||||
package org.signal.integration;
|
||||
|
||||
import static java.util.Objects.requireNonNull;
|
||||
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import java.security.SecureRandom;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.signal.libsignal.protocol.IdentityKeyPair;
|
||||
import org.signal.libsignal.protocol.InvalidKeyException;
|
||||
import org.signal.libsignal.protocol.ecc.ECPublicKey;
|
||||
import org.signal.libsignal.protocol.state.SignedPreKeyRecord;
|
||||
import javax.annotation.Nullable;
|
||||
import org.signal.libsignal.protocol.util.KeyHelper;
|
||||
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
public class TestUser {
|
||||
|
||||
@@ -36,21 +22,14 @@ public class TestUser {
|
||||
@Nullable
|
||||
private final Integer pniRegistrationId;
|
||||
|
||||
private final IdentityKeyPair aciIdentityKey;
|
||||
|
||||
private final Map<Byte, TestDevice> devices = new ConcurrentHashMap<>();
|
||||
|
||||
private final byte[] unidentifiedAccessKey;
|
||||
|
||||
@Nullable
|
||||
private String phoneNumber;
|
||||
private final String phoneNumber;
|
||||
|
||||
@Nullable
|
||||
private IdentityKeyPair pniIdentityKey;
|
||||
private final String accountPassword;
|
||||
|
||||
private String accountPassword;
|
||||
|
||||
private byte[] registrationPassword;
|
||||
private final byte[] registrationPassword;
|
||||
|
||||
private UUID aciUuid;
|
||||
|
||||
@@ -58,40 +37,44 @@ public class TestUser {
|
||||
private UUID pniUuid;
|
||||
|
||||
public static TestUser createNumberless(final String accountPassword, final byte[] accountRecoveryPassword) {
|
||||
final IdentityKeyPair aciIdentityKey = IdentityKeyPair.generate();
|
||||
final int registrationId = KeyHelper.generateRegistrationId(false);
|
||||
final byte[] unidentifiedAccessKey = new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH];
|
||||
new SecureRandom().nextBytes(unidentifiedAccessKey);
|
||||
final byte[] unidentifiedAccessKey = Operations.randomBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
|
||||
|
||||
return new TestUser(
|
||||
registrationId,
|
||||
null,
|
||||
aciIdentityKey,
|
||||
null,
|
||||
null,
|
||||
unidentifiedAccessKey,
|
||||
accountPassword,
|
||||
accountRecoveryPassword);
|
||||
}
|
||||
|
||||
public static TestUser createNumberlessForRecovery(final String accountPassword, final byte[] accountRecoveryPassword) {
|
||||
// Recovering a numberless account requires PNI keys (though they are discarded by the server)
|
||||
final int registrationId = KeyHelper.generateRegistrationId(false);
|
||||
final int pniRegistrationId = KeyHelper.generateRegistrationId(false);
|
||||
final byte[] unidentifiedAccessKey = new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH];
|
||||
new SecureRandom().nextBytes(unidentifiedAccessKey);
|
||||
|
||||
return new TestUser(
|
||||
registrationId,
|
||||
pniRegistrationId,
|
||||
null,
|
||||
unidentifiedAccessKey,
|
||||
accountPassword,
|
||||
accountRecoveryPassword);
|
||||
}
|
||||
|
||||
public static TestUser create(final String phoneNumber, final String accountPassword, final byte[] registrationPassword) {
|
||||
// ACI identity key pair
|
||||
final IdentityKeyPair aciIdentityKey = IdentityKeyPair.generate();
|
||||
// PNI identity key pair
|
||||
final IdentityKeyPair pniIdentityKey = IdentityKeyPair.generate();
|
||||
// registration id
|
||||
final int registrationId = KeyHelper.generateRegistrationId(false);
|
||||
final int pniRegistrationId = KeyHelper.generateRegistrationId(false);
|
||||
// uak
|
||||
final byte[] unidentifiedAccessKey = new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH];
|
||||
new SecureRandom().nextBytes(unidentifiedAccessKey);
|
||||
|
||||
return new TestUser(
|
||||
registrationId,
|
||||
pniRegistrationId,
|
||||
aciIdentityKey,
|
||||
phoneNumber,
|
||||
pniIdentityKey,
|
||||
unidentifiedAccessKey,
|
||||
accountPassword,
|
||||
registrationPassword);
|
||||
@@ -100,39 +83,26 @@ public class TestUser {
|
||||
public TestUser(
|
||||
final int registrationId,
|
||||
@Nullable final Integer pniRegistrationId,
|
||||
final IdentityKeyPair aciIdentityKey,
|
||||
@Nullable final String phoneNumber,
|
||||
@Nullable final IdentityKeyPair pniIdentityKey,
|
||||
final byte[] unidentifiedAccessKey,
|
||||
final String accountPassword,
|
||||
final byte[] registrationPassword) {
|
||||
this.registrationId = registrationId;
|
||||
this.pniRegistrationId = pniRegistrationId;
|
||||
this.aciIdentityKey = aciIdentityKey;
|
||||
this.phoneNumber = phoneNumber;
|
||||
this.pniIdentityKey = pniIdentityKey;
|
||||
this.unidentifiedAccessKey = unidentifiedAccessKey;
|
||||
this.accountPassword = accountPassword;
|
||||
this.registrationPassword = registrationPassword;
|
||||
devices.put(Device.PRIMARY_ID, TestDevice.create(Device.PRIMARY_ID, aciIdentityKey, pniIdentityKey));
|
||||
}
|
||||
|
||||
public int registrationId() {
|
||||
return registrationId;
|
||||
}
|
||||
|
||||
public IdentityKeyPair aciIdentityKey() {
|
||||
return aciIdentityKey;
|
||||
}
|
||||
|
||||
public Optional<String> phoneNumber() {
|
||||
return Optional.ofNullable(phoneNumber);
|
||||
}
|
||||
|
||||
public Optional<IdentityKeyPair> pniIdentityKey() {
|
||||
return Optional.ofNullable(pniIdentityKey);
|
||||
}
|
||||
|
||||
public String accountPassword() {
|
||||
return accountPassword;
|
||||
}
|
||||
@@ -151,9 +121,8 @@ public class TestUser {
|
||||
|
||||
public AccountAttributes accountAttributes() {
|
||||
return new AccountAttributes(true, registrationId, pniRegistrationId, "".getBytes(StandardCharsets.UTF_8), "", true,
|
||||
DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES, null)
|
||||
.setUnidentifiedAccessKey(unidentifiedAccessKey)
|
||||
.setRecoveryPassword(registrationPassword);
|
||||
DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES, registrationPassword)
|
||||
.setUnidentifiedAccessKey(unidentifiedAccessKey);
|
||||
}
|
||||
|
||||
public void setAciUuid(final UUID aciUuid) {
|
||||
@@ -163,59 +132,4 @@ public class TestUser {
|
||||
public void setPniUuid(@Nullable final UUID pniUuid) {
|
||||
this.pniUuid = pniUuid;
|
||||
}
|
||||
|
||||
public void setPhoneNumber(@Nullable final String phoneNumber) {
|
||||
this.phoneNumber = phoneNumber;
|
||||
}
|
||||
|
||||
public void setPniIdentityKey(@Nullable final IdentityKeyPair pniIdentityKey) {
|
||||
this.pniIdentityKey = pniIdentityKey;
|
||||
}
|
||||
|
||||
public void setAccountPassword(final String accountPassword) {
|
||||
this.accountPassword = accountPassword;
|
||||
}
|
||||
|
||||
public void setRegistrationPassword(final byte[] registrationPassword) {
|
||||
this.registrationPassword = registrationPassword;
|
||||
}
|
||||
|
||||
public PreKeySetPublicView preKeys(final byte deviceId, final boolean pni) {
|
||||
final IdentityKeyPair identity = pni
|
||||
? pniIdentityKey
|
||||
: aciIdentityKey;
|
||||
final TestDevice device = requireNonNull(devices.get(deviceId));
|
||||
final SignedPreKeyRecord signedPreKeyRecord = device.latestSignedPreKey(identity);
|
||||
try {
|
||||
return new PreKeySetPublicView(
|
||||
Collections.emptyList(),
|
||||
identity.getPublicKey(),
|
||||
new SignedPreKeyPublicView(
|
||||
signedPreKeyRecord.getId(),
|
||||
signedPreKeyRecord.getKeyPair().getPublicKey(),
|
||||
signedPreKeyRecord.getSignature()
|
||||
)
|
||||
);
|
||||
} catch (InvalidKeyException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public record SignedPreKeyPublicView(
|
||||
int keyId,
|
||||
@JsonSerialize(using = Codecs.ECPublicKeySerializer.class)
|
||||
@JsonDeserialize(using = Codecs.ECPublicKeyDeserializer.class)
|
||||
ECPublicKey publicKey,
|
||||
@JsonSerialize(using = Codecs.ByteArraySerializer.class)
|
||||
@JsonDeserialize(using = Codecs.ByteArrayDeserializer.class)
|
||||
byte[] signature) {
|
||||
}
|
||||
|
||||
public record PreKeySetPublicView(
|
||||
List<String> preKeys,
|
||||
@JsonSerialize(using = Codecs.IdentityKeySerializer.class)
|
||||
@JsonDeserialize(using = Codecs.IdentityKeyDeserializer.class)
|
||||
IdentityKey identityKey,
|
||||
SignedPreKeyPublicView signedPreKey) {
|
||||
}
|
||||
}
|
||||
+20
-12
@@ -5,6 +5,7 @@
|
||||
package org.signal.integration;
|
||||
|
||||
import com.google.protobuf.InvalidProtocolBufferException;
|
||||
import io.github.resilience4j.retry.Retry;
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.ByteBuffer;
|
||||
@@ -19,6 +20,7 @@ import org.eclipse.jetty.websocket.api.Callback;
|
||||
import org.eclipse.jetty.websocket.api.Session;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.configuration.RetryConfiguration;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
import org.whispersystems.websocket.messages.WebSocketMessage;
|
||||
@@ -30,6 +32,10 @@ import org.whispersystems.websocket.messages.protobuf.ProtobufWebSocketMessageFa
|
||||
public class WebsocketClientSession implements Session.Listener.AutoDemanding {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(WebsocketClientSession.class);
|
||||
private static final Retry REQUEST_RETRY = Retry.of("integration-test-websocket-request",
|
||||
new RetryConfiguration().<WebSocketResponseMessage>toRetryConfigBuilder()
|
||||
.retryOnResult(response -> response.getStatus() >= 500)
|
||||
.build());
|
||||
private final WebSocketMessageFactory messageFactory = new ProtobufWebSocketMessageFactory();
|
||||
private final AtomicLong requestId = new AtomicLong();
|
||||
private final ConcurrentHashMap<Long, CompletableFuture<WebSocketResponseMessage>> responseFutures = new ConcurrentHashMap<>();
|
||||
@@ -95,18 +101,20 @@ public class WebsocketClientSession implements Session.Listener.AutoDemanding {
|
||||
final String path,
|
||||
final List<String> headers,
|
||||
final T body) {
|
||||
final Session session = opened.join();
|
||||
final long id = requestId.incrementAndGet();
|
||||
final CompletableFuture<WebSocketResponseMessage> future = new CompletableFuture<>();
|
||||
responseFutures.put(id, future);
|
||||
final Optional<byte[]> maybeBody = Optional.ofNullable(body).map(Operations::encodeJsonBody);
|
||||
final byte[] bytes = messageFactory.createRequest(Optional.of(id), verb, path, headers, maybeBody).toByteArray();
|
||||
session.sendBinary(ByteBuffer.wrap(bytes), Callback.from(() -> {}, throwable -> {
|
||||
if (responseFutures.remove(id) != null) {
|
||||
future.completeExceptionally(throwable);
|
||||
}
|
||||
}));
|
||||
return future.join();
|
||||
return REQUEST_RETRY.executeSupplier(() -> {
|
||||
final Session session = opened.join();
|
||||
final long id = requestId.incrementAndGet();
|
||||
final CompletableFuture<WebSocketResponseMessage> future = new CompletableFuture<>();
|
||||
responseFutures.put(id, future);
|
||||
final Optional<byte[]> maybeBody = Optional.ofNullable(body).map(Operations::encodeJsonBody);
|
||||
final byte[] bytes = messageFactory.createRequest(Optional.of(id), verb, path, headers, maybeBody).toByteArray();
|
||||
session.sendBinary(ByteBuffer.wrap(bytes), Callback.from(() -> {}, throwable -> {
|
||||
if (responseFutures.remove(id) != null) {
|
||||
future.completeExceptionally(throwable);
|
||||
}
|
||||
}));
|
||||
return future.join();
|
||||
});
|
||||
}
|
||||
|
||||
public List<MessageProtos.Envelope> getReceivedEnvelopes() {
|
||||
|
||||
@@ -7,16 +7,19 @@ 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,
|
||||
@NotBlank String prescribedRegistrationCode,
|
||||
@NotBlank String prescribedReceiptSerial,
|
||||
@NotBlank String prescribedReceiptCredential,
|
||||
@NotBlank String serverZkPublicParams) {
|
||||
@NotBlank String serverZkPublicParams,
|
||||
@NotNull @Valid WebAuthnConfiguration webAuthn) {
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.signal.integration.config;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
|
||||
public record WebAuthnConfiguration(
|
||||
@NotBlank String relyingPartyId,
|
||||
@NotBlank String origin) {
|
||||
}
|
||||
@@ -5,24 +5,68 @@
|
||||
|
||||
package org.signal.integration;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import com.eatthepath.otp.TimeBasedOneTimePasswordGenerator;
|
||||
import com.google.protobuf.ByteString;
|
||||
import com.webauthn4j.data.AttestationConveyancePreference;
|
||||
import com.webauthn4j.data.AuthenticatorAttestationResponse;
|
||||
import com.webauthn4j.data.AuthenticatorSelectionCriteria;
|
||||
import com.webauthn4j.data.PublicKeyCredential;
|
||||
import com.webauthn4j.data.PublicKeyCredentialCreationOptions;
|
||||
import com.webauthn4j.data.PublicKeyCredentialParameters;
|
||||
import com.webauthn4j.data.PublicKeyCredentialRpEntity;
|
||||
import com.webauthn4j.data.PublicKeyCredentialType;
|
||||
import com.webauthn4j.data.PublicKeyCredentialUserEntity;
|
||||
import com.webauthn4j.data.ResidentKeyRequirement;
|
||||
import com.webauthn4j.data.UserVerificationRequirement;
|
||||
import com.webauthn4j.data.attestation.statement.COSEAlgorithmIdentifier;
|
||||
import com.webauthn4j.data.client.Origin;
|
||||
import com.webauthn4j.data.client.challenge.DefaultChallenge;
|
||||
import com.webauthn4j.test.EmulatorUtil;
|
||||
import com.webauthn4j.test.authenticator.webauthn.WebAuthnAuthenticatorAdaptor;
|
||||
import com.webauthn4j.test.client.ClientPlatform;
|
||||
import java.security.InvalidKeyException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import javax.crypto.SecretKey;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import org.apache.commons.lang3.tuple.Pair;
|
||||
import org.apache.http.HttpStatus;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.signal.chat.account.AccountsGrpc;
|
||||
import org.signal.chat.account.ConfirmTotpKeyRequest;
|
||||
import org.signal.chat.account.ConfirmTotpKeyResponse;
|
||||
import org.signal.chat.account.FinishWebAuthnRegistrationRequest;
|
||||
import org.signal.chat.account.FinishWebAuthnRegistrationResponse;
|
||||
import org.signal.chat.account.GenerateTotpKeyRequest;
|
||||
import org.signal.chat.account.GenerateTotpKeyResponse;
|
||||
import org.signal.chat.account.ListMfaKeysRequest;
|
||||
import org.signal.chat.account.ListMfaKeysResponse;
|
||||
import org.signal.chat.account.StartWebAuthnRegistrationRequest;
|
||||
import org.signal.chat.account.StartWebAuthnRegistrationResponse;
|
||||
import org.signal.chat.account.TotpParameters;
|
||||
import org.signal.integration.config.WebAuthnConfiguration;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.signal.libsignal.protocol.ecc.ECKeyPair;
|
||||
import org.signal.libsignal.usernames.BaseUsernameException;
|
||||
import org.signal.libsignal.usernames.Username;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.VerificationFailedException;
|
||||
import org.signal.libsignal.zkgroup.internal.ByteArray;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountIdentifierResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountIdentityResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.ChangeNumberRequest;
|
||||
@@ -39,18 +83,149 @@ public class AccountTest {
|
||||
public void testCreateNumberlessAccount()
|
||||
throws VerificationFailedException, InvalidInputException {
|
||||
final Operations.Receipt receipt = Operations.getPrescribedReceipt();
|
||||
final TestUser user = Operations.registerNumberlessUser(receipt.credential());
|
||||
Operations.deleteReceipt(receipt.serial());
|
||||
TestUser user = null;
|
||||
try {
|
||||
user = Operations.registerNumberlessUser(receipt.credential());
|
||||
final Pair<Integer, AccountIdentityResponse> execute = Operations.apiGet("/v1/accounts/whoami")
|
||||
.authorized(user)
|
||||
.execute(AccountIdentityResponse.class);
|
||||
assertEquals(HttpStatus.SC_OK, execute.getLeft());
|
||||
} finally {
|
||||
Operations.deleteReceipt(receipt.serial());
|
||||
Operations.deleteUser(user);
|
||||
if (user != null) {
|
||||
Operations.deleteUser(user);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class RecoverWithMfa {
|
||||
private TestUser user;
|
||||
|
||||
@BeforeEach
|
||||
void setup() throws InvalidInputException, VerificationFailedException {
|
||||
final Operations.Receipt receipt = Operations.getPrescribedReceipt();
|
||||
|
||||
// Clear receipt state in case a previous run had an unclean failure
|
||||
Operations.deleteReceipt(receipt.serial());
|
||||
user = Operations.registerNumberlessUser(receipt.credential());
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void teardown() throws InvalidInputException {
|
||||
final Operations.Receipt receipt = Operations.getPrescribedReceipt();
|
||||
Operations.deleteReceipt(receipt.serial());
|
||||
if (user != null) {
|
||||
Operations.deleteUser(user);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testRecoverWithTotp() throws NoSuchAlgorithmException, InvalidKeyException {
|
||||
final GenerateTotpKeyResponse generateTotpKeyResponse =
|
||||
getAccountsStubForUser(user).generateTotpKey(GenerateTotpKeyRequest.getDefaultInstance());
|
||||
assertEquals(GenerateTotpKeyResponse.ResponseCase.KEY_GENERATED, generateTotpKeyResponse.getResponseCase());
|
||||
|
||||
final TotpParameters totpParameters = generateTotpKeyResponse.getKeyGenerated().getTotpParameters();
|
||||
final TimeBasedOneTimePasswordGenerator totpGenerator = new TimeBasedOneTimePasswordGenerator(
|
||||
Duration.ofSeconds(totpParameters.getTimeStepSeconds()),
|
||||
totpParameters.getPasswordLength(),
|
||||
totpParameters.getAlgorithm());
|
||||
|
||||
final SecretKey totpKey = new SecretKeySpec(
|
||||
generateTotpKeyResponse.getKeyGenerated().getKey().toByteArray(),
|
||||
totpParameters.getAlgorithm());
|
||||
|
||||
final byte[] totpMetadata = Operations.randomBytes(160);
|
||||
|
||||
final ConfirmTotpKeyResponse confirmTotpKeyResponse = getAccountsStubForUser(user)
|
||||
.confirmTotpKey(ConfirmTotpKeyRequest.newBuilder()
|
||||
.setOneTimePassword(totpGenerator.generateOneTimePassword(totpKey, Instant.now()))
|
||||
.setMetadataCiphertext(ByteString.copyFrom(totpMetadata))
|
||||
.build());
|
||||
assertEquals(ConfirmTotpKeyResponse.ResponseCase.KEY_CONFIRMED, confirmTotpKeyResponse.getResponseCase());
|
||||
final int keyId = confirmTotpKeyResponse.getKeyConfirmed().getKeyId();
|
||||
|
||||
final TestUser recoveredUser = Operations.recoverNumberlessUserWithTotp(user, () ->
|
||||
totpGenerator.generateOneTimePassword(totpKey, Instant.now()));
|
||||
|
||||
assertEquals(user.aciUuid(), recoveredUser.aciUuid());
|
||||
|
||||
// MFA key should remain set after re-registration
|
||||
final Map<Integer, ListMfaKeysResponse.MfaKeyMetadata> mfaKeys =
|
||||
getAccountsStubForUser(recoveredUser).listMfaKeys(ListMfaKeysRequest.getDefaultInstance()).getKeysMap();
|
||||
|
||||
assertEquals(1, mfaKeys.size());
|
||||
assertTrue(mfaKeys.containsKey(keyId));
|
||||
assertEquals(ListMfaKeysResponse.MfaKeyMetadata.MfaKeyType.MFA_KEY_TYPE_TOTP, mfaKeys.get(keyId).getType());
|
||||
assertArrayEquals(totpMetadata, mfaKeys.get(keyId).getMetadataCiphertext().toByteArray());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRecoverWithWebAuthn() {
|
||||
final WebAuthnConfiguration webAuthnConfiguration = Operations.getWebAuthnConfiguration();
|
||||
final ClientPlatform clientPlatform = new ClientPlatform(new Origin(webAuthnConfiguration.origin()), new WebAuthnAuthenticatorAdaptor(EmulatorUtil.NONE_ATTESTATION_AUTHENTICATOR));
|
||||
final COSEAlgorithmIdentifier algorithm = COSEAlgorithmIdentifier.ES256;
|
||||
|
||||
final StartWebAuthnRegistrationResponse startWebAuthnRegistrationResponse =
|
||||
getAccountsStubForUser(user).startWebAuthnRegistration(StartWebAuthnRegistrationRequest.getDefaultInstance());
|
||||
assertEquals(StartWebAuthnRegistrationResponse.ResponseCase.PARAMS,
|
||||
startWebAuthnRegistrationResponse.getResponseCase());
|
||||
|
||||
final StartWebAuthnRegistrationResponse.WebAuthnCreateParameters webAuthnCreateParameters = startWebAuthnRegistrationResponse.getParams();
|
||||
|
||||
assertTrue(
|
||||
webAuthnCreateParameters.getAllowedAlgorithmsList().contains(algorithm.getValue()));
|
||||
|
||||
final PublicKeyCredential<AuthenticatorAttestationResponse, ?> credential =
|
||||
clientPlatform.create(new PublicKeyCredentialCreationOptions(
|
||||
new PublicKeyCredentialRpEntity(webAuthnConfiguration.relyingPartyId(), "test"),
|
||||
new PublicKeyCredentialUserEntity(webAuthnCreateParameters.getUserHandle().toByteArray(), "test", "test"),
|
||||
new DefaultChallenge(),
|
||||
List.of(new PublicKeyCredentialParameters(PublicKeyCredentialType.PUBLIC_KEY, algorithm)),
|
||||
null,
|
||||
List.of(),
|
||||
new AuthenticatorSelectionCriteria(
|
||||
null, false, ResidentKeyRequirement.DISCOURAGED, UserVerificationRequirement.DISCOURAGED),
|
||||
AttestationConveyancePreference.NONE,
|
||||
null));
|
||||
|
||||
final byte[] metadataCiphertext = Operations.randomBytes(160);
|
||||
|
||||
final FinishWebAuthnRegistrationResponse finishWebAuthnRegistrationResponse = getAccountsStubForUser(user)
|
||||
.finishWebAuthnRegistration(FinishWebAuthnRegistrationRequest.newBuilder()
|
||||
.setAttestationObject(ByteString.copyFrom(credential.getResponse().getAttestationObject()))
|
||||
.setCollectedClientDataJsonBytes(ByteString.copyFrom(credential.getResponse().getClientDataJSON()))
|
||||
.setMetadataCiphertext(ByteString.copyFrom(metadataCiphertext))
|
||||
.build());
|
||||
assertEquals(FinishWebAuthnRegistrationResponse.ResponseCase.KEY_CONFIRMED,
|
||||
finishWebAuthnRegistrationResponse.getResponseCase());
|
||||
final int keyId = finishWebAuthnRegistrationResponse.getKeyConfirmed().getKeyId();
|
||||
|
||||
final TestUser recoveredUser = Operations.recoverNumberlessUserWithWebAuthn(user, clientPlatform, credential.getRawId(),
|
||||
webAuthnConfiguration.relyingPartyId());
|
||||
|
||||
assertEquals(user.aciUuid(), recoveredUser.aciUuid());
|
||||
|
||||
// MFA key should remain set after re-registration
|
||||
final Map<Integer, ListMfaKeysResponse.MfaKeyMetadata> mfaKeys =
|
||||
getAccountsStubForUser(recoveredUser).listMfaKeys(ListMfaKeysRequest.getDefaultInstance()).getKeysMap();
|
||||
|
||||
assertEquals(1, mfaKeys.size());
|
||||
assertTrue(mfaKeys.containsKey(keyId));
|
||||
assertEquals(ListMfaKeysResponse.MfaKeyMetadata.MfaKeyType.MFA_KEY_TYPE_WEBAUTHN, mfaKeys.get(keyId).getType());
|
||||
assertArrayEquals(metadataCiphertext, mfaKeys.get(keyId).getMetadataCiphertext().toByteArray());
|
||||
}
|
||||
}
|
||||
|
||||
private static AccountsGrpc.AccountsBlockingStub getAccountsStubForUser(final TestUser user) {
|
||||
return AccountsGrpc
|
||||
.newBlockingStub(Operations.grpcChannel())
|
||||
.withInterceptors(Operations.authorizationInterceptor(user, Device.PRIMARY_ID));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreateAccount() {
|
||||
final TestUser user = Operations.newRegisteredUser("+19995550101");
|
||||
@@ -115,7 +290,10 @@ public class AccountTest {
|
||||
|
||||
// reserve a username
|
||||
final ReserveUsernameHashRequest reserveUsernameHashRequest = new ReserveUsernameHashRequest(
|
||||
candidates.stream().map(Username::getHash).toList());
|
||||
candidates.stream()
|
||||
.map(Username::getHash)
|
||||
.map(ByteArray::serialize)
|
||||
.toList());
|
||||
// try unauthorized
|
||||
Operations
|
||||
.apiPut("/v1/accounts/username_hash/reserve", reserveUsernameHashRequest)
|
||||
@@ -129,13 +307,13 @@ public class AccountTest {
|
||||
// find which one is the reserved username
|
||||
final byte[] reservedHash = reserveUsernameHashResponse.usernameHash();
|
||||
final Username reservedUsername = candidates.stream()
|
||||
.filter(u -> Arrays.equals(u.getHash(), reservedHash))
|
||||
.filter(u -> Arrays.equals(u.getHash().serialize(), reservedHash))
|
||||
.findAny()
|
||||
.orElseThrow();
|
||||
|
||||
// confirm a username
|
||||
final ConfirmUsernameHashRequest confirmUsernameHashRequest = new ConfirmUsernameHashRequest(
|
||||
reservedUsername.getHash(),
|
||||
reservedUsername.getHash().serialize(),
|
||||
reservedUsername.generateProof(),
|
||||
"cluck cluck i'm a parrot".getBytes()
|
||||
);
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
package org.signal.integration;
|
||||
|
||||
import io.micrometer.common.util.StringUtils;
|
||||
import org.apache.commons.lang3.tuple.Pair;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.whispersystems.textsecuregcm.entities.CreateVerificationSessionRequest;
|
||||
@@ -54,8 +55,13 @@ public class RegistrationTest {
|
||||
// verify code
|
||||
final SubmitVerificationCodeRequest submitVerificationCodeRequest = new SubmitVerificationCodeRequest(
|
||||
params.verificationCode());
|
||||
final VerificationSessionResponse codeVerified = Operations
|
||||
final Pair<Integer, VerificationSessionResponse> codeVerified = Operations
|
||||
.apiPut("/v1/verification/session/%s/code".formatted(sessionId), submitVerificationCodeRequest)
|
||||
.executeExpectSuccess(VerificationSessionResponse.class);
|
||||
.execute(VerificationSessionResponse.class);
|
||||
|
||||
// If we succeeded but then retried a 500, we might have submitted a code when we were already verified
|
||||
Assertions.assertTrue(codeVerified.getLeft() == 200 || codeVerified.getLeft() == 409,
|
||||
"Unexpected response code: " + codeVerified.getLeft());
|
||||
Assertions.assertTrue(codeVerified.getRight().verified());
|
||||
}
|
||||
}
|
||||
@@ -45,8 +45,12 @@
|
||||
</modules>
|
||||
|
||||
<properties>
|
||||
<aws.sdk2.version>2.54.7</aws.sdk2.version>
|
||||
<braintree.version>3.53.0</braintree.version>
|
||||
<aws.sdk2.version>2.59.1</aws.sdk2.version>
|
||||
<braintree.version>3.56.0</braintree.version>
|
||||
<!-- Weird stuff happens with parameter annotation counts under Java 27 with versions of Byte Buddy older than
|
||||
1.18.9, so we need to pull in a newer version than we'd get via Dropwizard -> Mockito -> Byte Buddy. We can drop
|
||||
this when Dropwizard updates and pulls in a newer version of Byte Buddy. -->
|
||||
<byte-buddy.version>1.18.17-jdk5</byte-buddy.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,49 +59,51 @@
|
||||
<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.93.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.8.0-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.23.0</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>
|
||||
<logstash.logback.version>9.0</logstash.logback.version>
|
||||
<lettuce.version>7.9.0.RELEASE</lettuce.version>
|
||||
<libphonenumber.version>9.0.43</libphonenumber.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.17.Final</netty.version>
|
||||
<micrometer.version>1.17.2</micrometer.version>
|
||||
<netty.version>4.2.20.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.85.Final</netty-tcnative.version>
|
||||
<!-- Instrumentation releases target upstream opentelemetry versions and include that BOM by reference -->
|
||||
<opentelemetry-instrumentation.version>2.33.1</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 -->
|
||||
<reactor-bom.version>2025.0.8</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>
|
||||
<simple-grpc.version>0.3.0</simple-grpc.version>
|
||||
<slf4j.version>2.0.20</slf4j.version>
|
||||
<stripe.version>34.1.0</stripe.version>
|
||||
<swagger.version>2.2.55</swagger.version>
|
||||
<testcontainers.version>2.0.5</testcontainers.version>
|
||||
<webauthn4j.version>0.32.0.RELEASE</webauthn4j.version>
|
||||
|
||||
<!-- images to use in tests via testcontainers -->
|
||||
<!-- Images to use in tests via testcontainers. See also: prepull-testcontainers-images <profile> -->
|
||||
<dynamodb.image>amazon/dynamodb-local:3.3.1@sha256:ff89bd48ff32cd8d9be5fee8873b65b8854dc408f1afe881be6eb00247bc0dab</dynamodb.image>
|
||||
<localstack.image>localstack/localstack:4.14@sha256:3ebc37595918b8accb852f8048fef2aff047d465167edd655528065b07bc364a</localstack.image>
|
||||
<redis.image>redis:7.4-alpine@sha256:6ab0b6e7381779332f97b8ca76193e45b0756f38d4c0dcda72dbb3c32061ab99</redis.image>
|
||||
<redis-cluster.image>docker.io/bitnamilegacy/redis-cluster:7.4.3@sha256:a53d023fdfaf8a8d7ddc58da040d3494e4cb45772644618ffa44c42dcd32b9af</redis-cluster.image>
|
||||
|
||||
<docker.image>eclipse-temurin:25-jre-resolute@sha256:71bfb73662d4146bdc9ee2f97418a764d5ab4e83f4e90baec3b3dcda14071007</docker.image>
|
||||
<docker.image>eclipse-temurin:27-jre-resolute@sha256:16a0cae9bfb17ab4257ac64e3d7585fc49233e7bdf3d376c4545289eaf193929</docker.image>
|
||||
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
</properties>
|
||||
@@ -140,6 +146,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>
|
||||
@@ -168,6 +179,16 @@
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>net.bytebuddy</groupId>
|
||||
<artifactId>byte-buddy</artifactId>
|
||||
<version>${byte-buddy.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>net.bytebuddy</groupId>
|
||||
<artifactId>byte-buddy-agent</artifactId>
|
||||
<version>${byte-buddy.version}</version>
|
||||
</dependency>
|
||||
<!-- Needed for gRPC with Java 9+ -->
|
||||
<dependency>
|
||||
<groupId>org.apache.tomcat</groupId>
|
||||
@@ -189,17 +210,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>
|
||||
@@ -252,11 +266,6 @@
|
||||
<artifactId>lettuce-core</artifactId>
|
||||
<version>${lettuce.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>net.logstash.logback</groupId>
|
||||
<artifactId>logstash-logback-encoder</artifactId>
|
||||
<version>${logstash.logback.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-csv</artifactId>
|
||||
@@ -298,11 +307,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>
|
||||
@@ -311,13 +315,13 @@
|
||||
<dependency>
|
||||
<groupId>com.redis</groupId>
|
||||
<artifactId>testcontainers-redis</artifactId>
|
||||
<version>2.2.4</version>
|
||||
<version>3.0.1</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.signal</groupId>
|
||||
<artifactId>libsignal-server</artifactId>
|
||||
<version>0.101.2</version>
|
||||
<version>0.108.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.signal</groupId>
|
||||
@@ -331,11 +335,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>
|
||||
@@ -439,6 +438,46 @@
|
||||
</file>
|
||||
</activation>
|
||||
</profile>
|
||||
|
||||
<profile>
|
||||
<!-- Starts pulling Testcontainers images in the background, reducing test blocks. This is primarily useful in CI,
|
||||
where images are less likely to be cached.-->
|
||||
<id>prepull-testcontainers-images</id>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
<!-- Run once for the whole reactor, rather than once per module -->
|
||||
<inherited>false</inherited>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>prepull-testcontainers-images</id>
|
||||
<phase>initialize</phase>
|
||||
<goals>
|
||||
<goal>exec</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<executable>sh</executable>
|
||||
<arguments>
|
||||
<argument>-c</argument>
|
||||
<!-- Images are pulled one at a time to limit contention with the build. If any fails, then exit status
|
||||
is non-zero, so failure is logged. -->
|
||||
<argument>status=0; for image in "$@"; do docker pull -q "$image" || status=1; done; exit $status</argument>
|
||||
<argument>sh</argument>
|
||||
<argument>${redis-cluster.image}</argument>
|
||||
<argument>${redis.image}</argument>
|
||||
<argument>${dynamodb.image}</argument>
|
||||
<argument>${localstack.image}</argument>
|
||||
</arguments>
|
||||
<async>true</async>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
</profiles>
|
||||
|
||||
<build>
|
||||
@@ -459,12 +498,12 @@
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>3.5.6</version>
|
||||
<version>3.6.1</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-failsafe-plugin</artifactId>
|
||||
<version>3.5.6</version>
|
||||
<version>3.6.1</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
@@ -484,12 +523,12 @@
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
<version>3.6.3</version>
|
||||
<version>3.7.0</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>properties-maven-plugin</artifactId>
|
||||
<version>1.3.0</version>
|
||||
<version>1.4.0</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</pluginManagement>
|
||||
@@ -530,9 +569,9 @@
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.15.0</version>
|
||||
<version>3.16.0</version>
|
||||
<configuration>
|
||||
<release>25</release>
|
||||
<release>27</release>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
@@ -572,7 +611,7 @@
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-enforcer-plugin</artifactId>
|
||||
<version>3.6.3</version>
|
||||
<version>3.7.0</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
@@ -593,7 +632,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>
|
||||
@@ -602,7 +641,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>
|
||||
|
||||
@@ -102,3 +102,5 @@ hlrLookup.apiKey: AAAAAAAAAAA
|
||||
hlrLookup.apiSecret: AAAAAAAAAAA
|
||||
|
||||
foundationDbMessages.versionstampCipherKey.0: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=
|
||||
|
||||
registrationWebAuthn.userHandleBlindingSecret: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=
|
||||
@@ -134,8 +134,6 @@ dynamoDbTables:
|
||||
tableName: Example_ProfilesV2
|
||||
pushChallenge:
|
||||
tableName: Example_PushChallenge
|
||||
pushNotificationExperimentSamples:
|
||||
tableName: Example_PushNotificationExperimentSamples
|
||||
redeemedReceipts:
|
||||
tableName: Example_RedeemedReceipts
|
||||
registrationRecovery:
|
||||
@@ -145,6 +143,8 @@ dynamoDbTables:
|
||||
tableName: Example_RemoteConfig
|
||||
reportMessage:
|
||||
tableName: Example_ReportMessage
|
||||
sandboxAccounts:
|
||||
tableName: Example_SandboxAccounts
|
||||
scheduledJobs:
|
||||
tableName: Example_ScheduledJobs
|
||||
expiration: P7D
|
||||
@@ -230,11 +230,6 @@ svrb:
|
||||
AAAAAAAAAAAAAAAAAAAA
|
||||
-----END CERTIFICATE-----
|
||||
|
||||
messageCache: # Redis server configuration for message store cache
|
||||
persistDelayMinutes: 1
|
||||
cluster:
|
||||
configurationUri: redis://redis.example.com:6379/
|
||||
|
||||
attachments:
|
||||
maxAttachmentUploadSizeInBytes: 1024
|
||||
maxMessageBackupUploadSizeInBytes: 1024
|
||||
@@ -260,7 +255,8 @@ fcm: # FCM configuration
|
||||
credentials: secret://fcm.credentials
|
||||
|
||||
cdn:
|
||||
bucket: cdn # S3 Bucket name
|
||||
baseUrl: https://cdn.example.com # Public base URL for objects in the bucket
|
||||
bucket: cdn # S3 Bucket name
|
||||
credentials:
|
||||
accessKeyId: secret://cdn.accessKey
|
||||
secretAccessKey: secret://cdn.accessSecret
|
||||
@@ -572,3 +568,10 @@ foundationDbMessages:
|
||||
- messages-1
|
||||
- messages-2
|
||||
- messages-3
|
||||
|
||||
registrationWebAuthn:
|
||||
relyingPartyId: example.org
|
||||
origins:
|
||||
- https://example.org
|
||||
challengeTtl: PT2M
|
||||
userHandleBlindingSecret: secret://registrationWebAuthn.userHandleBlindingSecret
|
||||
+36
-36
@@ -14,15 +14,14 @@
|
||||
<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.12.0</firebase-admin.version>
|
||||
<libphonenumber-geocoder.version>3.43</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.2</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>
|
||||
<webauthn4j.version>0.31.9.RELEASE</webauthn4j.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
@@ -58,6 +57,11 @@
|
||||
<artifactId>webauthn4j-appattest</artifactId>
|
||||
<version>${webauthn4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.webauthn4j</groupId>
|
||||
<artifactId>webauthn4j-core</artifactId>
|
||||
<version>${webauthn4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.swagger.core.v3</groupId>
|
||||
<artifactId>swagger-jaxrs2-jakarta</artifactId>
|
||||
@@ -173,25 +177,6 @@
|
||||
<groupId>ch.qos.logback</groupId>
|
||||
<artifactId>logback-classic</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>net.logstash.logback</groupId>
|
||||
<artifactId>logstash-logback-encoder</artifactId>
|
||||
<exclusions>
|
||||
<!-- conflicts with webauthn4j-appattest -->
|
||||
<exclusion>
|
||||
<groupId>tools.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<!-- sentinel for dependency convergence -->
|
||||
<dependency>
|
||||
<groupId>tools.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
<!-- update dependabot.yml when this dependency is removed -->
|
||||
<version>3.2.1</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>io.dropwizard.metrics</groupId>
|
||||
<artifactId>metrics-core</artifactId>
|
||||
@@ -236,7 +221,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>
|
||||
@@ -303,25 +288,29 @@
|
||||
<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>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<!-- 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>
|
||||
<groupId>com.google.code.findbugs</groupId>
|
||||
<artifactId>jsr305</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<!-- manually resolve dependency conflict -->
|
||||
<groupId>org.codehaus.woodstox</groupId>
|
||||
<artifactId>stax2-api</artifactId>
|
||||
<version>4.3.0</version>
|
||||
<groupId>io.github.resilience4j</groupId>
|
||||
<artifactId>resilience4j-bulkhead</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>io.github.resilience4j</groupId>
|
||||
<artifactId>resilience4j-circuitbreaker</artifactId>
|
||||
@@ -505,6 +494,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>
|
||||
@@ -572,6 +566,13 @@
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.webauthn4j</groupId>
|
||||
<artifactId>webauthn4j-test</artifactId>
|
||||
<version>${webauthn4j.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.uuid</groupId>
|
||||
<artifactId>java-uuid-generator</artifactId>
|
||||
@@ -624,6 +625,7 @@
|
||||
<version>${apollo-api-jvm.version}</version>
|
||||
|
||||
<exclusions>
|
||||
<!-- conflicts with kotlin-stdlib -->
|
||||
<exclusion>
|
||||
<groupId>org.jetbrains</groupId>
|
||||
<artifactId>annotations</artifactId>
|
||||
@@ -641,7 +643,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>
|
||||
@@ -780,12 +782,10 @@
|
||||
<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>
|
||||
<!-- This will likely become the default in a future version of Java, and we can remove this flag when
|
||||
that happens. Please see https://openjdk.org/jeps/534 for details. -->
|
||||
<jvmFlag>-XX:+UseCompactObjectHeaders</jvmFlag>
|
||||
</jvmFlags>
|
||||
<ports>
|
||||
<port>8080</port>
|
||||
@@ -856,7 +856,7 @@
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>templating-maven-plugin</artifactId>
|
||||
<version>3.1.0</version>
|
||||
<version>3.2.0</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>filter-src</id>
|
||||
|
||||
+18
-17
@@ -20,6 +20,7 @@ import org.whispersystems.textsecuregcm.configuration.AwsCredentialsProviderFact
|
||||
import org.whispersystems.textsecuregcm.configuration.BackupConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.BadgesConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.BraintreeConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.BulkheadConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.CallQualitySurveyConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.Cdn3StorageManagerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.CdnConfiguration;
|
||||
@@ -46,7 +47,6 @@ import org.whispersystems.textsecuregcm.configuration.KeyTransparencyServiceConf
|
||||
import org.whispersystems.textsecuregcm.configuration.LinkDeviceSecretConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.LoginPurchaseConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.MessageByteLimitCardinalityEstimatorConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.MessageCacheConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.OpenTelemetryConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.PagedSingleUseKEMPreKeyStoreConfiguration;
|
||||
@@ -67,6 +67,7 @@ import org.whispersystems.textsecuregcm.configuration.TotpConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.TurnConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.UnidentifiedDeliveryConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.VirtualThreadConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.WebAuthnConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.ZkConfig;
|
||||
import org.whispersystems.websocket.configuration.WebSocketConfiguration;
|
||||
|
||||
@@ -188,11 +189,6 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
@JsonProperty
|
||||
private FaultTolerantRedisClusterFactory rateLimitersCluster;
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
@JsonProperty
|
||||
private MessageCacheConfiguration messageCache;
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
@@ -337,9 +333,6 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
@JsonProperty
|
||||
private KeyTransparencyServiceConfiguration keyTransparencyService;
|
||||
|
||||
@JsonProperty
|
||||
private boolean logMessageDeliveryLoops;
|
||||
|
||||
@JsonProperty
|
||||
private IdlePrimaryDeviceReminderConfiguration idlePrimaryDeviceReminder =
|
||||
new IdlePrimaryDeviceReminderConfiguration(Duration.ofDays(30));
|
||||
@@ -350,6 +343,9 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
@JsonProperty
|
||||
private Map<String, @Valid RetryConfiguration> retries = Collections.emptyMap();
|
||||
|
||||
@JsonProperty
|
||||
private Map<String, @Valid BulkheadConfiguration> bulkheads = Collections.emptyMap();
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
@@ -390,6 +386,11 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
@JsonProperty
|
||||
private TotpConfiguration registrationTotp = TotpConfiguration.DEFAULT;
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
private WebAuthnConfiguration registrationWebAuthn;
|
||||
|
||||
public TlsKeyStoreConfiguration getTlsKeyStoreConfiguration() {
|
||||
return tlsKeyStore;
|
||||
}
|
||||
@@ -474,10 +475,6 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
return storageService;
|
||||
}
|
||||
|
||||
public MessageCacheConfiguration getMessageCacheConfiguration() {
|
||||
return messageCache;
|
||||
}
|
||||
|
||||
public FaultTolerantRedisClusterFactory getPushSchedulerCluster() {
|
||||
return pushSchedulerCluster;
|
||||
}
|
||||
@@ -606,10 +603,6 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
return keyTransparencyService;
|
||||
}
|
||||
|
||||
public boolean logMessageDeliveryLoops() {
|
||||
return logMessageDeliveryLoops;
|
||||
}
|
||||
|
||||
public IdlePrimaryDeviceReminderConfiguration idlePrimaryDeviceReminderConfiguration() {
|
||||
return idlePrimaryDeviceReminder;
|
||||
}
|
||||
@@ -622,6 +615,10 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
return retries;
|
||||
}
|
||||
|
||||
public Map<String, BulkheadConfiguration> getBulkheadConfigurations() {
|
||||
return bulkheads;
|
||||
}
|
||||
|
||||
public RetryConfiguration getGeneralRedisRetryConfiguration() {
|
||||
return generalRedisRetry;
|
||||
}
|
||||
@@ -653,4 +650,8 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
public TotpConfiguration getRegistrationTotpConfiguration() {
|
||||
return registrationTotp;
|
||||
}
|
||||
|
||||
public WebAuthnConfiguration getRegistrationWebAuthnConfiguration() {
|
||||
return registrationWebAuthn;
|
||||
}
|
||||
}
|
||||
@@ -33,10 +33,11 @@ import io.lettuce.core.metrics.MicrometerOptions;
|
||||
import io.lettuce.core.resource.ClientResources;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.binder.jvm.ExecutorServiceMetrics;
|
||||
import io.netty.channel.DefaultEventLoopGroup;
|
||||
import io.netty.channel.MultiThreadIoEventLoopGroup;
|
||||
import io.netty.channel.local.LocalAddress;
|
||||
import io.netty.channel.local.LocalIoHandler;
|
||||
import io.netty.channel.local.LocalServerChannel;
|
||||
import io.netty.channel.nio.NioEventLoopGroup;
|
||||
import io.netty.channel.nio.NioIoHandler;
|
||||
import io.netty.channel.socket.nio.NioDatagramChannel;
|
||||
import io.netty.channel.socket.nio.NioSocketChannel;
|
||||
import io.netty.handler.ssl.SslContext;
|
||||
@@ -75,6 +76,7 @@ import org.eclipse.jetty.ee10.websocket.server.config.JettyWebSocketServletConta
|
||||
import org.eclipse.jetty.websocket.core.WebSocketExtensionRegistry;
|
||||
import org.eclipse.jetty.websocket.core.server.WebSocketServerComponents;
|
||||
import org.glassfish.jersey.server.ServerProperties;
|
||||
import org.signal.chat.require.Auth;
|
||||
import org.signal.i18n.HeaderControlledResourceBundleLookup;
|
||||
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
|
||||
import org.signal.libsignal.zkgroup.ServerSecretParams;
|
||||
@@ -97,6 +99,7 @@ import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator
|
||||
import org.whispersystems.textsecuregcm.auth.IdlePrimaryDeviceAuthenticatedWebSocketUpgradeFilter;
|
||||
import org.whispersystems.textsecuregcm.auth.PhoneVerificationTokenManager;
|
||||
import org.whispersystems.textsecuregcm.auth.RegistrationLockVerificationManager;
|
||||
import org.whispersystems.textsecuregcm.auth.webauthn.WebAuthnCeremonyManager;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.ProhibitAuthenticationInterceptor;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.RequireAuthenticationInterceptor;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupAuthManager;
|
||||
@@ -111,6 +114,7 @@ import org.whispersystems.textsecuregcm.captcha.CaptchaClient;
|
||||
import org.whispersystems.textsecuregcm.captcha.RegistrationCaptchaManager;
|
||||
import org.whispersystems.textsecuregcm.captcha.ShortCodeExpander;
|
||||
import org.whispersystems.textsecuregcm.configuration.BadgeConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.FoundationDbExternalClientConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.secrets.SecretStore;
|
||||
import org.whispersystems.textsecuregcm.configuration.secrets.SecretsModule;
|
||||
@@ -168,10 +172,12 @@ import org.whispersystems.textsecuregcm.grpc.CredentialsGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.DevicesGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.DonationsGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.ErrorConformanceInterceptor;
|
||||
import org.whispersystems.textsecuregcm.grpc.ConcurrentCallLimitingInterceptor;
|
||||
import org.whispersystems.textsecuregcm.grpc.ErrorMappingInterceptor;
|
||||
import org.whispersystems.textsecuregcm.grpc.ExternalServiceDefinitions;
|
||||
import org.whispersystems.textsecuregcm.grpc.GroupSendTokenUtil;
|
||||
import org.whispersystems.textsecuregcm.grpc.GrpcAllowListInterceptor;
|
||||
import org.whispersystems.textsecuregcm.grpc.GrpcCompressionInterceptor;
|
||||
import org.whispersystems.textsecuregcm.grpc.KeyTransparencyGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.KeysAnonymousGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.KeysGrpcService;
|
||||
@@ -180,6 +186,7 @@ import org.whispersystems.textsecuregcm.grpc.MessageDispatcher;
|
||||
import org.whispersystems.textsecuregcm.grpc.MessagesAnonymousGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.MessagesGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.MetricServerInterceptor;
|
||||
import org.whispersystems.textsecuregcm.grpc.MetricServerStreamTracer;
|
||||
import org.whispersystems.textsecuregcm.grpc.OneTimeDonationsGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.PaymentsGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.ProductConfigurationGrpcService;
|
||||
@@ -189,22 +196,24 @@ import org.whispersystems.textsecuregcm.grpc.RemoteConfigurationGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.RequestAttributesInterceptor;
|
||||
import org.whispersystems.textsecuregcm.grpc.SubscriptionsGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.ValidatingInterceptor;
|
||||
import org.whispersystems.textsecuregcm.grpc.net.H2ConnectionFactory;
|
||||
import org.whispersystems.textsecuregcm.grpc.net.ManagedEventLoopGroup;
|
||||
import org.whispersystems.textsecuregcm.grpc.net.ManagedGrpcServer;
|
||||
import org.whispersystems.textsecuregcm.grpc.net.OmnibusH2Server;
|
||||
import org.whispersystems.textsecuregcm.grpc.net.OmnibusRouter;
|
||||
import org.whispersystems.textsecuregcm.grpc.net.PooledH2ConnectionFactory;
|
||||
import org.whispersystems.textsecuregcm.grpc.net.SniMapper;
|
||||
import org.whispersystems.textsecuregcm.grpc.net.UnpooledH2ConnectionFactory;
|
||||
import org.whispersystems.textsecuregcm.grpc.validators.ValidatorUtils;
|
||||
import org.whispersystems.textsecuregcm.jetty.JettyHttpConfigurationCustomizer;
|
||||
import org.whispersystems.textsecuregcm.keytransparency.KeyTransparencyServiceClient;
|
||||
import org.whispersystems.textsecuregcm.limits.CardinalityEstimator;
|
||||
import org.whispersystems.textsecuregcm.limits.MessageDeliveryLoopMonitor;
|
||||
import org.whispersystems.textsecuregcm.limits.NoopMessageDeliveryLoopMonitor;
|
||||
import org.whispersystems.textsecuregcm.limits.PushChallengeManager;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimitByIpFilter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimitChallengeManager;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.limits.RedisMessageDeliveryLoopMonitor;
|
||||
import org.whispersystems.textsecuregcm.mappers.BackupExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.CallNotPermittedExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.CompletionExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.DeviceLimitExceededExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.IOExceptionMapper;
|
||||
@@ -212,13 +221,14 @@ import org.whispersystems.textsecuregcm.mappers.IllegalStateExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.ImpossiblePhoneNumberExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.InvalidWebsocketAddressExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.JsonMappingExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.MfaFailureExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.NonNormalizedPhoneNumberExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.ObsoletePhoneNumberFormatExceptionMapper;
|
||||
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;
|
||||
@@ -237,7 +247,6 @@ import org.whispersystems.textsecuregcm.push.ProvisioningManager;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationScheduler;
|
||||
import org.whispersystems.textsecuregcm.push.ReceiptSender;
|
||||
import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager;
|
||||
import org.whispersystems.textsecuregcm.redis.ConnectionEventLogger;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
@@ -265,7 +274,6 @@ import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.storage.FoundationDbVersion;
|
||||
import org.whispersystems.textsecuregcm.storage.IssuedReceiptsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.KeysManager;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesCache;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesDynamoDb;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesManager;
|
||||
import org.whispersystems.textsecuregcm.storage.OneTimeDonationsManager;
|
||||
@@ -286,25 +294,29 @@ 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;
|
||||
import org.whispersystems.textsecuregcm.storage.TotpManager;
|
||||
import org.whispersystems.textsecuregcm.storage.VerificationSessionManager;
|
||||
import org.whispersystems.textsecuregcm.storage.VerificationSessions;
|
||||
import org.whispersystems.textsecuregcm.storage.devicecheck.AppleDeviceCheckManager;
|
||||
import org.whispersystems.textsecuregcm.storage.devicecheck.AppleDeviceCheckTrustAnchor;
|
||||
import org.whispersystems.textsecuregcm.storage.devicecheck.AppleDeviceChecks;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.FaultTolerantDatabase;
|
||||
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;
|
||||
@@ -321,6 +333,7 @@ import org.whispersystems.textsecuregcm.websocket.AuthenticatedConnectListener;
|
||||
import org.whispersystems.textsecuregcm.websocket.NoContextTakeoverPerMessageDeflateExtension;
|
||||
import org.whispersystems.textsecuregcm.websocket.ProvisioningConnectListener;
|
||||
import org.whispersystems.textsecuregcm.websocket.WebSocketAccountAuthenticator;
|
||||
import org.whispersystems.textsecuregcm.websocket.WebSocketConnection;
|
||||
import org.whispersystems.textsecuregcm.workers.BackupMetricsCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.BackupUsageRecalculationCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.CertificateCommand;
|
||||
@@ -331,16 +344,16 @@ import org.whispersystems.textsecuregcm.workers.ClearOrphanedFoundationDbQueuesC
|
||||
import org.whispersystems.textsecuregcm.workers.CopyToS3Command;
|
||||
import org.whispersystems.textsecuregcm.workers.DeleteUserCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.IdleDeviceNotificationSchedulerFactory;
|
||||
import org.whispersystems.textsecuregcm.workers.MessagePersisterServiceCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.NotifyIdleDevicesCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.PopulateAccountRecoveryPasswordsCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.ProcessScheduledJobsServiceCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.RegenerateSecondaryDynamoDbTableDataCommand;
|
||||
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;
|
||||
@@ -348,7 +361,6 @@ import org.whispersystems.textsecuregcm.workers.SetUserDiscoverabilityCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.TrimOversizedFoundationDbMessageQueuesCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.UnlinkDeviceCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.UnlinkDevicesWithIdlePrimaryCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.UpdateGambiaPniMappingsCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.ZkParamsCommand;
|
||||
import org.whispersystems.websocket.WebSocketResourceProviderFactory;
|
||||
import org.whispersystems.websocket.setup.WebSocketEnvironment;
|
||||
@@ -393,8 +405,9 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
bootstrap.addCommand(new SetUserDiscoverabilityCommand());
|
||||
bootstrap.addCommand(new UnlinkDeviceCommand());
|
||||
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()));
|
||||
@@ -415,10 +428,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
|
||||
bootstrap.addCommand(new RegenerateSecondaryDynamoDbTableDataCommand());
|
||||
|
||||
bootstrap.addCommand(new PopulateAccountRecoveryPasswordsCommand());
|
||||
|
||||
bootstrap.addCommand(new UpdateGambiaPniMappingsCommand());
|
||||
|
||||
ServiceLoader.load(SpamFilter.class)
|
||||
.stream()
|
||||
.map(ServiceLoader.Provider::get)
|
||||
@@ -445,6 +454,9 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
config.getRetryConfigurations().forEach((name, configuration) ->
|
||||
ResilienceUtil.getRetryRegistry().addConfiguration(name, configuration.toRetryConfigBuilder().build()));
|
||||
|
||||
config.getBulkheadConfigurations().forEach((name, configuration) ->
|
||||
ResilienceUtil.getBulkheadRegistry().addConfiguration(name, configuration.toBulkheadConfig().build()));
|
||||
|
||||
ResilienceUtil.setGeneralRedisRetryConfiguration(config.getGeneralRedisRetryConfiguration());
|
||||
|
||||
ScheduledExecutorService dynamicConfigurationExecutor = ScheduledExecutorServiceBuilder.of(environment, "dynamicConfiguration")
|
||||
@@ -504,9 +516,20 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
// we'd like, but is the least bad option given current constraints.
|
||||
fdb.disableShutdownHook();
|
||||
|
||||
final Map<Integer, List<Database>> messageDatabasesByEpoch;
|
||||
final FoundationDbExternalClientConfiguration externalClientConfiguration = config.getFoundationDbMessagesConfiguration()
|
||||
.externalClientConfiguration();
|
||||
if (externalClientConfiguration != null) {
|
||||
// If threadsPerClient is not specified, we default to the cluster size so that there is 1:1 correspondence between
|
||||
// Database objects and threads.
|
||||
final int clientThreadsPerVersion = externalClientConfiguration.threadsPerClient()
|
||||
.orElseGet(() -> config.getFoundationDbMessagesConfiguration().clusters().size());
|
||||
externalClientConfiguration.clientLibraryPaths().forEach(path -> fdb.options().setExternalClientLibrary(path));
|
||||
fdb.options().setClientThreadsPerVersion(clientThreadsPerVersion);
|
||||
}
|
||||
|
||||
final Map<Integer, List<FaultTolerantDatabase>> messageDatabasesByEpoch;
|
||||
{
|
||||
final Map<String, Database> databasesByName =
|
||||
final Map<String, FaultTolerantDatabase> faultTolerantDatabasesByName =
|
||||
config.getFoundationDbMessagesConfiguration().clusters().entrySet().stream()
|
||||
.collect(Collectors.toUnmodifiableMap(Map.Entry::getKey,
|
||||
entry -> {
|
||||
@@ -518,7 +541,9 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
database.options().setTransactionRetryLimit(
|
||||
config.getFoundationDbMessagesConfiguration().transactionRetryLimit());
|
||||
|
||||
return database;
|
||||
return new FaultTolerantDatabase(database, entry.getKey(),
|
||||
config.getFoundationDbMessagesConfiguration().circuitBreakerConfigurationName(),
|
||||
config.getFoundationDbMessagesConfiguration().bulkheadConfigurationName());
|
||||
} catch (final IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
@@ -527,8 +552,10 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
messageDatabasesByEpoch = config.getFoundationDbMessagesConfiguration().epochs().entrySet().stream()
|
||||
.collect(Collectors.toUnmodifiableMap(Map.Entry::getKey,
|
||||
entry -> entry.getValue().stream()
|
||||
.map(databasesByName::get)
|
||||
.map(faultTolerantDatabasesByName::get)
|
||||
.toList()));
|
||||
|
||||
environment.lifecycle().manage(new FoundationDBWarmup(faultTolerantDatabasesByName));
|
||||
}
|
||||
|
||||
final AwsCredentialsProvider cdnCredentialsProvider = config.getCdnConfiguration().credentials().build();
|
||||
@@ -541,7 +568,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
BlockingQueue<Runnable> messageDeletionQueue = new LinkedBlockingQueue<>();
|
||||
Metrics.gaugeCollectionSize(name(getClass(), "messageDeletionQueueSize"), Collections.emptyList(),
|
||||
messageDeletionQueue);
|
||||
ExecutorService messageDeletionAsyncExecutor = ExecutorServiceBuilder.of(environment, "messageDeletionAsyncExecutor")
|
||||
final ExecutorService messageDeletionAsyncExecutor = ExecutorServiceBuilder.of(environment, "messageDeletionAsyncExecutor")
|
||||
.minThreads(2)
|
||||
.maxThreads(2)
|
||||
.allowCoreThreadTimeOut(true)
|
||||
@@ -614,9 +641,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
|
||||
FaultTolerantRedisClusterClient cacheCluster = config.getCacheClusterConfiguration()
|
||||
.build("main_cache", sharedClientResources.mutate());
|
||||
FaultTolerantRedisClusterClient messagesCluster =
|
||||
config.getMessageCacheConfiguration().getRedisClusterConfiguration()
|
||||
.build("messages", sharedClientResources.mutate());
|
||||
FaultTolerantRedisClusterClient pushSchedulerCluster = config.getPushSchedulerCluster().build("push_scheduler",
|
||||
sharedClientResources.mutate());
|
||||
FaultTolerantRedisClusterClient rateLimitersCluster = config.getRateLimitersCluster().build("rate_limiters",
|
||||
@@ -650,7 +674,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();
|
||||
|
||||
@@ -708,13 +732,14 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
ScheduledExecutorService messagePollExecutor = ScheduledExecutorServiceBuilder.of(environment, "messagePollExecutor").threads(1).build();
|
||||
ScheduledExecutorService provisioningWebsocketTimeoutExecutor = ScheduledExecutorServiceBuilder.of(environment, "provisioningWebsocketTimeout").threads(1).build();
|
||||
|
||||
final ManagedEventLoopGroup<NioEventLoopGroup> dnsResolutionEventLoopGroup = new ManagedEventLoopGroup<>(new NioEventLoopGroup());
|
||||
final ManagedEventLoopGroup<MultiThreadIoEventLoopGroup> dnsResolutionEventLoopGroup =
|
||||
new ManagedEventLoopGroup<>(new MultiThreadIoEventLoopGroup(NioIoHandler.newFactory()));
|
||||
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());
|
||||
@@ -773,8 +798,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
disconnectionRequestListenerExecutor, retryExecutor);
|
||||
ProfilesManager profilesManager = new ProfilesManager(profilesV1, profiles, profileAvatars, cacheCluster, retryExecutor, asyncCdnS3Client,
|
||||
config.getCdnConfiguration().bucket());
|
||||
MessagesCache messagesCache = new MessagesCache(messagesCluster, messageDeliveryScheduler,
|
||||
messageDeletionAsyncExecutor, retryExecutor, clock);
|
||||
final FoundationDbMessageStore foundationDbMessageStore = new FoundationDbMessageStore(messageDatabasesByEpoch,
|
||||
config.getFoundationDbMessagesConfiguration().activeEpoch(),
|
||||
new VersionstampUUIDCipher(config.getFoundationDbMessagesConfiguration().currentVersionstampCipherKey(),
|
||||
@@ -789,23 +812,30 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
Clock.systemUTC());
|
||||
ReportMessageManager reportMessageManager = new ReportMessageManager(reportMessageDynamoDb, rateLimitersCluster,
|
||||
config.getReportMessageConfiguration().getCounterTtl());
|
||||
RedisMessageAvailabilityManager redisMessageAvailabilityManager =
|
||||
new RedisMessageAvailabilityManager(messagesCluster, clientEventExecutor, asyncOperationQueueingExecutor);
|
||||
MessagesManager messagesManager =
|
||||
new MessagesManager(messagesDynamoDb, messagesCache, foundationDbMessageStore, redisMessageAvailabilityManager,
|
||||
reportMessageManager, messageDeletionAsyncExecutor, Clock.systemUTC(), experimentEnrollmentManager);
|
||||
final MessagesManager messagesManager =
|
||||
new MessagesManager(messagesDynamoDb, foundationDbMessageStore,
|
||||
reportMessageManager, messageDeletionAsyncExecutor, Clock.systemUTC());
|
||||
final ChangeNumberWaitingPeriods changeNumberWaitingPeriods = new ChangeNumberWaitingPeriods(
|
||||
config.getDynamoDbTables().getChangeNumberWaitingPeriods().getTableName(), dynamoDbClient);
|
||||
final ChangeNumberWaitingPeriodManager changeNumberWaitingPeriodManager = new ChangeNumberWaitingPeriodManager(
|
||||
changeNumberWaitingPeriods, config.getChangeNumber().postRegistrationWaitingPeriod(), clock);
|
||||
AccountLockManager accountLockManager = new AccountLockManager(dynamoDbClient,
|
||||
config.getDynamoDbTables().getDeletedAccountsLock().getTableName());
|
||||
final TotpManager totpManager = new TotpManager(rateLimitersCluster, config.getRegistrationTotpConfiguration().maxValidationDelay());
|
||||
final WebAuthnCeremonyManager webAuthnCeremonyManager = new WebAuthnCeremonyManager(
|
||||
config.getRegistrationWebAuthnConfiguration().relyingPartyId(),
|
||||
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(),
|
||||
config.getRegistrationTotpConfiguration().maxValidationDelay());
|
||||
webAuthnCeremonyManager, totpManager);
|
||||
RemoteConfigsManager remoteConfigsManager = new RemoteConfigsManager(remoteConfigs, config.getRemoteConfigConfiguration().globalConfig());
|
||||
APNSender apnSender = new APNSender(apnSenderExecutor, Clock.systemUTC(), config.getApnConfiguration());
|
||||
FcmSender fcmSender = new FcmSender(fcmSenderExecutor, config.getFcmConfiguration().credentials().value());
|
||||
@@ -826,8 +856,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
config.getDynamoDbTables().getDonationPermits().getTableName(), config.getDynamoDbTables().getDonationPermits().getExpiration(), dynamoDbClient);
|
||||
Subscriptions subscriptions = new Subscriptions(
|
||||
config.getDynamoDbTables().getSubscriptions().getTableName(), dynamoDbClient);
|
||||
MessageDeliveryLoopMonitor messageDeliveryLoopMonitor =
|
||||
config.logMessageDeliveryLoops() ? new RedisMessageDeliveryLoopMonitor(rateLimitersCluster) : new NoopMessageDeliveryLoopMonitor();
|
||||
CallQualitySurveyManager callQualitySurveyManager = new CallQualitySurveyManager(asnInfoProviderSupplier,
|
||||
config.getCallQualitySurveyConfiguration().pubSubPublisher().build(),
|
||||
Clock.systemUTC(),
|
||||
@@ -914,7 +942,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
environment.lifecycle().manage(pushNotificationScheduler);
|
||||
environment.lifecycle().manage(provisioningManager);
|
||||
environment.lifecycle().manage(disconnectionRequestManager);
|
||||
environment.lifecycle().manage(redisMessageAvailabilityManager);
|
||||
environment.lifecycle().manage(currencyManager);
|
||||
environment.lifecycle().manage(registrationServiceClient);
|
||||
environment.lifecycle().manage(keyTransparencyServiceClient);
|
||||
@@ -1057,7 +1084,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
final HttpClient shortCodeRetrieverHttpClient = HttpClient.newBuilder().version(HttpClient.Version.HTTP_2)
|
||||
.connectTimeout(Duration.ofSeconds(10)).build();
|
||||
final ShortCodeExpander shortCodeRetriever = new ShortCodeExpander(shortCodeRetrieverHttpClient, config.getShortCodeRetrieverConfiguration().baseUrl());
|
||||
final CaptchaChecker captchaChecker = new CaptchaChecker(shortCodeRetriever, captchaClientSupplier);
|
||||
final CaptchaChecker captchaChecker = new CaptchaChecker(shortCodeRetriever, captchaClientSupplier, dynamicConfigurationManager);
|
||||
|
||||
final RegistrationCaptchaManager registrationCaptchaManager = new RegistrationCaptchaManager(captchaChecker);
|
||||
|
||||
@@ -1077,10 +1104,14 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
final ErrorMappingInterceptor errorMappingInterceptor = new ErrorMappingInterceptor();
|
||||
final ErrorConformanceInterceptor errorConformanceInterceptor = new ErrorConformanceInterceptor();
|
||||
final GrpcAllowListInterceptor grpcAllowListInterceptor = new GrpcAllowListInterceptor(dynamicConfigurationManager);
|
||||
final GrpcCompressionInterceptor grpcCompressionInterceptor = new GrpcCompressionInterceptor(dynamicConfigurationManager);
|
||||
final RequestAttributesInterceptor requestAttributesInterceptor = new RequestAttributesInterceptor();
|
||||
|
||||
final ValidatingInterceptor validatingInterceptor = new ValidatingInterceptor();
|
||||
|
||||
final ConcurrentCallLimitingInterceptor concurrentCallLimitingInterceptor =
|
||||
new ConcurrentCallLimitingInterceptor(config.getVirtualThreadConfiguration().maxConcurrentThreadsPerExecutor());
|
||||
|
||||
final ExternalRequestFilter grpcExternalRequestFilter = new ExternalRequestFilter(
|
||||
config.getExternalRequestFilterConfiguration().permittedInternalRanges(),
|
||||
config.getExternalRequestFilterConfiguration().grpcMethods());
|
||||
@@ -1089,8 +1120,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
final GroupSendTokenUtil groupSendTokenUtil = new GroupSendTokenUtil(groupZkSecretParams, Clock.systemUTC());
|
||||
final MessageMetrics messageMetrics = new MessageMetrics();
|
||||
final MessageDispatcher messageDispatcher = new MessageDispatcher(receiptSender, messagesManager, messageMetrics,
|
||||
pushNotificationManager, pushNotificationScheduler, messageDeliveryLoopMonitor, disconnectionRequestManager,
|
||||
clientReleaseManager);
|
||||
pushNotificationManager, pushNotificationScheduler, disconnectionRequestManager, clientReleaseManager, Clock.systemUTC());
|
||||
|
||||
final CertificateGenerator certificateGenerator =
|
||||
new CertificateGenerator(config.getDeliveryCertificate().certificate(),
|
||||
@@ -1111,8 +1141,9 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
new CallingGrpcService(cloudflareTurnCredentialsManager, rateLimiters),
|
||||
new CredentialsGrpcService(accountsManager, certificateGenerator, zkAuthOperations, callingGenericZkSecretParams, rateLimiters, Clock.systemUTC(), ExternalServiceDefinitions.createExternalServiceList(config, Clock.systemUTC())),
|
||||
new KeysGrpcService(accountsManager, keysManager, rateLimiters),
|
||||
new ProfileGrpcService(clock, accountsManager, profilesManager, asnInfoProviderSupplier, dynamicConfigurationManager, config.getBadges(), profileCdnPolicyGenerator, chatGenericZkSecretParams, profileBadgeConverter, rateLimiters),
|
||||
new MessagesGrpcService(accountsManager, rateLimiters, messageSender, messageByteLimitCardinalityEstimator, spamChecker, messageDispatcher, Clock.systemUTC()),
|
||||
new ProfileGrpcService(clock, accountsManager, profilesManager, asnInfoProviderSupplier, dynamicConfigurationManager, config.getBadges(), profileCdnPolicyGenerator,
|
||||
config.getCdnConfiguration().baseUrl(), chatGenericZkSecretParams, profileBadgeConverter, rateLimiters),
|
||||
new MessagesGrpcService(accountsManager, reportMessageManager, phoneNumberIdentifiers, rateLimiters, messageSender, messageByteLimitCardinalityEstimator, spamChecker, messageDispatcher, Clock.systemUTC()),
|
||||
new BackupsGrpcService(accountsManager, backupAuthManager, backupMetrics),
|
||||
new DevicesGrpcService(accountsManager),
|
||||
new AttachmentsGrpcService(experimentEnrollmentManager, rateLimiters, gcsAttachmentGenerator,
|
||||
@@ -1121,9 +1152,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
new PaymentsGrpcService(currencyManager),
|
||||
new ChallengeGrpcService(accountsManager, rateLimitChallengeManager, challengeConstraintChecker),
|
||||
new DonationsGrpcService(clock, zkReceiptOperations, redeemedReceiptsManager, accountsManager, config.getBadges(), ReceiptCredentialPresentation::new, donationPermitsManager, rateLimiters),
|
||||
new ProductConfigurationGrpcService(config.getSubscription(), config.getOneTimeDonations(),
|
||||
config.getLoginPurchase(), List.of(stripeManager, braintreeManager),
|
||||
config.getBackupConfiguration().maxTotalMediaSize()),
|
||||
new RemoteConfigurationGrpcService(remoteConfigsManager, profileBadgeConverter,
|
||||
config.getBadges().getBadges().stream()
|
||||
.map(BadgeConfiguration::getId)
|
||||
@@ -1134,11 +1162,13 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
validatingInterceptor,
|
||||
errorMappingInterceptor,
|
||||
errorConformanceInterceptor,
|
||||
grpcCompressionInterceptor,
|
||||
grpcAllowListInterceptor,
|
||||
remoteDeprecationFilter,
|
||||
metricServerInterceptor,
|
||||
requestAttributesInterceptor,
|
||||
requireAuthenticationInterceptor))
|
||||
requireAuthenticationInterceptor,
|
||||
concurrentCallLimitingInterceptor))
|
||||
.toList();
|
||||
final List<ServerServiceDefinition> unauthenticatedServices = Stream.of(
|
||||
new AccountsAnonymousGrpcService(accountsManager, rateLimiters, groupSendTokenUtil),
|
||||
@@ -1146,12 +1176,16 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
new KeysAnonymousGrpcService(accountsManager, keysManager, groupZkSecretParams, Clock.systemUTC()),
|
||||
new KeyTransparencyGrpcService(rateLimiters, keyTransparencyServiceClient),
|
||||
new LoginPurchaseGrpcService(loginPurchaseManager, dynamicConfigurationManager),
|
||||
new ProfileAnonymousGrpcService(accountsManager, profilesManager, profileBadgeConverter, profileCdnPolicyGenerator, chatGenericZkSecretParams, groupZkSecretParams, rateLimiters, clock),
|
||||
new ProfileAnonymousGrpcService(accountsManager, profilesManager, profileBadgeConverter, profileCdnPolicyGenerator,
|
||||
config.getCdnConfiguration().baseUrl(), 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 ProductConfigurationGrpcService(config.getSubscription(), config.getOneTimeDonations(),
|
||||
config.getLoginPurchase(), List.of(stripeManager, braintreeManager),
|
||||
config.getBackupConfiguration().maxTotalMediaSize()),
|
||||
new OneTimeDonationsGrpcService(config.getOneTimeDonations(), stripeManager, braintreeManager,
|
||||
payPalDonationsTranslator, oneTimeDonationsManager, issuedReceiptsManager,
|
||||
zkReceiptOperations, clock, rateLimiters, donationPermitsManager))
|
||||
@@ -1162,21 +1196,30 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
validatingInterceptor,
|
||||
errorMappingInterceptor,
|
||||
errorConformanceInterceptor,
|
||||
grpcCompressionInterceptor,
|
||||
grpcAllowListInterceptor,
|
||||
remoteDeprecationFilter,
|
||||
metricServerInterceptor,
|
||||
requestAttributesInterceptor,
|
||||
prohibitAuthenticationInterceptor))
|
||||
prohibitAuthenticationInterceptor,
|
||||
concurrentCallLimitingInterceptor))
|
||||
.toList();
|
||||
|
||||
final ManagedEventLoopGroup<DefaultEventLoopGroup> omnibusLocalEventLoopGroup = new ManagedEventLoopGroup<>(new DefaultEventLoopGroup());
|
||||
final ManagedEventLoopGroup<NioEventLoopGroup> omnibusNioEventLoopGroup = new ManagedEventLoopGroup<>(new NioEventLoopGroup());
|
||||
verifyServiceAuth(authenticatedServices, Auth.AUTH_ONLY_AUTHENTICATED);
|
||||
verifyServiceAuth(unauthenticatedServices, Auth.AUTH_ONLY_ANONYMOUS);
|
||||
|
||||
final ManagedEventLoopGroup<MultiThreadIoEventLoopGroup> omnibusLocalEventLoopGroup =
|
||||
new ManagedEventLoopGroup<>(new MultiThreadIoEventLoopGroup(LocalIoHandler.newFactory()));
|
||||
final ManagedEventLoopGroup<MultiThreadIoEventLoopGroup> omnibusNioEventLoopGroup =
|
||||
new ManagedEventLoopGroup<>(new MultiThreadIoEventLoopGroup(NioIoHandler.newFactory()));
|
||||
final LocalAddress grpcLocalAddress = new LocalAddress("grpc");
|
||||
final ServerBuilder<?> serverBuilder = NettyServerBuilder
|
||||
.forAddress(grpcLocalAddress)
|
||||
.channelType(LocalServerChannel.class)
|
||||
.bossEventLoopGroup(omnibusLocalEventLoopGroup.getEventLoopGroup())
|
||||
.workerEventLoopGroup(omnibusLocalEventLoopGroup.getEventLoopGroup());
|
||||
.workerEventLoopGroup(omnibusLocalEventLoopGroup.getEventLoopGroup())
|
||||
.executor(ManagedExecutors.newVirtualThreadPerTaskExecutor("managed-grpc-virtual-thread", environment))
|
||||
.addStreamTracerFactory(new MetricServerStreamTracer.Factory());
|
||||
authenticatedServices.forEach(serverBuilder::addService);
|
||||
unauthenticatedServices.forEach(serverBuilder::addService);
|
||||
final ManagedGrpcServer localGrpcServer = new ManagedGrpcServer(serverBuilder.build());
|
||||
@@ -1186,17 +1229,21 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
|
||||
final SocketAddress websocketAddress =
|
||||
new InetSocketAddress(config.getGrpc().websocketAddress(), config.getGrpc().websocketPort());
|
||||
final H2ConnectionFactory grpcH2ConnectionFactory = new PooledH2ConnectionFactory(grpcLocalAddress,
|
||||
omnibusLocalEventLoopGroup.getEventLoopGroup());
|
||||
final H2ConnectionFactory websocketH2ConnectionFactory = new UnpooledH2ConnectionFactory(websocketAddress, omnibusNioEventLoopGroup.getEventLoopGroup());
|
||||
final OmnibusRouter omnibusRouter = new OmnibusRouter(Map.of(
|
||||
websocketServletPath, websocketAddress,
|
||||
provisioningWebsocketServletPath, websocketAddress),
|
||||
grpcLocalAddress);
|
||||
websocketServletPath, websocketH2ConnectionFactory,
|
||||
provisioningWebsocketServletPath, websocketH2ConnectionFactory),
|
||||
grpcH2ConnectionFactory);
|
||||
@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(),
|
||||
omnibusLocalEventLoopGroup.getEventLoopGroup(),
|
||||
new InetSocketAddress(config.getGrpc().bindAddress(), config.getGrpc().port()), omnibusRouter,
|
||||
() -> dynamicConfigurationManager.getConfiguration().getOmnibus(),
|
||||
config.getGrpc().idleTimeout());
|
||||
@@ -1249,13 +1296,13 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
webSocketEnvironment.setConnectListener(
|
||||
new AuthenticatedConnectListener(accountsManager, receiptSender, messagesManager, messageMetrics, pushNotificationManager,
|
||||
pushNotificationScheduler, disconnectionRequestManager,
|
||||
messageDeliveryScheduler, asnInfoProviderSupplier, clientReleaseManager, messageDeliveryLoopMonitor, experimentEnrollmentManager
|
||||
messageDeliveryScheduler, asnInfoProviderSupplier, clientReleaseManager, dynamicConfigurationManager
|
||||
));
|
||||
webSocketEnvironment.jersey().register(new RateLimitByIpFilter(rateLimiters));
|
||||
webSocketEnvironment.jersey().register(new RequestStatisticsFilter(TrafficSource.WEBSOCKET));
|
||||
webSocketEnvironment.jersey().register(MultiRecipientMessageProvider.class);
|
||||
webSocketEnvironment.jersey().register(new MetricsApplicationEventListener(TrafficSource.WEBSOCKET, clientReleaseManager));
|
||||
webSocketEnvironment.jersey().register(new KeepAliveController(redisMessageAvailabilityManager));
|
||||
webSocketEnvironment.jersey().register(new KeepAliveController());
|
||||
webSocketEnvironment.jersey().register(new TimestampResponseFilter());
|
||||
|
||||
final PersistentTimer persistentTimer = new PersistentTimer(rateLimitersCluster, clock);
|
||||
@@ -1296,7 +1343,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
new VerificationController(registrationServiceClient, new VerificationSessionManager(verificationSessions),
|
||||
pushNotificationManager, registrationCaptchaManager, phoneNumberRecoveryPasswordsManager,
|
||||
phoneNumberIdentifiers, rateLimiters, accountsManager, carrierDataProvider, registrationFraudChecker,
|
||||
dynamicConfigurationManager, experimentEnrollmentManager, clock),
|
||||
dynamicConfigurationManager, clock),
|
||||
new SubscriptionController(clock, config.getSubscription(), config.getOneTimeDonations(),
|
||||
config.getLoginPurchase(), subscriptionManager, stripeManager, braintreeManager, googlePlayBillingManager,
|
||||
appleAppStoreManager,
|
||||
@@ -1317,9 +1364,11 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
webSocketEnvironment.getRequestLog(), Duration.ofMillis(60000));
|
||||
provisioningEnvironment.setConnectListener(new ProvisioningConnectListener(provisioningManager, asnInfoProviderSupplier, clientReleaseManager, provisioningWebsocketTimeoutExecutor, Duration.ofSeconds(90)));
|
||||
provisioningEnvironment.jersey().register(new MetricsApplicationEventListener(TrafficSource.WEBSOCKET, clientReleaseManager));
|
||||
provisioningEnvironment.jersey().register(new KeepAliveController(redisMessageAvailabilityManager));
|
||||
provisioningEnvironment.jersey().register(new KeepAliveController());
|
||||
provisioningEnvironment.jersey().register(new TimestampResponseFilter());
|
||||
|
||||
WebSocketConnection.registerDroppedErrorHook();
|
||||
|
||||
registerExceptionMappers(environment, webSocketEnvironment, provisioningEnvironment);
|
||||
|
||||
environment.jersey().property(ServerProperties.UNWRAP_COMPLETION_STAGE_IN_WRITER_ENABLE, Boolean.TRUE);
|
||||
@@ -1365,6 +1414,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
List.of(
|
||||
new LoggingUnhandledExceptionMapper(),
|
||||
new CompletionExceptionMapper(),
|
||||
new CallNotPermittedExceptionMapper(),
|
||||
new IOExceptionMapper(),
|
||||
new RateLimitExceededExceptionMapper(),
|
||||
new InvalidWebsocketAddressExceptionMapper(),
|
||||
@@ -1375,10 +1425,11 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
new NonNormalizedPhoneNumberExceptionMapper(),
|
||||
new ObsoletePhoneNumberFormatExceptionMapper(),
|
||||
new RegistrationServiceSenderExceptionMapper(),
|
||||
new SubscriptionExceptionMapper(),
|
||||
new PurchaseExceptionMapper(),
|
||||
new BackupExceptionMapper(),
|
||||
new JsonMappingExceptionMapper(),
|
||||
new RegistrationLockFailureExceptionMapper()
|
||||
new RegistrationLockFailureExceptionMapper(),
|
||||
new MfaFailureExceptionMapper()
|
||||
).forEach(exceptionMapper -> {
|
||||
environment.jersey().register(exceptionMapper);
|
||||
webSocketEnvironment.jersey().register(exceptionMapper);
|
||||
@@ -1386,6 +1437,16 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
});
|
||||
}
|
||||
|
||||
private static void verifyServiceAuth(final List<ServerServiceDefinition> services, final Auth expectedAuthType) {
|
||||
for (final ServerServiceDefinition service : services) {
|
||||
final Auth authType = ValidatorUtils.serviceAuthExtensionValue(service).orElse(Auth.AUTH_UNSPECIFIED);
|
||||
if (!authType.equals(expectedAuthType)) {
|
||||
throw new IllegalStateException("gRPC service %s is annotated with %s but was registered as %s"
|
||||
.formatted(service.getServiceDescriptor().getName(), authType, expectedAuthType));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static class ExecutorServiceBuilder extends io.dropwizard.lifecycle.setup.ExecutorServiceBuilder {
|
||||
private final String baseName;
|
||||
|
||||
|
||||
@@ -24,6 +24,7 @@ import java.util.Optional;
|
||||
import java.util.TreeMap;
|
||||
import java.util.zip.GZIPInputStream;
|
||||
import javax.annotation.Nonnull;
|
||||
import com.google.common.net.InetAddresses;
|
||||
import org.apache.commons.csv.CSVFormat;
|
||||
import org.apache.commons.csv.CSVParser;
|
||||
import org.apache.commons.csv.CSVRecord;
|
||||
@@ -74,8 +75,8 @@ public class AsnInfoProviderImpl implements AsnInfoProvider {
|
||||
for (final CSVRecord record : csvParser) {
|
||||
// format:
|
||||
// range_start_ip_string range_end_ip_string AS_number country_code AS_description
|
||||
final InetAddress startIp = InetAddress.getByName(record.get(0));
|
||||
final InetAddress endIp = InetAddress.getByName(record.get(1));
|
||||
final InetAddress startIp = InetAddresses.forString(record.get(0));
|
||||
final InetAddress endIp = InetAddresses.forString(record.get(1));
|
||||
final long asn = Long.parseLong(record.get(2));
|
||||
final String regionCode = record.get(3);
|
||||
// country code should be the same for any ASN, so we're caching AsnInfo objects
|
||||
@@ -123,7 +124,7 @@ public class AsnInfoProviderImpl implements AsnInfoProvider {
|
||||
@Override
|
||||
public Optional<AsnInfo> lookup(@Nonnull final String ipString) {
|
||||
try {
|
||||
final InetAddress address = InetAddress.getByName(ipString);
|
||||
final InetAddress address = InetAddresses.forString(ipString);
|
||||
if (address instanceof Inet4Address ip4) {
|
||||
final Long key = ip4BytesToLong(ip4);
|
||||
return lookupInMap(asnBlocksByFirstIpv4, key);
|
||||
|
||||
+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
@@ -6,6 +6,7 @@
|
||||
package org.whispersystems.textsecuregcm.auth;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import io.github.resilience4j.circuitbreaker.CallNotPermittedException;
|
||||
import io.netty.resolver.dns.DnsNameResolver;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import java.io.IOException;
|
||||
@@ -14,10 +15,8 @@ import java.net.URI;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.time.Duration;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import javax.annotation.Nullable;
|
||||
@@ -27,7 +26,6 @@ import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfigurati
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.http.FaultTolerantHttpClient;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
|
||||
public class CloudflareTurnCredentialsManager {
|
||||
@@ -133,10 +131,16 @@ public class CloudflareTurnCredentialsManager {
|
||||
|
||||
final HttpResponse<String> response;
|
||||
try {
|
||||
response = cloudflareTurnClient.sendAsync(getCredentialsRequest, HttpResponse.BodyHandlers.ofString()).join();
|
||||
} catch (CompletionException e) {
|
||||
response = cloudflareTurnClient.send(getCredentialsRequest, HttpResponse.BodyHandlers.ofString());
|
||||
} catch (Exception e) {
|
||||
|
||||
if (e instanceof CallNotPermittedException cnpe) {
|
||||
// the circuit breaker is open, and this can escape up to the exception mapper
|
||||
throw cnpe;
|
||||
}
|
||||
|
||||
logger.warn("failed to make http request to Cloudflare Turn: {}", e.getMessage());
|
||||
throw new IOException(ExceptionUtils.unwrap(e));
|
||||
throw new IOException(e);
|
||||
}
|
||||
|
||||
if (response.statusCode() != Response.Status.CREATED.getStatusCode()) {
|
||||
|
||||
+16
-17
@@ -27,7 +27,6 @@ import java.util.concurrent.ScheduledExecutorService;
|
||||
import javax.annotation.Nullable;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantPubSubConnection;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient;
|
||||
@@ -120,10 +119,6 @@ public class DisconnectionRequestManager extends RedisPubSubAdapter<byte[], byte
|
||||
|
||||
/**
|
||||
* Adds a listener for disconnection requests for a specific authenticated device.
|
||||
*
|
||||
* @param accountIdentifier TODO
|
||||
* @param deviceId TODO
|
||||
* @param listener the listener to register
|
||||
*/
|
||||
public void addListener(final UUID accountIdentifier, final byte deviceId, final DisconnectionRequestListener listener) {
|
||||
listeners.compute(new AccountIdentifierAndDeviceId(accountIdentifier, deviceId), (_, existingListeners) -> {
|
||||
@@ -138,10 +133,6 @@ public class DisconnectionRequestManager extends RedisPubSubAdapter<byte[], byte
|
||||
|
||||
/**
|
||||
* Removes a listener for disconnection requests for a specific authenticated device.
|
||||
*
|
||||
* @param accountIdentifier TODO
|
||||
* @param deviceId TODO
|
||||
* @param listener the listener to remove
|
||||
*/
|
||||
public void removeListener(final UUID accountIdentifier, final byte deviceId, final DisconnectionRequestListener listener) {
|
||||
listeners.computeIfPresent(new AccountIdentifierAndDeviceId(accountIdentifier, deviceId), (_, existingListeners) -> {
|
||||
@@ -218,14 +209,22 @@ public class DisconnectionRequestManager extends RedisPubSubAdapter<byte[], byte
|
||||
}
|
||||
|
||||
deviceIds.forEach(deviceId -> {
|
||||
listeners.getOrDefault(new AccountIdentifierAndDeviceId(accountIdentifier, deviceId), Collections.emptyList())
|
||||
.forEach(listener -> listenerEventExecutor.execute(() -> {
|
||||
try {
|
||||
listener.handleDisconnectionRequest();
|
||||
} catch (final Exception e) {
|
||||
logger.warn("Listener failed to handle disconnection request", e);
|
||||
}
|
||||
}));
|
||||
final ArrayList<DisconnectionRequestListener> listenersForDevice = new ArrayList<>();
|
||||
|
||||
// This is a little weird, but it's a thread-safe way to get an immutable copy of the list of listeners for a
|
||||
// given device
|
||||
listeners.computeIfPresent(new AccountIdentifierAndDeviceId(accountIdentifier, deviceId), (_, existingListeners) -> {
|
||||
listenersForDevice.addAll(existingListeners);
|
||||
return existingListeners;
|
||||
});
|
||||
|
||||
listenersForDevice.forEach(listener -> listenerEventExecutor.execute(() -> {
|
||||
try {
|
||||
listener.handleDisconnectionRequest();
|
||||
} catch (final Exception e) {
|
||||
logger.warn("Listener failed to handle disconnection request", e);
|
||||
}
|
||||
}));
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.auth;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
import org.whispersystems.textsecuregcm.auth.webauthn.AuthenticationCeremonyParameters;
|
||||
import org.whispersystems.textsecuregcm.util.NoStackTraceException;
|
||||
|
||||
public class MfaFailureException extends NoStackTraceException {
|
||||
|
||||
private final @Nullable AuthenticationCeremonyParameters webAuthnParameters;
|
||||
private final boolean hasTotp;
|
||||
|
||||
public MfaFailureException(@Nullable AuthenticationCeremonyParameters webAuthnParameters, boolean hasTotpKey) {
|
||||
this.webAuthnParameters = webAuthnParameters;
|
||||
this.hasTotp = hasTotpKey;
|
||||
}
|
||||
|
||||
public @Nullable AuthenticationCeremonyParameters getWebAuthnParameters() {
|
||||
return webAuthnParameters;
|
||||
}
|
||||
|
||||
public boolean hasTotpKey() {
|
||||
return hasTotp;
|
||||
}
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.auth.webauthn;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
|
||||
/// Server-generated parameters for a freshly-initiated authentication ceremony.
|
||||
public record AuthenticationCeremonyParameters(
|
||||
byte[] challenge,
|
||||
Duration timeout,
|
||||
List<byte[]> allowedCredentialIds) {
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.auth.webauthn;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/// Server-generated parameters for a freshly-initiated registration ceremony.
|
||||
public record RegistrationCeremonyParameters(
|
||||
byte[] userHandle,
|
||||
List<Long> allowedAlgorithms,
|
||||
List<byte[]> excludedCredentialIds) {
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.auth.webauthn;
|
||||
|
||||
import com.webauthn4j.data.attestation.authenticator.AttestedCredentialData;
|
||||
import com.webauthn4j.data.client.CollectedClientData;
|
||||
|
||||
/// Results of a registration ceremony for persisting.
|
||||
public record RegistrationCeremonyResult(
|
||||
AttestedCredentialData attestedCredentialData,
|
||||
CollectedClientData collectedClientData,
|
||||
long signCount
|
||||
) {
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.auth.webauthn;
|
||||
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public record WebAuthnAuthenticationParameters(
|
||||
@Schema(description = "The authentication ceremony challenge.")
|
||||
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
|
||||
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
|
||||
byte[] challenge,
|
||||
|
||||
@Schema(description = "The number of seconds the challenge will be valid.")
|
||||
long timeoutSeconds,
|
||||
|
||||
@Schema(description = "A list of authenticators previously registered to the account.")
|
||||
@JsonDeserialize(contentUsing = ByteArrayAdapter.Deserializing.class)
|
||||
@JsonSerialize(contentUsing = ByteArrayAdapter.Serializing.class)
|
||||
List<byte[]> allowedCredentialIds) {}
|
||||
+234
@@ -0,0 +1,234 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.auth.webauthn;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.webauthn4j.WebAuthnManager;
|
||||
import com.webauthn4j.credential.CredentialRecord;
|
||||
import com.webauthn4j.data.AuthenticationData;
|
||||
import com.webauthn4j.data.AuthenticationParameters;
|
||||
import com.webauthn4j.data.PublicKeyCredentialParameters;
|
||||
import com.webauthn4j.data.PublicKeyCredentialType;
|
||||
import com.webauthn4j.data.RegistrationData;
|
||||
import com.webauthn4j.data.RegistrationParameters;
|
||||
import com.webauthn4j.data.RegistrationRequest;
|
||||
import com.webauthn4j.data.attestation.statement.COSEAlgorithmIdentifier;
|
||||
import com.webauthn4j.data.client.Origin;
|
||||
import com.webauthn4j.server.ServerProperty;
|
||||
import com.webauthn4j.util.exception.WebAuthnException;
|
||||
import com.webauthn4j.verifier.exception.BadChallengeException;
|
||||
import com.webauthn4j.verifier.exception.VerificationException;
|
||||
import io.lettuce.core.SetArgs;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
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;
|
||||
import org.whispersystems.textsecuregcm.util.ResilienceUtil;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import tools.jackson.core.JacksonException;
|
||||
|
||||
/// Handles WebAuthn registration and authentication operations.
|
||||
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 Set<Origin> origins;
|
||||
private final byte[] blindingSecret;
|
||||
private final Duration challengeTtl;
|
||||
|
||||
private final FaultTolerantRedisClusterClient challengeStorageCluster;
|
||||
private final WebAuthnManager webAuthnManager;
|
||||
|
||||
private static final String RETRY_NAME = ResilienceUtil.name(WebAuthnCeremonyManager.class);
|
||||
|
||||
/// Ed25519 support is fairly limited, while ES256 is broadly supported
|
||||
private static final List<PublicKeyCredentialParameters> ALLOWED_WEBAUTHN_CREDENTIAL_ALGORITHMS = List.of(
|
||||
new PublicKeyCredentialParameters(PublicKeyCredentialType.PUBLIC_KEY, COSEAlgorithmIdentifier.Ed25519),
|
||||
new PublicKeyCredentialParameters(PublicKeyCredentialType.PUBLIC_KEY, COSEAlgorithmIdentifier.ES256)
|
||||
);
|
||||
|
||||
private static final SecureRandom SECURE_RANDOM = new SecureRandom();
|
||||
|
||||
public WebAuthnCeremonyManager(final String rpId, final List<String> origins, final Duration challengeTtl, final byte[] blindingSecret,
|
||||
final FaultTolerantRedisClusterClient challengeStorageCluster) {
|
||||
this.rpId = rpId;
|
||||
this.origins = origins.stream().map(Origin::new).collect(Collectors.toSet());
|
||||
this.challengeTtl = challengeTtl;
|
||||
this.blindingSecret = blindingSecret;
|
||||
this.challengeStorageCluster = challengeStorageCluster;
|
||||
this.webAuthnManager = WebAuthnManager.createNonStrictWebAuthnManager();
|
||||
}
|
||||
|
||||
/// Initiates a WebAuthn registration ceremony
|
||||
///
|
||||
/// @param identifier The account identifier
|
||||
///
|
||||
/// @param existingCredentials a list of already-stored credential records for the user; their IDs
|
||||
/// will be provided to the client to help prevent registering a duplicate ID on the same
|
||||
/// authenticator
|
||||
///
|
||||
/// @return parameters the client must use for its step in the registration ceremony. `identifier` will be blinded, so
|
||||
/// that it is a [non-identifiable user handle](https://www.w3.org/TR/webauthn/#sctn-user-handle-privacy)
|
||||
public RegistrationCeremonyParameters startRegistration(final UUID identifier, final List<? extends CredentialRecord> existingCredentials) {
|
||||
return new RegistrationCeremonyParameters(
|
||||
blindIdentifier(identifier),
|
||||
ALLOWED_WEBAUTHN_CREDENTIAL_ALGORITHMS.stream().map(pkcp -> pkcp.getAlg().getValue()).toList(),
|
||||
existingCredentials.stream().map(credentialRecord -> credentialRecord.getAttestedCredentialData().getCredentialId()).toList()
|
||||
);
|
||||
}
|
||||
|
||||
/// Verifies that the supplied authenticator response components form a
|
||||
/// valid WebAuthn registration ceremony with acceptable parameters.
|
||||
///
|
||||
/// @param serializedAttestationObject the "attestation object" from the authenticator response,
|
||||
/// serialized in the format specified by the WebAuthn TR. Its attestation format must be `none`
|
||||
/// and any attestation statement must have been cleared to mitigate privacy risks.
|
||||
///
|
||||
/// @param collectedClientDataJson the "collected client data" from the authenticator response,
|
||||
/// serialized in the [format specified by the WebAuthn TR](https://www.w3.org/TR/webauthn/#sctn-generating-an-attestation-object)
|
||||
///
|
||||
/// @return a record that can be stored for future authentication.
|
||||
///
|
||||
/// @throws WebAuthnException if the supplied authenticator response is
|
||||
/// invalid for any reason (structurally or due to selecting unacceptable
|
||||
/// parameters, for example an unsupported signature algorithm)
|
||||
public RegistrationCeremonyResult verifyRegistration(
|
||||
final byte[] serializedAttestationObject, final String collectedClientDataJson) throws WebAuthnException {
|
||||
|
||||
final RegistrationData registrationData;
|
||||
try {
|
||||
registrationData = webAuthnManager.parse(
|
||||
new RegistrationRequest(serializedAttestationObject, collectedClientDataJson.getBytes(StandardCharsets.UTF_8)));
|
||||
} catch (final JacksonException e) {
|
||||
throw new WebAuthnException(e);
|
||||
}
|
||||
|
||||
// These shouldn't ever be null, because the upstream RPC inputs are not nullable. However, the fields are annotated as
|
||||
// nullable.
|
||||
if (registrationData.getAttestationObject() == null) {
|
||||
throw new WebAuthnException("Attestation object must not be null");
|
||||
}
|
||||
if (registrationData.getCollectedClientData() == null) {
|
||||
throw new WebAuthnException("Collected client data must not be null");
|
||||
}
|
||||
|
||||
if (!"none".equals(registrationData.getAttestationObject().getAttestationStatement().getFormat())) {
|
||||
// Refuse any attestations; clients must clear them to prevent sharing information we don't want to store
|
||||
throw new WebAuthnException("attestation format must be 'none'");
|
||||
}
|
||||
|
||||
final ServerProperty serverProperties = ServerProperty.builder()
|
||||
// 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())
|
||||
.origins(origins)
|
||||
.rpId(rpId)
|
||||
.build();
|
||||
|
||||
webAuthnManager.verify(registrationData,
|
||||
new RegistrationParameters(serverProperties, ALLOWED_WEBAUTHN_CREDENTIAL_ALGORITHMS, false, true));
|
||||
|
||||
return new RegistrationCeremonyResult(
|
||||
registrationData.getAttestationObject().getAuthenticatorData().getAttestedCredentialData(),
|
||||
registrationData.getCollectedClientData(),
|
||||
registrationData.getAttestationObject().getAuthenticatorData().getSignCount());
|
||||
}
|
||||
|
||||
/// Initiates a WebAuthn authentication ceremony.
|
||||
///
|
||||
/// Each call generates, and replaces any existing, [challenge](https://www.w3.org/TR/webauthn/#sctn-cryptographic-challenges).
|
||||
///
|
||||
/// @param identifier the identifier of the account to be authenticated
|
||||
/// @param existingCredentials a list of stored credential records for the user being authenticated
|
||||
///
|
||||
/// @return a [AuthenticationCeremonyParameters] record with the details
|
||||
/// needed by a client in possession of a matching authenticator to complete
|
||||
/// the ceremony
|
||||
public AuthenticationCeremonyParameters startAuthentication(final UUID identifier, List<? extends CredentialRecord> existingCredentials) {
|
||||
final byte[] challengeKey = challengeKey(identifier);
|
||||
final byte[] challenge = new byte[16];
|
||||
SECURE_RANDOM.nextBytes(challenge);
|
||||
|
||||
ResilienceUtil.getGeneralRedisRetry(RETRY_NAME)
|
||||
.executeRunnable(
|
||||
() -> challengeStorageCluster.withBinaryCluster(cluster -> cluster.sync().set(challengeKey, challenge, SetArgs.Builder.ex(challengeTtl.toSeconds()))));
|
||||
|
||||
return new AuthenticationCeremonyParameters(
|
||||
challenge,
|
||||
challengeTtl,
|
||||
existingCredentials.stream().map(cr -> cr.getAttestedCredentialData().getCredentialId()).toList());
|
||||
}
|
||||
|
||||
/// Parses an authenticator response JSON blob, whose format is specified in the WebAuthn Technical Report
|
||||
public AuthenticationData parseAuthenticationResponse(final String authenticationResponseJson) throws WebAuthnException {
|
||||
try {
|
||||
return webAuthnManager.parseAuthenticationResponseJSON(authenticationResponseJson);
|
||||
} catch (final NullPointerException | JacksonException e) {
|
||||
throw new WebAuthnException(e);
|
||||
}
|
||||
}
|
||||
|
||||
/// Verifies an authenticator response to a WebAuthn authentication ceremony, consuming any existing stored challenge.
|
||||
///
|
||||
/// If verification succeeds, the `CredentialRecord` is [updated in-place](https://www.w3.org/TR/webauthn-3/#authn-ceremony-update-credential-record).
|
||||
///
|
||||
/// @param identifier the identifier of the account to be authenticated
|
||||
/// @param matchingCredential the stored credential record for the account to be authenticated with an ID matching the one from the authenticator response
|
||||
/// @param authenticationData the parsed authenticator response
|
||||
///
|
||||
///
|
||||
/// @throws VerificationException if the response could not be verified for any reason (incorrect signature, incorrect or expired challenge)
|
||||
public void verifyAuthentication(
|
||||
final UUID identifier,
|
||||
final CredentialRecord matchingCredential,
|
||||
final AuthenticationData authenticationData) throws VerificationException {
|
||||
|
||||
final byte[] challengeKey = challengeKey(identifier);
|
||||
@Nullable final byte[] challenge = ResilienceUtil.getGeneralRedisRetry(RETRY_NAME)
|
||||
.executeSupplier(() -> challengeStorageCluster.withBinaryCluster(cluster -> cluster.sync().getdel(challengeKey)));
|
||||
|
||||
//noinspection ConstantValue
|
||||
if (challenge == null) {
|
||||
throw new BadChallengeException("no challenge stored");
|
||||
}
|
||||
|
||||
final byte[] credentialId = matchingCredential.getAttestedCredentialData().getCredentialId();
|
||||
final AuthenticationParameters authenticationParameters = new AuthenticationParameters(
|
||||
ServerProperty.builder()
|
||||
.origins(origins)
|
||||
.rpId(rpId)
|
||||
.challenge(() -> challenge)
|
||||
.build(),
|
||||
matchingCredential,
|
||||
List.of(credentialId),
|
||||
false,
|
||||
true);
|
||||
|
||||
webAuthnManager.verify(authenticationData, authenticationParameters);
|
||||
}
|
||||
|
||||
/// @return `true` if [CredentialRecord]s represent the same actual credential ID. Note that this is more specific than
|
||||
/// whether they came from the same authenticator device, which cannot be determined in general.
|
||||
public static boolean isSameCredential(final CredentialRecord a, final CredentialRecord b) {
|
||||
return Arrays.equals(a.getAttestedCredentialData().getCredentialId(), b.getAttestedCredentialData().getCredentialId());
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static byte[] challengeKey(final UUID identifier) {
|
||||
return String.format("webauthn_challenge::{%s}", identifier).getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
private byte[] blindIdentifier(final UUID identifier) {
|
||||
return HmacUtils.hmac256Truncated(blindingSecret, UUIDUtil.toBytes(identifier), 32);
|
||||
}
|
||||
}
|
||||
+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));
|
||||
}
|
||||
|
||||
+25
-12
@@ -9,7 +9,6 @@ import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import jakarta.ws.rs.BadRequestException;
|
||||
import java.io.IOException;
|
||||
import java.util.Locale;
|
||||
import java.util.Optional;
|
||||
@@ -19,6 +18,8 @@ import java.util.function.Function;
|
||||
import javax.annotation.Nullable;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
|
||||
public class CaptchaChecker {
|
||||
private static final Logger logger = LoggerFactory.getLogger(CaptchaChecker.class);
|
||||
@@ -33,12 +34,15 @@ public class CaptchaChecker {
|
||||
|
||||
private final ShortCodeExpander shortCodeExpander;
|
||||
private final Function<String, CaptchaClient> captchaClientSupplier;
|
||||
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
|
||||
|
||||
public CaptchaChecker(
|
||||
final ShortCodeExpander shortCodeRetriever,
|
||||
final Function<String, CaptchaClient> captchaClientSupplier) {
|
||||
final Function<String, CaptchaClient> captchaClientSupplier,
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
|
||||
this.shortCodeExpander = shortCodeRetriever;
|
||||
this.captchaClientSupplier = captchaClientSupplier;
|
||||
this.dynamicConfigurationManager = dynamicConfigurationManager;
|
||||
}
|
||||
|
||||
|
||||
@@ -94,23 +98,32 @@ 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");
|
||||
}
|
||||
|
||||
final AssessmentResult result = client.verify(maybeAci, siteKey, parsedAction, token, ip, userAgent);
|
||||
Metrics.counter(ASSESSMENTS_COUNTER_NAME,
|
||||
"action", action,
|
||||
"score", result.getScoreString(),
|
||||
"provider", provider)
|
||||
.increment();
|
||||
return result;
|
||||
try {
|
||||
final AssessmentResult result = client.verify(maybeAci, siteKey, parsedAction, token, ip, userAgent);
|
||||
Metrics.counter(ASSESSMENTS_COUNTER_NAME,
|
||||
"action", parsedAction.getActionName(),
|
||||
"score", result.getScoreString(),
|
||||
"provider", provider)
|
||||
.increment();
|
||||
return result;
|
||||
} catch (final IOException | RuntimeException e) {
|
||||
if (dynamicConfigurationManager.getConfiguration().getCaptchaConfiguration().isFailOpen()) {
|
||||
logger.warn("Failed to verify captcha; failing open", e);
|
||||
return AssessmentResult.alwaysValid();
|
||||
}
|
||||
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
+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
|
||||
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import io.github.resilience4j.bulkhead.BulkheadConfig;
|
||||
import jakarta.validation.constraints.Min;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import java.time.Duration;
|
||||
|
||||
public class BulkheadConfiguration {
|
||||
|
||||
@JsonProperty
|
||||
@Min(1)
|
||||
private int maxConcurrentCalls = 256;
|
||||
|
||||
@JsonProperty
|
||||
@NotNull
|
||||
private Duration maxWaitDuration = BulkheadConfig.DEFAULT_MAX_WAIT_DURATION;
|
||||
|
||||
public int getMaxConcurrentCalls() {
|
||||
return maxConcurrentCalls;
|
||||
}
|
||||
|
||||
public void setMaxConcurrentCalls(final int maxConcurrentCalls) {
|
||||
this.maxConcurrentCalls = maxConcurrentCalls;
|
||||
}
|
||||
|
||||
public Duration getMaxWaitDuration() {
|
||||
return maxWaitDuration;
|
||||
}
|
||||
|
||||
public void setMaxWaitDuration(final Duration maxWaitDuration) {
|
||||
this.maxWaitDuration = maxWaitDuration;
|
||||
}
|
||||
|
||||
public BulkheadConfig.Builder toBulkheadConfig() {
|
||||
return BulkheadConfig.custom()
|
||||
.maxConcurrentCalls(maxConcurrentCalls)
|
||||
.maxWaitDuration(maxWaitDuration);
|
||||
}
|
||||
}
|
||||
+1
@@ -12,6 +12,7 @@ import javax.annotation.Nullable;
|
||||
import java.net.URI;
|
||||
|
||||
public record CdnConfiguration(@NotNull @Valid StaticAwsCredentialsFactory credentials,
|
||||
@NotBlank String baseUrl,
|
||||
@NotBlank String bucket,
|
||||
@NotBlank String region,
|
||||
@Nullable URI endpointOverride) {
|
||||
|
||||
+9
-9
@@ -68,11 +68,11 @@ public class DynamoDbTables {
|
||||
private final Table profiles;
|
||||
private final Table profilesV2;
|
||||
private final Table pushChallenge;
|
||||
private final Table pushNotificationExperimentSamples;
|
||||
private final Table redeemedReceipts;
|
||||
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;
|
||||
@@ -99,11 +99,11 @@ public class DynamoDbTables {
|
||||
@JsonProperty("profiles") final Table profiles,
|
||||
@JsonProperty("profilesV2") final Table profilesV2,
|
||||
@JsonProperty("pushChallenge") final Table pushChallenge,
|
||||
@JsonProperty("pushNotificationExperimentSamples") final Table pushNotificationExperimentSamples,
|
||||
@JsonProperty("redeemedReceipts") final Table redeemedReceipts,
|
||||
@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) {
|
||||
@@ -129,11 +129,11 @@ public class DynamoDbTables {
|
||||
this.profiles = profiles;
|
||||
this.profilesV2 = profilesV2;
|
||||
this.pushChallenge = pushChallenge;
|
||||
this.pushNotificationExperimentSamples = pushNotificationExperimentSamples;
|
||||
this.redeemedReceipts = redeemedReceipts;
|
||||
this.registrationRecovery = registrationRecovery;
|
||||
this.remoteConfig = remoteConfig;
|
||||
this.reportMessage = reportMessage;
|
||||
this.sandboxAccounts = sandboxAccounts;
|
||||
this.scheduledJobs = scheduledJobs;
|
||||
this.subscriptions = subscriptions;
|
||||
this.verificationSessions = verificationSessions;
|
||||
@@ -265,12 +265,6 @@ public class DynamoDbTables {
|
||||
return pushChallenge;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
public Table getPushNotificationExperimentSamples() {
|
||||
return pushNotificationExperimentSamples;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
public Table getRedeemedReceipts() {
|
||||
@@ -295,6 +289,12 @@ public class DynamoDbTables {
|
||||
return reportMessage;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
public Table getSandboxAccounts() {
|
||||
return sandboxAccounts;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
public TableWithExpiration getScheduledJobs() {
|
||||
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import jakarta.validation.constraints.PositiveOrZero;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/// Configuration for FoundationDB external clients. Primarily exists because an external client must be specified to
|
||||
/// make use of the multi-threaded client feature.
|
||||
///
|
||||
/// @param clientLibraryPaths a list of paths to external client libraries (generally .so files on Linux). This allows
|
||||
/// us to run multiple FDB client versions concurrently if needed; however, during normal operation, we expect the list
|
||||
/// to be a single path pointing to the current FDB client library
|
||||
/// @param threadsPerClient the number of networking threads spawned per client
|
||||
public record FoundationDbExternalClientConfiguration(@NotEmpty List<@NotBlank String> clientLibraryPaths,
|
||||
Optional<@PositiveOrZero Integer> threadsPerClient) {}
|
||||
+6
-2
@@ -5,6 +5,7 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import jakarta.annotation.Nullable;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.AssertTrue;
|
||||
import jakarta.validation.constraints.Max;
|
||||
@@ -25,7 +26,7 @@ import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessage
|
||||
/// @param batchPriorityTransactionTimeout the maximum time for a batch priority transaction. Should be greater than or equal to {@link transactionTimeout}
|
||||
/// @param batchPriorityTransactionRetryLimit the maximum number of retries permitted _within_ a batch priority transaction
|
||||
public record FoundationDbMessagesConfiguration(@NotEmpty Map<String, @Valid FoundationDbDatabaseFactory> clusters,
|
||||
@NotEmpty Map<@PositiveOrZero @Max(FoundationDbMessageStore.MAX_EPOCHS - 1) Integer, @Size(min = 1, max = FoundationDbMessageStore.MAX_SHARDS - 1) List<String>> epochs,
|
||||
@NotEmpty Map<@PositiveOrZero @Max(FoundationDbMessageStore.MAX_EPOCHS - 1) Integer, @Size(min = 1, max = FoundationDbMessageStore.MAX_SHARDS) List<String>> epochs,
|
||||
@PositiveOrZero @Max(FoundationDbMessageStore.MAX_EPOCHS - 1) int activeEpoch,
|
||||
@NotEmpty Map<@PositiveOrZero @Max(63) Integer, SecretBytes> versionstampCipherKeys,
|
||||
@PositiveOrZero @Max(63) int currentVersionstampCipherKey,
|
||||
@@ -33,7 +34,10 @@ public record FoundationDbMessagesConfiguration(@NotEmpty Map<String, @Valid Fou
|
||||
@NotNull Duration transactionTimeout,
|
||||
@PositiveOrZero long transactionRetryLimit,
|
||||
@NotNull Duration batchPriorityTransactionTimeout,
|
||||
@PositiveOrZero long batchPriorityTransactionRetryLimit) {
|
||||
@PositiveOrZero long batchPriorityTransactionRetryLimit,
|
||||
@Nullable String circuitBreakerConfigurationName,
|
||||
@Nullable String bulkheadConfigurationName,
|
||||
@Nullable @Valid FoundationDbExternalClientConfiguration externalClientConfiguration) {
|
||||
|
||||
public static final long DEFAULT_MAX_WATCHES_PER_CLIENT = 10_000;
|
||||
public static final Duration DEFAULT_TRANSACTION_TIMEOUT = Duration.ofSeconds(1);
|
||||
|
||||
+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
|
||||
|
||||
+11
-3
@@ -4,6 +4,7 @@
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import io.netty.handler.ssl.SslProvider;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import java.time.Duration;
|
||||
|
||||
@@ -13,15 +14,19 @@ import java.time.Duration;
|
||||
/// @param port The port to bind the omnibus server to
|
||||
/// @param websocketAddress The address of a listening websocket server for handling legacy requests
|
||||
/// @param websocketPort The port of a listening websocket server for handling legacy requests
|
||||
/// @param idleTimeout The duration after which an idle connection may be disconnected
|
||||
/// @param idleTimeout The duration after which a connection the client has not written to may be disconnected.
|
||||
/// Clients are expected to send some periodic write traffic (application-level or h2-level
|
||||
/// pings) to keep otherwise idle connections open
|
||||
/// @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()) {
|
||||
@@ -31,7 +36,10 @@ public record GrpcConfiguration(
|
||||
websocketAddress = "localhost";
|
||||
}
|
||||
if (idleTimeout == null) {
|
||||
idleTimeout = Duration.ofMinutes(5);
|
||||
idleTimeout = Duration.ofSeconds(60);
|
||||
}
|
||||
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 {
|
||||
|
||||
-29
@@ -1,29 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2020 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
|
||||
public class MessageCacheConfiguration {
|
||||
|
||||
@JsonProperty
|
||||
@NotNull
|
||||
@Valid
|
||||
private FaultTolerantRedisClusterFactory cluster;
|
||||
|
||||
@JsonProperty
|
||||
private int persistDelayMinutes = 10;
|
||||
|
||||
public FaultTolerantRedisClusterFactory getRedisClusterConfiguration() {
|
||||
return cluster;
|
||||
}
|
||||
|
||||
public int getPersistDelayMinutes() {
|
||||
return persistDelayMinutes;
|
||||
}
|
||||
}
|
||||
+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) {
|
||||
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
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,
|
||||
@NotEmpty List<@NotBlank String> origins,
|
||||
@NotNull Duration challengeTtl,
|
||||
@NotNull @ExactlySize(32) SecretBytes userHandleBlindingSecret) {
|
||||
}
|
||||
+10
@@ -35,6 +35,9 @@ public class DynamicCaptchaConfiguration {
|
||||
@NotNull
|
||||
private Map<Action, BigDecimal> scoreFloorByAction = Collections.emptyMap();
|
||||
|
||||
@JsonProperty
|
||||
private boolean failOpen = false;
|
||||
|
||||
public BigDecimal getScoreFloor() {
|
||||
return scoreFloor;
|
||||
}
|
||||
@@ -66,4 +69,11 @@ public class DynamicCaptchaConfiguration {
|
||||
this.hCaptchaSiteKeys = hCaptchaSiteKeys;
|
||||
}
|
||||
|
||||
public boolean isFailOpen() {
|
||||
return failOpen;
|
||||
}
|
||||
|
||||
public void setFailOpen(final boolean failOpen) {
|
||||
this.failOpen = failOpen;
|
||||
}
|
||||
}
|
||||
+14
-6
@@ -43,11 +43,11 @@ public class DynamicConfiguration {
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
DynamicMessagePersisterConfiguration messagePersister = new DynamicMessagePersisterConfiguration();
|
||||
DynamicMessageDeliveryConfiguration messageDelivery = new DynamicMessageDeliveryConfiguration();
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
DynamicMessageDeliveryConfiguration messageDelivery = new DynamicMessageDeliveryConfiguration();
|
||||
DynamicNotificationConfiguration notifications = DynamicNotificationConfiguration.DEFAULT;
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
@@ -77,6 +77,10 @@ public class DynamicConfiguration {
|
||||
@Valid
|
||||
private DynamicGrpcAllowListConfiguration grpcAllowList = new DynamicGrpcAllowListConfiguration();
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
private DynamicGrpcCompressionConfiguration grpcCompression = new DynamicGrpcCompressionConfiguration();
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
private DynamicOmnibusConfiguration omnibus = new DynamicOmnibusConfiguration(BigDecimal.ZERO);
|
||||
@@ -115,14 +119,14 @@ public class DynamicConfiguration {
|
||||
return captcha;
|
||||
}
|
||||
|
||||
public DynamicMessagePersisterConfiguration getMessagePersisterConfiguration() {
|
||||
return messagePersister;
|
||||
}
|
||||
|
||||
public DynamicMessageDeliveryConfiguration getMessageDeliveryConfiguration() {
|
||||
return messageDelivery;
|
||||
}
|
||||
|
||||
public DynamicNotificationConfiguration getNotificationConfiguration() {
|
||||
return notifications;
|
||||
}
|
||||
|
||||
public DynamicRegistrationConfiguration getRegistrationConfiguration() {
|
||||
return registrationConfiguration;
|
||||
}
|
||||
@@ -151,6 +155,10 @@ public class DynamicConfiguration {
|
||||
return grpcAllowList;
|
||||
}
|
||||
|
||||
public DynamicGrpcCompressionConfiguration getGrpcCompression() {
|
||||
return grpcCompression;
|
||||
}
|
||||
|
||||
public DynamicOmnibusConfiguration getOmnibus() {
|
||||
return omnibus;
|
||||
}
|
||||
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.configuration.dynamic;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Set;
|
||||
|
||||
/// Configure which gRPC methods may compress their responses
|
||||
///
|
||||
/// @param compressedServices A list of fully qualified service names for which all RPC responses should be compressed.
|
||||
/// For example, `kt_query.KeyTransparencyQueryService` would compress responses for all RPCs
|
||||
/// on that service.
|
||||
/// @param compressedMethods A list of fully qualified method names of RPCs whose responses should be compressed. For
|
||||
/// example, `kt_query.KeyTransparencyQueryService/Search` would compress responses for the
|
||||
/// `Search` RPC method
|
||||
public record DynamicGrpcCompressionConfiguration(
|
||||
Set<String> compressedServices,
|
||||
Set<String> compressedMethods) {
|
||||
|
||||
public DynamicGrpcCompressionConfiguration {
|
||||
if (compressedServices == null) {
|
||||
compressedServices = Collections.emptySet();
|
||||
}
|
||||
if (compressedMethods == null) {
|
||||
compressedMethods = Collections.emptySet();
|
||||
}
|
||||
}
|
||||
|
||||
public DynamicGrpcCompressionConfiguration() {
|
||||
// By default, no gRPC responses are compressed
|
||||
this(Collections.emptySet(), Collections.emptySet());
|
||||
}
|
||||
}
|
||||
+7
@@ -12,7 +12,14 @@ public class DynamicMessageDeliveryConfiguration {
|
||||
@JsonProperty
|
||||
private boolean readOnly = false;
|
||||
|
||||
@JsonProperty
|
||||
private boolean dropEphemeralMessages = false;
|
||||
|
||||
public boolean isReadOnly() {
|
||||
return readOnly;
|
||||
}
|
||||
|
||||
public boolean dropEphemeralMessages() {
|
||||
return dropEphemeralMessages;
|
||||
}
|
||||
}
|
||||
-58
@@ -1,58 +0,0 @@
|
||||
/*
|
||||
* Copyright 2022 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration.dynamic;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import java.time.Duration;
|
||||
|
||||
public class DynamicMessagePersisterConfiguration {
|
||||
|
||||
@JsonProperty
|
||||
private boolean persistenceEnabled = true;
|
||||
|
||||
/**
|
||||
* If we have to trim a client's persisted queue to make room to persist from Redis to DynamoDB, how much extra room should we make
|
||||
*/
|
||||
@JsonProperty
|
||||
private double trimOversizedQueueExtraRoomRatio = 1.5;
|
||||
|
||||
@JsonProperty
|
||||
private Duration nodeClaimTtl = Duration.ofMinutes(5);
|
||||
|
||||
@JsonProperty
|
||||
private Duration sleepBetweenNodes = Duration.ofSeconds(5);
|
||||
|
||||
public DynamicMessagePersisterConfiguration() {}
|
||||
|
||||
@VisibleForTesting
|
||||
public DynamicMessagePersisterConfiguration(final boolean persistenceEnabled,
|
||||
final double trimOversizedQueueExtraRoomRatio,
|
||||
final Duration nodeClaimTtl,
|
||||
final Duration sleepBetweenNodes) {
|
||||
|
||||
this.persistenceEnabled = persistenceEnabled;
|
||||
this.trimOversizedQueueExtraRoomRatio = trimOversizedQueueExtraRoomRatio;
|
||||
this.nodeClaimTtl = nodeClaimTtl;
|
||||
this.sleepBetweenNodes = sleepBetweenNodes;
|
||||
}
|
||||
|
||||
public boolean isPersistenceEnabled() {
|
||||
return persistenceEnabled;
|
||||
}
|
||||
|
||||
public double getTrimOversizedQueueExtraRoomRatio() {
|
||||
return trimOversizedQueueExtraRoomRatio;
|
||||
}
|
||||
|
||||
public Duration getNodeClaimTtl() {
|
||||
return nodeClaimTtl;
|
||||
}
|
||||
|
||||
public Duration getSleepBetweenNodes() {
|
||||
return sleepBetweenNodes;
|
||||
}
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration.dynamic;
|
||||
|
||||
public record DynamicNotificationConfiguration(boolean sendRemainingMessagesNotificationImmediately) {
|
||||
|
||||
public static final DynamicNotificationConfiguration DEFAULT =
|
||||
new DynamicNotificationConfiguration(false);
|
||||
}
|
||||
+19
-1
@@ -38,7 +38,9 @@ import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import javax.annotation.Nullable;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.glassfish.jersey.server.ManagedAsync;
|
||||
import org.signal.libsignal.usernames.BaseUsernameException;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
|
||||
@@ -97,6 +99,7 @@ public class AccountController {
|
||||
@Path("/gcm/")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@ManagedAsync
|
||||
public void setGcmRegistrationId(@Auth AuthenticatedDevice auth,
|
||||
@NotNull @Valid GcmRegistrationId registrationId) {
|
||||
|
||||
@@ -118,6 +121,7 @@ public class AccountController {
|
||||
|
||||
@DELETE
|
||||
@Path("/gcm/")
|
||||
@ManagedAsync
|
||||
public void deleteGcmRegistrationId(@Auth AuthenticatedDevice auth) {
|
||||
accounts.updateDevice(auth.accountIdentifier(), auth.deviceId(), d -> {
|
||||
d.setGcmId(null);
|
||||
@@ -130,6 +134,7 @@ public class AccountController {
|
||||
@Path("/apn/")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@ManagedAsync
|
||||
public void setApnRegistrationId(@Auth AuthenticatedDevice auth,
|
||||
@NotNull @Valid ApnRegistrationId registrationId) {
|
||||
|
||||
@@ -144,6 +149,7 @@ public class AccountController {
|
||||
|
||||
@DELETE
|
||||
@Path("/apn/")
|
||||
@ManagedAsync
|
||||
public void deleteApnRegistrationId(@Auth AuthenticatedDevice auth) {
|
||||
accounts.updateDevice(auth.accountIdentifier(), auth.deviceId(), d -> {
|
||||
d.setApnId(null);
|
||||
@@ -155,6 +161,7 @@ public class AccountController {
|
||||
@PUT
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/registration_lock")
|
||||
@ManagedAsync
|
||||
public void setRegistrationLock(@Auth AuthenticatedDevice auth, @NotNull @Valid RegistrationLock accountLock) {
|
||||
final SaltedTokenHash credentials = SaltedTokenHash.generateFor(accountLock.registrationLock());
|
||||
|
||||
@@ -168,6 +175,7 @@ public class AccountController {
|
||||
|
||||
@DELETE
|
||||
@Path("/registration_lock")
|
||||
@ManagedAsync
|
||||
public void removeRegistrationLock(@Auth AuthenticatedDevice auth) {
|
||||
accounts.update(auth.accountIdentifier(), a -> a.setRegistrationLock(null, null));
|
||||
}
|
||||
@@ -183,6 +191,7 @@ public class AccountController {
|
||||
@ApiResponse(responseCode = "204", description = "Device name changed successfully")
|
||||
@ApiResponse(responseCode = "404", description = "No device found with the given ID")
|
||||
@ApiResponse(responseCode = "403", description = "Not authorized to change the name of the device with the given ID")
|
||||
@ManagedAsync
|
||||
public void setName(@Auth final AuthenticatedDevice auth,
|
||||
@NotNull @Valid final DeviceName deviceName,
|
||||
|
||||
@@ -214,6 +223,7 @@ public class AccountController {
|
||||
@Path("/attributes/")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@ManagedAsync
|
||||
public void setAccountAttributes(
|
||||
@Auth AuthenticatedDevice auth,
|
||||
@HeaderParam(HeaderUtils.X_SIGNAL_AGENT) String signalAgent,
|
||||
@@ -260,6 +270,7 @@ public class AccountController {
|
||||
@GET
|
||||
@Path("/whoami")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@ManagedAsync
|
||||
public AccountIdentityResponse whoAmI(@Auth final AuthenticatedDevice auth) {
|
||||
final Account account = accounts.getByAccountIdentifier(auth.accountIdentifier())
|
||||
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
|
||||
@@ -278,6 +289,7 @@ public class AccountController {
|
||||
)
|
||||
@ApiResponse(responseCode = "204", description = "Username successfully deleted.", useReturnTypeSchema = true)
|
||||
@ApiResponse(responseCode = "401", description = "Account authentication check failed.")
|
||||
@ManagedAsync
|
||||
public void deleteUsernameHash(@Auth final AuthenticatedDevice auth) {
|
||||
accounts.clearUsernameHash(auth.accountIdentifier());
|
||||
}
|
||||
@@ -298,6 +310,7 @@ public class AccountController {
|
||||
@ApiResponse(responseCode = "409", description = "All username hashes from the list are taken.")
|
||||
@ApiResponse(responseCode = "422", description = "Invalid request format.")
|
||||
@ApiResponse(responseCode = "429", description = "Ratelimited.")
|
||||
@ManagedAsync
|
||||
public ReserveUsernameHashResponse reserveUsernameHash(
|
||||
@Auth final AuthenticatedDevice auth,
|
||||
@NotNull @Valid final ReserveUsernameHashRequest usernameRequest) throws RateLimitExceededException {
|
||||
@@ -337,13 +350,14 @@ public class AccountController {
|
||||
@ApiResponse(responseCode = "410", description = "Username hash not available (username can't be used).")
|
||||
@ApiResponse(responseCode = "422", description = "Invalid request format.")
|
||||
@ApiResponse(responseCode = "429", description = "Ratelimited.")
|
||||
@ManagedAsync
|
||||
public UsernameHashResponse confirmUsernameHash(
|
||||
@Auth final AuthenticatedDevice auth,
|
||||
@NotNull @Valid final ConfirmUsernameHashRequest confirmRequest) throws RateLimitExceededException {
|
||||
|
||||
try {
|
||||
usernameHashZkProofVerifier.verifyProof(confirmRequest.zkProof(), confirmRequest.usernameHash());
|
||||
} catch (final BaseUsernameException e) {
|
||||
} catch (final BaseUsernameException | InvalidInputException e) {
|
||||
throw new WebApplicationException(Response.status(422).build());
|
||||
}
|
||||
|
||||
@@ -417,6 +431,7 @@ public class AccountController {
|
||||
@ApiResponse(responseCode = "409", description = "Username is not set for the account.")
|
||||
@ApiResponse(responseCode = "422", description = "Invalid request format.")
|
||||
@ApiResponse(responseCode = "429", description = "Ratelimited.")
|
||||
@ManagedAsync
|
||||
public UsernameLinkHandle updateUsernameLink(
|
||||
@Auth final AuthenticatedDevice auth,
|
||||
@NotNull @Valid final EncryptedUsername encryptedUsername) throws RateLimitExceededException {
|
||||
@@ -454,6 +469,7 @@ public class AccountController {
|
||||
@ApiResponse(responseCode = "204", description = "Username Link successfully deleted.", useReturnTypeSchema = true)
|
||||
@ApiResponse(responseCode = "401", description = "Account authentication check failed.")
|
||||
@ApiResponse(responseCode = "429", description = "Ratelimited.")
|
||||
@ManagedAsync
|
||||
public void deleteUsernameLink(@Auth final AuthenticatedDevice auth) throws RateLimitExceededException {
|
||||
// check ratelimiter for username link operations
|
||||
rateLimiters.forDescriptor(RateLimiters.For.USERNAME_LINK_OPERATION).validate(auth.accountIdentifier());
|
||||
@@ -503,6 +519,7 @@ public class AccountController {
|
||||
@HEAD
|
||||
@Path("/account/{identifier}")
|
||||
@RateLimitedByIp(RateLimiters.For.CHECK_ACCOUNT_EXISTENCE)
|
||||
@ManagedAsync
|
||||
public Response accountExists(
|
||||
@Auth final Optional<AuthenticatedDevice> authenticatedAccount,
|
||||
|
||||
@@ -519,6 +536,7 @@ public class AccountController {
|
||||
|
||||
@DELETE
|
||||
@Path("/me")
|
||||
@ManagedAsync
|
||||
public void deleteAccount(@Auth AuthenticatedDevice auth) {
|
||||
accounts.delete(auth.accountIdentifier(), AccountsManager.DeletionReason.USER_REQUEST);
|
||||
}
|
||||
|
||||
+4
@@ -33,6 +33,7 @@ import java.io.IOException;
|
||||
import java.time.Instant;
|
||||
import java.util.UUID;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.glassfish.jersey.server.ManagedAsync;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.ChangesPhoneNumber;
|
||||
import org.whispersystems.textsecuregcm.auth.InvalidRegistrationSessionException;
|
||||
@@ -84,6 +85,7 @@ public class AccountControllerV2 {
|
||||
@ApiResponse(responseCode = "429", description = "Too many attempts", headers = @Header(
|
||||
name = "Retry-After",
|
||||
description = "If present, a positive integer indicating the number of seconds before a subsequent attempt could succeed"))
|
||||
@ManagedAsync
|
||||
public AccountIdentityResponse changeNumber(@Auth final AuthenticatedDevice authenticatedDevice,
|
||||
@NotNull @Valid final ChangeNumberRequest request,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgentString,
|
||||
@@ -151,6 +153,7 @@ public class AccountControllerV2 {
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Operation(summary = "Sets whether the account should be discoverable by phone number in the directory.")
|
||||
@ApiResponse(responseCode = "204", description = "The setting was successfully updated.")
|
||||
@ManagedAsync
|
||||
public void setPhoneNumberDiscoverability(
|
||||
@Auth AuthenticatedDevice auth,
|
||||
@NotNull @Valid PhoneNumberDiscoverabilityRequest phoneNumberDiscoverability) {
|
||||
@@ -171,6 +174,7 @@ public class AccountControllerV2 {
|
||||
@ApiResponse(responseCode = "200",
|
||||
description = "Response with data report. A plain text representation is a field in the response.",
|
||||
useReturnTypeSchema = true)
|
||||
@ManagedAsync
|
||||
public AccountDataReportResponse getAccountDataReport(@Auth final AuthenticatedDevice auth) {
|
||||
|
||||
final Account account = accountsManager.getByAccountIdentifier(auth.accountIdentifier())
|
||||
|
||||
+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");
|
||||
|
||||
+12
-16
@@ -9,13 +9,11 @@ import com.google.common.net.HttpHeaders;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.micrometer.core.instrument.DistributionSummary;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.headers.Header;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.Positive;
|
||||
import jakarta.ws.rs.ClientErrorException;
|
||||
import jakarta.ws.rs.GET;
|
||||
@@ -27,9 +25,9 @@ import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import javax.annotation.Nonnull;
|
||||
import javax.annotation.Nullable;
|
||||
import org.glassfish.jersey.server.ManagedAsync;
|
||||
import org.whispersystems.textsecuregcm.attachments.AttachmentGenerator;
|
||||
import org.whispersystems.textsecuregcm.attachments.AttachmentUtil;
|
||||
import org.whispersystems.textsecuregcm.attachments.GcsAttachmentGenerator;
|
||||
@@ -99,33 +97,31 @@ public class AttachmentControllerV4 {
|
||||
@ApiResponse(responseCode = "429", description = "Too many attempts", headers = @Header(
|
||||
name = "Retry-After",
|
||||
description = "If present, an positive integer indicating the number of seconds before a subsequent attempt could succeed"))
|
||||
@ManagedAsync
|
||||
public AttachmentDescriptorV3 getAttachmentUploadForm(
|
||||
@Auth AuthenticatedDevice auth,
|
||||
@Parameter(description = "The size of the attachment to upload in bytes")
|
||||
@QueryParam("uploadLength") final @Valid Optional<@Positive Long> maybeUploadLength,
|
||||
@QueryParam("uploadLength") @Positive final long uploadLength,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) @Nullable final String userAgent)
|
||||
throws RateLimitExceededException {
|
||||
|
||||
final long uploadLength = maybeUploadLength.orElse(maxUploadLength);
|
||||
if (uploadLength > maxUploadLength) {
|
||||
throw new ClientErrorException("exceeded maximum uploadLength", Response.Status.REQUEST_ENTITY_TOO_LARGE);
|
||||
}
|
||||
|
||||
countRateLimiter.validate(auth.accountIdentifier());
|
||||
if (maybeUploadLength.isPresent()) {
|
||||
// Ideally we'd check these two rate limits transactionally and only update them if both permits were acquired.
|
||||
// However, just undoing the first modification if the second one fails is close enough for our purposes
|
||||
try {
|
||||
bytesRateLimiter.validate(auth.accountIdentifier(), maybeUploadLength.get());
|
||||
} catch (RateLimitExceededException e) {
|
||||
countRateLimiter.restorePermits(auth.accountIdentifier(), 1);
|
||||
throw e;
|
||||
}
|
||||
|
||||
// Ideally we'd check these two rate limits transactionally and only update them if both permits were acquired.
|
||||
// However, just undoing the first modification if the second one fails is close enough for our purposes
|
||||
try {
|
||||
bytesRateLimiter.validate(auth.accountIdentifier(), uploadLength);
|
||||
} catch (RateLimitExceededException e) {
|
||||
countRateLimiter.restorePermits(auth.accountIdentifier(), 1);
|
||||
throw e;
|
||||
}
|
||||
|
||||
DistributionSummary.builder(ATTACHMENT_SIZE_NAME)
|
||||
.tags(Tags.of(UserAgentTagUtil.getPlatformTag(userAgent),
|
||||
Tag.of("uploadLengthSupplied", Boolean.toString(maybeUploadLength.isPresent()))))
|
||||
.tags(Tags.of(UserAgentTagUtil.getPlatformTag(userAgent)))
|
||||
.register(Metrics.globalRegistry)
|
||||
.record(uploadLength);
|
||||
|
||||
|
||||
+2
@@ -14,6 +14,7 @@ import jakarta.ws.rs.QueryParam;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import org.glassfish.jersey.server.ManagedAsync;
|
||||
import org.signal.libsignal.protocol.ServiceId;
|
||||
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
@@ -55,6 +56,7 @@ public class CallLinkController {
|
||||
@ApiResponse(responseCode = "401", description = "Account authentication check failed.")
|
||||
@ApiResponse(responseCode = "422", description = "Invalid request format.")
|
||||
@ApiResponse(responseCode = "429", description = "Ratelimited.")
|
||||
@ManagedAsync
|
||||
public CreateCallLinkCredential getCreateAuth(
|
||||
final @Auth AuthenticatedDevice auth,
|
||||
final @NotNull @Valid GetCreateCallLinkCredentialsRequest request,
|
||||
|
||||
+2
@@ -18,6 +18,7 @@ import jakarta.ws.rs.Produces;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
import org.glassfish.jersey.server.ManagedAsync;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.CloudflareTurnCredentialsManager;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
@@ -54,6 +55,7 @@ public class CallRoutingControllerV2 {
|
||||
@ApiResponse(responseCode = "401", description = "Account authentication check failed.")
|
||||
@ApiResponse(responseCode = "422", description = "Invalid request format.")
|
||||
@ApiResponse(responseCode = "429", description = "Rate limited.")
|
||||
@ManagedAsync
|
||||
public GetCallingRelaysResponse getCallingRelays(final @Auth AuthenticatedDevice auth)
|
||||
throws RateLimitExceededException, IOException {
|
||||
|
||||
|
||||
+3
@@ -29,6 +29,7 @@ import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import javax.annotation.Nonnull;
|
||||
import org.glassfish.jersey.server.ManagedAsync;
|
||||
import org.signal.libsignal.protocol.ServiceId;
|
||||
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
|
||||
import org.signal.libsignal.zkgroup.auth.AuthCredentialWithPniResponse;
|
||||
@@ -77,6 +78,7 @@ public class CertificateController {
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/delivery")
|
||||
@ManagedAsync
|
||||
public DeliveryCertificate getDeliveryCertificate(@Auth AuthenticatedDevice auth,
|
||||
@QueryParam("includeE164") @DefaultValue("true") boolean includeE164) {
|
||||
|
||||
@@ -96,6 +98,7 @@ public class CertificateController {
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/auth/group")
|
||||
@ManagedAsync
|
||||
public GroupCredentials getGroupAuthenticationCredentials(
|
||||
@Auth AuthenticatedDevice auth,
|
||||
@QueryParam("redemptionStartSeconds") long startSeconds,
|
||||
|
||||
+3
@@ -31,6 +31,7 @@ import jakarta.ws.rs.core.Context;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import java.io.IOException;
|
||||
import org.glassfish.jersey.server.ManagedAsync;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
@@ -88,6 +89,7 @@ public class ChallengeController {
|
||||
@ApiResponse(responseCode = "429", description = "Too many attempts", headers = @Header(
|
||||
name = "Retry-After",
|
||||
description = "If present, an positive integer indicating the number of seconds before a subsequent attempt could succeed"))
|
||||
@ManagedAsync
|
||||
public Response handleChallengeResponse(@Auth final AuthenticatedDevice auth,
|
||||
@Valid final AnswerChallengeRequest answerRequest,
|
||||
@Context final ContainerRequestContext requestContext,
|
||||
@@ -182,6 +184,7 @@ public class ChallengeController {
|
||||
@ApiResponse(responseCode = "429", description = "Too many attempts", headers = @Header(
|
||||
name = "Retry-After",
|
||||
description = "If present, an positive integer indicating the number of seconds before a subsequent attempt could succeed"))
|
||||
@ManagedAsync
|
||||
public Response requestPushChallenge(@Auth final AuthenticatedDevice auth,
|
||||
@Context ContainerRequestContext requestContext) {
|
||||
|
||||
|
||||
+8
-11
@@ -47,6 +47,7 @@ import java.util.concurrent.CompletionStage;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.stream.Collectors;
|
||||
import javax.annotation.Nullable;
|
||||
import org.glassfish.jersey.server.ManagedAsync;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.BasicAuthorizationHeader;
|
||||
import org.whispersystems.textsecuregcm.auth.ChangesLinkedDevices;
|
||||
@@ -72,6 +73,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 +90,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;
|
||||
@@ -136,6 +136,7 @@ public class DeviceController {
|
||||
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@ManagedAsync
|
||||
public DeviceInfoList getDevices(@Auth AuthenticatedDevice auth) {
|
||||
// Devices may change their own names (and primary devices may change the names of linked devices) and so the device
|
||||
// state associated with the authenticated account may be stale. Fetch a fresh copy to compensate.
|
||||
@@ -150,6 +151,7 @@ public class DeviceController {
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/{device_id}")
|
||||
@ChangesLinkedDevices
|
||||
@ManagedAsync
|
||||
public void removeDevice(@Auth AuthenticatedDevice auth, @PathParam("device_id") byte deviceId) {
|
||||
if (auth.deviceId() != Device.PRIMARY_ID && auth.deviceId() != deviceId) {
|
||||
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
|
||||
@@ -190,6 +192,7 @@ public class DeviceController {
|
||||
@ApiResponse(responseCode = "429", description = "Too many attempts", headers = @Header(
|
||||
name = "Retry-After",
|
||||
description = "If present, an positive integer indicating the number of seconds before a subsequent attempt could succeed"))
|
||||
@ManagedAsync
|
||||
public LinkDeviceToken createDeviceToken(@Auth AuthenticatedDevice auth)
|
||||
throws RateLimitExceededException, DeviceLimitExceededException {
|
||||
|
||||
@@ -198,15 +201,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));
|
||||
}
|
||||
@@ -228,6 +227,7 @@ public class DeviceController {
|
||||
@ApiResponse(responseCode = "429", description = "Too many attempts", headers = @Header(
|
||||
name = "Retry-After",
|
||||
description = "If present, an positive integer indicating the number of seconds before a subsequent attempt could succeed"))
|
||||
@ManagedAsync
|
||||
public LinkDeviceResponse linkDevice(@HeaderParam(HttpHeaders.AUTHORIZATION) @NotNull BasicAuthorizationHeader authorizationHeader,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) @Nullable String userAgent,
|
||||
@NotNull @Valid LinkDeviceRequest linkDeviceRequest)
|
||||
@@ -271,10 +271,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) {
|
||||
@@ -400,6 +396,7 @@ public class DeviceController {
|
||||
@PUT
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/capabilities")
|
||||
@ManagedAsync
|
||||
public void setCapabilities(@Auth final AuthenticatedDevice auth, @NotNull final Map<String, Boolean> capabilities) {
|
||||
accounts.updateDevice(auth.accountIdentifier(), auth.deviceId(),
|
||||
d -> d.setCapabilities(DeviceCapabilityAdapter.mapToSet(capabilities)));
|
||||
|
||||
+3
-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")
|
||||
@@ -160,6 +160,7 @@ public class DonationController {
|
||||
@ApiResponse(responseCode = "401", description = "Account authentication check failed")
|
||||
@ApiResponse(responseCode = "422", description = "Invalid request format")
|
||||
@ApiResponse(responseCode = "429", description = "Rate-limited; reduce requested permit count and/or try again after the prescribed delay")
|
||||
@ManagedAsync
|
||||
public CreateDonationPermitResponse createPermits(@Auth final AuthenticatedDevice auth,
|
||||
@NotNull @Valid final CreateDonationPermitsRequest request) throws RateLimitExceededException {
|
||||
|
||||
|
||||
+1
-50
@@ -5,66 +5,18 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.ws.rs.GET;
|
||||
import jakarta.ws.rs.Path;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Optional;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager;
|
||||
import org.whispersystems.websocket.session.WebSocketSession;
|
||||
import org.whispersystems.websocket.session.WebSocketSessionContext;
|
||||
|
||||
|
||||
@Path("/v1/keepalive")
|
||||
@Tag(name = "Keep Alive")
|
||||
public class KeepAliveController {
|
||||
|
||||
private final Logger logger = LoggerFactory.getLogger(KeepAliveController.class);
|
||||
|
||||
private final RedisMessageAvailabilityManager redisMessageAvailabilityManager;
|
||||
|
||||
private static final String CLOSED_CONNECTION_AGE_DISTRIBUTION_NAME = name(KeepAliveController.class,
|
||||
"closedConnectionAge");
|
||||
|
||||
|
||||
public KeepAliveController(final RedisMessageAvailabilityManager redisMessageAvailabilityManager) {
|
||||
this.redisMessageAvailabilityManager = redisMessageAvailabilityManager;
|
||||
}
|
||||
|
||||
@GET
|
||||
public Response getKeepAlive(@Auth Optional<AuthenticatedDevice> maybeAuth,
|
||||
@WebSocketSession WebSocketSessionContext context) {
|
||||
|
||||
maybeAuth.ifPresent(auth -> {
|
||||
if (!redisMessageAvailabilityManager.isLocallyPresent(auth.accountIdentifier(), auth.deviceId())) {
|
||||
|
||||
final Duration age = Duration.between(context.getClient().getCreated(), Instant.now());
|
||||
|
||||
logger.debug("***** No local subscription found for {}::{}; age = {}ms, User-Agent = {}",
|
||||
auth.accountIdentifier(), auth.deviceId(), age.toMillis(),
|
||||
context.getClient().getUserAgent());
|
||||
|
||||
context.getClient().close(1000, "OK");
|
||||
|
||||
Timer.builder(CLOSED_CONNECTION_AGE_DISTRIBUTION_NAME)
|
||||
.tags(Tags.of(UserAgentTagUtil.getPlatformTag(context.getClient().getUserAgent())))
|
||||
.register(Metrics.globalRegistry)
|
||||
.record(age);
|
||||
}
|
||||
});
|
||||
|
||||
public Response getKeepAlive() {
|
||||
return Response.ok().build();
|
||||
}
|
||||
|
||||
@@ -73,5 +25,4 @@ public class KeepAliveController {
|
||||
public Response getProvisioningKeepAlive() {
|
||||
return Response.ok().build();
|
||||
}
|
||||
|
||||
}
|
||||
+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);
|
||||
|
||||
+16
-42
@@ -91,9 +91,9 @@ import org.whispersystems.textsecuregcm.spam.SpamChecker;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
|
||||
import org.whispersystems.textsecuregcm.storage.ReportMessageHelper;
|
||||
import org.whispersystems.textsecuregcm.storage.ReportMessageManager;
|
||||
import org.whispersystems.textsecuregcm.util.HeaderUtils;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
|
||||
@Path("/v1/messages")
|
||||
@@ -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) {
|
||||
@@ -463,6 +463,7 @@ public class MessageController {
|
||||
@ApiResponse(
|
||||
responseCode = "410", description = "Mismatched registration ids supplied for some recipient devices",
|
||||
content = @Content(schema = @Schema(implementation = AccountStaleDevices[].class)))
|
||||
@ManagedAsync
|
||||
public Response sendMultiRecipientMessage(
|
||||
@Deprecated
|
||||
@Parameter(description="The bitwise xor of the unidentified access keys for every recipient of the message. Will be replaced with group send endorsements")
|
||||
@@ -605,7 +606,7 @@ public class MessageController {
|
||||
|
||||
CompletableFuture.allOf(resolvedRecipients.values()
|
||||
.stream()
|
||||
.map(account -> account.getAccountIdentifier())
|
||||
.map(Account::getAccountIdentifier)
|
||||
.map(accountIdentifier ->
|
||||
rateLimiters.getStoriesLimiter().validateAsync(accountIdentifier).toCompletableFuture())
|
||||
.toList()
|
||||
@@ -729,47 +730,13 @@ public class MessageController {
|
||||
@POST
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Path("/report/{source}/{messageGuid}")
|
||||
@ManagedAsync
|
||||
public Response reportSpamMessage(
|
||||
@Auth AuthenticatedDevice auth,
|
||||
@PathParam("source") String source,
|
||||
@PathParam("source") UUID source,
|
||||
@PathParam("messageGuid") UUID messageGuid,
|
||||
@Nullable SpamReport spamReport,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) String userAgent
|
||||
) {
|
||||
final Optional<String> sourceNumber;
|
||||
final Optional<UUID> sourceAci;
|
||||
final Optional<UUID> sourcePni;
|
||||
|
||||
boolean sourceAccountDeleted = false;
|
||||
if (source.startsWith("+")) {
|
||||
sourceNumber = Optional.of(source);
|
||||
final Optional<Account> maybeAccount = accountsManager.getByE164(source);
|
||||
if (maybeAccount.isPresent()) {
|
||||
sourceAci = maybeAccount.map(Account::getAccountIdentifier);
|
||||
sourcePni = maybeAccount.flatMap(Account::getPhoneNumberIdentifier);
|
||||
} else {
|
||||
sourcePni = Optional.ofNullable(phoneNumberIdentifiers.getPhoneNumberIdentifier(source).join());
|
||||
sourceAci = sourcePni.flatMap(accountsManager::findRecentlyDeletedAccountIdentifier);
|
||||
sourceAccountDeleted = true;
|
||||
}
|
||||
} else {
|
||||
sourceAci = Optional.of(UUID.fromString(source));
|
||||
|
||||
final Optional<Account> sourceAccount = accountsManager.getByAccountIdentifier(sourceAci.get());
|
||||
|
||||
if (sourceAccount.isEmpty()) {
|
||||
logger.warn("Could not find source: {}", sourceAci.get());
|
||||
sourcePni = accountsManager.findRecentlyDeletedPhoneNumberIdentifier(sourceAci.get());
|
||||
sourceNumber = sourcePni.flatMap(pni ->
|
||||
Util.getCanonicalNumber(phoneNumberIdentifiers.getPhoneNumber(pni).join()));
|
||||
sourceAccountDeleted = true;
|
||||
} else {
|
||||
sourceNumber = sourceAccount.flatMap(Account::getNumber);
|
||||
sourcePni = sourceAccount.flatMap(Account::getPhoneNumberIdentifier);
|
||||
}
|
||||
}
|
||||
|
||||
final UUID spamReporterUuid = auth.accountIdentifier();
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) String userAgent) {
|
||||
|
||||
// spam report token is optional, but if provided ensure it is non-empty.
|
||||
final Optional<byte[]> maybeSpamReportToken =
|
||||
@@ -777,7 +744,14 @@ public class MessageController {
|
||||
.flatMap(r -> Optional.ofNullable(r.token()))
|
||||
.filter(t -> t.length > 0);
|
||||
|
||||
reportMessageManager.report(sourceNumber, sourceAci, sourcePni, messageGuid, spamReporterUuid, maybeSpamReportToken, userAgent, sourceAccountDeleted);
|
||||
ReportMessageHelper.reportMessage(new AciServiceIdentifier(source),
|
||||
new AciServiceIdentifier(auth.accountIdentifier()),
|
||||
messageGuid,
|
||||
maybeSpamReportToken.orElse(null),
|
||||
userAgent,
|
||||
accountsManager,
|
||||
phoneNumberIdentifiers,
|
||||
reportMessageManager);
|
||||
|
||||
return Response.status(Status.ACCEPTED)
|
||||
.build();
|
||||
|
||||
+43
-60
@@ -36,14 +36,11 @@ import jakarta.ws.rs.core.Context;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import java.io.IOException;
|
||||
import java.math.BigDecimal;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import org.glassfish.jersey.server.ManagedAsync;
|
||||
@@ -62,21 +59,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.PurchaseAmountTooLargeException;
|
||||
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 +178,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 PurchaseAmountTooLargeException {
|
||||
|
||||
if (authenticatedAccount.isPresent()) {
|
||||
throw new ForbiddenException("must not use authenticated connection for one-time donation operations");
|
||||
@@ -199,7 +198,7 @@ public class OneTimeDonationController {
|
||||
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
|
||||
}
|
||||
|
||||
validateRequestCurrencyAmount(request, BigDecimal.valueOf(request.amount), stripeManager);
|
||||
validateRequestCurrencyAmount(request, request.amount, stripeManager);
|
||||
final PaymentIntent paymentIntent = stripeManager.createPaymentIntent(request.currency, request.amount,
|
||||
request.level,
|
||||
getClientPlatform(userAgent));
|
||||
@@ -212,29 +211,16 @@ public class OneTimeDonationController {
|
||||
*
|
||||
* @throws BadRequestException indicates validation failed. Inspect {@code response.error} for details
|
||||
*/
|
||||
private void validateRequestCurrencyAmount(final CreateBoostRequest request, final BigDecimal amount,
|
||||
private void validateRequestCurrencyAmount(final CreateBoostRequest request, final long amount,
|
||||
final CustomerAwareSubscriptionPaymentProcessor manager) {
|
||||
|
||||
final Map<String, String> errorBody = switch (OneTimeDonationUtil.validateOneTimeDonationRequest(request.currency,
|
||||
amount, request.level, request.paymentMethod, oneTimeDonationConfiguration, manager)) {
|
||||
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.UnsupportedLevel _ ->
|
||||
Map.of("error", "invalid_level");
|
||||
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.UnsupportedCurrency _ ->
|
||||
Map.of("error", "unsupported_currency");
|
||||
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.AmountBelowMinimum(final BigDecimal min) ->
|
||||
Map.of("error", "amount_below_currency_minimum",
|
||||
"minimum", min.toString());
|
||||
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.AmountAboveSepaLimit(final BigDecimal max) ->
|
||||
Map.of("error", "amount_above_sepa_limit",
|
||||
"maximum", max.toString());
|
||||
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.Success _ -> Collections.emptyMap();
|
||||
};
|
||||
|
||||
if (!errorBody.isEmpty()) {
|
||||
try {
|
||||
OneTimeDonationUtil.validateOneTimeDonationRequest(request.currency, amount, request.level, request.paymentMethod,
|
||||
oneTimeDonationConfiguration, manager);
|
||||
} catch (OneTimeDonationUtil.ValidationException e) {
|
||||
throw new BadRequestException(
|
||||
Response.status(Response.Status.BAD_REQUEST).entity(errorBody).build());
|
||||
Response.status(Response.Status.BAD_REQUEST).entity(e.getErrorBody()).build());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static class CreatePayPalBoostRequest extends CreateBoostRequest {
|
||||
@@ -265,7 +251,7 @@ public class OneTimeDonationController {
|
||||
throw new ForbiddenException("must not use authenticated connection for one-time donation operations");
|
||||
}
|
||||
|
||||
validateRequestCurrencyAmount(request, BigDecimal.valueOf(request.amount), braintreeManager);
|
||||
validateRequestCurrencyAmount(request, request.amount, braintreeManager);
|
||||
final List<Locale> acceptableLanguages =
|
||||
HeaderUtils.getAcceptableLanguagesForRequest(containerRequestContext);
|
||||
final OneTimeDonationUtil.LocalizedPayPalDonationLineItem localizedLineItem = OneTimeDonationUtil.localizePayPalDonationLineItem(
|
||||
@@ -301,13 +287,13 @@ 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");
|
||||
}
|
||||
|
||||
validateRequestCurrencyAmount(request, BigDecimal.valueOf(request.amount), braintreeManager);
|
||||
validateRequestCurrencyAmount(request, request.amount, braintreeManager);
|
||||
final BraintreeManager.PayPalChargeSuccessDetails chargeSuccessDetails = braintreeManager.captureOneTimePayment(
|
||||
request.payerId, request.paymentId,
|
||||
request.paymentToken, request.currency, request.amount, request.level, getClientPlatform(userAgent));
|
||||
@@ -315,7 +301,7 @@ public class OneTimeDonationController {
|
||||
return new ConfirmPayPalBoostResponse(chargeSuccessDetails.paymentId());
|
||||
}
|
||||
|
||||
public static class CreateBoostReceiptCredentialsRequest {
|
||||
public static class CreateBoostReceiptCredentialRequest {
|
||||
|
||||
/**
|
||||
* a payment ID from {@link #processor}
|
||||
@@ -329,10 +315,10 @@ public class OneTimeDonationController {
|
||||
public PaymentProvider processor = PaymentProvider.STRIPE;
|
||||
}
|
||||
|
||||
public record CreateBoostReceiptCredentialsSuccessResponse(byte[] receiptCredentialResponse) {
|
||||
public record CreateBoostReceiptCredentialSuccessResponse(byte[] receiptCredentialResponse) {
|
||||
}
|
||||
|
||||
public record CreateBoostReceiptCredentialsErrorResponse(
|
||||
public record CreateBoostReceiptCredentialErrorResponse(
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL) ChargeFailure chargeFailure) {}
|
||||
|
||||
@POST
|
||||
@@ -340,36 +326,32 @@ public class OneTimeDonationController {
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@ManagedAsync
|
||||
public Response createBoostReceiptCredentials(
|
||||
public Response createBoostReceiptCredential(
|
||||
@Auth final Optional<AuthenticatedDevice> authenticatedAccount,
|
||||
@NotNull @Valid final CreateBoostReceiptCredentialsRequest request,
|
||||
@NotNull @Valid final CreateBoostReceiptCredentialRequest request,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent) throws IOException {
|
||||
|
||||
if (authenticatedAccount.isPresent()) {
|
||||
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 CreateBoostReceiptCredentialsErrorResponse(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);
|
||||
@@ -377,6 +359,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);
|
||||
@@ -408,7 +391,7 @@ public class OneTimeDonationController {
|
||||
UserAgentTagUtil.getPlatformTag(userAgent)))
|
||||
.increment();
|
||||
return Response.ok(
|
||||
new CreateBoostReceiptCredentialsSuccessResponse(receiptCredentialResponse.serialize()))
|
||||
new CreateBoostReceiptCredentialSuccessResponse(receiptCredentialResponse.serialize()))
|
||||
.build();
|
||||
}
|
||||
}
|
||||
+2
-5
@@ -168,8 +168,8 @@ public class ProfileController {
|
||||
@ApiResponse(responseCode = "400", description = "Invalid create profile request.")
|
||||
@ApiResponse(responseCode = "401", description = "Account authentication check failed.")
|
||||
@ApiResponse(responseCode = "403", description = "The request contained a payment address, but payments are not supported in the region of the account’s phone number or the caller's ASN if the account does not have a phone number.")
|
||||
@ApiResponse(responseCode = "412", description = "The requesting account has the profiles_v2 capability")
|
||||
@ApiResponse(responseCode = "422", description = "Invalid request format")
|
||||
@ManagedAsync
|
||||
public Response setProfile(@Auth AuthenticatedDevice auth,
|
||||
@NotNull @Valid CreateProfileRequest request,
|
||||
@Context final ContainerRequestContext requestContext) {
|
||||
@@ -177,10 +177,6 @@ public class ProfileController {
|
||||
final Account account = accountsManager.getByAccountIdentifier(auth.accountIdentifier())
|
||||
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
|
||||
|
||||
if (account.hasCapability(DeviceCapability.PROFILES_V2)) {
|
||||
return Response.status(Response.Status.PRECONDITION_FAILED).build();
|
||||
}
|
||||
|
||||
final Optional<VersionedProfileV1> currentProfile =
|
||||
profilesManager.getV1(auth.accountIdentifier(), request.version());
|
||||
|
||||
@@ -278,6 +274,7 @@ public class ProfileController {
|
||||
@ApiResponse(responseCode = "401", description = "Not authorized to access this profile.")
|
||||
@ApiResponse(responseCode = "404", description = "Profile or account not found.")
|
||||
@ApiResponse(responseCode = "429", description = "Rate limit exceeded.")
|
||||
@ManagedAsync
|
||||
public ExpiringProfileKeyCredentialProfileResponse getProfile(
|
||||
@Auth Optional<AuthenticatedDevice> maybeAuthenticatedDevice,
|
||||
@HeaderParam(HeaderUtils.UNIDENTIFIED_ACCESS_KEY) Optional<Anonymous> accessKey,
|
||||
|
||||
+2
@@ -29,6 +29,7 @@ import jakarta.ws.rs.WebApplicationException;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import java.util.Base64;
|
||||
import org.glassfish.jersey.server.ManagedAsync;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.entities.ProvisioningMessage;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
@@ -76,6 +77,7 @@ public class ProvisioningController {
|
||||
@ApiResponse(responseCode="204", description="The provisioning message was delivered to the given provisioning address")
|
||||
@ApiResponse(responseCode="400", description="The provisioning message was too large")
|
||||
@ApiResponse(responseCode="404", description="No device with the given provisioning address was connected at the time of the request")
|
||||
@ManagedAsync
|
||||
public void sendProvisioningMessage(@Auth final AuthenticatedDevice auth,
|
||||
|
||||
@Parameter(description = "The temporary provisioning address to which to send a provisioning message")
|
||||
|
||||
+58
-17
@@ -45,6 +45,7 @@ import java.util.UUID;
|
||||
import javax.annotation.Nullable;
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.glassfish.jersey.server.ManagedAsync;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.VerificationFailedException;
|
||||
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialPresentation;
|
||||
@@ -53,6 +54,7 @@ import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.BasicAuthorizationHeader;
|
||||
import org.whispersystems.textsecuregcm.auth.InvalidRegistrationSessionException;
|
||||
import org.whispersystems.textsecuregcm.auth.MfaFailureException;
|
||||
import org.whispersystems.textsecuregcm.auth.PhoneVerificationTokenManager;
|
||||
import org.whispersystems.textsecuregcm.auth.RecoveryPasswordVerificationFailedException;
|
||||
import org.whispersystems.textsecuregcm.auth.RegistrationLockFailureException;
|
||||
@@ -66,18 +68,21 @@ import org.whispersystems.textsecuregcm.entities.RegistrationLockFailure;
|
||||
import org.whispersystems.textsecuregcm.entities.RegistrationRequest;
|
||||
import org.whispersystems.textsecuregcm.filters.RemoteAddressFilter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.mappers.MfaFailureExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.spam.RegistrationFraudChecker;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.AnnotatedTotpKey;
|
||||
import org.whispersystems.textsecuregcm.storage.AnnotatedWebAuthnCredential;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceIdentityInfo;
|
||||
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;
|
||||
|
||||
@@ -94,6 +99,7 @@ public class RegistrationController {
|
||||
private static final String COUNTRY_CODE_TAG_NAME = "countryCode";
|
||||
private static final String REGION_CODE_TAG_NAME = "regionCode";
|
||||
private static final String VERIFICATION_TYPE_TAG_NAME = "verification";
|
||||
private static final String FICTITIOUS_NUMBER_TAG_NAME = "fictitiousNumber";
|
||||
|
||||
private final AccountsManager accounts;
|
||||
private final PhoneVerificationTokenManager phoneVerificationTokenManager;
|
||||
@@ -149,8 +155,14 @@ public class RegistrationController {
|
||||
@ApiResponse(responseCode = "429", description = "Too many attempts", headers = @Header(
|
||||
name = "Retry-After",
|
||||
description = "If present, an positive integer indicating the number of seconds before a subsequent attempt could succeed"))
|
||||
@ApiResponse(responseCode = "441", description = "A valid one-time password (TOTP) is required, but either no password was provided or it was incorrect")
|
||||
@ApiResponse(responseCode = "441",
|
||||
description = """
|
||||
Second factor authentication failed. Either the account has one or more factors configured, and the request’s
|
||||
factor was incorrect or absent, or the account has no factors, but the request included a factor.
|
||||
""",
|
||||
content = @Content(schema = @Schema(implementation = MfaFailureExceptionMapper.MfaFailureResponse.class)))
|
||||
@ApiResponse(responseCode = "499", description = "Client must support post-quantum ratchet")
|
||||
@ManagedAsync
|
||||
public AccountCreationResponse register(
|
||||
@Parameter(
|
||||
in = ParameterIn.HEADER,
|
||||
@@ -171,7 +183,7 @@ public class RegistrationController {
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
|
||||
@NotNull @Valid final RegistrationRequest registrationRequest,
|
||||
@Context final ContainerRequestContext requestContext)
|
||||
throws RateLimitExceededException, InterruptedException, RegistrationLockFailureException {
|
||||
throws RateLimitExceededException, InterruptedException, RegistrationLockFailureException, MfaFailureException {
|
||||
|
||||
if (!registrationRequest.isEverySignedKeyValid(userAgent)) {
|
||||
throw new WebApplicationException("Invalid signature", 422);
|
||||
@@ -219,7 +231,7 @@ public class RegistrationController {
|
||||
final ContainerRequestContext requestContext,
|
||||
final String userAgent,
|
||||
final String signalAgent)
|
||||
throws RateLimitExceededException, InterruptedException, RegistrationLockFailureException {
|
||||
throws RateLimitExceededException, InterruptedException, RegistrationLockFailureException, MfaFailureException {
|
||||
|
||||
if (registrationRequest.pniIdentityKey() == null) {
|
||||
// RegistrationRequest checks that either all phone number-associated information is present or all is absent
|
||||
@@ -249,7 +261,7 @@ public class RegistrationController {
|
||||
|
||||
// There can be at most one existing account for a set of numbers in the same equivalence class, so it's sufficient
|
||||
// to find the first one.
|
||||
final Optional<Account> existingAccount = Util.getAlternateForms(number)
|
||||
Optional<Account> existingAccount = Util.getAlternateForms(number)
|
||||
.stream()
|
||||
.map(accounts::getByE164)
|
||||
.filter(Optional::isPresent)
|
||||
@@ -274,7 +286,7 @@ public class RegistrationController {
|
||||
registrationRequest.accountAttributes().getRegistrationLock(),
|
||||
userAgent, RegistrationLockVerificationManager.Flow.REGISTRATION, verificationType);
|
||||
|
||||
checkTotp(existingAccount.get(), registrationRequest.totp());
|
||||
existingAccount = Optional.of(checkMfa(existingAccount.get(), registrationRequest.webAuthnResponse(), registrationRequest.totp()));
|
||||
}
|
||||
|
||||
final Account account = accounts.create(number,
|
||||
@@ -311,7 +323,8 @@ public class RegistrationController {
|
||||
Metrics.counter(ACCOUNT_CREATED_COUNTER_NAME, Tags.of(UserAgentTagUtil.getPlatformTag(userAgent),
|
||||
Tag.of(COUNTRY_CODE_TAG_NAME, Util.getCountryCode(number)),
|
||||
Tag.of(REGION_CODE_TAG_NAME, Util.getRegion(number)),
|
||||
Tag.of(VERIFICATION_TYPE_TAG_NAME, verificationType.name())))
|
||||
Tag.of(VERIFICATION_TYPE_TAG_NAME, verificationType.name()),
|
||||
Tag.of(FICTITIOUS_NUMBER_TAG_NAME, String.valueOf(Util.isFictitiousNumber(number)))))
|
||||
.increment();
|
||||
|
||||
final AccountIdentityResponse identityResponse = new AccountIdentityResponseBuilder(account)
|
||||
@@ -357,7 +370,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");
|
||||
}
|
||||
|
||||
@@ -394,7 +407,7 @@ public class RegistrationController {
|
||||
final String password,
|
||||
final RegistrationRequest registrationRequest,
|
||||
final String userAgent,
|
||||
final String signalAgent) throws RegistrationLockFailureException, RateLimitExceededException {
|
||||
final String signalAgent) throws RegistrationLockFailureException, RateLimitExceededException, MfaFailureException {
|
||||
|
||||
if (!dynamicConfigurationManager.getConfiguration().getLoginPurchaseConfiguration().enabled()) {
|
||||
throw new BadRequestException("login purchases are not enabled");
|
||||
@@ -412,7 +425,7 @@ public class RegistrationController {
|
||||
throw new BadRequestException("Must specify a PNI-associated identity key when recovering an account by identifier");
|
||||
}
|
||||
|
||||
final Account existingAccount = accounts.getByAccountIdentifier(accountIdentifier)
|
||||
Account existingAccount = accounts.getByAccountIdentifier(accountIdentifier)
|
||||
.orElseThrow(ForbiddenException::new);
|
||||
|
||||
final boolean passwordVerified = existingAccount.getAccountRecoveryPassword()
|
||||
@@ -423,14 +436,14 @@ public class RegistrationController {
|
||||
throw new ForbiddenException();
|
||||
}
|
||||
|
||||
checkTotp(existingAccount, registrationRequest.totp());
|
||||
|
||||
if (!registrationRequest.skipDeviceTransfer() && existingAccount.hasCapability(DeviceCapability.TRANSFER)) {
|
||||
// If a device transfer is possible, clients must explicitly opt out of a transfer (i.e. after prompting the user)
|
||||
// before we'll let them recover an account and start "from scratch"
|
||||
throw new WebApplicationException(Response.status(409, "device transfer available").build());
|
||||
}
|
||||
|
||||
existingAccount = checkMfa(existingAccount, registrationRequest.webAuthnResponse(), registrationRequest.totp());
|
||||
|
||||
final Account reclaimedAccount = existingAccount.getNumber().isPresent()
|
||||
? recoverAccountWithPhoneNumber(existingAccount, registrationRequest, password, userAgent, signalAgent)
|
||||
: recoverAccountWithoutPhoneNumber(existingAccount, registrationRequest, password, userAgent, signalAgent);
|
||||
@@ -508,11 +521,39 @@ public class RegistrationController {
|
||||
userAgent);
|
||||
}
|
||||
|
||||
private void checkTotp(final Account account, @Nullable final Integer totp) throws RateLimitExceededException {
|
||||
rateLimiters.getCheckTotpLimiter().validate(account.getAccountIdentifier());
|
||||
/// @return the maybe-updated [Account] reference. Callers must use it to avoid stale reads and updates.
|
||||
private Account checkMfa(final Account account, @Nullable final String webAuthn, @Nullable final Integer totp) throws RateLimitExceededException, MfaFailureException {
|
||||
|
||||
if (!accounts.verifyTotp(account, clock.instant(), totp)) {
|
||||
throw new WebApplicationException(441);
|
||||
final boolean hasTotp = account.getMfaKeys().values().stream().anyMatch(k -> k instanceof AnnotatedTotpKey);
|
||||
final boolean hasWebAuthn = account.getMfaKeys().values().stream().anyMatch(k -> k instanceof AnnotatedWebAuthnCredential);
|
||||
|
||||
if (!hasTotp && !hasWebAuthn) {
|
||||
if (totp != null || webAuthn != null) {
|
||||
throw new MfaFailureException(null, false);
|
||||
}
|
||||
return account;
|
||||
}
|
||||
|
||||
if (totp != null || webAuthn != null) {
|
||||
rateLimiters.getCheckMfaLimiter().validate(account.getAccountIdentifier());
|
||||
}
|
||||
|
||||
final Optional<Account> updatedAccount;
|
||||
if (hasWebAuthn && webAuthn != null) {
|
||||
updatedAccount = accounts.verifyWebAuthnAuthentication(account, webAuthn);
|
||||
} else {
|
||||
updatedAccount = Optional.empty();
|
||||
}
|
||||
|
||||
final boolean webAuthnVerified = updatedAccount.isPresent();
|
||||
|
||||
final boolean totpVerified = hasTotp && totp != null
|
||||
&& accounts.verifyTotp(account, clock.instant(), totp);
|
||||
|
||||
if (webAuthnVerified || totpVerified) {
|
||||
return updatedAccount.orElse(account);
|
||||
}
|
||||
|
||||
throw new MfaFailureException(accounts.startWebAuthnAuthentication(account).orElse(null), hasTotp);
|
||||
}
|
||||
}
|
||||
+2
@@ -24,6 +24,7 @@ import jakarta.ws.rs.core.Response;
|
||||
import java.util.HexFormat;
|
||||
import java.util.Map;
|
||||
import javax.annotation.Nullable;
|
||||
import org.glassfish.jersey.server.ManagedAsync;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.entities.RemoteConfigurationResponse;
|
||||
import org.whispersystems.textsecuregcm.storage.RemoteConfigsManager;
|
||||
@@ -52,6 +53,7 @@ public class RemoteConfigController {
|
||||
@ApiResponse(responseCode = "304", description = "There is no change since the last fetch", content = {})
|
||||
@ApiResponse(responseCode = "401", description = "This request requires authentication", content = {})
|
||||
|
||||
@ManagedAsync
|
||||
public Response getAll(
|
||||
@Auth AuthenticatedDevice auth,
|
||||
|
||||
|
||||
+2
@@ -32,6 +32,7 @@ import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
import org.glassfish.jersey.server.ManagedAsync;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
|
||||
@@ -115,6 +116,7 @@ public class SecureValueRecovery2Controller {
|
||||
@ApiResponse(responseCode = "200", description = "`JSON` with the check results.", useReturnTypeSchema = true)
|
||||
@ApiResponse(responseCode = "422", description = "Provided list of SVR2 credentials could not be parsed")
|
||||
@ApiResponse(responseCode = "400", description = "`POST` request body is not a valid `JSON`")
|
||||
@ManagedAsync
|
||||
public AuthCheckResponseV2 authCheck(
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
|
||||
@NotNull @Valid final AuthCheckRequest request) {
|
||||
|
||||
+2
@@ -21,6 +21,7 @@ import java.time.Instant;
|
||||
import java.util.HexFormat;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import org.glassfish.jersey.server.ManagedAsync;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.entities.StickerPackFormUploadAttributes;
|
||||
import org.whispersystems.textsecuregcm.entities.StickerPackFormUploadAttributes.StickerPackFormUploadItem;
|
||||
@@ -49,6 +50,7 @@ public class StickerController {
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/pack/form/{count}")
|
||||
@ManagedAsync
|
||||
public StickerPackFormUploadAttributes getStickersForm(@Auth AuthenticatedDevice auth,
|
||||
@PathParam("count") @Min(1) @Max(201) int stickerCount)
|
||||
throws RateLimitExceededException {
|
||||
|
||||
+48
-47
@@ -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);
|
||||
|
||||
@@ -626,7 +626,7 @@ public class SubscriptionController {
|
||||
String currency,
|
||||
|
||||
@Schema(
|
||||
description = "The amount paid for the subscription in the currency's smallest unit",
|
||||
description = "The amount paid for the subscription in the currency's minor unit",
|
||||
externalDocs = @ExternalDocumentation(description = "Stripe Currencies", url = "https://docs.stripe.com/currencies"))
|
||||
BigDecimal amount,
|
||||
|
||||
@@ -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)
|
||||
@@ -678,7 +678,7 @@ public class SubscriptionController {
|
||||
subscriptionInformation.active(),
|
||||
subscriptionInformation.cancelAtPeriodEnd(),
|
||||
subscriptionInformation.price().currency(),
|
||||
subscriptionInformation.price().amount(),
|
||||
BigDecimal.valueOf(subscriptionInformation.price().amount()),
|
||||
subscriptionInformation.status().getApiValue(),
|
||||
subscriptionInformation.paymentProvider(),
|
||||
subscriptionInformation.paymentMethod(),
|
||||
@@ -688,12 +688,12 @@ public class SubscriptionController {
|
||||
.orElseGet(() -> new GetSubscriptionInformationResponse(null, null));
|
||||
}
|
||||
|
||||
public record GetReceiptCredentialsRequest(
|
||||
public record GetReceiptCredentialRequest(
|
||||
@Schema(description = "A ReceiptCredentialRequest encoded in standard base64 with padding")
|
||||
@NotEmpty byte[] receiptCredentialRequest) {
|
||||
}
|
||||
|
||||
public record GetReceiptCredentialsResponse(
|
||||
public record GetReceiptCredentialResponse(
|
||||
@Schema(description = "A ReceiptCredentialResponse encoded in standard base64 with padding")
|
||||
@NotEmpty byte[] receiptCredentialResponse) {
|
||||
}
|
||||
@@ -711,7 +711,7 @@ public class SubscriptionController {
|
||||
invoice. Clients SHOULD retry requests at this endpoint with the same ReceiptCredentialRequest value until
|
||||
receiving a response. After receiving a response, clients should then compute the ReceiptCredentialPresentation
|
||||
and redeem it at the receipt redemption endpoint. Once the first attempt is made there, the same
|
||||
ReceiptCredentialRequest MUST NOT be used again to request receipt credentials.
|
||||
ReceiptCredentialRequest MUST NOT be used again to request a receipt credential.
|
||||
|
||||
Note that you may in fact redeem TWO or more invoices for the same ReceiptCredentialRequest while retrying this
|
||||
operation if a later invoice gets paid while you are retrying. However, the returned receipt is always for the
|
||||
@@ -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")
|
||||
@@ -747,16 +747,17 @@ public class SubscriptionController {
|
||||
name = "Retry-After",
|
||||
description = "If present, a positive integer indicating the number of seconds before a subsequent attempt could succeed"))
|
||||
@ManagedAsync
|
||||
public Response createSubscriptionReceiptCredentials(
|
||||
public Response createSubscriptionReceiptCredential(
|
||||
@Auth Optional<AuthenticatedDevice> authenticatedAccount,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
|
||||
@PathParam("subscriberId") String subscriberId,
|
||||
@NotNull @Valid GetReceiptCredentialsRequest request) throws SubscriptionException, RateLimitExceededException {
|
||||
@NotNull @Valid GetReceiptCredentialRequest request) throws PurchaseException, RateLimitExceededException {
|
||||
SubscriberCredentials subscriberCredentials = SubscriberCredentials.process(authenticatedAccount, subscriberId, clock);
|
||||
try {
|
||||
final SubscriptionManager.ReceiptResult receiptCredential = subscriptionManager.createReceiptCredentials(
|
||||
final SubscriptionManager.ReceiptResult receiptCredential = subscriptionManager.createReceiptCredential(
|
||||
subscriberCredentials, request.receiptCredentialRequest(),
|
||||
r -> SubscriptionsUtil.receiptExpirationWithGracePeriod(subscriptionConfiguration, r));
|
||||
r -> SubscriptionsUtil.receiptExpirationWithGracePeriod(subscriptionConfiguration, r),
|
||||
userAgent);
|
||||
|
||||
final ReceiptCredentialResponse receiptCredentialResponse = receiptCredential.receiptCredentialResponse();
|
||||
final CustomerAwareSubscriptionPaymentProcessor.ReceiptItem receipt = receiptCredential.receiptItem();
|
||||
@@ -769,8 +770,8 @@ public class SubscriptionController {
|
||||
.toLowerCase(Locale.ROOT)),
|
||||
UserAgentTagUtil.getPlatformTag(userAgent)))
|
||||
.increment();
|
||||
return Response.ok(new GetReceiptCredentialsResponse(receiptCredentialResponse.serialize())).build();
|
||||
} catch (SubscriptionReceiptRequestedForOpenPaymentException e) {
|
||||
return Response.ok(new GetReceiptCredentialResponse(receiptCredentialResponse.serialize())).build();
|
||||
} catch (PurchaseReceiptRequestedForOpenPaymentException e) {
|
||||
return Response.noContent().build();
|
||||
}
|
||||
}
|
||||
@@ -782,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);
|
||||
|
||||
@@ -793,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);
|
||||
|
||||
@@ -804,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);
|
||||
|
||||
+6
-11
@@ -7,7 +7,6 @@ package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.i18n.phonenumbers.NumberParseException;
|
||||
import com.google.i18n.phonenumbers.PhoneNumberUtil;
|
||||
import com.google.i18n.phonenumbers.Phonenumber;
|
||||
@@ -61,6 +60,7 @@ import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import org.apache.commons.lang3.Strings;
|
||||
import org.apache.http.HttpStatus;
|
||||
import org.glassfish.jersey.server.ManagedAsync;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.captcha.AssessmentResult;
|
||||
@@ -73,9 +73,7 @@ import org.whispersystems.textsecuregcm.entities.SubmitVerificationCodeRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.UpdateVerificationSessionRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.VerificationCodeRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.VerificationSessionResponse;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.filters.RemoteAddressFilter;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.mappers.RegistrationServiceSenderExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.metrics.CaptchaMetrics;
|
||||
@@ -132,9 +130,6 @@ public class VerificationController {
|
||||
private static final String EXISTING_ACCOUNT_PLATFORM = "existingAccountPlatform";
|
||||
private static final String EXISTING_ACCOUNT_RECENTLY_SEEN_TAG_NAME = "existingAccountRecentlySeen";
|
||||
|
||||
@VisibleForTesting
|
||||
static final String VERIFICATION_CODE_PUSH_NOTIFICATION_EXPERIMENT_NAME = "verificationCodePushNotification";
|
||||
|
||||
private final RegistrationServiceClient registrationServiceClient;
|
||||
private final VerificationSessionManager verificationSessionManager;
|
||||
private final PushNotificationManager pushNotificationManager;
|
||||
@@ -146,7 +141,6 @@ public class VerificationController {
|
||||
private final CarrierDataProvider carrierDataProvider;
|
||||
private final RegistrationFraudChecker registrationFraudChecker;
|
||||
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
|
||||
private final ExperimentEnrollmentManager experimentEnrollmentManager;
|
||||
private final Clock clock;
|
||||
|
||||
public VerificationController(final RegistrationServiceClient registrationServiceClient,
|
||||
@@ -160,7 +154,6 @@ public class VerificationController {
|
||||
final CarrierDataProvider carrierDataProvider,
|
||||
final RegistrationFraudChecker registrationFraudChecker,
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
|
||||
final ExperimentEnrollmentManager experimentEnrollmentManager,
|
||||
final Clock clock) {
|
||||
this.registrationServiceClient = registrationServiceClient;
|
||||
this.verificationSessionManager = verificationSessionManager;
|
||||
@@ -173,7 +166,6 @@ public class VerificationController {
|
||||
this.carrierDataProvider = carrierDataProvider;
|
||||
this.registrationFraudChecker = registrationFraudChecker;
|
||||
this.dynamicConfigurationManager = dynamicConfigurationManager;
|
||||
this.experimentEnrollmentManager = experimentEnrollmentManager;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
@@ -193,6 +185,7 @@ public class VerificationController {
|
||||
name = "Retry-After",
|
||||
description = "If present, an positive integer indicating the number of seconds before a subsequent attempt could succeed",
|
||||
schema = @Schema(implementation = Integer.class)))
|
||||
@ManagedAsync
|
||||
public VerificationSessionResponse createSession(@NotNull @Valid final CreateVerificationSessionRequest request,
|
||||
@Context final ContainerRequestContext requestContext)
|
||||
throws RateLimitExceededException, ObsoletePhoneNumberFormatException {
|
||||
@@ -272,6 +265,7 @@ public class VerificationController {
|
||||
name = "Retry-After",
|
||||
description = "If present, an positive integer indicating the number of seconds before a subsequent attempt could succeed",
|
||||
schema = @Schema(implementation = Integer.class)))
|
||||
@ManagedAsync
|
||||
public VerificationSessionResponse updateSession(
|
||||
@PathParam("sessionId") final String encodedSessionId,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
|
||||
@@ -527,6 +521,7 @@ public class VerificationController {
|
||||
@ApiResponse(responseCode = "400", description = "Invalid session ID")
|
||||
@ApiResponse(responseCode = "404", description = "Session with the specified ID could not be found")
|
||||
@ApiResponse(responseCode = "422", description = "Malformed session ID encoding")
|
||||
@ManagedAsync
|
||||
public VerificationSessionResponse getSession(@PathParam("sessionId") final String encodedSessionId) {
|
||||
|
||||
final RegistrationServiceSession registrationServiceSession = retrieveRegistrationServiceSession(encodedSessionId);
|
||||
@@ -573,6 +568,7 @@ public class VerificationController {
|
||||
future attempts to request or submit verification codes (since those attempts would be all but guaranteed to fail).
|
||||
""",
|
||||
content = @Content(schema = @Schema(implementation = RegistrationServiceSenderExceptionMapper.SendVerificationCodeFailureResponse.class)))
|
||||
@ManagedAsync
|
||||
public VerificationSessionResponse requestVerificationCode(@PathParam("sessionId") final String encodedSessionId,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
|
||||
@Parameter(in = ParameterIn.HEADER, description = "Ordered list of languages in which the client prefers to receive SMS or voice verification messages") @HeaderParam(HttpHeaders.ACCEPT_LANGUAGE)
|
||||
@@ -665,8 +661,6 @@ public class VerificationController {
|
||||
}
|
||||
|
||||
accountsManager.getByE164(registrationServiceSession.number())
|
||||
.filter(existingAccount ->
|
||||
experimentEnrollmentManager.isEnrolled(existingAccount.getAccountIdentifier(), VERIFICATION_CODE_PUSH_NOTIFICATION_EXPERIMENT_NAME))
|
||||
.ifPresent(existingAccount -> {
|
||||
try {
|
||||
pushNotificationManager.sendVerificationCodeRequestedNotifications(existingAccount, clock.instant());
|
||||
@@ -711,6 +705,7 @@ public class VerificationController {
|
||||
name = "Retry-After",
|
||||
description = "If present, an positive integer indicating the number of seconds before a subsequent attempt could succeed",
|
||||
schema = @Schema(implementation = Integer.class)))
|
||||
@ManagedAsync
|
||||
public VerificationSessionResponse verifyCode(@PathParam("sessionId") final String encodedSessionId,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
|
||||
@NotNull @Valid final SubmitVerificationCodeRequest submitVerificationCodeRequest) {
|
||||
|
||||
@@ -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) {
|
||||
}
|
||||
+19
-2
@@ -14,10 +14,11 @@ import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.AssertTrue;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.PositiveOrZero;
|
||||
import java.util.List;
|
||||
import java.util.stream.Stream;
|
||||
import javax.annotation.Nullable;
|
||||
import jakarta.validation.constraints.PositiveOrZero;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
|
||||
@@ -60,6 +61,15 @@ public record RegistrationRequest(@Schema(requiredMode = Schema.RequiredMode.NOT
|
||||
@Nullable
|
||||
Integer totp,
|
||||
|
||||
@Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED, description = """
|
||||
A JSON-serialized assertion response from a completed authentication ceremony.
|
||||
See https://www.w3.org/TR/webauthn/#authenticatorassertionresponse.
|
||||
""")
|
||||
@Nullable
|
||||
// There is no documented max size, but 8kiB should be enough
|
||||
@Size(min = 1, max = 8192)
|
||||
String webAuthnResponse,
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
@Schema(requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
@@ -150,6 +160,13 @@ public record RegistrationRequest(@Schema(requiredMode = Schema.RequiredMode.NOT
|
||||
@AssertTrue
|
||||
@Schema(hidden = true)
|
||||
boolean isMfaAbsentWhenUsingReceipt() {
|
||||
return ArrayUtils.isEmpty(receiptCredentialPresentation) || totp == null;
|
||||
return ArrayUtils.isEmpty(receiptCredentialPresentation) || (totp == null && webAuthnResponse == null);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
@AssertTrue
|
||||
@Schema(hidden = true)
|
||||
boolean isAtMostOneMfaPresent() {
|
||||
return totp == null || webAuthnResponse == null;
|
||||
}
|
||||
}
|
||||
-132
@@ -1,132 +0,0 @@
|
||||
package org.whispersystems.textsecuregcm.experiment;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.workers.IdleWakeupEligibilityChecker;
|
||||
import reactor.core.publisher.Flux;
|
||||
import javax.annotation.Nullable;
|
||||
import java.util.Collections;
|
||||
import java.util.EnumMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
abstract class IdleDevicePushNotificationExperiment implements PushNotificationExperiment<DeviceLastSeenState> {
|
||||
|
||||
private final IdleWakeupEligibilityChecker idleWakeupEligibilityChecker;
|
||||
|
||||
private final Logger log = LoggerFactory.getLogger(getClass());
|
||||
|
||||
@VisibleForTesting
|
||||
enum Population {
|
||||
APNS_CONTROL,
|
||||
APNS_EXPERIMENT,
|
||||
FCM_CONTROL,
|
||||
FCM_EXPERIMENT
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
enum Outcome {
|
||||
DELETED,
|
||||
UNINSTALLED,
|
||||
REACTIVATED,
|
||||
UNCHANGED
|
||||
}
|
||||
|
||||
protected IdleDevicePushNotificationExperiment(final IdleWakeupEligibilityChecker idleWakeupEligibilityChecker) {
|
||||
this.idleWakeupEligibilityChecker = idleWakeupEligibilityChecker;
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
boolean hasPushToken(final Device device) {
|
||||
return !StringUtils.isAllBlank(device.getApnId(), device.getGcmId());
|
||||
}
|
||||
|
||||
abstract boolean isIdleDeviceEligible(final Account account, final Device idleDevice, final DeviceLastSeenState state);
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Boolean> isDeviceEligible(final Account account, final Device device) {
|
||||
return idleWakeupEligibilityChecker.isDeviceEligible(account, device).thenApply(idle ->
|
||||
idle && isIdleDeviceEligible(account, device, getState(account, device)));
|
||||
}
|
||||
|
||||
@Override
|
||||
public DeviceLastSeenState getState(@Nullable final Account account, @Nullable final Device device) {
|
||||
if (account != null && device != null) {
|
||||
final DeviceLastSeenState.PushTokenType pushTokenType;
|
||||
if (StringUtils.isNotBlank(device.getApnId())) {
|
||||
pushTokenType = DeviceLastSeenState.PushTokenType.APNS;
|
||||
} else if (StringUtils.isNotBlank(device.getGcmId())) {
|
||||
pushTokenType = DeviceLastSeenState.PushTokenType.FCM;
|
||||
} else {
|
||||
pushTokenType = null;
|
||||
}
|
||||
return new DeviceLastSeenState(true, device.getAccountRegistrationId(), hasPushToken(device), device.getLastSeen(), pushTokenType);
|
||||
} else {
|
||||
return DeviceLastSeenState.MISSING_DEVICE_STATE;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void analyzeResults(final Flux<PushNotificationExperimentSample<DeviceLastSeenState>> samples) {
|
||||
final Map<Population, Map<Outcome, Integer>> contingencyTable = new EnumMap<>(Population.class);
|
||||
|
||||
samples.doOnNext(sample ->
|
||||
contingencyTable.computeIfAbsent(getPopulation(sample), ignored -> new EnumMap<>(Outcome.class))
|
||||
.merge(getOutcome(sample), 1, Integer::sum))
|
||||
.then()
|
||||
.block();
|
||||
|
||||
final StringBuilder reportBuilder = new StringBuilder("population,deleted,uninstalled,reactivated,unchanged\n");
|
||||
|
||||
for (final Population population : Population.values()) {
|
||||
final Map<Outcome, Integer> countsByOutcome = contingencyTable.getOrDefault(population, Collections.emptyMap());
|
||||
|
||||
reportBuilder.append(population.name());
|
||||
reportBuilder.append(",");
|
||||
reportBuilder.append(countsByOutcome.getOrDefault(Outcome.DELETED, 0));
|
||||
reportBuilder.append(",");
|
||||
reportBuilder.append(countsByOutcome.getOrDefault(Outcome.UNINSTALLED, 0));
|
||||
reportBuilder.append(",");
|
||||
reportBuilder.append(countsByOutcome.getOrDefault(Outcome.REACTIVATED, 0));
|
||||
reportBuilder.append(",");
|
||||
reportBuilder.append(countsByOutcome.getOrDefault(Outcome.UNCHANGED, 0));
|
||||
reportBuilder.append("\n");
|
||||
}
|
||||
|
||||
log.info(reportBuilder.toString());
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static Population getPopulation(final PushNotificationExperimentSample<DeviceLastSeenState> sample) {
|
||||
assert sample.initialState() != null && sample.initialState().pushTokenType() != null;
|
||||
|
||||
return switch (sample.initialState().pushTokenType()) {
|
||||
case APNS -> sample.inExperimentGroup() ? Population.APNS_EXPERIMENT : Population.APNS_CONTROL;
|
||||
case FCM -> sample.inExperimentGroup() ? Population.FCM_EXPERIMENT : Population.FCM_CONTROL;
|
||||
};
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static Outcome getOutcome(final PushNotificationExperimentSample<DeviceLastSeenState> sample) {
|
||||
final Outcome outcome;
|
||||
|
||||
assert sample.finalState() != null;
|
||||
|
||||
if (!sample.finalState().deviceExists() || sample.initialState().registrationId() != sample.finalState().registrationId()) {
|
||||
outcome = Outcome.DELETED;
|
||||
} else if (!sample.finalState().hasPushToken()) {
|
||||
outcome = Outcome.UNINSTALLED;
|
||||
} else if (sample.initialState().lastSeenMillis() != sample.finalState().lastSeenMillis()) {
|
||||
outcome = Outcome.REACTIVATED;
|
||||
} else {
|
||||
outcome = Outcome.UNCHANGED;
|
||||
}
|
||||
|
||||
return outcome;
|
||||
}
|
||||
}
|
||||
-85
@@ -1,85 +0,0 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.experiment;
|
||||
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import reactor.core.publisher.Flux;
|
||||
import javax.annotation.Nullable;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
/**
|
||||
* A push notification selects for eligible devices, applies a control or experimental treatment, and provides a
|
||||
* mechanism for comparing device states before and after receiving the treatment.
|
||||
*
|
||||
* @param <T> the type of state object stored for this experiment
|
||||
*/
|
||||
public interface PushNotificationExperiment<T> {
|
||||
|
||||
/**
|
||||
* Returns the unique name of this experiment.
|
||||
*
|
||||
* @return the unique name of this experiment
|
||||
*/
|
||||
String getExperimentName();
|
||||
|
||||
/**
|
||||
* Tests whether a device is eligible for this experiment. An eligible device may be assigned to either the control
|
||||
* or experiment group within an experiment. Ineligible devices will not participate in the experiment in any way.
|
||||
*
|
||||
* @param account the account to which the device belongs
|
||||
* @param device the device to test for eligibility in this experiment
|
||||
*
|
||||
* @return a future that yields a boolean value indicating whether the target device is eligible for this experiment
|
||||
*/
|
||||
CompletableFuture<Boolean> isDeviceEligible(Account account, Device device);
|
||||
|
||||
/**
|
||||
* Returns the class of the state object stored for this experiment.
|
||||
*
|
||||
* @return the class of the state object stored for this experiment
|
||||
*/
|
||||
Class<T> getStateClass();
|
||||
|
||||
/**
|
||||
* Generates an experiment specific state "snapshot" of the given device. Experiment results are generally evaluated
|
||||
* by comparing a device's state before a treatment is applied and its state after the treatment is applied.
|
||||
*
|
||||
* @param account the account to which the device belongs
|
||||
* @param device the device for which to generate a state "snapshot"
|
||||
*
|
||||
* @return an experiment-specific state "snapshot" of the given device
|
||||
*/
|
||||
T getState(@Nullable Account account, @Nullable Device device);
|
||||
|
||||
/**
|
||||
* Applies a control treatment to the given device. In many cases (and by default) no action is taken for devices in
|
||||
* the control group.
|
||||
*
|
||||
* @param account the account to which the device belongs
|
||||
* @param device the device to which to apply the control treatment for this experiment
|
||||
*
|
||||
* @return a future that completes when the control treatment has been applied for the given device
|
||||
*/
|
||||
default CompletableFuture<Void> applyControlTreatment(Account account, Device device) {
|
||||
return CompletableFuture.completedFuture(null);
|
||||
};
|
||||
|
||||
/**
|
||||
* Applies an experimental treatment to the given device. This generally involves sending or scheduling a specific
|
||||
* type of push notification for the given device.
|
||||
*
|
||||
* @param account the account to which the device belongs
|
||||
* @param device the device to which to apply the experimental treatment for this experiment
|
||||
*
|
||||
* @return a future that completes when the experimental treatment has been applied for the given device
|
||||
*/
|
||||
CompletableFuture<Void> applyExperimentTreatment(Account account, Device device);
|
||||
|
||||
/**
|
||||
* Consumes a stream of finished samples and emits an analysis of the results via an implementation-specific channel
|
||||
* (e.g. a log message). Implementations must block until all samples have been consumed and analyzed.
|
||||
*
|
||||
* @param samples a stream of finished samples from this experiment
|
||||
*/
|
||||
void analyzeResults(Flux<PushNotificationExperimentSample<T>> samples);
|
||||
}
|
||||
-11
@@ -1,11 +0,0 @@
|
||||
package org.whispersystems.textsecuregcm.experiment;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
import java.util.UUID;
|
||||
|
||||
public record PushNotificationExperimentSample<T>(UUID accountIdentifier,
|
||||
byte deviceId,
|
||||
boolean inExperimentGroup,
|
||||
T initialState,
|
||||
@Nullable T finalState) {
|
||||
}
|
||||
-279
@@ -1,279 +0,0 @@
|
||||
package org.whispersystems.textsecuregcm.experiment;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.util.function.Tuple2;
|
||||
import reactor.util.function.Tuples;
|
||||
import reactor.util.retry.Retry;
|
||||
import software.amazon.awssdk.core.SdkBytes;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
|
||||
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ConditionalCheckFailedException;
|
||||
import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.PutItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ReturnValue;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ScanRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;
|
||||
|
||||
public class PushNotificationExperimentSamples {
|
||||
|
||||
private final DynamoDbAsyncClient dynamoDbAsyncClient;
|
||||
private final String tableName;
|
||||
private final Clock clock;
|
||||
|
||||
// Experiment name; DynamoDB string; partition key
|
||||
public static final String KEY_EXPERIMENT_NAME = "N";
|
||||
|
||||
// Combined ACI and device ID; DynamoDB byte array; sort key
|
||||
public static final String ATTR_ACI_AND_DEVICE_ID = "AD";
|
||||
|
||||
// Whether the device is enrolled in the experiment group (as opposed to control group); DynamoDB boolean
|
||||
static final String ATTR_IN_EXPERIMENT_GROUP = "X";
|
||||
|
||||
// The experiment-specific state of the device at the start of the experiment, represented as a JSON blob; DynamoDB
|
||||
// string
|
||||
static final String ATTR_INITIAL_STATE = "I";
|
||||
|
||||
// The experiment-specific state of the device at the end of the experiment, represented as a JSON blob; DynamoDB
|
||||
// string
|
||||
static final String ATTR_FINAL_STATE = "F";
|
||||
|
||||
// The time, in seconds since the epoch, at which this sample should be deleted automatically
|
||||
static final String ATTR_TTL = "E";
|
||||
|
||||
private static final Duration FINAL_SAMPLE_TTL = Duration.ofDays(7);
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(PushNotificationExperimentSamples.class);
|
||||
|
||||
public PushNotificationExperimentSamples(final DynamoDbAsyncClient dynamoDbAsyncClient,
|
||||
final String tableName,
|
||||
final Clock clock) {
|
||||
|
||||
this.dynamoDbAsyncClient = dynamoDbAsyncClient;
|
||||
this.tableName = tableName;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes the initial state of a device participating in a push notification experiment.
|
||||
*
|
||||
* @param accountIdentifier the account identifier for the account to which the target device is linked
|
||||
* @param deviceId the identifier for the device within the given account
|
||||
* @param experimentName the name of the experiment
|
||||
* @param inExperimentGroup whether the given device is in the experiment group (as opposed to control group)
|
||||
* @param initialState the initial state of the object; must be serializable as a JSON text
|
||||
*
|
||||
* @return a future that completes when the record has been stored; the future yields {@code true} if a new record
|
||||
* was stored or {@code false} if a conflicting record already exists
|
||||
*
|
||||
* @param <T> the type of state object for this sample
|
||||
*
|
||||
* @throws JsonProcessingException if the given {@code initialState} could not be serialized as a JSON text
|
||||
*/
|
||||
public <T> CompletableFuture<Boolean> recordInitialState(final UUID accountIdentifier,
|
||||
final byte deviceId,
|
||||
final String experimentName,
|
||||
final boolean inExperimentGroup,
|
||||
final T initialState) throws JsonProcessingException {
|
||||
|
||||
final AttributeValue initialStateAttributeValue =
|
||||
AttributeValue.fromS(SystemMapper.jsonMapper().writeValueAsString(initialState));
|
||||
|
||||
final AttributeValue inExperimentGroupAttributeValue = AttributeValue.fromBool(inExperimentGroup);
|
||||
|
||||
return dynamoDbAsyncClient.putItem(PutItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.item(Map.of(
|
||||
KEY_EXPERIMENT_NAME, AttributeValue.fromS(experimentName),
|
||||
ATTR_ACI_AND_DEVICE_ID, buildSortKey(accountIdentifier, deviceId),
|
||||
ATTR_IN_EXPERIMENT_GROUP, inExperimentGroupAttributeValue,
|
||||
ATTR_INITIAL_STATE, initialStateAttributeValue,
|
||||
ATTR_TTL, AttributeValue.fromN(String.valueOf(clock.instant().plus(FINAL_SAMPLE_TTL).getEpochSecond()))))
|
||||
.conditionExpression("(attribute_not_exists(#inExperimentGroup) OR #inExperimentGroup = :inExperimentGroup) AND (attribute_not_exists(#initialState) OR #initialState = :initialState) AND attribute_not_exists(#finalState)")
|
||||
.expressionAttributeNames(Map.of(
|
||||
"#inExperimentGroup", ATTR_IN_EXPERIMENT_GROUP,
|
||||
"#initialState", ATTR_INITIAL_STATE,
|
||||
"#finalState", ATTR_FINAL_STATE))
|
||||
.expressionAttributeValues(Map.of(
|
||||
":inExperimentGroup", inExperimentGroupAttributeValue,
|
||||
":initialState", initialStateAttributeValue))
|
||||
.build())
|
||||
.thenApply(ignored -> true)
|
||||
.exceptionally(throwable -> {
|
||||
if (ExceptionUtils.unwrap(throwable) instanceof ConditionalCheckFailedException) {
|
||||
return false;
|
||||
}
|
||||
|
||||
throw ExceptionUtils.wrap(throwable);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes the final state of a device participating in a push notification experiment.
|
||||
*
|
||||
* @param accountIdentifier the account identifier for the account to which the target device is linked
|
||||
* @param deviceId the identifier for the device within the given account
|
||||
* @param experimentName the name of the experiment
|
||||
* @param finalState the final state of the object; must be serializable as a JSON text and of the same type as the
|
||||
* previously-stored initial state
|
||||
|
||||
* @return A future that completes when the final state has been stored; yields a finished sample if an initial sample
|
||||
* was found or empty if no initial sample was found for the given account, device, and experiment. The future may
|
||||
* with a {@link JsonProcessingException} if the initial state could not be read or the final state could not be
|
||||
* written as a JSON text.
|
||||
*
|
||||
* @param <T> the type of state object for this sample
|
||||
*/
|
||||
public <T> CompletableFuture<PushNotificationExperimentSample<T>> recordFinalState(final UUID accountIdentifier,
|
||||
final byte deviceId,
|
||||
final String experimentName,
|
||||
final T finalState) {
|
||||
|
||||
CompletableFuture<String> finalStateJsonFuture;
|
||||
|
||||
// Process the final state JSON on the calling thread, but inside a CompletionStage so there's just one "channel"
|
||||
// for reporting JSON exceptions. The alternative is to `throw JsonProcessingException`, but then callers would have
|
||||
// to both catch the exception when calling this method and also watch the returned future for the same exception.
|
||||
try {
|
||||
finalStateJsonFuture =
|
||||
CompletableFuture.completedFuture(SystemMapper.jsonMapper().writeValueAsString(finalState));
|
||||
} catch (final JsonProcessingException e) {
|
||||
finalStateJsonFuture = CompletableFuture.failedFuture(e);
|
||||
}
|
||||
|
||||
final AttributeValue aciAndDeviceIdAttributeValue = buildSortKey(accountIdentifier, deviceId);
|
||||
|
||||
return finalStateJsonFuture.thenCompose(finalStateJson -> {
|
||||
return dynamoDbAsyncClient.updateItem(UpdateItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.key(Map.of(
|
||||
KEY_EXPERIMENT_NAME, AttributeValue.fromS(experimentName),
|
||||
ATTR_ACI_AND_DEVICE_ID, aciAndDeviceIdAttributeValue))
|
||||
// `UpdateItem` will, by default, create a new item if one does not already exist for the given primary key. We
|
||||
// want update-only-if-exists behavior, though, and so check that there's already an existing item for this ACI
|
||||
// and device ID.
|
||||
.conditionExpression("#aciAndDeviceId = :aciAndDeviceId")
|
||||
.updateExpression("SET #finalState = if_not_exists(#finalState, :finalState)")
|
||||
.expressionAttributeNames(Map.of(
|
||||
"#aciAndDeviceId", ATTR_ACI_AND_DEVICE_ID,
|
||||
"#finalState", ATTR_FINAL_STATE))
|
||||
.expressionAttributeValues(Map.of(
|
||||
":aciAndDeviceId", aciAndDeviceIdAttributeValue,
|
||||
":finalState", AttributeValue.fromS(finalStateJson)))
|
||||
.returnValues(ReturnValue.ALL_NEW)
|
||||
.build())
|
||||
.thenApply(updateItemResponse -> {
|
||||
try {
|
||||
final boolean inExperimentGroup = updateItemResponse.attributes().get(ATTR_IN_EXPERIMENT_GROUP).bool();
|
||||
|
||||
@SuppressWarnings("unchecked") final T parsedInitialState =
|
||||
(T) parseState(updateItemResponse.attributes().get(ATTR_INITIAL_STATE).s(), finalState.getClass());
|
||||
|
||||
@SuppressWarnings("unchecked") final T parsedFinalState =
|
||||
(T) parseState(updateItemResponse.attributes().get(ATTR_FINAL_STATE).s(), finalState.getClass());
|
||||
|
||||
return new PushNotificationExperimentSample<>(accountIdentifier, deviceId, inExperimentGroup, parsedInitialState, parsedFinalState);
|
||||
} catch (final JsonProcessingException e) {
|
||||
throw ExceptionUtils.wrap(e);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a publisher across all samples for a given experiment.
|
||||
*
|
||||
* @param experimentName the name of the experiment for which to fetch samples
|
||||
* @param stateClass the type of state object for sample in the given experiment
|
||||
*
|
||||
* @return a publisher of tuples of ACI, device ID, and sample for all samples associated with the given experiment
|
||||
*
|
||||
* @param <T> the type of the sample's state objects
|
||||
*
|
||||
* @see <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Scan.html#Scan.ParallelScan">Working with scans - Parallel scan</a>
|
||||
*/
|
||||
public <T> Flux<PushNotificationExperimentSample<T>> getSamples(final String experimentName, final Class<T> stateClass) {
|
||||
|
||||
return Flux.from(dynamoDbAsyncClient.queryPaginator(QueryRequest.builder()
|
||||
.tableName(tableName)
|
||||
.keyConditionExpression("#experiment = :experiment")
|
||||
.expressionAttributeNames(Map.of("#experiment", KEY_EXPERIMENT_NAME))
|
||||
.expressionAttributeValues(Map.of(":experiment", AttributeValue.fromS(experimentName)))
|
||||
.build())
|
||||
.items())
|
||||
.handle((item, sink) -> {
|
||||
try {
|
||||
final Tuple2<UUID, Byte> aciAndDeviceId = parseSortKey(item.get(ATTR_ACI_AND_DEVICE_ID));
|
||||
|
||||
final boolean inExperimentGroup = item.get(ATTR_IN_EXPERIMENT_GROUP).bool();
|
||||
final T initialState = parseState(item.get(ATTR_INITIAL_STATE).s(), stateClass);
|
||||
final T finalState = item.get(ATTR_FINAL_STATE) != null
|
||||
? parseState(item.get(ATTR_FINAL_STATE).s(), stateClass)
|
||||
: null;
|
||||
|
||||
sink.next(new PushNotificationExperimentSample<>(aciAndDeviceId.getT1(), aciAndDeviceId.getT2(), inExperimentGroup, initialState, finalState));
|
||||
} catch (final JsonProcessingException e) {
|
||||
sink.error(e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> discardSamples(final String experimentName, final int maxConcurrency) {
|
||||
final AttributeValue experimentNameAttributeValue = AttributeValue.fromS(experimentName);
|
||||
|
||||
return Flux.from(dynamoDbAsyncClient.scanPaginator(ScanRequest.builder()
|
||||
.tableName(tableName)
|
||||
.filterExpression("#experiment = :experiment")
|
||||
.expressionAttributeNames(Map.of("#experiment", KEY_EXPERIMENT_NAME))
|
||||
.expressionAttributeValues(Map.of(":experiment", experimentNameAttributeValue))
|
||||
.projectionExpression(ATTR_ACI_AND_DEVICE_ID)
|
||||
.build())
|
||||
.items())
|
||||
.map(item -> item.get(ATTR_ACI_AND_DEVICE_ID))
|
||||
.flatMap(aciAndDeviceId -> Mono.fromFuture(() -> dynamoDbAsyncClient.deleteItem(DeleteItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.key(Map.of(
|
||||
KEY_EXPERIMENT_NAME, experimentNameAttributeValue,
|
||||
ATTR_ACI_AND_DEVICE_ID, aciAndDeviceId))
|
||||
.build()))
|
||||
.retryWhen(Retry.backoff(5, Duration.ofSeconds(5)))
|
||||
.onErrorResume(throwable -> {
|
||||
log.warn("Failed to delete sample for experiment {}", experimentName, throwable);
|
||||
return Mono.empty();
|
||||
}), maxConcurrency)
|
||||
.then()
|
||||
.toFuture();
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static AttributeValue buildSortKey(final UUID accountIdentifier, final byte deviceId) {
|
||||
return AttributeValue.fromB(SdkBytes.fromByteBuffer(ByteBuffer.allocate(17)
|
||||
.putLong(accountIdentifier.getMostSignificantBits())
|
||||
.putLong(accountIdentifier.getLeastSignificantBits())
|
||||
.put(deviceId)
|
||||
.flip()));
|
||||
}
|
||||
|
||||
private static Tuple2<UUID, Byte> parseSortKey(final AttributeValue sortKey) {
|
||||
final ByteBuffer byteBuffer = sortKey.b().asByteBuffer();
|
||||
|
||||
return Tuples.of(new UUID(byteBuffer.getLong(), byteBuffer.getLong()), byteBuffer.get());
|
||||
}
|
||||
|
||||
private static <T> T parseState(final String state, final Class<T> clazz) throws JsonProcessingException {
|
||||
return SystemMapper.jsonMapper().readValue(state, clazz);
|
||||
}
|
||||
}
|
||||
+7
-2
@@ -7,6 +7,7 @@ package org.whispersystems.textsecuregcm.filters;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.google.common.net.InetAddresses;
|
||||
import io.grpc.Metadata;
|
||||
import io.grpc.MethodDescriptor;
|
||||
import io.grpc.ServerCall;
|
||||
@@ -73,8 +74,12 @@ public class ExternalRequestFilter implements Filter, ServerInterceptor {
|
||||
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
|
||||
throws IOException, ServletException {
|
||||
|
||||
final InetAddress remoteInetAddress = InetAddress.getByName(
|
||||
(String) request.getAttribute(RemoteAddressFilter.REMOTE_ADDRESS_ATTRIBUTE_NAME));
|
||||
final String remoteAddressString = (String) request.getAttribute(RemoteAddressFilter.REMOTE_ADDRESS_ATTRIBUTE_NAME);
|
||||
|
||||
final InetAddress remoteInetAddress = remoteAddressString != null
|
||||
? InetAddresses.forString(remoteAddressString)
|
||||
: InetAddress.getLoopbackAddress();
|
||||
|
||||
final boolean restricted = shouldBlock(remoteInetAddress);
|
||||
|
||||
Metrics.counter(REQUESTS_COUNTER_NAME,
|
||||
|
||||
+4
@@ -59,6 +59,10 @@ public class RequestStatisticsFilter implements ContainerRequestFilter {
|
||||
private static String resolveIpVersion(@Nonnull final ContainerRequestContext ctx) {
|
||||
final String ipString = (String) ctx.getProperty(RemoteAddressFilter.REMOTE_ADDRESS_ATTRIBUTE_NAME);
|
||||
|
||||
if (ipString == null) {
|
||||
return "unresolved";
|
||||
}
|
||||
|
||||
try {
|
||||
final InetAddress addr = InetAddresses.forString(ipString);
|
||||
if (addr instanceof Inet4Address) {
|
||||
|
||||
+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
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+120
-6
@@ -23,6 +23,7 @@ import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
import javax.annotation.Nullable;
|
||||
import org.signal.chat.account.Capabilities;
|
||||
import org.signal.chat.account.ChangeNumberRequest;
|
||||
import org.signal.chat.account.ChangeNumberResponse;
|
||||
@@ -41,6 +42,10 @@ import org.signal.chat.account.DeleteUsernameHashResponse;
|
||||
import org.signal.chat.account.DeleteUsernameLinkRequest;
|
||||
import org.signal.chat.account.DeleteUsernameLinkResponse;
|
||||
import org.signal.chat.account.ExternalServiceCredentials;
|
||||
import org.signal.chat.account.FinishMfaVerificationRequest;
|
||||
import org.signal.chat.account.FinishMfaVerificationResponse;
|
||||
import org.signal.chat.account.FinishWebAuthnRegistrationRequest;
|
||||
import org.signal.chat.account.FinishWebAuthnRegistrationResponse;
|
||||
import org.signal.chat.account.GenerateTotpKeyRequest;
|
||||
import org.signal.chat.account.GenerateTotpKeyResponse;
|
||||
import org.signal.chat.account.GetAccountDataReportRequest;
|
||||
@@ -54,6 +59,7 @@ import org.signal.chat.account.GetEntitlementsResponse;
|
||||
import org.signal.chat.account.ListMfaKeysRequest;
|
||||
import org.signal.chat.account.ListMfaKeysResponse;
|
||||
import org.signal.chat.account.ListMfaKeysResponse.MfaKeyMetadata.MfaKeyType;
|
||||
import org.signal.chat.account.StartMfaVerificationResponse.WebAuthnAuthenticationParameters;
|
||||
import org.signal.chat.account.RegistrationLockFailure;
|
||||
import org.signal.chat.account.RemoveMfaKeyRequest;
|
||||
import org.signal.chat.account.RemoveMfaKeyResponse;
|
||||
@@ -61,18 +67,23 @@ import org.signal.chat.account.ReserveUsernameHashRequest;
|
||||
import org.signal.chat.account.ReserveUsernameHashResponse;
|
||||
import org.signal.chat.account.SetDiscoverableByPhoneNumberRequest;
|
||||
import org.signal.chat.account.SetDiscoverableByPhoneNumberResponse;
|
||||
import org.signal.chat.account.SetMfaKeyMetadataRequest;
|
||||
import org.signal.chat.account.SetMfaKeyMetadataResponse;
|
||||
import org.signal.chat.account.SetRegistrationLockRequest;
|
||||
import org.signal.chat.account.SetRegistrationLockResponse;
|
||||
import org.signal.chat.account.SetRegistrationRecoveryPasswordRequest;
|
||||
import org.signal.chat.account.SetRegistrationRecoveryPasswordResponse;
|
||||
import org.signal.chat.account.SetMfaKeyMetadataRequest;
|
||||
import org.signal.chat.account.SetMfaKeyMetadataResponse;
|
||||
import org.signal.chat.account.SetUsernameLinkRequest;
|
||||
import org.signal.chat.account.SetUsernameLinkResponse;
|
||||
import org.signal.chat.account.SetZkCredentialKeyRequest;
|
||||
import org.signal.chat.account.SetZkCredentialKeyResponse;
|
||||
import org.signal.chat.account.SimpleAccountsGrpc;
|
||||
import org.signal.chat.account.StaleDevices;
|
||||
import org.signal.chat.account.StartMfaVerificationRequest;
|
||||
import org.signal.chat.account.StartMfaVerificationResponse;
|
||||
import org.signal.chat.account.StartWebAuthnRegistrationRequest;
|
||||
import org.signal.chat.account.StartWebAuthnRegistrationResponse;
|
||||
import org.signal.chat.account.StartWebAuthnRegistrationResponse.WebAuthnCreateParameters;
|
||||
import org.signal.chat.account.TotpParameters;
|
||||
import org.signal.chat.account.UsernameNotAvailable;
|
||||
import org.signal.chat.common.AccountIdentifiers;
|
||||
@@ -91,6 +102,8 @@ import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
|
||||
import org.whispersystems.textsecuregcm.auth.UnverifiedRegistrationSessionException;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
|
||||
import org.whispersystems.textsecuregcm.auth.webauthn.AuthenticationCeremonyParameters;
|
||||
import org.whispersystems.textsecuregcm.auth.webauthn.RegistrationCeremonyParameters;
|
||||
import org.whispersystems.textsecuregcm.controllers.MessageDeliveryNotAllowedException;
|
||||
import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
@@ -107,6 +120,7 @@ import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.AnnotatedMfaKey;
|
||||
import org.whispersystems.textsecuregcm.storage.AnnotatedTotpKey;
|
||||
import org.whispersystems.textsecuregcm.storage.AnnotatedWebAuthnCredential;
|
||||
import org.whispersystems.textsecuregcm.storage.ChangeNumberManager;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
|
||||
import org.whispersystems.textsecuregcm.storage.PhoneNumberRecoveryPasswordsManager;
|
||||
@@ -121,7 +135,6 @@ import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import org.whispersystems.textsecuregcm.util.UsernameHashZkProofVerifier;
|
||||
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem;
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
|
||||
|
||||
@@ -250,7 +263,7 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
|
||||
|
||||
try {
|
||||
usernameHashZkProofVerifier.verifyProof(request.getZkProof().toByteArray(), request.getUsernameHash().toByteArray());
|
||||
} catch (final BaseUsernameException e) {
|
||||
} catch (final BaseUsernameException | InvalidInputException e) {
|
||||
throw GrpcExceptions.invalidArguments("Could not verify proof");
|
||||
}
|
||||
|
||||
@@ -562,6 +575,11 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
|
||||
@Override
|
||||
public GenerateTotpKeyResponse generateTotpKey(final GenerateTotpKeyRequest request) {
|
||||
try {
|
||||
final Account account = getAuthenticatedAccount();
|
||||
if (account.getNumber().isPresent()) {
|
||||
throw GrpcExceptions.invalidArguments("TOTP keys may not be generated for an account with a number");
|
||||
}
|
||||
|
||||
final TotpKey pendingTotpKey =
|
||||
accountsManager.generatePendingTotpKey(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier());
|
||||
|
||||
@@ -585,6 +603,11 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
|
||||
@Override
|
||||
public ConfirmTotpKeyResponse confirmTotpKey(final ConfirmTotpKeyRequest request) {
|
||||
try {
|
||||
final Account account = getAuthenticatedAccount();
|
||||
if (account.getNumber().isPresent()) {
|
||||
throw GrpcExceptions.invalidArguments("TOTP keys may not be added to an account with a number");
|
||||
}
|
||||
|
||||
final Optional<Byte> maybeConfirmedTotpKeyId =
|
||||
accountsManager.confirmPendingTotpKey(
|
||||
AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier(),
|
||||
@@ -606,6 +629,58 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public StartWebAuthnRegistrationResponse startWebAuthnRegistration(final StartWebAuthnRegistrationRequest request) {
|
||||
|
||||
final Account account = getAuthenticatedAccount();
|
||||
if (account.getNumber().isPresent()) {
|
||||
throw GrpcExceptions.invalidArguments("WebAuthn keys may not be set for an account with a number");
|
||||
}
|
||||
|
||||
try {
|
||||
final RegistrationCeremonyParameters registrationParameters =
|
||||
accountsManager.startWebAuthnRegistration(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier());
|
||||
|
||||
return StartWebAuthnRegistrationResponse.newBuilder()
|
||||
.setParams(WebAuthnCreateParameters.newBuilder()
|
||||
.setUserHandle(ByteString.copyFrom(registrationParameters.userHandle()))
|
||||
.addAllAllowedAlgorithms(registrationParameters.allowedAlgorithms())
|
||||
.addAllExcludeCredentialIds(
|
||||
registrationParameters.excludedCredentialIds().stream().map(ByteString::copyFrom).toList()))
|
||||
.build();
|
||||
} catch (TooManyMfaKeysException _) {
|
||||
return StartWebAuthnRegistrationResponse.newBuilder()
|
||||
.setTooManyMfaKeys(FailedPrecondition.getDefaultInstance())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public FinishWebAuthnRegistrationResponse finishWebAuthnRegistration(final FinishWebAuthnRegistrationRequest request) {
|
||||
final Account account = getAuthenticatedAccount();
|
||||
if (account.getNumber().isPresent()) {
|
||||
throw GrpcExceptions.invalidArguments("WebAuthn keys may not be set for an account with a number");
|
||||
}
|
||||
|
||||
try {
|
||||
final Optional<Byte> maybeKeyId = accountsManager.finishWebAuthnRegistration(
|
||||
AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier(),
|
||||
request.getAttestationObject().toByteArray(),
|
||||
request.getCollectedClientDataJson(),
|
||||
request.getMetadataCiphertext().toByteArray());
|
||||
|
||||
return maybeKeyId.map(
|
||||
keyId -> FinishWebAuthnRegistrationResponse.newBuilder()
|
||||
.setKeyConfirmed(FinishWebAuthnRegistrationResponse.KeyConfirmed.newBuilder().setKeyId(keyId)))
|
||||
.orElseGet(() -> FinishWebAuthnRegistrationResponse.newBuilder().setKeyNotConfirmed(FailedPrecondition.getDefaultInstance()))
|
||||
.build();
|
||||
} catch (TooManyMfaKeysException _) {
|
||||
return FinishWebAuthnRegistrationResponse.newBuilder()
|
||||
.setTooManyMfaKeys(FailedPrecondition.getDefaultInstance())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public ListMfaKeysResponse listMfaKeys(final ListMfaKeysRequest request) {
|
||||
final ListMfaKeysResponse.Builder responseBuilder = ListMfaKeysResponse.newBuilder();
|
||||
@@ -618,7 +693,8 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
|
||||
ListMfaKeysResponse.MfaKeyMetadata.newBuilder()
|
||||
.setMetadataCiphertext(ByteString.copyFrom(mfaKey.metadataCiphertext()))
|
||||
.setType(switch (mfaKey) {
|
||||
case AnnotatedTotpKey _ -> MfaKeyType.MFA_KEY_TYPE_TOTP;
|
||||
case AnnotatedTotpKey _ -> MfaKeyType.MFA_KEY_TYPE_TOTP;
|
||||
case AnnotatedWebAuthnCredential _ -> MfaKeyType.MFA_KEY_TYPE_WEBAUTHN;
|
||||
}).build());
|
||||
});
|
||||
|
||||
@@ -644,7 +720,7 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
|
||||
});
|
||||
|
||||
return SetMfaKeyMetadataResponse.newBuilder()
|
||||
.setMetadataUpdated(SetMfaKeyMetadataResponse.MetadataUpdated.getDefaultInstance())
|
||||
.setSuccess(SetMfaKeyMetadataResponse.MetadataUpdated.getDefaultInstance())
|
||||
.build();
|
||||
} catch (final MfaKeyNotFoundException _) {
|
||||
return SetMfaKeyMetadataResponse.newBuilder()
|
||||
@@ -667,6 +743,36 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
|
||||
return RemoveMfaKeyResponse.getDefaultInstance();
|
||||
}
|
||||
|
||||
@Override
|
||||
public StartMfaVerificationResponse startMfaVerification(final StartMfaVerificationRequest request) {
|
||||
final Account account = getAuthenticatedAccount();
|
||||
|
||||
final StartMfaVerificationResponse.Builder builder = StartMfaVerificationResponse.newBuilder()
|
||||
.setHasTotp(account.getMfaKeys().values().stream().anyMatch(AnnotatedTotpKey.class::isInstance));
|
||||
|
||||
accountsManager.startWebAuthnAuthentication(account)
|
||||
.map(AccountsGrpcService::toGrpcWebAuthnAuthenticationParameters)
|
||||
.ifPresent(builder::setWebauthnAuthenticationParameters);
|
||||
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public FinishMfaVerificationResponse finishMfaVerification(final FinishMfaVerificationRequest request) throws RateLimitExceededException {
|
||||
rateLimiters.getCheckMfaLimiter().validate(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier());
|
||||
|
||||
final Account account = getAuthenticatedAccount();
|
||||
|
||||
final boolean success = switch (request.getCredentialCase()) {
|
||||
case TOTP_PASSWORD -> accountsManager.verifyTotp(account, clock.instant(), request.getTotpPassword());
|
||||
case WEBAUTHN_AUTHENTICATION_RESPONSE_JSON ->
|
||||
accountsManager.verifyWebAuthnAuthentication(account, request.getWebauthnAuthenticationResponseJson()).isPresent();
|
||||
case CREDENTIAL_NOT_SET -> false;
|
||||
};
|
||||
|
||||
return FinishMfaVerificationResponse.newBuilder().setSuccess(success).build();
|
||||
}
|
||||
|
||||
private byte validateMfaKeyId(final int keyId) {
|
||||
if (keyId < 0 || keyId > Account.MAX_MFA_KEY_ID) {
|
||||
throw GrpcExceptions.invalidArguments("MFA key ID out of range");
|
||||
@@ -683,6 +789,14 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
|
||||
.build();
|
||||
}
|
||||
|
||||
private static WebAuthnAuthenticationParameters toGrpcWebAuthnAuthenticationParameters(final AuthenticationCeremonyParameters parameters) {
|
||||
return WebAuthnAuthenticationParameters.newBuilder()
|
||||
.setChallenge(ByteString.copyFrom(parameters.challenge()))
|
||||
.setTimeoutSeconds((int) parameters.timeout().toSeconds())
|
||||
.addAllAllowedCredentialIds(parameters.allowedCredentialIds().stream().map(ByteString::copyFrom).toList())
|
||||
.build();
|
||||
}
|
||||
|
||||
private static AccountIdentifiers buildAccountIdentifiers(final Account account) {
|
||||
final AccountIdentifiers.Builder accountIdentifiersBuilder = AccountIdentifiers.newBuilder()
|
||||
.addServiceIdentifiers(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(new AciServiceIdentifier(account.getAccountIdentifier())));
|
||||
|
||||
+13
-2
@@ -16,6 +16,7 @@ import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
import org.signal.chat.backup.GetBackupAuthCredentialsRequest;
|
||||
import org.signal.chat.backup.GetBackupAuthCredentialsResponse;
|
||||
import org.signal.chat.backup.GetBackupIdLimitsResponse;
|
||||
import org.signal.chat.backup.RedeemReceiptRequest;
|
||||
import org.signal.chat.backup.RedeemReceiptResponse;
|
||||
import org.signal.chat.backup.SetBackupIdRequest;
|
||||
@@ -72,7 +73,7 @@ public class BackupsGrpcService extends SimpleBackupsGrpc.BackupsImplBase {
|
||||
final Account account = authenticatedAccount();
|
||||
final Device device = account
|
||||
.getDevice(authenticatedDevice.deviceId())
|
||||
.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException);
|
||||
.orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials"));
|
||||
backupAuthManager.commitBackupId(account, device, messagesCredentialRequest, mediaCredentialRequest);
|
||||
return SetBackupIdResponse.getDefaultInstance();
|
||||
}
|
||||
@@ -138,6 +139,16 @@ public class BackupsGrpcService extends SimpleBackupsGrpc.BackupsImplBase {
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public GetBackupIdLimitsResponse getBackupIdLimits(final Empty request) {
|
||||
final Account account = authenticatedAccount();
|
||||
final BackupAuthManager.BackupIdRotationLimit limit = backupAuthManager.checkBackupIdRotationLimit(account);
|
||||
return GetBackupIdLimitsResponse.newBuilder()
|
||||
.setHasPermitsRemaining(limit.hasPermitsRemaining())
|
||||
.setRetryAfterSeconds(limit.nextPermitAvailable().getSeconds())
|
||||
.build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Throwable mapException(final Throwable throwable) {
|
||||
return switch (throwable) {
|
||||
@@ -151,7 +162,7 @@ public class BackupsGrpcService extends SimpleBackupsGrpc.BackupsImplBase {
|
||||
private Account authenticatedAccount() {
|
||||
return accountManager
|
||||
.getByAccountIdentifier(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier())
|
||||
.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException);
|
||||
.orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials"));
|
||||
}
|
||||
|
||||
private interface Deserializer<T> {
|
||||
|
||||
+45
-11
@@ -1,14 +1,18 @@
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import java.io.IOException;
|
||||
import com.google.protobuf.Empty;
|
||||
import org.signal.chat.challenge.AnswerChallengeRequest;
|
||||
import org.signal.chat.challenge.AnswerChallengeResponse;
|
||||
import org.signal.chat.challenge.RequestPushChallengeRequest;
|
||||
import org.signal.chat.challenge.RequestPushChallengeResponse;
|
||||
import org.signal.chat.challenge.SimpleChallengeGrpc;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
|
||||
import org.signal.chat.errors.FailedPrecondition;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
|
||||
import org.whispersystems.textsecuregcm.captcha.InvalidCaptchaArgumentException;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimitChallengeManager;
|
||||
import org.whispersystems.textsecuregcm.push.NotPushRegisteredException;
|
||||
import org.whispersystems.textsecuregcm.spam.ChallengeConstraintChecker;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
@@ -28,19 +32,21 @@ public class ChallengeGrpcService extends SimpleChallengeGrpc.ChallengeImplBase
|
||||
}
|
||||
|
||||
@Override
|
||||
public AnswerChallengeResponse handleChallengeResponse(final AnswerChallengeRequest request)
|
||||
public AnswerChallengeResponse answerChallenge(final AnswerChallengeRequest request)
|
||||
throws RateLimitExceededException, IOException {
|
||||
|
||||
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
|
||||
final Account account = accountsManager.getByAccountIdentifier(authenticatedDevice.accountIdentifier())
|
||||
.orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials"));
|
||||
|
||||
final ChallengeConstraintChecker.ChallengeConstraints constraints = challengeConstraintChecker.challengeConstraintsGrpc(
|
||||
account);
|
||||
final Account account = requireAuthenticatedAccount();
|
||||
final ChallengeConstraintChecker.ChallengeConstraints constraints =
|
||||
challengeConstraintChecker.challengeConstraintsGrpc(account);
|
||||
|
||||
final boolean success = switch (request.getRequestCase()) {
|
||||
case PUSH -> constraints.pushPermitted() && rateLimitChallengeManager.answerPushChallenge(account,
|
||||
request.getPush().getChallenge());
|
||||
case PUSH -> {
|
||||
if (!constraints.pushPermitted()) {
|
||||
throw GrpcExceptions.rateLimitExceeded(null);
|
||||
}
|
||||
|
||||
yield rateLimitChallengeManager.answerPushChallenge(account, request.getPush().getChallenge());
|
||||
}
|
||||
case CAPTCHA -> {
|
||||
try {
|
||||
yield rateLimitChallengeManager.answerCaptchaChallenge(
|
||||
@@ -49,7 +55,7 @@ public class ChallengeGrpcService extends SimpleChallengeGrpc.ChallengeImplBase
|
||||
RequestAttributesUtil.getRemoteAddress().getHostAddress(),
|
||||
RequestAttributesUtil.getUserAgent().orElse(null),
|
||||
constraints.captchaScoreThreshold());
|
||||
} catch (InvalidCaptchaArgumentException e) {
|
||||
} catch (final InvalidCaptchaArgumentException e) {
|
||||
throw GrpcExceptions.invalidArguments(e.getMessage());
|
||||
}
|
||||
}
|
||||
@@ -60,4 +66,32 @@ public class ChallengeGrpcService extends SimpleChallengeGrpc.ChallengeImplBase
|
||||
.setSuccess(success)
|
||||
.build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public RequestPushChallengeResponse requestPushChallenge(final RequestPushChallengeRequest request) {
|
||||
final Account account = requireAuthenticatedAccount();
|
||||
final ChallengeConstraintChecker.ChallengeConstraints constraints =
|
||||
challengeConstraintChecker.challengeConstraintsGrpc(account);
|
||||
|
||||
if (!constraints.pushPermitted()) {
|
||||
throw GrpcExceptions.rateLimitExceeded(null);
|
||||
}
|
||||
|
||||
try {
|
||||
rateLimitChallengeManager.sendPushChallenge(account);
|
||||
} catch (NotPushRegisteredException _) {
|
||||
return RequestPushChallengeResponse.newBuilder()
|
||||
.setNoPushToken(FailedPrecondition.getDefaultInstance())
|
||||
.build();
|
||||
}
|
||||
|
||||
return RequestPushChallengeResponse.newBuilder()
|
||||
.setSentPushChallenge(Empty.getDefaultInstance())
|
||||
.build();
|
||||
}
|
||||
|
||||
private Account requireAuthenticatedAccount() {
|
||||
return accountsManager.getByAccountIdentifier(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier())
|
||||
.orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials"));
|
||||
}
|
||||
}
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.grpc.ForwardingServerCallListener;
|
||||
import io.grpc.Metadata;
|
||||
import io.grpc.ServerCall;
|
||||
import io.grpc.ServerCallHandler;
|
||||
import io.grpc.ServerInterceptor;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
|
||||
/// Limits the number of concurrent gRPC calls. Returns `io.grpc.Status.UNAVAILABLE` if the limit is exceeded. This
|
||||
/// interceptor is meant to be used alongside a virtual thread executor. Unfortunately, we can't re-use
|
||||
/// [org.whispersystems.textsecuregcm.util.BoundedVirtualThreadFactory] directly because the gRPC stack does not
|
||||
/// gracefully handle [java.util.concurrent.RejectedExecutionException]s (see
|
||||
/// [issue](https://github.com/grpc/grpc-java/issues/636))
|
||||
public class ConcurrentCallLimitingInterceptor implements ServerInterceptor {
|
||||
|
||||
private final int maxConcurrentCalls;
|
||||
|
||||
private final AtomicInteger concurrentCalls = new AtomicInteger(0);
|
||||
private final Counter rejectedCallCounter;
|
||||
|
||||
public ConcurrentCallLimitingInterceptor(final int maxConcurrentCalls) {
|
||||
this.maxConcurrentCalls = maxConcurrentCalls;
|
||||
|
||||
Metrics.gauge(MetricsUtil.name(ConcurrentCallLimitingInterceptor.class, "active"),
|
||||
concurrentCalls, AtomicInteger::doubleValue);
|
||||
this.rejectedCallCounter =
|
||||
Metrics.counter(MetricsUtil.name(ConcurrentCallLimitingInterceptor.class, "rejected"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(final ServerCall<ReqT, RespT> call,
|
||||
final Metadata headers, final ServerCallHandler<ReqT, RespT> next) {
|
||||
|
||||
if (concurrentCalls.incrementAndGet() > maxConcurrentCalls) {
|
||||
concurrentCalls.decrementAndGet();
|
||||
rejectedCallCounter.increment();
|
||||
return ServerInterceptorUtil.closeWithStatusException(call, GrpcExceptions.unavailable());
|
||||
}
|
||||
|
||||
try {
|
||||
return new ForwardingServerCallListener.SimpleForwardingServerCallListener<>(next.startCall(call, headers)) {
|
||||
@Override
|
||||
public void onComplete() {
|
||||
concurrentCalls.decrementAndGet();
|
||||
super.onComplete();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCancel() {
|
||||
concurrentCalls.decrementAndGet();
|
||||
super.onCancel();
|
||||
}
|
||||
};
|
||||
} catch (final Exception e) {
|
||||
concurrentCalls.decrementAndGet();
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
int getActiveCalls() {
|
||||
return concurrentCalls.get();
|
||||
}
|
||||
}
|
||||
+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),
|
||||
|
||||
+9
-9
@@ -12,9 +12,10 @@ import java.time.temporal.ChronoUnit;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import org.signal.chat.common.ZkCredential;
|
||||
import org.signal.chat.credentials.ExternalServiceType;
|
||||
import org.signal.chat.credentials.GetCreateCallLinkCredentialsRequest;
|
||||
import org.signal.chat.credentials.GetCreateCallLinkCredentialsResponse;
|
||||
import org.signal.chat.credentials.GetCreateCallLinkCredentialRequest;
|
||||
import org.signal.chat.credentials.GetCreateCallLinkCredentialResponse;
|
||||
import org.signal.chat.credentials.GetDeliveryCertificateRequest;
|
||||
import org.signal.chat.credentials.GetDeliveryCertificateResponse;
|
||||
import org.signal.chat.credentials.GetExternalServiceCredentialsRequest;
|
||||
@@ -138,14 +139,14 @@ public class CredentialsGrpcService extends SimpleCredentialsGrpc.CredentialsImp
|
||||
.orElseThrow(
|
||||
() -> new IllegalStateException("account without PNI must have auth credential salt")),
|
||||
redemption));
|
||||
responseBuilder.addGroupCredentials(GetGroupCredentialsResponse.CredentialAndRedemptionTime.newBuilder()
|
||||
.setRedemptionTimeSeconds(redemption.getEpochSecond())
|
||||
responseBuilder.addGroupCredentials(ZkCredential.newBuilder()
|
||||
.setRedemptionTime(redemption.getEpochSecond())
|
||||
.setCredential(ByteString.copyFrom(
|
||||
authCredentialWithPniResponse.serialize()))
|
||||
.build());
|
||||
|
||||
responseBuilder.addCallLinkAuthCredentials(GetGroupCredentialsResponse.CredentialAndRedemptionTime.newBuilder()
|
||||
.setRedemptionTimeSeconds(redemption.getEpochSecond())
|
||||
responseBuilder.addCallLinkAuthCredentials(ZkCredential.newBuilder()
|
||||
.setRedemptionTime(redemption.getEpochSecond())
|
||||
.setCredential(ByteString.copyFrom(
|
||||
CallLinkAuthCredentialResponse.issueCredential(aci, redemption, serverSecretParams).serialize()))
|
||||
.build());
|
||||
@@ -155,7 +156,7 @@ public class CredentialsGrpcService extends SimpleCredentialsGrpc.CredentialsImp
|
||||
}
|
||||
|
||||
@Override
|
||||
public GetCreateCallLinkCredentialsResponse getCreateCallLinkCredentials(final GetCreateCallLinkCredentialsRequest request)
|
||||
public GetCreateCallLinkCredentialResponse getCreateCallLinkCredential(final GetCreateCallLinkCredentialRequest request)
|
||||
throws RateLimitExceededException {
|
||||
|
||||
final UUID accountIdentifier = AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier();
|
||||
@@ -167,8 +168,7 @@ public class CredentialsGrpcService extends SimpleCredentialsGrpc.CredentialsImp
|
||||
final CreateCallLinkCredentialRequest createCallLinkCredentialRequest =
|
||||
new CreateCallLinkCredentialRequest(request.getCredentialRequest().toByteArray());
|
||||
|
||||
return GetCreateCallLinkCredentialsResponse.newBuilder()
|
||||
.setRedemptionTimeSeconds(truncatedDayTimestamp.getEpochSecond())
|
||||
return GetCreateCallLinkCredentialResponse.newBuilder()
|
||||
.setCredential(ByteString.copyFrom(createCallLinkCredentialRequest.issueCredential(
|
||||
new ServiceId.Aci(accountIdentifier),
|
||||
truncatedDayTimestamp,
|
||||
|
||||
+6
-2
@@ -18,9 +18,11 @@ public class DeviceCapabilityUtil {
|
||||
case DEVICE_CAPABILITY_TRANSFER -> DeviceCapability.TRANSFER;
|
||||
case DEVICE_CAPABILITY_ATTACHMENT_BACKFILL -> DeviceCapability.ATTACHMENT_BACKFILL;
|
||||
case DEVICE_CAPABILITY_SPARSE_POST_QUANTUM_RATCHET -> DeviceCapability.SPARSE_POST_QUANTUM_RATCHET;
|
||||
case DEVICE_CAPABILITY_PROFILES_V2 -> DeviceCapability.PROFILES_V2;
|
||||
case DEVICE_CAPABILITY_USERNAME_CHANGE_SYNC_MESSAGE -> DeviceCapability.USERNAME_CHANGE_SYNC_MESSAGE;
|
||||
case DEVICE_CAPABILITY_OPTIONAL_PHONE_NUMBER -> DeviceCapability.OPTIONAL_PHONE_NUMBER;
|
||||
case DEVICE_CAPABILITY_REPLY_PRIVATELY -> DeviceCapability.REPLY_PRIVATELY;
|
||||
case DEVICE_CAPABILITY_CONTACT_DELETE -> DeviceCapability.CONTACT_DELETE;
|
||||
case DEVICE_CAPABILITY_ADMIN_REMOVE_AND_DELETE -> DeviceCapability.ADMIN_REMOVE_AND_DELETE;
|
||||
case DEVICE_CAPABILITY_UNSPECIFIED, UNRECOGNIZED ->
|
||||
throw GrpcExceptions.invalidArguments("unrecognized device capability");
|
||||
};
|
||||
@@ -32,9 +34,11 @@ public class DeviceCapabilityUtil {
|
||||
case TRANSFER -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_TRANSFER;
|
||||
case ATTACHMENT_BACKFILL -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_ATTACHMENT_BACKFILL;
|
||||
case SPARSE_POST_QUANTUM_RATCHET -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_SPARSE_POST_QUANTUM_RATCHET;
|
||||
case PROFILES_V2 -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_PROFILES_V2;
|
||||
case USERNAME_CHANGE_SYNC_MESSAGE -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_USERNAME_CHANGE_SYNC_MESSAGE;
|
||||
case OPTIONAL_PHONE_NUMBER -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_OPTIONAL_PHONE_NUMBER;
|
||||
case REPLY_PRIVATELY -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_REPLY_PRIVATELY;
|
||||
case CONTACT_DELETE -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_CONTACT_DELETE;
|
||||
case ADMIN_REMOVE_AND_DELETE -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_ADMIN_REMOVE_AND_DELETE;
|
||||
};
|
||||
}
|
||||
}
|
||||
+19
-1
@@ -12,6 +12,8 @@ import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import javax.annotation.Nullable;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.signal.chat.device.ChangeDevicePasswordRequest;
|
||||
import org.signal.chat.device.ChangeDevicePasswordResponse;
|
||||
import org.signal.chat.device.ClearPushTokenRequest;
|
||||
import org.signal.chat.device.ClearPushTokenResponse;
|
||||
import org.signal.chat.device.GetDevicesRequest;
|
||||
@@ -28,7 +30,6 @@ import org.signal.chat.device.SimpleDevicesGrpc;
|
||||
import org.signal.chat.errors.NotFound;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
@@ -184,6 +185,23 @@ public class DevicesGrpcService extends SimpleDevicesGrpc.DevicesImplBase {
|
||||
return SetCapabilitiesResponse.getDefaultInstance();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ChangeDevicePasswordResponse changeDevicePassword(final ChangeDevicePasswordRequest request) {
|
||||
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
|
||||
|
||||
if (request.getNewPassword().isBlank()) {
|
||||
throw GrpcExceptions.fieldViolation("new_password", "password must not be blank");
|
||||
}
|
||||
|
||||
if (!accountsManager.updateDevicePassword(authenticatedDevice.accountIdentifier(), authenticatedDevice.deviceId(),
|
||||
request.getNewPassword())) {
|
||||
|
||||
throw GrpcExceptions.invalidCredentials("invalid credentials");
|
||||
}
|
||||
|
||||
return ChangeDevicePasswordResponse.getDefaultInstance();
|
||||
}
|
||||
|
||||
private Account getAuthenticatedAccount() {
|
||||
return accountsManager.getByAccountIdentifier(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier())
|
||||
.orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials"));
|
||||
|
||||
+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();
|
||||
}
|
||||
}
|
||||
+16
-5
@@ -5,6 +5,7 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import io.github.resilience4j.circuitbreaker.CallNotPermittedException;
|
||||
import io.grpc.ForwardingServerCall;
|
||||
import io.grpc.Metadata;
|
||||
import io.grpc.ServerCall;
|
||||
@@ -12,12 +13,14 @@ import io.grpc.ServerCallHandler;
|
||||
import io.grpc.ServerInterceptor;
|
||||
import io.grpc.Status;
|
||||
import io.grpc.StatusRuntimeException;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.logging.ImpossibleEvents;
|
||||
import io.lettuce.core.RedisException;
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountNotFoundException;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.logging.ImpossibleEvents;
|
||||
|
||||
/**
|
||||
* This interceptor observes responses from the service and if the response status is {@link Status#UNKNOWN}
|
||||
@@ -52,6 +55,7 @@ public class ErrorMappingInterceptor implements ServerInterceptor {
|
||||
|
||||
final StatusRuntimeException statusException = switch (cause) {
|
||||
case ConvertibleToGrpcStatus e -> e.toStatusRuntimeException();
|
||||
case AccountNotFoundException _ -> GrpcExceptions.invalidCredentials("invalid credentials");
|
||||
case UncheckedIOException e -> {
|
||||
log.warn("RPC {} encountered UncheckedIOException", call.getMethodDescriptor().getFullMethodName(), e.getCause());
|
||||
yield GrpcExceptions.unavailable();
|
||||
@@ -64,6 +68,13 @@ public class ErrorMappingInterceptor implements ServerInterceptor {
|
||||
ImpossibleEvents.logImpossible(log, e.getMessage(), e);
|
||||
yield GrpcExceptions.unavailable();
|
||||
}
|
||||
case CallNotPermittedException _ -> GrpcExceptions.unavailable();
|
||||
case RedisException e -> {
|
||||
if (!ExceptionUtils.isBreakerOpen(e)) {
|
||||
log.warn("RPC {} encountered RedisException", call.getMethodDescriptor().getFullMethodName(), e);
|
||||
}
|
||||
yield GrpcExceptions.unavailable();
|
||||
}
|
||||
case null -> {
|
||||
log.error("RPC {} finished with status UNKNOWN: {}",
|
||||
call.getMethodDescriptor().getFullMethodName(), status.getDescription());
|
||||
@@ -71,7 +82,7 @@ public class ErrorMappingInterceptor implements ServerInterceptor {
|
||||
}
|
||||
default -> {
|
||||
log.error("RPC {} finished with status UNKNOWN",
|
||||
call.getMethodDescriptor().getFullMethodName(), status.getCause());
|
||||
call.getMethodDescriptor().getFullMethodName(), cause);
|
||||
yield GrpcExceptions.unavailable();
|
||||
}
|
||||
};
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import com.google.protobuf.InvalidProtocolBufferException;
|
||||
import com.google.rpc.ErrorInfo;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.util.Optional;
|
||||
|
||||
public class ErrorUtil {
|
||||
public static Optional<ErrorInfo> errorInfo(final com.google.rpc.Status statusProto) {
|
||||
return statusProto.getDetailsList().stream()
|
||||
.filter(any -> any.is(ErrorInfo.class))
|
||||
.map(errorInfo -> {
|
||||
try {
|
||||
return errorInfo.unpack(ErrorInfo.class);
|
||||
} catch (final InvalidProtocolBufferException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
})
|
||||
.findFirst();
|
||||
}
|
||||
}
|
||||
Loaded 100 of 452 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user