mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-12-01 08:06:47 +00:00
Compare commits
21
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3ceaa8bd20 | ||
|
|
790b9bbf01 | ||
|
|
ee1016523f | ||
|
|
2f51778421 | ||
|
|
d3d68c2a60 | ||
|
|
0628b3e41c | ||
|
|
eac183495a | ||
|
|
0ae02da9be | ||
|
|
90fe634ddd | ||
|
|
1cae841ed6 | ||
|
|
a88560e557 | ||
|
|
3ca9a66323 | ||
|
|
3a4a55c245 | ||
|
|
f4a243861c | ||
|
|
68209f270e | ||
|
|
8af939d320 | ||
|
|
16a50935ea | ||
|
|
24ea10c451 | ||
|
|
95abda4870 | ||
|
|
c8993c4da8 | ||
|
|
d096798340 |
No files matched your search
@@ -11,8 +11,8 @@ jobs:
|
||||
contents: write
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7
|
||||
- uses: actions/setup-java@99b8673ff64fbf99d8d325f52d9a5bdedb8483e9 # v4.2.1
|
||||
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||
- uses: actions/setup-java@7a6d8a8234af8eb26422e24e3006232cccaa061b # v4.6.0
|
||||
with:
|
||||
distribution: 'temurin'
|
||||
java-version: '21'
|
||||
|
||||
@@ -13,13 +13,13 @@ jobs:
|
||||
id-token: write
|
||||
contents: read
|
||||
steps:
|
||||
- uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7
|
||||
- uses: actions/setup-java@99b8673ff64fbf99d8d325f52d9a5bdedb8483e9 # v4.2.1
|
||||
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||
- uses: actions/setup-java@7a6d8a8234af8eb26422e24e3006232cccaa061b # v4.6.0
|
||||
with:
|
||||
distribution: 'temurin'
|
||||
java-version: '21'
|
||||
cache: 'maven'
|
||||
- uses: aws-actions/configure-aws-credentials@5579c002bb4778aa43395ef1df492868a9a1c83f # v4.0.2
|
||||
- uses: aws-actions/configure-aws-credentials@e3dd6a429d7300a6a4c196c26e071d42e0343502 # v4.0.2
|
||||
name: Configure AWS credentials from Test account
|
||||
with:
|
||||
role-to-assume: ${{ vars.AWS_ROLE }}
|
||||
|
||||
@@ -11,9 +11,9 @@ jobs:
|
||||
container: ubuntu:22.04
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7
|
||||
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||
- name: Set up JDK 21
|
||||
uses: actions/setup-java@99b8673ff64fbf99d8d325f52d9a5bdedb8483e9 # v4.2.1
|
||||
uses: actions/setup-java@7a6d8a8234af8eb26422e24e3006232cccaa061b # v4.6.0
|
||||
with:
|
||||
distribution: 'temurin'
|
||||
java-version: 21
|
||||
|
||||
+2
-2
@@ -14,7 +14,7 @@
|
||||
# KIND, either express or implied. See the License for the
|
||||
# specific language governing permissions and limitations
|
||||
# under the License.
|
||||
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.8/apache-maven-3.9.8-bin.zip
|
||||
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip
|
||||
wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.3.2/maven-wrapper-3.3.2.jar
|
||||
distributionSha256Sum=8351955a9acf2f83c136c4eee0f6db894ab6265fdbe0a94b32a380307dbaa3e1
|
||||
distributionSha256Sum=4ec3f26fb1a692473aea0235c300bd20f0f9fe741947c82c1234cefd76ac3a3c
|
||||
wrapperSha256Sum=3d8f20ce6103913be8b52aef6d994e0c54705fb527324ceb9b835b338739c7a8
|
||||
@@ -37,45 +37,44 @@
|
||||
</modules>
|
||||
|
||||
<properties>
|
||||
<aws.sdk2.version>2.29.7</aws.sdk2.version>
|
||||
<aws.sdk2.version>2.29.48</aws.sdk2.version>
|
||||
<braintree.version>3.37.0</braintree.version>
|
||||
<commons-csv.version>1.12.0</commons-csv.version>
|
||||
<commons-io.version>2.17.0</commons-io.version>
|
||||
<dropwizard.version>4.0.10</dropwizard.version>
|
||||
<commons-io.version>2.18.0</commons-io.version>
|
||||
<dropwizard.version>4.0.11</dropwizard.version>
|
||||
<dropwizard-metrics-datadog.version>1.1.13</dropwizard-metrics-datadog.version>
|
||||
<!-- can be updated to latest version with Dropwizard 5 (Jetty 12); will then need to disable telemetry -->
|
||||
<dynamodblocal.version>2.2.1</dynamodblocal.version>
|
||||
<google-cloud-libraries.version>26.50.0</google-cloud-libraries.version>
|
||||
<grpc.version>1.61.1</grpc.version> <!-- should be kept in sync with the value from Google libraries-bom -->
|
||||
<google-cloud-libraries.version>26.52.0</google-cloud-libraries.version>
|
||||
<grpc.version>1.69.0</grpc.version> <!-- should be kept in sync with the value from Google libraries-bom -->
|
||||
<gson.version>2.11.0</gson.version>
|
||||
<!-- several libraries (AWS, Google Cloud) use Apache http components transitively, and we need to align them -->
|
||||
<httpcore.version>4.4.16</httpcore.version>
|
||||
<httpclient.version>4.5.14</httpclient.version>
|
||||
<jackson.version>2.18.1</jackson.version>
|
||||
<jackson.version>2.18.2</jackson.version>
|
||||
<jaxb.version>2.3.1</jaxb.version>
|
||||
<junit-pioneer.version>2.3.0</junit-pioneer.version>
|
||||
<jsr305.version>3.0.2</jsr305.version>
|
||||
<kotlin.version>1.9.24</kotlin.version>
|
||||
<kotlinx-serialization.version>1.5.1</kotlinx-serialization.version>
|
||||
<kotlin.version>1.9.25</kotlin.version>
|
||||
<lettuce.version>6.5.1.RELEASE</lettuce.version>
|
||||
<libphonenumber.version>8.13.50</libphonenumber.version>
|
||||
<libphonenumber.version>8.13.52</libphonenumber.version>
|
||||
<logstash.logback.version>7.3</logstash.logback.version>
|
||||
<log4j-bom.version>2.23.1</log4j-bom.version>
|
||||
<luajava.version>3.4.0</luajava.version>
|
||||
<micrometer.version>1.13.6</micrometer.version>
|
||||
<netty.version>4.1.111.Final</netty.version>
|
||||
<log4j-bom.version>2.24.3</log4j-bom.version>
|
||||
<luajava.version>3.5.0</luajava.version>
|
||||
<micrometer.version>1.14.2</micrometer.version>
|
||||
<netty.version>4.1.116.Final</netty.version>
|
||||
<protobuf.version>3.25.5</protobuf.version> <!-- must be greater than or equal to the value from Google libraries-bom, see https://protobuf.dev/support/cross-version-runtime-guarantee/ -->
|
||||
<pushy.version>0.15.4</pushy.version>
|
||||
<reactive.grpc.version>1.2.4</reactive.grpc.version>
|
||||
<reactor-bom.version>2023.0.11</reactor-bom.version> <!-- 3.6.x, see https://github.com/reactor/reactor#bom-versioning-scheme -->
|
||||
<reactor-bom.version>2024.0.1</reactor-bom.version> <!-- 3.7.1, see https://github.com/reactor/reactor#bom-versioning-scheme -->
|
||||
<resilience4j.version>2.2.0</resilience4j.version>
|
||||
<semver4j.version>3.1.0</semver4j.version>
|
||||
<slf4j.version>2.0.13</slf4j.version>
|
||||
<slf4j.version>2.0.16</slf4j.version>
|
||||
<stripe.version>23.10.0</stripe.version>
|
||||
<swagger.version>2.2.25</swagger.version>
|
||||
<swagger.version>2.2.27</swagger.version>
|
||||
|
||||
<!-- 21.0.4_7-jre-jammy (note: always use the multi-arch manifest *LIST* here) -->
|
||||
<docker.image.sha256>870aae69d4521fdaf26e952f8026f75b37cb721e6302d4d4d7100f6b09823057</docker.image.sha256>
|
||||
<!-- eclipse-temurin:21.0.5_11-jre-jammy (note: always use the multi-arch manifest *LIST* here) -->
|
||||
<docker.image.sha256>5f8358c9d5615c18e95728e8b8528bda7ff40a7a5da2ac9a35b7a01f5d9b231a</docker.image.sha256>
|
||||
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
</properties>
|
||||
@@ -511,7 +510,7 @@
|
||||
<rules>
|
||||
<dependencyConvergence/>
|
||||
<requireMavenVersion>
|
||||
<version>3.8.6</version>
|
||||
<version>3.9.9</version>
|
||||
</requireMavenVersion>
|
||||
</rules>
|
||||
</configuration>
|
||||
|
||||
@@ -484,6 +484,7 @@ turn:
|
||||
- turns:%s:443?transport=tcp
|
||||
ttl: 86400
|
||||
hostname: turn.cloudflare.example.com
|
||||
numHttpClients: 1
|
||||
|
||||
linkDevice:
|
||||
secret: secret://linkDevice.secret
|
||||
|
||||
+9
-9
@@ -11,11 +11,11 @@
|
||||
<artifactId>service</artifactId>
|
||||
|
||||
<properties>
|
||||
<firebase-admin.version>9.4.1</firebase-admin.version>
|
||||
<firebase-admin.version>9.4.2</firebase-admin.version>
|
||||
<java-uuid-generator.version>5.1.0</java-uuid-generator.version>
|
||||
<google-androidpublisher.version>v3-rev20241016-2.0.0</google-androidpublisher.version>
|
||||
<google-androidpublisher.version>v3-rev20250102-2.0.0</google-androidpublisher.version>
|
||||
<storekit.version>3.2.0</storekit.version>
|
||||
<webauthn4j.version>0.28.0.RELEASE</webauthn4j.version>
|
||||
<webauthn4j.version>0.28.4.RELEASE</webauthn4j.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
@@ -229,13 +229,13 @@
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-compress</artifactId>
|
||||
<version>1.26.0</version>
|
||||
<version>1.27.1</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.maxmind.geoip2</groupId>
|
||||
<artifactId>geoip2</artifactId>
|
||||
<version>4.2.0</version>
|
||||
<version>4.2.1</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
@@ -251,13 +251,13 @@
|
||||
<dependency>
|
||||
<groupId>io.opentelemetry.semconv</groupId>
|
||||
<artifactId>opentelemetry-semconv</artifactId>
|
||||
<version>1.25.0-alpha</version>
|
||||
<version>1.27.0-alpha</version>
|
||||
</dependency>
|
||||
<!-- resolve opentelemetry-semconv conflict from lower in firebase-admin dependency tree -->
|
||||
<dependency>
|
||||
<groupId>com.google.cloud</groupId>
|
||||
<artifactId>google-cloud-firestore</artifactId>
|
||||
<version>3.28.0</version>
|
||||
<version>3.30.2</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>io.opentelemetry.semconv</groupId>
|
||||
@@ -368,7 +368,7 @@
|
||||
<dependency>
|
||||
<groupId>com.amazonaws</groupId>
|
||||
<artifactId>dynamodb-lock-client</artifactId>
|
||||
<version>1.2.0</version>
|
||||
<version>1.3.0</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
@@ -410,7 +410,7 @@
|
||||
<dependency>
|
||||
<groupId>com.googlecode.libphonenumber</groupId>
|
||||
<artifactId>geocoder</artifactId>
|
||||
<version>2.234</version>
|
||||
<version>2.246</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
|
||||
@@ -154,6 +154,7 @@ import org.whispersystems.textsecuregcm.grpc.PaymentsGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.ProfileAnonymousGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.ProfileGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.RequestAttributesInterceptor;
|
||||
import org.whispersystems.textsecuregcm.grpc.ValidatingInterceptor;
|
||||
import org.whispersystems.textsecuregcm.grpc.net.GrpcClientConnectionManager;
|
||||
import org.whispersystems.textsecuregcm.grpc.net.ManagedDefaultEventLoopGroup;
|
||||
import org.whispersystems.textsecuregcm.grpc.net.ManagedLocalGrpcServer;
|
||||
@@ -175,6 +176,7 @@ import org.whispersystems.textsecuregcm.mappers.ImpossiblePhoneNumberExceptionMa
|
||||
import org.whispersystems.textsecuregcm.mappers.InvalidWebsocketAddressExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.JsonMappingExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.NonNormalizedPhoneNumberExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.ObsoletePhoneNumberFormatExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.RegistrationServiceSenderExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.ServerRejectedExceptionMapper;
|
||||
@@ -667,8 +669,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
|
||||
final MessageSender messageSender = new MessageSender(messagesManager, pushNotificationManager);
|
||||
final ReceiptSender receiptSender = new ReceiptSender(accountsManager, messageSender, receiptSenderExecutor);
|
||||
final TurnTokenGenerator turnTokenGenerator = new TurnTokenGenerator(dynamicConfigurationManager,
|
||||
config.getTurnConfiguration().secret().value());
|
||||
final TurnTokenGenerator turnTokenGenerator = new TurnTokenGenerator(config.getTurnConfiguration().secret().value());
|
||||
final CloudflareTurnCredentialsManager cloudflareTurnCredentialsManager = new CloudflareTurnCredentialsManager(
|
||||
config.getTurnConfiguration().cloudflare().apiToken().value(),
|
||||
config.getTurnConfiguration().cloudflare().endpoint(),
|
||||
@@ -676,6 +677,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
config.getTurnConfiguration().cloudflare().urls(),
|
||||
config.getTurnConfiguration().cloudflare().urlsWithIps(),
|
||||
config.getTurnConfiguration().cloudflare().hostname(),
|
||||
config.getTurnConfiguration().cloudflare().numHttpClients(),
|
||||
config.getTurnConfiguration().cloudflare().circuitBreaker(),
|
||||
cloudflareTurnHttpExecutor,
|
||||
config.getTurnConfiguration().cloudflare().retry(),
|
||||
@@ -860,6 +862,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
final RequestAttributesInterceptor requestAttributesInterceptor =
|
||||
new RequestAttributesInterceptor(grpcClientConnectionManager);
|
||||
|
||||
final ValidatingInterceptor validatingInterceptor = new ValidatingInterceptor();
|
||||
|
||||
final LocalAddress anonymousGrpcServerAddress = new LocalAddress("grpc-anonymous");
|
||||
final LocalAddress authenticatedGrpcServerAddress = new LocalAddress("grpc-authenticated");
|
||||
|
||||
@@ -873,6 +877,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
.intercept(
|
||||
new ExternalRequestFilter(config.getExternalRequestFilterConfiguration().permittedInternalRanges(),
|
||||
config.getExternalRequestFilterConfiguration().grpcMethods()))
|
||||
.intercept(validatingInterceptor)
|
||||
// TODO: specialize metrics with user-agent platform
|
||||
.intercept(metricCollectingServerInterceptor)
|
||||
.intercept(errorMappingInterceptor)
|
||||
@@ -895,6 +900,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
// http://grpc.github.io/grpc-java/javadoc/io/grpc/ServerBuilder.html#intercept-io.grpc.ServerInterceptor-
|
||||
serverBuilder
|
||||
// TODO: specialize metrics with user-agent platform
|
||||
.intercept(validatingInterceptor)
|
||||
.intercept(metricCollectingServerInterceptor)
|
||||
.intercept(errorMappingInterceptor)
|
||||
.intercept(remoteDeprecationFilter)
|
||||
@@ -1094,7 +1100,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
final PhoneVerificationTokenManager phoneVerificationTokenManager = new PhoneVerificationTokenManager(
|
||||
phoneNumberIdentifiers, registrationServiceClient, registrationRecoveryPasswordsManager, registrationRecoveryChecker);
|
||||
final List<Object> commonControllers = Lists.newArrayList(
|
||||
new AccountController(accountsManager, rateLimiters, turnTokenGenerator, registrationRecoveryPasswordsManager,
|
||||
new AccountController(accountsManager, rateLimiters, registrationRecoveryPasswordsManager,
|
||||
usernameHashZkProofVerifier),
|
||||
new AccountControllerV2(accountsManager, changeNumberManager, phoneVerificationTokenManager,
|
||||
registrationLockVerificationManager, rateLimiters),
|
||||
@@ -1212,6 +1218,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
new ServerRejectedExceptionMapper(),
|
||||
new ImpossiblePhoneNumberExceptionMapper(),
|
||||
new NonNormalizedPhoneNumberExceptionMapper(),
|
||||
new ObsoletePhoneNumberFormatExceptionMapper(),
|
||||
new RegistrationServiceSenderExceptionMapper(),
|
||||
new SubscriptionExceptionMapper(),
|
||||
new JsonMappingExceptionMapper()
|
||||
|
||||
+19
-2
@@ -6,6 +6,8 @@
|
||||
package org.whispersystems.textsecuregcm.auth;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
import io.netty.resolver.dns.DnsNameResolver;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import java.io.IOException;
|
||||
@@ -22,6 +24,7 @@ import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.configuration.CircuitBreakerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.RetryConfiguration;
|
||||
import org.whispersystems.textsecuregcm.http.FaultTolerantHttpClient;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
|
||||
@@ -29,6 +32,9 @@ public class CloudflareTurnCredentialsManager {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(CloudflareTurnCredentialsManager.class);
|
||||
|
||||
private static final String CREDENTIAL_FETCH_TIMER_NAME = MetricsUtil.name(CloudflareTurnCredentialsManager.class,
|
||||
"credentialFetchLatency");
|
||||
|
||||
private final List<String> cloudflareTurnUrls;
|
||||
private final List<String> cloudflareTurnUrlsWithIps;
|
||||
private final String cloudflareTurnHostname;
|
||||
@@ -51,8 +57,9 @@ public class CloudflareTurnCredentialsManager {
|
||||
public CloudflareTurnCredentialsManager(final String cloudflareTurnApiToken,
|
||||
final String cloudflareTurnEndpoint, final long cloudflareTurnTtl, final List<String> cloudflareTurnUrls,
|
||||
final List<String> cloudflareTurnUrlsWithIps, final String cloudflareTurnHostname,
|
||||
final CircuitBreakerConfiguration circuitBreaker, final ExecutorService executor, final RetryConfiguration retry,
|
||||
final ScheduledExecutorService retryExecutor, final DnsNameResolver dnsNameResolver) {
|
||||
final int cloudflareTurnNumHttpClients, final CircuitBreakerConfiguration circuitBreaker,
|
||||
final ExecutorService executor, final RetryConfiguration retry, final ScheduledExecutorService retryExecutor,
|
||||
final DnsNameResolver dnsNameResolver) {
|
||||
|
||||
this.cloudflareTurnClient = FaultTolerantHttpClient.newBuilder()
|
||||
.withName("cloudflare-turn")
|
||||
@@ -60,6 +67,7 @@ public class CloudflareTurnCredentialsManager {
|
||||
.withExecutor(executor)
|
||||
.withRetry(retry)
|
||||
.withRetryExecutor(retryExecutor)
|
||||
.withNumClients(cloudflareTurnNumHttpClients)
|
||||
.build();
|
||||
this.cloudflareTurnUrls = cloudflareTurnUrls;
|
||||
this.cloudflareTurnUrlsWithIps = cloudflareTurnUrlsWithIps;
|
||||
@@ -93,11 +101,20 @@ public class CloudflareTurnCredentialsManager {
|
||||
throw new IOException(e);
|
||||
}
|
||||
|
||||
final Timer.Sample sample = Timer.start();
|
||||
final HttpResponse<String> response;
|
||||
try {
|
||||
response = cloudflareTurnClient.sendAsync(request, HttpResponse.BodyHandlers.ofString()).join();
|
||||
sample.stop(Timer.builder(CREDENTIAL_FETCH_TIMER_NAME)
|
||||
.publishPercentileHistogram(true)
|
||||
.tags("outcome", "success")
|
||||
.register(Metrics.globalRegistry));
|
||||
} catch (CompletionException e) {
|
||||
logger.warn("failed to make http request to Cloudflare Turn: {}", e.getMessage());
|
||||
sample.stop(Timer.builder(CREDENTIAL_FETCH_TIMER_NAME)
|
||||
.publishPercentileHistogram(true)
|
||||
.tags("outcome", "failure")
|
||||
.register(Metrics.globalRegistry));
|
||||
throw new IOException(ExceptionUtils.unwrap(e));
|
||||
}
|
||||
|
||||
|
||||
+1
-29
@@ -27,8 +27,6 @@ import org.whispersystems.textsecuregcm.util.WeightedRandomSelect;
|
||||
|
||||
public class TurnTokenGenerator {
|
||||
|
||||
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
|
||||
|
||||
private final byte[] turnSecret;
|
||||
|
||||
private static final String ALGORITHM = "HmacSHA1";
|
||||
@@ -37,17 +35,10 @@ public class TurnTokenGenerator {
|
||||
|
||||
private static final String WithIpsProtocol = "01";
|
||||
|
||||
public TurnTokenGenerator(final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
|
||||
final byte[] turnSecret) {
|
||||
this.dynamicConfigurationManager = dynamicConfigurationManager;
|
||||
public TurnTokenGenerator(final byte[] turnSecret) {
|
||||
this.turnSecret = turnSecret;
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public TurnToken generate(final UUID aci) {
|
||||
return generateToken(null, null, urls(aci));
|
||||
}
|
||||
|
||||
public TurnToken generateWithTurnServerOptions(TurnServerOptions options) {
|
||||
return generateToken(options.hostname(), options.urlsWithIps(), options.urlsWithHostname());
|
||||
}
|
||||
@@ -71,23 +62,4 @@ public class TurnTokenGenerator {
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
}
|
||||
|
||||
private List<String> urls(final UUID aci) {
|
||||
final DynamicTurnConfiguration turnConfig = dynamicConfigurationManager.getConfiguration().getTurnConfiguration();
|
||||
|
||||
// Check if number is enrolled to test out specific turn servers
|
||||
final Optional<TurnUriConfiguration> enrolled = turnConfig.getUriConfigs().stream()
|
||||
.filter(config -> config.getEnrolledAcis().contains(aci))
|
||||
.findFirst();
|
||||
|
||||
if (enrolled.isPresent()) {
|
||||
return enrolled.get().getUris();
|
||||
}
|
||||
|
||||
// Otherwise, select from turn server sets by weighted choice
|
||||
return WeightedRandomSelect.select(turnConfig
|
||||
.getUriConfigs()
|
||||
.stream()
|
||||
.map(c -> new Pair<>(c.getUris(), c.getWeight())).toList());
|
||||
}
|
||||
}
|
||||
+3
-1
@@ -9,6 +9,7 @@ import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import java.util.List;
|
||||
import jakarta.validation.constraints.Positive;
|
||||
import org.whispersystems.textsecuregcm.configuration.secrets.SecretString;
|
||||
|
||||
public record CloudflareTurnConfiguration(@NotNull SecretString apiToken,
|
||||
@@ -18,7 +19,8 @@ public record CloudflareTurnConfiguration(@NotNull SecretString apiToken,
|
||||
@NotBlank List<String> urlsWithIps,
|
||||
@NotNull @Valid CircuitBreakerConfiguration circuitBreaker,
|
||||
@NotNull @Valid RetryConfiguration retry,
|
||||
@NotBlank String hostname) {
|
||||
@NotBlank String hostname,
|
||||
@Positive int numHttpClients) {
|
||||
|
||||
public CloudflareTurnConfiguration {
|
||||
if (circuitBreaker == null) {
|
||||
|
||||
-17
@@ -35,11 +35,8 @@ import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import javax.annotation.Nullable;
|
||||
import org.signal.libsignal.usernames.BaseUsernameException;
|
||||
import org.whispersystems.textsecuregcm.auth.AccountAndAuthenticatedDeviceHolder;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
|
||||
import org.whispersystems.textsecuregcm.auth.TurnToken;
|
||||
import org.whispersystems.textsecuregcm.auth.TurnTokenGenerator;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountIdentifierResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountIdentityResponse;
|
||||
@@ -61,7 +58,6 @@ import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
|
||||
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.UsernameHashNotAvailableException;
|
||||
import org.whispersystems.textsecuregcm.storage.UsernameReservationNotFoundException;
|
||||
@@ -82,33 +78,20 @@ public class AccountController {
|
||||
|
||||
private final AccountsManager accounts;
|
||||
private final RateLimiters rateLimiters;
|
||||
private final TurnTokenGenerator turnTokenGenerator;
|
||||
private final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager;
|
||||
private final UsernameHashZkProofVerifier usernameHashZkProofVerifier;
|
||||
|
||||
public AccountController(
|
||||
AccountsManager accounts,
|
||||
RateLimiters rateLimiters,
|
||||
TurnTokenGenerator turnTokenGenerator,
|
||||
RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager,
|
||||
UsernameHashZkProofVerifier usernameHashZkProofVerifier) {
|
||||
this.accounts = accounts;
|
||||
this.rateLimiters = rateLimiters;
|
||||
this.turnTokenGenerator = turnTokenGenerator;
|
||||
this.registrationRecoveryPasswordsManager = registrationRecoveryPasswordsManager;
|
||||
this.usernameHashZkProofVerifier = usernameHashZkProofVerifier;
|
||||
}
|
||||
|
||||
// may be removed after 2024-07-16
|
||||
@Deprecated(forRemoval = true)
|
||||
@GET
|
||||
@Path("/turn/")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public TurnToken getTurnToken(@ReadOnly @Auth AuthenticatedDevice auth) throws RateLimitExceededException {
|
||||
rateLimiters.getTurnLimiter().validate(auth.getAccount().getUuid());
|
||||
return turnTokenGenerator.generate(auth.getAccount().getUuid());
|
||||
}
|
||||
|
||||
@PUT
|
||||
@Path("/gcm/")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
|
||||
+12
-4
@@ -6,12 +6,13 @@ 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 jakarta.ws.rs.core.Response;
|
||||
import java.time.Clock;
|
||||
import java.util.UUID;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
@@ -48,9 +49,16 @@ public class DirectoryV2Controller {
|
||||
@GET
|
||||
@Path("/auth")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public Response getAuthToken(final @ReadOnly @Auth AuthenticatedDevice auth) {
|
||||
@Operation(
|
||||
summary = "Generate credentials for Contact Discovery Service",
|
||||
description = """
|
||||
Generate Contact Discovery Service credentials. Generated credentials have an expiration time of 24 hours\s
|
||||
(however, the TTL is fully controlled by the server and may change even for already generated credentials).
|
||||
"""
|
||||
)
|
||||
@ApiResponse(responseCode = "200", description = "`JSON` with generated credentials.", useReturnTypeSchema = true)
|
||||
public ExternalServiceCredentials getAuthToken(final @ReadOnly @Auth AuthenticatedDevice auth) {
|
||||
final UUID uuid = auth.getAccount().getUuid();
|
||||
final ExternalServiceCredentials credentials = directoryServiceTokenGenerator.generateForUuid(uuid);
|
||||
return Response.ok().entity(credentials).build();
|
||||
return directoryServiceTokenGenerator.generateForUuid(uuid);
|
||||
}
|
||||
}
|
||||
+3
-3
@@ -151,21 +151,21 @@ public class KeyTransparencyController {
|
||||
try {
|
||||
final AciMonitorRequest aciMonitorRequest = AciMonitorRequest.newBuilder()
|
||||
.setAci(ByteString.copyFrom(request.aci().value().toCompactByteArray()))
|
||||
.addAllEntries(request.aci().positions())
|
||||
.setEntryPosition(request.aci().entryPosition())
|
||||
.setCommitmentIndex(ByteString.copyFrom(request.aci().commitmentIndex()))
|
||||
.build();
|
||||
|
||||
final Optional<UsernameHashMonitorRequest> usernameHashMonitorRequest = request.usernameHash().map(usernameHash ->
|
||||
UsernameHashMonitorRequest.newBuilder()
|
||||
.setUsernameHash(ByteString.copyFrom(usernameHash.value()))
|
||||
.addAllEntries(usernameHash.positions())
|
||||
.setEntryPosition(usernameHash.entryPosition())
|
||||
.setCommitmentIndex(ByteString.copyFrom(usernameHash.commitmentIndex()))
|
||||
.build());
|
||||
|
||||
final Optional<E164MonitorRequest> e164MonitorRequest = request.e164().map(e164 ->
|
||||
E164MonitorRequest.newBuilder()
|
||||
.setE164(e164.value())
|
||||
.addAllEntries(e164.positions())
|
||||
.setEntryPosition(e164.entryPosition())
|
||||
.setCommitmentIndex(ByteString.copyFrom(e164.commitmentIndex()))
|
||||
.build());
|
||||
|
||||
|
||||
+17
@@ -177,6 +177,7 @@ public class MessageController {
|
||||
private static final CompletableFuture<?>[] EMPTY_FUTURE_ARRAY = new CompletableFuture<?>[0];
|
||||
|
||||
private static final String REJECT_OVERSIZE_MESSAGE_COUNTER = name(MessageController.class, "rejectOversizeMessage");
|
||||
private static final String LARGE_BUT_NOT_OVERSIZE_MESSAGE_COUNTER = name(MessageController.class, "largeMessage");
|
||||
private static final String SENT_MESSAGE_COUNTER_NAME = name(MessageController.class, "sentMessages");
|
||||
private static final String CONTENT_SIZE_DISTRIBUTION_NAME = MetricsUtil.name(MessageController.class, "messageContentSize");
|
||||
private static final String OUTGOING_MESSAGE_LIST_SIZE_BYTES_DISTRIBUTION_NAME = name(MessageController.class, "outgoingMessageListSizeBytes");
|
||||
@@ -208,6 +209,12 @@ public class MessageController {
|
||||
|
||||
@VisibleForTesting
|
||||
static final long MAX_MESSAGE_SIZE = DataSize.kibibytes(256).toBytes();
|
||||
private static final long LARGE_MESSAGE_SIZE = DataSize.kibibytes(8).toBytes();
|
||||
|
||||
// The Signal desktop client (really, JavaScript in general) can handle message timestamps at most 100,000,000 days
|
||||
// past the epoch; please see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date
|
||||
// for additional details.
|
||||
public static final long MAX_TIMESTAMP = 86_400_000L * 100_000_000L;
|
||||
|
||||
private static final Duration NOTIFY_FOR_REMAINING_MESSAGES_DELAY = Duration.ofMinutes(1);
|
||||
|
||||
@@ -554,6 +561,10 @@ public class MessageController {
|
||||
|
||||
@Context ContainerRequestContext context) throws RateLimitExceededException {
|
||||
|
||||
if (timestamp < 0 || timestamp > MAX_TIMESTAMP) {
|
||||
throw new BadRequestException("Illegal timestamp");
|
||||
}
|
||||
|
||||
final SpamChecker.SpamCheckResult spamCheck = spamChecker.checkForSpam(context, Optional.empty(), Optional.empty(), Optional.empty());
|
||||
if (spamCheck instanceof final SpamChecker.Spam spam) {
|
||||
return spam.response();
|
||||
@@ -993,6 +1004,12 @@ public class MessageController {
|
||||
.increment();
|
||||
throw new WebApplicationException(Status.REQUEST_ENTITY_TOO_LARGE);
|
||||
}
|
||||
if (contentLength > LARGE_MESSAGE_SIZE) {
|
||||
Metrics.counter(
|
||||
LARGE_BUT_NOT_OVERSIZE_MESSAGE_COUNTER,
|
||||
Tags.of(UserAgentTagUtil.getPlatformTag(userAgent), Tag.of("multiRecipientMessage", String.valueOf(multiRecipientMessage))))
|
||||
.increment();
|
||||
}
|
||||
}
|
||||
|
||||
private void validateEnvelopeType(final int type, final String userAgent) {
|
||||
|
||||
+12
@@ -7,6 +7,8 @@ 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;
|
||||
@@ -52,6 +54,16 @@ public class RemoteConfigController {
|
||||
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Operation(
|
||||
summary = "Fetch remote configuration",
|
||||
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.
|
||||
"""
|
||||
)
|
||||
@ApiResponse(responseCode = "200", description = "Remote configuration values for the authenticated user", useReturnTypeSchema = true)
|
||||
public UserRemoteConfigList getAll(@ReadOnly @Auth AuthenticatedDevice auth) {
|
||||
try {
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA1");
|
||||
|
||||
+10
@@ -6,6 +6,8 @@
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
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;
|
||||
@@ -37,6 +39,14 @@ public class SecureStorageController {
|
||||
@GET
|
||||
@Path("/auth")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Operation(
|
||||
summary = "Generate credentials for Storage Service",
|
||||
description = """
|
||||
Generate Storage Service credentials. Generated credentials have an expiration time of 24 hours\s
|
||||
(however, the TTL is fully controlled by the server and may change even for already generated credentials).
|
||||
"""
|
||||
)
|
||||
@ApiResponse(responseCode = "200", description = "`JSON` with generated credentials.", useReturnTypeSchema = true)
|
||||
public ExternalServiceCredentials getAuth(@ReadOnly @Auth AuthenticatedDevice auth) {
|
||||
return storageServiceCredentialsGenerator.generateForUuid(auth.getAccount().getUuid());
|
||||
}
|
||||
|
||||
+2
-1
@@ -95,6 +95,7 @@ import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
|
||||
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.VerificationSessionManager;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.ObsoletePhoneNumberFormatException;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
@@ -173,7 +174,7 @@ public class VerificationController {
|
||||
description = "If present, an positive integer indicating the number of seconds before a subsequent attempt could succeed",
|
||||
schema = @Schema(implementation = Integer.class)))
|
||||
public VerificationSessionResponse createSession(@NotNull @Valid final CreateVerificationSessionRequest request)
|
||||
throws RateLimitExceededException {
|
||||
throws RateLimitExceededException, ObsoletePhoneNumberFormatException {
|
||||
|
||||
final Pair<String, PushNotification.TokenType> pushTokenAndType = validateAndExtractPushToken(
|
||||
request.getUpdateVerificationSessionRequest());
|
||||
|
||||
+13
-2
@@ -9,6 +9,8 @@ import static com.codahale.metrics.MetricRegistry.name;
|
||||
import com.fasterxml.jackson.annotation.JsonCreator;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
import jakarta.validation.constraints.Max;
|
||||
import jakarta.validation.constraints.PositiveOrZero;
|
||||
import org.whispersystems.textsecuregcm.controllers.MessageController;
|
||||
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
@@ -19,8 +21,17 @@ import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.AssertTrue;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
|
||||
public record IncomingMessageList(@NotNull @Valid List<@NotNull IncomingMessage> messages,
|
||||
boolean online, boolean urgent, long timestamp) {
|
||||
public record IncomingMessageList(@NotNull
|
||||
@Valid
|
||||
List<@NotNull @Valid IncomingMessage> messages,
|
||||
|
||||
boolean online,
|
||||
|
||||
boolean urgent,
|
||||
|
||||
@PositiveOrZero
|
||||
@Max(MessageController.MAX_TIMESTAMP)
|
||||
long timestamp) {
|
||||
|
||||
private static final Counter REJECT_DUPLICATE_RECIPIENT_COUNTER =
|
||||
Metrics.counter(
|
||||
|
||||
+9
-15
@@ -13,7 +13,6 @@ import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Positive;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
|
||||
@@ -49,11 +48,9 @@ public record KeyTransparencyMonitorRequest(
|
||||
@Schema(description = "The aci identifier to monitor")
|
||||
AciServiceIdentifier value,
|
||||
|
||||
@Schema(description = "A list of log tree positions maintained by the client for the aci search key.")
|
||||
@Valid
|
||||
@NotNull
|
||||
@NotEmpty
|
||||
List<@Positive Long> positions,
|
||||
@Schema(description = "A log tree position maintained by the client for the aci.")
|
||||
@Positive
|
||||
long entryPosition,
|
||||
|
||||
@Schema(description = "The commitment index derived from a previous search request, encoded in standard unpadded base64")
|
||||
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
|
||||
@@ -68,11 +65,9 @@ public record KeyTransparencyMonitorRequest(
|
||||
@NotBlank
|
||||
String value,
|
||||
|
||||
@Schema(description = "A list of log tree positions maintained by the client for the e164 search key.")
|
||||
@NotNull
|
||||
@NotEmpty
|
||||
@Valid
|
||||
List<@Positive Long> positions,
|
||||
@Schema(description = "A log tree position maintained by the client for the e164.")
|
||||
@Positive
|
||||
long entryPosition,
|
||||
|
||||
@Schema(description = "The commitment index derived from a previous search request, encoded in standard unpadded base64")
|
||||
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
|
||||
@@ -91,10 +86,9 @@ public record KeyTransparencyMonitorRequest(
|
||||
@NotEmpty
|
||||
byte[] value,
|
||||
|
||||
@Schema(description = "A list of log tree positions maintained by the client for the username hash search key.")
|
||||
@NotNull
|
||||
@NotEmpty
|
||||
@Valid List<@Positive Long> positions,
|
||||
@Schema(description = "A log tree position maintained by the client for the username hash.")
|
||||
@Positive
|
||||
long entryPosition,
|
||||
|
||||
@Schema(description = "The commitment index derived from a previous search request, encoded in standard unpadded base64")
|
||||
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
|
||||
|
||||
+10
-5
@@ -6,24 +6,29 @@
|
||||
package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
|
||||
public class UserRemoteConfig {
|
||||
|
||||
@JsonProperty
|
||||
private String name;
|
||||
@Schema(description = "Name of the configuration", example = "android.exampleFeature")
|
||||
private String name;
|
||||
|
||||
@JsonProperty
|
||||
@Schema(description = "Whether the configuration is enabled for the user")
|
||||
private boolean enabled;
|
||||
|
||||
@JsonProperty
|
||||
private String value;
|
||||
@Schema(description = "The value to be used for the configuration, if it is a non-boolean type")
|
||||
private String value;
|
||||
|
||||
public UserRemoteConfig() {}
|
||||
public UserRemoteConfig() {
|
||||
}
|
||||
|
||||
public UserRemoteConfig(String name, boolean enabled, String value) {
|
||||
this.name = name;
|
||||
this.name = name;
|
||||
this.enabled = enabled;
|
||||
this.value = value;
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
|
||||
+6
@@ -10,16 +10,22 @@ import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import org.whispersystems.textsecuregcm.util.InstantAdapter;
|
||||
|
||||
public class UserRemoteConfigList {
|
||||
|
||||
@JsonProperty
|
||||
@Schema(description = "List of remote configurations applicable to the user")
|
||||
private List<UserRemoteConfig> config;
|
||||
|
||||
@JsonProperty
|
||||
@JsonSerialize(using = InstantAdapter.EpochSecondSerializer.class)
|
||||
@JsonFormat(shape = JsonFormat.Shape.NUMBER_INT)
|
||||
@Schema(description = """
|
||||
Timestamp when the configuration was generated. Deprecated in favor of `X-Signal-Timestamp` response header.
|
||||
""", deprecated = true)
|
||||
@Deprecated
|
||||
private Instant serverEpochTime;
|
||||
|
||||
public UserRemoteConfigList() {}
|
||||
|
||||
+226
@@ -0,0 +1,226 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import io.grpc.Status;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import org.signal.chat.backup.CopyMediaRequest;
|
||||
import org.signal.chat.backup.CopyMediaResponse;
|
||||
import org.signal.chat.backup.DeleteAllRequest;
|
||||
import org.signal.chat.backup.DeleteAllResponse;
|
||||
import org.signal.chat.backup.DeleteMediaRequest;
|
||||
import org.signal.chat.backup.DeleteMediaResponse;
|
||||
import org.signal.chat.backup.GetBackupInfoRequest;
|
||||
import org.signal.chat.backup.GetBackupInfoResponse;
|
||||
import org.signal.chat.backup.GetCdnCredentialsRequest;
|
||||
import org.signal.chat.backup.GetCdnCredentialsResponse;
|
||||
import org.signal.chat.backup.GetUploadFormRequest;
|
||||
import org.signal.chat.backup.GetUploadFormResponse;
|
||||
import org.signal.chat.backup.ListMediaRequest;
|
||||
import org.signal.chat.backup.ListMediaResponse;
|
||||
import org.signal.chat.backup.ReactorBackupsAnonymousGrpc;
|
||||
import org.signal.chat.backup.RefreshRequest;
|
||||
import org.signal.chat.backup.RefreshResponse;
|
||||
import org.signal.chat.backup.SetPublicKeyRequest;
|
||||
import org.signal.chat.backup.SetPublicKeyResponse;
|
||||
import org.signal.chat.backup.SignedPresentation;
|
||||
import org.signal.libsignal.protocol.InvalidKeyException;
|
||||
import org.signal.libsignal.protocol.ecc.ECPublicKey;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.backups.BackupAuthCredentialPresentation;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedBackupUser;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupManager;
|
||||
import org.whispersystems.textsecuregcm.backup.CopyParameters;
|
||||
import org.whispersystems.textsecuregcm.backup.MediaEncryptionParameters;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
public class BackupsAnonymousGrpcService extends ReactorBackupsAnonymousGrpc.BackupsAnonymousImplBase {
|
||||
|
||||
private final BackupManager backupManager;
|
||||
|
||||
public BackupsAnonymousGrpcService(final BackupManager backupManager) {
|
||||
this.backupManager = backupManager;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<GetCdnCredentialsResponse> getCdnCredentials(final GetCdnCredentialsRequest request) {
|
||||
return authenticateBackupUserMono(request.getSignedPresentation())
|
||||
.map(user -> backupManager.generateReadAuth(user, request.getCdn()))
|
||||
.map(credentials -> GetCdnCredentialsResponse.newBuilder().putAllHeaders(credentials).build());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<GetBackupInfoResponse> getBackupInfo(final GetBackupInfoRequest request) {
|
||||
return Mono.fromFuture(() ->
|
||||
authenticateBackupUser(request.getSignedPresentation()).thenCompose(backupManager::backupInfo))
|
||||
.map(info -> GetBackupInfoResponse.newBuilder()
|
||||
.setBackupName(info.messageBackupKey())
|
||||
.setCdn(info.cdn())
|
||||
.setBackupDir(info.backupSubdir())
|
||||
.setMediaDir(info.mediaSubdir())
|
||||
.setUsedSpace(info.mediaUsedSpace().orElse(0L))
|
||||
.build());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<RefreshResponse> refresh(final RefreshRequest request) {
|
||||
return Mono.fromFuture(() -> authenticateBackupUser(request.getSignedPresentation())
|
||||
.thenCompose(backupManager::ttlRefresh))
|
||||
.thenReturn(RefreshResponse.getDefaultInstance());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<SetPublicKeyResponse> setPublicKey(final SetPublicKeyRequest request) {
|
||||
final ECPublicKey publicKey = deserialize(ECPublicKey::new, request.getPublicKey().toByteArray());
|
||||
final BackupAuthCredentialPresentation presentation = deserialize(
|
||||
BackupAuthCredentialPresentation::new,
|
||||
request.getSignedPresentation().getPresentation().toByteArray());
|
||||
final byte[] signature = request.getSignedPresentation().getPresentationSignature().toByteArray();
|
||||
|
||||
return Mono.fromFuture(() -> backupManager.setPublicKey(presentation, signature, publicKey))
|
||||
.thenReturn(SetPublicKeyResponse.getDefaultInstance());
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public Mono<GetUploadFormResponse> getUploadForm(final GetUploadFormRequest request) {
|
||||
return authenticateBackupUserMono(request.getSignedPresentation())
|
||||
.flatMap(backupUser -> switch (request.getUploadTypeCase()) {
|
||||
case MESSAGES -> Mono.fromFuture(backupManager.createMessageBackupUploadDescriptor(backupUser));
|
||||
case MEDIA -> Mono.fromCompletionStage(backupManager.createTemporaryAttachmentUploadDescriptor(backupUser));
|
||||
case UPLOADTYPE_NOT_SET -> Mono.error(Status.INVALID_ARGUMENT
|
||||
.withDescription("Must set upload_type")
|
||||
.asRuntimeException());
|
||||
})
|
||||
.map(uploadDescriptor -> GetUploadFormResponse.newBuilder()
|
||||
.setCdn(uploadDescriptor.cdn())
|
||||
.setKey(uploadDescriptor.key())
|
||||
.setSignedUploadLocation(uploadDescriptor.signedUploadLocation())
|
||||
.putAllHeaders(uploadDescriptor.headers())
|
||||
.build());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Flux<CopyMediaResponse> copyMedia(final CopyMediaRequest request) {
|
||||
return authenticateBackupUserMono(request.getSignedPresentation())
|
||||
.flatMapMany(backupUser -> backupManager.copyToBackup(backupUser,
|
||||
request.getItemsList().stream().map(item -> new CopyParameters(
|
||||
item.getSourceAttachmentCdn(), item.getSourceKey(),
|
||||
// uint32 in proto, make sure it fits in a signed int
|
||||
fromUnsignedExact(item.getObjectLength()),
|
||||
new MediaEncryptionParameters(item.getEncryptionKey().toByteArray(), item.getHmacKey().toByteArray()),
|
||||
item.getMediaId().toByteArray())).toList()))
|
||||
.map(copyResult -> {
|
||||
CopyMediaResponse.Builder builder = CopyMediaResponse
|
||||
.newBuilder()
|
||||
.setMediaId(ByteString.copyFrom(copyResult.mediaId()));
|
||||
builder = switch (copyResult.outcome()) {
|
||||
case SUCCESS -> builder
|
||||
.setSuccess(CopyMediaResponse.CopySuccess.newBuilder().setCdn(copyResult.cdn()).build());
|
||||
case OUT_OF_QUOTA -> builder
|
||||
.setOutOfSpace(CopyMediaResponse.OutOfSpace.getDefaultInstance());
|
||||
case SOURCE_WRONG_LENGTH -> builder
|
||||
.setWrongSourceLength(CopyMediaResponse.WrongSourceLength.getDefaultInstance());
|
||||
case SOURCE_NOT_FOUND -> builder
|
||||
.setSourceNotFound(CopyMediaResponse.SourceNotFound.getDefaultInstance());
|
||||
};
|
||||
return builder.build();
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<ListMediaResponse> listMedia(final ListMediaRequest request) {
|
||||
return authenticateBackupUserMono(request.getSignedPresentation()).zipWhen(
|
||||
backupUser -> Mono.fromFuture(backupManager.list(
|
||||
backupUser,
|
||||
request.hasCursor() ? Optional.of(request.getCursor()) : Optional.empty(),
|
||||
request.getLimit()).toCompletableFuture()),
|
||||
|
||||
(backupUser, listResult) -> {
|
||||
final ListMediaResponse.Builder builder = ListMediaResponse.newBuilder();
|
||||
for (BackupManager.StorageDescriptorWithLength sd : listResult.media()) {
|
||||
builder.addPage(ListMediaResponse.ListEntry.newBuilder()
|
||||
.setMediaId(ByteString.copyFrom(sd.key()))
|
||||
.setCdn(sd.cdn())
|
||||
.setLength(sd.length())
|
||||
.build());
|
||||
}
|
||||
builder
|
||||
.setBackupDir(backupUser.backupDir())
|
||||
.setMediaDir(backupUser.mediaDir());
|
||||
listResult.cursor().ifPresent(builder::setCursor);
|
||||
return builder.build();
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<DeleteAllResponse> deleteAll(final DeleteAllRequest request) {
|
||||
return Mono.fromFuture(() -> authenticateBackupUser(request.getSignedPresentation())
|
||||
.thenCompose(backupManager::deleteEntireBackup))
|
||||
.thenReturn(DeleteAllResponse.getDefaultInstance());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Flux<DeleteMediaResponse> deleteMedia(final DeleteMediaRequest request) {
|
||||
return Mono
|
||||
.fromFuture(() -> authenticateBackupUser(request.getSignedPresentation()))
|
||||
.flatMapMany(backupUser -> backupManager.deleteMedia(backupUser, request
|
||||
.getItemsList()
|
||||
.stream()
|
||||
.map(item -> new BackupManager.StorageDescriptor(item.getCdn(), item.getMediaId().toByteArray()))
|
||||
.toList()))
|
||||
.map(storageDescriptor -> DeleteMediaResponse.newBuilder()
|
||||
.setMediaId(ByteString.copyFrom(storageDescriptor.key()))
|
||||
.setCdn(storageDescriptor.cdn()).build());
|
||||
}
|
||||
|
||||
private Mono<AuthenticatedBackupUser> authenticateBackupUserMono(final SignedPresentation signedPresentation) {
|
||||
return Mono.fromFuture(() -> authenticateBackupUser(signedPresentation));
|
||||
}
|
||||
|
||||
private CompletableFuture<AuthenticatedBackupUser> authenticateBackupUser(
|
||||
final SignedPresentation signedPresentation) {
|
||||
if (signedPresentation == null) {
|
||||
throw Status.UNAUTHENTICATED.asRuntimeException();
|
||||
}
|
||||
try {
|
||||
return backupManager.authenticateBackupUser(
|
||||
new BackupAuthCredentialPresentation(signedPresentation.getPresentation().toByteArray()),
|
||||
signedPresentation.getPresentationSignature().toByteArray());
|
||||
} catch (InvalidInputException e) {
|
||||
throw Status.UNAUTHENTICATED.withDescription("Could not deserialize presentation").asRuntimeException();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert an int from a proto uint32 to a signed positive integer, throwing if the value exceeds
|
||||
* {@link Integer#MAX_VALUE}. To convert to a long, see {@link Integer#toUnsignedLong(int)}
|
||||
*/
|
||||
private static int fromUnsignedExact(final int i) {
|
||||
if (i < 0) {
|
||||
throw Status.INVALID_ARGUMENT.withDescription("Invalid size").asRuntimeException();
|
||||
}
|
||||
return i;
|
||||
}
|
||||
|
||||
private interface Deserializer<T> {
|
||||
|
||||
T deserialize(byte[] bytes) throws InvalidInputException, InvalidKeyException;
|
||||
}
|
||||
|
||||
private static <T> T deserialize(Deserializer<T> deserializer, byte[] bytes) {
|
||||
try {
|
||||
return deserializer.deserialize(bytes);
|
||||
} catch (InvalidInputException | InvalidKeyException e) {
|
||||
throw Status.INVALID_ARGUMENT.withDescription("Invalid serialization").asRuntimeException();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import io.grpc.Status;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import org.signal.chat.backup.GetBackupAuthCredentialsRequest;
|
||||
import org.signal.chat.backup.GetBackupAuthCredentialsResponse;
|
||||
import org.signal.chat.backup.ReactorBackupsGrpc;
|
||||
import org.signal.chat.backup.RedeemReceiptRequest;
|
||||
import org.signal.chat.backup.RedeemReceiptResponse;
|
||||
import org.signal.chat.backup.SetBackupIdRequest;
|
||||
import org.signal.chat.backup.SetBackupIdResponse;
|
||||
import org.signal.chat.common.ZkCredential;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.backups.BackupAuthCredentialRequest;
|
||||
import org.signal.libsignal.zkgroup.backups.BackupCredentialType;
|
||||
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialPresentation;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupAuthManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
public class BackupsGrpcService extends ReactorBackupsGrpc.BackupsImplBase {
|
||||
|
||||
private final AccountsManager accountManager;
|
||||
private final BackupAuthManager backupAuthManager;
|
||||
|
||||
public BackupsGrpcService(final AccountsManager accountManager, final BackupAuthManager backupAuthManager) {
|
||||
this.accountManager = accountManager;
|
||||
this.backupAuthManager = backupAuthManager;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public Mono<SetBackupIdResponse> setBackupId(SetBackupIdRequest request) {
|
||||
|
||||
final BackupAuthCredentialRequest messagesCredentialRequest = deserialize(
|
||||
BackupAuthCredentialRequest::new,
|
||||
request.getMessagesBackupAuthCredentialRequest().toByteArray());
|
||||
|
||||
final BackupAuthCredentialRequest mediaCredentialRequest = deserialize(
|
||||
BackupAuthCredentialRequest::new,
|
||||
request.getMediaBackupAuthCredentialRequest().toByteArray());
|
||||
|
||||
return authenticatedAccount()
|
||||
.flatMap(account -> Mono.fromFuture(
|
||||
backupAuthManager.commitBackupId(account, messagesCredentialRequest, mediaCredentialRequest)))
|
||||
.thenReturn(SetBackupIdResponse.getDefaultInstance());
|
||||
}
|
||||
|
||||
public Mono<RedeemReceiptResponse> redeemReceipt(RedeemReceiptRequest request) {
|
||||
final ReceiptCredentialPresentation receiptCredentialPresentation = deserialize(
|
||||
ReceiptCredentialPresentation::new,
|
||||
request.getPresentation().toByteArray());
|
||||
return authenticatedAccount()
|
||||
.flatMap(account -> Mono.fromFuture(backupAuthManager.redeemReceipt(account, receiptCredentialPresentation)))
|
||||
.thenReturn(RedeemReceiptResponse.getDefaultInstance());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<GetBackupAuthCredentialsResponse> getBackupAuthCredentials(GetBackupAuthCredentialsRequest request) {
|
||||
return authenticatedAccount().flatMap(account -> {
|
||||
final Mono<List<BackupAuthManager.Credential>> messageCredentials = Mono.fromCompletionStage(() ->
|
||||
backupAuthManager.getBackupAuthCredentials(
|
||||
account,
|
||||
BackupCredentialType.MESSAGES,
|
||||
Instant.ofEpochSecond(request.getRedemptionStart()),
|
||||
Instant.ofEpochSecond(request.getRedemptionStop())));
|
||||
final Mono<List<BackupAuthManager.Credential>> mediaCredentials = Mono.fromCompletionStage(() ->
|
||||
backupAuthManager.getBackupAuthCredentials(
|
||||
account,
|
||||
BackupCredentialType.MEDIA,
|
||||
Instant.ofEpochSecond(request.getRedemptionStart()),
|
||||
Instant.ofEpochSecond(request.getRedemptionStop())));
|
||||
|
||||
return messageCredentials.zipWith(mediaCredentials, (messageCreds, mediaCreds) ->
|
||||
GetBackupAuthCredentialsResponse.newBuilder()
|
||||
.putAllMessageCredentials(messageCreds.stream().collect(Collectors.toMap(
|
||||
c -> c.redemptionTime().getEpochSecond(),
|
||||
c -> ZkCredential.newBuilder()
|
||||
.setCredential(ByteString.copyFrom(c.credential().serialize()))
|
||||
.setRedemptionTime(c.redemptionTime().getEpochSecond())
|
||||
.build())))
|
||||
.putAllMediaCredentials(mediaCreds.stream().collect(Collectors.toMap(
|
||||
c -> c.redemptionTime().getEpochSecond(),
|
||||
c -> ZkCredential.newBuilder()
|
||||
.setCredential(ByteString.copyFrom(c.credential().serialize()))
|
||||
.setRedemptionTime(c.redemptionTime().getEpochSecond())
|
||||
.build())))
|
||||
.build());
|
||||
});
|
||||
}
|
||||
|
||||
private Mono<Account> authenticatedAccount() {
|
||||
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
|
||||
return Mono
|
||||
.fromFuture(() -> accountManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier()))
|
||||
.map(maybeAccount -> maybeAccount.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException));
|
||||
}
|
||||
|
||||
private interface Deserializer<T> {
|
||||
|
||||
T deserialize(byte[] bytes) throws InvalidInputException;
|
||||
}
|
||||
|
||||
private <T> T deserialize(Deserializer<T> deserializer, byte[] bytes) {
|
||||
try {
|
||||
return deserializer.deserialize(bytes);
|
||||
} catch (InvalidInputException e) {
|
||||
throw Status.INVALID_ARGUMENT.withDescription("Invalid serialization").asRuntimeException();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import org.signal.chat.calling.GetTurnCredentialsRequest;
|
||||
import org.signal.chat.calling.GetTurnCredentialsResponse;
|
||||
import org.signal.chat.calling.ReactorCallingGrpc;
|
||||
import org.whispersystems.textsecuregcm.auth.TurnTokenGenerator;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
public class CallingGrpcService extends ReactorCallingGrpc.CallingImplBase {
|
||||
|
||||
private final TurnTokenGenerator turnTokenGenerator;
|
||||
private final RateLimiters rateLimiters;
|
||||
|
||||
public CallingGrpcService(final TurnTokenGenerator turnTokenGenerator, final RateLimiters rateLimiters) {
|
||||
this.turnTokenGenerator = turnTokenGenerator;
|
||||
this.rateLimiters = rateLimiters;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<GetTurnCredentialsResponse> getTurnCredentials(final GetTurnCredentialsRequest request) {
|
||||
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
|
||||
|
||||
return rateLimiters.getTurnLimiter().validateReactive(authenticatedDevice.accountIdentifier())
|
||||
.then(Mono.fromSupplier(() -> turnTokenGenerator.generate(authenticatedDevice.accountIdentifier())))
|
||||
.map(turnToken -> GetTurnCredentialsResponse.newBuilder()
|
||||
.setUsername(turnToken.username())
|
||||
.setPassword(turnToken.password())
|
||||
.addAllUrls(turnToken.urls())
|
||||
.build());
|
||||
}
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package org.whispersystems.textsecuregcm.mappers;
|
||||
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import jakarta.ws.rs.ext.ExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.util.ObsoletePhoneNumberFormatException;
|
||||
|
||||
public class ObsoletePhoneNumberFormatExceptionMapper implements ExceptionMapper<ObsoletePhoneNumberFormatException> {
|
||||
|
||||
private static final String COUNTER_NAME = MetricsUtil.name(ObsoletePhoneNumberFormatExceptionMapper.class, "errors");
|
||||
|
||||
@Override
|
||||
public Response toResponse(final ObsoletePhoneNumberFormatException exception) {
|
||||
Metrics.counter(COUNTER_NAME, "regionCode", exception.getRegionCode()).increment();
|
||||
return Response.status(499).build();
|
||||
}
|
||||
}
|
||||
+3
-2
@@ -94,8 +94,9 @@ class BraintreeGraphqlClient {
|
||||
final CreatePayPalOneTimePaymentMutation.Data data = assertSuccessAndExtractDataFromApolloResponse(apolloResponse);
|
||||
if (data.createPayPalOneTimePayment == null) {
|
||||
logger.warn(
|
||||
"createPayPalOneTimePayment requestId={} did not have any errors but data was null. response={}",
|
||||
apolloResponse.extensions.getOrDefault("requestId", "<No-Request-Id>"), httpResponse.body());
|
||||
"createPayPalOneTimePayment requestId={} currency={} amount={} did not have any errors but data was null. response={}",
|
||||
apolloResponse.extensions.getOrDefault("requestId", "<No-Request-Id>"),
|
||||
currency, amount, httpResponse.body());
|
||||
throw new ServiceUnavailableException();
|
||||
}
|
||||
return data.createPayPalOneTimePayment;
|
||||
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package org.whispersystems.textsecuregcm.util;
|
||||
|
||||
public class ObsoletePhoneNumberFormatException extends Exception {
|
||||
|
||||
private final String regionCode;
|
||||
|
||||
public ObsoletePhoneNumberFormatException(final String regionCode) {
|
||||
super("The provided format is obsolete in %s".formatted(regionCode));
|
||||
this.regionCode = regionCode;
|
||||
}
|
||||
|
||||
public String getRegionCode() {
|
||||
return regionCode;
|
||||
}
|
||||
}
|
||||
@@ -27,7 +27,6 @@ import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.Function;
|
||||
import java.util.random.RandomGenerator;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
public class Util {
|
||||
@@ -125,7 +124,7 @@ public class Util {
|
||||
try {
|
||||
final PhoneNumber phoneNumber = PHONE_NUMBER_UTIL.parse(number, null);
|
||||
|
||||
// Benin is changing phone number formats from +229 XXXXXXXX to +229 01XXXXXXXX starting on November 30, 2024
|
||||
// Benin changed phone number formats from +229 XXXXXXXX to +229 01XXXXXXXX on November 30, 2024
|
||||
if ("BJ".equals(PHONE_NUMBER_UTIL.getRegionCodeForNumber(phoneNumber))) {
|
||||
final String nationalSignificantNumber = PHONE_NUMBER_UTIL.getNationalSignificantNumber(phoneNumber);
|
||||
final String alternateE164;
|
||||
@@ -176,7 +175,7 @@ public class Util {
|
||||
throw new IllegalArgumentException("Numbers from different countries cannot be equivalent alternate forms");
|
||||
}
|
||||
if (regions.contains("BJ")) {
|
||||
// Benin is changing phone number formats from +229 XXXXXXXX to +229 01XXXXXXXX starting on November 30, 2024
|
||||
// Benin changed phone number formats from +229 XXXXXXXX to +229 01XXXXXXXX on November 30, 2024
|
||||
// We prefer the longest form for long-term stability
|
||||
return e164s.stream().sorted(Comparator.comparingInt(String::length).reversed()).findFirst();
|
||||
}
|
||||
@@ -217,7 +216,7 @@ public class Util {
|
||||
}
|
||||
|
||||
/**
|
||||
* Benin is changing phone number formats from +229 XXXXXXXX to +229 01XXXXXXXX starting on November 30, 2024.
|
||||
* Benin changed phone number formats from +229 XXXXXXXX to +229 01XXXXXXXX on November 30, 2024
|
||||
*
|
||||
* @param phoneNumber the phone number to check.
|
||||
* @return whether the provided phone number is an old-format Benin phone number
|
||||
@@ -235,11 +234,9 @@ public class Util {
|
||||
* @return the canonical phone number if applicable, otherwise the original phone number.
|
||||
*/
|
||||
public static Phonenumber.PhoneNumber canonicalizePhoneNumber(final Phonenumber.PhoneNumber phoneNumber)
|
||||
throws NumberParseException {
|
||||
throws NumberParseException, ObsoletePhoneNumberFormatException {
|
||||
if (isOldFormatBeninPhoneNumber(phoneNumber)) {
|
||||
// Benin changed phone number formats from +229 XXXXXXXX to +229 01XXXXXXXX starting on November 30, 2024.
|
||||
final String newFormatNumber = "+22901" + PHONE_NUMBER_UTIL.getNationalSignificantNumber(phoneNumber);
|
||||
return PhoneNumberUtil.getInstance().parse(newFormatNumber, null);
|
||||
throw new ObsoletePhoneNumberFormatException("bj");
|
||||
}
|
||||
return phoneNumber;
|
||||
}
|
||||
|
||||
+2
-28
@@ -8,9 +8,6 @@ package org.whispersystems.textsecuregcm.websocket;
|
||||
import static org.whispersystems.textsecuregcm.util.HeaderUtils.basicCredentialsFromAuthHeader;
|
||||
|
||||
import com.google.common.net.HttpHeaders;
|
||||
import io.dropwizard.auth.basic.BasicCredentials;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import javax.annotation.Nullable;
|
||||
import org.eclipse.jetty.websocket.api.UpgradeRequest;
|
||||
import org.whispersystems.textsecuregcm.auth.AccountAuthenticator;
|
||||
@@ -26,7 +23,6 @@ public class WebSocketAccountAuthenticator implements WebSocketAuthenticator<Aut
|
||||
private static final ReusableAuth<AuthenticatedDevice> CREDENTIALS_NOT_PRESENTED = ReusableAuth.anonymous();
|
||||
|
||||
private static final ReusableAuth<AuthenticatedDevice> INVALID_CREDENTIALS_PRESENTED = ReusableAuth.invalid();
|
||||
|
||||
private final AccountAuthenticator accountAuthenticator;
|
||||
private final PrincipalSupplier<AuthenticatedDevice> principalSupplier;
|
||||
|
||||
@@ -40,13 +36,7 @@ public class WebSocketAccountAuthenticator implements WebSocketAuthenticator<Aut
|
||||
public ReusableAuth<AuthenticatedDevice> authenticate(final UpgradeRequest request)
|
||||
throws AuthenticationException {
|
||||
try {
|
||||
// If the `Authorization` header was set for the request it takes priority, and we use the result of the
|
||||
// header-based auth ignoring the result of the query-based auth.
|
||||
final String authHeader = request.getHeader(HttpHeaders.AUTHORIZATION);
|
||||
if (authHeader != null) {
|
||||
return authenticatedAccountFromHeaderAuth(authHeader);
|
||||
}
|
||||
return authenticatedAccountFromQueryParams(request);
|
||||
return authenticatedAccountFromHeaderAuth(request.getHeader(HttpHeaders.AUTHORIZATION));
|
||||
} catch (final Exception e) {
|
||||
// this will be handled and logged upstream
|
||||
// the most likely exception is a transient error connecting to account storage
|
||||
@@ -54,23 +44,7 @@ public class WebSocketAccountAuthenticator implements WebSocketAuthenticator<Aut
|
||||
}
|
||||
}
|
||||
|
||||
private ReusableAuth<AuthenticatedDevice> authenticatedAccountFromQueryParams(final UpgradeRequest request) {
|
||||
final Map<String, List<String>> parameters = request.getParameterMap();
|
||||
final List<String> usernames = parameters.get("login");
|
||||
final List<String> passwords = parameters.get("password");
|
||||
if (usernames == null || usernames.size() == 0 ||
|
||||
passwords == null || passwords.size() == 0) {
|
||||
return CREDENTIALS_NOT_PRESENTED;
|
||||
}
|
||||
final BasicCredentials credentials = new BasicCredentials(usernames.get(0).replace(" ", "+"),
|
||||
passwords.get(0).replace(" ", "+"));
|
||||
return accountAuthenticator.authenticate(credentials)
|
||||
.map(authenticatedAccount -> ReusableAuth.authenticated(authenticatedAccount, this.principalSupplier))
|
||||
.orElse(INVALID_CREDENTIALS_PRESENTED);
|
||||
}
|
||||
|
||||
private ReusableAuth<AuthenticatedDevice> authenticatedAccountFromHeaderAuth(@Nullable final String authHeader)
|
||||
throws AuthenticationException {
|
||||
private ReusableAuth<AuthenticatedDevice> authenticatedAccountFromHeaderAuth(@Nullable final String authHeader) {
|
||||
if (authHeader == null) {
|
||||
return CREDENTIALS_NOT_PRESENTED;
|
||||
}
|
||||
|
||||
@@ -295,19 +295,19 @@ message MonitorRequest {
|
||||
|
||||
message AciMonitorRequest {
|
||||
bytes aci = 1;
|
||||
repeated uint64 entries = 2;
|
||||
uint64 entry_position = 2;
|
||||
bytes commitment_index = 3;
|
||||
}
|
||||
|
||||
message UsernameHashMonitorRequest {
|
||||
bytes username_hash = 1;
|
||||
repeated uint64 entries = 2;
|
||||
uint64 entry_position = 2;
|
||||
bytes commitment_index = 3;
|
||||
}
|
||||
|
||||
message E164MonitorRequest {
|
||||
string e164 = 1;
|
||||
repeated uint64 entries = 2;
|
||||
uint64 entry_position = 2;
|
||||
bytes commitment_index = 3;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,544 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
syntax = "proto3";
|
||||
|
||||
option java_multiple_files = true;
|
||||
|
||||
package org.signal.chat.backup;
|
||||
|
||||
import "google/protobuf/empty.proto";
|
||||
import "org/signal/chat/common.proto";
|
||||
import "org/signal/chat/require.proto";
|
||||
|
||||
/**
|
||||
* Service for backup operations that require account authentication.
|
||||
*
|
||||
* Most actual backup operations operate on the backup-id and cannot be linked
|
||||
* to the caller's account, but setting up anonymous credentials and changing
|
||||
* backup tier requires account authentication.
|
||||
*
|
||||
* All rpcs on this service may return these errors. rpc specific errors
|
||||
* documented on the individual rpc.
|
||||
*
|
||||
* errors:
|
||||
* UNAUTHENTICATED Authentication failed or the account does not exist
|
||||
* INVALID_ARGUMENT The request did not meet a documented requirement
|
||||
* RESOURCE_EXHAUSTED Rate limit exceeded. A retry-after header containing an
|
||||
* ISO8601 duration string will be present in the response
|
||||
* trailers.
|
||||
*/
|
||||
service Backups {
|
||||
option (require.auth) = AUTH_ONLY_AUTHENTICATED;
|
||||
|
||||
/**
|
||||
* Set a (blinded) backup-id for the account.
|
||||
*
|
||||
* Each account may have a single active backup-id that can be used
|
||||
* to store and retrieve backups. Once the backup-id is set,
|
||||
* BackupAuthCredentials can be generated using GetBackupAuthCredentials.
|
||||
*
|
||||
* The blinded backup-id and the key-pair used to blind it must be derived
|
||||
* from a recoverable secret.
|
||||
*
|
||||
* errors:
|
||||
* PERMISSION_DENIED: This account is not currently eligible for backups
|
||||
*/
|
||||
rpc SetBackupId(SetBackupIdRequest) returns (SetBackupIdResponse) {}
|
||||
|
||||
/**
|
||||
* Redeem a receipt acquired from /v1/subscription/{subscriberId}/receipt_credentials
|
||||
* to mark the account as eligible for the paid backup tier.
|
||||
*
|
||||
* After successful redemption, subsequent requests to
|
||||
* GetBackupAuthCredentials will return credentials with the level on the
|
||||
* provided receipt until the expiration time on the receipt.
|
||||
*/
|
||||
rpc RedeemReceipt(RedeemReceiptRequest) returns (RedeemReceiptResponse) {}
|
||||
|
||||
/**
|
||||
* After setting a blinded backup-id with PUT /v1/archives/, this fetches
|
||||
* credentials that can be used to perform operations against that backup-id.
|
||||
* Clients may (and should) request up to 7 days of credentials at a time.
|
||||
*
|
||||
* The redemption_start and redemption_end seconds must be UTC day aligned, and
|
||||
* must not span more than 7 days.
|
||||
*
|
||||
* Each credential contains a receipt level which indicates the backup level
|
||||
* the credential is good for. If the account has paid backup access that
|
||||
* expires at some point in the provided redemption window, credentials with
|
||||
* redemption times after the expiration may be on a lower backup level.
|
||||
*
|
||||
* Clients must validate the receipt level on the credential matches a known
|
||||
* receipt level before using it.
|
||||
*
|
||||
* errors:
|
||||
* NOT_FOUND: Could not find an existing blinded backup id associated with the
|
||||
* account.
|
||||
*/
|
||||
rpc GetBackupAuthCredentials(GetBackupAuthCredentialsRequest) returns (GetBackupAuthCredentialsResponse) {}
|
||||
}
|
||||
|
||||
message SetBackupIdRequest {
|
||||
/**
|
||||
* A BackupAuthCredentialRequest containing a blinded encrypted backup-id,
|
||||
* encoded in standard padded base64. This backup-id should be used for
|
||||
* message backups only, and must have the message backup type set on the
|
||||
* credential.
|
||||
*/
|
||||
bytes messages_backup_auth_credential_request = 1;
|
||||
|
||||
/**
|
||||
* A BackupAuthCredentialRequest containing a blinded encrypted backup-id,
|
||||
* encoded in standard padded base64. This backup-id should be used for
|
||||
* media only, and must have the media type set on the credential.
|
||||
*/
|
||||
bytes media_backup_auth_credential_request = 2;
|
||||
}
|
||||
message SetBackupIdResponse {}
|
||||
|
||||
|
||||
message RedeemReceiptRequest {
|
||||
/**
|
||||
* Presentation for a previously acquired receipt, serialized with libsignal
|
||||
*/
|
||||
bytes presentation = 1;
|
||||
}
|
||||
message RedeemReceiptResponse {}
|
||||
|
||||
message GetBackupAuthCredentialsRequest {
|
||||
/**
|
||||
* The redemption time for the first credential. This must be a day-aligned
|
||||
* seconds since epoch in UTC.
|
||||
*/
|
||||
int64 redemption_start = 1 [(require.range).min = 1];
|
||||
|
||||
/**
|
||||
* The redemption time for the last credential. This must be a day-aligned
|
||||
* seconds since epoch in UTC. The span between redemptionStart and
|
||||
* redemptionEnd must not exceed 7 days.
|
||||
*/
|
||||
int64 redemption_stop = 2 [(require.range).min = 1];
|
||||
}
|
||||
|
||||
message GetBackupAuthCredentialsResponse {
|
||||
/**
|
||||
* The requested message backup ZkCredentials indexed by the start of their
|
||||
* validity period. The smallest key should be for the requested
|
||||
* redemption_start, the largest for the requested the requested
|
||||
* redemption_end.
|
||||
*/
|
||||
map<int64, common.ZkCredential> message_credentials = 1;
|
||||
|
||||
/**
|
||||
* The requested media backup ZkCredentials indexed by the start of their
|
||||
* validity period. The smallest key should be for the requested
|
||||
* redemption_start, the largest for the requested the requested
|
||||
* redemption_end.
|
||||
*/
|
||||
map<int64, common.ZkCredential> media_credentials = 2;
|
||||
}
|
||||
|
||||
/**
|
||||
* Service for backup operations with anonymous credentials
|
||||
*
|
||||
* This service never requires account authentication. It instead requires a
|
||||
* backup-id authenticated with an anonymous credential that cannot be linked
|
||||
* to the account.
|
||||
*
|
||||
* To register an anonymous credential:
|
||||
* 1. Set a backup-id on the authenticated channel via Backups::SetBackupId
|
||||
* 2. Retrieve BackupAuthCredentials via Backups::GetBackupAuthCredentials
|
||||
* 3. Generate a key pair and set the public key via
|
||||
* BackupsAnonymous::SetPublicKey
|
||||
*
|
||||
* Unless otherwise noted, requests for this service require a
|
||||
* SignedPresentation, which includes:
|
||||
* - a presentation generated from a BackupAuthCredential issued by
|
||||
* GetBackupAuthCredentials
|
||||
* - a signature of that presentation using the private key of a key pair
|
||||
* previously set with SetPublicKey.
|
||||
*
|
||||
* All RPCs on this service may return these errors. RPC specific errors
|
||||
* documented on the individual RPC.
|
||||
*
|
||||
* errors:
|
||||
* UNAUTHENTICATED Either the presentation was missing, the credential was
|
||||
* expired, presentation verification failed, the signature
|
||||
* was incorrect, there was no committed public key for the
|
||||
* corresponding backup id, or the request was made on a
|
||||
* non-anonymous channel.
|
||||
* PERMISSION_DENIED The credential does not have permission to perform the
|
||||
* requested action.
|
||||
* RESOURCE_EXHAUSTED Rate limit exceeded. A retry-after header containing an
|
||||
* ISO8601 duration string will be present in the response
|
||||
* trailers.
|
||||
* INVALID_ARGUMENT The request did not meet a documented requirement
|
||||
*/
|
||||
service BackupsAnonymous {
|
||||
option (require.auth) = AUTH_ONLY_ANONYMOUS;
|
||||
|
||||
/**
|
||||
* Retrieve credentials used to read objects stored on the backup cdn
|
||||
*/
|
||||
rpc GetCdnCredentials(GetCdnCredentialsRequest) returns (GetCdnCredentialsResponse) {}
|
||||
|
||||
/**
|
||||
* Retrieve information about the currently stored backup
|
||||
*/
|
||||
rpc GetBackupInfo(GetBackupInfoRequest) returns (GetBackupInfoResponse) {}
|
||||
|
||||
/**
|
||||
* Permanently set the public key of an ED25519 key-pair for the backup-id.
|
||||
* All requests (including this one!) must sign their BackupAuthCredential
|
||||
* presentations with the private key corresponding to the provided public key.
|
||||
*
|
||||
* Trying to set a public key when a different one is already set will return
|
||||
* an UNAUTHENTICATED error.
|
||||
*/
|
||||
rpc SetPublicKey(SetPublicKeyRequest) returns (SetPublicKeyResponse) {}
|
||||
|
||||
/**
|
||||
* Refresh the backup, indicating that the backup is still active. Clients
|
||||
* must periodically upload new backups or perform a refresh. If a backup has
|
||||
* not been active for 30 days, it may deleted
|
||||
*/
|
||||
rpc Refresh(RefreshRequest) returns (RefreshResponse) {}
|
||||
|
||||
/**
|
||||
* Retrieve an upload form that can be used to perform a resumable upload
|
||||
*/
|
||||
rpc GetUploadForm(GetUploadFormRequest) returns (GetUploadFormResponse) {}
|
||||
|
||||
/**
|
||||
* Copy and re-encrypt media from the attachments cdn into the backup cdn.
|
||||
* The original, already encrypted, attachments will be encrypted with the
|
||||
* provided key material before being copied.
|
||||
*
|
||||
* The copy operation is not atomic and responses will be returned as copy
|
||||
* operations complete with detailed information about the outcome. If an
|
||||
* error is encountered, not all requests may be reflected in the responses.
|
||||
*
|
||||
* On retries, a particular destination media id must not be reused with a
|
||||
* different source media id or different encryption parameters.
|
||||
*/
|
||||
rpc CopyMedia(CopyMediaRequest) returns (stream CopyMediaResponse) {}
|
||||
|
||||
/**
|
||||
* Retrieve a page of media objects stored for this backup-id. A client may
|
||||
* have previously stored media objects that are no longer referenced in their
|
||||
* current backup. To reclaim storage space used by these orphaned objects,
|
||||
* perform a list operation and remove any unreferenced media objects
|
||||
* via DeleteMedia.
|
||||
*/
|
||||
rpc ListMedia(ListMediaRequest) returns (ListMediaResponse) {}
|
||||
|
||||
/**
|
||||
* Delete media objects stored with this backup-id. Streams the locations of
|
||||
* media items back when the item has successfully been removed.
|
||||
*/
|
||||
rpc DeleteMedia(DeleteMediaRequest) returns (stream DeleteMediaResponse) {}
|
||||
|
||||
/**
|
||||
* Delete all backup metadata, objects, and stored public key. To use
|
||||
* backups again, a public key must be resupplied.
|
||||
*/
|
||||
rpc DeleteAll(DeleteAllRequest) returns (DeleteAllResponse) {}
|
||||
}
|
||||
|
||||
message SignedPresentation {
|
||||
/**
|
||||
* Presentation of a BackupAuthCredential previously retrieved from
|
||||
* GetBackupAuthCredentials on the authenticated channel
|
||||
*/
|
||||
bytes presentation = 1;
|
||||
|
||||
/**
|
||||
* The presentation signed with the private key corresponding to the public
|
||||
* key set with SetPublicKey
|
||||
*/
|
||||
bytes presentation_signature = 2;
|
||||
}
|
||||
|
||||
message SetPublicKeyRequest {
|
||||
SignedPresentation signed_presentation = 1;
|
||||
|
||||
/**
|
||||
* The public key, serialized in libsignal's elliptic-curve public key format.
|
||||
*/
|
||||
bytes public_key = 2;
|
||||
}
|
||||
message SetPublicKeyResponse {}
|
||||
|
||||
message GetCdnCredentialsRequest {
|
||||
SignedPresentation signed_presentation = 1;
|
||||
int32 cdn = 2;
|
||||
}
|
||||
message GetCdnCredentialsResponse {
|
||||
/**
|
||||
* Headers to include with requests to the read from the backup CDN. Includes
|
||||
* time limited read-only credentials.
|
||||
*/
|
||||
map<string, string> headers = 1;
|
||||
}
|
||||
|
||||
message GetBackupInfoRequest {
|
||||
SignedPresentation signed_presentation = 1;
|
||||
}
|
||||
message GetBackupInfoResponse {
|
||||
/**
|
||||
* The base directory of your backup data on the cdn. The message backup can
|
||||
* be found in the returned cdn at /backup_dir/backup_name and stored media can
|
||||
* be found at /backup_dir/media_dir/media_id
|
||||
*/
|
||||
string backup_dir = 1;
|
||||
|
||||
/**
|
||||
* The prefix path component for media objects on a cdn. Stored media for a
|
||||
* media_id can be found at /backup_dir/media_dir/media_id, where the media_id
|
||||
* is encoded in unpadded url-safe base64.
|
||||
*/
|
||||
string media_dir = 2;
|
||||
|
||||
/**
|
||||
* The CDN type where the message backup is stored. Media may be stored
|
||||
* elsewhere. If absent, no message backup currently exists.
|
||||
*/
|
||||
optional int32 cdn = 3;
|
||||
|
||||
/**
|
||||
* The name of the most recent message backup on the cdn. The backup is at
|
||||
* /backup_dir/backup_name. If absent, no message backup currently exists.
|
||||
*/
|
||||
optional string backup_name = 4;
|
||||
|
||||
/**
|
||||
* The amount of space used to store media
|
||||
*/
|
||||
uint64 used_space = 5;
|
||||
}
|
||||
|
||||
message RefreshRequest {
|
||||
SignedPresentation signed_presentation = 1;
|
||||
}
|
||||
message RefreshResponse {
|
||||
SignedPresentation signed_presentation = 1;
|
||||
}
|
||||
|
||||
message GetUploadFormRequest {
|
||||
SignedPresentation signed_presentation = 1;
|
||||
|
||||
message MessagesUploadType {}
|
||||
message MediaUploadType {}
|
||||
oneof upload_type {
|
||||
/**
|
||||
* Retrieve an upload form that can be used to perform a resumable upload of
|
||||
* a message backup. The finished upload will be available on the backup cdn.
|
||||
*/
|
||||
MessagesUploadType messages = 2;
|
||||
|
||||
/**
|
||||
* Retrieve an upload form for a temporary location that can be used to
|
||||
* perform a resumable upload of an attachment. After uploading, the
|
||||
* attachment can be copied into the backup via CopyMedia.
|
||||
*
|
||||
* Behaves identically to the account authenticated version at /attachments.
|
||||
*/
|
||||
MediaUploadType media = 3;
|
||||
}
|
||||
}
|
||||
message GetUploadFormResponse {
|
||||
/**
|
||||
* Indicates the CDN type. 3 indicates resumable uploads using TUS
|
||||
*/
|
||||
int32 cdn = 1;
|
||||
|
||||
/**
|
||||
* The location within the specified cdn where the finished upload can be found
|
||||
*/
|
||||
string key = 2;
|
||||
|
||||
/**
|
||||
* A map of headers to include with all upload requests. Potentially contains
|
||||
* time-limited upload credentials
|
||||
*/
|
||||
map<string, string> headers = 3;
|
||||
|
||||
/**
|
||||
* The URL to upload to with the appropriate protocol
|
||||
*/
|
||||
string signed_upload_location = 4;
|
||||
}
|
||||
|
||||
message CopyMediaItem {
|
||||
/**
|
||||
* The attachment cdn of the object to copy into the backup
|
||||
*/
|
||||
int32 source_attachment_cdn = 1 [(require.present) = true];
|
||||
|
||||
/**
|
||||
* The attachment key of the object to copy into the backup
|
||||
*/
|
||||
string source_key = 2 [(require.nonEmpty) = true];
|
||||
|
||||
/**
|
||||
* The length of the source attachment before the encryption applied by the
|
||||
* copy operation
|
||||
*/
|
||||
uint32 object_length = 3;
|
||||
|
||||
/**
|
||||
* media_id to copy on to the backup CDN
|
||||
*/
|
||||
bytes media_id = 4 [(require.exactlySize) = 15];
|
||||
|
||||
/**
|
||||
* A 32-byte key for the MAC
|
||||
*/
|
||||
bytes hmac_key = 5 [(require.exactlySize) = 32];
|
||||
|
||||
/**
|
||||
* A 32-byte encryption key for AES
|
||||
*/
|
||||
bytes encryption_key = 6 [(require.exactlySize) = 32];
|
||||
}
|
||||
|
||||
message CopyMediaRequest {
|
||||
SignedPresentation signed_presentation = 1;
|
||||
|
||||
/**
|
||||
* Items to copy
|
||||
*/
|
||||
repeated CopyMediaItem items = 2;
|
||||
}
|
||||
|
||||
message CopyMediaResponse {
|
||||
message SourceNotFound {}
|
||||
message WrongSourceLength {}
|
||||
message OutOfSpace {}
|
||||
message CopySuccess {
|
||||
/**
|
||||
* The backup cdn where this media object is stored
|
||||
*/
|
||||
int32 cdn = 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* The 15-byte media_id from the corresponding CopyMediaItem in the request
|
||||
*/
|
||||
bytes media_id = 1;
|
||||
|
||||
oneof outcome {
|
||||
/**
|
||||
* The media item was successfully copied into the backup
|
||||
*/
|
||||
CopySuccess success = 2;
|
||||
|
||||
/**
|
||||
* The source object was not found
|
||||
*/
|
||||
SourceNotFound source_not_found = 3;
|
||||
|
||||
/**
|
||||
* The provided object length was incorrect
|
||||
*/
|
||||
WrongSourceLength wrong_source_length = 4;
|
||||
|
||||
/**
|
||||
* All media capacity has been consumed. Free some space to continue.
|
||||
*/
|
||||
OutOfSpace out_of_space = 5;
|
||||
}
|
||||
}
|
||||
|
||||
message ListMediaRequest {
|
||||
SignedPresentation signed_presentation = 1;
|
||||
|
||||
/**
|
||||
* A cursor returned by a previous call to ListMedia, absent on the first call
|
||||
*/
|
||||
optional string cursor = 2;
|
||||
|
||||
/**
|
||||
* If provided, the maximum number of entries to return in a page
|
||||
*/
|
||||
uint32 limit = 3 [(require.range) = {min: 0, max: 10000}];
|
||||
}
|
||||
message ListMediaResponse {
|
||||
message ListEntry {
|
||||
/**
|
||||
* The backup cdn where this media object is stored
|
||||
*/
|
||||
int32 cdn = 1;
|
||||
/**
|
||||
* The media_id of the object
|
||||
*/
|
||||
bytes media_id = 2;
|
||||
/**
|
||||
* The length of the object in bytes
|
||||
*/
|
||||
uint64 length = 3;
|
||||
}
|
||||
|
||||
/**
|
||||
* A page of media objects stored for this backup ID
|
||||
*/
|
||||
repeated ListEntry page = 1;
|
||||
|
||||
/**
|
||||
* The base directory of the backup data on the cdn. The stored media can be
|
||||
* found at /backup_dir/media_dir/media_id, where the media_id is encoded with
|
||||
* unpadded url-safe base64.
|
||||
*/
|
||||
string backup_dir = 2;
|
||||
|
||||
/**
|
||||
* The prefix path component for the media objects. The stored media for
|
||||
* media_id can be found at /backup_dir/media_dir/media_id, where the media_id
|
||||
* is encoded with unpadded url-safe base64.
|
||||
*/
|
||||
string media_dir = 3;
|
||||
|
||||
/**
|
||||
* If set, the cursor value to pass to the next list request to continue
|
||||
* listing. If absent, all objects have been listed
|
||||
*/
|
||||
optional string cursor = 4;
|
||||
}
|
||||
|
||||
message DeleteAllRequest {
|
||||
SignedPresentation signed_presentation = 1;
|
||||
}
|
||||
message DeleteAllResponse {}
|
||||
|
||||
message DeleteMediaItem {
|
||||
/**
|
||||
* The backup cdn where this media object is stored
|
||||
*/
|
||||
int32 cdn = 1;
|
||||
|
||||
/**
|
||||
* The media_id of the object to delete
|
||||
*/
|
||||
bytes media_id = 2;
|
||||
}
|
||||
|
||||
message DeleteMediaRequest {
|
||||
SignedPresentation signed_presentation = 1;
|
||||
|
||||
repeated DeleteMediaItem items = 2;
|
||||
}
|
||||
|
||||
message DeleteMediaResponse {
|
||||
/**
|
||||
* The backup cdn where the media object was stored
|
||||
*/
|
||||
int32 cdn = 1;
|
||||
|
||||
/**
|
||||
* The media_id of the object that was successfully deleted
|
||||
*/
|
||||
bytes media_id = 3;
|
||||
}
|
||||
@@ -101,3 +101,15 @@ enum DeviceCapability {
|
||||
DEVICE_CAPABILITY_VERSIONED_EXPIRATION_TIMER = 4;
|
||||
DEVICE_CAPABILITY_STORAGE_SERVICE_RECORD_KEY_ROTATION = 5;
|
||||
}
|
||||
|
||||
message ZkCredential {
|
||||
/*
|
||||
* Day on which this credential can be redeemed, in UTC seconds since epoch
|
||||
*/
|
||||
int64 redemption_time = 1;
|
||||
|
||||
/*
|
||||
* The ZK credential, using libsignal's serialization
|
||||
*/
|
||||
bytes credential = 2;
|
||||
}
|
||||
+1
@@ -61,6 +61,7 @@ public class CloudflareTurnCredentialsManagerTest {
|
||||
List.of("turn:cf.example.com"),
|
||||
List.of("turn:%s", "turn:%s:80?transport=tcp", "turns:%s:443?transport=tcp"),
|
||||
TURN_HOSTNAME,
|
||||
2,
|
||||
new CircuitBreakerConfiguration(),
|
||||
httpExecutor,
|
||||
new RetryConfiguration(),
|
||||
|
||||
-137
@@ -1,137 +0,0 @@
|
||||
package org.whispersystems.textsecuregcm.auth;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
|
||||
public class TurnTokenGeneratorTest {
|
||||
@Test
|
||||
public void testAlwaysSelectFirst() throws JsonProcessingException {
|
||||
final String configString = """
|
||||
captcha:
|
||||
scoreFloor: 1.0
|
||||
turn:
|
||||
uriConfigs:
|
||||
- uris:
|
||||
- always1.org
|
||||
- always2.org
|
||||
- uris:
|
||||
- never.org
|
||||
weight: 0
|
||||
""";
|
||||
DynamicConfiguration config = DynamicConfigurationManager
|
||||
.parseConfiguration(configString, DynamicConfiguration.class)
|
||||
.orElseThrow();
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
DynamicConfigurationManager<DynamicConfiguration> mockDynamicConfigManager = mock(
|
||||
DynamicConfigurationManager.class);
|
||||
|
||||
when(mockDynamicConfigManager.getConfiguration()).thenReturn(config);
|
||||
|
||||
final TurnTokenGenerator turnTokenGenerator =
|
||||
new TurnTokenGenerator(mockDynamicConfigManager, "bloop".getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
final long COUNT = 1000;
|
||||
|
||||
final Map<String, Long> urlCounts = Stream
|
||||
.generate(() -> turnTokenGenerator.generate(UUID.randomUUID()))
|
||||
.limit(COUNT)
|
||||
.flatMap(token -> token.urls().stream())
|
||||
.collect(Collectors.groupingBy(i -> i, Collectors.counting()));
|
||||
|
||||
assertThat(urlCounts.get("always1.org")).isEqualTo(COUNT);
|
||||
assertThat(urlCounts.get("always2.org")).isEqualTo(COUNT);
|
||||
assertThat(urlCounts).doesNotContainKey("never.org");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testProbabilisticUrls() throws JsonProcessingException {
|
||||
final String configString = """
|
||||
captcha:
|
||||
scoreFloor: 1.0
|
||||
turn:
|
||||
uriConfigs:
|
||||
- uris:
|
||||
- always.org
|
||||
- sometimes1.org
|
||||
weight: 5
|
||||
- uris:
|
||||
- always.org
|
||||
- sometimes2.org
|
||||
weight: 5
|
||||
""";
|
||||
DynamicConfiguration config = DynamicConfigurationManager
|
||||
.parseConfiguration(configString, DynamicConfiguration.class)
|
||||
.orElseThrow();
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
DynamicConfigurationManager<DynamicConfiguration> mockDynamicConfigManager = mock(
|
||||
DynamicConfigurationManager.class);
|
||||
|
||||
when(mockDynamicConfigManager.getConfiguration()).thenReturn(config);
|
||||
|
||||
final TurnTokenGenerator turnTokenGenerator =
|
||||
new TurnTokenGenerator(mockDynamicConfigManager, "bloop".getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
final long COUNT = 1000;
|
||||
|
||||
final Map<String, Long> urlCounts = Stream
|
||||
.generate(() -> turnTokenGenerator.generate(UUID.randomUUID()))
|
||||
.limit(COUNT)
|
||||
.flatMap(token -> token.urls().stream())
|
||||
.collect(Collectors.groupingBy(i -> i, Collectors.counting()));
|
||||
|
||||
assertThat(urlCounts.get("always.org")).isEqualTo(COUNT);
|
||||
assertThat(urlCounts.get("sometimes1.org")).isGreaterThan(0);
|
||||
assertThat(urlCounts.get("sometimes2.org")).isGreaterThan(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testExplicitEnrollment() throws JsonProcessingException {
|
||||
final String configString = """
|
||||
captcha:
|
||||
scoreFloor: 1.0
|
||||
turn:
|
||||
secret: bloop
|
||||
uriConfigs:
|
||||
- uris:
|
||||
- enrolled.org
|
||||
weight: 0
|
||||
enrolledAcis:
|
||||
- 732506d7-d04f-43a4-b1d7-8a3a91ebe8a6
|
||||
- uris:
|
||||
- unenrolled.org
|
||||
weight: 1
|
||||
""";
|
||||
DynamicConfiguration config = DynamicConfigurationManager
|
||||
.parseConfiguration(configString, DynamicConfiguration.class)
|
||||
.orElseThrow();
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
DynamicConfigurationManager<DynamicConfiguration> mockDynamicConfigManager = mock(
|
||||
DynamicConfigurationManager.class);
|
||||
|
||||
when(mockDynamicConfigManager.getConfiguration()).thenReturn(config);
|
||||
|
||||
final TurnTokenGenerator turnTokenGenerator =
|
||||
new TurnTokenGenerator(mockDynamicConfigManager, "bloop".getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
TurnToken token = turnTokenGenerator.generate(UUID.fromString("732506d7-d04f-43a4-b1d7-8a3a91ebe8a6"));
|
||||
assertThat(token.urls().get(0)).isEqualTo("enrolled.org");
|
||||
token = turnTokenGenerator.generate(UUID.randomUUID());
|
||||
assertThat(token.urls().get(0)).isEqualTo("unenrolled.org");
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
-1
@@ -159,7 +159,6 @@ class AccountControllerTest {
|
||||
.addResource(new AccountController(
|
||||
accountsManager,
|
||||
rateLimiters,
|
||||
turnTokenGenerator,
|
||||
registrationRecoveryPasswordsManager,
|
||||
usernameZkProofVerifier
|
||||
))
|
||||
|
||||
+3
-8
@@ -34,12 +34,10 @@ import org.whispersystems.textsecuregcm.auth.TurnToken;
|
||||
import org.whispersystems.textsecuregcm.auth.TurnTokenGenerator;
|
||||
import org.whispersystems.textsecuregcm.calls.routing.TurnCallRouter;
|
||||
import org.whispersystems.textsecuregcm.calls.routing.TurnServerOptions;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
import org.whispersystems.textsecuregcm.util.TestRemoteAddressFilterProvider;
|
||||
@@ -52,12 +50,10 @@ class CallRoutingControllerTest {
|
||||
|
||||
private static final RateLimiters rateLimiters = mock(RateLimiters.class);
|
||||
private static final RateLimiter getCallEndpointLimiter = mock(RateLimiter.class);
|
||||
private static final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager = mock(
|
||||
DynamicConfigurationManager.class);
|
||||
private static final ExperimentEnrollmentManager experimentEnrollmentManager = mock(
|
||||
ExperimentEnrollmentManager.class);
|
||||
private static final TurnTokenGenerator turnTokenGenerator = new TurnTokenGenerator(dynamicConfigurationManager,
|
||||
"bloop".getBytes(StandardCharsets.UTF_8));
|
||||
private static final TurnTokenGenerator turnTokenGenerator =
|
||||
new TurnTokenGenerator("bloop".getBytes(StandardCharsets.UTF_8));
|
||||
private static final CloudflareTurnCredentialsManager cloudflareTurnCredentialsManager = mock(
|
||||
CloudflareTurnCredentialsManager.class);
|
||||
|
||||
@@ -81,8 +77,7 @@ class CallRoutingControllerTest {
|
||||
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
reset(experimentEnrollmentManager, dynamicConfigurationManager, rateLimiters, getCallEndpointLimiter,
|
||||
turnCallRouter);
|
||||
reset(experimentEnrollmentManager, rateLimiters, getCallEndpointLimiter, turnCallRouter);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+2
-6
@@ -63,12 +63,9 @@ class CallRoutingControllerV2Test {
|
||||
|
||||
private static final RateLimiters rateLimiters = mock(RateLimiters.class);
|
||||
private static final RateLimiter getCallEndpointLimiter = mock(RateLimiter.class);
|
||||
private static final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager = mock(
|
||||
DynamicConfigurationManager.class);
|
||||
private static final ExperimentEnrollmentManager experimentEnrollmentManager = mock(
|
||||
ExperimentEnrollmentManager.class);
|
||||
private static final TurnTokenGenerator turnTokenGenerator = new TurnTokenGenerator(dynamicConfigurationManager,
|
||||
"bloop".getBytes(StandardCharsets.UTF_8));
|
||||
private static final TurnTokenGenerator turnTokenGenerator = new TurnTokenGenerator("bloop".getBytes(StandardCharsets.UTF_8));
|
||||
private static final CloudflareTurnCredentialsManager cloudflareTurnCredentialsManager = mock(
|
||||
CloudflareTurnCredentialsManager.class);
|
||||
private static final TurnCallRouter turnCallRouter = mock(TurnCallRouter.class);
|
||||
@@ -91,8 +88,7 @@ class CallRoutingControllerV2Test {
|
||||
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
reset(experimentEnrollmentManager, dynamicConfigurationManager, rateLimiters, getCallEndpointLimiter,
|
||||
turnCallRouter);
|
||||
reset(experimentEnrollmentManager, rateLimiters, getCallEndpointLimiter, turnCallRouter);
|
||||
}
|
||||
|
||||
void initializeMocksWith(Optional<TurnServerOptions> signalTurn, Optional<TurnToken> cloudflare) {
|
||||
|
||||
+4
-4
@@ -37,11 +37,11 @@ class DirectoryControllerV2Test {
|
||||
final UUID uuid = UUID.fromString("11111111-1111-1111-1111-111111111111");
|
||||
when(account.getUuid()).thenReturn(uuid);
|
||||
|
||||
final ExternalServiceCredentials credentials = (ExternalServiceCredentials) controller.getAuthToken(
|
||||
new AuthenticatedDevice(account, mock(Device.class))).getEntity();
|
||||
final ExternalServiceCredentials credentials = controller.getAuthToken(
|
||||
new AuthenticatedDevice(account, mock(Device.class)));
|
||||
|
||||
assertEquals(credentials.username(), "d369bc712e2e0dd36258");
|
||||
assertEquals(credentials.password(), "1633738643:4433b0fab41f25f79dd4");
|
||||
assertEquals("d369bc712e2e0dd36258", credentials.username());
|
||||
assertEquals("1633738643:4433b0fab41f25f79dd4", credentials.password());
|
||||
}
|
||||
|
||||
}
|
||||
+39
-53
@@ -305,7 +305,7 @@ public class KeyTransparencyControllerTest {
|
||||
try (Response response = request.post(Entity.json(
|
||||
createRequestJson(
|
||||
new KeyTransparencyMonitorRequest(
|
||||
new KeyTransparencyMonitorRequest.AciMonitor(ACI, List.of(3L), COMMITMENT_INDEX),
|
||||
new KeyTransparencyMonitorRequest.AciMonitor(ACI,3, COMMITMENT_INDEX),
|
||||
Optional.empty(), Optional.empty(), 3L, 4L))))) {
|
||||
assertEquals(200, response.getStatus());
|
||||
|
||||
@@ -327,7 +327,7 @@ public class KeyTransparencyControllerTest {
|
||||
try (Response response = request.post(
|
||||
Entity.json(createRequestJson(
|
||||
new KeyTransparencyMonitorRequest(
|
||||
new KeyTransparencyMonitorRequest.AciMonitor(ACI, List.of(3L), COMMITMENT_INDEX),
|
||||
new KeyTransparencyMonitorRequest.AciMonitor(ACI, 3, COMMITMENT_INDEX),
|
||||
Optional.empty(), Optional.empty(), 3L, 4L))))) {
|
||||
assertEquals(400, response.getStatus());
|
||||
verifyNoInteractions(keyTransparencyServiceClient);
|
||||
@@ -346,7 +346,7 @@ public class KeyTransparencyControllerTest {
|
||||
try (Response response = request.post(
|
||||
Entity.json(createRequestJson(
|
||||
new KeyTransparencyMonitorRequest(
|
||||
new KeyTransparencyMonitorRequest.AciMonitor(ACI, List.of(3L), COMMITMENT_INDEX),
|
||||
new KeyTransparencyMonitorRequest.AciMonitor(ACI, 3, COMMITMENT_INDEX),
|
||||
Optional.empty(), Optional.empty(), 3L, 4L))))) {
|
||||
assertEquals(httpStatus, response.getStatus());
|
||||
verify(keyTransparencyServiceClient, times(1)).monitor(any(), any(), any(), anyLong(), anyLong(), any());
|
||||
@@ -381,115 +381,101 @@ public class KeyTransparencyControllerTest {
|
||||
new KeyTransparencyMonitorRequest(null, Optional.empty(), Optional.empty(), 3L, 4L))),
|
||||
// aci monitor fields can't be null
|
||||
Arguments.of(createRequestJson(
|
||||
new KeyTransparencyMonitorRequest(new KeyTransparencyMonitorRequest.AciMonitor(null, null, null),
|
||||
new KeyTransparencyMonitorRequest(new KeyTransparencyMonitorRequest.AciMonitor(null, 4, null),
|
||||
Optional.empty(), Optional.empty(), 3L, 4L))),
|
||||
Arguments.of(createRequestJson(
|
||||
new KeyTransparencyMonitorRequest(
|
||||
new KeyTransparencyMonitorRequest.AciMonitor(null, List.of(4L), COMMITMENT_INDEX),
|
||||
new KeyTransparencyMonitorRequest.AciMonitor(null, 4, COMMITMENT_INDEX),
|
||||
Optional.empty(), Optional.empty(), 3L, 4L))),
|
||||
Arguments.of(createRequestJson(
|
||||
new KeyTransparencyMonitorRequest(new KeyTransparencyMonitorRequest.AciMonitor(ACI, null, COMMITMENT_INDEX),
|
||||
new KeyTransparencyMonitorRequest(new KeyTransparencyMonitorRequest.AciMonitor(ACI, 4, null),
|
||||
Optional.empty(), Optional.empty(), 3L, 4L))),
|
||||
Arguments.of(createRequestJson(
|
||||
new KeyTransparencyMonitorRequest(new KeyTransparencyMonitorRequest.AciMonitor(ACI, List.of(4L), null),
|
||||
Optional.empty(), Optional.empty(), 3L, 4L))),
|
||||
// aciPositions list can't be empty
|
||||
// aciPosition must be positive
|
||||
Arguments.of(createRequestJson(new KeyTransparencyMonitorRequest(
|
||||
new KeyTransparencyMonitorRequest.AciMonitor(ACI, Collections.emptyList(), COMMITMENT_INDEX),
|
||||
new KeyTransparencyMonitorRequest.AciMonitor(ACI, 0, COMMITMENT_INDEX),
|
||||
Optional.empty(), Optional.empty(), 3L, 4L))),
|
||||
// aci commitment index must be the correct size
|
||||
Arguments.of(createRequestJson(new KeyTransparencyMonitorRequest(
|
||||
new KeyTransparencyMonitorRequest.AciMonitor(ACI, List.of(4L), new byte[0]),
|
||||
new KeyTransparencyMonitorRequest.AciMonitor(ACI, 4, new byte[0]),
|
||||
Optional.empty(), Optional.empty(), 3L, 4L))),
|
||||
Arguments.of(createRequestJson(new KeyTransparencyMonitorRequest(
|
||||
new KeyTransparencyMonitorRequest.AciMonitor(ACI, Collections.emptyList(), new byte[33]),
|
||||
new KeyTransparencyMonitorRequest.AciMonitor(ACI, 0, new byte[33]),
|
||||
Optional.empty(), Optional.empty(), 3L, 4L))),
|
||||
// username monitor fields cannot be null
|
||||
Arguments.of(createRequestJson(
|
||||
new KeyTransparencyMonitorRequest(
|
||||
new KeyTransparencyMonitorRequest.AciMonitor(ACI, List.of(4L), COMMITMENT_INDEX), Optional.empty(),
|
||||
Optional.of(new KeyTransparencyMonitorRequest.UsernameHashMonitor(null, null, null)),
|
||||
new KeyTransparencyMonitorRequest.AciMonitor(ACI, 4, COMMITMENT_INDEX), Optional.empty(),
|
||||
Optional.of(new KeyTransparencyMonitorRequest.UsernameHashMonitor(null, 5, null)),
|
||||
3L, 4L))),
|
||||
Arguments.of(createRequestJson(
|
||||
new KeyTransparencyMonitorRequest(
|
||||
new KeyTransparencyMonitorRequest.AciMonitor(ACI, List.of(4L), COMMITMENT_INDEX), Optional.empty(),
|
||||
Optional.of(new KeyTransparencyMonitorRequest.UsernameHashMonitor(null, List.of(5L), COMMITMENT_INDEX)),
|
||||
new KeyTransparencyMonitorRequest.AciMonitor(ACI, 4, COMMITMENT_INDEX), Optional.empty(),
|
||||
Optional.of(new KeyTransparencyMonitorRequest.UsernameHashMonitor(null, 5, COMMITMENT_INDEX)),
|
||||
3L, 4L))),
|
||||
Arguments.of(createRequestJson(
|
||||
new KeyTransparencyMonitorRequest(
|
||||
new KeyTransparencyMonitorRequest.AciMonitor(ACI, List.of(4L), COMMITMENT_INDEX), Optional.empty(),
|
||||
Optional.of(
|
||||
new KeyTransparencyMonitorRequest.UsernameHashMonitor(USERNAME_HASH, null, COMMITMENT_INDEX)),
|
||||
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(
|
||||
new KeyTransparencyMonitorRequest(
|
||||
new KeyTransparencyMonitorRequest.AciMonitor(ACI, List.of(4L), COMMITMENT_INDEX), Optional.empty(),
|
||||
Optional.of(new KeyTransparencyMonitorRequest.UsernameHashMonitor(USERNAME_HASH, List.of(5L), null)),
|
||||
3L, 4L))),
|
||||
// usernameHashPositions list cannot be empty
|
||||
Arguments.of(createRequestJson(
|
||||
new KeyTransparencyMonitorRequest(
|
||||
new KeyTransparencyMonitorRequest.AciMonitor(ACI, List.of(4L), COMMITMENT_INDEX),
|
||||
new KeyTransparencyMonitorRequest.AciMonitor(ACI, 4, COMMITMENT_INDEX),
|
||||
Optional.empty(),
|
||||
Optional.of(new KeyTransparencyMonitorRequest.UsernameHashMonitor(USERNAME_HASH,
|
||||
Collections.emptyList(), COMMITMENT_INDEX)), 3L, 4L))),
|
||||
0, COMMITMENT_INDEX)), 3L, 4L))),
|
||||
// username commitment index must be the correct size
|
||||
Arguments.of(createRequestJson(
|
||||
new KeyTransparencyMonitorRequest(
|
||||
new KeyTransparencyMonitorRequest.AciMonitor(ACI, List.of(4L), new byte[0]),
|
||||
new KeyTransparencyMonitorRequest.AciMonitor(ACI, 4, new byte[0]),
|
||||
Optional.empty(),
|
||||
Optional.of(new KeyTransparencyMonitorRequest.UsernameHashMonitor(USERNAME_HASH,
|
||||
List.of(5L), new byte[0])), 3L, 4L))),
|
||||
5, new byte[0])), 3L, 4L))),
|
||||
Arguments.of(createRequestJson(
|
||||
new KeyTransparencyMonitorRequest(new KeyTransparencyMonitorRequest.AciMonitor(ACI, List.of(4L), null),
|
||||
new KeyTransparencyMonitorRequest(new KeyTransparencyMonitorRequest.AciMonitor(ACI, 4, null),
|
||||
Optional.empty(),
|
||||
Optional.of(new KeyTransparencyMonitorRequest.UsernameHashMonitor(USERNAME_HASH,
|
||||
List.of(5L), new byte[33])), 3L, 4L))),
|
||||
5, new byte[33])), 3L, 4L))),
|
||||
// e164 fields cannot be null
|
||||
Arguments.of(
|
||||
createRequestJson(new KeyTransparencyMonitorRequest(
|
||||
new KeyTransparencyMonitorRequest.AciMonitor(ACI, List.of(4L), COMMITMENT_INDEX),
|
||||
Optional.of(new KeyTransparencyMonitorRequest.E164Monitor(null, null, null)),
|
||||
new KeyTransparencyMonitorRequest.AciMonitor(ACI, 4, COMMITMENT_INDEX),
|
||||
Optional.of(new KeyTransparencyMonitorRequest.E164Monitor(null, 5, null)),
|
||||
Optional.empty(), 3L, 4L))),
|
||||
Arguments.of(
|
||||
createRequestJson(new KeyTransparencyMonitorRequest(
|
||||
new KeyTransparencyMonitorRequest.AciMonitor(ACI, List.of(4L), COMMITMENT_INDEX),
|
||||
Optional.of(new KeyTransparencyMonitorRequest.E164Monitor(null, List.of(5L), COMMITMENT_INDEX)),
|
||||
new KeyTransparencyMonitorRequest.AciMonitor(ACI, 4, COMMITMENT_INDEX),
|
||||
Optional.of(new KeyTransparencyMonitorRequest.E164Monitor(null, 5, COMMITMENT_INDEX)),
|
||||
Optional.empty(), 3L, 4L))),
|
||||
Arguments.of(
|
||||
createRequestJson(new KeyTransparencyMonitorRequest(
|
||||
new KeyTransparencyMonitorRequest.AciMonitor(ACI, List.of(4L), COMMITMENT_INDEX),
|
||||
Optional.of(new KeyTransparencyMonitorRequest.E164Monitor(NUMBER, null, COMMITMENT_INDEX)),
|
||||
new KeyTransparencyMonitorRequest.AciMonitor(ACI, 4, COMMITMENT_INDEX),
|
||||
Optional.of(new KeyTransparencyMonitorRequest.E164Monitor(NUMBER, 5, null)),
|
||||
Optional.empty(), 3L, 4L))),
|
||||
Arguments.of(
|
||||
createRequestJson(new KeyTransparencyMonitorRequest(
|
||||
new KeyTransparencyMonitorRequest.AciMonitor(ACI, List.of(4L), COMMITMENT_INDEX),
|
||||
Optional.of(new KeyTransparencyMonitorRequest.E164Monitor(NUMBER, List.of(5L), null)),
|
||||
Optional.empty(), 3L, 4L))),
|
||||
// e164Positions list cannot empty
|
||||
// e164Position must be positive
|
||||
Arguments.of(createRequestJson(new KeyTransparencyMonitorRequest(
|
||||
new KeyTransparencyMonitorRequest.AciMonitor(ACI, List.of(4L), COMMITMENT_INDEX),
|
||||
new KeyTransparencyMonitorRequest.AciMonitor(ACI, 4, COMMITMENT_INDEX),
|
||||
Optional.of(
|
||||
new KeyTransparencyMonitorRequest.E164Monitor(NUMBER, Collections.emptyList(), COMMITMENT_INDEX)),
|
||||
new KeyTransparencyMonitorRequest.E164Monitor(NUMBER, 0, COMMITMENT_INDEX)),
|
||||
Optional.empty(), 3L, 4L))),
|
||||
// e164 commitment index must be the correct size
|
||||
Arguments.of(createRequestJson(new KeyTransparencyMonitorRequest(
|
||||
new KeyTransparencyMonitorRequest.AciMonitor(ACI, List.of(4L), COMMITMENT_INDEX),
|
||||
new KeyTransparencyMonitorRequest.AciMonitor(ACI, 4, COMMITMENT_INDEX),
|
||||
Optional.of(
|
||||
new KeyTransparencyMonitorRequest.E164Monitor(NUMBER, List.of(5L), new byte[0])),
|
||||
new KeyTransparencyMonitorRequest.E164Monitor(NUMBER, 5, new byte[0])),
|
||||
Optional.empty(), 3L, 4L))),
|
||||
Arguments.of(createRequestJson(new KeyTransparencyMonitorRequest(
|
||||
new KeyTransparencyMonitorRequest.AciMonitor(ACI, List.of(4L), COMMITMENT_INDEX),
|
||||
new KeyTransparencyMonitorRequest.AciMonitor(ACI, 4, COMMITMENT_INDEX),
|
||||
Optional.of(
|
||||
new KeyTransparencyMonitorRequest.E164Monitor(NUMBER, List.of(5L), new byte[33])),
|
||||
new KeyTransparencyMonitorRequest.E164Monitor(NUMBER, 5, new byte[33])),
|
||||
Optional.empty(), 3L, 4L))),
|
||||
// lastNonDistinguishedTreeHeadSize must be positive
|
||||
Arguments.of(createRequestJson(new KeyTransparencyMonitorRequest(
|
||||
new KeyTransparencyMonitorRequest.AciMonitor(ACI, List.of(4L), COMMITMENT_INDEX), Optional.empty(),
|
||||
new KeyTransparencyMonitorRequest.AciMonitor(ACI, 4, COMMITMENT_INDEX), Optional.empty(),
|
||||
Optional.empty(), 0L, 4L))),
|
||||
// lastDistinguishedTreeHeadSize must be positive
|
||||
Arguments.of(createRequestJson(new KeyTransparencyMonitorRequest(
|
||||
new KeyTransparencyMonitorRequest.AciMonitor(ACI, List.of(4L), COMMITMENT_INDEX), Optional.empty(),
|
||||
new KeyTransparencyMonitorRequest.AciMonitor(ACI, 4, COMMITMENT_INDEX), Optional.empty(),
|
||||
Optional.empty(), 3L, 0L)))
|
||||
);
|
||||
}
|
||||
@@ -503,7 +489,7 @@ public class KeyTransparencyControllerTest {
|
||||
.request();
|
||||
try (Response response = request.post(
|
||||
Entity.json(createRequestJson(
|
||||
new KeyTransparencyMonitorRequest(new KeyTransparencyMonitorRequest.AciMonitor(ACI, List.of(3L), null),
|
||||
new KeyTransparencyMonitorRequest(new KeyTransparencyMonitorRequest.AciMonitor(ACI, 3, null),
|
||||
Optional.empty(), Optional.empty(),
|
||||
3L, 4L))))) {
|
||||
assertEquals(429, response.getStatus());
|
||||
|
||||
+99
-2
@@ -485,6 +485,43 @@ class MessageControllerTest {
|
||||
Arguments.of(SINGLE_DEVICE_ACI_ID, SINGLE_DEVICE_ACI_ID, Duration.ofHours(1), true, true, 400));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({
|
||||
"-1, 422",
|
||||
"0, 200",
|
||||
"1, 200",
|
||||
"8640000000000000, 200",
|
||||
"8640000000000001, 422",
|
||||
|
||||
// This is something of a quirk; because this failure is happening at the parsing layer (we can't parse it as a
|
||||
// `long`) instead of the validation layer, we get a 400 instead of a 422
|
||||
"99999999999999999999999999999999999, 400"
|
||||
})
|
||||
void testSingleDeviceExtremeTimestamp(final String timestamp, final int expectedStatus) throws JsonProcessingException {
|
||||
final String jsonTemplate = """
|
||||
{
|
||||
"timestamp" : %s,
|
||||
"messages" : [{
|
||||
"type" : 1,
|
||||
"destinationDeviceId" : 1,
|
||||
"content" : "Zm9vYmFyego"
|
||||
}]
|
||||
}
|
||||
""";
|
||||
|
||||
final String json = String.format(jsonTemplate, timestamp);
|
||||
|
||||
try (final Response response =
|
||||
resources.getJerseyTest()
|
||||
.target(String.format("/v1/messages/%s", SINGLE_DEVICE_UUID))
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.put(Entity.json(json))) {
|
||||
|
||||
assertThat(response.getStatus(), is(equalTo(expectedStatus)));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSendBadAuth() throws Exception {
|
||||
try (final Response response =
|
||||
@@ -1058,7 +1095,7 @@ class MessageControllerTest {
|
||||
.request()
|
||||
.header(HeaderUtils.UNIDENTIFIED_ACCESS_KEY, Base64.getEncoder().encodeToString(UNIDENTIFIED_ACCESS_BYTES))
|
||||
.put(Entity.entity(new IncomingMessageList(
|
||||
List.of(new IncomingMessage(1, (byte) 1, 1, new String(contentBytes))), false, true,
|
||||
List.of(new IncomingMessage(1, (byte) 1, 1, Base64.getEncoder().encodeToString(contentBytes))), false, true,
|
||||
System.currentTimeMillis()),
|
||||
MediaType.APPLICATION_JSON_TYPE))) {
|
||||
|
||||
@@ -1166,7 +1203,7 @@ class MessageControllerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testManyRecipientMessage() throws Exception {
|
||||
void testManyRecipientMessage() {
|
||||
|
||||
when(messagesManager.insertSharedMultiRecipientMessagePayload(any(SealedSenderMultiRecipientMessage.class)))
|
||||
.thenReturn(new byte[]{1});
|
||||
@@ -1560,6 +1597,66 @@ class MessageControllerTest {
|
||||
checkBadMultiRecipientResponse(response, 400);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({
|
||||
"-1, 400",
|
||||
"0, 200",
|
||||
"1, 200",
|
||||
"8640000000000000, 200",
|
||||
"8640000000000001, 400",
|
||||
|
||||
// 404 here is a weird quirk of controller pattern matching; this value doesn't get interpreted as `long`, and so
|
||||
// it doesn't match the "send multi-recipient message" endpoint
|
||||
"99999999999999999999999999999999999, 404"
|
||||
})
|
||||
void testMultiRecipientExtremeTimestamp(final String timestamp, final int expectedStatus) {
|
||||
|
||||
when(messagesManager.insertSharedMultiRecipientMessagePayload(any(SealedSenderMultiRecipientMessage.class)))
|
||||
.thenReturn(new byte[]{1});
|
||||
|
||||
final int nRecipients = 999;
|
||||
final int devicesPerRecipient = 5;
|
||||
final List<Recipient> recipients = new ArrayList<>();
|
||||
|
||||
for (int i = 0; i < nRecipients; i++) {
|
||||
final List<Device> devices =
|
||||
IntStream.range(1, devicesPerRecipient + 1)
|
||||
.mapToObj(
|
||||
d -> generateTestDevice(
|
||||
(byte) d, 100 + d, 10 * d, true))
|
||||
.collect(Collectors.toList());
|
||||
final UUID aci = new UUID(0L, i);
|
||||
final UUID pni = new UUID(1L, i);
|
||||
final String e164 = String.format("+1408555%04d", i);
|
||||
final Account account = AccountsHelper.generateTestAccount(e164, aci, pni, devices, UNIDENTIFIED_ACCESS_BYTES);
|
||||
|
||||
when(accountsManager.getByServiceIdentifierAsync(new AciServiceIdentifier(aci)))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(account)));
|
||||
|
||||
when(accountsManager.getByServiceIdentifierAsync(new PniServiceIdentifier(pni)))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(account)));
|
||||
|
||||
devices.forEach(d -> recipients.add(new Recipient(new AciServiceIdentifier(aci), d.getId(), d.getRegistrationId(), new byte[48])));
|
||||
}
|
||||
|
||||
byte[] buffer = new byte[1048576];
|
||||
InputStream stream = initializeMultiPayload(recipients, buffer, true);
|
||||
Entity<InputStream> entity = Entity.entity(stream, MultiRecipientMessageProvider.MEDIA_TYPE);
|
||||
try (final Response response = resources
|
||||
.getJerseyTest()
|
||||
.target("/v1/messages/multi_recipient")
|
||||
.queryParam("online", true)
|
||||
.queryParam("story", true)
|
||||
.queryParam("urgent", false)
|
||||
.queryParam("ts", timestamp)
|
||||
.request()
|
||||
.header(HttpHeaders.USER_AGENT, "test")
|
||||
.put(entity)) {
|
||||
|
||||
assertThat(response.readEntity(String.class), response.getStatus(), is(equalTo(expectedStatus)));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSendStoryToUnknownAccount() throws Exception {
|
||||
String accessBytes = Base64.getEncoder().encodeToString(UNIDENTIFIED_ACCESS_BYTES);
|
||||
|
||||
+27
-3
@@ -66,6 +66,7 @@ import org.whispersystems.textsecuregcm.limits.RateLimiter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.mappers.ImpossiblePhoneNumberExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.NonNormalizedPhoneNumberExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.ObsoletePhoneNumberFormatExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.RegistrationServiceSenderExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
|
||||
@@ -117,6 +118,7 @@ class VerificationControllerTest {
|
||||
.addProvider(new RateLimitExceededExceptionMapper())
|
||||
.addProvider(new ImpossiblePhoneNumberExceptionMapper())
|
||||
.addProvider(new NonNormalizedPhoneNumberExceptionMapper())
|
||||
.addProvider(new ObsoletePhoneNumberFormatExceptionMapper())
|
||||
.addProvider(new RegistrationServiceSenderExceptionMapper())
|
||||
.setMapper(SystemMapper.jsonMapper())
|
||||
.setTestContainerFactory(new GrizzlyWebTestContainerFactory())
|
||||
@@ -220,7 +222,7 @@ class VerificationControllerTest {
|
||||
when(registrationServiceClient.createRegistrationSession(any(), anyBoolean(), any()))
|
||||
.thenReturn(
|
||||
CompletableFuture.completedFuture(
|
||||
new RegistrationServiceSession(SESSION_ID, NUMBER, false, null, null, null,
|
||||
new RegistrationServiceSession(SESSION_ID, requestedNumber, false, null, null, null,
|
||||
SESSION_EXPIRATION_SECONDS)));
|
||||
when(verificationSessionManager.insert(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
@@ -245,14 +247,36 @@ class VerificationControllerTest {
|
||||
// libphonenumber 8.13.50 and on generate new-format numbers for Benin
|
||||
final String newFormatBeninE164 = PhoneNumberUtil.getInstance()
|
||||
.format(PhoneNumberUtil.getInstance().getExampleNumber("BJ"), PhoneNumberUtil.PhoneNumberFormat.E164);
|
||||
final String oldFormatBeninE164 = newFormatBeninE164.replaceFirst("01", "");
|
||||
return Stream.of(
|
||||
Arguments.of(oldFormatBeninE164, newFormatBeninE164),
|
||||
Arguments.of(newFormatBeninE164, newFormatBeninE164),
|
||||
Arguments.of(NUMBER, NUMBER)
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void createBeninSessionFailure() {
|
||||
// libphonenumber 8.13.50 and on generate new-format numbers for Benin
|
||||
final String newFormatBeninE164 = PhoneNumberUtil.getInstance()
|
||||
.format(PhoneNumberUtil.getInstance().getExampleNumber("BJ"), PhoneNumberUtil.PhoneNumberFormat.E164);
|
||||
final String oldFormatBeninE164 = newFormatBeninE164.replaceFirst("01", "");
|
||||
|
||||
when(registrationServiceClient.createRegistrationSession(any(), anyBoolean(), any()))
|
||||
.thenReturn(
|
||||
CompletableFuture.completedFuture(
|
||||
new RegistrationServiceSession(SESSION_ID, NUMBER, false, null, null, null,
|
||||
SESSION_EXPIRATION_SECONDS)));
|
||||
when(verificationSessionManager.insert(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
.target("/v1/verification/session")
|
||||
.request()
|
||||
.header(HttpHeaders.X_FORWARDED_FOR, "127.0.0.1");
|
||||
try (Response response = request.post(Entity.json(createSessionJson(oldFormatBeninE164, "token", "fcm")))) {
|
||||
assertEquals(499, response.getStatus());
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void createSessionSuccess(final String pushToken, final String pushTokenType,
|
||||
|
||||
+328
@@ -0,0 +1,328 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
|
||||
import static org.assertj.core.api.Assertions.assertThatNoException;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import io.grpc.Status;
|
||||
import io.grpc.StatusRuntimeException;
|
||||
import java.time.Clock;
|
||||
import java.util.Arrays;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junitpioneer.jupiter.cartesian.CartesianTest;
|
||||
import org.mockito.Mock;
|
||||
import org.signal.chat.backup.BackupsAnonymousGrpc;
|
||||
import org.signal.chat.backup.CopyMediaItem;
|
||||
import org.signal.chat.backup.CopyMediaRequest;
|
||||
import org.signal.chat.backup.CopyMediaResponse;
|
||||
import org.signal.chat.backup.DeleteMediaItem;
|
||||
import org.signal.chat.backup.DeleteMediaRequest;
|
||||
import org.signal.chat.backup.GetBackupInfoRequest;
|
||||
import org.signal.chat.backup.GetBackupInfoResponse;
|
||||
import org.signal.chat.backup.GetCdnCredentialsRequest;
|
||||
import org.signal.chat.backup.GetCdnCredentialsResponse;
|
||||
import org.signal.chat.backup.GetUploadFormRequest;
|
||||
import org.signal.chat.backup.GetUploadFormResponse;
|
||||
import org.signal.chat.backup.ListMediaRequest;
|
||||
import org.signal.chat.backup.ListMediaResponse;
|
||||
import org.signal.chat.backup.SetPublicKeyRequest;
|
||||
import org.signal.chat.backup.SignedPresentation;
|
||||
import org.signal.libsignal.protocol.ecc.Curve;
|
||||
import org.signal.libsignal.zkgroup.VerificationFailedException;
|
||||
import org.signal.libsignal.zkgroup.backups.BackupAuthCredentialPresentation;
|
||||
import org.signal.libsignal.zkgroup.backups.BackupCredentialType;
|
||||
import org.signal.libsignal.zkgroup.backups.BackupLevel;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedBackupUser;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupAuthTestUtil;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupManager;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupUploadDescriptor;
|
||||
import org.whispersystems.textsecuregcm.backup.CopyResult;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
|
||||
import reactor.core.publisher.Flux;
|
||||
|
||||
class BackupsAnonymousGrpcServiceTest extends
|
||||
SimpleBaseGrpcTest<BackupsAnonymousGrpcService, BackupsAnonymousGrpc.BackupsAnonymousBlockingStub> {
|
||||
|
||||
private final UUID aci = UUID.randomUUID();
|
||||
private final byte[] messagesBackupKey = TestRandomUtil.nextBytes(32);
|
||||
private final BackupAuthTestUtil backupAuthTestUtil = new BackupAuthTestUtil(Clock.systemUTC());
|
||||
private final BackupAuthCredentialPresentation presentation =
|
||||
presentation(backupAuthTestUtil, messagesBackupKey, aci);
|
||||
|
||||
@Mock
|
||||
private BackupManager backupManager;
|
||||
|
||||
@Override
|
||||
protected BackupsAnonymousGrpcService createServiceBeforeEachTest() {
|
||||
return new BackupsAnonymousGrpcService(backupManager);
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
when(backupManager.authenticateBackupUser(any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
backupUser(presentation.getBackupId(), BackupCredentialType.MESSAGES, BackupLevel.PAID)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void setPublicKey() {
|
||||
when(backupManager.setPublicKey(any(), any(), any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
assertThatNoException().isThrownBy(() -> unauthenticatedServiceStub().setPublicKey(SetPublicKeyRequest.newBuilder()
|
||||
.setPublicKey(ByteString.copyFrom(Curve.generateKeyPair().getPublicKey().serialize()))
|
||||
.setSignedPresentation(signedPresentation(presentation))
|
||||
.build()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void setBadPublicKey() {
|
||||
when(backupManager.setPublicKey(any(), any(), any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
assertThatExceptionOfType(StatusRuntimeException.class).isThrownBy(() ->
|
||||
unauthenticatedServiceStub().setPublicKey(SetPublicKeyRequest.newBuilder()
|
||||
.setPublicKey(ByteString.copyFromUtf8("aaaaa")) // Invalid public key
|
||||
.setSignedPresentation(signedPresentation(presentation))
|
||||
.build()))
|
||||
.extracting(ex -> ex.getStatus().getCode())
|
||||
.isEqualTo(Status.Code.INVALID_ARGUMENT);
|
||||
}
|
||||
|
||||
@Test
|
||||
void setMissingPublicKey() {
|
||||
assertThatExceptionOfType(StatusRuntimeException.class).isThrownBy(() ->
|
||||
unauthenticatedServiceStub().setPublicKey(SetPublicKeyRequest.newBuilder()
|
||||
// Missing public key
|
||||
.setSignedPresentation(signedPresentation(presentation))
|
||||
.build()))
|
||||
.extracting(ex -> ex.getStatus().getCode())
|
||||
.isEqualTo(Status.Code.INVALID_ARGUMENT);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
void putMediaBatchSuccess() {
|
||||
final byte[][] mediaIds = {TestRandomUtil.nextBytes(15), TestRandomUtil.nextBytes(15)};
|
||||
when(backupManager.copyToBackup(any(), any()))
|
||||
.thenReturn(Flux.just(
|
||||
new CopyResult(CopyResult.Outcome.SUCCESS, mediaIds[0], 1),
|
||||
new CopyResult(CopyResult.Outcome.SUCCESS, mediaIds[1], 1)));
|
||||
|
||||
final CopyMediaRequest request = CopyMediaRequest.newBuilder()
|
||||
.setSignedPresentation(signedPresentation(presentation))
|
||||
.addItems(CopyMediaItem.newBuilder()
|
||||
.setSourceAttachmentCdn(3)
|
||||
.setSourceKey("abc")
|
||||
.setObjectLength(100)
|
||||
.setMediaId(ByteString.copyFrom(mediaIds[0]))
|
||||
.setHmacKey(ByteString.copyFrom(TestRandomUtil.nextBytes(32)))
|
||||
.setEncryptionKey(ByteString.copyFrom(TestRandomUtil.nextBytes(32)))
|
||||
.build())
|
||||
.addItems(CopyMediaItem.newBuilder()
|
||||
.setSourceAttachmentCdn(3)
|
||||
.setSourceKey("def")
|
||||
.setObjectLength(200)
|
||||
.setMediaId(ByteString.copyFrom(mediaIds[1]))
|
||||
.setHmacKey(ByteString.copyFrom(TestRandomUtil.nextBytes(32)))
|
||||
.setEncryptionKey(ByteString.copyFrom(TestRandomUtil.nextBytes(32)))
|
||||
.build())
|
||||
.build();
|
||||
|
||||
final Iterator<CopyMediaResponse> it = unauthenticatedServiceStub().copyMedia(request);
|
||||
|
||||
for (int i = 0; i < 2; i++) {
|
||||
final CopyMediaResponse response = it.next();
|
||||
assertThat(response.getSuccess().getCdn()).isEqualTo(1);
|
||||
assertThat(response.getMediaId().toByteArray()).isEqualTo(mediaIds[i]);
|
||||
}
|
||||
assertThat(it.hasNext()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void putMediaBatchPartialFailure() {
|
||||
// Copy four different mediaIds, with a variety of success/failure outcomes
|
||||
final byte[][] mediaIds = IntStream.range(0, 4).mapToObj(i -> TestRandomUtil.nextBytes(15)).toArray(byte[][]::new);
|
||||
final CopyResult.Outcome[] outcomes = new CopyResult.Outcome[]{
|
||||
CopyResult.Outcome.SUCCESS,
|
||||
CopyResult.Outcome.SOURCE_NOT_FOUND,
|
||||
CopyResult.Outcome.SOURCE_WRONG_LENGTH,
|
||||
CopyResult.Outcome.OUT_OF_QUOTA
|
||||
};
|
||||
when(backupManager.copyToBackup(any(), any()))
|
||||
.thenReturn(Flux.fromStream(IntStream.range(0, 4)
|
||||
.mapToObj(i -> new CopyResult(
|
||||
outcomes[i],
|
||||
mediaIds[i],
|
||||
outcomes[i] == CopyResult.Outcome.SUCCESS ? 1 : null))));
|
||||
|
||||
final CopyMediaRequest request = CopyMediaRequest.newBuilder()
|
||||
.setSignedPresentation(signedPresentation(presentation))
|
||||
.addAllItems(Arrays.stream(mediaIds)
|
||||
.map(mediaId -> CopyMediaItem.newBuilder()
|
||||
.setSourceAttachmentCdn(3)
|
||||
.setSourceKey("abc")
|
||||
.setObjectLength(100)
|
||||
.setMediaId(ByteString.copyFrom(mediaId))
|
||||
.setHmacKey(ByteString.copyFrom(TestRandomUtil.nextBytes(32)))
|
||||
.setEncryptionKey(ByteString.copyFrom(TestRandomUtil.nextBytes(32)))
|
||||
.build())
|
||||
.collect(Collectors.toList()))
|
||||
.build();
|
||||
|
||||
final Iterator<CopyMediaResponse> responses = unauthenticatedServiceStub().copyMedia(request);
|
||||
|
||||
// Verify that we get the expected response for each mediaId
|
||||
for (int i = 0; i < mediaIds.length; i++) {
|
||||
final CopyMediaResponse response = responses.next();
|
||||
switch (outcomes[i]) {
|
||||
case SUCCESS -> assertThat(response.getSuccess().getCdn()).isEqualTo(1);
|
||||
case SOURCE_WRONG_LENGTH -> assertThat(response.getWrongSourceLength()).isNotNull();
|
||||
case OUT_OF_QUOTA -> assertThat(response.getOutOfSpace()).isNotNull();
|
||||
case SOURCE_NOT_FOUND -> assertThat(response.getSourceNotFound()).isNotNull();
|
||||
}
|
||||
assertThat(response.getMediaId().toByteArray()).isEqualTo(mediaIds[i]);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void getBackupInfo() {
|
||||
when(backupManager.backupInfo(any())).thenReturn(CompletableFuture.completedFuture(new BackupManager.BackupInfo(
|
||||
1, "myBackupDir", "myMediaDir", "filename", Optional.empty())));
|
||||
|
||||
final GetBackupInfoResponse response = unauthenticatedServiceStub().getBackupInfo(GetBackupInfoRequest.newBuilder()
|
||||
.setSignedPresentation(signedPresentation(presentation))
|
||||
.build());
|
||||
assertThat(response.getBackupDir()).isEqualTo("myBackupDir");
|
||||
assertThat(response.getBackupName()).isEqualTo("filename");
|
||||
assertThat(response.getCdn()).isEqualTo(1);
|
||||
assertThat(response.getUsedSpace()).isEqualTo(0L);
|
||||
}
|
||||
|
||||
|
||||
@CartesianTest
|
||||
void list(
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean cursorProvided,
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean cursorReturned)
|
||||
throws VerificationFailedException {
|
||||
|
||||
final byte[] mediaId = TestRandomUtil.nextBytes(15);
|
||||
final Optional<String> expectedCursor = cursorProvided ? Optional.of("myCursor") : Optional.empty();
|
||||
final Optional<String> returnedCursor = cursorReturned ? Optional.of("newCursor") : Optional.empty();
|
||||
|
||||
final int limit = 17;
|
||||
|
||||
when(backupManager.list(any(), eq(expectedCursor), eq(limit)))
|
||||
.thenReturn(CompletableFuture.completedFuture(new BackupManager.ListMediaResult(
|
||||
List.of(new BackupManager.StorageDescriptorWithLength(1, mediaId, 100)),
|
||||
returnedCursor)));
|
||||
|
||||
final ListMediaRequest.Builder request = ListMediaRequest.newBuilder()
|
||||
.setSignedPresentation(signedPresentation(presentation))
|
||||
.setLimit(limit);
|
||||
if (cursorProvided) {
|
||||
request.setCursor("myCursor");
|
||||
}
|
||||
|
||||
final ListMediaResponse response = unauthenticatedServiceStub().listMedia(request.build());
|
||||
assertThat(response.getPageCount()).isEqualTo(1);
|
||||
assertThat(response.getPage(0).getLength()).isEqualTo(100);
|
||||
assertThat(response.getPage(0).getMediaId().toByteArray()).isEqualTo(mediaId);
|
||||
assertThat(response.hasCursor() ? response.getCursor() : null).isEqualTo(returnedCursor.orElse(null));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
void delete() {
|
||||
final DeleteMediaRequest request = DeleteMediaRequest.newBuilder()
|
||||
.setSignedPresentation(signedPresentation(presentation))
|
||||
.addAllItems(IntStream.range(0, 100).mapToObj(i ->
|
||||
DeleteMediaItem.newBuilder()
|
||||
.setCdn(3)
|
||||
.setMediaId(ByteString.copyFrom(TestRandomUtil.nextBytes(15)))
|
||||
.build())
|
||||
.toList()).build();
|
||||
|
||||
when(backupManager.deleteMedia(any(), any()))
|
||||
.thenReturn(Flux.fromStream(request.getItemsList().stream()
|
||||
.map(m -> new BackupManager.StorageDescriptor(m.getCdn(), m.getMediaId().toByteArray()))));
|
||||
|
||||
final AtomicInteger count = new AtomicInteger(0);
|
||||
unauthenticatedServiceStub().deleteMedia(request).forEachRemaining(i -> count.getAndIncrement());
|
||||
assertThat(count.get()).isEqualTo(100);
|
||||
}
|
||||
|
||||
@Test
|
||||
void mediaUploadForm() {
|
||||
when(backupManager.createTemporaryAttachmentUploadDescriptor(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
new BackupUploadDescriptor(3, "abc", Map.of("k", "v"), "example.org")));
|
||||
final GetUploadFormRequest request = GetUploadFormRequest.newBuilder()
|
||||
.setMedia(GetUploadFormRequest.MediaUploadType.getDefaultInstance())
|
||||
.setSignedPresentation(signedPresentation(presentation))
|
||||
.build();
|
||||
|
||||
final GetUploadFormResponse uploadForm = unauthenticatedServiceStub().getUploadForm(request);
|
||||
assertThat(uploadForm.getCdn()).isEqualTo(3);
|
||||
assertThat(uploadForm.getKey()).isEqualTo("abc");
|
||||
assertThat(uploadForm.getHeadersMap()).containsExactlyEntriesOf(Map.of("k", "v"));
|
||||
assertThat(uploadForm.getSignedUploadLocation()).isEqualTo("example.org");
|
||||
|
||||
// rate limit
|
||||
when(backupManager.createTemporaryAttachmentUploadDescriptor(any()))
|
||||
.thenReturn(CompletableFuture.failedFuture(new RateLimitExceededException(null)));
|
||||
assertThatExceptionOfType(StatusRuntimeException.class)
|
||||
.isThrownBy(() -> unauthenticatedServiceStub().getUploadForm(request))
|
||||
.extracting(StatusRuntimeException::getStatus)
|
||||
.isEqualTo(Status.RESOURCE_EXHAUSTED);
|
||||
}
|
||||
|
||||
@Test
|
||||
void readAuth() {
|
||||
when(backupManager.generateReadAuth(any(), eq(3))).thenReturn(Map.of("key", "value"));
|
||||
|
||||
final GetCdnCredentialsResponse response = unauthenticatedServiceStub().getCdnCredentials(
|
||||
GetCdnCredentialsRequest.newBuilder()
|
||||
.setCdn(3)
|
||||
.setSignedPresentation(signedPresentation(presentation))
|
||||
.build());
|
||||
assertThat(response.getHeadersMap()).containsExactlyEntriesOf(Map.of("key", "value"));
|
||||
}
|
||||
|
||||
private static AuthenticatedBackupUser backupUser(final byte[] backupId, final BackupCredentialType credentialType,
|
||||
final BackupLevel backupLevel) {
|
||||
return new AuthenticatedBackupUser(backupId, credentialType, backupLevel, "myBackupDir", "myMediaDir");
|
||||
}
|
||||
|
||||
private static BackupAuthCredentialPresentation presentation(BackupAuthTestUtil backupAuthTestUtil,
|
||||
byte[] messagesBackupKey, UUID aci) {
|
||||
try {
|
||||
return backupAuthTestUtil.getPresentation(BackupLevel.PAID, messagesBackupKey, aci);
|
||||
} catch (VerificationFailedException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private static SignedPresentation signedPresentation(BackupAuthCredentialPresentation presentation) {
|
||||
return SignedPresentation.newBuilder()
|
||||
.setPresentation(ByteString.copyFrom(presentation.serialize()))
|
||||
.setPresentationSignature(ByteString.copyFromUtf8("aaa")).build();
|
||||
}
|
||||
|
||||
}
|
||||
+243
@@ -0,0 +1,243 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import io.grpc.Status;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.stream.Stream;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.junit.jupiter.params.provider.EnumSource;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.junitpioneer.jupiter.cartesian.CartesianTest;
|
||||
import org.mockito.Mock;
|
||||
import org.signal.chat.backup.BackupsGrpc;
|
||||
import org.signal.chat.backup.GetBackupAuthCredentialsRequest;
|
||||
import org.signal.chat.backup.GetBackupAuthCredentialsResponse;
|
||||
import org.signal.chat.backup.RedeemReceiptRequest;
|
||||
import org.signal.chat.backup.SetBackupIdRequest;
|
||||
import org.signal.chat.common.ZkCredential;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.ServerSecretParams;
|
||||
import org.signal.libsignal.zkgroup.VerificationFailedException;
|
||||
import org.signal.libsignal.zkgroup.backups.BackupAuthCredentialRequest;
|
||||
import org.signal.libsignal.zkgroup.backups.BackupCredentialType;
|
||||
import org.signal.libsignal.zkgroup.backups.BackupLevel;
|
||||
import org.signal.libsignal.zkgroup.receipts.ClientZkReceiptOperations;
|
||||
import org.signal.libsignal.zkgroup.receipts.ReceiptCredential;
|
||||
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialPresentation;
|
||||
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialRequestContext;
|
||||
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialResponse;
|
||||
import org.signal.libsignal.zkgroup.receipts.ReceiptSerial;
|
||||
import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupAuthManager;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupAuthTestUtil;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.util.EnumMapUtil;
|
||||
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
|
||||
|
||||
class BackupsGrpcServiceTest extends SimpleBaseGrpcTest<BackupsGrpcService, BackupsGrpc.BackupsBlockingStub> {
|
||||
|
||||
private final byte[] messagesBackupKey = TestRandomUtil.nextBytes(32);
|
||||
private final byte[] mediaBackupKey = TestRandomUtil.nextBytes(32);
|
||||
private final BackupAuthTestUtil backupAuthTestUtil = new BackupAuthTestUtil(Clock.systemUTC());
|
||||
final BackupAuthCredentialRequest mediaAuthCredRequest =
|
||||
backupAuthTestUtil.getRequest(mediaBackupKey, AUTHENTICATED_ACI);
|
||||
final BackupAuthCredentialRequest messagesAuthCredRequest =
|
||||
backupAuthTestUtil.getRequest(messagesBackupKey, AUTHENTICATED_ACI);
|
||||
private final Account account = mock(Account.class);
|
||||
|
||||
@Mock
|
||||
private BackupAuthManager backupAuthManager;
|
||||
@Mock
|
||||
private AccountsManager accountsManager;
|
||||
|
||||
@Override
|
||||
protected BackupsGrpcService createServiceBeforeEachTest() {
|
||||
return new BackupsGrpcService(accountsManager, backupAuthManager);
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
when(accountsManager.getByAccountIdentifierAsync(AUTHENTICATED_ACI))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(account)));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
void setBackupId() {
|
||||
when(backupAuthManager.commitBackupId(any(), any(), any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
authenticatedServiceStub().setBackupId(
|
||||
SetBackupIdRequest.newBuilder()
|
||||
.setMediaBackupAuthCredentialRequest(ByteString.copyFrom(mediaAuthCredRequest.serialize()))
|
||||
.setMessagesBackupAuthCredentialRequest(ByteString.copyFrom(messagesAuthCredRequest.serialize()))
|
||||
.build());
|
||||
|
||||
verify(backupAuthManager).commitBackupId(account, messagesAuthCredRequest, mediaAuthCredRequest);
|
||||
}
|
||||
|
||||
@Test
|
||||
void setBackupIdInvalid() {
|
||||
// missing media credential
|
||||
GrpcTestUtils.assertStatusException(
|
||||
Status.INVALID_ARGUMENT, () -> authenticatedServiceStub().setBackupId(SetBackupIdRequest.newBuilder()
|
||||
.setMessagesBackupAuthCredentialRequest(ByteString.copyFrom(messagesAuthCredRequest.serialize()))
|
||||
.build())
|
||||
);
|
||||
|
||||
// missing message credential
|
||||
GrpcTestUtils.assertStatusException(
|
||||
Status.INVALID_ARGUMENT, () -> authenticatedServiceStub().setBackupId(SetBackupIdRequest.newBuilder()
|
||||
.setMediaBackupAuthCredentialRequest(ByteString.copyFrom(mediaAuthCredRequest.serialize()))
|
||||
.build())
|
||||
);
|
||||
|
||||
// missing all credentials
|
||||
GrpcTestUtils.assertStatusException(
|
||||
Status.INVALID_ARGUMENT, () -> authenticatedServiceStub().setBackupId(SetBackupIdRequest.newBuilder().build())
|
||||
);
|
||||
|
||||
// invalid serialization
|
||||
GrpcTestUtils.assertStatusException(
|
||||
Status.INVALID_ARGUMENT, () -> authenticatedServiceStub().setBackupId(
|
||||
SetBackupIdRequest.newBuilder()
|
||||
.setMessagesBackupAuthCredentialRequest(ByteString.fromHex("FF"))
|
||||
.setMediaBackupAuthCredentialRequest(ByteString.fromHex("FF"))
|
||||
.build())
|
||||
);
|
||||
|
||||
}
|
||||
|
||||
public static Stream<Arguments> setBackupIdException() {
|
||||
return Stream.of(
|
||||
Arguments.of(new RateLimitExceededException(null), false, Status.RESOURCE_EXHAUSTED),
|
||||
Arguments.of(Status.INVALID_ARGUMENT.withDescription("async").asRuntimeException(), false,
|
||||
Status.INVALID_ARGUMENT),
|
||||
Arguments.of(Status.INVALID_ARGUMENT.withDescription("sync").asRuntimeException(), true,
|
||||
Status.INVALID_ARGUMENT)
|
||||
);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void setBackupIdException(final Exception ex, final boolean sync, final Status expected) {
|
||||
if (sync) {
|
||||
when(backupAuthManager.commitBackupId(any(), any(), any())).thenThrow(ex);
|
||||
} else {
|
||||
when(backupAuthManager.commitBackupId(any(), any(), any())).thenReturn(CompletableFuture.failedFuture(ex));
|
||||
}
|
||||
|
||||
GrpcTestUtils.assertStatusException(
|
||||
expected, () -> authenticatedServiceStub().setBackupId(SetBackupIdRequest.newBuilder()
|
||||
.setMediaBackupAuthCredentialRequest(ByteString.copyFrom(mediaAuthCredRequest.serialize()))
|
||||
.setMessagesBackupAuthCredentialRequest(ByteString.copyFrom(messagesAuthCredRequest.serialize()))
|
||||
.build())
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void redeemReceipt() throws InvalidInputException, VerificationFailedException {
|
||||
final ServerSecretParams params = ServerSecretParams.generate();
|
||||
final ServerZkReceiptOperations serverOps = new ServerZkReceiptOperations(params);
|
||||
final ClientZkReceiptOperations clientOps = new ClientZkReceiptOperations(params.getPublicParams());
|
||||
final ReceiptCredentialRequestContext rcrc = clientOps
|
||||
.createReceiptCredentialRequestContext(new ReceiptSerial(TestRandomUtil.nextBytes(ReceiptSerial.SIZE)));
|
||||
final ReceiptCredentialResponse rcr = serverOps.issueReceiptCredential(rcrc.getRequest(), 0L, 3L);
|
||||
final ReceiptCredential receiptCredential = clientOps.receiveReceiptCredential(rcrc, rcr);
|
||||
final ReceiptCredentialPresentation presentation = clientOps.createReceiptCredentialPresentation(receiptCredential);
|
||||
|
||||
when(backupAuthManager.redeemReceipt(any(), any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
authenticatedServiceStub().redeemReceipt(RedeemReceiptRequest.newBuilder()
|
||||
.setPresentation(ByteString.copyFrom(presentation.serialize()))
|
||||
.build());
|
||||
|
||||
verify(backupAuthManager).redeemReceipt(account, presentation);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
void getCredentials() {
|
||||
final Instant start = Instant.now().truncatedTo(ChronoUnit.DAYS);
|
||||
final Instant end = start.plus(Duration.ofDays(1));
|
||||
|
||||
final Map<BackupCredentialType, List<BackupAuthManager.Credential>> expectedCredentialsByType =
|
||||
EnumMapUtil.toEnumMap(BackupCredentialType.class, credentialType -> backupAuthTestUtil.getCredentials(
|
||||
BackupLevel.PAID, backupAuthTestUtil.getRequest(messagesBackupKey, AUTHENTICATED_ACI), credentialType,
|
||||
start, end));
|
||||
|
||||
expectedCredentialsByType.forEach((credentialType, expectedCredentials) ->
|
||||
when(backupAuthManager.getBackupAuthCredentials(any(), eq(credentialType), eq(start), eq(end)))
|
||||
.thenReturn(CompletableFuture.completedFuture(expectedCredentials)));
|
||||
|
||||
final GetBackupAuthCredentialsResponse credentialResponse = authenticatedServiceStub().getBackupAuthCredentials(
|
||||
GetBackupAuthCredentialsRequest.newBuilder()
|
||||
.setRedemptionStart(start.getEpochSecond()).setRedemptionStop(end.getEpochSecond())
|
||||
.build());
|
||||
|
||||
expectedCredentialsByType.forEach((credentialType, expectedCredentials) -> {
|
||||
|
||||
final Map<Long, ZkCredential> creds = switch (credentialType) {
|
||||
case MESSAGES -> credentialResponse.getMessageCredentialsMap();
|
||||
case MEDIA -> credentialResponse.getMediaCredentialsMap();
|
||||
};
|
||||
assertThat(creds).hasSize(expectedCredentials.size()).containsKey(start.getEpochSecond());
|
||||
|
||||
for (BackupAuthManager.Credential expectedCred : expectedCredentials) {
|
||||
assertThat(creds)
|
||||
.extractingByKey(expectedCred.redemptionTime().getEpochSecond())
|
||||
.isNotNull()
|
||||
.extracting(ZkCredential::getCredential)
|
||||
.extracting(ByteString::toByteArray)
|
||||
.isEqualTo(expectedCred.credential().serialize());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({
|
||||
"true, false",
|
||||
"false, true",
|
||||
"true, true"
|
||||
})
|
||||
void getCredentialsBadInput(final boolean missingStart, final boolean missingEnd) {
|
||||
final Instant start = Instant.now().truncatedTo(ChronoUnit.DAYS);
|
||||
final Instant end = start.plus(Duration.ofDays(1));
|
||||
|
||||
final GetBackupAuthCredentialsRequest.Builder builder = GetBackupAuthCredentialsRequest.newBuilder();
|
||||
if (!missingStart) {
|
||||
builder.setRedemptionStart(start.getEpochSecond());
|
||||
}
|
||||
if (!missingEnd) {
|
||||
builder.setRedemptionStop(end.getEpochSecond());
|
||||
}
|
||||
|
||||
GrpcTestUtils.assertStatusException(Status.INVALID_ARGUMENT,
|
||||
() -> authenticatedServiceStub().getBackupAuthCredentials(builder.build()));
|
||||
}
|
||||
|
||||
}
|
||||
-75
@@ -1,75 +0,0 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.whispersystems.textsecuregcm.grpc.GrpcTestUtils.assertRateLimitExceeded;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mock;
|
||||
import org.signal.chat.calling.CallingGrpc;
|
||||
import org.signal.chat.calling.GetTurnCredentialsRequest;
|
||||
import org.signal.chat.calling.GetTurnCredentialsResponse;
|
||||
import org.whispersystems.textsecuregcm.auth.TurnToken;
|
||||
import org.whispersystems.textsecuregcm.auth.TurnTokenGenerator;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.util.MockUtils;
|
||||
|
||||
class CallingGrpcServiceTest extends SimpleBaseGrpcTest<CallingGrpcService, CallingGrpc.CallingBlockingStub> {
|
||||
|
||||
@Mock
|
||||
private TurnTokenGenerator turnTokenGenerator;
|
||||
|
||||
@Mock
|
||||
private RateLimiter turnCredentialRateLimiter;
|
||||
|
||||
|
||||
@Override
|
||||
protected CallingGrpcService createServiceBeforeEachTest() {
|
||||
final RateLimiters rateLimiters = mock(RateLimiters.class);
|
||||
when(rateLimiters.getTurnLimiter()).thenReturn(turnCredentialRateLimiter);
|
||||
return new CallingGrpcService(turnTokenGenerator, rateLimiters);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getTurnCredentials() {
|
||||
final String username = "test-username";
|
||||
final String password = "test-password";
|
||||
final List<String> urls = List.of("first", "second");
|
||||
final String hostname = "hostname";
|
||||
|
||||
MockUtils.updateRateLimiterResponseToAllow(turnCredentialRateLimiter, AUTHENTICATED_ACI);
|
||||
when(turnTokenGenerator.generate(any())).thenReturn(new TurnToken(username, password, urls, null, hostname));
|
||||
|
||||
final GetTurnCredentialsResponse response = authenticatedServiceStub().getTurnCredentials(GetTurnCredentialsRequest.newBuilder().build());
|
||||
|
||||
final GetTurnCredentialsResponse expectedResponse = GetTurnCredentialsResponse.newBuilder()
|
||||
.setUsername(username)
|
||||
.setPassword(password)
|
||||
.addAllUrls(urls)
|
||||
.build();
|
||||
|
||||
assertEquals(expectedResponse, response);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getTurnCredentialsRateLimited() {
|
||||
final Duration retryAfter = MockUtils.updateRateLimiterResponseToFail(
|
||||
turnCredentialRateLimiter, AUTHENTICATED_ACI, Duration.ofMinutes(19));
|
||||
assertRateLimitExceeded(retryAfter, () -> authenticatedServiceStub().getTurnCredentials(GetTurnCredentialsRequest.newBuilder().build()));
|
||||
verify(turnTokenGenerator, never()).generate(any());
|
||||
verifyNoInteractions(turnTokenGenerator);
|
||||
}
|
||||
}
|
||||
@@ -35,7 +35,7 @@ public final class GrpcTestUtils {
|
||||
final BindableService service) {
|
||||
mockAuthenticationInterceptor.setAuthenticatedDevice(authenticatedAci, authenticatedDeviceId);
|
||||
extension.getServiceRegistry()
|
||||
.addService(ServerInterceptors.intercept(service, mockRequestAttributesInterceptor, mockAuthenticationInterceptor, new ErrorMappingInterceptor()));
|
||||
.addService(ServerInterceptors.intercept(service, new ValidatingInterceptor(), mockRequestAttributesInterceptor, mockAuthenticationInterceptor, new ErrorMappingInterceptor()));
|
||||
}
|
||||
|
||||
public static void setupUnauthenticatedExtension(
|
||||
@@ -43,7 +43,7 @@ public final class GrpcTestUtils {
|
||||
final MockRequestAttributesInterceptor mockRequestAttributesInterceptor,
|
||||
final BindableService service) {
|
||||
extension.getServiceRegistry()
|
||||
.addService(ServerInterceptors.intercept(service, mockRequestAttributesInterceptor, new ErrorMappingInterceptor()));
|
||||
.addService(ServerInterceptors.intercept(service, new ValidatingInterceptor(), mockRequestAttributesInterceptor, new ErrorMappingInterceptor()));
|
||||
}
|
||||
|
||||
public static void assertStatusException(final Status expected, final Executable serviceCall) {
|
||||
|
||||
@@ -7,15 +7,17 @@ package org.whispersystems.textsecuregcm.util;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import com.google.i18n.phonenumbers.NumberParseException;
|
||||
import com.google.i18n.phonenumbers.PhoneNumberUtil;
|
||||
import com.google.i18n.phonenumbers.Phonenumber;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import java.util.stream.Stream;
|
||||
import com.google.i18n.phonenumbers.Phonenumber;
|
||||
import javax.annotation.Nullable;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
@@ -93,9 +95,13 @@ class UtilTest {
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void normalizeBeninPhoneNumber(final Phonenumber.PhoneNumber beninNumber, final Phonenumber.PhoneNumber expectedBeninNumber)
|
||||
throws NumberParseException {
|
||||
assertTrue(expectedBeninNumber.exactlySameAs(Util.canonicalizePhoneNumber(beninNumber)));
|
||||
void normalizeBeninPhoneNumber(final Phonenumber.PhoneNumber beninNumber, final Phonenumber.PhoneNumber expectedBeninNumber, @Nullable Class<? extends Throwable> exception)
|
||||
throws Exception {
|
||||
if (exception == null) {
|
||||
assertTrue(expectedBeninNumber.exactlySameAs(Util.canonicalizePhoneNumber(beninNumber)));
|
||||
} else {
|
||||
assertThrows(exception, () -> Util.canonicalizePhoneNumber(beninNumber));
|
||||
}
|
||||
}
|
||||
|
||||
private static Stream<Arguments> normalizeBeninPhoneNumber() throws NumberParseException {
|
||||
@@ -103,9 +109,9 @@ class UtilTest {
|
||||
final Phonenumber.PhoneNumber newFormatBeninPhoneNumber = PhoneNumberUtil.getInstance().parse(NEW_FORMAT_BENIN_E164_STRING, null);
|
||||
final Phonenumber.PhoneNumber usPhoneNumber = PhoneNumberUtil.getInstance().getExampleNumber("US");
|
||||
return Stream.of(
|
||||
Arguments.of(newFormatBeninPhoneNumber, newFormatBeninPhoneNumber),
|
||||
Arguments.of(oldFormatBeninPhoneNumber, newFormatBeninPhoneNumber),
|
||||
Arguments.of(usPhoneNumber, usPhoneNumber)
|
||||
Arguments.of(newFormatBeninPhoneNumber, newFormatBeninPhoneNumber, null),
|
||||
Arguments.of(oldFormatBeninPhoneNumber, null, ObsoletePhoneNumberFormatException.class),
|
||||
Arguments.of(usPhoneNumber, usPhoneNumber, null)
|
||||
);
|
||||
}
|
||||
}
|
||||
+5
-22
@@ -13,8 +13,6 @@ import static org.mockito.Mockito.when;
|
||||
import com.google.common.net.HttpHeaders;
|
||||
import com.google.i18n.phonenumbers.PhoneNumberUtil;
|
||||
import io.dropwizard.auth.basic.BasicCredentials;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Stream;
|
||||
import javax.annotation.Nullable;
|
||||
@@ -64,11 +62,9 @@ class WebSocketAccountAuthenticatorTest {
|
||||
@MethodSource
|
||||
void testAuthenticate(
|
||||
@Nullable final String authorizationHeaderValue,
|
||||
final Map<String, List<String>> upgradeRequestParameters,
|
||||
final boolean expectAccount,
|
||||
final boolean expectInvalid) throws Exception {
|
||||
|
||||
when(upgradeRequest.getParameterMap()).thenReturn(upgradeRequestParameters);
|
||||
if (authorizationHeaderValue != null) {
|
||||
when(upgradeRequest.getHeader(eq(HttpHeaders.AUTHORIZATION))).thenReturn(authorizationHeaderValue);
|
||||
}
|
||||
@@ -84,29 +80,16 @@ class WebSocketAccountAuthenticatorTest {
|
||||
}
|
||||
|
||||
private static Stream<Arguments> testAuthenticate() {
|
||||
final Map<String, List<String>> paramsMapWithValidAuth =
|
||||
Map.of("login", List.of(VALID_USER), "password", List.of(VALID_PASSWORD));
|
||||
final Map<String, List<String>> paramsMapWithInvalidAuth =
|
||||
Map.of("login", List.of(INVALID_USER), "password", List.of(INVALID_PASSWORD));
|
||||
final String headerWithValidAuth =
|
||||
HeaderUtils.basicAuthHeader(VALID_USER, VALID_PASSWORD);
|
||||
final String headerWithInvalidAuth =
|
||||
HeaderUtils.basicAuthHeader(INVALID_USER, INVALID_PASSWORD);
|
||||
return Stream.of(
|
||||
// if `Authorization` header is present, outcome should not depend on the value of query parameters
|
||||
Arguments.of(headerWithValidAuth, Map.of(), true, false),
|
||||
Arguments.of(headerWithInvalidAuth, Map.of(), false, true),
|
||||
Arguments.of("invalid header value", Map.of(), false, true),
|
||||
Arguments.of(headerWithValidAuth, paramsMapWithValidAuth, true, false),
|
||||
Arguments.of(headerWithInvalidAuth, paramsMapWithValidAuth, false, true),
|
||||
Arguments.of("invalid header value", paramsMapWithValidAuth, false, true),
|
||||
Arguments.of(headerWithValidAuth, paramsMapWithInvalidAuth, true, false),
|
||||
Arguments.of(headerWithInvalidAuth, paramsMapWithInvalidAuth, false, true),
|
||||
Arguments.of("invalid header value", paramsMapWithInvalidAuth, false, true),
|
||||
// if `Authorization` header is not set, outcome should match the query params based auth
|
||||
Arguments.of(null, paramsMapWithValidAuth, true, false),
|
||||
Arguments.of(null, paramsMapWithInvalidAuth, false, true),
|
||||
Arguments.of(null, Map.of(), false, false)
|
||||
Arguments.of(headerWithValidAuth, true, false),
|
||||
Arguments.of(headerWithInvalidAuth, false, true),
|
||||
Arguments.of("invalid header value", false, true),
|
||||
// if `Authorization` header is not set, we expect no account and anonymous credentials
|
||||
Arguments.of(null, false, false)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -478,6 +478,7 @@ turn:
|
||||
- turn:%s:80?transport=tcp
|
||||
- turns:%s:443?transport=tcp
|
||||
hostname: turn.cloudflare.example.com
|
||||
numHttpClients: 1
|
||||
|
||||
linkDevice:
|
||||
secret: secret://linkDevice.secret
|
||||
|
||||
@@ -1,23 +1,21 @@
|
||||
{
|
||||
"timestamp" : 1234,
|
||||
"messages" : [{
|
||||
"type" : 1,
|
||||
"destinationDeviceId" : 1,
|
||||
"destinationRegistrationId" : 222,
|
||||
"content" : "Zm9vYmFyego",
|
||||
"timestamp" : 1234
|
||||
"content" : "Zm9vYmFyego"
|
||||
},
|
||||
{
|
||||
"type" : 1,
|
||||
"destinationDeviceId" : 2,
|
||||
"destinationRegistrationId" : 333,
|
||||
"content" : "Zm9vYmFyego",
|
||||
"timestamp" : 1234
|
||||
"content" : "Zm9vYmFyego"
|
||||
},
|
||||
{
|
||||
"type" : 1,
|
||||
"destinationDeviceId" : 1,
|
||||
"destinationRegistrationId" : 222,
|
||||
"content" : "Zm9vYmFyego",
|
||||
"timestamp" : 1234
|
||||
"content" : "Zm9vYmFyego"
|
||||
}]
|
||||
}
|
||||
@@ -1,20 +1,18 @@
|
||||
{
|
||||
"timestamp" : 1234,
|
||||
"messages" : [{
|
||||
"type" : 1,
|
||||
"destinationDeviceId" : 1,
|
||||
"content" : "Zm9vYmFyego",
|
||||
"timestamp" : 1234
|
||||
"content" : "Zm9vYmFyego"
|
||||
},
|
||||
{
|
||||
"type" : 1,
|
||||
"destinationDeviceId" : 3,
|
||||
"content" : "Zm9vYmFyego",
|
||||
"timestamp" : 1234
|
||||
"content" : "Zm9vYmFyego"
|
||||
},
|
||||
{
|
||||
"type" : 1,
|
||||
"destinationDeviceId" : 4,
|
||||
"content" : "Zm9vYmFyego",
|
||||
"timestamp" : 1234
|
||||
"content" : "Zm9vYmFyego"
|
||||
}]
|
||||
}
|
||||
@@ -1,23 +1,21 @@
|
||||
{
|
||||
"timestamp" : 1234,
|
||||
"messages" : [{
|
||||
"type" : 1,
|
||||
"destinationDeviceId" : 1,
|
||||
"destinationRegistrationId" : 222,
|
||||
"content" : "Zm9vYmFyego",
|
||||
"timestamp" : 1234
|
||||
"content" : "Zm9vYmFyego"
|
||||
},
|
||||
{
|
||||
"type" : 1,
|
||||
"destinationDeviceId" : 2,
|
||||
"destinationRegistrationId" : 333,
|
||||
"content" : "Zm9vYmFyego",
|
||||
"timestamp" : 1234
|
||||
"content" : "Zm9vYmFyego"
|
||||
},
|
||||
{
|
||||
"type" : 1,
|
||||
"destinationDeviceId" : 3,
|
||||
"destinationRegistrationId" : 444,
|
||||
"content" : "Zm9vYmFyego",
|
||||
"timestamp" : 1234
|
||||
"content" : "Zm9vYmFyego"
|
||||
}]
|
||||
}
|
||||
@@ -1,26 +1,24 @@
|
||||
{
|
||||
"urgent": false,
|
||||
"timestamp": 1234,
|
||||
"messages": [
|
||||
{
|
||||
"type": 1,
|
||||
"destinationDeviceId": 1,
|
||||
"destinationRegistrationId": 222,
|
||||
"content": "Zm9vYmFyego",
|
||||
"timestamp": 1234
|
||||
"content": "Zm9vYmFyego"
|
||||
},
|
||||
{
|
||||
"type": 1,
|
||||
"destinationDeviceId": 2,
|
||||
"destinationRegistrationId": 333,
|
||||
"content": "Zm9vYmFyego",
|
||||
"timestamp": 1234
|
||||
"content": "Zm9vYmFyego"
|
||||
},
|
||||
{
|
||||
"type": 1,
|
||||
"destinationDeviceId": 3,
|
||||
"destinationRegistrationId": 444,
|
||||
"content": "Zm9vYmFyego",
|
||||
"timestamp": 1234
|
||||
"content": "Zm9vYmFyego"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,23 +1,21 @@
|
||||
{
|
||||
"timestamp" : 1234,
|
||||
"messages" : [{
|
||||
"type" : 1,
|
||||
"destinationDeviceId" : 1,
|
||||
"destinationRegistrationId" : 2222,
|
||||
"content" : "Zm9vYmFyego",
|
||||
"timestamp" : 1234
|
||||
"content" : "Zm9vYmFyego"
|
||||
},
|
||||
{
|
||||
"type" : 1,
|
||||
"destinationDeviceId" : 2,
|
||||
"destinationRegistrationId" : 3333,
|
||||
"content" : "Zm9vYmFyego",
|
||||
"timestamp" : 1234
|
||||
"content" : "Zm9vYmFyego"
|
||||
},
|
||||
{
|
||||
"type" : 1,
|
||||
"destinationDeviceId" : 3,
|
||||
"destinationRegistrationId" : 4444,
|
||||
"content" : "Zm9vYmFyego",
|
||||
"timestamp" : 1234
|
||||
"content" : "Zm9vYmFyego"
|
||||
}]
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
{
|
||||
"timestamp" : 1234,
|
||||
"messages" : [ {
|
||||
"type" : 1,
|
||||
"destinationDeviceId" : 1,
|
||||
"content" : "Zm9vYmFyego",
|
||||
"timestamp" : 1234
|
||||
"content" : "Zm9vYmFyego"
|
||||
}, null ]
|
||||
}
|
||||
@@ -1,23 +1,21 @@
|
||||
{
|
||||
"timestamp" : 1234,
|
||||
"messages" : [{
|
||||
"type" : 1,
|
||||
"destinationDeviceId" : 1,
|
||||
"destinationRegistrationId" : 222,
|
||||
"content" : "Zm9vYmFyego",
|
||||
"timestamp" : 1234
|
||||
"content" : "Zm9vYmFyego"
|
||||
},
|
||||
{
|
||||
"type" : 1,
|
||||
"destinationDeviceId" : 2,
|
||||
"destinationRegistrationId" : 999,
|
||||
"content" : "Zm9vYmFyego",
|
||||
"timestamp" : 1234
|
||||
"content" : "Zm9vYmFyego"
|
||||
},
|
||||
{
|
||||
"type" : 1,
|
||||
"destinationDeviceId" : 3,
|
||||
"destinationRegistrationId" : 444,
|
||||
"content" : "Zm9vYmFyego",
|
||||
"timestamp" : 1234
|
||||
"content" : "Zm9vYmFyego"
|
||||
}]
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
{
|
||||
"timestamp" : 1234,
|
||||
"messages" : [{
|
||||
"type" : 1,
|
||||
"destinationDeviceId" : 1,
|
||||
"content" : "Zm9vYmFyego",
|
||||
"timestamp" : 1234
|
||||
"content" : "Zm9vYmFyego"
|
||||
}]
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
{
|
||||
"timestamp" : 1234,
|
||||
"messages" : [{
|
||||
"type" : 7,
|
||||
"destinationDeviceId" : 1,
|
||||
"content" : "Zm9vYmFyego",
|
||||
"timestamp" : 1234
|
||||
"content" : "Zm9vYmFyego"
|
||||
}]
|
||||
}
|
||||
@@ -1,11 +1,11 @@
|
||||
{
|
||||
"urgent": false,
|
||||
"timestamp": 1234,
|
||||
"messages": [
|
||||
{
|
||||
"type": 1,
|
||||
"destinationDeviceId": 1,
|
||||
"content": "Zm9vYmFyego",
|
||||
"timestamp": 1234
|
||||
"content": "Zm9vYmFyego"
|
||||
}
|
||||
]
|
||||
}
|
||||
+2
-2
@@ -1,10 +1,10 @@
|
||||
{
|
||||
"timestamp": 1234,
|
||||
"messages": [
|
||||
{
|
||||
"type": 5,
|
||||
"destinationDeviceId": 1,
|
||||
"content": "Zm9vYmFyego",
|
||||
"timestamp": 1234
|
||||
"content": "Zm9vYmFyego"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
{
|
||||
"timestamp" : 1234,
|
||||
"messages" : [{
|
||||
"type" : 1,
|
||||
"destinationDeviceId" : 2,
|
||||
"content" : "Zm9vYmFyego",
|
||||
"timestamp" : 1234
|
||||
"content" : "Zm9vYmFyego"
|
||||
}]
|
||||
}
|
||||
+1
-1
Submodule spam-filter updated: d5ba4f5bbc...c9a4cb27b2.
Reference in new issue
Block a user