mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-12-01 06:16:47 +00:00
Compare commits
57
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0d2bee7599 | ||
|
|
78aa81dd56 | ||
|
|
08f6ec639c | ||
|
|
6c3cfc88b5 | ||
|
|
389d44fd80 | ||
|
|
7604306818 | ||
|
|
92e133b21f | ||
|
|
4af50986e0 | ||
|
|
c72458b47a | ||
|
|
aa2f9e5a65 | ||
|
|
f13837d2f2 | ||
|
|
3ff2af47cb | ||
|
|
c719da3527 | ||
|
|
0ea52b785e | ||
|
|
1ce1c298d3 | ||
|
|
4d5cc4dc22 | ||
|
|
640274108e | ||
|
|
dd17ddc98c | ||
|
|
4c4a954c1c | ||
|
|
65ce9af366 | ||
|
|
4af0de2ab2 | ||
|
|
ccf72a45db | ||
|
|
f3744fbcb1 | ||
|
|
ec08731e6d | ||
|
|
852591df40 | ||
|
|
9ff9b3a7b3 | ||
|
|
dd4e058cd7 | ||
|
|
85226bdd87 | ||
|
|
faa74469ea | ||
|
|
bb94975d74 | ||
|
|
298b0d8d28 | ||
|
|
9da643dd69 | ||
|
|
6dc4bfe5fa | ||
|
|
23a3e32eb8 | ||
|
|
bf6939ec00 | ||
|
|
3b310463c3 | ||
|
|
f7eb6fab33 | ||
|
|
ce945ff245 | ||
|
|
4dbd564442 | ||
|
|
24f8f48a26 | ||
|
|
a2ce37fd53 | ||
|
|
c4d55e099e | ||
|
|
0f950917d8 | ||
|
|
3116913378 | ||
|
|
d7a9e3c9f3 | ||
|
|
14010a4f83 | ||
|
|
ad0bcd5436 | ||
|
|
88d458cf79 | ||
|
|
342c8a1b28 | ||
|
|
ad2500d4fd | ||
|
|
c2ebabad58 | ||
|
|
1105753aab | ||
|
|
9378b9a6e6 | ||
|
|
c68e3103c4 | ||
|
|
c9760f4c38 | ||
|
|
73765fc4ec | ||
|
|
9e1b716548 |
No files matched your search
@@ -42,7 +42,6 @@
|
||||
<commons-csv.version>1.14.1</commons-csv.version>
|
||||
<commons-io.version>2.20.0</commons-io.version>
|
||||
<dropwizard.version>4.0.16</dropwizard.version>
|
||||
<dropwizard-metrics-datadog.version>1.1.14</dropwizard-metrics-datadog.version>
|
||||
<!-- Note: when updating FoundationDB, also include a copy of `libfdb_c.so` from the FoundationDB release at
|
||||
src/main/jib/usr/lib/libfdb_c.so. We use x86_64 builds without AVX instructions enabled (i.e. FoundationDB versions
|
||||
with even-numbered patch versions). Also when updating FoundationDB, make sure to update the version of FoundationDB
|
||||
@@ -80,7 +79,7 @@
|
||||
<semver4j.version>3.1.0</semver4j.version>
|
||||
<simple-grpc.version>0.1.0</simple-grpc.version>
|
||||
<slf4j.version>2.0.17</slf4j.version>
|
||||
<stripe.version>28.4.0</stripe.version>
|
||||
<stripe.version>30.2.0</stripe.version>
|
||||
<swagger.version>2.2.36</swagger.version>
|
||||
<testcontainers.version>1.21.3</testcontainers.version>
|
||||
|
||||
@@ -88,7 +87,7 @@
|
||||
<dynamodb.image>amazon/dynamodb-local:3.0.0@sha256:2fed5e3a965a4ba5aa6ac82baec57058b5a3848e959d705518f3fd579a77e76b</dynamodb.image>
|
||||
<localstack.image>localstack/localstack:4@sha256:5a97e0f9917a3f0d9630bb13b9d8ccf10cbe52f33252807d3b4e21418cc21348</localstack.image>
|
||||
<redis.image>redis:7.4-alpine@sha256:af1d0fc3f63b02b13ff7906c9baf7c5b390b8881ca08119cd570677fe2f60b55</redis.image>
|
||||
<redis-cluster.image>docker.io/bitnami/redis-cluster:7.4@sha256:a53d023fdfaf8a8d7ddc58da040d3494e4cb45772644618ffa44c42dcd32b9af</redis-cluster.image>
|
||||
<redis-cluster.image>docker.io/bitnamilegacy/redis-cluster:7.4.3@sha256:a53d023fdfaf8a8d7ddc58da040d3494e4cb45772644618ffa44c42dcd32b9af</redis-cluster.image>
|
||||
|
||||
<!-- eclipse-temurin:24.0.2_12-jre-noble (note: always use the multi-arch manifest *LIST* here) -->
|
||||
<docker.image.sha256>85ecfc9bbb42af046d2bacbf1219d2005be4840cbfa16c2e6fd910d9ccfec95b</docker.image.sha256>
|
||||
@@ -231,11 +230,6 @@
|
||||
<artifactId>commons-csv</artifactId>
|
||||
<version>${commons-csv.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.coursera</groupId>
|
||||
<artifactId>dropwizard-metrics-datadog</artifactId>
|
||||
<version>${dropwizard-metrics-datadog.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.foundationdb</groupId>
|
||||
<artifactId>fdb-java</artifactId>
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
datadog.apiKey: unset
|
||||
|
||||
stripe.apiKey: unset
|
||||
stripe.idempotencyKeyGenerator: abcdefg12345678= # base64 for creating request idempotency hash
|
||||
|
||||
|
||||
+17
-33
@@ -10,35 +10,7 @@ logging:
|
||||
threshold: ALL
|
||||
timeZone: UTC
|
||||
target: stdout
|
||||
- type: logstashtcpsocket
|
||||
destination: example.com:10516
|
||||
apiKey: secret://datadog.apiKey
|
||||
environment: staging
|
||||
|
||||
metrics:
|
||||
reporters:
|
||||
- type: signal-datadog
|
||||
frequency: 10 seconds
|
||||
tags:
|
||||
- "env:staging"
|
||||
- "service:chat"
|
||||
udpTransport:
|
||||
statsdHost: localhost
|
||||
port: 8125
|
||||
excludesAttributes:
|
||||
- m1_rate
|
||||
- m5_rate
|
||||
- m15_rate
|
||||
- mean_rate
|
||||
- stddev
|
||||
useRegexFilters: true
|
||||
excludes:
|
||||
- ^.+\.total$
|
||||
- ^.+\.request\.filtering$
|
||||
- ^.+\.response\.filtering$
|
||||
- ^executor\..+$
|
||||
- ^lettuce\..+$
|
||||
reportOnStop: true
|
||||
- type: otlp
|
||||
|
||||
tlsKeyStore:
|
||||
password: secret://tlsKeyStore.password
|
||||
@@ -294,10 +266,6 @@ cdn3StorageManager:
|
||||
2: gcs
|
||||
3: r2
|
||||
|
||||
dogstatsd:
|
||||
environment: dev
|
||||
host: 127.0.0.1
|
||||
|
||||
openTelemetry:
|
||||
enabled: true
|
||||
environment: dev
|
||||
@@ -542,3 +510,19 @@ idlePrimaryDeviceReminder:
|
||||
|
||||
grpc:
|
||||
port: 50051
|
||||
|
||||
asnTable:
|
||||
s3Region: a-region
|
||||
s3Bucket: a-bucket
|
||||
objectKey: asn.tsv
|
||||
maxSize: 100000
|
||||
refreshInterval: PT10S
|
||||
|
||||
callQualitySurvey:
|
||||
pubSubPublisher:
|
||||
project: example-project
|
||||
topic: example-topic
|
||||
credentialConfiguration: |
|
||||
{
|
||||
"credential": "configuration"
|
||||
}
|
||||
+1
-8
@@ -346,18 +346,10 @@
|
||||
<groupId>io.micrometer</groupId>
|
||||
<artifactId>micrometer-core</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.micrometer</groupId>
|
||||
<artifactId>micrometer-registry-statsd</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.micrometer</groupId>
|
||||
<artifactId>micrometer-registry-otlp</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.coursera</groupId>
|
||||
<artifactId>dropwizard-metrics-datadog</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-core</artifactId>
|
||||
@@ -719,6 +711,7 @@
|
||||
<jvmFlag>-Djava.awt.headless=true</jvmFlag>
|
||||
<jvmFlag>-Djdk.nio.maxCachedBufferSize=262144</jvmFlag>
|
||||
<jvmFlag>-Dlog4j2.formatMsgNoLookups=true</jvmFlag>
|
||||
<jvmFlag>-Djdk.tls.server.newSessionTicketCount=0</jvmFlag>
|
||||
<jvmFlag>-XX:MaxRAMPercentage=75</jvmFlag>
|
||||
<jvmFlag>-XX:+HeapDumpOnOutOfMemoryError</jvmFlag>
|
||||
<jvmFlag>-XX:HeapDumpPath=/tmp/heapdump.bin</jvmFlag>
|
||||
|
||||
+19
-11
@@ -21,15 +21,14 @@ import org.whispersystems.textsecuregcm.configuration.AppleDeviceCheckConfigurat
|
||||
import org.whispersystems.textsecuregcm.configuration.AwsCredentialsProviderFactory;
|
||||
import org.whispersystems.textsecuregcm.configuration.BadgesConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.BraintreeConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.CallQualitySurveyConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.Cdn3StorageManagerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.CdnConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.CircuitBreakerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.ClientReleaseConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.DatadogConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.DefaultAwsCredentialsFactory;
|
||||
import org.whispersystems.textsecuregcm.configuration.DeviceCheckConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.DirectoryV2Configuration;
|
||||
import org.whispersystems.textsecuregcm.configuration.DogstatsdConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.DynamoDbClientFactory;
|
||||
import org.whispersystems.textsecuregcm.configuration.DynamoDbTables;
|
||||
import org.whispersystems.textsecuregcm.configuration.ExternalRequestFilterConfiguration;
|
||||
@@ -136,11 +135,6 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
@JsonProperty
|
||||
private Cdn3StorageManagerConfiguration cdn3StorageManager;
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
@JsonProperty
|
||||
private DatadogConfiguration dogstatsd = new DogstatsdConfiguration();
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
@JsonProperty
|
||||
@@ -348,6 +342,16 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
@JsonProperty
|
||||
private GrpcConfiguration grpc;
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
private S3ObjectMonitorFactory asnTable;
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
private CallQualitySurveyConfiguration callQualitySurvey;
|
||||
|
||||
public TlsKeyStoreConfiguration getTlsKeyStoreConfiguration() {
|
||||
return tlsKeyStore;
|
||||
}
|
||||
@@ -452,10 +456,6 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
return cdn3StorageManager;
|
||||
}
|
||||
|
||||
public DatadogConfiguration getDatadogConfiguration() {
|
||||
return dogstatsd;
|
||||
}
|
||||
|
||||
public OpenTelemetryConfiguration getOpenTelemetryConfiguration() {
|
||||
return openTelemetry;
|
||||
}
|
||||
@@ -582,4 +582,12 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
public GrpcConfiguration getGrpc() {
|
||||
return grpc;
|
||||
}
|
||||
|
||||
public S3ObjectMonitorFactory getAsnTableConfiguration() {
|
||||
return asnTable;
|
||||
}
|
||||
|
||||
public CallQualitySurveyConfiguration getCallQualitySurveyConfiguration() {
|
||||
return callQualitySurvey;
|
||||
}
|
||||
}
|
||||
@@ -4,8 +4,8 @@
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm;
|
||||
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
import static java.util.Objects.requireNonNull;
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
import com.webauthn4j.appattest.DeviceCheckManager;
|
||||
@@ -60,7 +60,7 @@ import java.util.concurrent.SynchronousQueue;
|
||||
import java.util.concurrent.ThreadPoolExecutor;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Stream;
|
||||
import org.eclipse.jetty.websocket.core.WebSocketComponents;
|
||||
import org.eclipse.jetty.websocket.core.WebSocketExtensionRegistry;
|
||||
import org.eclipse.jetty.websocket.core.server.WebSocketServerComponents;
|
||||
import org.eclipse.jetty.websocket.server.config.JettyWebSocketServletContainerInitializer;
|
||||
import org.glassfish.jersey.server.ServerProperties;
|
||||
@@ -73,6 +73,8 @@ import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialPresentation;
|
||||
import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.asn.AsnInfoProvider;
|
||||
import org.whispersystems.textsecuregcm.asn.AsnInfoProviderImpl;
|
||||
import org.whispersystems.textsecuregcm.attachments.GcsAttachmentGenerator;
|
||||
import org.whispersystems.textsecuregcm.attachments.TusAttachmentGenerator;
|
||||
import org.whispersystems.textsecuregcm.auth.AccountAuthenticator;
|
||||
@@ -105,6 +107,7 @@ import org.whispersystems.textsecuregcm.controllers.AccountControllerV2;
|
||||
import org.whispersystems.textsecuregcm.controllers.ArchiveController;
|
||||
import org.whispersystems.textsecuregcm.controllers.AttachmentControllerV4;
|
||||
import org.whispersystems.textsecuregcm.controllers.CallLinkController;
|
||||
import org.whispersystems.textsecuregcm.controllers.CallQualitySurveyController;
|
||||
import org.whispersystems.textsecuregcm.controllers.CallRoutingControllerV2;
|
||||
import org.whispersystems.textsecuregcm.controllers.CertificateController;
|
||||
import org.whispersystems.textsecuregcm.controllers.ChallengeController;
|
||||
@@ -122,7 +125,6 @@ import org.whispersystems.textsecuregcm.controllers.ProfileController;
|
||||
import org.whispersystems.textsecuregcm.controllers.ProvisioningController;
|
||||
import org.whispersystems.textsecuregcm.controllers.RegistrationController;
|
||||
import org.whispersystems.textsecuregcm.controllers.RemoteConfigController;
|
||||
import org.whispersystems.textsecuregcm.controllers.RemoteConfigControllerV1;
|
||||
import org.whispersystems.textsecuregcm.controllers.SecureStorageController;
|
||||
import org.whispersystems.textsecuregcm.controllers.SecureValueRecovery2Controller;
|
||||
import org.whispersystems.textsecuregcm.controllers.StickerController;
|
||||
@@ -140,6 +142,7 @@ import org.whispersystems.textsecuregcm.filters.RestDeprecationFilter;
|
||||
import org.whispersystems.textsecuregcm.filters.TimestampResponseFilter;
|
||||
import org.whispersystems.textsecuregcm.grpc.AccountsAnonymousGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.AccountsGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.CallQualitySurveyGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.ErrorMappingInterceptor;
|
||||
import org.whispersystems.textsecuregcm.grpc.ExternalServiceCredentialsAnonymousGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.ExternalServiceCredentialsGrpcService;
|
||||
@@ -177,6 +180,7 @@ import org.whispersystems.textsecuregcm.mappers.RegistrationServiceSenderExcepti
|
||||
import org.whispersystems.textsecuregcm.mappers.ServerRejectedExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.SubscriptionExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.metrics.BackupMetrics;
|
||||
import org.whispersystems.textsecuregcm.metrics.CallQualitySurveyManager;
|
||||
import org.whispersystems.textsecuregcm.metrics.MessageMetrics;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsApplicationEventListener;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsHttpChannelListener;
|
||||
@@ -200,6 +204,7 @@ import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import org.whispersystems.textsecuregcm.registration.RegistrationServiceClient;
|
||||
import org.whispersystems.textsecuregcm.s3.PolicySigner;
|
||||
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
|
||||
import org.whispersystems.textsecuregcm.s3.S3MonitoringSupplier;
|
||||
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
|
||||
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecoveryClient;
|
||||
import org.whispersystems.textsecuregcm.spam.ChallengeConstraintChecker;
|
||||
@@ -246,6 +251,7 @@ 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.subscriptions.AppleAppStoreClient;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.AppleAppStoreManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.BankMandateTranslator;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.BraintreeManager;
|
||||
@@ -262,6 +268,7 @@ import org.whispersystems.textsecuregcm.util.VirtualThreadPinEventMonitor;
|
||||
import org.whispersystems.textsecuregcm.util.logging.LoggingUnhandledExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.util.logging.UncaughtExceptionHandler;
|
||||
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.workers.BackupMetricsCommand;
|
||||
@@ -285,6 +292,7 @@ import org.whispersystems.textsecuregcm.workers.ServerVersionCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.SetRequestLoggingEnabledTask;
|
||||
import org.whispersystems.textsecuregcm.workers.SetUserDiscoverabilityCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.UnlinkDeviceCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.UnlinkDevicesWithIdlePrimaryCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.ZkParamsCommand;
|
||||
import org.whispersystems.websocket.WebSocketResourceProviderFactory;
|
||||
import org.whispersystems.websocket.setup.WebSocketEnvironment;
|
||||
@@ -337,6 +345,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
bootstrap.addCommand(new BackupMetricsCommand(Clock.systemUTC()));
|
||||
bootstrap.addCommand(new BackupUsageRecalculationCommand());
|
||||
bootstrap.addCommand(new RemoveExpiredLinkedDevicesCommand());
|
||||
bootstrap.addCommand(new UnlinkDevicesWithIdlePrimaryCommand(Clock.systemUTC()));
|
||||
bootstrap.addCommand(new NotifyIdleDevicesCommand());
|
||||
bootstrap.addCommand(new ClearIssuedReceiptRedemptionsCommand());
|
||||
|
||||
@@ -345,6 +354,12 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
new IdleDeviceNotificationSchedulerFactory()));
|
||||
|
||||
bootstrap.addCommand(new RegenerateSecondaryDynamoDbTableDataCommand());
|
||||
|
||||
ServiceLoader.load(SpamFilter.class)
|
||||
.stream()
|
||||
.map(ServiceLoader.Provider::get)
|
||||
.flatMap(spamFilter -> spamFilter.getCommands().stream())
|
||||
.forEach(bootstrap::addCommand);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -579,10 +594,15 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
"disconnectionRequest",
|
||||
config.getVirtualThreadConfiguration().maxConcurrentThreadsPerExecutor(),
|
||||
environment);
|
||||
ExecutorService callQualitySurveyPubSubExecutor = ManagedExecutors.newVirtualThreadPerTaskExecutor(
|
||||
"callQualitySurvey",
|
||||
config.getVirtualThreadConfiguration().maxConcurrentThreadsPerExecutor(),
|
||||
environment);
|
||||
|
||||
ScheduledExecutorService cloudflareTurnRetryExecutor = ScheduledExecutorServiceBuilder.of(environment, "cloudflareTurnRetry").threads(1).build();
|
||||
ScheduledExecutorService messagePollExecutor = ScheduledExecutorServiceBuilder.of(environment, "messagePollExecutor").threads(1).build();
|
||||
ScheduledExecutorService provisioningWebsocketTimeoutExecutor = ScheduledExecutorServiceBuilder.of(environment, "provisioningWebsocketTimeout").threads(1).build();
|
||||
ScheduledExecutorService jmxDumper = ScheduledExecutorServiceBuilder.of(environment, "jmxDumper").threads(1).build();
|
||||
|
||||
final ManagedNioEventLoopGroup dnsResolutionEventLoopGroup = new ManagedNioEventLoopGroup();
|
||||
final DnsNameResolver cloudflareDnsResolver = new DnsNameResolverBuilder(dnsResolutionEventLoopGroup.next())
|
||||
@@ -603,6 +623,14 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
ExternalServiceCredentialsGenerator svrbCredentialsGenerator =
|
||||
SecureValueRecoveryBCredentialsGeneratorFactory.svrbCredentialsGenerator(config.getSvrbConfiguration());
|
||||
|
||||
final S3MonitoringSupplier<AsnInfoProvider> asnInfoProviderSupplier = new S3MonitoringSupplier<>(
|
||||
recurringJobExecutor,
|
||||
awsCredentialsProvider,
|
||||
config.getAsnTableConfiguration(),
|
||||
AsnInfoProviderImpl::fromTsvGz,
|
||||
AsnInfoProvider.EMPTY,
|
||||
"AsnManager");
|
||||
|
||||
RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager =
|
||||
new RegistrationRecoveryPasswordsManager(registrationRecoveryPasswords);
|
||||
UsernameHashZkProofVerifier usernameHashZkProofVerifier = new UsernameHashZkProofVerifier();
|
||||
@@ -679,6 +707,10 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
config.getDynamoDbTables().getSubscriptions().getTableName(), dynamoDbAsyncClient);
|
||||
MessageDeliveryLoopMonitor messageDeliveryLoopMonitor =
|
||||
config.logMessageDeliveryLoops() ? new RedisMessageDeliveryLoopMonitor(rateLimitersCluster) : new NoopMessageDeliveryLoopMonitor();
|
||||
CallQualitySurveyManager callQualitySurveyManager = new CallQualitySurveyManager(asnInfoProviderSupplier,
|
||||
config.getCallQualitySurveyConfiguration().pubSubPublisher().build(),
|
||||
Clock.systemUTC(),
|
||||
callQualitySurveyPubSubExecutor);
|
||||
|
||||
final RegistrationLockVerificationManager registrationLockVerificationManager = new RegistrationLockVerificationManager(
|
||||
accountsManager, disconnectionRequestManager, svr2CredentialsGenerator, registrationRecoveryPasswordsManager,
|
||||
@@ -743,12 +775,19 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
config.getGooglePlayBilling().applicationName(),
|
||||
config.getGooglePlayBilling().productIdToLevel());
|
||||
AppleAppStoreManager appleAppStoreManager = new AppleAppStoreManager(
|
||||
config.getAppleAppStore().env(), config.getAppleAppStore().bundleId(), config.getAppleAppStore().appAppleId(),
|
||||
config.getAppleAppStore().issuerId(), config.getAppleAppStore().keyId(),
|
||||
config.getAppleAppStore().encodedKey().value(), config.getAppleAppStore().subscriptionGroupId(),
|
||||
config.getAppleAppStore().productIdToLevel(),
|
||||
config.getAppleAppStore().appleRootCerts(),
|
||||
config.getAppleAppStore().retryConfigurationName());
|
||||
new AppleAppStoreClient(
|
||||
config.getAppleAppStore().env(),
|
||||
config.getAppleAppStore().bundleId(),
|
||||
config.getAppleAppStore().appAppleId(),
|
||||
config.getAppleAppStore().issuerId(),
|
||||
config.getAppleAppStore().keyId(),
|
||||
config.getAppleAppStore().encodedKey().value(),
|
||||
config.getAppleAppStore().appleRootCerts(),
|
||||
config.getAppleAppStore().retryConfigurationName()),
|
||||
config.getAppleAppStore().subscriptionGroupId(),
|
||||
config.getAppleAppStore().productIdToLevel());
|
||||
|
||||
environment.lifecycle().manage(asnInfoProviderSupplier);
|
||||
|
||||
environment.lifecycle().manage(apnSender);
|
||||
environment.lifecycle().manage(pushNotificationScheduler);
|
||||
@@ -853,6 +892,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
|
||||
final List<ServerServiceDefinition> unauthenticatedServices = Stream.of(
|
||||
new AccountsAnonymousGrpcService(accountsManager, rateLimiters),
|
||||
new CallQualitySurveyGrpcService(callQualitySurveyManager, rateLimiters),
|
||||
new KeysAnonymousGrpcService(accountsManager, keysManager, zkSecretParams, Clock.systemUTC()),
|
||||
new PaymentsGrpcService(currencyManager),
|
||||
ExternalServiceCredentialsAnonymousGrpcService.create(accountsManager, config),
|
||||
@@ -1030,6 +1070,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
new ArchiveController(accountsManager, backupAuthManager, backupManager, backupMetrics),
|
||||
new CallRoutingControllerV2(rateLimiters, cloudflareTurnCredentialsManager),
|
||||
new CallLinkController(rateLimiters, callingGenericZkSecretParams),
|
||||
new CallQualitySurveyController(callQualitySurveyManager),
|
||||
new CertificateController(accountsManager, new CertificateGenerator(config.getDeliveryCertificate().certificate(),
|
||||
config.getDeliveryCertificate().ecPrivateKey(), config.getDeliveryCertificate().expiresDays()),
|
||||
zkAuthOperations, callingGenericZkSecretParams, clock),
|
||||
@@ -1043,7 +1084,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
ReceiptCredentialPresentation::new),
|
||||
new KeysController(rateLimiters, keysManager, accountsManager, zkSecretParams, Clock.systemUTC()),
|
||||
new KeyTransparencyController(keyTransparencyServiceClient),
|
||||
new MessageController(rateLimiters, messageByteLimitCardinalityEstimator, messageSender, receiptSender,
|
||||
new MessageController(rateLimiters, messageByteLimitCardinalityEstimator, messageSender,
|
||||
accountsManager, messagesManager, phoneNumberIdentifiers, pushNotificationManager, pushNotificationScheduler,
|
||||
reportMessageManager, messageDeliveryScheduler, clientReleaseManager,
|
||||
zkSecretParams, spamChecker, messageMetrics, messageDeliveryLoopMonitor,
|
||||
@@ -1055,7 +1096,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
new ProvisioningController(rateLimiters, provisioningManager),
|
||||
new RegistrationController(accountsManager, phoneVerificationTokenManager, registrationLockVerificationManager,
|
||||
rateLimiters),
|
||||
new RemoteConfigControllerV1(remoteConfigsManager, config.getRemoteConfigConfiguration().globalConfig(), clock),
|
||||
new RemoteConfigController(remoteConfigsManager, config.getRemoteConfigConfiguration().globalConfig(), clock),
|
||||
new SecureStorageController(storageCredentialsGenerator),
|
||||
new SecureValueRecovery2Controller(svr2CredentialsGenerator, accountsManager),
|
||||
@@ -1097,10 +1137,14 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
provisioningEnvironment.jersey().property(ServerProperties.UNWRAP_COMPLETION_STAGE_IN_WRITER_ENABLE, Boolean.TRUE);
|
||||
|
||||
JettyWebSocketServletContainerInitializer.configure(environment.getApplicationContext(), (context, container) -> {
|
||||
final WebSocketExtensionRegistry extensionRegistry = WebSocketServerComponents
|
||||
.getWebSocketComponents(environment.getApplicationContext().getServletContext())
|
||||
.getExtensionRegistry();
|
||||
if (config.getWebSocketConfiguration().isDisablePerMessageDeflate()) {
|
||||
WebSocketComponents components =
|
||||
WebSocketServerComponents.getWebSocketComponents(environment.getApplicationContext().getServletContext());
|
||||
components.getExtensionRegistry().unregister("permessage-deflate");
|
||||
extensionRegistry.unregister("permessage-deflate");
|
||||
} else if (config.getWebSocketConfiguration().isDisableCrossMessageOutgoingCompression()) {
|
||||
extensionRegistry.unregister("permessage-deflate");
|
||||
extensionRegistry.register("permessage-deflate", NoContextTakeoverPerMessageDeflateExtension.class);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1121,6 +1165,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
provisioning.setAsyncSupported(true);
|
||||
|
||||
environment.admin().addTask(new SetRequestLoggingEnabledTask());
|
||||
|
||||
}
|
||||
|
||||
private void registerExceptionMappers(Environment environment,
|
||||
@@ -1149,7 +1194,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
});
|
||||
}
|
||||
|
||||
private static class ExecutorServiceBuilder extends io.dropwizard.lifecycle.setup.ExecutorServiceBuilder {
|
||||
public static class ExecutorServiceBuilder extends io.dropwizard.lifecycle.setup.ExecutorServiceBuilder {
|
||||
private final String baseName;
|
||||
|
||||
public ExecutorServiceBuilder(final LifecycleEnvironment environment, final String baseName) {
|
||||
@@ -1167,7 +1212,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
}
|
||||
}
|
||||
|
||||
private static class ScheduledExecutorServiceBuilder extends io.dropwizard.lifecycle.setup.ScheduledExecutorServiceBuilder {
|
||||
public static class ScheduledExecutorServiceBuilder extends io.dropwizard.lifecycle.setup.ScheduledExecutorServiceBuilder {
|
||||
private final String baseName;
|
||||
|
||||
public ScheduledExecutorServiceBuilder(final LifecycleEnvironment environment, final String baseName) {
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
/*
|
||||
* Copyright 2013-2021 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.asn;
|
||||
|
||||
import static java.util.Objects.requireNonNull;
|
||||
|
||||
import com.google.i18n.phonenumbers.PhoneNumberUtil;
|
||||
import javax.annotation.Nonnull;
|
||||
|
||||
public record AsnInfo(long asn, @Nonnull String regionCode) {
|
||||
|
||||
public AsnInfo {
|
||||
requireNonNull(regionCode, "regionCode must not be null");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
/*
|
||||
* Copyright 2013-2021 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.asn;
|
||||
|
||||
import java.util.Optional;
|
||||
import javax.annotation.Nonnull;
|
||||
|
||||
public interface AsnInfoProvider {
|
||||
|
||||
/// Gets ASN information for an IP address.
|
||||
///
|
||||
/// @param ipString a string representation of an IP address
|
||||
///
|
||||
/// @return ASN information for the given IP address or empty if no ASN information was found for the given IP address
|
||||
Optional<AsnInfo> lookup(@Nonnull String ipString);
|
||||
|
||||
AsnInfoProvider EMPTY = _ -> Optional.empty();
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
/*
|
||||
* Copyright 2013-2021 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.asn;
|
||||
|
||||
import static java.util.Objects.requireNonNull;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.lang.invoke.MethodHandles;
|
||||
import java.math.BigInteger;
|
||||
import java.net.Inet4Address;
|
||||
import java.net.Inet6Address;
|
||||
import java.net.InetAddress;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.NavigableMap;
|
||||
import java.util.Optional;
|
||||
import java.util.TreeMap;
|
||||
import java.util.zip.GZIPInputStream;
|
||||
import javax.annotation.Nonnull;
|
||||
import org.apache.commons.csv.CSVFormat;
|
||||
import org.apache.commons.csv.CSVParser;
|
||||
import org.apache.commons.csv.CSVRecord;
|
||||
import org.apache.commons.lang3.Validate;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* {@code AsnInfoProvider} implementation that supports both IPv4 and IPv6.
|
||||
*/
|
||||
public class AsnInfoProviderImpl implements AsnInfoProvider {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
|
||||
|
||||
@Nonnull
|
||||
private final NavigableMap<Long, AsnRange<Long>> asnBlocksByFirstIpv4;
|
||||
|
||||
@Nonnull
|
||||
private final NavigableMap<BigInteger, AsnRange<BigInteger>> asnBlocksByFirstIpv6;
|
||||
|
||||
|
||||
/**
|
||||
* Creates an instance of {@code AsnInfoProviderImpl} using data from <a href="https://iptoasn.com/">iptoasn.com</a>.
|
||||
* @param tsvGzInputStream gzip input stream representing the data.
|
||||
*/
|
||||
@Nonnull
|
||||
public static AsnInfoProviderImpl fromTsvGz(@Nonnull final InputStream tsvGzInputStream) {
|
||||
try (final GZIPInputStream inputStream = new GZIPInputStream(tsvGzInputStream)) {
|
||||
return fromTsv(inputStream);
|
||||
} catch (final IOException e) {
|
||||
log.error("failed to ungzip the input stream", e);
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an instance of {@code AsnInfoProviderImpl} using data from <a href="https://iptoasn.com/">iptoasn.com</a>.
|
||||
* @param tsvInputStream input stream representing the data.
|
||||
*/
|
||||
@Nonnull
|
||||
public static AsnInfoProviderImpl fromTsv(@Nonnull final InputStream tsvInputStream) {
|
||||
try (final InputStreamReader tsvReader = new InputStreamReader(tsvInputStream)) {
|
||||
final NavigableMap<Long, AsnRange<Long>> ip4asns = new TreeMap<>();
|
||||
final NavigableMap<BigInteger, AsnRange<BigInteger>> ip6asns = new TreeMap<>();
|
||||
final Map<Long, AsnInfo> asnInfoCache = new HashMap<>();
|
||||
|
||||
try (final CSVParser csvParser = CSVFormat.TDF.parse(tsvReader)) {
|
||||
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 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
|
||||
// not to have multiple instances with the same values
|
||||
final AsnInfo asnInfo = asnInfoCache.computeIfAbsent(asn, k -> new AsnInfo(asn, regionCode));
|
||||
if (!regionCode.equals(asnInfo.regionCode())) {
|
||||
log.warn("ASN {} mapped to country codes {} and {}", asn, regionCode, asnInfo.regionCode());
|
||||
}
|
||||
|
||||
// IPv4
|
||||
if (startIp instanceof Inet4Address) {
|
||||
final AsnRange<Long> asnRange = new AsnRange<>(
|
||||
ip4BytesToLong((Inet4Address) startIp),
|
||||
ip4BytesToLong((Inet4Address) endIp),
|
||||
asnInfo
|
||||
);
|
||||
ip4asns.put(asnRange.from(), asnRange);
|
||||
}
|
||||
|
||||
// IPv6
|
||||
if (startIp instanceof Inet6Address) {
|
||||
final AsnRange<BigInteger> asnRange = new AsnRange<>(
|
||||
ip6BytesToBigInteger((Inet6Address) startIp),
|
||||
ip6BytesToBigInteger((Inet6Address) endIp),
|
||||
asnInfo
|
||||
);
|
||||
ip6asns.put(asnRange.from(), asnRange);
|
||||
}
|
||||
}
|
||||
}
|
||||
return new AsnInfoProviderImpl(ip4asns, ip6asns);
|
||||
} catch (final Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public AsnInfoProviderImpl(
|
||||
@Nonnull final NavigableMap<Long, AsnRange<Long>> asnBlocksByFirstIpv4,
|
||||
@Nonnull final NavigableMap<BigInteger, AsnRange<BigInteger>> asnBlocksByFirstIpv6) {
|
||||
this.asnBlocksByFirstIpv4 = requireNonNull(asnBlocksByFirstIpv4);
|
||||
this.asnBlocksByFirstIpv6 = requireNonNull(asnBlocksByFirstIpv6);
|
||||
}
|
||||
|
||||
@Nonnull
|
||||
@Override
|
||||
public Optional<AsnInfo> lookup(@Nonnull final String ipString) {
|
||||
try {
|
||||
final InetAddress address = InetAddress.getByName(ipString);
|
||||
if (address instanceof Inet4Address ip4) {
|
||||
final Long key = ip4BytesToLong(ip4);
|
||||
return lookupInMap(asnBlocksByFirstIpv4, key);
|
||||
}
|
||||
if (address instanceof Inet6Address ip6) {
|
||||
final BigInteger key = ip6BytesToBigInteger(ip6);
|
||||
return lookupInMap(asnBlocksByFirstIpv6, key);
|
||||
}
|
||||
// safety net, should never happen
|
||||
log.warn("Unknown InetAddress implementation: {}", address.getClass().getName());
|
||||
} catch (final Exception e) {
|
||||
log.error("Could not resolve ASN for IP string {}", ipString);
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
protected static long ip4BytesToLong(@Nonnull final Inet4Address address) {
|
||||
final byte[] arr = address.getAddress();
|
||||
Validate.isTrue(arr.length == 4);
|
||||
return Integer.toUnsignedLong(ByteBuffer.wrap(arr).getInt());
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
protected static BigInteger ip6BytesToBigInteger(@Nonnull final Inet6Address address) {
|
||||
final byte[] arr = address.getAddress();
|
||||
Validate.isTrue(arr.length == 16);
|
||||
return new BigInteger(1, arr);
|
||||
}
|
||||
|
||||
@Nonnull
|
||||
private static <T extends Comparable<T>> Optional<AsnInfo> lookupInMap(
|
||||
@Nonnull final NavigableMap<T, AsnRange<T>> map,
|
||||
@Nonnull final T key) {
|
||||
return Optional.ofNullable(map.floorEntry(key))
|
||||
.filter(e -> e.getValue().contains(key) && e.getValue().asnInfo().asn() != 0)
|
||||
.map(e -> e.getValue().asnInfo());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
/*
|
||||
* Copyright 2013-2021 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.asn;
|
||||
|
||||
import static java.util.Objects.requireNonNull;
|
||||
|
||||
import javax.annotation.Nonnull;
|
||||
import org.apache.commons.lang3.Validate;
|
||||
|
||||
public record AsnRange<T extends Comparable<T>>(@Nonnull T from,
|
||||
@Nonnull T to,
|
||||
@Nonnull AsnInfo asnInfo) {
|
||||
public AsnRange {
|
||||
requireNonNull(from);
|
||||
requireNonNull(to);
|
||||
requireNonNull(asnInfo);
|
||||
Validate.isTrue(from.compareTo(to) <= 0);
|
||||
}
|
||||
|
||||
boolean contains(@Nonnull final T element) {
|
||||
requireNonNull(element);
|
||||
return from.compareTo(element) <= 0
|
||||
&& element.compareTo(to) <= 0;
|
||||
}
|
||||
}
|
||||
+3
-5
@@ -5,7 +5,7 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.auth;
|
||||
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.dropwizard.auth.Authenticator;
|
||||
@@ -29,13 +29,11 @@ import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
public class AccountAuthenticator implements Authenticator<BasicCredentials, AuthenticatedDevice> {
|
||||
|
||||
private static final String LEGACY_NAME_PREFIX = "org.whispersystems.textsecuregcm.auth.BaseAccountAuthenticator";
|
||||
|
||||
private static final String AUTHENTICATION_COUNTER_NAME = name(LEGACY_NAME_PREFIX, "authentication");
|
||||
private static final String AUTHENTICATION_COUNTER_NAME = name(AccountAuthenticator.class, "authentication");
|
||||
private static final String AUTHENTICATION_SUCCEEDED_TAG_NAME = "succeeded";
|
||||
private static final String AUTHENTICATION_FAILURE_REASON_TAG_NAME = "reason";
|
||||
|
||||
private static final String DAYS_SINCE_LAST_SEEN_DISTRIBUTION_NAME = name(LEGACY_NAME_PREFIX, "daysSinceLastSeen");
|
||||
private static final String DAYS_SINCE_LAST_SEEN_DISTRIBUTION_NAME = name(AccountAuthenticator.class, "daysSinceLastSeen");
|
||||
private static final String IS_PRIMARY_DEVICE_TAG = "isPrimary";
|
||||
|
||||
private static final Counter OLD_TOKEN_VERSION_COUNTER =
|
||||
|
||||
@@ -56,6 +56,7 @@ import org.whispersystems.textsecuregcm.util.ua.UserAgentUtil;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
public class BackupManager {
|
||||
|
||||
@@ -73,8 +74,8 @@ public class BackupManager {
|
||||
private static final Timer SYNCHRONOUS_DELETE_TIMER =
|
||||
Metrics.timer(MetricsUtil.name(BackupManager.class, "synchronousDelete"));
|
||||
|
||||
private static final String NUM_OBJECTS_SUMMARY_NAME = MetricsUtil.name(BackupsDb.class, "numObjects");
|
||||
private static final String BYTES_USED_SUMMARY_NAME = MetricsUtil.name(BackupsDb.class, "bytesUsed");
|
||||
private static final String NUM_OBJECTS_SUMMARY_NAME = MetricsUtil.name(BackupManager.class, "numObjects");
|
||||
private static final String BYTES_USED_SUMMARY_NAME = MetricsUtil.name(BackupManager.class, "bytesUsed");
|
||||
|
||||
private static final String SUCCESS_TAG_NAME = "success";
|
||||
private static final String FAILURE_REASON_TAG_NAME = "reason";
|
||||
@@ -622,11 +623,13 @@ public class BackupManager {
|
||||
return backupsDb
|
||||
.retrieveAuthenticationData(presentation.getBackupId())
|
||||
.thenApply(optionalAuthenticationData -> {
|
||||
final UserAgent userAgent = parseUserAgent(userAgentString);
|
||||
final BackupsDb.AuthenticationData authenticationData = optionalAuthenticationData
|
||||
.orElseGet(() -> {
|
||||
Metrics.counter(ZK_AUTHN_COUNTER_NAME,
|
||||
SUCCESS_TAG_NAME, String.valueOf(false),
|
||||
FAILURE_REASON_TAG_NAME, "missing_public_key")
|
||||
Metrics.counter(ZK_AUTHN_COUNTER_NAME, Tags.of(
|
||||
Tag.of(SUCCESS_TAG_NAME, String.valueOf(false)),
|
||||
Tag.of(FAILURE_REASON_TAG_NAME, "missing_public_key"),
|
||||
UserAgentTagUtil.getPlatformTag(userAgent)))
|
||||
.increment();
|
||||
// There was no stored public key, use a bunk public key so that validation will fail
|
||||
return new BackupsDb.AuthenticationData(INVALID_PUBLIC_KEY, null, null);
|
||||
@@ -635,13 +638,6 @@ public class BackupManager {
|
||||
final Pair<BackupCredentialType, BackupLevel> credentialTypeAndBackupLevel =
|
||||
signatureVerifier.verifySignature(signature, authenticationData.publicKey());
|
||||
|
||||
UserAgent userAgent;
|
||||
try {
|
||||
userAgent = UserAgentUtil.parseUserAgentString(userAgentString);
|
||||
} catch (UnrecognizedUserAgentException e) {
|
||||
userAgent = null;
|
||||
}
|
||||
|
||||
return new AuthenticatedBackupUser(
|
||||
presentation.getBackupId(),
|
||||
credentialTypeAndBackupLevel.first(),
|
||||
@@ -842,4 +838,12 @@ public class BackupManager {
|
||||
static String rateLimitKey(final AuthenticatedBackupUser backupUser) {
|
||||
return Base64.getEncoder().encodeToString(BackupsDb.hashedBackupId(backupUser.backupId()));
|
||||
}
|
||||
|
||||
private static @Nullable UserAgent parseUserAgent(final String userAgentString) {
|
||||
try {
|
||||
return UserAgentUtil.parseUserAgentString(userAgentString);
|
||||
} catch (UnrecognizedUserAgentException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
|
||||
public record CallQualitySurveyConfiguration (@Valid @NotNull PubSubPublisherFactory pubSubPublisher) {
|
||||
}
|
||||
-21
@@ -1,21 +0,0 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonTypeInfo;
|
||||
import io.dropwizard.jackson.Discoverable;
|
||||
import io.micrometer.statsd.StatsdConfig;
|
||||
import java.time.Duration;
|
||||
|
||||
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type", defaultImpl = DogstatsdConfiguration.class)
|
||||
public interface DatadogConfiguration extends StatsdConfig, Discoverable {
|
||||
|
||||
boolean enabled();
|
||||
|
||||
String getEnvironment();
|
||||
|
||||
Duration getShutdownWaitDuration();
|
||||
}
|
||||
-68
@@ -1,68 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.annotation.JsonTypeName;
|
||||
import io.micrometer.statsd.StatsdFlavor;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import java.time.Duration;
|
||||
|
||||
@JsonTypeName("default")
|
||||
public class DogstatsdConfiguration implements DatadogConfiguration {
|
||||
|
||||
@JsonProperty
|
||||
private boolean enabled = true;
|
||||
|
||||
@JsonProperty
|
||||
@NotNull
|
||||
private Duration step = Duration.ofSeconds(10);
|
||||
|
||||
@JsonProperty
|
||||
@NotBlank
|
||||
private String environment;
|
||||
|
||||
@JsonProperty
|
||||
@NotBlank
|
||||
private String host;
|
||||
|
||||
@Override
|
||||
public boolean enabled() {
|
||||
return enabled;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Duration step() {
|
||||
return step;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getEnvironment() {
|
||||
return environment;
|
||||
}
|
||||
|
||||
@Override
|
||||
public StatsdFlavor flavor() {
|
||||
return StatsdFlavor.DATADOG;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String get(final String key) {
|
||||
// We have no Micrometer key/value pairs to report, so always return `null`
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String host() {
|
||||
return host;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Duration getShutdownWaitDuration() {
|
||||
return step().plus(step.dividedBy(2));
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -50,7 +50,7 @@ public class DynamicConfiguration {
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
DynamicMetricsConfiguration metricsConfiguration = new DynamicMetricsConfiguration(false, false, null);
|
||||
DynamicMetricsConfiguration metricsConfiguration = new DynamicMetricsConfiguration(false, false);
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
|
||||
+1
-5
@@ -5,15 +5,11 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration.dynamic;
|
||||
|
||||
import java.util.Set;
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
/**
|
||||
* @param enableLettuceRemoteTag whether the `remote` tag should be added. Note: although this is dynamic, meters are
|
||||
* cached after creation, so changes will only affect servers launched after the change.
|
||||
* @param enableAwsSdkMetrics whether to record AWS SDK metrics. Note: although this is dynamic, meters are cached after
|
||||
* creation, so changes will only affect servers launched after the change.
|
||||
* @param datadogAllowList if present, a list of metrics to send to datadog; others will be filtered out. If null, this filtering is not performed.
|
||||
*/
|
||||
public record DynamicMetricsConfiguration(boolean enableLettuceRemoteTag, boolean enableAwsSdkMetrics, @Nullable Set<String> datadogAllowList) {
|
||||
public record DynamicMetricsConfiguration(boolean enableLettuceRemoteTag, boolean enableAwsSdkMetrics) {
|
||||
}
|
||||
+1
-1
@@ -177,7 +177,7 @@ public class AccountController {
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/registration_lock")
|
||||
public void setRegistrationLock(@Auth AuthenticatedDevice auth, @NotNull @Valid RegistrationLock accountLock) {
|
||||
final SaltedTokenHash credentials = SaltedTokenHash.generateFor(accountLock.getRegistrationLock());
|
||||
final SaltedTokenHash credentials = SaltedTokenHash.generateFor(accountLock.registrationLock());
|
||||
|
||||
final Account account = accounts.getByAccountIdentifier(auth.accountIdentifier())
|
||||
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
|
||||
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import com.google.common.net.HttpHeaders;
|
||||
import com.google.protobuf.InvalidProtocolBufferException;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.headers.Header;
|
||||
import io.swagger.v3.oas.annotations.parameters.RequestBody;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.ws.rs.Consumes;
|
||||
import jakarta.ws.rs.ForbiddenException;
|
||||
import jakarta.ws.rs.HeaderParam;
|
||||
import jakarta.ws.rs.PUT;
|
||||
import jakarta.ws.rs.Path;
|
||||
import jakarta.ws.rs.Produces;
|
||||
import jakarta.ws.rs.WebApplicationException;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.ws.rs.core.Context;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import java.util.Optional;
|
||||
import org.signal.chat.calling.quality.SubmitCallQualitySurveyRequest;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.filters.RemoteAddressFilter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimitedByIp;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.metrics.CallQualitySurveyManager;
|
||||
|
||||
@Path("/v1/call_quality_survey")
|
||||
@io.swagger.v3.oas.annotations.tags.Tag(name = "Call quality survey")
|
||||
public class CallQualitySurveyController {
|
||||
|
||||
private final CallQualitySurveyManager callQualitySurveyManager;
|
||||
|
||||
public CallQualitySurveyController(final CallQualitySurveyManager callQualitySurveyManager) {
|
||||
this.callQualitySurveyManager = callQualitySurveyManager;
|
||||
}
|
||||
|
||||
@PUT
|
||||
@Consumes(MediaType.APPLICATION_OCTET_STREAM)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Operation(summary = "Submit survey response", description = "Submits a call quality survey response")
|
||||
@ApiResponse(responseCode = "204", description = "The survey response was submitted successfully")
|
||||
@ApiResponse(responseCode = "422", description = "The survey response could not be parsed")
|
||||
@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"))
|
||||
@RateLimitedByIp(RateLimiters.For.SUBMIT_CALL_QUALITY_SURVERY)
|
||||
public void submitCallQualitySurvey(@Auth final Optional<AuthenticatedDevice> authenticatedDevice,
|
||||
@RequestBody(description = "A serialized survey response protobuf entity")
|
||||
@NotNull final byte[] surveyResponse,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgentString,
|
||||
@Context final ContainerRequestContext requestContext) {
|
||||
|
||||
if (authenticatedDevice.isPresent()) {
|
||||
throw new ForbiddenException("must not use authenticated connection for call quality survey submissions");
|
||||
}
|
||||
|
||||
final SubmitCallQualitySurveyRequest submitCallQualitySurveyRequest;
|
||||
|
||||
try {
|
||||
submitCallQualitySurveyRequest = SubmitCallQualitySurveyRequest.parseFrom(surveyResponse);
|
||||
} catch (final InvalidProtocolBufferException e) {
|
||||
throw new WebApplicationException("Invalid protobuf entity", 422);
|
||||
}
|
||||
|
||||
final String remoteAddress = (String) requestContext.getProperty(RemoteAddressFilter.REMOTE_ADDRESS_ATTRIBUTE_NAME);
|
||||
|
||||
try {
|
||||
callQualitySurveyManager.submitCallQualitySurvey(submitCallQualitySurveyRequest, remoteAddress, userAgentString);
|
||||
} catch (final IllegalArgumentException e) {
|
||||
throw new WebApplicationException(e.getMessage(), 422);
|
||||
}
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -5,7 +5,7 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.dropwizard.auth.Auth;
|
||||
@@ -55,7 +55,7 @@ public class CertificateController {
|
||||
|
||||
@VisibleForTesting
|
||||
public static final Duration MAX_REDEMPTION_DURATION = Duration.ofDays(7);
|
||||
private static final String GENERATE_DELIVERY_CERTIFICATE_COUNTER_NAME = name(CertificateGenerator.class, "generateCertificate");
|
||||
private static final String GENERATE_DELIVERY_CERTIFICATE_COUNTER_NAME = name(CertificateController.class, "generateCertificate");
|
||||
private static final String INCLUDE_E164_TAG_NAME = "includeE164";
|
||||
|
||||
public CertificateController(
|
||||
|
||||
+1
-1
@@ -251,7 +251,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"))
|
||||
public LinkDeviceResponse linkDevice(@HeaderParam(HttpHeaders.AUTHORIZATION) BasicAuthorizationHeader authorizationHeader,
|
||||
public LinkDeviceResponse linkDevice(@HeaderParam(HttpHeaders.AUTHORIZATION) @NotNull BasicAuthorizationHeader authorizationHeader,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) @Nullable String userAgent,
|
||||
@NotNull @Valid LinkDeviceRequest linkDeviceRequest)
|
||||
throws RateLimitExceededException, DeviceLimitExceededException {
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
|
||||
+8
-3
@@ -76,8 +76,10 @@ public class KeyTransparencyController {
|
||||
)
|
||||
@ApiResponse(responseCode = "200", description = "The ACI was found and its mapped value matched the provided ACI identity key", useReturnTypeSchema = true)
|
||||
@ApiResponse(responseCode = "400", description = "Invalid request. See response for any available details.")
|
||||
@ApiResponse(responseCode = "403", description = "The ACI was found but its mapped value did not match the provided ACI identity key")
|
||||
@ApiResponse(responseCode = "404", description = "The ACI was not found in the log")
|
||||
@ApiResponse(responseCode = "403", description = """
|
||||
The ACI was found but its mapped value did not match the provided ACI identity key
|
||||
or the ACI was not found in the log.
|
||||
""")
|
||||
@ApiResponse(responseCode = "422", description = "Invalid request format")
|
||||
@ApiResponse(responseCode = "429", description = "Rate-limited")
|
||||
@POST
|
||||
@@ -108,7 +110,10 @@ public class KeyTransparencyController {
|
||||
request.usernameHash().map(ByteString::copyFrom),
|
||||
maybeE164SearchRequest,
|
||||
request.lastTreeHeadSize(),
|
||||
request.distinguishedTreeHeadSize())
|
||||
request.distinguishedTreeHeadSize(),
|
||||
request.aciVersion(),
|
||||
request.e164Version(),
|
||||
request.usernameHashVersion())
|
||||
.toByteArray());
|
||||
} catch (final StatusRuntimeException exception) {
|
||||
handleKeyTransparencyServiceError(exception);
|
||||
|
||||
+6
-40
@@ -4,7 +4,7 @@
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.google.common.net.HttpHeaders;
|
||||
import io.dropwizard.auth.Auth;
|
||||
@@ -21,7 +21,6 @@ import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.ws.rs.BadRequestException;
|
||||
import jakarta.ws.rs.Consumes;
|
||||
import jakarta.ws.rs.DELETE;
|
||||
import jakarta.ws.rs.DefaultValue;
|
||||
import jakarta.ws.rs.GET;
|
||||
import jakarta.ws.rs.HeaderParam;
|
||||
@@ -74,7 +73,6 @@ import org.whispersystems.textsecuregcm.entities.AccountStaleDevices;
|
||||
import org.whispersystems.textsecuregcm.entities.IncomingMessage;
|
||||
import org.whispersystems.textsecuregcm.entities.IncomingMessageList;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope.Type;
|
||||
import org.whispersystems.textsecuregcm.entities.MismatchedDevicesResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.OutgoingMessageEntity;
|
||||
import org.whispersystems.textsecuregcm.entities.OutgoingMessageEntityList;
|
||||
@@ -97,7 +95,6 @@ import org.whispersystems.textsecuregcm.push.MessageTooLargeException;
|
||||
import org.whispersystems.textsecuregcm.push.MessageUtil;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationScheduler;
|
||||
import org.whispersystems.textsecuregcm.push.ReceiptSender;
|
||||
import org.whispersystems.textsecuregcm.spam.MessageType;
|
||||
import org.whispersystems.textsecuregcm.spam.SpamCheckResult;
|
||||
import org.whispersystems.textsecuregcm.spam.SpamChecker;
|
||||
@@ -123,7 +120,6 @@ public class MessageController {
|
||||
private final RateLimiters rateLimiters;
|
||||
private final CardinalityEstimator messageByteLimitEstimator;
|
||||
private final MessageSender messageSender;
|
||||
private final ReceiptSender receiptSender;
|
||||
private final AccountsManager accountsManager;
|
||||
private final MessagesManager messagesManager;
|
||||
private final PhoneNumberIdentifiers phoneNumberIdentifiers;
|
||||
@@ -177,7 +173,6 @@ public class MessageController {
|
||||
RateLimiters rateLimiters,
|
||||
CardinalityEstimator messageByteLimitEstimator,
|
||||
MessageSender messageSender,
|
||||
ReceiptSender receiptSender,
|
||||
AccountsManager accountsManager,
|
||||
MessagesManager messagesManager,
|
||||
PhoneNumberIdentifiers phoneNumberIdentifiers,
|
||||
@@ -194,7 +189,6 @@ public class MessageController {
|
||||
this.rateLimiters = rateLimiters;
|
||||
this.messageByteLimitEstimator = messageByteLimitEstimator;
|
||||
this.messageSender = messageSender;
|
||||
this.receiptSender = receiptSender;
|
||||
this.accountsManager = accountsManager;
|
||||
this.messagesManager = messagesManager;
|
||||
this.phoneNumberIdentifiers = phoneNumberIdentifiers;
|
||||
@@ -221,7 +215,10 @@ public class MessageController {
|
||||
Deliver a message to a single recipient. May be authenticated or unauthenticated; if unauthenticated,
|
||||
an unidentifed-access key or group-send endorsement token must be provided, unless the message is a story.
|
||||
""")
|
||||
@ApiResponse(responseCode="200", description="Message was successfully sent", useReturnTypeSchema=true)
|
||||
@ApiResponse(
|
||||
responseCode="200",
|
||||
description="Message was successfully sent",
|
||||
content = @Content(schema = @Schema(implementation = SendMessageResponse.class)))
|
||||
@ApiResponse(
|
||||
responseCode="401",
|
||||
description="The message is not a story and the authorization, unauthorized access key, or group send endorsement token is missing or incorrect")
|
||||
@@ -247,7 +244,7 @@ public class MessageController {
|
||||
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
|
||||
|
||||
@Parameter(description="If true, deliver the message only to recipients that are online when it is sent")
|
||||
@Parameter(description="The recipient’s account or phone-number identifier")
|
||||
@PathParam("destination") final ServiceIdentifier destinationIdentifier,
|
||||
|
||||
@Parameter(description="If true, the message is a story; access tokens are not checked and sending to nonexistent recipients is permitted")
|
||||
@@ -840,37 +837,6 @@ public class MessageController {
|
||||
return size;
|
||||
}
|
||||
|
||||
@DELETE
|
||||
@Path("/uuid/{uuid}")
|
||||
public CompletableFuture<Response> removePendingMessage(@Auth AuthenticatedDevice auth, @PathParam("uuid") UUID uuid) {
|
||||
final Account account = accountsManager.getByAccountIdentifier(auth.accountIdentifier())
|
||||
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
|
||||
|
||||
final Device device = account.getDevice(auth.deviceId())
|
||||
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
|
||||
|
||||
return messagesManager.delete(auth.accountIdentifier(), device, uuid, null)
|
||||
.thenAccept(maybeRemovedMessage -> maybeRemovedMessage.ifPresent(removedMessage -> {
|
||||
if (removedMessage.sourceServiceId().isPresent()
|
||||
&& removedMessage.envelopeType() != Type.SERVER_DELIVERY_RECEIPT) {
|
||||
if (removedMessage.sourceServiceId().get() instanceof AciServiceIdentifier aciServiceIdentifier) {
|
||||
try {
|
||||
receiptSender.sendReceipt(removedMessage.destinationServiceId(), auth.deviceId(),
|
||||
aciServiceIdentifier, removedMessage.clientTimestamp());
|
||||
} catch (Exception e) {
|
||||
logger.warn("Failed to send delivery receipt", e);
|
||||
}
|
||||
} else {
|
||||
// If source service ID is present and the envelope type is not a server delivery receipt, then
|
||||
// the source service ID *should always* be an ACI -- PNIs are receive-only, so they can only be the
|
||||
// "source" via server delivery receipts
|
||||
logger.warn("Source service ID unexpectedly a PNI service ID");
|
||||
}
|
||||
}
|
||||
}))
|
||||
.thenApply(Util.ASYNC_EMPTY_RESPONSE);
|
||||
}
|
||||
|
||||
@POST
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Path("/report/{source}/{messageGuid}")
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.common.net.HttpHeaders;
|
||||
|
||||
+2
-1
@@ -92,7 +92,8 @@ public class RegistrationController {
|
||||
2. gets 409 from device available for transfer \n
|
||||
3. success \n
|
||||
""")
|
||||
@ApiResponse(responseCode = "200", description = "The phone number associated with the authenticated account was changed successfully", useReturnTypeSchema = true)
|
||||
@ApiResponse(responseCode = "200", description = "Account creation succeeded", useReturnTypeSchema = true)
|
||||
@ApiResponse(responseCode = "401", description = "The session identified in the request is not verified")
|
||||
@ApiResponse(responseCode = "403", description = "Verification failed for the provided Registration Recovery Password")
|
||||
@ApiResponse(responseCode = "409", description = "The caller has not explicitly elected to skip transferring data from another device, but a device transfer is technically possible")
|
||||
@ApiResponse(responseCode = "422", description = "The request did not pass validation")
|
||||
|
||||
-107
@@ -1,107 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.ws.rs.GET;
|
||||
import jakarta.ws.rs.Path;
|
||||
import jakarta.ws.rs.Produces;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.time.Clock;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.entities.UserRemoteConfig;
|
||||
import org.whispersystems.textsecuregcm.entities.UserRemoteConfigList;
|
||||
import org.whispersystems.textsecuregcm.storage.RemoteConfigsManager;
|
||||
import org.whispersystems.textsecuregcm.util.Conversions;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
@Path("/v1/config")
|
||||
@Tag(name = "Remote Config")
|
||||
public class RemoteConfigControllerV1 {
|
||||
|
||||
private final RemoteConfigsManager remoteConfigsManager;
|
||||
private final Map<String, String> globalConfig;
|
||||
|
||||
private final Clock clock;
|
||||
|
||||
private static final String GLOBAL_CONFIG_PREFIX = "global.";
|
||||
|
||||
public RemoteConfigControllerV1(RemoteConfigsManager remoteConfigsManager,
|
||||
Map<String, String> globalConfig,
|
||||
final Clock clock) {
|
||||
this.remoteConfigsManager = remoteConfigsManager;
|
||||
this.globalConfig = globalConfig;
|
||||
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Deprecated
|
||||
@Operation(
|
||||
summary = "Fetch remote configuration (deprecated)",
|
||||
description = """
|
||||
Remote configuration is a list of namespaced keys that clients may use for consistent configuration or behavior.
|
||||
|
||||
Configuration values change over time, and the list should be refreshed periodically, typically at client
|
||||
launch and every few hours thereafter.
|
||||
|
||||
This endpoint is deprecated; use GET /v2/config instead
|
||||
"""
|
||||
)
|
||||
@ApiResponse(responseCode = "200", description = "Remote configuration values for the authenticated user", useReturnTypeSchema = true)
|
||||
public UserRemoteConfigList getAll(@Auth AuthenticatedDevice auth) {
|
||||
try {
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||
|
||||
final Stream<UserRemoteConfig> globalConfigStream = globalConfig.entrySet().stream()
|
||||
.map(entry -> new UserRemoteConfig(GLOBAL_CONFIG_PREFIX + entry.getKey(), true, entry.getValue()));
|
||||
return new UserRemoteConfigList(Stream.concat(remoteConfigsManager.getAll().stream().map(config -> {
|
||||
final byte[] hashKey = config.getHashKey() != null ? config.getHashKey().getBytes(StandardCharsets.UTF_8)
|
||||
: config.getName().getBytes(StandardCharsets.UTF_8);
|
||||
boolean inBucket = isInBucket(digest, auth.accountIdentifier(), hashKey, config.getPercentage(),
|
||||
config.getUuids());
|
||||
return new UserRemoteConfig(config.getName(), inBucket,
|
||||
inBucket ? config.getValue() : config.getDefaultValue());
|
||||
}), globalConfigStream).collect(Collectors.toList()), clock.instant());
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
public static boolean isInBucket(MessageDigest digest, UUID uid, byte[] hashKey, int configPercentage,
|
||||
Set<UUID> uuidsInBucket) {
|
||||
if (uuidsInBucket.contains(uid)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
|
||||
bb.putLong(uid.getMostSignificantBits());
|
||||
bb.putLong(uid.getLeastSignificantBits());
|
||||
|
||||
digest.update(bb.array());
|
||||
|
||||
byte[] hash = digest.digest(hashKey);
|
||||
int bucket = (int) (Util.ensureNonNegativeLong(Conversions.byteArrayToLong(hash)) % 100);
|
||||
|
||||
return bucket < configPercentage;
|
||||
}
|
||||
|
||||
}
|
||||
+2
@@ -193,6 +193,8 @@ public class VerificationController {
|
||||
|
||||
registrationServiceSession = registrationServiceClient.createRegistrationSession(phoneNumber, sourceHost,
|
||||
accountsManager.getByE164(request.number()).isPresent(),
|
||||
request.updateVerificationSessionRequest().mcc(),
|
||||
request.updateVerificationSessionRequest().mnc(),
|
||||
REGISTRATION_RPC_TIMEOUT).join();
|
||||
} catch (final CancellationException e) {
|
||||
|
||||
|
||||
+3
-3
@@ -205,11 +205,11 @@ public class CurrencyConversionManager implements Managed {
|
||||
|
||||
private void updateCachedData(final String cacheKey, final Map<String, BigDecimal> data) {
|
||||
cacheCluster.useCluster(connection -> {
|
||||
final Map<String, String> sharedCoinGeckoValues = new HashMap<>();
|
||||
final Map<String, String> sharedValues = new HashMap<>();
|
||||
|
||||
data.forEach((currency, conversionRate) -> sharedCoinGeckoValues.put(currency, conversionRate.toString()));
|
||||
data.forEach((currency, conversionRate) -> sharedValues.put(currency, conversionRate.toString()));
|
||||
|
||||
connection.sync().hset(cacheKey, sharedCoinGeckoValues);
|
||||
connection.sync().hset(cacheKey, sharedValues);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
+3
-3
@@ -4,7 +4,7 @@
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonCreator;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
@@ -34,7 +34,7 @@ public record IncomingMessageList(@NotNull
|
||||
|
||||
private static final Counter REJECT_DUPLICATE_RECIPIENT_COUNTER =
|
||||
Metrics.counter(
|
||||
name(MessageController.class, "rejectDuplicateRecipients"),
|
||||
name(IncomingMessageList.class, "rejectDuplicateRecipients"),
|
||||
"multiRecipient", "false");
|
||||
|
||||
@JsonCreator
|
||||
@@ -48,7 +48,7 @@ public record IncomingMessageList(@NotNull
|
||||
|
||||
@AssertTrue
|
||||
@Schema(hidden = true)
|
||||
public boolean hasNoDuplicateRecipients() {
|
||||
public boolean isNotDuplicateRecipients() {
|
||||
final boolean valid = messages.stream()
|
||||
.filter(Objects::nonNull)
|
||||
.map(IncomingMessage::destinationDeviceId).distinct().count() == messages.size();
|
||||
|
||||
+4
-3
@@ -14,6 +14,7 @@ import jakarta.validation.constraints.NotEmpty;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Positive;
|
||||
import java.util.Optional;
|
||||
import jakarta.validation.constraints.PositiveOrZero;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
|
||||
import org.whispersystems.textsecuregcm.util.ByteArrayBase64UrlAdapter;
|
||||
@@ -49,7 +50,7 @@ public record KeyTransparencyMonitorRequest(
|
||||
AciServiceIdentifier value,
|
||||
|
||||
@Schema(description = "A log tree position maintained by the client for the aci.")
|
||||
@Positive
|
||||
@PositiveOrZero
|
||||
long entryPosition,
|
||||
|
||||
@Schema(description = "The commitment index derived from a previous search request, encoded in standard unpadded base64")
|
||||
@@ -66,7 +67,7 @@ public record KeyTransparencyMonitorRequest(
|
||||
String value,
|
||||
|
||||
@Schema(description = "A log tree position maintained by the client for the e164.")
|
||||
@Positive
|
||||
@PositiveOrZero
|
||||
long entryPosition,
|
||||
|
||||
@Schema(description = "The commitment index derived from a previous search request, encoded in standard unpadded base64")
|
||||
@@ -87,7 +88,7 @@ public record KeyTransparencyMonitorRequest(
|
||||
byte[] value,
|
||||
|
||||
@Schema(description = "A log tree position maintained by the client for the username hash.")
|
||||
@Positive
|
||||
@PositiveOrZero
|
||||
long entryPosition,
|
||||
|
||||
@Schema(description = "The commitment index derived from a previous search request, encoded in standard unpadded base64")
|
||||
|
||||
+15
-1
@@ -9,6 +9,8 @@ import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.constraints.AssertTrue;
|
||||
import jakarta.validation.constraints.Max;
|
||||
import jakarta.validation.constraints.Min;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Positive;
|
||||
import java.util.Optional;
|
||||
@@ -51,8 +53,20 @@ public record KeyTransparencySearchRequest(
|
||||
Optional<@Positive Long> lastTreeHeadSize,
|
||||
|
||||
@Schema(description = "The distinguished tree head size to prove consistency against.")
|
||||
@Positive long distinguishedTreeHeadSize
|
||||
@Positive long distinguishedTreeHeadSize,
|
||||
|
||||
@Schema(description = "The version of the ACI to look up.")
|
||||
Optional<@Max(MAX_UINT32) @Min(0) Long> aciVersion,
|
||||
|
||||
@Schema(description = "The version of the E164 to look up.")
|
||||
Optional<@Max(MAX_UINT32) @Min(0) Long> e164Version,
|
||||
|
||||
@Schema(description = "The version of the username hash to look up.")
|
||||
Optional<@Max(MAX_UINT32) @Min(0) Long> usernameHashVersion
|
||||
) {
|
||||
// This is the max value for a protobuf uint32 field
|
||||
private static final long MAX_UINT32 = 0xFFFFFFFFL;
|
||||
|
||||
@AssertTrue
|
||||
@Schema(hidden = true)
|
||||
public boolean isUnidentifiedAccessKeyProvidedWithE164() {
|
||||
|
||||
+1
-1
@@ -43,7 +43,7 @@ public record LinkDeviceRequest(@Schema(requiredMode = Schema.RequiredMode.REQUI
|
||||
|
||||
@AssertTrue
|
||||
@Schema(hidden = true)
|
||||
public boolean hasExactlyOneMessageDeliveryChannel() {
|
||||
public boolean isExactlyOneMessageDeliveryChannel() {
|
||||
if (accountAttributes.getFetchesMessages()) {
|
||||
return deviceActivationRequest().apnToken().isEmpty() && deviceActivationRequest().gcmToken().isEmpty();
|
||||
} else {
|
||||
|
||||
+1
-19
@@ -6,26 +6,8 @@
|
||||
package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
public class RegistrationLock {
|
||||
|
||||
@JsonProperty
|
||||
@Size(min=64, max=64)
|
||||
@NotEmpty
|
||||
private String registrationLock;
|
||||
|
||||
public RegistrationLock() {}
|
||||
|
||||
@VisibleForTesting
|
||||
public RegistrationLock(String registrationLock) {
|
||||
this.registrationLock = registrationLock;
|
||||
}
|
||||
|
||||
public String getRegistrationLock() {
|
||||
return registrationLock;
|
||||
}
|
||||
|
||||
public record RegistrationLock(@JsonProperty @Size(min = 64, max = 64) @NotEmpty String registrationLock) {
|
||||
}
|
||||
+1
-1
@@ -88,7 +88,7 @@ public record RegistrationRequest(@Schema(requiredMode = Schema.RequiredMode.NOT
|
||||
@VisibleForTesting
|
||||
@AssertTrue
|
||||
@Schema(hidden = true)
|
||||
boolean hasExactlyOneMessageDeliveryChannel() {
|
||||
boolean isExactlyOneMessageDeliveryChannel() {
|
||||
if (deviceActivationRequest == null || accountAttributes == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
+1
-1
@@ -105,7 +105,7 @@ public class ExperimentEnrollmentManager {
|
||||
}).orElse(false);
|
||||
}
|
||||
|
||||
private boolean isEnrolled(final Object entity, final int enrollmentPercentage, final String experimentName) {
|
||||
private static boolean isEnrolled(final Object entity, final int enrollmentPercentage, final String experimentName) {
|
||||
final int enrollmentHash = ((entity.hashCode() ^ experimentName.hashCode()) & Integer.MAX_VALUE) % 100;
|
||||
|
||||
return enrollmentHash < enrollmentPercentage;
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.filters;
|
||||
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.google.common.net.HttpHeaders;
|
||||
import com.vdurmont.semver4j.Semver;
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.filters;
|
||||
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
import static java.util.Objects.requireNonNull;
|
||||
|
||||
import com.google.common.net.InetAddresses;
|
||||
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import io.grpc.Status;
|
||||
import io.grpc.StatusRuntimeException;
|
||||
import org.signal.chat.calling.quality.SimpleCallQualityGrpc;
|
||||
import org.signal.chat.calling.quality.SubmitCallQualitySurveyRequest;
|
||||
import org.signal.chat.calling.quality.SubmitCallQualitySurveyResponse;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.metrics.CallQualitySurveyManager;
|
||||
|
||||
public class CallQualitySurveyGrpcService extends SimpleCallQualityGrpc.CallQualityImplBase {
|
||||
|
||||
private final CallQualitySurveyManager callQualitySurveyManager;
|
||||
private final RateLimiters rateLimiters;
|
||||
|
||||
public CallQualitySurveyGrpcService(final CallQualitySurveyManager callQualitySurveyManager,
|
||||
final RateLimiters rateLimiters) {
|
||||
|
||||
this.callQualitySurveyManager = callQualitySurveyManager;
|
||||
this.rateLimiters = rateLimiters;
|
||||
}
|
||||
|
||||
@Override
|
||||
public SubmitCallQualitySurveyResponse submitCallQualitySurvey(final SubmitCallQualitySurveyRequest request)
|
||||
throws RateLimitExceededException {
|
||||
|
||||
final String remoteAddress = RequestAttributesUtil.getRemoteAddress().getHostAddress();
|
||||
|
||||
rateLimiters.getSubmitCallQualitySurveyLimiter().validate(remoteAddress);
|
||||
|
||||
try {
|
||||
callQualitySurveyManager.submitCallQualitySurvey(request,
|
||||
remoteAddress,
|
||||
RequestAttributesUtil.getUserAgent().orElse(null));
|
||||
} catch (final IllegalArgumentException e) {
|
||||
throw Status.INVALID_ARGUMENT.withDescription(e.getMessage()).asRuntimeException();
|
||||
}
|
||||
|
||||
return SubmitCallQualitySurveyResponse.getDefaultInstance();
|
||||
}
|
||||
}
|
||||
@@ -17,8 +17,6 @@ public class DeviceCapabilityUtil {
|
||||
return switch (grpcDeviceCapability) {
|
||||
case DEVICE_CAPABILITY_STORAGE -> DeviceCapability.STORAGE;
|
||||
case DEVICE_CAPABILITY_TRANSFER -> DeviceCapability.TRANSFER;
|
||||
case DEVICE_CAPABILITY_DELETE_SYNC -> DeviceCapability.DELETE_SYNC;
|
||||
case DEVICE_CAPABILITY_STORAGE_SERVICE_RECORD_KEY_ROTATION -> DeviceCapability.STORAGE_SERVICE_RECORD_KEY_ROTATION;
|
||||
case DEVICE_CAPABILITY_ATTACHMENT_BACKFILL -> DeviceCapability.ATTACHMENT_BACKFILL;
|
||||
case DEVICE_CAPABILITY_SPARSE_POST_QUANTUM_RATCHET -> DeviceCapability.SPARSE_POST_QUANTUM_RATCHET;
|
||||
case DEVICE_CAPABILITY_UNSPECIFIED, UNRECOGNIZED -> throw Status.INVALID_ARGUMENT.withDescription("Unrecognized device capability").asRuntimeException();
|
||||
@@ -29,8 +27,6 @@ public class DeviceCapabilityUtil {
|
||||
return switch (deviceCapability) {
|
||||
case STORAGE -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_STORAGE;
|
||||
case TRANSFER -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_TRANSFER;
|
||||
case DELETE_SYNC -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_DELETE_SYNC;
|
||||
case STORAGE_SERVICE_RECORD_KEY_ROTATION -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_STORAGE_SERVICE_RECORD_KEY_ROTATION;
|
||||
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;
|
||||
};
|
||||
|
||||
+8
-1
@@ -116,7 +116,10 @@ public class KeyTransparencyServiceClient implements Managed {
|
||||
final Optional<ByteString> usernameHash,
|
||||
final Optional<E164SearchRequest> e164SearchRequest,
|
||||
final Optional<Long> lastTreeHeadSize,
|
||||
final long distinguishedTreeHeadSize) {
|
||||
final long distinguishedTreeHeadSize,
|
||||
final Optional<Long> aciVersion,
|
||||
final Optional<Long> e164Version,
|
||||
final Optional<Long> usernameHashVersion) {
|
||||
final SearchRequest.Builder searchRequestBuilder = SearchRequest.newBuilder()
|
||||
.setAci(aci)
|
||||
.setAciIdentityKey(aciIdentityKey);
|
||||
@@ -124,6 +127,10 @@ public class KeyTransparencyServiceClient implements Managed {
|
||||
usernameHash.ifPresent(searchRequestBuilder::setUsernameHash);
|
||||
e164SearchRequest.ifPresent(searchRequestBuilder::setE164SearchRequest);
|
||||
|
||||
aciVersion.ifPresent(version -> searchRequestBuilder.setAciVersion(version.intValue()));
|
||||
e164Version.ifPresent(version -> searchRequestBuilder.setE164Version(version.intValue()));
|
||||
usernameHashVersion.ifPresent(version -> searchRequestBuilder.setUsernameHashVersion(version.intValue()));
|
||||
|
||||
final ConsistencyParameters.Builder consistency = ConsistencyParameters.newBuilder()
|
||||
.setDistinguished(distinguishedTreeHeadSize);
|
||||
lastTreeHeadSize.ifPresent(consistency::setLast);
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.limits;
|
||||
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.security.SecureRandom;
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.limits;
|
||||
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
|
||||
+1
-1
@@ -17,7 +17,7 @@ public record RateLimiterConfig(int bucketSize, Duration permitRegenerationDurat
|
||||
|
||||
@AssertTrue
|
||||
@Schema(hidden = true)
|
||||
public boolean hasPositiveRegenerationRate() {
|
||||
public boolean isPositiveRegenerationRate() {
|
||||
try {
|
||||
return permitRegenerationDuration.toNanos() > 0;
|
||||
} catch (final ArithmeticException e) {
|
||||
|
||||
@@ -56,6 +56,7 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
|
||||
RECORD_DEVICE_TRANSFER_REQUEST("recordDeviceTransferRequest", new RateLimiterConfig(10, Duration.ofMillis(100), true)),
|
||||
WAIT_FOR_DEVICE_TRANSFER_REQUEST("waitForDeviceTransferRequest", new RateLimiterConfig(10, Duration.ofMillis(100), true)),
|
||||
DEVICE_CHECK_CHALLENGE("deviceCheckChallenge", new RateLimiterConfig(10, Duration.ofMinutes(1), false)),
|
||||
SUBMIT_CALL_QUALITY_SURVERY("submitCallQualitySurvey", new RateLimiterConfig(100, Duration.ofMinutes(1), true))
|
||||
;
|
||||
|
||||
private final String id;
|
||||
@@ -221,4 +222,8 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
|
||||
public RateLimiter getKeyTransparencyMonitorLimiter() {
|
||||
return forDescriptor(For.KEY_TRANSPARENCY_MONITOR_PER_IP);
|
||||
}
|
||||
|
||||
public RateLimiter getSubmitCallQualitySurveyLimiter() {
|
||||
return forDescriptor(For.SUBMIT_CALL_QUALITY_SURVERY);
|
||||
}
|
||||
}
|
||||
+23
-5
@@ -6,31 +6,49 @@
|
||||
package org.whispersystems.textsecuregcm.metrics;
|
||||
|
||||
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import io.micrometer.core.instrument.Gauge;
|
||||
import io.micrometer.core.instrument.MeterRegistry;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import org.eclipse.jetty.util.component.LifeCycle;
|
||||
import org.eclipse.jetty.util.component.AbstractLifeCycle;
|
||||
import org.eclipse.jetty.util.thread.ShutdownThread;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* A managed monitor that reports whether the application is shutting down as a metric. That metric can then be used in
|
||||
* conjunction with other indicators to conditionally fire or suppress alerts.
|
||||
*/
|
||||
public class ApplicationShutdownMonitor implements LifeCycle.Listener {
|
||||
public class ApplicationShutdownMonitor extends AbstractLifeCycle {
|
||||
|
||||
private final AtomicBoolean shuttingDown = new AtomicBoolean(false);
|
||||
private final Logger logger = LoggerFactory.getLogger(ApplicationShutdownMonitor.class);
|
||||
|
||||
public ApplicationShutdownMonitor(final MeterRegistry meterRegistry) {
|
||||
// without a strong reference to the gauge’s value supplier, shutdown garbage collection
|
||||
// might prevent the final value from being reported
|
||||
Gauge.builder(name(getClass().getSimpleName(), "shuttingDown"), () -> shuttingDown.get() ? 1 : 0)
|
||||
Gauge.builder(name(getClass(), "shuttingDown"), () -> shuttingDown.get() ? 1 : 0)
|
||||
.strongReference(true)
|
||||
.register(meterRegistry);
|
||||
}
|
||||
|
||||
public void register() {
|
||||
// Force this component to get shut down before Dropwizard's
|
||||
// DelayedShutdownHandler, which initiates the delayed-shutdown process
|
||||
// without an additional chance for us to hook it
|
||||
logger.info("registering shutdown monitor");
|
||||
try {
|
||||
start(); // jetty won't stop an unstarted lifecycle
|
||||
ShutdownThread.register(0, this);
|
||||
} catch (Exception e) {
|
||||
logger.error("failed to start application shutdown monitor", e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void lifeCycleStopping(final LifeCycle event) {
|
||||
public void doStop() {
|
||||
logger.info("setting shutdown flag");
|
||||
shuttingDown.set(true);
|
||||
}
|
||||
}
|
||||
+170
@@ -0,0 +1,170 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.metrics;
|
||||
|
||||
import com.google.cloud.pubsub.v1.PublisherInterface;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.pubsub.v1.PubsubMessage;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.time.Clock;
|
||||
import java.util.Locale;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.function.Supplier;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.signal.calling.survey.CallQualitySurveyResponsePubSubMessage;
|
||||
import org.signal.chat.calling.quality.SubmitCallQualitySurveyRequest;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.asn.AsnInfoProvider;
|
||||
import org.whispersystems.textsecuregcm.util.GoogleApiUtil;
|
||||
import org.whispersystems.textsecuregcm.util.ua.UnrecognizedUserAgentException;
|
||||
import org.whispersystems.textsecuregcm.util.ua.UserAgent;
|
||||
import org.whispersystems.textsecuregcm.util.ua.UserAgentUtil;
|
||||
|
||||
public class CallQualitySurveyManager {
|
||||
|
||||
private final Supplier<AsnInfoProvider> asnInfoProviderSupplier;
|
||||
private final PublisherInterface pubSubPublisher;
|
||||
private final Clock clock;
|
||||
private final Executor pubSubCallbackExecutor;
|
||||
|
||||
private final String PUB_SUB_MESSAGE_COUNTER_NAME = MetricsUtil.name(CallQualitySurveyManager.class, "pubSubMessage");
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(CallQualitySurveyManager.class);
|
||||
|
||||
public CallQualitySurveyManager(final Supplier<AsnInfoProvider> asnInfoProviderSupplier,
|
||||
final PublisherInterface pubSubPublisher,
|
||||
final Clock clock,
|
||||
final Executor pubSubCallbackExecutor) {
|
||||
|
||||
this.asnInfoProviderSupplier = asnInfoProviderSupplier;
|
||||
this.pubSubPublisher = pubSubPublisher;
|
||||
this.clock = clock;
|
||||
this.pubSubCallbackExecutor = pubSubCallbackExecutor;
|
||||
}
|
||||
|
||||
public void submitCallQualitySurvey(final SubmitCallQualitySurveyRequest submitCallQualitySurveyRequest,
|
||||
final String remoteAddress,
|
||||
final String userAgentString) {
|
||||
|
||||
final CallQualitySurveyResponsePubSubMessage.Builder pubSubMessageBuilder =
|
||||
CallQualitySurveyResponsePubSubMessage.newBuilder()
|
||||
.setResponseId(UUID.randomUUID().toString())
|
||||
.setSubmissionTimestamp(clock.millis() * 1000)
|
||||
.setUserSatisfied(submitCallQualitySurveyRequest.getUserSatisfied())
|
||||
// We receive timestamps as milliseconds since the epoch, but the backing data store wants microseconds
|
||||
.setStartTimestamp(submitCallQualitySurveyRequest.getStartTimestamp() * 1_000)
|
||||
.setEndTimestamp(submitCallQualitySurveyRequest.getEndTimestamp() * 1_000)
|
||||
.setCallType(submitCallQualitySurveyRequest.getCallType())
|
||||
.setSuccess(submitCallQualitySurveyRequest.getSuccess())
|
||||
.setCallEndReason(submitCallQualitySurveyRequest.getCallEndReason());
|
||||
|
||||
try {
|
||||
final UserAgent userAgent = UserAgentUtil.parseUserAgentString(userAgentString);
|
||||
|
||||
pubSubMessageBuilder.setClientPlatform(userAgent.platform().name().toLowerCase(Locale.ROOT));
|
||||
pubSubMessageBuilder.setClientVersion(userAgent.version().toString());
|
||||
|
||||
if (StringUtils.isNotBlank(userAgent.additionalSpecifiers())) {
|
||||
pubSubMessageBuilder.setClientUaAdditionalSpecifiers(userAgent.additionalSpecifiers());
|
||||
}
|
||||
} catch (final UnrecognizedUserAgentException _) {
|
||||
}
|
||||
|
||||
asnInfoProviderSupplier.get().lookup(remoteAddress)
|
||||
.ifPresent(asnInfo -> pubSubMessageBuilder.setAsnRegion(asnInfo.regionCode()));
|
||||
|
||||
pubSubMessageBuilder.addAllCallQualityIssues(submitCallQualitySurveyRequest.getCallQualityIssuesList());
|
||||
|
||||
if (submitCallQualitySurveyRequest.hasAdditionalIssuesDescription()) {
|
||||
pubSubMessageBuilder.setAdditionalIssuesDescription(submitCallQualitySurveyRequest.getAdditionalIssuesDescription());
|
||||
}
|
||||
|
||||
if (submitCallQualitySurveyRequest.hasDebugLogUrl()) {
|
||||
pubSubMessageBuilder.setDebugLogUrl(submitCallQualitySurveyRequest.getDebugLogUrl());
|
||||
}
|
||||
|
||||
if (submitCallQualitySurveyRequest.hasConnectionRttMedian()) {
|
||||
pubSubMessageBuilder.setConnectionRttMedian(submitCallQualitySurveyRequest.getConnectionRttMedian());
|
||||
}
|
||||
|
||||
if (submitCallQualitySurveyRequest.hasAudioRttMedian()) {
|
||||
pubSubMessageBuilder.setAudioRttMedian(submitCallQualitySurveyRequest.getAudioRttMedian());
|
||||
}
|
||||
|
||||
if (submitCallQualitySurveyRequest.hasVideoRttMedian()) {
|
||||
pubSubMessageBuilder.setVideoRttMedian(submitCallQualitySurveyRequest.getVideoRttMedian());
|
||||
}
|
||||
|
||||
if (submitCallQualitySurveyRequest.hasAudioRecvJitterMedian()) {
|
||||
pubSubMessageBuilder.setAudioRecvJitterMedian(submitCallQualitySurveyRequest.getAudioRecvJitterMedian());
|
||||
}
|
||||
|
||||
if (submitCallQualitySurveyRequest.hasVideoRecvJitterMedian()) {
|
||||
pubSubMessageBuilder.setVideoRecvJitterMedian(submitCallQualitySurveyRequest.getVideoRecvJitterMedian());
|
||||
}
|
||||
|
||||
if (submitCallQualitySurveyRequest.hasAudioSendJitterMedian()) {
|
||||
pubSubMessageBuilder.setAudioSendJitterMedian(submitCallQualitySurveyRequest.getAudioSendJitterMedian());
|
||||
}
|
||||
|
||||
if (submitCallQualitySurveyRequest.hasVideoSendJitterMedian()) {
|
||||
pubSubMessageBuilder.setVideoSendJitterMedian(submitCallQualitySurveyRequest.getVideoSendJitterMedian());
|
||||
}
|
||||
|
||||
if (submitCallQualitySurveyRequest.hasAudioRecvPacketLossFraction()) {
|
||||
pubSubMessageBuilder.setAudioRecvPacketLossFraction(submitCallQualitySurveyRequest.getAudioRecvPacketLossFraction());
|
||||
}
|
||||
|
||||
if (submitCallQualitySurveyRequest.hasVideoRecvPacketLossFraction()) {
|
||||
pubSubMessageBuilder.setVideoRecvPacketLossFraction(submitCallQualitySurveyRequest.getVideoRecvPacketLossFraction());
|
||||
}
|
||||
|
||||
if (submitCallQualitySurveyRequest.hasAudioSendPacketLossFraction()) {
|
||||
pubSubMessageBuilder.setAudioSendPacketLossFraction(submitCallQualitySurveyRequest.getAudioSendPacketLossFraction());
|
||||
}
|
||||
|
||||
if (submitCallQualitySurveyRequest.hasVideoSendPacketLossFraction()) {
|
||||
pubSubMessageBuilder.setVideoSendPacketLossFraction(submitCallQualitySurveyRequest.getVideoSendPacketLossFraction());
|
||||
}
|
||||
|
||||
if (submitCallQualitySurveyRequest.hasCallTelemetry()) {
|
||||
pubSubMessageBuilder.setCallTelemetry(submitCallQualitySurveyRequest.getCallTelemetry());
|
||||
}
|
||||
|
||||
GoogleApiUtil.toCompletableFuture(pubSubPublisher.publish(PubsubMessage.newBuilder()
|
||||
.setData(pubSubMessageBuilder.build().toByteString())
|
||||
.build()), pubSubCallbackExecutor)
|
||||
.whenComplete((_, throwable) -> {
|
||||
if (throwable != null) {
|
||||
logger.warn("Failed to publish call quality survey pub/sub message", throwable);
|
||||
}
|
||||
|
||||
Metrics.counter(PUB_SUB_MESSAGE_COUNTER_NAME, "success", String.valueOf(throwable == null))
|
||||
.increment();
|
||||
});
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static void validateRequest(final SubmitCallQualitySurveyRequest request) {
|
||||
if (request.getStartTimestamp() == 0) {
|
||||
throw new IllegalArgumentException("Start timestamp not specified");
|
||||
}
|
||||
|
||||
if (request.getEndTimestamp() == 0) {
|
||||
throw new IllegalArgumentException("End timestamp not specified");
|
||||
}
|
||||
|
||||
if (StringUtils.isBlank(request.getCallType())) {
|
||||
throw new IllegalArgumentException("Call type not specified");
|
||||
}
|
||||
|
||||
if (StringUtils.isBlank(request.getCallEndReason())) {
|
||||
throw new IllegalArgumentException("Call end reason not specified");
|
||||
}
|
||||
}
|
||||
}
|
||||
+8
-3
@@ -143,14 +143,19 @@ public class MetricsHttpChannelListener implements HttpChannel.Listener, Contain
|
||||
tags.add(Tag.of(TRAFFIC_SOURCE_TAG, TrafficSource.HTTP.name().toLowerCase()));
|
||||
tags.addAll(UserAgentTagUtil.getLibsignalAndPlatformTags(requestInfo.userAgent()));
|
||||
|
||||
final Optional<Tag> maybeClientVersionTag =
|
||||
UserAgentTagUtil.getClientVersionTag(requestInfo.userAgent, clientReleaseManager);
|
||||
|
||||
maybeClientVersionTag.ifPresent(tags::add);
|
||||
|
||||
meterRegistry.counter(REQUEST_COUNTER_NAME, tags).increment();
|
||||
|
||||
meterRegistry.counter(RESPONSE_BYTES_COUNTER_NAME, tags).increment(request.getResponse().getContentCount());
|
||||
meterRegistry.counter(REQUEST_BYTES_COUNTER_NAME, tags).increment(request.getContentRead());
|
||||
|
||||
UserAgentTagUtil.getClientVersionTag(requestInfo.userAgent(), clientReleaseManager).ifPresent(
|
||||
clientVersionTag -> meterRegistry.counter(REQUESTS_BY_VERSION_COUNTER_NAME,
|
||||
Tags.of(clientVersionTag, UserAgentTagUtil.getPlatformTag(requestInfo.userAgent()))).increment());
|
||||
maybeClientVersionTag.ifPresent(clientVersionTag -> meterRegistry.counter(REQUESTS_BY_VERSION_COUNTER_NAME,
|
||||
Tags.of(clientVersionTag, UserAgentTagUtil.getPlatformTag(requestInfo.userAgent)))
|
||||
.increment());
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
+16
-10
@@ -5,7 +5,8 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.metrics;
|
||||
|
||||
import com.codahale.metrics.MetricRegistry;
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.common.net.HttpHeaders;
|
||||
import io.micrometer.core.instrument.MeterRegistry;
|
||||
@@ -16,6 +17,7 @@ import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import javax.annotation.Nullable;
|
||||
import org.eclipse.jetty.io.ArrayByteBufferPool;
|
||||
import org.glassfish.jersey.server.ContainerResponse;
|
||||
import org.glassfish.jersey.server.monitoring.RequestEvent;
|
||||
import org.glassfish.jersey.server.monitoring.RequestEventListener;
|
||||
@@ -35,10 +37,10 @@ public class MetricsRequestEventListener implements RequestEventListener {
|
||||
|
||||
private final ClientReleaseManager clientReleaseManager;
|
||||
|
||||
public static final String REQUEST_COUNTER_NAME = MetricRegistry.name(MetricsRequestEventListener.class, "request");
|
||||
public static final String REQUESTS_BY_VERSION_COUNTER_NAME = MetricRegistry.name(MetricsRequestEventListener.class, "requestByVersion");
|
||||
public static final String RESPONSE_BYTES_COUNTER_NAME = MetricRegistry.name(MetricsRequestEventListener.class, "responseBytes");
|
||||
public static final String REQUEST_BYTES_COUNTER_NAME = MetricRegistry.name(MetricsRequestEventListener.class, "requestBytes");
|
||||
public static final String REQUEST_COUNTER_NAME = name(MetricsRequestEventListener.class, "request");
|
||||
public static final String REQUESTS_BY_VERSION_COUNTER_NAME = name(MetricsRequestEventListener.class, "requestByVersion");
|
||||
public static final String RESPONSE_BYTES_COUNTER_NAME = name(MetricsRequestEventListener.class, "responseBytes");
|
||||
public static final String REQUEST_BYTES_COUNTER_NAME = name(MetricsRequestEventListener.class, "requestBytes");
|
||||
|
||||
@VisibleForTesting
|
||||
static final String PATH_TAG = "path";
|
||||
@@ -98,11 +100,16 @@ public class MetricsRequestEventListener implements RequestEventListener {
|
||||
@Nullable final String userAgent;
|
||||
{
|
||||
final List<String> userAgentValues = event.getContainerRequest().getRequestHeader(HttpHeaders.USER_AGENT);
|
||||
userAgent = userAgentValues != null && !userAgentValues.isEmpty() ? userAgentValues.get(0) : null;
|
||||
userAgent = userAgentValues != null && !userAgentValues.isEmpty() ? userAgentValues.getFirst() : null;
|
||||
}
|
||||
|
||||
tags.addAll(UserAgentTagUtil.getLibsignalAndPlatformTags(userAgent));
|
||||
|
||||
final Optional<Tag> maybeClientVersionTag =
|
||||
UserAgentTagUtil.getClientVersionTag(userAgent, clientReleaseManager);
|
||||
|
||||
maybeClientVersionTag.ifPresent(tags::add);
|
||||
|
||||
meterRegistry.counter(REQUEST_COUNTER_NAME, tags).increment();
|
||||
|
||||
Optional.ofNullable(event.getContainerRequest().getProperty(WebSocketResourceProvider.REQUEST_LENGTH_PROPERTY))
|
||||
@@ -117,10 +124,9 @@ public class MetricsRequestEventListener implements RequestEventListener {
|
||||
.filter(bytes -> bytes >= 0)
|
||||
.ifPresent(bytes -> meterRegistry.counter(RESPONSE_BYTES_COUNTER_NAME, tags).increment(bytes));
|
||||
|
||||
UserAgentTagUtil.getClientVersionTag(userAgent, clientReleaseManager)
|
||||
.ifPresent(clientVersionTag -> meterRegistry.counter(REQUESTS_BY_VERSION_COUNTER_NAME,
|
||||
Tags.of(clientVersionTag, UserAgentTagUtil.getPlatformTag(userAgent)))
|
||||
.increment());
|
||||
maybeClientVersionTag.ifPresent(clientVersionTag -> meterRegistry.counter(REQUESTS_BY_VERSION_COUNTER_NAME,
|
||||
Tags.of(clientVersionTag, UserAgentTagUtil.getPlatformTag(userAgent)))
|
||||
.increment());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,7 +12,6 @@ import io.dropwizard.lifecycle.Managed;
|
||||
import io.micrometer.core.instrument.Meter;
|
||||
import io.micrometer.core.instrument.MeterRegistry;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import io.micrometer.core.instrument.binder.jetty.JettySslHandshakeMetrics;
|
||||
import io.micrometer.core.instrument.binder.jvm.JvmMemoryMetrics;
|
||||
import io.micrometer.core.instrument.binder.jvm.JvmThreadMetrics;
|
||||
@@ -21,7 +20,6 @@ import io.micrometer.core.instrument.binder.system.ProcessorMetrics;
|
||||
import io.micrometer.core.instrument.config.MeterFilter;
|
||||
import io.micrometer.core.instrument.distribution.DistributionStatisticConfig;
|
||||
import io.micrometer.registry.otlp.OtlpMeterRegistry;
|
||||
import io.micrometer.statsd.StatsdMeterRegistry;
|
||||
import io.opentelemetry.exporter.otlp.http.logs.OtlpHttpLogRecordExporter;
|
||||
import io.opentelemetry.instrumentation.logback.appender.v1_0.OpenTelemetryAppender;
|
||||
import io.opentelemetry.sdk.OpenTelemetrySdk;
|
||||
@@ -29,13 +27,12 @@ import io.opentelemetry.sdk.logs.SdkLoggerProvider;
|
||||
import io.opentelemetry.sdk.logs.export.BatchLogRecordProcessor;
|
||||
import io.opentelemetry.sdk.resources.Resource;
|
||||
import io.opentelemetry.sdk.resources.ResourceBuilder;
|
||||
import io.opentelemetry.semconv.ServiceAttributes;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.eclipse.jetty.util.component.LifeCycle;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerVersion;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.util.Constants;
|
||||
@@ -75,23 +72,6 @@ public class MetricsUtil {
|
||||
|
||||
Duration shutdownWaitDuration = Duration.ZERO;
|
||||
|
||||
if (config.getDatadogConfiguration().enabled()) {
|
||||
final StatsdMeterRegistry dogstatsdMeterRegistry = new StatsdMeterRegistry(
|
||||
config.getDatadogConfiguration(), io.micrometer.core.instrument.Clock.SYSTEM);
|
||||
|
||||
dogstatsdMeterRegistry.config().commonTags(
|
||||
Tags.of(
|
||||
"service", "chat",
|
||||
"version", WhisperServerVersion.getServerVersion(),
|
||||
"env", config.getDatadogConfiguration().getEnvironment()));
|
||||
|
||||
configureMeterFilters(dogstatsdMeterRegistry.config(), dynamicConfigurationManager);
|
||||
configureDatadogAllowList(dogstatsdMeterRegistry.config(), dynamicConfigurationManager);
|
||||
Metrics.addRegistry(dogstatsdMeterRegistry);
|
||||
|
||||
shutdownWaitDuration = config.getDatadogConfiguration().getShutdownWaitDuration();
|
||||
}
|
||||
|
||||
if (config.getOpenTelemetryConfiguration().enabled()) {
|
||||
final OtlpMeterRegistry otlpMeterRegistry = new OtlpMeterRegistry(
|
||||
config.getOpenTelemetryConfiguration(), io.micrometer.core.instrument.Clock.SYSTEM);
|
||||
@@ -99,15 +79,13 @@ public class MetricsUtil {
|
||||
configureMeterFilters(otlpMeterRegistry.config(), dynamicConfigurationManager);
|
||||
Metrics.addRegistry(otlpMeterRegistry);
|
||||
|
||||
if (config.getOpenTelemetryConfiguration().shutdownWaitDuration().compareTo(shutdownWaitDuration) > 0) {
|
||||
shutdownWaitDuration = config.getOpenTelemetryConfiguration().shutdownWaitDuration();
|
||||
}
|
||||
shutdownWaitDuration = config.getOpenTelemetryConfiguration().shutdownWaitDuration();
|
||||
}
|
||||
|
||||
environment.lifecycle().addServerLifecycleListener(
|
||||
server -> JettySslHandshakeMetrics.addToAllConnectors(server, Metrics.globalRegistry));
|
||||
|
||||
environment.lifecycle().addEventListener(new ApplicationShutdownMonitor(Metrics.globalRegistry));
|
||||
new ApplicationShutdownMonitor(Metrics.globalRegistry).register();
|
||||
environment.lifecycle().addEventListener(
|
||||
new MicrometerRegistryManager(Metrics.globalRegistry, shutdownWaitDuration));
|
||||
|
||||
@@ -144,10 +122,10 @@ public class MetricsUtil {
|
||||
|
||||
OpenTelemetryAppender.install(openTelemetry);
|
||||
|
||||
environment.lifecycle().manage(new Managed() {
|
||||
environment.lifecycle().addEventListener(new LifeCycle.Listener() {
|
||||
@Override
|
||||
public void stop() {
|
||||
openTelemetry.shutdown();
|
||||
public void lifeCycleStopped(final LifeCycle event) {
|
||||
openTelemetry.close();
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -189,14 +167,6 @@ public class MetricsUtil {
|
||||
&& id.getName().startsWith(awsSdkMetricNamePrefix)));
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static void configureDatadogAllowList(
|
||||
final MeterRegistry.Config config, final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
|
||||
config.meterFilter(MeterFilter.denyUnless(id ->
|
||||
dynamicConfigurationManager.getConfiguration().getMetricsConfiguration().datadogAllowList() == null ||
|
||||
dynamicConfigurationManager.getConfiguration().getMetricsConfiguration().datadogAllowList().contains(id.getName())));
|
||||
}
|
||||
|
||||
static void registerSystemResourceMetrics() {
|
||||
new ProcessorMetrics().bindTo(Metrics.globalRegistry);
|
||||
new FileDescriptorMetrics().bindTo(Metrics.globalRegistry);
|
||||
|
||||
+1
@@ -33,6 +33,7 @@ public class OpenTelemetryAppenderFactory extends AbstractAppenderFactory<ILoggi
|
||||
final OpenTelemetryAppender appender = new OpenTelemetryAppender();
|
||||
appender.setCaptureCodeAttributes(true);
|
||||
appender.setCaptureLoggerContext(true);
|
||||
appender.setCaptureMarkerAttribute(true);
|
||||
|
||||
// The installation of an OpenTelemetry configuration happens in
|
||||
// WhisperServerService (or CommandDependencies), in order to let us tie
|
||||
|
||||
+3
-4
@@ -5,7 +5,7 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.metrics;
|
||||
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.util.Map;
|
||||
@@ -15,7 +15,6 @@ import net.logstash.logback.marker.Markers;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ReportMessageManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ReportedMessageListener;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
@@ -24,8 +23,8 @@ public class ReportedMessageMetricsListener implements ReportedMessageListener {
|
||||
private final AccountsManager accountsManager;
|
||||
|
||||
// ReportMessageManager name used deliberately to preserve continuity of metrics
|
||||
private static final String REPORTED_COUNTER_NAME = name(ReportMessageManager.class, "reported");
|
||||
private static final String REPORTER_COUNTER_NAME = name(ReportMessageManager.class, "reporter");
|
||||
private static final String REPORTED_COUNTER_NAME = name(ReportedMessageMetricsListener.class, "reported");
|
||||
private static final String REPORTER_COUNTER_NAME = name(ReportedMessageMetricsListener.class, "reporter");
|
||||
|
||||
private static final String COUNTRY_CODE_TAG_NAME = "countryCode";
|
||||
|
||||
|
||||
-109
@@ -1,109 +0,0 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
/*
|
||||
* This is derived from Coursera's dropwizard datadog reporter.
|
||||
* https://github.com/coursera/metrics-datadog
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.metrics;
|
||||
|
||||
import com.codahale.metrics.MetricRegistry;
|
||||
import com.codahale.metrics.ScheduledReporter;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.annotation.JsonTypeName;
|
||||
import io.dropwizard.metrics.common.BaseReporterFactory;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.Min;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import java.util.ArrayList;
|
||||
import java.util.EnumSet;
|
||||
import java.util.List;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.coursera.metrics.datadog.DatadogReporter;
|
||||
import org.coursera.metrics.datadog.DatadogReporter.Expansion;
|
||||
import org.coursera.metrics.datadog.DefaultMetricNameFormatterFactory;
|
||||
import org.coursera.metrics.datadog.DynamicTagsCallbackFactory;
|
||||
import org.coursera.metrics.datadog.MetricNameFormatterFactory;
|
||||
import org.coursera.metrics.datadog.transport.UdpTransport;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerVersion;
|
||||
|
||||
@JsonTypeName("signal-datadog")
|
||||
public class SignalDatadogReporterFactory extends BaseReporterFactory {
|
||||
|
||||
@JsonProperty
|
||||
private List<String> tags = null;
|
||||
|
||||
@Valid
|
||||
@JsonProperty
|
||||
private DynamicTagsCallbackFactory dynamicTagsCallback = null;
|
||||
|
||||
@JsonProperty
|
||||
private String prefix = null;
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
private MetricNameFormatterFactory metricNameFormatter = new DefaultMetricNameFormatterFactory();
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty("udpTransport")
|
||||
private UdpTransportConfig udpTransportConfig;
|
||||
|
||||
private static final EnumSet<Expansion> EXPANSIONS = EnumSet.of(
|
||||
Expansion.COUNT,
|
||||
Expansion.MIN,
|
||||
Expansion.MAX,
|
||||
Expansion.MEAN,
|
||||
Expansion.MEDIAN,
|
||||
Expansion.P75,
|
||||
Expansion.P95,
|
||||
Expansion.P99,
|
||||
Expansion.P999
|
||||
);
|
||||
|
||||
public ScheduledReporter build(final MetricRegistry registry) {
|
||||
final List<String> combinedTags;
|
||||
|
||||
{
|
||||
final String versionTag = "version:" + WhisperServerVersion.getServerVersion();
|
||||
|
||||
if (tags != null) {
|
||||
combinedTags = new ArrayList<>(tags);
|
||||
combinedTags.add(versionTag);
|
||||
} else {
|
||||
combinedTags = new ArrayList<>((List.of(versionTag)));
|
||||
}
|
||||
}
|
||||
|
||||
final String entityId = StringUtils.stripToNull(System.getenv("DD_ENTITY_ID"));
|
||||
if (entityId != null) {
|
||||
combinedTags.add("dd.internal.entity_id:" + entityId);
|
||||
}
|
||||
|
||||
return DatadogReporter.forRegistry(registry)
|
||||
.withTransport(udpTransportConfig.udpTransport())
|
||||
.withTags(combinedTags)
|
||||
.withPrefix(prefix)
|
||||
.withExpansions(EXPANSIONS)
|
||||
.withMetricNameFormatter(metricNameFormatter.build())
|
||||
.withDynamicTagCallback(dynamicTagsCallback != null ? dynamicTagsCallback.build() : null)
|
||||
.filter(getFilter())
|
||||
.convertDurationsTo(getDurationUnit())
|
||||
.convertRatesTo(getRateUnit())
|
||||
.build();
|
||||
}
|
||||
|
||||
public record UdpTransportConfig(@NotNull String statsdHost, @Min(1) int port) {
|
||||
|
||||
public UdpTransport udpTransport() {
|
||||
return new UdpTransport.Builder()
|
||||
.withStatsdHost(statsdHost)
|
||||
.withPort(port)
|
||||
.build();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,7 @@
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.push;
|
||||
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
import static org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
@@ -24,7 +24,6 @@ import javax.annotation.Nullable;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage;
|
||||
import org.signal.libsignal.protocol.util.Pair;
|
||||
import org.whispersystems.textsecuregcm.controllers.MessageController;
|
||||
import org.whispersystems.textsecuregcm.controllers.MismatchedDevices;
|
||||
import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
|
||||
import org.whispersystems.textsecuregcm.controllers.MultiRecipientMismatchedDevicesException;
|
||||
@@ -54,8 +53,8 @@ public class MessageSender {
|
||||
private final PushNotificationManager pushNotificationManager;
|
||||
|
||||
// Note that these names deliberately reference `MessageController` for metric continuity
|
||||
private static final String REJECT_OVERSIZE_MESSAGE_COUNTER_NAME = name(MessageController.class, "rejectOversizeMessage");
|
||||
private static final String CONTENT_SIZE_DISTRIBUTION_NAME = MetricsUtil.name(MessageController.class, "messageContentSize");
|
||||
private static final String REJECT_OVERSIZE_MESSAGE_COUNTER_NAME = name(MessageSender.class, "rejectOversizeMessage");
|
||||
private static final String CONTENT_SIZE_DISTRIBUTION_NAME = MetricsUtil.name(MessageSender.class, "messageContentSize");
|
||||
private static final String EMPTY_MESSAGE_LIST_COUNTER_NAME = MetricsUtil.name(MessageSender.class, "emptyMessageList");
|
||||
|
||||
private static final String SEND_COUNTER_NAME = name(MessageSender.class, "sendMessage");
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.push;
|
||||
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import com.google.protobuf.InvalidProtocolBufferException;
|
||||
|
||||
+8
-1
@@ -94,7 +94,12 @@ public class RegistrationServiceClient implements Managed {
|
||||
}
|
||||
|
||||
public CompletableFuture<RegistrationServiceSession> createRegistrationSession(
|
||||
final Phonenumber.PhoneNumber phoneNumber, final String sourceHost, final boolean accountExistsWithPhoneNumber, final Duration timeout) {
|
||||
final Phonenumber.PhoneNumber phoneNumber,
|
||||
final String sourceHost,
|
||||
final boolean accountExistsWithPhoneNumber,
|
||||
@javax.annotation.Nullable final String clientMcc,
|
||||
@javax.annotation.Nullable final String clientMnc,
|
||||
final Duration timeout) {
|
||||
|
||||
final long e164 = Long.parseLong(
|
||||
PhoneNumberUtil.getInstance().format(phoneNumber, PhoneNumberUtil.PhoneNumberFormat.E164).substring(1));
|
||||
@@ -105,6 +110,8 @@ public class RegistrationServiceClient implements Managed {
|
||||
.setE164(e164)
|
||||
.setAccountExistsWithE164(accountExistsWithPhoneNumber)
|
||||
.setRateLimitCollationKey(rateLimitCollationKey)
|
||||
.setMcc(clientMcc != null ? clientMcc : "")
|
||||
.setMnc(clientMnc != null ? clientMnc : "")
|
||||
.build()), callbackExecutor)
|
||||
.thenApply(response -> switch (response.getResponseCase()) {
|
||||
case SESSION_METADATA -> buildSessionResponseFromMetadata(response.getSessionMetadata());
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
/*
|
||||
* Copyright 2013 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.s3;
|
||||
|
||||
import io.dropwizard.lifecycle.Managed;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
public interface ManagedSupplier<T> extends Supplier<T>, Managed {
|
||||
|
||||
@Override
|
||||
default void start() throws Exception {
|
||||
// noop
|
||||
}
|
||||
|
||||
@Override
|
||||
default void stop() throws Exception {
|
||||
// noop
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
/*
|
||||
* Copyright 2021 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.s3;
|
||||
|
||||
import static java.util.Objects.requireNonNull;
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
import java.io.InputStream;
|
||||
import java.lang.invoke.MethodHandles;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.function.Function;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.configuration.S3ObjectMonitorFactory;
|
||||
import org.whispersystems.textsecuregcm.s3.ManagedSupplier;
|
||||
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
|
||||
|
||||
public class S3MonitoringSupplier<T> implements ManagedSupplier<T> {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
|
||||
|
||||
private final Timer refreshTimer;
|
||||
|
||||
private final Counter refreshErrors;
|
||||
|
||||
private final AtomicReference<T> holder;
|
||||
|
||||
private final S3ObjectMonitor monitor;
|
||||
|
||||
private final Function<InputStream, T> parser;
|
||||
|
||||
|
||||
public S3MonitoringSupplier(
|
||||
final ScheduledExecutorService executor,
|
||||
final AwsCredentialsProvider awsCredentialsProvider,
|
||||
final S3ObjectMonitorFactory cfg,
|
||||
final Function<InputStream, T> parser,
|
||||
final T initial,
|
||||
final String name) {
|
||||
this.refreshTimer = Metrics.timer(name(S3MonitoringSupplier.class, name, "refresh"));
|
||||
this.refreshErrors = Metrics.counter(name(S3MonitoringSupplier.class, name, "refreshErrors"));
|
||||
this.holder = new AtomicReference<>(initial);
|
||||
this.parser = requireNonNull(parser);
|
||||
this.monitor = cfg.build(awsCredentialsProvider, executor);
|
||||
}
|
||||
|
||||
@Override
|
||||
public T get() {
|
||||
return requireNonNull(holder.get());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void start() throws Exception {
|
||||
monitor.start(this::handleObjectChange);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stop() throws Exception {
|
||||
monitor.stop();
|
||||
}
|
||||
|
||||
private void handleObjectChange(final InputStream inputStream) {
|
||||
refreshTimer.record(() -> {
|
||||
// parser function is supposed to close the input stream
|
||||
try {
|
||||
holder.set(parser.apply(inputStream));
|
||||
} catch (final Exception e) {
|
||||
log.error("failed to update internal state from the monitored object", e);
|
||||
refreshErrors.increment();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -6,10 +6,13 @@
|
||||
package org.whispersystems.textsecuregcm.spam;
|
||||
|
||||
import io.dropwizard.configuration.ConfigurationValidationException;
|
||||
import io.dropwizard.core.cli.ConfiguredCommand;
|
||||
import io.dropwizard.lifecycle.Managed;
|
||||
import jakarta.validation.Validator;
|
||||
import java.io.IOException;
|
||||
import java.util.Collection;
|
||||
import java.util.function.Function;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.captcha.CaptchaClient;
|
||||
import org.whispersystems.textsecuregcm.storage.ReportedMessageListener;
|
||||
|
||||
@@ -35,6 +38,14 @@ public interface SpamFilter extends Managed {
|
||||
*/
|
||||
void configure(String environmentName, Validator validator) throws IOException, ConfigurationValidationException;
|
||||
|
||||
/**
|
||||
* Returns a collection of commands provided by this spam filter. Note that this method may be called before
|
||||
* {@link #configure(String, Validator)}.
|
||||
*
|
||||
* @return a collection of commands provided by this spam filter
|
||||
*/
|
||||
Collection<ConfiguredCommand<WhisperServerConfiguration>> getCommands();
|
||||
|
||||
/**
|
||||
* Return a reported message listener controlled by the spam filter. Listeners will be registered with the
|
||||
* {@link org.whispersystems.textsecuregcm.storage.ReportMessageManager}.
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
import static io.micrometer.core.instrument.Metrics.counter;
|
||||
import static io.micrometer.core.instrument.Metrics.timer;
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
import static java.util.Objects.requireNonNull;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
@@ -70,6 +70,7 @@ import software.amazon.awssdk.services.dynamodb.model.TransactionCanceledExcepti
|
||||
import software.amazon.awssdk.services.dynamodb.model.TransactionConflictException;
|
||||
import software.amazon.awssdk.services.dynamodb.model.Update;
|
||||
import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.paginators.ScanPublisher;
|
||||
import software.amazon.awssdk.utils.CompletableFutureUtils;
|
||||
|
||||
/**
|
||||
@@ -1244,14 +1245,20 @@ public class Accounts {
|
||||
return Flux.range(0, segments)
|
||||
.parallel()
|
||||
.runOn(scheduler)
|
||||
.flatMap(segment -> dynamoDbAsyncClient.scanPaginator(ScanRequest.builder()
|
||||
.tableName(accountsTableName)
|
||||
.consistentRead(true)
|
||||
.segment(segment)
|
||||
.totalSegments(segments)
|
||||
.build())
|
||||
.items()
|
||||
.map(Accounts::fromItem))
|
||||
.flatMap(segment -> {
|
||||
final ScanPublisher scanPublisher = dynamoDbAsyncClient.scanPaginator(ScanRequest.builder()
|
||||
.tableName(accountsTableName)
|
||||
.consistentRead(true)
|
||||
.segment(segment)
|
||||
.totalSegments(segments)
|
||||
.build());
|
||||
|
||||
// Subscribe to the publisher of responses (i.e. `scanPublisher`) rather than the publisher of items
|
||||
// (i.e. `scanPublisher.items()`) to work around https://github.com/aws/aws-sdk-java-v2/issues/6411
|
||||
return Flux.from(scanPublisher)
|
||||
.flatMap(scanResponse -> Flux.fromIterable(scanResponse.items()))
|
||||
.map(Accounts::fromItem);
|
||||
})
|
||||
.sequential();
|
||||
}
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
import static java.util.Objects.requireNonNull;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
|
||||
@@ -10,10 +10,6 @@ import java.util.Optional;
|
||||
public enum DeviceCapability {
|
||||
STORAGE("storage", AccountCapabilityMode.ANY_DEVICE, false, false),
|
||||
TRANSFER("transfer", AccountCapabilityMode.PRIMARY_DEVICE, false, false),
|
||||
@Deprecated(forRemoval = true) // Can be removed sometime after 11/10/2025
|
||||
DELETE_SYNC("deleteSync", AccountCapabilityMode.ALWAYS_CAPABLE, true, true),
|
||||
@Deprecated(forRemoval = true) // Can be removed sometime after 11/10/2025
|
||||
STORAGE_SERVICE_RECORD_KEY_ROTATION("ssre2", AccountCapabilityMode.ALWAYS_CAPABLE, true, true),
|
||||
ATTACHMENT_BACKFILL("attachmentBackfill", AccountCapabilityMode.PRIMARY_DEVICE, false, true),
|
||||
SPARSE_POST_QUANTUM_RATCHET("spqr", AccountCapabilityMode.ALL_DEVICES, false, true);
|
||||
|
||||
|
||||
@@ -13,7 +13,6 @@ import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import org.whispersystems.textsecuregcm.controllers.KeysController;
|
||||
import org.whispersystems.textsecuregcm.entities.ECPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
|
||||
@@ -28,7 +27,7 @@ import javax.annotation.Nullable;
|
||||
|
||||
public class KeysManager {
|
||||
// KeysController for backwards compatibility
|
||||
private static final String GET_KEYS_COUNTER_NAME = MetricsUtil.name(KeysController.class, "getKeys");
|
||||
private static final String GET_KEYS_COUNTER_NAME = MetricsUtil.name(KeysManager.class, "getKeys");
|
||||
|
||||
private final SingleUseECPreKeyStore ecPreKeys;
|
||||
private final SingleUseKEMPreKeyStore pqPreKeys;
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.protobuf.ByteString;
|
||||
|
||||
+1
-51
@@ -5,8 +5,8 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
import static io.micrometer.core.instrument.Metrics.timer;
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.common.collect.ImmutableMap;
|
||||
@@ -30,9 +30,6 @@ import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.util.AttributeValues;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
import reactor.core.scheduler.Schedulers;
|
||||
import software.amazon.awssdk.core.SdkBytes;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
|
||||
@@ -51,9 +48,6 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
|
||||
@VisibleForTesting
|
||||
static final String KEY_SORT = "S";
|
||||
|
||||
@VisibleForTesting
|
||||
static final String LOCAL_INDEX_MESSAGE_UUID_NAME = "Message_UUID_Index";
|
||||
|
||||
@VisibleForTesting
|
||||
static final String LOCAL_INDEX_MESSAGE_UUID_KEY_SORT = "U";
|
||||
|
||||
@@ -69,7 +63,6 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
|
||||
private final String tableName;
|
||||
private final Duration timeToLive;
|
||||
private final ExecutorService messageDeletionExecutor;
|
||||
private final Scheduler messageDeletionScheduler;
|
||||
private final ExperimentEnrollmentManager experimentEnrollmentManager;
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(MessagesDynamoDb.class);
|
||||
@@ -84,7 +77,6 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
|
||||
this.timeToLive = timeToLive;
|
||||
|
||||
this.messageDeletionExecutor = messageDeletionExecutor;
|
||||
this.messageDeletionScheduler = Schedulers.fromExecutor(messageDeletionExecutor);
|
||||
this.experimentEnrollmentManager = experimentEnrollmentManager;
|
||||
}
|
||||
|
||||
@@ -164,48 +156,6 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
|
||||
.filter(Predicate.not(Objects::isNull));
|
||||
}
|
||||
|
||||
public CompletableFuture<Optional<MessageProtos.Envelope>> deleteMessageByDestinationAndGuid(
|
||||
final UUID destinationAccountUuid, final Device destinationDevice, final UUID messageUuid) {
|
||||
final AttributeValue partitionKey = convertPartitionKey(destinationAccountUuid, destinationDevice);
|
||||
final QueryRequest queryRequest = QueryRequest.builder()
|
||||
.tableName(tableName)
|
||||
.indexName(LOCAL_INDEX_MESSAGE_UUID_NAME)
|
||||
.projectionExpression(KEY_SORT)
|
||||
.consistentRead(true)
|
||||
.keyConditionExpression("#part = :part AND #uuid = :uuid")
|
||||
.expressionAttributeNames(Map.of(
|
||||
"#part", KEY_PARTITION,
|
||||
"#uuid", LOCAL_INDEX_MESSAGE_UUID_KEY_SORT))
|
||||
.expressionAttributeValues(Map.of(
|
||||
":part", partitionKey,
|
||||
":uuid", convertLocalIndexMessageUuidSortKey(messageUuid)))
|
||||
.build();
|
||||
|
||||
// because we are filtering on message UUID, this query should return at most one item,
|
||||
// but it’s simpler to handle the full stream and return the “last” item
|
||||
return Flux.from(dbAsyncClient.queryPaginator(queryRequest).items())
|
||||
.flatMap(item -> Mono.fromCompletionStage(dbAsyncClient.deleteItem(DeleteItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.key(Map.of(KEY_PARTITION, partitionKey, KEY_SORT,
|
||||
AttributeValues.fromByteArray(item.get(KEY_SORT).b().asByteArray())))
|
||||
.returnValues(ReturnValue.ALL_OLD)
|
||||
.build())))
|
||||
.mapNotNull(deleteItemResponse -> {
|
||||
try {
|
||||
if (deleteItemResponse.attributes() != null && deleteItemResponse.attributes().containsKey(KEY_PARTITION)) {
|
||||
return convertItemToEnvelope(deleteItemResponse.attributes(), experimentEnrollmentManager);
|
||||
}
|
||||
} catch (final InvalidProtocolBufferException e) {
|
||||
logger.error("Failed to parse envelope", e);
|
||||
}
|
||||
return null;
|
||||
})
|
||||
.map(Optional::ofNullable)
|
||||
.subscribeOn(messageDeletionScheduler)
|
||||
.last(Optional.empty()) // if the flux is empty, last() will throw without a default
|
||||
.toFuture();
|
||||
}
|
||||
|
||||
public CompletableFuture<Optional<MessageProtos.Envelope>> deleteMessage(final UUID destinationAccountUuid,
|
||||
final Device destinationDevice, final UUID messageUuid, final long serverTimestamp) {
|
||||
DeleteItemRequest.Builder deleteItemRequest = DeleteItemRequest.builder()
|
||||
|
||||
+10
-20
@@ -28,7 +28,6 @@ import org.reactivestreams.Publisher;
|
||||
import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
@@ -253,26 +252,17 @@ public class MessagesManager {
|
||||
return messagesCache.clear(destinationUuid, deviceId);
|
||||
}
|
||||
|
||||
public CompletableFuture<Optional<RemovedMessage>> delete(UUID destinationUuid, Device destinationDevice, UUID guid,
|
||||
@Nullable Long serverTimestamp) {
|
||||
public CompletableFuture<Optional<RemovedMessage>> delete(final UUID destinationUuid,
|
||||
final Device destinationDevice,
|
||||
final UUID guid,
|
||||
final long serverTimestamp) {
|
||||
|
||||
return messagesCache.remove(destinationUuid, destinationDevice.getId(), guid)
|
||||
.thenComposeAsync(removed -> {
|
||||
|
||||
if (removed.isPresent()) {
|
||||
return CompletableFuture.completedFuture(removed);
|
||||
}
|
||||
|
||||
final CompletableFuture<Optional<MessageProtos.Envelope>> maybeDeletedEnvelope;
|
||||
if (serverTimestamp == null) {
|
||||
maybeDeletedEnvelope = messagesDynamoDb.deleteMessageByDestinationAndGuid(destinationUuid,
|
||||
destinationDevice, guid);
|
||||
} else {
|
||||
maybeDeletedEnvelope = messagesDynamoDb.deleteMessage(destinationUuid, destinationDevice, guid,
|
||||
serverTimestamp);
|
||||
}
|
||||
|
||||
return maybeDeletedEnvelope.thenApply(maybeEnvelope -> maybeEnvelope.map(RemovedMessage::fromEnvelope));
|
||||
}, messageDeletionExecutor);
|
||||
.thenComposeAsync(removed -> removed
|
||||
.map(_ -> CompletableFuture.completedFuture(removed))
|
||||
.orElseGet(() -> messagesDynamoDb.deleteMessage(destinationUuid, destinationDevice, guid, serverTimestamp)
|
||||
.thenApply(maybeEnvelope -> maybeEnvelope.map(RemovedMessage::fromEnvelope))
|
||||
), messageDeletionExecutor);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.time.Duration;
|
||||
|
||||
+190
@@ -0,0 +1,190 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
|
||||
import com.apple.itunes.storekit.client.APIError;
|
||||
import com.apple.itunes.storekit.client.APIException;
|
||||
import com.apple.itunes.storekit.client.AppStoreServerAPIClient;
|
||||
import com.apple.itunes.storekit.model.Environment;
|
||||
import com.apple.itunes.storekit.model.LastTransactionsItem;
|
||||
import com.apple.itunes.storekit.model.Status;
|
||||
import com.apple.itunes.storekit.model.StatusResponse;
|
||||
import com.apple.itunes.storekit.verification.SignedDataVerifier;
|
||||
import com.apple.itunes.storekit.verification.VerificationException;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.github.resilience4j.retry.Retry;
|
||||
import io.github.resilience4j.retry.RetryConfig;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import javax.annotation.Nullable;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.util.ResilienceUtil;
|
||||
|
||||
/// Client for interacting with the storekit server APIs.
|
||||
///
|
||||
/// This handles fetching information about a subscription from a transaction id, and then can be used to verify
|
||||
/// individual transactions from that subscription with [#verify]. Transactions generated with both production and
|
||||
/// sandbox environments can be used.
|
||||
public class AppleAppStoreClient {
|
||||
|
||||
private static final Status[] EMPTY_STATUSES = new Status[0];
|
||||
|
||||
private static final String GET_SUBSCRIPTION_ERROR_COUNTER_NAME =
|
||||
MetricsUtil.name(AppleAppStoreClient.class, "getSubscriptionsError");
|
||||
|
||||
private final Environment defaultEnvironment;
|
||||
private final SignedDataVerifier productionSignedDataVerifier;
|
||||
private final AppStoreServerAPIClient productionApiClient;
|
||||
private final SignedDataVerifier sandboxSignedDataVerifier;
|
||||
private final AppStoreServerAPIClient sandboxApiClient;
|
||||
private final Retry retry;
|
||||
|
||||
|
||||
/// Construct an AppleAppStoreClient
|
||||
///
|
||||
/// @param defaultEnvironment The first environment to try. If it is the production environment and a
|
||||
/// transactionId does not exist there, we will fallback to the sandbox environment
|
||||
/// @param bundleId The bundleId of the app
|
||||
/// @param appAppleId The integer id of the app
|
||||
/// @param issuerId The issuerId for the
|
||||
/// [keys](https://developer.apple.com/documentation/appstoreconnectapi/generating_tokens_for_api_requests)
|
||||
/// @param keyId The keyId for encodedKey
|
||||
/// @param encodedKey A private key with the "In-App Purchase" key type
|
||||
/// @param base64AppleRootCerts [Apple root certificates](https://www.apple.com/certificateauthority/) to verify
|
||||
/// signed API responses, encoded as base64 strings:
|
||||
/// @param retryConfigurationName The name of the retry configuration to use in the App Store client; if `null`, uses
|
||||
/// the global default configuration.
|
||||
public AppleAppStoreClient(
|
||||
final Environment defaultEnvironment,
|
||||
final String bundleId,
|
||||
final long appAppleId,
|
||||
final String issuerId,
|
||||
final String keyId,
|
||||
final String encodedKey,
|
||||
final List<String> base64AppleRootCerts,
|
||||
@Nullable final String retryConfigurationName) {
|
||||
this(defaultEnvironment,
|
||||
new SignedDataVerifier(decodeRootCerts(base64AppleRootCerts), bundleId, appAppleId, Environment.PRODUCTION,
|
||||
true),
|
||||
new AppStoreServerAPIClient(encodedKey, keyId, issuerId, bundleId, Environment.PRODUCTION),
|
||||
new SignedDataVerifier(decodeRootCerts(base64AppleRootCerts), bundleId, appAppleId, Environment.SANDBOX, true),
|
||||
new AppStoreServerAPIClient(encodedKey, keyId, issuerId, bundleId, Environment.SANDBOX),
|
||||
retryConfigurationName);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
AppleAppStoreClient(
|
||||
Environment defaultEnvironment,
|
||||
SignedDataVerifier productionSignedDataVerifier,
|
||||
AppStoreServerAPIClient productionApiClient,
|
||||
SignedDataVerifier sandboxSignedDataVerifier,
|
||||
AppStoreServerAPIClient sandboxApiClient,
|
||||
@Nullable final String retryConfigurationName) {
|
||||
this.defaultEnvironment = defaultEnvironment;
|
||||
this.sandboxSignedDataVerifier = sandboxSignedDataVerifier;
|
||||
this.sandboxApiClient = sandboxApiClient;
|
||||
this.productionSignedDataVerifier = productionSignedDataVerifier;
|
||||
this.productionApiClient = productionApiClient;
|
||||
this.retry = ResilienceUtil.getRetryRegistry().retry("appstore-retry", RetryConfig
|
||||
.<HttpResponse<?>>from(Optional.ofNullable(retryConfigurationName)
|
||||
.flatMap(name -> ResilienceUtil.getRetryRegistry().getConfiguration(name))
|
||||
.orElseGet(() -> ResilienceUtil.getRetryRegistry().getDefaultConfig()))
|
||||
.retryOnException(AppleAppStoreClient::shouldRetry).build());
|
||||
}
|
||||
|
||||
|
||||
/// Verify signature and decode transaction payloads
|
||||
public AppleAppStoreDecodedTransaction verify(final Environment environment, final LastTransactionsItem tx) {
|
||||
final SignedDataVerifier signedDataVerifier = switch (environment) {
|
||||
case PRODUCTION -> productionSignedDataVerifier;
|
||||
case SANDBOX -> sandboxSignedDataVerifier;
|
||||
default -> throw new IllegalStateException("Unexpected environment: " + environment);
|
||||
};
|
||||
try {
|
||||
return new AppleAppStoreDecodedTransaction(
|
||||
tx,
|
||||
signedDataVerifier.verifyAndDecodeTransaction(tx.getSignedTransactionInfo()),
|
||||
signedDataVerifier.verifyAndDecodeRenewalInfo(tx.getSignedRenewalInfo()));
|
||||
} catch (VerificationException e) {
|
||||
throw new UncheckedIOException(new IOException("Failed to verify payload from App Store Server", e));
|
||||
}
|
||||
}
|
||||
|
||||
public StatusResponse getAllSubscriptions(final String originalTransactionId)
|
||||
throws SubscriptionNotFoundException, SubscriptionInvalidArgumentsException, RateLimitExceededException {
|
||||
try {
|
||||
return retry.executeCallable(() -> {
|
||||
try {
|
||||
return getAllSubscriptionsHelper(defaultEnvironment, originalTransactionId);
|
||||
} catch (final APIException e) {
|
||||
Metrics.counter(GET_SUBSCRIPTION_ERROR_COUNTER_NAME, "reason", e.getApiError().name()).increment();
|
||||
throw switch (e.getApiError()) {
|
||||
case TRANSACTION_ID_NOT_FOUND, ORIGINAL_TRANSACTION_ID_NOT_FOUND -> new SubscriptionNotFoundException();
|
||||
case RATE_LIMIT_EXCEEDED -> new RateLimitExceededException(null);
|
||||
case INVALID_ORIGINAL_TRANSACTION_ID -> new SubscriptionInvalidArgumentsException(e.getApiErrorMessage());
|
||||
default -> throw e;
|
||||
};
|
||||
} catch (final IOException e) {
|
||||
Metrics.counter(GET_SUBSCRIPTION_ERROR_COUNTER_NAME, "reason", "io_error").increment();
|
||||
throw e;
|
||||
}
|
||||
});
|
||||
} catch (SubscriptionNotFoundException | SubscriptionInvalidArgumentsException | RateLimitExceededException e) {
|
||||
throw e;
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
} catch (APIException e) {
|
||||
throw new UncheckedIOException(new IOException(e));
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private StatusResponse getAllSubscriptionsHelper(final Environment env, final String originalTransactionId)
|
||||
throws APIException, IOException {
|
||||
final AppStoreServerAPIClient client = switch (env) {
|
||||
case SANDBOX -> sandboxApiClient;
|
||||
case PRODUCTION -> productionApiClient;
|
||||
default -> throw new IllegalArgumentException("Unknown environment: " + env);
|
||||
};
|
||||
try {
|
||||
return client.getAllSubscriptionStatuses(originalTransactionId, EMPTY_STATUSES);
|
||||
} catch (APIException e) {
|
||||
// First attempts to look up the transaction on the production environment, falling back to the sandbox env if
|
||||
// the transaction is not found.
|
||||
// See: https://developer.apple.com/documentation/AppStoreServerAPI#Test-using-the-sandbox-environment
|
||||
if (env == Environment.PRODUCTION && e.getApiError() == APIError.TRANSACTION_ID_NOT_FOUND) {
|
||||
return getAllSubscriptionsHelper(Environment.SANDBOX, originalTransactionId);
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
private static Set<InputStream> decodeRootCerts(final List<String> rootCerts) {
|
||||
return rootCerts.stream()
|
||||
.map(Base64.getDecoder()::decode)
|
||||
.map(ByteArrayInputStream::new)
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
private static boolean shouldRetry(Throwable e) {
|
||||
return e instanceof APIException apiException && switch (apiException.getApiError()) {
|
||||
case ORIGINAL_TRANSACTION_ID_NOT_FOUND_RETRYABLE, GENERAL_INTERNAL_RETRYABLE, APP_NOT_FOUND_RETRYABLE -> true;
|
||||
default -> false;
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
|
||||
import com.apple.itunes.storekit.model.JWSRenewalInfoDecodedPayload;
|
||||
import com.apple.itunes.storekit.model.JWSTransactionDecodedPayload;
|
||||
import com.apple.itunes.storekit.model.LastTransactionsItem;
|
||||
|
||||
/**
|
||||
* A decoded and validated storekit transaction
|
||||
*
|
||||
* @param signedTransaction The transaction
|
||||
* @param transaction The transaction info with a validated signature
|
||||
* @param renewalInfo The renewal info with a validated signature
|
||||
*/
|
||||
record AppleAppStoreDecodedTransaction(
|
||||
LastTransactionsItem signedTransaction,
|
||||
JWSTransactionDecodedPayload transaction,
|
||||
JWSRenewalInfoDecodedPayload renewalInfo) {}
|
||||
+34
-154
@@ -5,43 +5,21 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
|
||||
import com.apple.itunes.storekit.client.APIException;
|
||||
import com.apple.itunes.storekit.client.AppStoreServerAPIClient;
|
||||
import com.apple.itunes.storekit.model.AutoRenewStatus;
|
||||
import com.apple.itunes.storekit.model.Environment;
|
||||
import com.apple.itunes.storekit.model.JWSRenewalInfoDecodedPayload;
|
||||
import com.apple.itunes.storekit.model.JWSTransactionDecodedPayload;
|
||||
import com.apple.itunes.storekit.model.LastTransactionsItem;
|
||||
import com.apple.itunes.storekit.model.Status;
|
||||
import com.apple.itunes.storekit.model.StatusResponse;
|
||||
import com.apple.itunes.storekit.model.SubscriptionGroupIdentifierItem;
|
||||
import com.apple.itunes.storekit.verification.SignedDataVerifier;
|
||||
import com.apple.itunes.storekit.verification.VerificationException;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.github.resilience4j.retry.Retry;
|
||||
import io.github.resilience4j.retry.RetryConfig;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.math.BigDecimal;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.time.Instant;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import javax.annotation.Nullable;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.PaymentTime;
|
||||
import org.whispersystems.textsecuregcm.util.ResilienceUtil;
|
||||
|
||||
/**
|
||||
* Manages subscriptions made with the Apple App Store
|
||||
@@ -54,51 +32,17 @@ public class AppleAppStoreManager implements SubscriptionPaymentProcessor {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(AppleAppStoreManager.class);
|
||||
|
||||
private final AppStoreServerAPIClient apiClient;
|
||||
private final SignedDataVerifier signedDataVerifier;
|
||||
private final AppleAppStoreClient appleAppStoreClient;
|
||||
private final Map<String, Long> productIdToLevel;
|
||||
|
||||
private static final Status[] EMPTY_STATUSES = new Status[0];
|
||||
|
||||
private static final String GET_SUBSCRIPTION_ERROR_COUNTER_NAME =
|
||||
MetricsUtil.name(AppleAppStoreManager.class, "getSubscriptionsError");
|
||||
|
||||
private final String subscriptionGroupId;
|
||||
private final Retry retry;
|
||||
|
||||
|
||||
public AppleAppStoreManager(
|
||||
final Environment env,
|
||||
final String bundleId,
|
||||
final long appAppleId,
|
||||
final String issuerId,
|
||||
final String keyId,
|
||||
final String encodedKey,
|
||||
AppleAppStoreClient appleAppStoreClient,
|
||||
final String subscriptionGroupId,
|
||||
final Map<String, Long> productIdToLevel,
|
||||
final List<String> base64AppleRootCerts,
|
||||
@Nullable final String retryConfigurationName) {
|
||||
this(new AppStoreServerAPIClient(encodedKey, keyId, issuerId, bundleId, env),
|
||||
new SignedDataVerifier(decodeRootCerts(base64AppleRootCerts), bundleId, appAppleId, env, true),
|
||||
subscriptionGroupId, productIdToLevel, retryConfigurationName);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
AppleAppStoreManager(
|
||||
final AppStoreServerAPIClient apiClient,
|
||||
final SignedDataVerifier signedDataVerifier,
|
||||
final String subscriptionGroupId,
|
||||
final Map<String, Long> productIdToLevel,
|
||||
@Nullable final String retryConfigurationName) {
|
||||
this.apiClient = apiClient;
|
||||
this.signedDataVerifier = signedDataVerifier;
|
||||
final Map<String, Long> productIdToLevel) {
|
||||
this.appleAppStoreClient = appleAppStoreClient;
|
||||
this.subscriptionGroupId = subscriptionGroupId;
|
||||
this.productIdToLevel = productIdToLevel;
|
||||
this.retry = ResilienceUtil.getRetryRegistry().retry("appstore-retry", RetryConfig
|
||||
.<HttpResponse<?>>from(Optional.ofNullable(retryConfigurationName)
|
||||
.flatMap(name -> ResilienceUtil.getRetryRegistry().getConfiguration(name))
|
||||
.orElseGet(() -> ResilienceUtil.getRetryRegistry().getDefaultConfig()))
|
||||
.retryOnException(AppleAppStoreManager::shouldRetry).build());
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -106,7 +50,6 @@ public class AppleAppStoreManager implements SubscriptionPaymentProcessor {
|
||||
return PaymentProvider.APPLE_APP_STORE;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Check if the subscription with the provided originalTransactionId is valid.
|
||||
*
|
||||
@@ -120,7 +63,7 @@ public class AppleAppStoreManager implements SubscriptionPaymentProcessor {
|
||||
*/
|
||||
public Long validateTransaction(final String originalTransactionId)
|
||||
throws SubscriptionInvalidArgumentsException, RateLimitExceededException, SubscriptionNotFoundException, SubscriptionPaymentRequiredException {
|
||||
final DecodedTransaction tx = lookupAndValidateTransaction(originalTransactionId);
|
||||
final AppleAppStoreDecodedTransaction tx = lookupAndValidateTransaction(originalTransactionId);
|
||||
if (!isSubscriptionActive(tx)) {
|
||||
throw new SubscriptionPaymentRequiredException();
|
||||
}
|
||||
@@ -144,10 +87,10 @@ public class AppleAppStoreManager implements SubscriptionPaymentProcessor {
|
||||
public void cancelAllActiveSubscriptions(String originalTransactionId)
|
||||
throws SubscriptionInvalidArgumentsException, RateLimitExceededException {
|
||||
try {
|
||||
final DecodedTransaction tx = lookup(originalTransactionId);
|
||||
if (tx.signedTransaction.getStatus() != Status.EXPIRED &&
|
||||
tx.signedTransaction.getStatus() != Status.REVOKED &&
|
||||
tx.renewalInfo.getAutoRenewStatus() != AutoRenewStatus.OFF) {
|
||||
final AppleAppStoreDecodedTransaction tx = lookup(originalTransactionId);
|
||||
if (tx.signedTransaction().getStatus() != Status.EXPIRED &&
|
||||
tx.signedTransaction().getStatus() != Status.REVOKED &&
|
||||
tx.renewalInfo().getAutoRenewStatus() != AutoRenewStatus.OFF) {
|
||||
throw new SubscriptionInvalidArgumentsException("must cancel subscription with storekit before deleting");
|
||||
}
|
||||
} catch (SubscriptionNotFoundException _) {
|
||||
@@ -159,8 +102,8 @@ public class AppleAppStoreManager implements SubscriptionPaymentProcessor {
|
||||
@Override
|
||||
public SubscriptionInformation getSubscriptionInformation(final String originalTransactionId)
|
||||
throws RateLimitExceededException, SubscriptionNotFoundException {
|
||||
final DecodedTransaction tx = lookup(originalTransactionId);
|
||||
final SubscriptionStatus status = switch (tx.signedTransaction.getStatus()) {
|
||||
final AppleAppStoreDecodedTransaction tx = lookup(originalTransactionId);
|
||||
final SubscriptionStatus status = switch (tx.signedTransaction().getStatus()) {
|
||||
case ACTIVE -> SubscriptionStatus.ACTIVE;
|
||||
case BILLING_RETRY -> SubscriptionStatus.PAST_DUE;
|
||||
case BILLING_GRACE_PERIOD -> SubscriptionStatus.UNPAID;
|
||||
@@ -170,10 +113,10 @@ public class AppleAppStoreManager implements SubscriptionPaymentProcessor {
|
||||
return new SubscriptionInformation(
|
||||
getSubscriptionPrice(tx),
|
||||
getLevel(tx),
|
||||
Instant.ofEpochMilli(tx.transaction.getOriginalPurchaseDate()),
|
||||
Instant.ofEpochMilli(tx.transaction.getExpiresDate()),
|
||||
Instant.ofEpochMilli(tx.transaction().getOriginalPurchaseDate()),
|
||||
Instant.ofEpochMilli(tx.transaction().getExpiresDate()),
|
||||
isSubscriptionActive(tx),
|
||||
tx.renewalInfo.getAutoRenewStatus() == AutoRenewStatus.OFF,
|
||||
tx.renewalInfo().getAutoRenewStatus() == AutoRenewStatus.OFF,
|
||||
status,
|
||||
PaymentProvider.APPLE_APP_STORE,
|
||||
PaymentMethod.APPLE_APP_STORE,
|
||||
@@ -185,7 +128,7 @@ public class AppleAppStoreManager implements SubscriptionPaymentProcessor {
|
||||
@Override
|
||||
public ReceiptItem getReceiptItem(String originalTransactionId)
|
||||
throws RateLimitExceededException, SubscriptionNotFoundException, SubscriptionPaymentRequiredException {
|
||||
final DecodedTransaction tx = lookup(originalTransactionId);
|
||||
final AppleAppStoreDecodedTransaction tx = lookup(originalTransactionId);
|
||||
if (!isSubscriptionActive(tx)) {
|
||||
throw new SubscriptionPaymentRequiredException();
|
||||
}
|
||||
@@ -193,14 +136,14 @@ public class AppleAppStoreManager implements SubscriptionPaymentProcessor {
|
||||
// A new transactionId might be generated if you restore a subscription on a new device. webOrderLineItemId is
|
||||
// guaranteed not to change for a specific renewal purchase.
|
||||
// See: https://developer.apple.com/documentation/appstoreservernotifications/weborderlineitemid
|
||||
final String itemId = tx.transaction.getWebOrderLineItemId();
|
||||
final PaymentTime paymentTime = PaymentTime.periodEnds(Instant.ofEpochMilli(tx.transaction.getExpiresDate()));
|
||||
final String itemId = tx.transaction().getWebOrderLineItemId();
|
||||
final PaymentTime paymentTime = PaymentTime.periodEnds(Instant.ofEpochMilli(tx.transaction().getExpiresDate()));
|
||||
|
||||
return new ReceiptItem(itemId, paymentTime, getLevel(tx));
|
||||
|
||||
}
|
||||
|
||||
private DecodedTransaction lookup(final String originalTransactionId)
|
||||
private AppleAppStoreDecodedTransaction lookup(final String originalTransactionId)
|
||||
throws RateLimitExceededException, SubscriptionNotFoundException {
|
||||
try {
|
||||
return lookupAndValidateTransaction(originalTransactionId);
|
||||
@@ -210,16 +153,16 @@ public class AppleAppStoreManager implements SubscriptionPaymentProcessor {
|
||||
}
|
||||
}
|
||||
|
||||
private DecodedTransaction lookupAndValidateTransaction(final String originalTransactionId)
|
||||
private AppleAppStoreDecodedTransaction lookupAndValidateTransaction(final String originalTransactionId)
|
||||
throws SubscriptionInvalidArgumentsException, RateLimitExceededException, SubscriptionNotFoundException {
|
||||
final StatusResponse statuses = getAllSubscriptions(originalTransactionId);
|
||||
final StatusResponse statuses = appleAppStoreClient.getAllSubscriptions(originalTransactionId);
|
||||
final SubscriptionGroupIdentifierItem item = statuses.getData().stream()
|
||||
.filter(s -> subscriptionGroupId.equals(s.getSubscriptionGroupIdentifier())).findFirst()
|
||||
.orElseThrow(() -> new SubscriptionInvalidArgumentsException("transaction did not contain a backup subscription", null));
|
||||
|
||||
final List<DecodedTransaction> txs = item.getLastTransactions().stream()
|
||||
.map(this::decode)
|
||||
.filter(decoded -> productIdToLevel.containsKey(decoded.transaction.getProductId()))
|
||||
final List<AppleAppStoreDecodedTransaction> txs = item.getLastTransactions().stream()
|
||||
.map(txItem -> appleAppStoreClient.verify(statuses.getEnvironment(), txItem))
|
||||
.filter(decoded -> productIdToLevel.containsKey(decoded.transaction().getProductId()))
|
||||
.toList();
|
||||
|
||||
if (txs.isEmpty()) {
|
||||
@@ -231,7 +174,7 @@ public class AppleAppStoreManager implements SubscriptionPaymentProcessor {
|
||||
originalTransactionId);
|
||||
}
|
||||
|
||||
if (!originalTransactionId.equals(txs.getFirst().signedTransaction.getOriginalTransactionId())) {
|
||||
if (!originalTransactionId.equals(txs.getFirst().signedTransaction().getOriginalTransactionId())) {
|
||||
// Get All Subscriptions only requires that the transaction be some transaction associated with the
|
||||
// subscription. This is too flexible, since we'd like to key on the originalTransactionId in the
|
||||
// SubscriptionManager.
|
||||
@@ -240,74 +183,18 @@ public class AppleAppStoreManager implements SubscriptionPaymentProcessor {
|
||||
return txs.getFirst();
|
||||
}
|
||||
|
||||
private StatusResponse getAllSubscriptions(final String originalTransactionId)
|
||||
throws SubscriptionNotFoundException, SubscriptionInvalidArgumentsException, RateLimitExceededException {
|
||||
try {
|
||||
return retry.executeCallable(() -> {
|
||||
try {
|
||||
return apiClient.getAllSubscriptionStatuses(originalTransactionId, EMPTY_STATUSES);
|
||||
} catch (final APIException e) {
|
||||
Metrics.counter(GET_SUBSCRIPTION_ERROR_COUNTER_NAME, "reason", e.getApiError().name()).increment();
|
||||
throw switch (e.getApiError()) {
|
||||
case ORIGINAL_TRANSACTION_ID_NOT_FOUND, TRANSACTION_ID_NOT_FOUND -> new SubscriptionNotFoundException();
|
||||
case RATE_LIMIT_EXCEEDED -> new RateLimitExceededException(null);
|
||||
case INVALID_ORIGINAL_TRANSACTION_ID -> new SubscriptionInvalidArgumentsException(e.getApiErrorMessage());
|
||||
default -> e;
|
||||
};
|
||||
} catch (final IOException e) {
|
||||
Metrics.counter(GET_SUBSCRIPTION_ERROR_COUNTER_NAME, "reason", "io_error").increment();
|
||||
throw e;
|
||||
}
|
||||
});
|
||||
} catch (SubscriptionNotFoundException | SubscriptionInvalidArgumentsException | RateLimitExceededException e) {
|
||||
throw e;
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
} catch (APIException e) {
|
||||
throw new UncheckedIOException(new IOException(e));
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean shouldRetry(Throwable e) {
|
||||
return e instanceof APIException apiException && switch (apiException.getApiError()) {
|
||||
case ORIGINAL_TRANSACTION_ID_NOT_FOUND_RETRYABLE, GENERAL_INTERNAL_RETRYABLE, APP_NOT_FOUND_RETRYABLE -> true;
|
||||
default -> false;
|
||||
};
|
||||
}
|
||||
|
||||
private record DecodedTransaction(
|
||||
LastTransactionsItem signedTransaction,
|
||||
JWSTransactionDecodedPayload transaction,
|
||||
JWSRenewalInfoDecodedPayload renewalInfo) {}
|
||||
|
||||
/**
|
||||
* Verify signature and decode transaction payloads
|
||||
*/
|
||||
private DecodedTransaction decode(final LastTransactionsItem tx) {
|
||||
try {
|
||||
return new DecodedTransaction(
|
||||
tx,
|
||||
signedDataVerifier.verifyAndDecodeTransaction(tx.getSignedTransactionInfo()),
|
||||
signedDataVerifier.verifyAndDecodeRenewalInfo(tx.getSignedRenewalInfo()));
|
||||
} catch (VerificationException e) {
|
||||
throw new UncheckedIOException(new IOException("Failed to verify payload from App Store Server", e));
|
||||
}
|
||||
}
|
||||
|
||||
private SubscriptionPrice getSubscriptionPrice(final DecodedTransaction tx) {
|
||||
final BigDecimal amount = new BigDecimal(tx.transaction.getPrice()).scaleByPowerOfTen(-3);
|
||||
private SubscriptionPrice getSubscriptionPrice(final AppleAppStoreDecodedTransaction tx) {
|
||||
final BigDecimal amount = new BigDecimal(tx.transaction().getPrice()).scaleByPowerOfTen(-3);
|
||||
return new SubscriptionPrice(
|
||||
tx.transaction.getCurrency().toUpperCase(Locale.ROOT),
|
||||
SubscriptionCurrencyUtil.convertConfiguredAmountToApiAmount(tx.transaction.getCurrency(), amount));
|
||||
tx.transaction().getCurrency().toUpperCase(Locale.ROOT),
|
||||
SubscriptionCurrencyUtil.convertConfiguredAmountToApiAmount(tx.transaction().getCurrency(), amount));
|
||||
}
|
||||
|
||||
private long getLevel(final DecodedTransaction tx) {
|
||||
final Long level = productIdToLevel.get(tx.transaction.getProductId());
|
||||
private long getLevel(final AppleAppStoreDecodedTransaction tx) {
|
||||
final Long level = productIdToLevel.get(tx.transaction().getProductId());
|
||||
if (level == null) {
|
||||
throw new UncheckedIOException(new IOException(
|
||||
"Transaction for unknown productId " + tx.transaction.getProductId()));
|
||||
"Transaction for unknown productId " + tx.transaction().getProductId()));
|
||||
}
|
||||
return level;
|
||||
}
|
||||
@@ -315,16 +202,9 @@ public class AppleAppStoreManager implements SubscriptionPaymentProcessor {
|
||||
/**
|
||||
* Return true if the subscription's entitlement can currently be granted
|
||||
*/
|
||||
private boolean isSubscriptionActive(final DecodedTransaction tx) {
|
||||
return tx.signedTransaction.getStatus() == Status.ACTIVE
|
||||
|| tx.signedTransaction.getStatus() == Status.BILLING_GRACE_PERIOD;
|
||||
}
|
||||
|
||||
private static Set<InputStream> decodeRootCerts(final List<String> rootCerts) {
|
||||
return rootCerts.stream()
|
||||
.map(Base64.getDecoder()::decode)
|
||||
.map(ByteArrayInputStream::new)
|
||||
.collect(Collectors.toSet());
|
||||
private boolean isSubscriptionActive(final AppleAppStoreDecodedTransaction tx) {
|
||||
return tx.signedTransaction().getStatus() == Status.ACTIVE
|
||||
|| tx.signedTransaction().getStatus() == Status.BILLING_GRACE_PERIOD;
|
||||
}
|
||||
|
||||
}
|
||||
+8
-28
@@ -13,10 +13,8 @@ import com.google.api.services.androidpublisher.AndroidPublisher;
|
||||
import com.google.api.services.androidpublisher.AndroidPublisherRequest;
|
||||
import com.google.api.services.androidpublisher.AndroidPublisherScopes;
|
||||
import com.google.api.services.androidpublisher.model.AutoRenewingPlan;
|
||||
import com.google.api.services.androidpublisher.model.BasePlan;
|
||||
import com.google.api.services.androidpublisher.model.Money;
|
||||
import com.google.api.services.androidpublisher.model.OfferDetails;
|
||||
import com.google.api.services.androidpublisher.model.RegionalBasePlanConfig;
|
||||
import com.google.api.services.androidpublisher.model.Subscription;
|
||||
import com.google.api.services.androidpublisher.model.SubscriptionPurchaseLineItem;
|
||||
import com.google.api.services.androidpublisher.model.SubscriptionPurchaseV2;
|
||||
import com.google.api.services.androidpublisher.model.SubscriptionPurchasesAcknowledgeRequest;
|
||||
@@ -37,7 +35,6 @@ import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
@@ -130,7 +127,6 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor {
|
||||
* Acknowledge the purchase to the play billing server. If a purchase is never acknowledged, it will eventually be
|
||||
* refunded.
|
||||
*
|
||||
* @return A stage that completes when the purchase has been successfully acknowledged
|
||||
*/
|
||||
public void acknowledgePurchase()
|
||||
throws RateLimitExceededException, SubscriptionNotFoundException {
|
||||
@@ -269,32 +265,16 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor {
|
||||
}
|
||||
|
||||
private SubscriptionPrice getSubscriptionPrice(final SubscriptionPurchaseV2 subscriptionPurchase) {
|
||||
|
||||
final SubscriptionPurchaseLineItem lineItem = getLineItem(subscriptionPurchase);
|
||||
final OfferDetails offerDetails = lineItem.getOfferDetails();
|
||||
final String basePlanId = offerDetails.getBasePlanId();
|
||||
|
||||
try {
|
||||
final Subscription subscription = this.androidPublisher.monetization().subscriptions()
|
||||
.get(packageName, lineItem.getProductId()).execute();
|
||||
|
||||
final BasePlan basePlan = subscription.getBasePlans().stream()
|
||||
.filter(bp -> bp.getBasePlanId().equals(basePlanId))
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new UncheckedIOException(new IOException("unknown basePlanId " + basePlanId)));
|
||||
final String region = subscriptionPurchase.getRegionCode();
|
||||
final RegionalBasePlanConfig basePlanConfig = basePlan.getRegionalConfigs()
|
||||
.stream()
|
||||
.filter(rbpc -> Objects.equals(region, rbpc.getRegionCode()))
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new UncheckedIOException(new IOException("unknown subscription region " + region)));
|
||||
|
||||
return new SubscriptionPrice(
|
||||
basePlanConfig.getPrice().getCurrencyCode().toUpperCase(Locale.ROOT),
|
||||
SubscriptionCurrencyUtil.convertGoogleMoneyToApiAmount(basePlanConfig.getPrice()));
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
// We don't offer pre-paid plans, so autoRenewingPlan must be nonnull
|
||||
if (lineItem.getAutoRenewingPlan() == null) {
|
||||
throw new UncheckedIOException(new IOException("Subscription purchases must be auto-renewing plans"));
|
||||
}
|
||||
final Money price = lineItem.getAutoRenewingPlan().getRecurringPrice();
|
||||
return new SubscriptionPrice(
|
||||
price.getCurrencyCode().toUpperCase(Locale.ROOT),
|
||||
SubscriptionCurrencyUtil.convertGoogleMoneyToApiAmount(price));
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
+98
-68
@@ -6,7 +6,6 @@
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.common.base.Strings;
|
||||
import com.google.common.collect.Lists;
|
||||
import com.stripe.Stripe;
|
||||
import com.stripe.StripeClient;
|
||||
@@ -18,6 +17,7 @@ import com.stripe.model.Charge;
|
||||
import com.stripe.model.Customer;
|
||||
import com.stripe.model.Invoice;
|
||||
import com.stripe.model.InvoiceLineItem;
|
||||
import com.stripe.model.InvoicePayment;
|
||||
import com.stripe.model.PaymentIntent;
|
||||
import com.stripe.model.Price;
|
||||
import com.stripe.model.Product;
|
||||
@@ -26,11 +26,11 @@ import com.stripe.model.StripeCollection;
|
||||
import com.stripe.model.Subscription;
|
||||
import com.stripe.model.SubscriptionItem;
|
||||
import com.stripe.net.RequestOptions;
|
||||
import com.stripe.param.ChargeRetrieveParams;
|
||||
import com.stripe.param.CustomerCreateParams;
|
||||
import com.stripe.param.CustomerRetrieveParams;
|
||||
import com.stripe.param.CustomerUpdateParams;
|
||||
import com.stripe.param.CustomerUpdateParams.InvoiceSettings;
|
||||
import com.stripe.param.InvoiceListParams;
|
||||
import com.stripe.param.PaymentIntentCreateParams;
|
||||
import com.stripe.param.PaymentIntentRetrieveParams;
|
||||
import com.stripe.param.PriceRetrieveParams;
|
||||
@@ -49,7 +49,6 @@ import java.io.UncheckedIOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.InvalidKeyException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
@@ -61,6 +60,7 @@ import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionException;
|
||||
@@ -117,7 +117,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
@Nonnull Map<PaymentMethod, Set<String>> supportedCurrenciesByPaymentMethod) {
|
||||
this(new StripeClient(apiKey), executor, idempotencyKeyGenerator, boostDescription, supportedCurrenciesByPaymentMethod);
|
||||
|
||||
if (Strings.isNullOrEmpty(apiKey)) {
|
||||
if (StringUtils.isEmpty(apiKey)) {
|
||||
throw new IllegalArgumentException("apiKey cannot be empty");
|
||||
}
|
||||
}
|
||||
@@ -154,7 +154,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
}
|
||||
|
||||
try {
|
||||
final Customer customer = stripeClient.customers()
|
||||
final Customer customer = stripeClient.v1().customers()
|
||||
.create(builder.build(), commonOptions(generateIdempotencyKeyForSubscriberUser(subscriberUser)));
|
||||
return new ProcessorCustomer(customer.getId(), getProvider());
|
||||
} catch (StripeException e) {
|
||||
@@ -165,7 +165,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
public Customer getCustomer(String customerId) {
|
||||
CustomerRetrieveParams params = CustomerRetrieveParams.builder().build();
|
||||
try {
|
||||
return stripeClient.customers().retrieve(customerId, params, commonOptions());
|
||||
return stripeClient.v1().customers().retrieve(customerId, params, commonOptions());
|
||||
} catch (StripeException e) {
|
||||
throw new UncheckedIOException(new IOException(e));
|
||||
}
|
||||
@@ -180,7 +180,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
.build())
|
||||
.build();
|
||||
try {
|
||||
stripeClient.customers().update(customerId, params, commonOptions());
|
||||
stripeClient.v1().customers().update(customerId, params, commonOptions());
|
||||
} catch (InvalidRequestException e) {
|
||||
// Could happen if the paymentMethodId was bunk or the client didn't actually finish setting it up
|
||||
throw new SubscriptionInvalidArgumentsException(e.getMessage());
|
||||
@@ -195,7 +195,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
.setCustomer(customerId)
|
||||
.build();
|
||||
try {
|
||||
return stripeClient.setupIntents().create(params, commonOptions()).getClientSecret();
|
||||
return stripeClient.v1().setupIntents().create(params, commonOptions()).getClientSecret();
|
||||
} catch (StripeException e) {
|
||||
throw new UncheckedIOException(new IOException(e));
|
||||
}
|
||||
@@ -228,7 +228,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
}
|
||||
|
||||
try {
|
||||
return stripeClient.paymentIntents().create(builder.build(), commonOptions());
|
||||
return stripeClient.v1().paymentIntents().create(builder.build(), commonOptions());
|
||||
} catch (StripeException e) {
|
||||
final String errorCode = StringUtils.lowerCase(e.getCode(), Locale.ROOT);
|
||||
switch (errorCode) {
|
||||
@@ -243,9 +243,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
public CompletableFuture<PaymentDetails> getPaymentDetails(String paymentIntentId) {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
try {
|
||||
final PaymentIntentRetrieveParams params = PaymentIntentRetrieveParams.builder()
|
||||
.addExpand("latest_charge").build();
|
||||
final PaymentIntent paymentIntent = stripeClient.paymentIntents().retrieve(paymentIntentId, params, commonOptions());
|
||||
final PaymentIntent paymentIntent = getPaymentIntent(paymentIntentId);
|
||||
|
||||
ChargeFailure chargeFailure = null;
|
||||
if (paymentIntent.getLatestChargeObject() != null) {
|
||||
@@ -302,7 +300,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
//
|
||||
// If the client tells the server several times in a row before the initial creation of a subscription to
|
||||
// create a subscription, we want to ensure only one gets created.
|
||||
final Subscription subscription = stripeClient.subscriptions().create(
|
||||
final Subscription subscription = stripeClient.v1().subscriptions().create(
|
||||
params,
|
||||
commonOptions(generateIdempotencyKeyForCreateSubscription(customerId, lastSubscriptionCreatedAt)));
|
||||
return new SubscriptionId(subscription.getId());
|
||||
@@ -332,7 +330,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
|
||||
List<SubscriptionUpdateParams.Item> items = new ArrayList<>();
|
||||
try {
|
||||
final StripeCollection<SubscriptionItem> subscriptionItems = stripeClient.subscriptionItems()
|
||||
final StripeCollection<SubscriptionItem> subscriptionItems = stripeClient.v1().subscriptionItems()
|
||||
.list(SubscriptionItemListParams.builder().setSubscription(subscription.getId()).build(),
|
||||
commonOptions());
|
||||
for (final SubscriptionItem item : subscriptionItems.autoPagingIterable()) {
|
||||
@@ -355,7 +353,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
.setPaymentBehavior(SubscriptionUpdateParams.PaymentBehavior.ERROR_IF_INCOMPLETE)
|
||||
.addAllItem(items)
|
||||
.build();
|
||||
final Subscription subscription1 = stripeClient.subscriptions().update(subscription.getId(), params,
|
||||
final Subscription subscription1 = stripeClient.v1().subscriptions().update(subscription.getId(), params,
|
||||
commonOptions(generateIdempotencyKeyForSubscriptionUpdate(subscription.getCustomer(), idempotencyKey)));
|
||||
return new SubscriptionId(subscription1.getId());
|
||||
} catch (IdempotencyException e) {
|
||||
@@ -367,14 +365,32 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
}
|
||||
}
|
||||
|
||||
/// Retrieves the subscription object with `latest_invoice.payments` expanded
|
||||
@Override
|
||||
public Object getSubscription(String subscriptionId) {
|
||||
SubscriptionRetrieveParams params = SubscriptionRetrieveParams.builder()
|
||||
.addExpand("latest_invoice")
|
||||
.addExpand("latest_invoice.charge")
|
||||
.addExpand("latest_invoice.payments")
|
||||
.build();
|
||||
try {
|
||||
return stripeClient.subscriptions().retrieve(subscriptionId, params, commonOptions());
|
||||
return stripeClient.v1().subscriptions().retrieve(subscriptionId, params, commonOptions());
|
||||
} catch (StripeException e) {
|
||||
throw new UncheckedIOException(new IOException(e));
|
||||
}
|
||||
}
|
||||
|
||||
/// Retrieves the payment intent object with `latest_charge` expanded
|
||||
public PaymentIntent getPaymentIntent(String paymentIntentId) throws StripeException {
|
||||
PaymentIntentRetrieveParams params = PaymentIntentRetrieveParams.builder()
|
||||
.addExpand("latest_charge")
|
||||
.build();
|
||||
return stripeClient.v1().paymentIntents().retrieve(paymentIntentId, params, commonOptions());
|
||||
}
|
||||
|
||||
public Charge getCharge(String chargeId) {
|
||||
ChargeRetrieveParams params = ChargeRetrieveParams.builder()
|
||||
.build();
|
||||
try {
|
||||
return stripeClient.v1().charges().retrieve(chargeId, params, commonOptions());
|
||||
} catch (StripeException e) {
|
||||
throw new UncheckedIOException(new IOException(e));
|
||||
}
|
||||
@@ -409,7 +425,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
.build();
|
||||
try {
|
||||
return Lists.newArrayList(
|
||||
stripeClient.subscriptions().list(params, commonOptions()).autoPagingIterable());
|
||||
stripeClient.v1().subscriptions().list(params, commonOptions()).autoPagingIterable());
|
||||
} catch (StripeException e) {
|
||||
throw new UncheckedIOException(new IOException(e));
|
||||
}
|
||||
@@ -430,7 +446,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
private Subscription cancelSubscriptionImmediately(Subscription subscription) {
|
||||
SubscriptionCancelParams params = SubscriptionCancelParams.builder().build();
|
||||
try {
|
||||
return stripeClient.subscriptions().cancel(subscription.getId(), params, commonOptions());
|
||||
return stripeClient.v1().subscriptions().cancel(subscription.getId(), params, commonOptions());
|
||||
} catch (StripeException e) {
|
||||
throw new UncheckedIOException(new IOException(e));
|
||||
}
|
||||
@@ -441,7 +457,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
.setCancelAtPeriodEnd(true)
|
||||
.build();
|
||||
try {
|
||||
return stripeClient.subscriptions().update(subscription.getId(), params, commonOptions());
|
||||
return stripeClient.v1().subscriptions().update(subscription.getId(), params, commonOptions());
|
||||
} catch (StripeException e) {
|
||||
throw new UncheckedIOException(new IOException(e));
|
||||
}
|
||||
@@ -449,7 +465,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
|
||||
public Collection<SubscriptionItem> getItemsForSubscription(Subscription subscription) {
|
||||
try {
|
||||
final StripeCollection<SubscriptionItem> subscriptionItems = stripeClient.subscriptionItems().list(
|
||||
final StripeCollection<SubscriptionItem> subscriptionItems = stripeClient.v1().subscriptionItems().list(
|
||||
SubscriptionItemListParams.builder().setSubscription(subscription.getId()).build(), commonOptions());
|
||||
return Lists.newArrayList(subscriptionItems.autoPagingIterable());
|
||||
|
||||
@@ -491,7 +507,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
public Product getProductForPrice(String priceId) {
|
||||
PriceRetrieveParams params = PriceRetrieveParams.builder().addExpand("product").build();
|
||||
try {
|
||||
return stripeClient.prices().retrieve(priceId, params, commonOptions()).getProductObject();
|
||||
return stripeClient.v1().prices().retrieve(priceId, params, commonOptions()).getProductObject();
|
||||
} catch (StripeException e) {
|
||||
throw new UncheckedIOException(new IOException(e));
|
||||
}
|
||||
@@ -501,28 +517,6 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
return Long.parseLong(product.getMetadata().get(METADATA_KEY_LEVEL));
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the paid invoices within the past 90 days for a subscription ordered by the creation date in descending
|
||||
* order (latest first).
|
||||
*/
|
||||
public Collection<Invoice> getPaidInvoicesForSubscription(String subscriptionId, Instant now) {
|
||||
InvoiceListParams params = InvoiceListParams.builder()
|
||||
.setSubscription(subscriptionId)
|
||||
.setStatus(InvoiceListParams.Status.PAID)
|
||||
.setCreated(InvoiceListParams.Created.builder()
|
||||
.setGte(now.minus(Duration.ofDays(90)).getEpochSecond())
|
||||
.build())
|
||||
.build();
|
||||
try {
|
||||
ArrayList<Invoice> invoices = Lists.newArrayList(stripeClient.invoices().list(params, commonOptions())
|
||||
.autoPagingIterable());
|
||||
invoices.sort(Comparator.comparingLong(Invoice::getCreated).reversed());
|
||||
return invoices;
|
||||
} catch (StripeException e) {
|
||||
throw new UncheckedIOException(new IOException(e));
|
||||
}
|
||||
}
|
||||
|
||||
private static ChargeFailure createChargeFailure(final Charge charge) {
|
||||
Charge.Outcome outcome = charge.getOutcome();
|
||||
return new ChargeFailure(
|
||||
@@ -557,15 +551,21 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
final Invoice invoice = subscription.getLatestInvoiceObject();
|
||||
paymentProcessing = "open".equals(invoice.getStatus());
|
||||
|
||||
if (invoice.getChargeObject() != null) {
|
||||
final Charge charge = invoice.getChargeObject();
|
||||
if (charge.getFailureCode() != null || charge.getFailureMessage() != null) {
|
||||
chargeFailure = createChargeFailure(charge);
|
||||
}
|
||||
final Optional<InvoicePayment> latestInvoicePayment = getMostRecentInvoicePayment(invoice);
|
||||
|
||||
if (charge.getPaymentMethodDetails() != null
|
||||
&& charge.getPaymentMethodDetails().getType() != null) {
|
||||
paymentMethod = getPaymentMethodFromStripeString(charge.getPaymentMethodDetails().getType(), invoice.getId());
|
||||
if (latestInvoicePayment.isPresent()) {
|
||||
final Optional<Charge> maybeCharge = getChargeForInvoicePayment(latestInvoicePayment.get());
|
||||
|
||||
if (maybeCharge.isPresent()) {
|
||||
final Charge charge = maybeCharge.get();
|
||||
if (charge.getFailureCode() != null || charge.getFailureMessage() != null) {
|
||||
chargeFailure = createChargeFailure(charge);
|
||||
}
|
||||
|
||||
if (charge.getPaymentMethodDetails() != null
|
||||
&& charge.getPaymentMethodDetails().getType() != null) {
|
||||
paymentMethod = getPaymentMethodFromStripeString(charge.getPaymentMethodDetails().getType(), invoice.getId());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -574,7 +574,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
new SubscriptionPrice(price.getCurrency().toUpperCase(Locale.ROOT), price.getUnitAmountDecimal()),
|
||||
level,
|
||||
Instant.ofEpochSecond(subscription.getBillingCycleAnchor()),
|
||||
Instant.ofEpochSecond(subscription.getCurrentPeriodEnd()),
|
||||
Instant.ofEpochSecond(subscription.getItems().getData().getFirst().getCurrentPeriodEnd()),
|
||||
Objects.equals(subscription.getStatus(), "active"),
|
||||
subscription.getCancelAtPeriodEnd(),
|
||||
getSubscriptionStatus(subscription.getStatus()),
|
||||
@@ -616,23 +616,33 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
if (latestSubscriptionInvoice == null) {
|
||||
throw new SubscriptionReceiptRequestedForOpenPaymentException();
|
||||
}
|
||||
if (StringUtils.equalsIgnoreCase("open", latestSubscriptionInvoice.getStatus())) {
|
||||
if ("open".equalsIgnoreCase(latestSubscriptionInvoice.getStatus())) {
|
||||
throw new SubscriptionReceiptRequestedForOpenPaymentException();
|
||||
}
|
||||
if (!StringUtils.equalsIgnoreCase("paid", latestSubscriptionInvoice.getStatus())) {
|
||||
final Charge charge = latestSubscriptionInvoice.getChargeObject();
|
||||
if (charge != null && (charge.getFailureCode() != null || charge.getFailureMessage() != null)) {
|
||||
// If the charge object has a failure reason we can present to the user, create a detailed exception
|
||||
throw new SubscriptionChargeFailurePaymentRequiredException(getProvider(), createChargeFailure(charge));
|
||||
} else {
|
||||
// Otherwise, return a generic payment required error
|
||||
throw new SubscriptionPaymentRequiredException();
|
||||
}
|
||||
if (!"paid".equalsIgnoreCase(latestSubscriptionInvoice.getStatus())) {
|
||||
|
||||
final Optional<InvoicePayment> latestInvoicePayment = getMostRecentInvoicePayment(latestSubscriptionInvoice);
|
||||
|
||||
final SubscriptionPaymentRequiredException exception = latestInvoicePayment.map(invoicePayment -> {
|
||||
|
||||
final Optional<Charge> maybeCharge = getChargeForInvoicePayment(invoicePayment);
|
||||
|
||||
return maybeCharge.filter(charge -> charge.getFailureCode() != null || charge.getFailureMessage() != null)
|
||||
.map(charge -> {
|
||||
// If the charge object has a failure reason we can present to the user, create a detailed exception
|
||||
return (SubscriptionPaymentRequiredException) (new SubscriptionChargeFailurePaymentRequiredException(
|
||||
getProvider(), createChargeFailure(charge)));
|
||||
})
|
||||
.orElseGet(SubscriptionPaymentRequiredException::new);
|
||||
})
|
||||
.orElseGet(SubscriptionPaymentRequiredException::new);
|
||||
|
||||
throw exception;
|
||||
}
|
||||
|
||||
final Collection<InvoiceLineItem> invoiceLineItems = getInvoiceLineItemsForInvoice(latestSubscriptionInvoice);
|
||||
Collection<InvoiceLineItem> subscriptionLineItems = invoiceLineItems.stream()
|
||||
.filter(invoiceLineItem -> Objects.equals("subscription", invoiceLineItem.getType()))
|
||||
.filter(invoiceLineItem -> "subscription_item_details".equalsIgnoreCase(invoiceLineItem.getParent().getType()))
|
||||
.toList();
|
||||
if (subscriptionLineItems.isEmpty()) {
|
||||
throw new IllegalStateException("latest subscription invoice has no subscription line items; subscriptionId="
|
||||
@@ -657,7 +667,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
invoice.getId());
|
||||
paidAt = Instant.ofEpochSecond(subscriptionLineItem.getPeriod().getStart());
|
||||
}
|
||||
final Product product = getProductForPrice(subscriptionLineItem.getPrice().getId());
|
||||
final Product product = getProductForPrice(subscriptionLineItem.getPricing().getPriceDetails().getPrice());
|
||||
return new ReceiptItem(
|
||||
subscriptionLineItem.getId(),
|
||||
PaymentTime.periodStart(paidAt),
|
||||
@@ -666,7 +676,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
|
||||
public Collection<InvoiceLineItem> getInvoiceLineItemsForInvoice(Invoice invoice) {
|
||||
try {
|
||||
final StripeCollection<InvoiceLineItem> lineItems = stripeClient.invoices().lineItems()
|
||||
final StripeCollection<InvoiceLineItem> lineItems = stripeClient.v1().invoices().lineItems()
|
||||
.list(invoice.getId(), commonOptions());
|
||||
return Lists.newArrayList(lineItems.autoPagingIterable());
|
||||
} catch (final StripeException e) {
|
||||
@@ -680,7 +690,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
.addExpand("latest_attempt")
|
||||
.build();
|
||||
try {
|
||||
final SetupIntent setupIntent = stripeClient.setupIntents().retrieve(setupIntentId, params, commonOptions());
|
||||
final SetupIntent setupIntent = stripeClient.v1().setupIntents().retrieve(setupIntentId, params, commonOptions());
|
||||
if (setupIntent.getLatestAttemptObject() == null
|
||||
|| setupIntent.getLatestAttemptObject().getPaymentMethodDetails() == null
|
||||
|| setupIntent.getLatestAttemptObject().getPaymentMethodDetails().getIdeal() == null
|
||||
@@ -701,6 +711,26 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
}, executor);
|
||||
}
|
||||
|
||||
private Optional<InvoicePayment> getMostRecentInvoicePayment(final Invoice invoice) {
|
||||
final List<InvoicePayment> sorted = new ArrayList<>(invoice.getPayments().getData());
|
||||
sorted.sort(Comparator.comparingLong(InvoicePayment::getCreated).reversed());
|
||||
|
||||
return sorted.isEmpty() ? Optional.empty() : Optional.of(sorted.getFirst());
|
||||
}
|
||||
|
||||
private Optional<Charge> getChargeForInvoicePayment(final InvoicePayment invoicePayment) {
|
||||
return Optional.ofNullable(invoicePayment.getPayment().getPaymentIntent())
|
||||
.map(paymentIntentId -> {
|
||||
try {
|
||||
return getPaymentIntent(paymentIntentId);
|
||||
} catch (final StripeException e) {
|
||||
throw new UncheckedIOException(new IOException(e));
|
||||
}
|
||||
})
|
||||
.map(PaymentIntent::getLatestChargeObject)
|
||||
.or(() -> Optional.ofNullable(invoicePayment.getPayment().getCharge()).map(this::getCharge));
|
||||
}
|
||||
|
||||
/**
|
||||
* We use a client generated idempotency key for subscription updates due to not being able to distinguish between a
|
||||
* call to update to level 2, then back to level 1, then back to level 2. If this all happens within Stripe's
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
package org.whispersystems.textsecuregcm.util;
|
||||
|
||||
import io.dropwizard.lifecycle.Managed;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import javax.management.MBeanServer;
|
||||
import java.lang.management.ManagementFactory;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
public class JmxDumper implements Managed {
|
||||
private static final Logger log = LoggerFactory.getLogger(JmxDumper.class);
|
||||
|
||||
|
||||
private final ScheduledExecutorService executor;
|
||||
|
||||
public JmxDumper(final ScheduledExecutorService executor) {
|
||||
this.executor = executor;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void start() throws Exception {
|
||||
// executor.schedule()
|
||||
}
|
||||
|
||||
private void dump() {
|
||||
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
|
||||
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -35,7 +35,7 @@ import reactor.core.scheduler.Scheduler;
|
||||
|
||||
public class AuthenticatedConnectListener implements WebSocketConnectListener {
|
||||
|
||||
private static final String OPEN_WEBSOCKET_GAUGE_NAME = name(WebSocketConnection.class, "openWebsockets");
|
||||
private static final String OPEN_WEBSOCKET_GAUGE_NAME = name(AuthenticatedConnectListener.class, "openWebsockets");
|
||||
private static final String NEW_CONNECTION_COUNTER_NAME = name(AuthenticatedConnectListener.class, "newConnections");
|
||||
private static final String CONNECTED_DURATION_TIMER_NAME =
|
||||
name(AuthenticatedConnectListener.class, "connectedDuration");
|
||||
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package org.whispersystems.textsecuregcm.websocket;
|
||||
|
||||
import org.eclipse.jetty.websocket.core.ExtensionConfig;
|
||||
import org.eclipse.jetty.websocket.core.WebSocketComponents;
|
||||
import org.eclipse.jetty.websocket.core.internal.PerMessageDeflateExtension;
|
||||
|
||||
/// A variant of the Jetty {@link PerMessageDeflateExtension} that always negotiates the [server_no_context_takeover
|
||||
/// extension parameter](https://datatracker.ietf.org/doc/html/rfc7692#section-7.1.1.1)
|
||||
public final class NoContextTakeoverPerMessageDeflateExtension extends PerMessageDeflateExtension {
|
||||
|
||||
@Override
|
||||
public void init(ExtensionConfig config, WebSocketComponents components) {
|
||||
config.setParameter("server_no_context_takeover");
|
||||
super.init(config, components);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -5,7 +5,7 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.websocket;
|
||||
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
|
||||
+1
-1
@@ -58,7 +58,7 @@ public abstract class AbstractCommandWithDependencies extends EnvironmentCommand
|
||||
|
||||
} finally {
|
||||
logger.info("Stopping command dependencies");
|
||||
environment.lifecycle().getManagedObjects().forEach(managedObject -> {
|
||||
environment.lifecycle().getManagedObjects().reversed().forEach(managedObject -> {
|
||||
try {
|
||||
managedObject.stop();
|
||||
} catch (final Exception e) {
|
||||
|
||||
+45
-40
@@ -5,9 +5,6 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.workers;
|
||||
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
|
||||
import com.codahale.metrics.MetricRegistry;
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import io.dropwizard.core.setup.Environment;
|
||||
import io.lettuce.core.resource.ClientResources;
|
||||
@@ -25,7 +22,8 @@ import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.ServerSecretParams;
|
||||
import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerService;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerService.ExecutorServiceBuilder;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerService.ScheduledExecutorServiceBuilder;
|
||||
import org.whispersystems.textsecuregcm.attachments.TusAttachmentGenerator;
|
||||
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestManager;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
|
||||
@@ -77,9 +75,11 @@ import org.whispersystems.textsecuregcm.storage.SingleUseECPreKeyStore;
|
||||
import org.whispersystems.textsecuregcm.storage.SingleUseKEMPreKeyStore;
|
||||
import org.whispersystems.textsecuregcm.storage.SubscriptionManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Subscriptions;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.AppleAppStoreClient;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.AppleAppStoreManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.GooglePlayBillingManager;
|
||||
import org.whispersystems.textsecuregcm.util.ManagedAwsCrt;
|
||||
import org.whispersystems.textsecuregcm.util.ManagedExecutors;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
import reactor.core.scheduler.Schedulers;
|
||||
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
|
||||
@@ -91,7 +91,7 @@ import software.amazon.awssdk.services.s3.S3AsyncClient;
|
||||
/**
|
||||
* Construct utilities commonly used by worker commands
|
||||
*/
|
||||
record CommandDependencies(
|
||||
public record CommandDependencies(
|
||||
AccountsManager accountsManager,
|
||||
ProfilesManager profilesManager,
|
||||
ReportMessageManager reportMessageManager,
|
||||
@@ -129,8 +129,8 @@ record CommandDependencies(
|
||||
|
||||
final AwsCredentialsProvider awsCredentialsProvider = configuration.getAwsCredentialsConfiguration().build();
|
||||
|
||||
ScheduledExecutorService dynamicConfigurationExecutor = environment.lifecycle()
|
||||
.scheduledExecutorService(name(WhisperServerService.class, "dynamicConfiguration-%d")).threads(1).build();
|
||||
ScheduledExecutorService dynamicConfigurationExecutor = ScheduledExecutorServiceBuilder.of(environment, "dynamicConfiguration")
|
||||
.threads(1).build();
|
||||
|
||||
DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager =
|
||||
new DynamicConfigurationManager<>(
|
||||
@@ -150,33 +150,35 @@ record CommandDependencies(
|
||||
|
||||
Scheduler messageDeliveryScheduler = Schedulers.fromExecutorService(
|
||||
environment.lifecycle().executorService("messageDelivery").minThreads(4).maxThreads(4).build());
|
||||
ExecutorService messageDeletionExecutor = environment.lifecycle()
|
||||
.executorService(name(WhisperServerService.class, "messageDeletion-%d")).minThreads(4).maxThreads(4).build();
|
||||
ExecutorService secureValueRecoveryServiceExecutor = environment.lifecycle()
|
||||
.executorService(name(WhisperServerService.class, "secureValueRecoveryService-%d")).maxThreads(8).minThreads(8).build();
|
||||
ExecutorService storageServiceExecutor = environment.lifecycle()
|
||||
.executorService(name(WhisperServerService.class, "storageService-%d")).maxThreads(8).minThreads(8).build();
|
||||
ExecutorService accountLockExecutor = environment.lifecycle()
|
||||
.executorService(name(WhisperServerService.class, "accountLock-%d")).minThreads(8).maxThreads(8).build();
|
||||
ExecutorService remoteStorageHttpExecutor = environment.lifecycle()
|
||||
.executorService(name(WhisperServerService.class, "remoteStorage-%d"))
|
||||
ExecutorService messageDeletionExecutor = ExecutorServiceBuilder.of(environment, "messageDeletion")
|
||||
.minThreads(4).maxThreads(4).build();
|
||||
ExecutorService secureValueRecoveryServiceExecutor = ExecutorServiceBuilder.of(environment, "secureValueRecoveryService")
|
||||
.maxThreads(8).minThreads(8).build();
|
||||
ExecutorService storageServiceExecutor = ExecutorServiceBuilder.of(environment, "storageService")
|
||||
.maxThreads(8).minThreads(8).build();
|
||||
ExecutorService accountLockExecutor = ExecutorServiceBuilder.of(environment, "accountLock")
|
||||
.minThreads(8).maxThreads(8).build();
|
||||
ExecutorService remoteStorageHttpExecutor = ExecutorServiceBuilder.of(environment, "remoteStorage")
|
||||
|
||||
.minThreads(0).maxThreads(Integer.MAX_VALUE).workQueue(new SynchronousQueue<>())
|
||||
.keepAliveTime(io.dropwizard.util.Duration.seconds(60L)).build();
|
||||
ExecutorService apnSenderExecutor = environment.lifecycle().executorService(name(WhisperServerService.class, "apnSender-%d"))
|
||||
ExecutorService apnSenderExecutor = ExecutorServiceBuilder.of(environment, "apnSender")
|
||||
.maxThreads(1).minThreads(1).build();
|
||||
ExecutorService fcmSenderExecutor = environment.lifecycle().executorService(name(WhisperServerService.class, "fcmSender-%d"))
|
||||
ExecutorService fcmSenderExecutor = ExecutorServiceBuilder.of(environment, "fcmSender")
|
||||
.maxThreads(16).minThreads(16).build();
|
||||
ExecutorService clientEventExecutor = environment.lifecycle()
|
||||
.virtualExecutorService(name(WhisperServerService.class, "clientEvent-%d"));
|
||||
ExecutorService asyncOperationQueueingExecutor = environment.lifecycle()
|
||||
.executorService(name(WhisperServerService.class, "asyncOperationQueueing-%d")).minThreads(1).maxThreads(1).build();
|
||||
ExecutorService disconnectionRequestListenerExecutor = environment.lifecycle()
|
||||
.virtualExecutorService(name(WhisperServerService.class, "disconnectionRequest-%d"));
|
||||
ExecutorService clientEventExecutor = ManagedExecutors.newVirtualThreadPerTaskExecutor(
|
||||
"clientEvent", configuration.getVirtualThreadConfiguration().maxConcurrentThreadsPerExecutor(), environment);
|
||||
ExecutorService asyncOperationQueueingExecutor = ExecutorServiceBuilder.of(environment, "asyncOperationQueueing")
|
||||
.minThreads(1).maxThreads(1).build();
|
||||
ExecutorService disconnectionRequestListenerExecutor = ManagedExecutors.newVirtualThreadPerTaskExecutor(
|
||||
"disconnectionRequest",
|
||||
configuration.getVirtualThreadConfiguration().maxConcurrentThreadsPerExecutor(),
|
||||
environment);
|
||||
|
||||
final ScheduledExecutorService messagePollExecutor = environment.lifecycle()
|
||||
.scheduledExecutorService(name(WhisperServerService.class, "messagePollExecutor-%d")).threads(1).build();
|
||||
final ScheduledExecutorService retryExecutor = environment.lifecycle()
|
||||
.scheduledExecutorService(name(WhisperServerService.class, "retry-%d")).threads(4).build();
|
||||
final ScheduledExecutorService messagePollExecutor = ScheduledExecutorServiceBuilder.of(environment, "messagePollExecutor")
|
||||
.threads(1).build();
|
||||
final ScheduledExecutorService retryExecutor = ScheduledExecutorServiceBuilder.of(environment, "retry")
|
||||
.threads(1).build();
|
||||
|
||||
ExternalServiceCredentialsGenerator storageCredentialsGenerator = SecureStorageController.credentialsGenerator(
|
||||
configuration.getSecureStorageServiceConfiguration());
|
||||
@@ -185,8 +187,10 @@ record CommandDependencies(
|
||||
ExternalServiceCredentialsGenerator secureValueRecoveryBCredentialsGenerator =
|
||||
SecureValueRecoveryBCredentialsGeneratorFactory.svrbCredentialsGenerator(configuration.getSvrbConfiguration());
|
||||
|
||||
final ExecutorService awsSdkMetricsExecutor = environment.lifecycle()
|
||||
.virtualExecutorService(MetricRegistry.name(WhisperServerService.class, "awsSdkMetrics-%d"));
|
||||
final ExecutorService awsSdkMetricsExecutor = ManagedExecutors.newVirtualThreadPerTaskExecutor(
|
||||
"awsSdkMetrics",
|
||||
configuration.getVirtualThreadConfiguration().maxConcurrentThreadsPerExecutor(),
|
||||
environment);
|
||||
|
||||
DynamoDbAsyncClient dynamoDbAsyncClient = configuration.getDynamoDbClientConfiguration()
|
||||
.buildAsyncClient(awsCredentialsProvider, new MicrometerAwsSdkMetricPublisher(awsSdkMetricsExecutor, "dynamoDbAsyncCommand"));
|
||||
@@ -329,16 +333,17 @@ record CommandDependencies(
|
||||
configuration.getGooglePlayBilling().applicationName(),
|
||||
configuration.getGooglePlayBilling().productIdToLevel());
|
||||
AppleAppStoreManager appleAppStoreManager = new AppleAppStoreManager(
|
||||
configuration.getAppleAppStore().env(),
|
||||
configuration.getAppleAppStore().bundleId(),
|
||||
configuration.getAppleAppStore().appAppleId(),
|
||||
configuration.getAppleAppStore().issuerId(),
|
||||
configuration.getAppleAppStore().keyId(),
|
||||
configuration.getAppleAppStore().encodedKey().value(),
|
||||
new AppleAppStoreClient(
|
||||
configuration.getAppleAppStore().env(),
|
||||
configuration.getAppleAppStore().bundleId(),
|
||||
configuration.getAppleAppStore().appAppleId(),
|
||||
configuration.getAppleAppStore().issuerId(),
|
||||
configuration.getAppleAppStore().keyId(),
|
||||
configuration.getAppleAppStore().encodedKey().value(),
|
||||
configuration.getAppleAppStore().appleRootCerts(),
|
||||
configuration.getAppleAppStore().retryConfigurationName()),
|
||||
configuration.getAppleAppStore().subscriptionGroupId(),
|
||||
configuration.getAppleAppStore().productIdToLevel(),
|
||||
configuration.getAppleAppStore().appleRootCerts(),
|
||||
configuration.getAppleAppStore().retryConfigurationName());
|
||||
configuration.getAppleAppStore().productIdToLevel());
|
||||
final SubscriptionManager subscriptionManager = new SubscriptionManager(
|
||||
new Subscriptions(configuration.getDynamoDbTables().getSubscriptions().getTableName(), dynamoDbAsyncClient),
|
||||
List.of(googlePlayBillingManager, appleAppStoreManager),
|
||||
|
||||
+121
@@ -0,0 +1,121 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.workers;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import net.sourceforge.argparse4j.inf.Subparser;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.util.function.Tuples;
|
||||
import reactor.util.retry.Retry;
|
||||
|
||||
public class UnlinkDevicesWithIdlePrimaryCommand extends AbstractSinglePassCrawlAccountsCommand {
|
||||
|
||||
private final Clock clock;
|
||||
|
||||
@VisibleForTesting
|
||||
static final String DRY_RUN_ARGUMENT = "dry-run";
|
||||
|
||||
@VisibleForTesting
|
||||
static final String MAX_CONCURRENCY_ARGUMENT = "max-concurrency";
|
||||
|
||||
@VisibleForTesting
|
||||
static final String PRIMARY_IDLE_DAYS_ARGUMENT = "primary-idle-days";
|
||||
|
||||
@VisibleForTesting
|
||||
static final int DEFAULT_PRIMARY_IDLE_DAYS = 90;
|
||||
|
||||
private static final String UNLINK_DEVICE_COUNTER_NAME =
|
||||
MetricsUtil.name(UnlinkDevicesWithIdlePrimaryCommand.class, "unlinkDevice");
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(UnlinkDevicesWithIdlePrimaryCommand.class);
|
||||
|
||||
public UnlinkDevicesWithIdlePrimaryCommand(final Clock clock) {
|
||||
super("unlink-devices-with-idle-primary", "Unlinks linked devices if the account's primary device is idle");
|
||||
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configure(final Subparser subparser) {
|
||||
subparser.addArgument("--dry-run")
|
||||
.type(Boolean.class)
|
||||
.dest(DRY_RUN_ARGUMENT)
|
||||
.required(false)
|
||||
.setDefault(true)
|
||||
.help("If true, don't actually delete accounts");
|
||||
|
||||
subparser.addArgument("--max-concurrency")
|
||||
.type(Integer.class)
|
||||
.dest(MAX_CONCURRENCY_ARGUMENT)
|
||||
.setDefault(16)
|
||||
.help("Max concurrency for DynamoDB operations");
|
||||
|
||||
subparser.addArgument("--primary-idle-days")
|
||||
.type(Integer.class)
|
||||
.dest(PRIMARY_IDLE_DAYS_ARGUMENT)
|
||||
.required(false)
|
||||
.setDefault(DEFAULT_PRIMARY_IDLE_DAYS)
|
||||
.help("The number of inactivity after which a primary device is considered idle");
|
||||
|
||||
super.configure(subparser);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void crawlAccounts(final Flux<Account> accounts) {
|
||||
final boolean isDryRun = getNamespace().getBoolean(DRY_RUN_ARGUMENT);
|
||||
final int maxConcurrency = getNamespace().getInt(MAX_CONCURRENCY_ARGUMENT);
|
||||
final Duration idleDurationThreshold = Duration.ofDays(getNamespace().getInt(PRIMARY_IDLE_DAYS_ARGUMENT));
|
||||
|
||||
final AccountsManager accountsManager = getCommandDependencies().accountsManager();
|
||||
|
||||
final Counter unlinkDeviceCounter =
|
||||
Metrics.counter(UNLINK_DEVICE_COUNTER_NAME, "dryRun", String.valueOf(isDryRun));
|
||||
|
||||
final Instant currentTime = clock.instant();
|
||||
|
||||
accounts
|
||||
.filter(account -> isPrimaryDeviceIdle(account, currentTime, idleDurationThreshold))
|
||||
.flatMap(accountWithIdlePrimaryDevice -> Flux.fromIterable(accountWithIdlePrimaryDevice.getDevices())
|
||||
.filter(device -> !device.isPrimary())
|
||||
.map(linkedDevice -> Tuples.of(accountWithIdlePrimaryDevice, linkedDevice.getId())))
|
||||
.flatMap(accountAndLinkedDeviceId -> {
|
||||
final Mono<Account> unlinkDeviceMono = isDryRun
|
||||
? Mono.empty()
|
||||
: Mono.fromFuture(() -> accountsManager.removeDevice(accountAndLinkedDeviceId.getT1(), accountAndLinkedDeviceId.getT2()));
|
||||
|
||||
return unlinkDeviceMono
|
||||
.doOnSuccess(ignored -> unlinkDeviceCounter.increment())
|
||||
.retryWhen(Retry.backoff(3, Duration.ofSeconds(1)).maxBackoff(Duration.ofSeconds(4)))
|
||||
.onErrorResume(throwable -> {
|
||||
logger.warn("Failed to unlink device to delete account {}:{}", accountAndLinkedDeviceId.getT1().getIdentifier(
|
||||
IdentityType.ACI), accountAndLinkedDeviceId.getT2(), throwable);
|
||||
|
||||
return Mono.empty();
|
||||
});
|
||||
}, maxConcurrency)
|
||||
.then()
|
||||
.block();
|
||||
}
|
||||
|
||||
private static boolean isPrimaryDeviceIdle(final Account account, final Instant currentTime, final Duration idleDurationThreshold) {
|
||||
final Duration durationSincePrimaryLastSeen =
|
||||
Duration.between(Instant.ofEpochMilli(account.getPrimaryDevice().getLastSeen()), currentTime);
|
||||
|
||||
return durationSincePrimaryLastSeen.compareTo(idleDurationThreshold) > 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
// Copyright 2025 Signal Messenger, LLC
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
|
||||
// Note: proto2 is de-facto required here because BigQuery pub/sub
|
||||
// subscriptions demand strict matching of "modes" (i.e. nullability), and
|
||||
// the BigQuery subscription system doesn't recognize proto3 fields as
|
||||
// "required".
|
||||
syntax = "proto2";
|
||||
|
||||
package org.signal.calling.survey;
|
||||
|
||||
option java_multiple_files = true;
|
||||
|
||||
message CallQualitySurveyResponsePubSubMessage {
|
||||
// A unique identifier for this call quality survey response
|
||||
required string response_id = 1;
|
||||
|
||||
// The time at which this call quality survey response was received in
|
||||
// microseconds since the epoch (see
|
||||
// https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types#timestamp_type)
|
||||
required int64 submission_timestamp = 2;
|
||||
|
||||
// The geographic region (an ISO 3166-1 alpha-2 region code) associated with
|
||||
// the IP address of the client that submitted this call quality survey
|
||||
// response
|
||||
optional string asn_region = 3;
|
||||
|
||||
// The platform of the client that submitted this call quality survey response
|
||||
optional string client_platform = 4;
|
||||
|
||||
// The semantic version of the client that submitted this call quality survey
|
||||
// response
|
||||
optional string client_version = 5;
|
||||
|
||||
// Any additional specifiers (e.g. "Windows 10.0.19045 libsignal/0.81.1") from
|
||||
// the caller's user-agent string
|
||||
optional string client_ua_additional_specifiers = 6;
|
||||
|
||||
// Indicates whether the user was generally satisfied with the quality of the
|
||||
// call
|
||||
required bool user_satisfied = 7;
|
||||
|
||||
// A list of call quality issues selected by the user
|
||||
repeated string call_quality_issues = 8;
|
||||
|
||||
// A free-form description of any additional issues as written by the user
|
||||
optional string additional_issues_description = 9;
|
||||
|
||||
// A URL for a set of debug logs associated with the call if the user chose to
|
||||
// submit debug logs
|
||||
optional string debug_log_url = 10;
|
||||
|
||||
// The time at which the call started in microseconds since the epoch (see
|
||||
// https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types#timestamp_type)
|
||||
required int64 start_timestamp = 11;
|
||||
|
||||
// The time at which the call ended in microseconds since the epoch (see
|
||||
// https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types#timestamp_type)
|
||||
required int64 end_timestamp = 12;
|
||||
|
||||
// The type of call; note that direct voice calls can become video calls and
|
||||
// vice versa, and this field indicates which mode was selected at call
|
||||
// initiation time. At the time of writing, expected call types are
|
||||
// "direct_voice", "direct_video", "group", and "call_link".
|
||||
required string call_type = 13;
|
||||
|
||||
// Indicates whether the call completed without error or if it terminated
|
||||
// abnormally
|
||||
required bool success = 14;
|
||||
|
||||
// A client-defined, but human-readable reason for call termination
|
||||
required string call_end_reason = 15;
|
||||
|
||||
// The median round-trip time, measured in milliseconds, for STUN/ICE packets
|
||||
// (i.e. connection maintenance and establishment)
|
||||
optional float connection_rtt_median = 16;
|
||||
|
||||
// The median round-trip time, measured in milliseconds, for RTP/RTCP packets
|
||||
// for audio streams
|
||||
optional float audio_rtt_median = 17;
|
||||
|
||||
// The median round-trip time, measured in milliseconds, for RTP/RTCP packets
|
||||
// for video streams
|
||||
optional float video_rtt_median = 18;
|
||||
|
||||
// The median jitter for audio streams, measured in milliseconds, for the
|
||||
// duration of the call as measured by the client submitting the survey
|
||||
optional float audio_recv_jitter_median = 19;
|
||||
|
||||
// The median jitter for video streams, measured in milliseconds, for the
|
||||
// duration of the call as measured by the client submitting the survey
|
||||
optional float video_recv_jitter_median = 20;
|
||||
|
||||
// The median jitter for audio streams, measured in milliseconds, for the
|
||||
// duration of the call as measured by the remote endpoint in the call (either
|
||||
// the peer of the client submitting the survey in a direct call or the SFU in
|
||||
// a group call)
|
||||
optional float audio_send_jitter_median = 21;
|
||||
|
||||
// The median jitter for video streams, measured in milliseconds, for the
|
||||
// duration of the call as measured by the remote endpoint in the call (either
|
||||
// the peer of the client submitting the survey in a direct call or the SFU in
|
||||
// a group call)
|
||||
optional float video_send_jitter_median = 22;
|
||||
|
||||
// The fraction of audio packets lost over the duration of the call as
|
||||
// measured by the client submitting the survey
|
||||
optional float audio_recv_packet_loss_fraction = 23;
|
||||
|
||||
// The fraction of video packets lost over the duration of the call as
|
||||
// measured by the client submitting the survey
|
||||
optional float video_recv_packet_loss_fraction = 24;
|
||||
|
||||
// The fraction of audio packets lost over the duration of the call as
|
||||
// measured by the remote endpoint in the call (either the peer of the client
|
||||
// submitting the survey in a direct call or the SFU in a group call)
|
||||
optional float audio_send_packet_loss_fraction = 25;
|
||||
|
||||
// The fraction of video packets lost over the duration of the call as
|
||||
// measured by the remote endpoint in the call (either the peer of the client
|
||||
// submitting the survey in a direct call or the SFU in a group call)
|
||||
optional float video_send_packet_loss_fraction = 26;
|
||||
|
||||
// Technical, machine-generated data about the quality and mechanics of a
|
||||
// call; this is a serialized protobuf entity generated (and, critically,
|
||||
// explained to the user!) by the calling library
|
||||
optional bytes call_telemetry = 27;
|
||||
}
|
||||
@@ -68,6 +68,18 @@ message SearchRequest {
|
||||
* The tree head size(s) to prove consistency against.
|
||||
*/
|
||||
ConsistencyParameters consistency = 5 [(org.signal.chat.require.present) = true];
|
||||
/**
|
||||
* The version of the ACI to look up.
|
||||
*/
|
||||
optional uint32 aci_version = 6;
|
||||
/**
|
||||
* The version of the E164 to look up.
|
||||
*/
|
||||
optional uint32 e164_version = 7;
|
||||
/**
|
||||
* The version of the username hash to look up.
|
||||
*/
|
||||
optional uint32 username_hash_version = 8;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -45,6 +45,16 @@ message CreateRegistrationSessionRequest {
|
||||
* collated by this key.
|
||||
*/
|
||||
string rate_limit_collation_key = 3;
|
||||
|
||||
/**
|
||||
* The MCC for the given `e164` as reported by the client.
|
||||
*/
|
||||
string mcc = 4;
|
||||
|
||||
/**
|
||||
* The MNC for the given `e164` as reported by the client.
|
||||
*/
|
||||
string mnc = 5;
|
||||
}
|
||||
|
||||
message CreateRegistrationSessionResponse {
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
syntax = "proto3";
|
||||
|
||||
option java_multiple_files = true;
|
||||
|
||||
package org.signal.chat.calling.quality;
|
||||
|
||||
// Provides methods for submitting call quality surveys
|
||||
service CallQuality {
|
||||
|
||||
// Submits a call quality survey response.
|
||||
//
|
||||
// This RPC may fail with a `RESOURCE_EXHAUSTED` status if a rate limit for
|
||||
// submitting survey responses has been exceeded, in which case a
|
||||
// `retry-after` header containing an ISO 8601 duration string will be present
|
||||
// in the response trailers.
|
||||
rpc SubmitCallQualitySurvey(SubmitCallQualitySurveyRequest) returns (SubmitCallQualitySurveyResponse) {}
|
||||
}
|
||||
|
||||
message SubmitCallQualitySurveyRequest {
|
||||
// Indicates whether the caller was generally satisfied with the quality of
|
||||
// the call
|
||||
bool user_satisfied = 1;
|
||||
|
||||
// A list of call quality issues selected by the caller
|
||||
repeated string call_quality_issues = 2;
|
||||
|
||||
// A free-form description of any additional issues as written by the caller
|
||||
optional string additional_issues_description = 3;
|
||||
|
||||
// A URL for a set of debug logs associated with the call if the caller chose
|
||||
// to submit debug logs
|
||||
optional string debug_log_url = 4;
|
||||
|
||||
// The time at which the call started in milliseconds since the epoch
|
||||
int64 start_timestamp = 5;
|
||||
|
||||
// The time at which the call ended in milliseconds since the epoch
|
||||
int64 end_timestamp = 6;
|
||||
|
||||
// The type of call; note that direct voice calls can become video calls and
|
||||
// vice versa, and this field indicates which mode was selected at call
|
||||
// initiation time. At the time of writing, expected call types are
|
||||
// "direct_voice", "direct_video", "group", and "call_link".
|
||||
string call_type = 7;
|
||||
|
||||
// Indicates whether the call completed without error or if it terminated
|
||||
// abnormally
|
||||
bool success = 8;
|
||||
|
||||
// A client-defined, but human-readable reason for call termination
|
||||
string call_end_reason = 9;
|
||||
|
||||
// The median round-trip time, measured in milliseconds, for STUN/ICE packets
|
||||
// (i.e. connection maintenance and establishment)
|
||||
optional float connection_rtt_median = 10;
|
||||
|
||||
// The median round-trip time, measured in milliseconds, for RTP/RTCP packets
|
||||
// for audio streams
|
||||
optional float audio_rtt_median = 11;
|
||||
|
||||
// The median round-trip time, measured in milliseconds, for RTP/RTCP packets
|
||||
// for video streams
|
||||
optional float video_rtt_median = 12;
|
||||
|
||||
// The median jitter for audio streams, measured in milliseconds, for the
|
||||
// duration of the call as measured by the client submitting the survey
|
||||
optional float audio_recv_jitter_median = 13;
|
||||
|
||||
// The median jitter for video streams, measured in milliseconds, for the
|
||||
// duration of the call as measured by the client submitting the survey
|
||||
optional float video_recv_jitter_median = 14;
|
||||
|
||||
// The median jitter for audio streams, measured in milliseconds, for the
|
||||
// duration of the call as measured by the remote endpoint in the call (either
|
||||
// the peer of the client submitting the survey in a direct call or the SFU in
|
||||
// a group call)
|
||||
optional float audio_send_jitter_median = 15;
|
||||
|
||||
// The median jitter for video streams, measured in milliseconds, for the
|
||||
// duration of the call as measured by the remote endpoint in the call (either
|
||||
// the peer of the client submitting the survey in a direct call or the SFU in
|
||||
// a group call)
|
||||
optional float video_send_jitter_median = 16;
|
||||
|
||||
// The fraction of audio packets lost over the duration of the call as
|
||||
// measured by the client submitting the survey
|
||||
optional float audio_recv_packet_loss_fraction = 17;
|
||||
|
||||
// The fraction of video packets lost over the duration of the call as
|
||||
// measured by the client submitting the survey
|
||||
optional float video_recv_packet_loss_fraction = 18;
|
||||
|
||||
// The fraction of audio packets lost over the duration of the call as
|
||||
// measured by the remote endpoint in the call (either the peer of the client
|
||||
// submitting the survey in a direct call or the SFU in a group call)
|
||||
optional float audio_send_packet_loss_fraction = 19;
|
||||
|
||||
// The fraction of video packets lost over the duration of the call as
|
||||
// measured by the remote endpoint in the call (either the peer of the client
|
||||
// submitting the survey in a direct call or the SFU in a group call)
|
||||
optional float video_send_packet_loss_fraction = 20;
|
||||
|
||||
// Machine-generated telemetry from the call; this is a serialized protobuf
|
||||
// entity generated (and, critically, explained to the user!) by the calling
|
||||
// library
|
||||
optional bytes call_telemetry = 21;
|
||||
}
|
||||
|
||||
message SubmitCallQualitySurveyResponse {
|
||||
}
|
||||
@@ -97,9 +97,9 @@ enum DeviceCapability {
|
||||
DEVICE_CAPABILITY_UNSPECIFIED = 0;
|
||||
DEVICE_CAPABILITY_STORAGE = 1;
|
||||
DEVICE_CAPABILITY_TRANSFER = 2;
|
||||
DEVICE_CAPABILITY_DELETE_SYNC = 3;
|
||||
reserved 3;
|
||||
reserved 4;
|
||||
DEVICE_CAPABILITY_STORAGE_SERVICE_RECORD_KEY_ROTATION = 5;
|
||||
reserved 5;
|
||||
DEVICE_CAPABILITY_ATTACHMENT_BACKFILL = 6;
|
||||
DEVICE_CAPABILITY_SPARSE_POST_QUANTUM_RATCHET = 7;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
org.whispersystems.textsecuregcm.configuration.AwsCredentialsProviderFactory
|
||||
org.whispersystems.textsecuregcm.configuration.DatadogConfiguration
|
||||
org.whispersystems.textsecuregcm.configuration.DynamoDbClientFactory
|
||||
org.whispersystems.textsecuregcm.configuration.FaultTolerantRedisClusterFactory
|
||||
org.whispersystems.textsecuregcm.configuration.FaultTolerantRedisClientFactory
|
||||
|
||||
-1
@@ -1 +0,0 @@
|
||||
org.whispersystems.textsecuregcm.metrics.SignalDatadogReporterFactory
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
/*
|
||||
* Copyright 2013-2021 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.asn;
|
||||
|
||||
import static java.util.Objects.requireNonNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.whispersystems.textsecuregcm.asn.AsnInfoProviderImpl.ip4BytesToLong;
|
||||
import static org.whispersystems.textsecuregcm.asn.AsnInfoProviderImpl.ip6BytesToBigInteger;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.math.BigInteger;
|
||||
import java.net.Inet4Address;
|
||||
import java.net.Inet6Address;
|
||||
import java.net.InetAddress;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class AsnInfoProviderImplTest {
|
||||
|
||||
private static final String RESOURCE_NAME = "ip2asn-test.tsv";
|
||||
|
||||
@SuppressWarnings("OptionalGetWithoutIsPresent")
|
||||
@Test
|
||||
void testAsnInfo() throws IOException {
|
||||
try (final InputStream tsvInputStream = getClass().getResourceAsStream(RESOURCE_NAME)) {
|
||||
final AsnInfoProvider asnInfoProvider = AsnInfoProviderImpl.fromTsv(requireNonNull(tsvInputStream));
|
||||
assertEquals(16625L, asnInfoProvider.lookup("2.16.112.0").get().asn());
|
||||
assertEquals(16625L, asnInfoProvider.lookup("2.16.112.255").get().asn());
|
||||
assertEquals(16625L, asnInfoProvider.lookup("2.16.113.0").get().asn());
|
||||
assertEquals(16625L, asnInfoProvider.lookup("2.16.113.123").get().asn());
|
||||
assertEquals(16625L, asnInfoProvider.lookup("2.16.113.255").get().asn());
|
||||
|
||||
assertEquals("US", asnInfoProvider.lookup("2.16.113.255").get().regionCode());
|
||||
|
||||
assertEquals(4690L, asnInfoProvider.lookup("2001:200:e00::").get().asn());
|
||||
assertEquals(4690L, asnInfoProvider.lookup("2001:200:ef0::").get().asn());
|
||||
assertEquals(4690L, asnInfoProvider.lookup("2001:200:eff:ffff::").get().asn());
|
||||
assertEquals(4690L, asnInfoProvider.lookup("2001:200:eff:ffff:ffff:ffff:ffff:ffff").get().asn());
|
||||
|
||||
assertEquals("JP", asnInfoProvider.lookup("2001:200:eff:ffff:ffff:ffff:ffff:ffff").get().regionCode());
|
||||
|
||||
assertTrue(asnInfoProvider.lookup("1.3.0.0").isEmpty());
|
||||
assertTrue(asnInfoProvider.lookup("1.4.127.255").isEmpty());
|
||||
assertTrue(asnInfoProvider.lookup("2001:4:113::").isEmpty());
|
||||
assertTrue(asnInfoProvider.lookup("0.0.0.0").isEmpty());
|
||||
assertTrue(asnInfoProvider.lookup("127.0.0.1").isEmpty());
|
||||
assertTrue(asnInfoProvider.lookup("not an ip").isEmpty());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBytesToLong() throws Exception {
|
||||
assertEquals(0x00000000ffffffffL, ip4BytesToLong((Inet4Address) InetAddress.getByName("255.255.255.255")));
|
||||
assertEquals(0x0000000000000001L, ip4BytesToLong((Inet4Address) InetAddress.getByName("0.0.0.1")));
|
||||
assertEquals(0x00000000ff00ff01L, ip4BytesToLong((Inet4Address) InetAddress.getByName("255.0.255.1")));
|
||||
|
||||
final BigInteger start = ip6BytesToBigInteger((Inet6Address) InetAddress.getByName("2c0f:fff1:0:0:0:0:0:0"));
|
||||
final BigInteger end = ip6BytesToBigInteger((Inet6Address) InetAddress.getByName("fdff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"));
|
||||
assertTrue(start.compareTo(BigInteger.ZERO) >= 0);
|
||||
assertTrue(end.compareTo(BigInteger.ZERO) >= 0);
|
||||
assertTrue(start.compareTo(end) <= 0);
|
||||
}
|
||||
}
|
||||
-18
@@ -1,18 +0,0 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonTypeName;
|
||||
import java.time.Duration;
|
||||
|
||||
@JsonTypeName("nowait")
|
||||
public class NoWaitDogstatsdConfiguration extends DogstatsdConfiguration {
|
||||
|
||||
@Override
|
||||
public Duration getShutdownWaitDuration() {
|
||||
return Duration.ZERO;
|
||||
}
|
||||
}
|
||||
+6
-1
@@ -61,7 +61,12 @@ public class StubRegistrationServiceClientFactory implements RegistrationService
|
||||
|
||||
@Override
|
||||
public CompletableFuture<RegistrationServiceSession> createRegistrationSession(
|
||||
final Phonenumber.PhoneNumber phoneNumber, final String sourceHost, final boolean accountExistsWithPhoneNumber, final Duration timeout) {
|
||||
final Phonenumber.PhoneNumber phoneNumber,
|
||||
final String sourceHost,
|
||||
final boolean accountExistsWithPhoneNumber,
|
||||
@javax.annotation.Nullable final String clientMcc,
|
||||
@javax.annotation.Nullable final String clientMnc,
|
||||
final Duration timeout) {
|
||||
|
||||
final String e164 = PhoneNumberUtil.getInstance()
|
||||
.format(phoneNumber, PhoneNumberUtil.PhoneNumberFormat.E164);
|
||||
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.reset;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import io.dropwizard.auth.AuthValueFactoryProvider;
|
||||
import io.dropwizard.testing.junit5.DropwizardExtensionsSupport;
|
||||
import io.dropwizard.testing.junit5.ResourceExtension;
|
||||
import jakarta.ws.rs.client.Entity;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.signal.chat.calling.quality.SubmitCallQualitySurveyRequest;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.metrics.CallQualitySurveyManager;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
import org.whispersystems.textsecuregcm.util.TestRemoteAddressFilterProvider;
|
||||
import java.util.List;
|
||||
|
||||
@ExtendWith(DropwizardExtensionsSupport.class)
|
||||
class CallQualitySurveyControllerTest {
|
||||
|
||||
private static final CallQualitySurveyManager CALL_QUALITY_SURVEY_MANAGER = mock(CallQualitySurveyManager.class);
|
||||
|
||||
private static final String USER_AGENT = "Signal-iOS/7.78.0.1041 iOS/18.3.2 libsignal/0.80.3";
|
||||
private static final String REMOTE_ADDRESS = "127.0.0.1";
|
||||
|
||||
private static final ResourceExtension RESOURCE_EXTENSION = ResourceExtension.builder()
|
||||
.addProvider(AuthHelper.getAuthFilter())
|
||||
.addProvider(new AuthValueFactoryProvider.Binder<>(AuthenticatedDevice.class))
|
||||
.addProvider(new RateLimitExceededExceptionMapper())
|
||||
.addProvider(new TestRemoteAddressFilterProvider(REMOTE_ADDRESS))
|
||||
.setMapper(SystemMapper.jsonMapper())
|
||||
.setTestContainerFactory(new GrizzlyWebTestContainerFactory())
|
||||
.addResource(new CallQualitySurveyController(CALL_QUALITY_SURVEY_MANAGER))
|
||||
.build();
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
reset(CALL_QUALITY_SURVEY_MANAGER);
|
||||
}
|
||||
|
||||
@Test
|
||||
void submitCallQualitySurvey() {
|
||||
final SubmitCallQualitySurveyRequest request = SubmitCallQualitySurveyRequest.getDefaultInstance();
|
||||
|
||||
try (final Response response = RESOURCE_EXTENSION.getJerseyTest()
|
||||
.target("/v1/call_quality_survey")
|
||||
.request()
|
||||
.header("User-Agent", USER_AGENT)
|
||||
.put(Entity.entity(request.toByteArray(), MediaType.APPLICATION_OCTET_STREAM_TYPE))) {
|
||||
|
||||
assertEquals(204, response.getStatus());
|
||||
verify(CALL_QUALITY_SURVEY_MANAGER).submitCallQualitySurvey(request, REMOTE_ADDRESS, USER_AGENT);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void submitCallQualitySurveyAuthenticated() {
|
||||
final SubmitCallQualitySurveyRequest request = SubmitCallQualitySurveyRequest.getDefaultInstance();
|
||||
|
||||
try (final Response response = RESOURCE_EXTENSION.getJerseyTest()
|
||||
.target("/v1/call_quality_survey")
|
||||
.request()
|
||||
.header("User-Agent", USER_AGENT)
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.put(Entity.entity(request.toByteArray(), MediaType.APPLICATION_OCTET_STREAM_TYPE))) {
|
||||
|
||||
assertEquals(403, response.getStatus());
|
||||
verify(CALL_QUALITY_SURVEY_MANAGER, never()).submitCallQualitySurvey(any(), any(), any());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void submitCallQualitySurveyInvalidArgument() {
|
||||
final SubmitCallQualitySurveyRequest request = SubmitCallQualitySurveyRequest.getDefaultInstance();
|
||||
|
||||
doThrow(new IllegalArgumentException())
|
||||
.when(CALL_QUALITY_SURVEY_MANAGER).submitCallQualitySurvey(request, REMOTE_ADDRESS, USER_AGENT);
|
||||
|
||||
try (final Response response = RESOURCE_EXTENSION.getJerseyTest()
|
||||
.target("/v1/call_quality_survey")
|
||||
.request()
|
||||
.header("User-Agent", USER_AGENT)
|
||||
.put(Entity.entity(request.toByteArray(), MediaType.APPLICATION_OCTET_STREAM_TYPE))) {
|
||||
|
||||
assertEquals(422, response.getStatus());
|
||||
}
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -830,11 +830,11 @@ class DeviceControllerTest {
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.header(HttpHeaders.USER_AGENT, "Signal-Android/5.42.8675309 Android/30")
|
||||
.put(Entity.json("{\"deleteSync\": true, \"notARealDeviceCapability\": true}"))) {
|
||||
.put(Entity.json("{\"storage\": true, \"notARealDeviceCapability\": true}"))) {
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(204);
|
||||
assertThat(response.hasEntity()).isFalse();
|
||||
verify(primaryDevice).setCapabilities(Set.of(DeviceCapability.DELETE_SYNC));
|
||||
verify(primaryDevice).setCapabilities(Set.of(DeviceCapability.STORAGE));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+82
-65
@@ -35,6 +35,8 @@ import jakarta.ws.rs.client.WebTarget;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Stream;
|
||||
@@ -123,7 +125,13 @@ public class KeyTransparencyControllerTest {
|
||||
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void searchSuccess(final Optional<String> e164, final Optional<byte[]> usernameHash) {
|
||||
void searchSuccess(
|
||||
final Optional<String> e164,
|
||||
final Optional<byte[]> usernameHash,
|
||||
final Optional<Long> aciVersion,
|
||||
final Optional<Long> e164Version,
|
||||
final Optional<Long> usernameHashVersion
|
||||
) {
|
||||
final CondensedTreeSearchResponse aciSearchResponse = CondensedTreeSearchResponse.newBuilder()
|
||||
.setOpening(ByteString.copyFrom(TestRandomUtil.nextBytes(16)))
|
||||
.setSearch(SearchProof.getDefaultInstance())
|
||||
@@ -139,7 +147,7 @@ public class KeyTransparencyControllerTest {
|
||||
e164.ifPresent(ignored -> searchResponseBuilder.setE164(CondensedTreeSearchResponse.getDefaultInstance()));
|
||||
usernameHash.ifPresent(ignored -> searchResponseBuilder.setUsernameHash(CondensedTreeSearchResponse.getDefaultInstance()));
|
||||
|
||||
when(keyTransparencyServiceClient.search(any(), any(), any(), any(), any(), anyLong()))
|
||||
when(keyTransparencyServiceClient.search(any(), any(), any(), any(), any(), anyLong(), any(), any(), any()))
|
||||
.thenReturn(searchResponseBuilder.build());
|
||||
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
@@ -149,7 +157,7 @@ public class KeyTransparencyControllerTest {
|
||||
final Optional<byte[]> unidentifiedAccessKey = e164.isPresent() ? Optional.of(UNIDENTIFIED_ACCESS_KEY) : Optional.empty();
|
||||
final String searchJson = createRequestJson(
|
||||
new KeyTransparencySearchRequest(ACI, e164, usernameHash, ACI_IDENTITY_KEY,
|
||||
unidentifiedAccessKey, Optional.of(3L), 4L));
|
||||
unidentifiedAccessKey, Optional.of(3L), 4L, aciVersion, e164Version, usernameHashVersion));
|
||||
|
||||
try (Response response = request.post(Entity.json(searchJson))) {
|
||||
assertEquals(200, response.getStatus());
|
||||
@@ -163,9 +171,13 @@ public class KeyTransparencyControllerTest {
|
||||
ArgumentCaptor<ByteString> aciIdentityKeyArgument = ArgumentCaptor.forClass(ByteString.class);
|
||||
ArgumentCaptor<Optional<ByteString>> usernameHashArgument = ArgumentCaptor.forClass(Optional.class);
|
||||
ArgumentCaptor<Optional<E164SearchRequest>> e164Argument = ArgumentCaptor.forClass(Optional.class);
|
||||
ArgumentCaptor<Optional<Long>> aciVersionArgument = ArgumentCaptor.forClass(Optional.class);
|
||||
ArgumentCaptor<Optional<Long>> e164VersionArgument = ArgumentCaptor.forClass(Optional.class);
|
||||
ArgumentCaptor<Optional<Long>> usernameHashVersionArgument = ArgumentCaptor.forClass(Optional.class);
|
||||
|
||||
|
||||
verify(keyTransparencyServiceClient).search(aciArgument.capture(), aciIdentityKeyArgument.capture(),
|
||||
usernameHashArgument.capture(), e164Argument.capture(), eq(Optional.of(3L)), eq(4L));
|
||||
usernameHashArgument.capture(), e164Argument.capture(), eq(Optional.of(3L)), eq(4L), aciVersionArgument.capture(), e164VersionArgument.capture(), usernameHashVersionArgument.capture());
|
||||
|
||||
assertArrayEquals(ACI.toCompactByteArray(), aciArgument.getValue().toByteArray());
|
||||
assertArrayEquals(ACI_IDENTITY_KEY.serialize(), aciIdentityKeyArgument.getValue().toByteArray());
|
||||
@@ -185,6 +197,18 @@ public class KeyTransparencyControllerTest {
|
||||
} else {
|
||||
assertTrue(e164Argument.getValue().isEmpty());
|
||||
}
|
||||
|
||||
final List<ArgumentCaptor<Optional<Long>>> versionArgumentCaptors = List.of(aciVersionArgument, e164VersionArgument, usernameHashVersionArgument);
|
||||
final List<Optional<Long>> providedVersions = List.of(aciVersion, e164Version, usernameHashVersion);
|
||||
|
||||
for (int i = 0; i < versionArgumentCaptors.size(); i++) {
|
||||
if (providedVersions.get(i).isPresent()) {
|
||||
assertEquals(providedVersions.get(i), versionArgumentCaptors.get(i).getValue());
|
||||
} else {
|
||||
assertTrue(versionArgumentCaptors.get(i).getValue().isEmpty());
|
||||
}
|
||||
}
|
||||
|
||||
} catch (InvalidProtocolBufferException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
@@ -192,10 +216,12 @@ public class KeyTransparencyControllerTest {
|
||||
|
||||
private static Stream<Arguments> searchSuccess() {
|
||||
return Stream.of(
|
||||
Arguments.of(Optional.of(NUMBER), Optional.empty()),
|
||||
Arguments.of(Optional.empty(), Optional.of(USERNAME_HASH)),
|
||||
Arguments.of(Optional.of(NUMBER), Optional.of(USERNAME_HASH))
|
||||
);
|
||||
Arguments.argumentSet("Search for ACI and E164", Optional.of(NUMBER), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty()),
|
||||
Arguments.argumentSet("Search for ACI and username hash", Optional.empty(), Optional.of(USERNAME_HASH), Optional.empty(), Optional.empty(), Optional.empty()),
|
||||
Arguments.argumentSet("Search for ACI, E164, and username hash", Optional.of(NUMBER), Optional.of(USERNAME_HASH), Optional.empty(), Optional.empty(), Optional.empty()),
|
||||
Arguments.argumentSet("Search for version 0 of the ACI", Optional.of(NUMBER), Optional.of(USERNAME_HASH), Optional.of(0L), Optional.empty(), Optional.empty()),
|
||||
Arguments.argumentSet("Search for multiple versioned identifiers", Optional.of(NUMBER), Optional.of(USERNAME_HASH), Optional.empty(), Optional.of(0L), Optional.of(1L))
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -206,7 +232,8 @@ public class KeyTransparencyControllerTest {
|
||||
.header(HttpHeaders.AUTHORIZATION, AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD));
|
||||
try (Response response = request.post(
|
||||
Entity.json(createRequestJson(new KeyTransparencySearchRequest(ACI, Optional.empty(), Optional.empty(),
|
||||
ACI_IDENTITY_KEY, Optional.empty(), Optional.empty(), 4L))))) {
|
||||
ACI_IDENTITY_KEY, Optional.empty(), Optional.empty(), 4L, Optional.empty(), Optional.empty(),
|
||||
Optional.empty()))))) {
|
||||
assertEquals(400, response.getStatus());
|
||||
}
|
||||
verifyNoInteractions(keyTransparencyServiceClient);
|
||||
@@ -215,7 +242,7 @@ public class KeyTransparencyControllerTest {
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void searchGrpcErrors(final Status grpcStatus, final int httpStatus) {
|
||||
when(keyTransparencyServiceClient.search(any(), any(), any(), any(), any(), anyLong()))
|
||||
when(keyTransparencyServiceClient.search(any(), any(), any(), any(), any(), anyLong(), any(), any(), any()))
|
||||
.thenThrow(new StatusRuntimeException(grpcStatus));
|
||||
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
@@ -223,15 +250,14 @@ public class KeyTransparencyControllerTest {
|
||||
.request();
|
||||
try (Response response = request.post(
|
||||
Entity.json(createRequestJson(new KeyTransparencySearchRequest(ACI, Optional.empty(), Optional.empty(),
|
||||
ACI_IDENTITY_KEY, Optional.empty(), Optional.empty(), 4L))))) {
|
||||
ACI_IDENTITY_KEY, Optional.empty(), Optional.empty(), 4L, Optional.empty(), Optional.empty(), Optional.empty()))))) {
|
||||
assertEquals(httpStatus, response.getStatus());
|
||||
verify(keyTransparencyServiceClient, times(1)).search(any(), any(), any(), any(), any(), anyLong());
|
||||
verify(keyTransparencyServiceClient, times(1)).search(any(), any(), any(), any(), any(), anyLong(), any(), any(), any());
|
||||
}
|
||||
}
|
||||
|
||||
private static Stream<Arguments> searchGrpcErrors() {
|
||||
return Stream.of(
|
||||
Arguments.of(Status.NOT_FOUND, 404),
|
||||
Arguments.of(Status.PERMISSION_DENIED, 403),
|
||||
Arguments.of(Status.INVALID_ARGUMENT, 422),
|
||||
Arguments.of(Status.UNKNOWN, 500)
|
||||
@@ -246,13 +272,16 @@ public class KeyTransparencyControllerTest {
|
||||
final Optional<String> e164,
|
||||
final Optional<byte[]> unidentifiedAccessKey,
|
||||
final Optional<Long> lastTreeHeadSize,
|
||||
final long distinguishedTreeHeadSize) {
|
||||
final long distinguishedTreeHeadSize,
|
||||
final Optional<Long> aciVersion,
|
||||
final Optional<Long> e164Version,
|
||||
final Optional<Long> usernameHashVersion) {
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
.target("/v1/key-transparency/search")
|
||||
.request();
|
||||
try (Response response = request.post(Entity.json(
|
||||
createRequestJson(new KeyTransparencySearchRequest(aci, e164, Optional.empty(),
|
||||
aciIdentityKey, unidentifiedAccessKey, lastTreeHeadSize, distinguishedTreeHeadSize))))) {
|
||||
aciIdentityKey, unidentifiedAccessKey, lastTreeHeadSize, distinguishedTreeHeadSize, aciVersion, e164Version, usernameHashVersion))))) {
|
||||
assertEquals(422, response.getStatus());
|
||||
verifyNoInteractions(keyTransparencyServiceClient);
|
||||
}
|
||||
@@ -260,18 +289,18 @@ public class KeyTransparencyControllerTest {
|
||||
|
||||
private static Stream<Arguments> searchInvalidRequest() {
|
||||
return Stream.of(
|
||||
// ACI can't be null
|
||||
Arguments.of(null, ACI_IDENTITY_KEY, Optional.empty(), Optional.empty(), Optional.empty(), 4L),
|
||||
// ACI identity key can't be null
|
||||
Arguments.of(ACI, null, Optional.empty(), Optional.empty(), Optional.empty(), 4L),
|
||||
// lastNonDistinguishedTreeHeadSize must be positive
|
||||
Arguments.of(ACI, ACI_IDENTITY_KEY, Optional.empty(), Optional.empty(), Optional.of(0L), 4L),
|
||||
// lastDistinguishedTreeHeadSize must be positive
|
||||
Arguments.of(ACI, ACI_IDENTITY_KEY, Optional.empty(), Optional.empty(), Optional.empty(), 0L),
|
||||
// E164 can't be provided without an unidentified access key
|
||||
Arguments.of(ACI, ACI_IDENTITY_KEY, Optional.of(NUMBER), Optional.empty(), Optional.empty(), 4L),
|
||||
// ...and an unidentified access key can't be provided without an E164
|
||||
Arguments.of(ACI, ACI_IDENTITY_KEY, Optional.empty(), Optional.of(UNIDENTIFIED_ACCESS_KEY), Optional.empty(), 4L)
|
||||
Arguments.argumentSet("ACI can't be null", null, ACI_IDENTITY_KEY, Optional.empty(), Optional.empty(), Optional.empty(), 4L, Optional.empty(), Optional.empty(), Optional.empty()),
|
||||
Arguments.argumentSet("ACI identity key can't be null", ACI, null, Optional.empty(), Optional.empty(), Optional.empty(), 4L, Optional.empty(), Optional.empty(), Optional.empty()),
|
||||
Arguments.argumentSet("lastNonDistinguishedTreeHeadSize must be positive", ACI, ACI_IDENTITY_KEY, Optional.empty(), Optional.empty(), Optional.of(0L), 4L, Optional.empty(), Optional.empty(), Optional.empty()),
|
||||
Arguments.argumentSet("lastDistinguishedTreeHeadSize must be positive", ACI, ACI_IDENTITY_KEY, Optional.empty(), Optional.empty(), Optional.empty(), 0L, Optional.empty(), Optional.empty(), Optional.empty()),
|
||||
Arguments.argumentSet("E164 can't be provided without an unidentified access key", ACI, ACI_IDENTITY_KEY, Optional.of(NUMBER), Optional.empty(), Optional.empty(), 4L, Optional.empty(), Optional.empty(), Optional.empty()),
|
||||
Arguments.argumentSet("An unidentified access key can't be provided without an E164", ACI, ACI_IDENTITY_KEY, Optional.empty(), Optional.of(UNIDENTIFIED_ACCESS_KEY), Optional.empty(), 4L, Optional.empty(), Optional.empty(), Optional.empty()),
|
||||
Arguments.argumentSet("ACI version cannot be negative", ACI, ACI_IDENTITY_KEY, Optional.empty(), Optional.of(UNIDENTIFIED_ACCESS_KEY), Optional.empty(), 4L, Optional.of(-1L), Optional.empty(), Optional.empty()),
|
||||
Arguments.argumentSet("ACI version cannot be greater than max uint32 protobuf value", ACI, ACI_IDENTITY_KEY, Optional.empty(), Optional.of(UNIDENTIFIED_ACCESS_KEY), Optional.empty(), 4L, Optional.of(0xFFFFFFFFL), Optional.empty(), Optional.empty()),
|
||||
Arguments.argumentSet("E164 version cannot be negative", ACI, ACI_IDENTITY_KEY, Optional.empty(), Optional.of(UNIDENTIFIED_ACCESS_KEY), Optional.empty(), 4L, Optional.empty(), Optional.of(-1L), Optional.empty()),
|
||||
Arguments.argumentSet("E164 version cannot be greater than max uint32 protobuf value", ACI, ACI_IDENTITY_KEY, Optional.empty(), Optional.of(UNIDENTIFIED_ACCESS_KEY), Optional.empty(), 4L, Optional.empty(), Optional.of(0xFFFFFFFFL), Optional.empty()),
|
||||
Arguments.argumentSet("Username hash version cannot be negative", ACI, ACI_IDENTITY_KEY, Optional.empty(), Optional.of(UNIDENTIFIED_ACCESS_KEY), Optional.empty(), 4L, Optional.empty(), Optional.empty(), Optional.of(-1L)),
|
||||
Arguments.argumentSet("Username hash cannot be greater than max uint32 protobuf value", ACI, ACI_IDENTITY_KEY, Optional.empty(), Optional.of(UNIDENTIFIED_ACCESS_KEY), Optional.empty(), 4L, Optional.empty(), Optional.empty(), Optional.of(0xFFFFFFFFL))
|
||||
);
|
||||
}
|
||||
|
||||
@@ -284,7 +313,7 @@ public class KeyTransparencyControllerTest {
|
||||
.request();
|
||||
try (Response response = request.post(
|
||||
Entity.json(createRequestJson(new KeyTransparencySearchRequest(ACI, Optional.empty(), Optional.empty(),
|
||||
ACI_IDENTITY_KEY, Optional.empty(), Optional.empty(), 4L))))) {
|
||||
ACI_IDENTITY_KEY, Optional.empty(), Optional.empty(), 4L, Optional.empty(), Optional.empty(), Optional.empty()))))) {
|
||||
assertEquals(429, response.getStatus());
|
||||
verifyNoInteractions(keyTransparencyServiceClient);
|
||||
}
|
||||
@@ -302,7 +331,7 @@ public class KeyTransparencyControllerTest {
|
||||
try (Response response = request.post(Entity.json(
|
||||
createRequestJson(
|
||||
new KeyTransparencyMonitorRequest(
|
||||
new KeyTransparencyMonitorRequest.AciMonitor(ACI,3, COMMITMENT_INDEX),
|
||||
new KeyTransparencyMonitorRequest.AciMonitor(ACI, 0, COMMITMENT_INDEX),
|
||||
Optional.empty(), Optional.empty(), 3L, 4L))))) {
|
||||
assertEquals(200, response.getStatus());
|
||||
|
||||
@@ -373,105 +402,93 @@ public class KeyTransparencyControllerTest {
|
||||
|
||||
private static Stream<Arguments> monitorInvalidRequest() {
|
||||
return Stream.of(
|
||||
// aci monitor cannot be null
|
||||
Arguments.of(createRequestJson(
|
||||
Arguments.argumentSet("aci monitor cannot be null", createRequestJson(
|
||||
new KeyTransparencyMonitorRequest(null, Optional.empty(), Optional.empty(), 3L, 4L))),
|
||||
// aci monitor fields can't be null
|
||||
Arguments.of(createRequestJson(
|
||||
Arguments.argumentSet("aci monitor fields can't be null - null value and commitment index", createRequestJson(
|
||||
new KeyTransparencyMonitorRequest(new KeyTransparencyMonitorRequest.AciMonitor(null, 4, null),
|
||||
Optional.empty(), Optional.empty(), 3L, 4L))),
|
||||
Arguments.of(createRequestJson(
|
||||
Arguments.argumentSet("aci monitor fields can't be null - null value", createRequestJson(
|
||||
new KeyTransparencyMonitorRequest(
|
||||
new KeyTransparencyMonitorRequest.AciMonitor(null, 4, COMMITMENT_INDEX),
|
||||
Optional.empty(), Optional.empty(), 3L, 4L))),
|
||||
Arguments.of(createRequestJson(
|
||||
Arguments.argumentSet("aci monitor fields can't be null - null commitment index", createRequestJson(
|
||||
new KeyTransparencyMonitorRequest(new KeyTransparencyMonitorRequest.AciMonitor(ACI, 4, null),
|
||||
Optional.empty(), Optional.empty(), 3L, 4L))),
|
||||
// aciPosition must be positive
|
||||
Arguments.of(createRequestJson(new KeyTransparencyMonitorRequest(
|
||||
new KeyTransparencyMonitorRequest.AciMonitor(ACI, 0, COMMITMENT_INDEX),
|
||||
Arguments.argumentSet("aciPosition must be non-negative", createRequestJson(new KeyTransparencyMonitorRequest(
|
||||
new KeyTransparencyMonitorRequest.AciMonitor(ACI, -1, COMMITMENT_INDEX),
|
||||
Optional.empty(), Optional.empty(), 3L, 4L))),
|
||||
// aci commitment index must be the correct size
|
||||
Arguments.of(createRequestJson(new KeyTransparencyMonitorRequest(
|
||||
Arguments.argumentSet("aci commitment index must be the correct size - too small", createRequestJson(new KeyTransparencyMonitorRequest(
|
||||
new KeyTransparencyMonitorRequest.AciMonitor(ACI, 4, new byte[0]),
|
||||
Optional.empty(), Optional.empty(), 3L, 4L))),
|
||||
Arguments.of(createRequestJson(new KeyTransparencyMonitorRequest(
|
||||
Arguments.argumentSet("aci commitment index must be the correct size - too large", createRequestJson(new KeyTransparencyMonitorRequest(
|
||||
new KeyTransparencyMonitorRequest.AciMonitor(ACI, 0, new byte[33]),
|
||||
Optional.empty(), Optional.empty(), 3L, 4L))),
|
||||
// username monitor fields cannot be null
|
||||
Arguments.of(createRequestJson(
|
||||
Arguments.argumentSet("username monitor fields cannot be null - null value and commitment index", createRequestJson(
|
||||
new KeyTransparencyMonitorRequest(
|
||||
new KeyTransparencyMonitorRequest.AciMonitor(ACI, 4, COMMITMENT_INDEX), Optional.empty(),
|
||||
Optional.of(new KeyTransparencyMonitorRequest.UsernameHashMonitor(null, 5, null)),
|
||||
3L, 4L))),
|
||||
Arguments.of(createRequestJson(
|
||||
Arguments.argumentSet("username monitor fields cannot be null - null value", createRequestJson(
|
||||
new KeyTransparencyMonitorRequest(
|
||||
new KeyTransparencyMonitorRequest.AciMonitor(ACI, 4, COMMITMENT_INDEX), Optional.empty(),
|
||||
Optional.of(new KeyTransparencyMonitorRequest.UsernameHashMonitor(null, 5, COMMITMENT_INDEX)),
|
||||
3L, 4L))),
|
||||
Arguments.of(createRequestJson(
|
||||
Arguments.argumentSet("username monitor fields cannot be null - null commitment index", createRequestJson(
|
||||
new KeyTransparencyMonitorRequest(
|
||||
new KeyTransparencyMonitorRequest.AciMonitor(ACI, 4, COMMITMENT_INDEX), Optional.empty(),
|
||||
Optional.of(new KeyTransparencyMonitorRequest.UsernameHashMonitor(USERNAME_HASH, 5, null)),
|
||||
3L, 4L))),
|
||||
// usernameHashPosition must be positive
|
||||
Arguments.of(createRequestJson(
|
||||
Arguments.argumentSet("usernameHashPosition must be non-negative", createRequestJson(
|
||||
new KeyTransparencyMonitorRequest(
|
||||
new KeyTransparencyMonitorRequest.AciMonitor(ACI, 4, COMMITMENT_INDEX),
|
||||
Optional.empty(),
|
||||
Optional.of(new KeyTransparencyMonitorRequest.UsernameHashMonitor(USERNAME_HASH,
|
||||
0, COMMITMENT_INDEX)), 3L, 4L))),
|
||||
// username commitment index must be the correct size
|
||||
Arguments.of(createRequestJson(
|
||||
-1, COMMITMENT_INDEX)), 3L, 4L))),
|
||||
Arguments.argumentSet("username commitment index must be the correct size - too small", createRequestJson(
|
||||
new KeyTransparencyMonitorRequest(
|
||||
new KeyTransparencyMonitorRequest.AciMonitor(ACI, 4, new byte[0]),
|
||||
Optional.empty(),
|
||||
Optional.of(new KeyTransparencyMonitorRequest.UsernameHashMonitor(USERNAME_HASH,
|
||||
5, new byte[0])), 3L, 4L))),
|
||||
Arguments.of(createRequestJson(
|
||||
Arguments.argumentSet("username commitment index must be the correct size - too large", createRequestJson(
|
||||
new KeyTransparencyMonitorRequest(new KeyTransparencyMonitorRequest.AciMonitor(ACI, 4, null),
|
||||
Optional.empty(),
|
||||
Optional.of(new KeyTransparencyMonitorRequest.UsernameHashMonitor(USERNAME_HASH,
|
||||
5, new byte[33])), 3L, 4L))),
|
||||
// e164 fields cannot be null
|
||||
Arguments.of(
|
||||
Arguments.argumentSet("e164 fields cannot be null - null value and commitment index",
|
||||
createRequestJson(new KeyTransparencyMonitorRequest(
|
||||
new KeyTransparencyMonitorRequest.AciMonitor(ACI, 4, COMMITMENT_INDEX),
|
||||
Optional.of(new KeyTransparencyMonitorRequest.E164Monitor(null, 5, null)),
|
||||
Optional.empty(), 3L, 4L))),
|
||||
Arguments.of(
|
||||
Arguments.argumentSet("e164 fields cannot be null - null value",
|
||||
createRequestJson(new KeyTransparencyMonitorRequest(
|
||||
new KeyTransparencyMonitorRequest.AciMonitor(ACI, 4, COMMITMENT_INDEX),
|
||||
Optional.of(new KeyTransparencyMonitorRequest.E164Monitor(null, 5, COMMITMENT_INDEX)),
|
||||
Optional.empty(), 3L, 4L))),
|
||||
Arguments.of(
|
||||
Arguments.argumentSet("e164 fields cannot be null - null commitment index",
|
||||
createRequestJson(new KeyTransparencyMonitorRequest(
|
||||
new KeyTransparencyMonitorRequest.AciMonitor(ACI, 4, COMMITMENT_INDEX),
|
||||
Optional.of(new KeyTransparencyMonitorRequest.E164Monitor(NUMBER, 5, null)),
|
||||
Optional.empty(), 3L, 4L))),
|
||||
// e164Position must be positive
|
||||
Arguments.of(createRequestJson(new KeyTransparencyMonitorRequest(
|
||||
Arguments.argumentSet("e164Position must be non-negative", createRequestJson(new KeyTransparencyMonitorRequest(
|
||||
new KeyTransparencyMonitorRequest.AciMonitor(ACI, 4, COMMITMENT_INDEX),
|
||||
Optional.of(
|
||||
new KeyTransparencyMonitorRequest.E164Monitor(NUMBER, 0, COMMITMENT_INDEX)),
|
||||
new KeyTransparencyMonitorRequest.E164Monitor(NUMBER, -1, COMMITMENT_INDEX)),
|
||||
Optional.empty(), 3L, 4L))),
|
||||
// e164 commitment index must be the correct size
|
||||
Arguments.of(createRequestJson(new KeyTransparencyMonitorRequest(
|
||||
Arguments.argumentSet("e164 commitment index must be the correct size - too small", createRequestJson(new KeyTransparencyMonitorRequest(
|
||||
new KeyTransparencyMonitorRequest.AciMonitor(ACI, 4, COMMITMENT_INDEX),
|
||||
Optional.of(
|
||||
new KeyTransparencyMonitorRequest.E164Monitor(NUMBER, 5, new byte[0])),
|
||||
Optional.empty(), 3L, 4L))),
|
||||
Arguments.of(createRequestJson(new KeyTransparencyMonitorRequest(
|
||||
Arguments.argumentSet("e164 commitment index must be the correct size - too large", createRequestJson(new KeyTransparencyMonitorRequest(
|
||||
new KeyTransparencyMonitorRequest.AciMonitor(ACI, 4, COMMITMENT_INDEX),
|
||||
Optional.of(
|
||||
new KeyTransparencyMonitorRequest.E164Monitor(NUMBER, 5, new byte[33])),
|
||||
Optional.empty(), 3L, 4L))),
|
||||
// lastNonDistinguishedTreeHeadSize must be positive
|
||||
Arguments.of(createRequestJson(new KeyTransparencyMonitorRequest(
|
||||
Arguments.argumentSet("lastNonDistinguishedTreeHeadSize must be positive", createRequestJson(new KeyTransparencyMonitorRequest(
|
||||
new KeyTransparencyMonitorRequest.AciMonitor(ACI, 4, COMMITMENT_INDEX), Optional.empty(),
|
||||
Optional.empty(), 0L, 4L))),
|
||||
// lastDistinguishedTreeHeadSize must be positive
|
||||
Arguments.of(createRequestJson(new KeyTransparencyMonitorRequest(
|
||||
Arguments.argumentSet("lastDistinguishedTreeHeadSize must be positive", createRequestJson(new KeyTransparencyMonitorRequest(
|
||||
new KeyTransparencyMonitorRequest.AciMonitor(ACI, 4, COMMITMENT_INDEX), Optional.empty(),
|
||||
Optional.empty(), 3L, 0L)))
|
||||
);
|
||||
|
||||
+1
-80
@@ -100,7 +100,6 @@ import org.whispersystems.textsecuregcm.push.MessageSender;
|
||||
import org.whispersystems.textsecuregcm.push.MessageTooLargeException;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationScheduler;
|
||||
import org.whispersystems.textsecuregcm.push.ReceiptSender;
|
||||
import org.whispersystems.textsecuregcm.spam.SpamChecker;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
@@ -108,13 +107,11 @@ import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesManager;
|
||||
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
|
||||
import org.whispersystems.textsecuregcm.storage.RemovedMessage;
|
||||
import org.whispersystems.textsecuregcm.storage.ReportMessageManager;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AccountsHelper;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
|
||||
import org.whispersystems.textsecuregcm.tests.util.MultiRecipientMessageHelper;
|
||||
import org.whispersystems.textsecuregcm.tests.util.TestRecipient;
|
||||
import org.whispersystems.textsecuregcm.util.CompletableFutureTestUtil;
|
||||
import org.whispersystems.textsecuregcm.util.HeaderUtils;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
@@ -165,7 +162,6 @@ class MessageControllerTest {
|
||||
private static final RedisAdvancedClusterCommands<String, String> redisCommands = mock(RedisAdvancedClusterCommands.class);
|
||||
|
||||
private static final MessageSender messageSender = mock(MessageSender.class);
|
||||
private static final ReceiptSender receiptSender = mock(ReceiptSender.class);
|
||||
private static final AccountsManager accountsManager = mock(AccountsManager.class);
|
||||
private static final MessagesManager messagesManager = mock(MessagesManager.class);
|
||||
private static final RateLimiters rateLimiters = mock(RateLimiters.class);
|
||||
@@ -192,7 +188,7 @@ class MessageControllerTest {
|
||||
.addProvider(MultiRecipientMessageProvider.class)
|
||||
.setTestContainerFactory(new GrizzlyWebTestContainerFactory())
|
||||
.addResource(
|
||||
new MessageController(rateLimiters, cardinalityEstimator, messageSender, receiptSender, accountsManager,
|
||||
new MessageController(rateLimiters, cardinalityEstimator, messageSender, accountsManager,
|
||||
messagesManager, phoneNumberIdentifiers, pushNotificationManager, pushNotificationScheduler,
|
||||
reportMessageManager, messageDeliveryScheduler, mock(ClientReleaseManager.class),
|
||||
serverSecretParams, SpamChecker.noop(), new MessageMetrics(), mock(MessageDeliveryLoopMonitor.class),
|
||||
@@ -269,7 +265,6 @@ class MessageControllerTest {
|
||||
reset(
|
||||
redisCommands,
|
||||
messageSender,
|
||||
receiptSender,
|
||||
accountsManager,
|
||||
messagesManager,
|
||||
rateLimiters,
|
||||
@@ -798,80 +793,6 @@ class MessageControllerTest {
|
||||
assertThat("Unauthorized response", response.getStatus(), is(equalTo(401)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDeleteMessages() {
|
||||
long clientTimestamp = System.currentTimeMillis();
|
||||
|
||||
UUID sourceUuid = UUID.randomUUID();
|
||||
|
||||
UUID uuid1 = UUID.randomUUID();
|
||||
|
||||
final long serverTimestamp = 0;
|
||||
when(messagesManager.delete(AuthHelper.VALID_UUID, AuthHelper.VALID_DEVICE, uuid1, null))
|
||||
.thenReturn(
|
||||
CompletableFutureTestUtil.almostCompletedFuture(Optional.of(
|
||||
new RemovedMessage(Optional.of(new AciServiceIdentifier(sourceUuid)),
|
||||
new AciServiceIdentifier(AuthHelper.VALID_UUID), uuid1, serverTimestamp, clientTimestamp,
|
||||
Envelope.Type.CIPHERTEXT))));
|
||||
|
||||
UUID uuid2 = UUID.randomUUID();
|
||||
when(messagesManager.delete(AuthHelper.VALID_UUID, AuthHelper.VALID_DEVICE, uuid2, null))
|
||||
.thenReturn(
|
||||
CompletableFutureTestUtil.almostCompletedFuture(Optional.of(
|
||||
new RemovedMessage(Optional.of(new AciServiceIdentifier(sourceUuid)),
|
||||
new AciServiceIdentifier(AuthHelper.VALID_UUID), uuid2, serverTimestamp, clientTimestamp,
|
||||
Envelope.Type.SERVER_DELIVERY_RECEIPT))));
|
||||
|
||||
UUID uuid3 = UUID.randomUUID();
|
||||
when(messagesManager.delete(AuthHelper.VALID_UUID, AuthHelper.VALID_DEVICE, uuid3, null))
|
||||
.thenReturn(CompletableFutureTestUtil.almostCompletedFuture(Optional.empty()));
|
||||
|
||||
UUID uuid4 = UUID.randomUUID();
|
||||
when(messagesManager.delete(AuthHelper.VALID_UUID, AuthHelper.VALID_DEVICE, uuid4, null))
|
||||
.thenReturn(CompletableFuture.failedFuture(new RuntimeException("Oh No")));
|
||||
|
||||
try (final Response response = resources.getJerseyTest()
|
||||
.target(String.format("/v1/messages/uuid/%s", uuid1))
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.delete()) {
|
||||
|
||||
assertThat("Good Response Code", response.getStatus(), is(equalTo(204)));
|
||||
verify(receiptSender).sendReceipt(eq(new AciServiceIdentifier(AuthHelper.VALID_UUID)), eq((byte) 1),
|
||||
eq(new AciServiceIdentifier(sourceUuid)), eq(clientTimestamp));
|
||||
}
|
||||
|
||||
try (final Response response = resources.getJerseyTest()
|
||||
.target(String.format("/v1/messages/uuid/%s", uuid2))
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.delete()) {
|
||||
|
||||
assertThat("Good Response Code", response.getStatus(), is(equalTo(204)));
|
||||
verifyNoMoreInteractions(receiptSender);
|
||||
}
|
||||
|
||||
try (final Response response = resources.getJerseyTest()
|
||||
.target(String.format("/v1/messages/uuid/%s", uuid3))
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.delete()) {
|
||||
|
||||
assertThat("Good Response Code", response.getStatus(), is(equalTo(204)));
|
||||
verifyNoMoreInteractions(receiptSender);
|
||||
}
|
||||
|
||||
try (final Response response = resources.getJerseyTest()
|
||||
.target(String.format("/v1/messages/uuid/%s", uuid4))
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.delete()) {
|
||||
|
||||
assertThat("Bad Response Code", response.getStatus(), is(equalTo(500)));
|
||||
verifyNoMoreInteractions(receiptSender);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testReportMessageByE164() {
|
||||
final String senderNumber = "+12125550001";
|
||||
|
||||
-238
@@ -1,238 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.reset;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoMoreInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import io.dropwizard.auth.AuthValueFactoryProvider;
|
||||
import io.dropwizard.testing.junit5.DropwizardExtensionsSupport;
|
||||
import io.dropwizard.testing.junit5.ResourceExtension;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.time.Instant;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Random;
|
||||
import java.util.Set;
|
||||
import org.assertj.core.api.Assertions;
|
||||
import org.assertj.core.api.InstanceOfAssertFactory;
|
||||
import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.entities.UserRemoteConfig;
|
||||
import org.whispersystems.textsecuregcm.entities.UserRemoteConfigList;
|
||||
import org.whispersystems.textsecuregcm.mappers.DeviceLimitExceededExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.storage.RemoteConfig;
|
||||
import org.whispersystems.textsecuregcm.storage.RemoteConfigsManager;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
|
||||
import org.whispersystems.textsecuregcm.util.TestClock;
|
||||
|
||||
@ExtendWith(DropwizardExtensionsSupport.class)
|
||||
class RemoteConfigControllerV1Test {
|
||||
|
||||
private static final RemoteConfigsManager remoteConfigsManager = mock(RemoteConfigsManager.class);
|
||||
|
||||
private static final long PINNED_EPOCH_SECONDS = 1701287216L;
|
||||
private static final TestClock TEST_CLOCK = TestClock.pinned(Instant.ofEpochSecond(PINNED_EPOCH_SECONDS));
|
||||
|
||||
|
||||
private static final ResourceExtension resources = ResourceExtension.builder()
|
||||
.addProvider(AuthHelper.getAuthFilter())
|
||||
.addProvider(new AuthValueFactoryProvider.Binder<>(AuthenticatedDevice.class))
|
||||
.setTestContainerFactory(new GrizzlyWebTestContainerFactory())
|
||||
.addProvider(new DeviceLimitExceededExceptionMapper())
|
||||
.addResource(new RemoteConfigControllerV1(remoteConfigsManager, Map.of("maxGroupSize", "42"), TEST_CLOCK))
|
||||
.build();
|
||||
|
||||
|
||||
@BeforeEach
|
||||
void setup() throws Exception {
|
||||
when(remoteConfigsManager.getAll()).thenReturn(new LinkedList<>() {{
|
||||
add(new RemoteConfig("android.stickers", 25, Set.of(AuthHelper.VALID_UUID_3, AuthHelper.INVALID_UUID), null,
|
||||
null, null));
|
||||
add(new RemoteConfig("ios.stickers", 50, Set.of(), null, null, null));
|
||||
add(new RemoteConfig("always.true", 100, Set.of(), null, null, null));
|
||||
add(new RemoteConfig("only.special", 0, Set.of(AuthHelper.VALID_UUID), null, null, null));
|
||||
add(new RemoteConfig("value.always.true", 100, Set.of(), "foo", "bar", null));
|
||||
add(new RemoteConfig("value.only.special", 0, Set.of(AuthHelper.VALID_UUID), "abc", "xyz", null));
|
||||
add(new RemoteConfig("value.always.false", 0, Set.of(), "red", "green", null));
|
||||
add(new RemoteConfig("linked.config.0", 50, Set.of(), null, null, null));
|
||||
add(new RemoteConfig("linked.config.1", 50, Set.of(), null, null, "linked.config.0"));
|
||||
add(new RemoteConfig("unlinked.config", 50, Set.of(), null, null, null));
|
||||
}});
|
||||
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void teardown() {
|
||||
reset(remoteConfigsManager);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRetrieveConfig() {
|
||||
UserRemoteConfigList configuration = resources.getJerseyTest()
|
||||
.target("/v1/config/")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.get(UserRemoteConfigList.class);
|
||||
|
||||
verify(remoteConfigsManager, times(1)).getAll();
|
||||
|
||||
assertThat(configuration.getConfig()).hasSize(11);
|
||||
assertThat(configuration.getConfig().get(0).getName()).isEqualTo("android.stickers");
|
||||
assertThat(configuration.getConfig().get(1).getName()).isEqualTo("ios.stickers");
|
||||
assertThat(configuration.getConfig().get(2).getName()).isEqualTo("always.true");
|
||||
assertThat(configuration.getConfig().get(2).isEnabled()).isEqualTo(true);
|
||||
assertThat(configuration.getConfig().get(2).getValue()).isNull();
|
||||
assertThat(configuration.getConfig().get(3).getName()).isEqualTo("only.special");
|
||||
assertThat(configuration.getConfig().get(3).isEnabled()).isEqualTo(true);
|
||||
assertThat(configuration.getConfig().get(2).getValue()).isNull();
|
||||
assertThat(configuration.getConfig().get(4).getName()).isEqualTo("value.always.true");
|
||||
assertThat(configuration.getConfig().get(4).isEnabled()).isEqualTo(true);
|
||||
assertThat(configuration.getConfig().get(4).getValue()).isEqualTo("bar");
|
||||
assertThat(configuration.getConfig().get(5).getName()).isEqualTo("value.only.special");
|
||||
assertThat(configuration.getConfig().get(5).isEnabled()).isEqualTo(true);
|
||||
assertThat(configuration.getConfig().get(5).getValue()).isEqualTo("xyz");
|
||||
assertThat(configuration.getConfig().get(6).getName()).isEqualTo("value.always.false");
|
||||
assertThat(configuration.getConfig().get(6).isEnabled()).isEqualTo(false);
|
||||
assertThat(configuration.getConfig().get(6).getValue()).isEqualTo("red");
|
||||
assertThat(configuration.getConfig().get(7).getName()).isEqualTo("linked.config.0");
|
||||
assertThat(configuration.getConfig().get(8).getName()).isEqualTo("linked.config.1");
|
||||
assertThat(configuration.getConfig().get(9).getName()).isEqualTo("unlinked.config");
|
||||
assertThat(configuration.getConfig().get(10).getName()).isEqualTo("global.maxGroupSize");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testServerEpochTime() {
|
||||
Object serverEpochTime = resources.getJerseyTest()
|
||||
.target("/v1/config/")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.get(Map.class)
|
||||
.get("serverEpochTime");
|
||||
|
||||
assertThat(serverEpochTime).asInstanceOf(new InstanceOfAssertFactory<>(Number.class, Assertions::assertThat))
|
||||
.extracting(Number::longValue)
|
||||
.isEqualTo(PINNED_EPOCH_SECONDS);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRetrieveConfigNotSpecial() {
|
||||
UserRemoteConfigList configuration = resources.getJerseyTest()
|
||||
.target("/v1/config/")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID_TWO, AuthHelper.VALID_PASSWORD_TWO))
|
||||
.get(UserRemoteConfigList.class);
|
||||
|
||||
verify(remoteConfigsManager, times(1)).getAll();
|
||||
|
||||
assertThat(configuration.getConfig()).hasSize(11);
|
||||
assertThat(configuration.getConfig().get(0).getName()).isEqualTo("android.stickers");
|
||||
assertThat(configuration.getConfig().get(1).getName()).isEqualTo("ios.stickers");
|
||||
assertThat(configuration.getConfig().get(2).getName()).isEqualTo("always.true");
|
||||
assertThat(configuration.getConfig().get(2).isEnabled()).isEqualTo(true);
|
||||
assertThat(configuration.getConfig().get(2).getValue()).isNull();
|
||||
assertThat(configuration.getConfig().get(3).getName()).isEqualTo("only.special");
|
||||
assertThat(configuration.getConfig().get(3).isEnabled()).isEqualTo(false);
|
||||
assertThat(configuration.getConfig().get(2).getValue()).isNull();
|
||||
assertThat(configuration.getConfig().get(4).getName()).isEqualTo("value.always.true");
|
||||
assertThat(configuration.getConfig().get(4).isEnabled()).isEqualTo(true);
|
||||
assertThat(configuration.getConfig().get(4).getValue()).isEqualTo("bar");
|
||||
assertThat(configuration.getConfig().get(5).getName()).isEqualTo("value.only.special");
|
||||
assertThat(configuration.getConfig().get(5).isEnabled()).isEqualTo(false);
|
||||
assertThat(configuration.getConfig().get(5).getValue()).isEqualTo("abc");
|
||||
assertThat(configuration.getConfig().get(6).getName()).isEqualTo("value.always.false");
|
||||
assertThat(configuration.getConfig().get(6).isEnabled()).isEqualTo(false);
|
||||
assertThat(configuration.getConfig().get(6).getValue()).isEqualTo("red");
|
||||
assertThat(configuration.getConfig().get(7).getName()).isEqualTo("linked.config.0");
|
||||
assertThat(configuration.getConfig().get(8).getName()).isEqualTo("linked.config.1");
|
||||
assertThat(configuration.getConfig().get(9).getName()).isEqualTo("unlinked.config");
|
||||
assertThat(configuration.getConfig().get(10).getName()).isEqualTo("global.maxGroupSize");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testHashKeyLinkedConfigs() {
|
||||
boolean allUnlinkedConfigsMatched = true;
|
||||
for (AuthHelper.TestAccount testAccount : AuthHelper.TEST_ACCOUNTS) {
|
||||
UserRemoteConfigList configuration = resources.getJerseyTest()
|
||||
.target("/v1/config/")
|
||||
.request()
|
||||
.header("Authorization", testAccount.getAuthHeader())
|
||||
.get(UserRemoteConfigList.class);
|
||||
|
||||
assertThat(configuration.getConfig()).hasSize(11);
|
||||
|
||||
final UserRemoteConfig linkedConfig0 = configuration.getConfig().get(7);
|
||||
assertThat(linkedConfig0.getName()).isEqualTo("linked.config.0");
|
||||
|
||||
final UserRemoteConfig linkedConfig1 = configuration.getConfig().get(8);
|
||||
assertThat(linkedConfig1.getName()).isEqualTo("linked.config.1");
|
||||
|
||||
final UserRemoteConfig unlinkedConfig = configuration.getConfig().get(9);
|
||||
assertThat(unlinkedConfig.getName()).isEqualTo("unlinked.config");
|
||||
|
||||
assertThat(linkedConfig0.isEnabled() == linkedConfig1.isEnabled()).isTrue();
|
||||
allUnlinkedConfigsMatched &= (linkedConfig0.isEnabled() == unlinkedConfig.isEnabled());
|
||||
}
|
||||
assertThat(allUnlinkedConfigsMatched).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRetrieveConfigUnauthorized() {
|
||||
Response response = resources.getJerseyTest()
|
||||
.target("/v1/config/")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.INVALID_PASSWORD))
|
||||
.get();
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(401);
|
||||
|
||||
verifyNoMoreInteractions(remoteConfigsManager);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testMath() throws NoSuchAlgorithmException {
|
||||
List<RemoteConfig> remoteConfigList = remoteConfigsManager.getAll();
|
||||
Map<String, Integer> enabledMap = new HashMap<>();
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA256");
|
||||
int iterations = 100000;
|
||||
Random random = new Random(9424242L); // the seed value doesn't matter so much as it's constant to make the test not flaky
|
||||
|
||||
for (int i=0;i<iterations;i++) {
|
||||
for (RemoteConfig config : remoteConfigList) {
|
||||
int count = enabledMap.getOrDefault(config.getName(), 0);
|
||||
|
||||
if (RemoteConfigControllerV1.isInBucket(digest, AuthHelper.getRandomUUID(random), config.getName().getBytes(), config.getPercentage(), new HashSet<>())) {
|
||||
count++;
|
||||
}
|
||||
|
||||
enabledMap.put(config.getName(), count);
|
||||
}
|
||||
}
|
||||
|
||||
for (RemoteConfig config : remoteConfigList) {
|
||||
double targetNumber = iterations * (config.getPercentage() / 100.0);
|
||||
double variance = targetNumber * 0.01;
|
||||
|
||||
assertThat(enabledMap.get(config.getName())).isBetween((int) (targetNumber - variance),
|
||||
(int) (targetNumber + variance));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+9
-7
@@ -192,7 +192,7 @@ class VerificationControllerTest {
|
||||
|
||||
@Test
|
||||
void createSessionRateLimited() {
|
||||
when(registrationServiceClient.createRegistrationSession(any(), anyString(), anyBoolean(), any()))
|
||||
when(registrationServiceClient.createRegistrationSession(any(), anyString(), anyBoolean(), any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.failedFuture(new RateLimitExceededException(null)));
|
||||
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
@@ -206,7 +206,7 @@ class VerificationControllerTest {
|
||||
|
||||
@Test
|
||||
void createSessionRegistrationServiceError() {
|
||||
when(registrationServiceClient.createRegistrationSession(any(), anyString(), anyBoolean(), any()))
|
||||
when(registrationServiceClient.createRegistrationSession(any(), anyString(), anyBoolean(), any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.failedFuture(new RuntimeException("expected service error")));
|
||||
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
@@ -221,7 +221,7 @@ class VerificationControllerTest {
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void createBeninSessionSuccess(final String requestedNumber, final String expectedNumber) {
|
||||
when(registrationServiceClient.createRegistrationSession(any(), anyString(), anyBoolean(), any()))
|
||||
when(registrationServiceClient.createRegistrationSession(any(), anyString(), anyBoolean(), any(), any(), any()))
|
||||
.thenReturn(
|
||||
CompletableFuture.completedFuture(
|
||||
new RegistrationServiceSession(SESSION_ID, requestedNumber, false, null, null, null,
|
||||
@@ -238,7 +238,7 @@ class VerificationControllerTest {
|
||||
|
||||
final ArgumentCaptor<Phonenumber.PhoneNumber> phoneNumberArgumentCaptor = ArgumentCaptor.forClass(
|
||||
Phonenumber.PhoneNumber.class);
|
||||
verify(registrationServiceClient).createRegistrationSession(phoneNumberArgumentCaptor.capture(), anyString(), anyBoolean(), any());
|
||||
verify(registrationServiceClient).createRegistrationSession(phoneNumberArgumentCaptor.capture(), anyString(), anyBoolean(), any(), any(), any());
|
||||
final Phonenumber.PhoneNumber phoneNumber = phoneNumberArgumentCaptor.getValue();
|
||||
|
||||
assertEquals(expectedNumber, PhoneNumberUtil.getInstance().format(phoneNumber, PhoneNumberUtil.PhoneNumberFormat.E164));
|
||||
@@ -262,7 +262,7 @@ class VerificationControllerTest {
|
||||
.format(PhoneNumberUtil.getInstance().getExampleNumber("BJ"), PhoneNumberUtil.PhoneNumberFormat.E164);
|
||||
final String oldFormatBeninE164 = newFormatBeninE164.replaceFirst("01", "");
|
||||
|
||||
when(registrationServiceClient.createRegistrationSession(any(), anyString(), anyBoolean(), any()))
|
||||
when(registrationServiceClient.createRegistrationSession(any(), anyString(), anyBoolean(), any(), any(), any()))
|
||||
.thenReturn(
|
||||
CompletableFuture.completedFuture(
|
||||
new RegistrationServiceSession(SESSION_ID, NUMBER, false, null, null, null,
|
||||
@@ -283,7 +283,7 @@ class VerificationControllerTest {
|
||||
@MethodSource
|
||||
void createSessionSuccess(final String pushToken, final String pushTokenType,
|
||||
final List<VerificationSession.Information> expectedRequestedInformation) {
|
||||
when(registrationServiceClient.createRegistrationSession(any(), anyString(), anyBoolean(), any()))
|
||||
when(registrationServiceClient.createRegistrationSession(any(), anyString(), anyBoolean(), any(), any(), any()))
|
||||
.thenReturn(
|
||||
CompletableFuture.completedFuture(
|
||||
new RegistrationServiceSession(SESSION_ID, NUMBER, false, null, null, null,
|
||||
@@ -317,7 +317,7 @@ class VerificationControllerTest {
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void createSessionReregistration(final boolean isReregistration) throws NumberParseException {
|
||||
when(registrationServiceClient.createRegistrationSession(any(), anyString(), anyBoolean(), any()))
|
||||
when(registrationServiceClient.createRegistrationSession(any(), anyString(), anyBoolean(), any(), any(), any()))
|
||||
.thenReturn(
|
||||
CompletableFuture.completedFuture(
|
||||
new RegistrationServiceSession(SESSION_ID, NUMBER, false, null, null, null,
|
||||
@@ -341,6 +341,8 @@ class VerificationControllerTest {
|
||||
eq(PhoneNumberUtil.getInstance().parse(NUMBER, null)),
|
||||
anyString(),
|
||||
eq(isReregistration),
|
||||
any(),
|
||||
any(),
|
||||
any()
|
||||
);
|
||||
}
|
||||
|
||||
-1
@@ -30,7 +30,6 @@ import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.junitpioneer.jupiter.cartesian.CartesianTest;
|
||||
import org.mockito.Mock;
|
||||
import org.signal.chat.backup.BackupsGrpc;
|
||||
import org.signal.chat.backup.GetBackupAuthCredentialsRequest;
|
||||
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.google.common.net.InetAddresses;
|
||||
import java.time.Duration;
|
||||
import io.grpc.Status;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mock;
|
||||
import org.signal.chat.calling.quality.CallQualityGrpc;
|
||||
import org.signal.chat.calling.quality.SubmitCallQualitySurveyRequest;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.metrics.CallQualitySurveyManager;
|
||||
|
||||
class CallQualitySurveyGrpcServiceTest extends SimpleBaseGrpcTest<CallQualitySurveyGrpcService, CallQualityGrpc.CallQualityBlockingStub> {
|
||||
|
||||
@Mock
|
||||
private CallQualitySurveyManager callQualitySurveyManager;
|
||||
|
||||
@Mock
|
||||
private RateLimiter rateLimiter;
|
||||
|
||||
private static final String USER_AGENT = "Signal-iOS/7.78.0.1041 iOS/18.3.2 libsignal/0.80.3";
|
||||
private static final String REMOTE_ADDRESS = "127.0.0.1";
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
getMockRequestAttributesInterceptor()
|
||||
.setRequestAttributes(new RequestAttributes(InetAddresses.forString(REMOTE_ADDRESS), USER_AGENT, null));
|
||||
}
|
||||
|
||||
@Override
|
||||
protected CallQualitySurveyGrpcService createServiceBeforeEachTest() {
|
||||
final RateLimiters rateLimiters = mock(RateLimiters.class);
|
||||
when(rateLimiters.getSubmitCallQualitySurveyLimiter()).thenReturn(rateLimiter);
|
||||
|
||||
return new CallQualitySurveyGrpcService(callQualitySurveyManager, rateLimiters);
|
||||
}
|
||||
|
||||
@Test
|
||||
void submitCallQualitySurvey() {
|
||||
final SubmitCallQualitySurveyRequest request = SubmitCallQualitySurveyRequest.getDefaultInstance();
|
||||
assertDoesNotThrow(() -> unauthenticatedServiceStub().submitCallQualitySurvey(request));
|
||||
|
||||
verify(callQualitySurveyManager).submitCallQualitySurvey(request, REMOTE_ADDRESS, USER_AGENT);
|
||||
}
|
||||
|
||||
@Test
|
||||
void submitCallQualitySurveyRateLimited() throws RateLimitExceededException {
|
||||
final Duration retryAfter = Duration.ofMinutes(17);
|
||||
|
||||
doThrow(new RateLimitExceededException(retryAfter))
|
||||
.when(rateLimiter).validate(REMOTE_ADDRESS);
|
||||
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
GrpcTestUtils.assertRateLimitExceeded(retryAfter,
|
||||
() -> unauthenticatedServiceStub().submitCallQualitySurvey(SubmitCallQualitySurveyRequest.getDefaultInstance()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void submitCallQualitySurveyInvalidArgument() {
|
||||
final SubmitCallQualitySurveyRequest request = SubmitCallQualitySurveyRequest.getDefaultInstance();
|
||||
|
||||
doThrow(new IllegalArgumentException())
|
||||
.when(callQualitySurveyManager).submitCallQualitySurvey(request, REMOTE_ADDRESS, USER_AGENT);
|
||||
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
GrpcTestUtils.assertStatusException(Status.INVALID_ARGUMENT,
|
||||
() -> unauthenticatedServiceStub().submitCallQualitySurvey(request));
|
||||
}
|
||||
}
|
||||
-7
@@ -466,10 +466,6 @@ class DevicesGrpcServiceTest extends SimpleBaseGrpcTest<DevicesGrpcService, Devi
|
||||
requestBuilder.addCapabilities(org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_TRANSFER);
|
||||
}
|
||||
|
||||
if (deleteSync) {
|
||||
requestBuilder.addCapabilities(org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_DELETE_SYNC);
|
||||
}
|
||||
|
||||
if (attachmentBackfill) {
|
||||
requestBuilder.addCapabilities(org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_ATTACHMENT_BACKFILL);
|
||||
}
|
||||
@@ -490,9 +486,6 @@ class DevicesGrpcServiceTest extends SimpleBaseGrpcTest<DevicesGrpcService, Devi
|
||||
expectedCapabilities.add(DeviceCapability.TRANSFER);
|
||||
}
|
||||
|
||||
if (deleteSync) {
|
||||
expectedCapabilities.add(DeviceCapability.DELETE_SYNC);
|
||||
}
|
||||
|
||||
if (attachmentBackfill) {
|
||||
expectedCapabilities.add(DeviceCapability.ATTACHMENT_BACKFILL);
|
||||
|
||||
-2
@@ -133,7 +133,6 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
|
||||
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
|
||||
when(account.getIdentityKey(org.whispersystems.textsecuregcm.identity.IdentityType.ACI)).thenReturn(identityKey);
|
||||
when(account.hasCapability(any())).thenReturn(false);
|
||||
when(account.hasCapability(DeviceCapability.DELETE_SYNC)).thenReturn(true);
|
||||
when(accountsManager.getByServiceIdentifier(serviceIdentifier)).thenReturn(Optional.of(account));
|
||||
|
||||
final GetUnversionedProfileAnonymousRequest request = GetUnversionedProfileAnonymousRequest.newBuilder()
|
||||
@@ -153,7 +152,6 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
|
||||
.setIdentityKey(ByteString.copyFrom(identityKey.serialize()))
|
||||
.setUnidentifiedAccess(ByteString.copyFrom(unidentifiedAccessChecksum))
|
||||
.setUnrestrictedUnidentifiedAccess(false)
|
||||
.addCapabilities(org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_DELETE_SYNC)
|
||||
.addAllBadges(ProfileGrpcHelper.buildBadges(badges))
|
||||
.build();
|
||||
|
||||
|
||||
Loaded 100 of 121 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user